query
stringlengths 7
9.55k
| document
stringlengths 10
363k
| metadata
dict | negatives
listlengths 0
101
| negative_scores
listlengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
|---|---|---|---|---|---|---|
Creates a new account associated with a user
|
def create_account(user)
account = Account.to_adapter.get!(user.id)
update_status = account.update_with_password({ "email" => user.email, "name" => user.username })
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create_account_user(options = {})\n post('accountuser?_method=PUT', options)\n end",
"def create\n user = User.new(user_params)\n if user.save\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n else\n response = { message: Message.account_not_created}\n json_response(response)\n end\n\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.username, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n end",
"def create_user user={}, account={}\n\n req = {}\n req.merge!({ :user => user }) unless user.empty?\n req.merge!({ :account => account }) unless account.empty?\n\n request('create-user', req)\n\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.username, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n end",
"def create\n response = UserAccount::Create.call(user_account_params)\n if response.success?\n success_response(message: response.status_message, http_status: 202, data: response.data)\n else\n error_response(message: response.status_message, data: response.data)\n end\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n json_response(response, :created)\n end",
"def create\n user = User.create!(user_params)\n response = { message: Message.account_created }\n json_response(response, :created)\n end",
"def create\n user = User.new(user_params)\n if user.save\n auth_token = AuthenticateUser.new(user.email, user.password)\n .call\n # send email using welcome template\n UserMailer.welcome_email(user).deliver_now\n response = { message: Message.account_created, token: auth_token }\n json_response(response, :created)\n else\n json_response(user.errors, :unprocessable_entity)\n end\n end",
"def create_account\n unless authenticated?\n payload = encode( { :user => { :github_account => github_user } } )\n response = site['users.json'].post payload, :content_type => :json\n !response.nil?\n end\n end",
"def create\n user = User.create!(user_params) # will raise an error if creation fails\n # call the authentication service\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token}\n json_response(response, :created)\n end",
"def create\n @user = User.new(username: params[:username], email: params[:email], password: params[:password])\n\n if @user.save\n render json: {status: 'SUCCESS', message: 'Account successfully created', accessToken: @user.access_token}.to_json\n else\n render json: {errors: [\"Sign up failed!\"], status: 422}.to_json\n end\n\n end",
"def create(body = {})\n @client.account.create(body)\n end",
"def create\n # Note this is different to the usual situation where anybody can create\n # an account. Here, only administrators can create accounts for others;\n # and doing so does not log them out.\n unless current_user.admin?\n flash[:error] = \"Users can only be created by administrators.\"\n redirect_to (request.env[\"HTTP_REFERER\"] || root_path) and return\n end\n \n @user = User.new(params[:user])\n success = @user && @user.save\n if success && @user.errors.empty?\n # Protects against session fixation attacks, causes request forgery\n # protection if visitor resubmits an earlier form using back\n # button. Uncomment if you understand the tradeoffs.\n # reset session\n redirect_to users_path\n flash[:notice] = \"The account #{ERB::Util.h @user.login} has been setup for #{ERB::Util.h @user.name}.\"\n else\n flash.now[:error] = \"We couldn't set up that account, sorry.\"\n render :action => 'new'\n end\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token , uid: user.id }\n json_response(response, :created)\n end",
"def create\n @account = Account.create(params[:account])\n @user = User.create(params[:user])\n @user.password = params[:user][:password] # Because we don't mass assign password\n @user.password_confirmation = params[:user][:password_confirmation]\n @user.account_admin = true # Account creator is always account administrator\n Account.transaction do\n @account.save! \n @account.users << @user\n @user.save!\n end\n flash[:notice] = I18n.t('accounts.new_account.created')\n redirect_to the_new_account_url\n \n rescue ActiveRecord::RecordInvalid\n flash.now[:error] = I18n.t('accounts.new_account.creation_error')\n render :new\n end",
"def create\n @account_user = AccountUser.new(account_user_params)\n respond_to do |format|\n if @account_user.save\n format.html { redirect_to @account_user, notice: 'Account user was successfully created.' }\n format.json { render :show, status: :created, location: @account_user }\n else\n format.html { render :new }\n format.json { render json: @account_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_account = UserAccount.new(user_account_params)\n\n respond_to do |format|\n if @user_account.save\n format.html { redirect_to @user_account, notice: 'User account was successfully created.' }\n format.json { render :show, status: :created, location: @user_account }\n else\n format.html { render :new }\n format.json { render json: @user_account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_account\n set_user\n set_payer\n set_user_sport\n save_account\n end",
"def create\n @user.account = Account.new if @user.account.nil?\n\n if @user.account.save_with_stripe(params)\n redirect_to user_url(@user), notice: 'Account was successfully created.'\n else\n handle_account_errors(@user, params)\n render :new\n end\n end",
"def create\n @account = Account.new(account_params)\n @account.user = @user\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to @account, notice: 'Account was successfully created.' }\n format.json { render :show, status: :created, location: @account }\n else\n format.html { render :new }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n args = user_params\n user = User.create!(args)\n token_str = AuthenticateUser.new(user.email, user.password).call\n token = Token.new\n token.token = token_str\n token.save!\n user.token_id = token.id\n user.save!\n response = { message: Message.account_created, token: token_str }\n json_response(response, :created)\n end",
"def create_user_account\n User.create!(email: self.email, password: self.customer)\n # user = User.new do |u|\n # u.email = email\n # u.password = customer\n # u.save\n # end\n end",
"def create_user_account\n Account.cache_or_create_by! @current_user\n rescue => e\n log_error(e, account: 'cannot_create_unique_account_record')\n end",
"def create\n @account = current_user.accounts.new(account_params)\n if @account.save\n redirect_to @account, notice: 'Account was successfully created.'\n else\n render :new\n end\n end",
"def create\n @account = Account.new(account_params)\n @account.user_id = current_user.id\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to @account, notice: 'Account was successfully created.' }\n format.json { render :show, status: :created, location: @account }\n else\n format.html { render :new }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @account = Account.new(account_params)\n @account.user_created_id = current_user.id\n respond_to do |format|\n if @account.save\n format.html { redirect_to accounts_path, notice: I18n.t('account.controller.create') }\n format.json { render :show, status: :created, location: @account }\n else\n format.html { render :new }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n @user.reset_perishable_token\n flash[:notice] = t(\"users.create.flash.success\")\n UserMailer.account_created(@user).deliver\n\n begin\n redirect_to :back\n rescue ActionController::RedirectBackError\n redirect_to root_path\n end\n\n else\n flash[:error] = t(\"scaffolds.generic.flash.error\")\n redirect_to new_user_path\n end\n end",
"def new_user_create\n @user = User.create_user(user_params, current_user.account_id) # New User\n begin\n @user.save!\n @users = User.get_all(current_user.account_id)\n flash[:success] = \"User was created successfully!\"\n rescue => e\n flash[:alert] = \"User creation failed!\"\n end \n end",
"def create_account(options)\n form_data = options.merge({ 'action' => 'createaccount' })\n res, dummy = make_api_request(form_data)\n res\n end",
"def create\n user = User.find_by(email: user_params['email'])\n if !user\n dataToRegister = {\n username: user_params['username'],\n balance: user_params['balance'],\n password: Base64.decode64(user_params['password']),\n password_confirmation: Base64.decode64(user_params['password_confirmation']),\n email: user_params['email'],\n }\n user = User.create!(dataToRegister)\n auth_token = AuthenticateUser.new(user.email, Base64.encode64(user.password)).call\n response = {\n data: {\n message: Message.account_created,\n token: auth_token,\n user: {\n username: user.username,\n email: user.email\n }\n }\n }\n json_response(response, :created)\n\n else\n raise(ExceptionHandler::AuthenticationError, Message.email_Already_used)\n end\n end",
"def create\n @user = User.new_user(params[:user])\n @user.attributes.each do |attr, val|\n logger.debug(\"attr: #{attr}, val: #{val}\")\n end\n\n if @user.save\n flash[:success] = \"Successfully created account, please sign in\"\n redirect_to login_path\n else\n flash[:warning] = \"Couldn't process the user\"\n render action: \"new\"\n end\n\n end",
"def create\n user = User.create!(user_params)\n auth_token = AuthenticateUser.new(user.email, user.password).call\n response = { message: Message.account_created, auth_token: auth_token }\n @api_response[:code] = @response_codes[:success]\n @api_response[:result] = response\n\n rescue Exception => e\n @errors, @api_response = api_exception_handler(e)\n ensure\n send_response(@api_response, @errors)\n #json_response(response, :created)\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 signin_path, notice: 'Account 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_account = UserAccount.new(params[:user_account])\n\n respond_to do |format|\n if @user_account.save\n format.html { redirect_to user_account_url(@user_account.user, @user_account), notice: 'User account was successfully created.' }\n format.json { render json: @user_account, status: :created, location: @user_account }\n format.xml { render xml: @user_account, status: :created, location: @user_account }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user_account.errors, status: :unprocessable_entity }\n format.xml { render xml: @user_account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_account\n\n end",
"def create\n user = User.find_by_email(params[:email])\n if !user.present?\n user = User.create!(user_params)\n user.account_active = false\n user.save!\n accountHash = AccountHash.create(:hashcode => create_hashcode, :user_id => user.id, :password => user.password, :temp_email => nil)\n AppropMailer.account_created(user, accountHash).deliver\n render json: { message: Message.account_created, hashcode: accountHash.hashcode }\n else\n json_response({error: 'El email ya se encuentra registrado en Approp'}, :unprocessable_entity)\n end\n end",
"def create\n @account = current_user.accounts.new(params[:account])\n\n respond_to do |format|\n if @account.save\n flash[:notice] = 'Account was successfully created.'\n format.html { redirect_to([current_user, @account]) }\n format.xml { render :xml => @account, :status => :created, :location => @account }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @account.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n\t\t\n\t\treg_params = params.require(:user).permit(\n\t\t\t:name, :email, :password, :password_confirmation\n\t\t)\n\n\t\tname = reg_params[:name]\n\t\temail = reg_params[:email]\n\t\tpassword = reg_params[:password]\n\t\tpassword_confirmation = reg_params[:password_confirmation]\n\n\t\tnew_user = User.new(\n\t\t\tname: name,\n\t\t\temail: email,\n\t\t\tpassword: password,\n\t\t\tpassword_confirmation: password_confirmation\n\t\t)\n\n\t\tif new_user.valid?\n\t\t\tnew_user.save(validate: false)\n\t\t\tflash[:success] = \"Account successfully created.\"\n\t\telse\n\t\t\tflash[:error] = new_user.errors.full_messages\n\t\tend\n\t\tredirect_to root_path\n\tend",
"def create\n @t_user_account = TUserAccount.new(t_user_account_params)\n\n respond_to do |format|\n if @t_user_account.save\n format.html { redirect_to @t_user_account, notice: 'T user account was successfully created.' }\n format.json { render :show, status: :created, location: @t_user_account }\n else\n format.html { render :new }\n format.json { render json: @t_user_account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_account = UserAccount.new(params[:user_account])\n\n respond_to do |format|\n if @user_account.save\n format.html { redirect_to(@user_account, :notice => 'User account was successfully created.') }\n format.xml { render :xml => @user_account, :status => :created, :location => @user_account }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_account.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = Account.new(user_params)\n if @user.save\n session[:user_id] = @user.id\n redirect_to @user\n else\n render 'new'\n end\n end",
"def create_account\n if new_record? && !self.account_id\n account = Account.new\n account.name = \"Preecha o nome da sua empresa\"\n account.save\n self.account_id = account.id\n self.admin = true\n end\n end",
"def create\n # authorize @accounts\n @account = Account.new(account_params)\n @account.user_id=current_user.id\n if @account.save\n redirect_to @account, notice: \"Account was successfully created.\" \n else\n render :new\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 if user_params[:password_confirmation]\n user = User.create!(user_params)\n\n session[:user_id] = user.id\n session[:expiration_time] = Time.now + 6*60*60 # 6 hours until expiration\n \n response = { message: Message.account_created }\n json_response(response, :created)\n else\n response = { message: Message.password_confirmation_missing}\n json_response(response, :not_acceptable)\n end\n end",
"def create\n\t@user = User.create(user_params)\n\tif @user.save\n\t\tflash[:notice] = \"Your account has been created.\"\n\telse\n\t\tflash[:notice] = \"There was an error creating your account.\"\n\tend\n\tredirect_to root_path\nend",
"def create\n @account = Account.new(account_params.merge({ user_id: @current_user.id }))\n\n if @account.save\n render :show, status: :created, location: @account\n else\n render json: @account.errors, status: :unprocessable_entity\n end\n end",
"def create(params)\n put('v1/account', params)\n end",
"def create(user)\n @user = User.new(user)\n # Encrypt password and immediately delete the cleartext version\n @user.encrypt_password\n @user.password = nil\n if @user.save\n redirect \"/\",\n :message => {:notice => \"Account created\"}\n else\n message[:error] = \"Registration failed\"\n render :new\n end\n end",
"def create_new_user_and_identity(auth, params)\n user = User.create!(\n first_name: auth.info[:first_name],\n last_name: auth.info[:last_name],\n email: auth.info[:email],\n oauth_signup: true,\n # referred_by_user_id => params.andand[\"rid\"]\n )\n user.confirm!\n create_new_identity(user, auth)\n end",
"def create_user\n params = {\n client_id: @client_id,\n email: @email\n }\n @user = User.using_client_shard(client: @client).create!(params)\n end",
"def register\n\t\t@user = User.new(user_params)\n\n\t\trespond_to do |format|\n\t\t\tif @user.save\n\n\t\t\t\tformat.html { redirect_to login_path, notice: \"Account created successfully!\" }\n\t\t\telse\n\t\t\t\tformat.html { render action: :create_account }\n\t\t\tend\n\t\tend\n\tend",
"def create\n\t\t\t\t@user = User.create!(create_user_params)\n\t\t\tend",
"def create_user(attributes)\n BrickFTP::API::User.create(attributes)\n end",
"def create_user(attributes)\n BrickFTP::API::User.create(attributes)\n end",
"def create\n user = AuthenticationManager.new(\n params.slice(%i[email first_name last_name password]).merge(is_profile_owner: true, password_confirmation: params[:password], tos_accepted: params.bool(:tos_accepted))\n ).register\n user = session_manager.login(user.email, params[:password], use_api_token: true)\n json_success user: api_response.current_user_data(user)\n end",
"def create\n cookies.delete :auth_token\n @user = User.new(params[:user])\n @user.save!\n self.current_user = @user\n redirect_back_or_default('/')\n flash[:notice] = 'Your account has been created. Please check your email.'\n rescue ActiveRecord::RecordInvalid\n render :action => 'new'\n end",
"def create_user(options = {})\n post \"/users\", options\n end",
"def create_account\n @customer = Customer.find params[:id]\n fail unless @customer.email == params[:customer][:email]\n @customer.update_attributes!(customer_params)\n @customer_session = Authentication::CustomerSession.new(\n email: @customer.email,\n password: customer_params[:password]\n )\n @customer_session.save!\n end",
"def create\n @user = User.new(user_params)\n #@user.profile_picture = \"/assets/images/default_profile.jpg\"\n if @user.save\n UserMailer.registration_confirmation(@user).deliver\n auth_token = AuthenticateUser.new(@user.email, @user.password).call\n response = {status: 'SUCCESS', message: Message.account_created, auth_token: auth_token }\n render json: response, status: :created\n else\n render json: {status: 'FAIL', message: \"Email already taken or passwords don\\'t match\"}, status: :ok\n end\n end",
"def newaccount\n if params[:commit] == \"Cancel\"\n session[:authhash] = nil\n session.delete :authhash\n redirect_to root_url\n else # create account\n @newuser = User.new\n @newuser.name = session[:authhash][:name]\n @newuser.email = session[:authhash][:email]\n @newuser.services.build(:provider => session[:authhash][:provider], :uid => session[:authhash][:uid], :uname => session[:authhash][:name], :uemail => session[:authhash][:email])\n \n if @newuser.save!\n # signin existing user\n # in the session his user id and the service id used for signing in is stored\n session[:user_id] = @newuser.id\n session[:service_id] = @newuser.services.first.id\n \n flash[:notice] = 'Your account has been created and you have been signed in!'\n\tif session[:authhash][:provider] == 'facebook'\n\t\tredirect_to services_facebook_redirect_path\n\telse\n \tredirect_to services_path\n\tend\n else\n flash[:error] = 'This is embarrassing! There was an error while creating your account from which we were not able to recover.'\n redirect_to root_url\n end \n end\n end",
"def create_new_account(email, full_name=nil, password=nil)\n return call('User.create', {'email' => email, 'full_name' => full_name,\\\n 'password' => password})\n end",
"def create\n @account = Account.new(:name=>params[:account_name].downcase, :password=>params[:password], :password_confirmation =>params[:password_confirmation], :account_type=>params[:account_type])\n user = User.new\n user.nick_name = params[:nick_name]\n @account.user = user\n\n respond_to do |format|\n if @account.save\n session[:user_id] = @account.user.id\n format.html { redirect_to(:controller=>'yueyue_objects', :action => \"index\") }\n format.xml { render :xml => @account, :status => :created, :location => @account }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @account.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n megam_rest.post_accounts(to_hash)\n end",
"def create_account(account_name)\r\n\t\taccount = Account.new\r\n\t\taccount.name = account_name\r\n\t\taccount.user = self\r\n\r\n\t\tif account.valid?\r\n\t\t\taccount.save\r\n\t\t\treload\r\n\t\tend\r\n\r\n\t\treturn account\r\n\tend",
"def create\n @account = Account.new(params[:account])\n @account.owner = current_user\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to @account, notice: 'Account was successfully created.' }\n format.json { render json: @account, status: :created, location: @account }\n else\n format.html { render action: \"new\" }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @account = Account.new(name: account_params[:name])\n \n respond_to do |format|\n if @account.save\n user = @account.users.build(account_params[:users_attributes])\n if user.save\n session[:user_id] = user.id\n format.html { redirect_to samples_path, notice: 'account was successfully created.' }\n format.json { render samples_path, status: :created, location: @account }\n else\n format.html { redirect_to register_path, notice: 'Error, in user save' }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n else\n format.html { render :new, notice: 'Error, in account save' }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create( params )\n params.delete( :id ) # Prevent overwriting ID\n Account.new( params ).save\n end",
"def create_user(**args)\n params = parameters(args) do\n required_params :name, :email, :active_flag\n optional_params :name, :email, :active_flag\n end\n request(:post, 'users', params)\n end",
"def create\n @account = Account.new(account_params)\n\n if @account.save\n redirect_to root_path, notice: 'Account was successfully created.'\n else\n redirect_to root_path, alert: 'Some thing went wrong! try more...'\n end\n end",
"def create_user(user_hash={})\n @user = User.new(user_hash)\n @user.save\n end",
"def create_user(user_hash={})\n @user = User.new(user_hash)\n @user.save\n end",
"def create_account(account_create_model, fields = '')\n if account_create_model.blank?\n raise LoginRadius::Error.new, getValidationMessage('account_create_model')\n end\n\n query_parameters = {}\n query_parameters['apiKey'] = @api_key\n query_parameters['apiSecret'] = @api_secret\n unless isNullOrWhiteSpace(fields)\n query_parameters['fields'] = fields\n end\n\n resource_path = 'identity/v2/manage/account'\n post_request(resource_path, query_parameters, account_create_model)\n end",
"def create_account(body, opts = {})\n data, _status_code, _headers = create_account_with_http_info(body, opts)\n data\n end",
"def create\n user = User.new(user_params)\n if user.save\n payload = { user_id: user.id }\n\n hmac_secret = 'my$ecretK3ys'\n\n auth_token = JWT.encode(payload, hmac_secret)\n\n render json: { message: 'Account created successfully', auth_token: auth_token }\n else\n render json: { message: 'Something went wrong', errors: user.errors }, status: :unprocessable_entity\n end\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\t# If user was save with succes, then sign in automaticly, else, render new.\n\t\tif @user.save\n\t\t\tsign_in @user\n\t\t \tflash[:sucess] = \"Seja bem-vindo!\"\n\t\t\tredirect_to :action => :show, :id => @user.id\n\t\t\tCUSTOM_LOGGER.info(\"Created and associated user to params #{@user.to_yaml}\")\n\t\telse\n\t\t\trender 'new'\n\t\t\tCUSTOM_LOGGER.error(\"Not created and associated user to params #{@user.to_yaml}\")\n\t\tend\n\tend",
"def create\n\t\tcookies.delete 'auth_token'\n\t\treset_session\n\t\t\n\t\tself.new\n\t\t# User model doesn’t require email, but web login does\n\t\t@user.email_required = true\n\t\t@user.login_at = Time.current\n\t\t# anti-spam\n\t\tunless (params[:user].nil? or params[:user][:login].blank?) and (params[:user].nil? or params[:user][:url].blank?)\n\t\t\t# looks like a non-human is trying to auto-fill the form\n\t\t\traise Wayground::SpammerDetected\n\t\tend\n\t\t@user.save!\n\t\tself.current_user = @user\n\t\t\n\t\t# send email confirmation\n\t\tif @user.email_addresses[0] and Notifier.deliver_signup_confirmation(@user.email_addresses[0])\n\t\t\tflash[:notice] = \"Thanks for signing up! A confirmation email has been sent to you at #{@user.email}. Please look for a message from #{(WAYGROUND['SENDER'].gsub(/[><]/){|x|{'>'=>'>','<'=>'<'}[x]})}.\"\n\t\telse\n\t\t\tflash[:error] = \"Your new user account has been created, but there was an error when trying to send an email confirmation. Please contact the website administrator about this problem. #{WAYGROUND['EMAIL']}\"\n\t\tend\n\t\t\n\t\tredirect_to '/users/account'\n\trescue Wayground::SpammerDetected\n\t\tblock_spammer\n\t\t# skip the save, but let them think it was saved\n\t\tflash.now[:notice] = \"Thanks for signing up! A confirmation email has been sent to you at #{@user.email}. Please look for a message from #{(WAYGROUND['SENDER'].gsub(/[><]/){|x|{'>'=>'>','<'=>'<'}[x]})}.\"\n\t\t@page_title = 'User Account'\n\t\trender :action=>:account\n\trescue ActiveRecord::RecordInvalid\n\t\trender :action=>'new'\n\tend",
"def create\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n sign_in @user\n format.html { redirect_to @user, notice: 'Account created - welcome to StoryStore!' }\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 @account = Account.new(account_params)\n\n if @account.save\n AccountMailer.welcome(@account).deliver_later\n\n if current_user && @account.owner == current_user\n # User is already signed in and owns the account\n redirect_to @account, notice: 'Welcome to your new account!'\n else\n # User is not signed in or specified another user as the account owner\n redirect_to account_created_path\n end\n else\n @plans = Plan.all\n render :new\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(@user, :notice => 'Account registered!') }\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_new_user\n username = find_username\n @user = User.new(\n email: auth_email,\n username: username,\n password: Devise.friendly_token[0, 20]\n )\n @user.skip_confirmation!\n @user.save!\n\n @user\n end",
"def create\n respond_to do |format|\n if @user.save(account_update_params)\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.create! user_params\n logger.info \"New User with id #{@user.id} has been saved.\"\n #\n # log-in the user immediately after sign-up\n # issue a refresh token with that the\n # user will request an access token.\n set_refresh_token @user\n render :show, status: :created\n end",
"def create_user\n User.create name: \"test\", email: \"test@example.com\", password: \"123456\"\n end",
"def create\n @user = User.new(user_params)\n\n # save was requested by either current_user or else must be a new registration\n if @user.save(current_user)\n redirect_to users_path\n else\n render('new', status: :unprocessable_entity)\n end\n end",
"def create_user(options = {})\n post :create, {:user => { :name => 'quire', :point_value => \"2\", :login => 'quire', :email => 'quire@example.com',\n :password => 'quire', :password_confirmation => 'quire' }.merge(options)}, {:user_id => \"1\"}\n end",
"def create\n @user = User.new(user_params)\n User.create_with_omniauth\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, 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(safe_params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to \"/\", notice: \"Account registered!\" }\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 extuser = User.find_by(username: user_params[:username])\n if(extuser.nil?)\n @user = User.new(user_params)\n @user.high_score = 0\n @user.save!\n auth_token = AuthenticateUser.new(user_params[:username], user_params[:password]).call\n response = { message: Message.account_created, auth_token: auth_token, high_score: 0 }\n json_response(response, :created)\n else\n response = { message: Message.dublicate_user }\n json_response(response, :bad_request)\n end \n end",
"def create_account\n account = Account.new(:email => email, :subdomain => subdomain)\n account.save!\n end",
"def create\n omniauth = request.env['omniauth.auth']\n authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])\n if authentication\n flash[:notice] = \"Signed in successfully\"\n sign_in_and_redirect(:account, authentication.account)\n else\n user = Account.new(password: Devise.friendly_token) # If you create an account with twitter/fb, we don't need a passwod\n user.apply_omniauth(omniauth)\n user.email = get_email_from_omniauth omniauth\n if user.save\n flash[:notice] = \"Successfully registered\"\n sign_in_and_redirect(:account, user)\n else\n session[:omniauth] = omniauth.except('extra')\n session[:omniauth_email] = omniauth['extra'] && omniauth['extra']['user_hash'] && omniauth['extra']['user_hash']['email']\n\n # Check if email already taken. If so, ask user to link_accounts\n if user.errors[:email][0] =~ /has already been taken/ # omniauth? TBD\n # fetch the user with this email id!\n user = Account.find_by_email(user.email)\n return redirect_to link_accounts_url(user.id)\n end\n redirect_to new_account_registration_url\n end\n end\n end",
"def create\n @account = Account.new(account_params)\n\n respond_to do |format|\n if @account.save\n\n # sign in user\n user = @account.users.first\n sign_in(:user, user)\n @account.update_attributes(user_id: user.id)\n\n format.html { redirect_to prism_root_path(@account), notice: 'Welcome to Satiisfy!' }\n format.json { render action: 'show', status: :created, location: @account }\n else\n format.html { render action: 'new' }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @account = Account.new(account_params)\n @account.zip = Account.random_zip\n @account.user_id = @current_user.id if @current_user\n respond_to do |format|\n if @account.save\n format.html { redirect_to @account, notice: 'Account was successfully created.' }\n format.json { render :show, status: :created, location: @account }\n else\n format.html { render :new }\n format.json { render json: @account.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user = User.new(user_params)\n msg = if user.save\n 'User has successfully created.'\n else\n set_error(:unprocessable_entity, user)\n end\n common_response(msg, user: user)\n end",
"def create\n logout_keeping_session!\n\n\t\t# create a new user with the parameters provided\n @user = User.new(params[:user])\n\t\t\n\t\t# if creation of @user is successful and if it was written to the database successfully\n success = @user && @user.save\n\t\t\n\t\t# if success is TRUE and if there were no errors\n if success && @user.errors.empty?\n\t\t\t# redirect back and flash a pop up regarding successful creation \n redirect_back_or_default('/')\n gflash :success => \"Thanks for signing up! We're sending you an email with your activation code.\"\n else\n\t\t\t# else display pop up error and redirect back to the page\n gflash :error => \"We couldn't set up that account, sorry. Please try again, or contact an admin (link is above).\"\n render :action => 'new'\n end\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n UserMailer.account_activation(@user).deliver_now\n flash[:info] = \"Proszę sprawdź swój email, aby aktywować konto\"\n redirect_to root_url\n else\n render 'new'\n end\n end",
"def create\n @user = User.new(user_params)\n @user.tenant_id = current_tenant.id\n if @user.save\n render json: {\n message: 'User was successfully created.',\n user: @user\n }\n else\n render json: {message: 'User Not Created'}\n end\n end",
"def open_user_account\n Account.create(user_id: self.id) \t\n end"
] |
[
"0.8249613",
"0.8177913",
"0.8169718",
"0.8167203",
"0.81080574",
"0.8106919",
"0.80858177",
"0.80858177",
"0.80858177",
"0.8024215",
"0.7987127",
"0.7946853",
"0.7906529",
"0.7906014",
"0.79030114",
"0.7872508",
"0.78147525",
"0.7814468",
"0.7783149",
"0.7780288",
"0.7758448",
"0.77281773",
"0.77163696",
"0.76774514",
"0.7663429",
"0.76415825",
"0.76310045",
"0.7630069",
"0.7624032",
"0.7588766",
"0.7563125",
"0.755141",
"0.75452906",
"0.7541458",
"0.75132304",
"0.75118977",
"0.7503806",
"0.7502385",
"0.7500287",
"0.74650025",
"0.7459186",
"0.7458271",
"0.7452987",
"0.7437095",
"0.74251735",
"0.74033225",
"0.73977166",
"0.7350758",
"0.7337925",
"0.733292",
"0.7331778",
"0.7310003",
"0.73001254",
"0.7285966",
"0.72792536",
"0.7277551",
"0.72774065",
"0.7277108",
"0.72685266",
"0.72540706",
"0.7252135",
"0.7246635",
"0.72403544",
"0.72379255",
"0.72331816",
"0.7231746",
"0.72313774",
"0.72263587",
"0.7220564",
"0.7202273",
"0.71949506",
"0.71940345",
"0.7187396",
"0.7178136",
"0.7178136",
"0.71767503",
"0.7168586",
"0.7166533",
"0.7165168",
"0.7145696",
"0.7141192",
"0.7134615",
"0.7119723",
"0.71111506",
"0.7099562",
"0.70994717",
"0.70978856",
"0.70955753",
"0.7095241",
"0.7092956",
"0.7083056",
"0.7082565",
"0.7079675",
"0.70758176",
"0.7073454",
"0.70726186",
"0.7071793",
"0.7068455",
"0.70682377",
"0.70661896",
"0.70638347"
] |
0.0
|
-1
|
Creates or finds an object by id. If an actor is given, will use the actor to create the object. Otherwise, will just use the new method on the model given
|
def find_or_create(model, actor, id, user, params)
curation_concern = model.where(desc_metadata__identifier_tesim: id).first
if curation_concern.nil?
curation_concern = model.new(identifier: id)
if actor.present?
actor.new(curation_concern, user, params).create
else
curation_concern.attributes = params
curation_concern.apply_depositor_metadata(user.user_key)
curation_concern.save!
end
end
curation_concern
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def find_or_create( id )\n begin\n get( id )\n rescue\n create!( :id => id )\n end \n end",
"def set_actor\n @actor = Actor.find(params[:id])\n end",
"def get_object\n class_name.create_from_database(id)\n end",
"def set_actor\n @actor = Actor.find(params[:id])\n end",
"def set_actor\n @actor = Actor.find(params[:id])\n end",
"def set_actor\n @actor = Actor.find(params[:id])\n end",
"def new\n @object = AbstractModel.find_object(params[:type], params[:id].to_s)\n end",
"def create\n @actor = Actor.where('LOWER(name) = ?', params[:name].downcase).first\n unless @actor\n @actor = Actor.new(name: params[:name])\n if @actor.valid_name? && @actor.in_database?\n @actor.reset_name\n @actor.find_tmdb_id\n if @actor.save\n @actor.add_movies\n current_user.actors.append @actor unless current_user.actors.include? @actor\n redirect_to current_user\n else \n flash[:notice] = 'invalid actor'\n redirect_to '/actors'\n end\n else \n flash[:notice] = 'name invalid or not in database (please check spelling)'\n redirect_to '/actors'\n end\n else\n current_user.actors.append @actor unless current_user.actors.include? @actor\n redirect_to current_user\n end\n end",
"def create\n @actor = Actor.new(actor_params)\n\n respond_to do |format|\n if @actor.save\n session[:actor_id] = @actor.id\n format.html { redirect_to @actor, notice: 'Actor was successfully created.' }\n format.json { render action: 'show', status: :created, location: @actor }\n else\n format.html { render action: 'new' }\n format.json { render json: @actor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @actor = Actor.new(actor_params)\n if @actor.save\n redirect_to @actor\n else\n render :new\n end\n end",
"def create\n @actor = Actor.new(params[:actor])\n\n respond_to do |format|\n if @actor.save\n format.html { redirect_to @actor, notice: 'Actor was successfully created.' }\n format.json { render json: @actor, status: :created, location: @actor }\n else\n format.html { render action: \"new\" }\n format.json { render json: @actor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save\n if self.send('id').nil?\n self.create\n else\n self.update\n end\n end",
"def create(id)\n success = Utils.call_executable_returning_status('--create', '-i', id)\n return nil unless success\n\n reload\n self[id]\n end",
"def find_object\n @object = @model_class.find_by_id(params[:id].to_i)\n end",
"def find_by_id!(id)\n new(one.find_by_id(id) || raise(RecordNotFound, \"A #{name} record for #{id} does not exist.\"))\n end",
"def find(id)\n found_id = redis.get \"#{klass}:id:#{id}\"\n\n if found_id\n object = self.new\n object.send(:id=, found_id.to_i)\n object\n end\n end",
"def find!(ctx, params:, **)\n ctx[:model] = ::Contact.find_by(uuid: params[:id])\n end",
"def create(params = {}, attributes = {})\n raise ArgumentError.new(\"Record already exists for '#{params[:id]}'\") if self.is_exist?(params[:id])\n if self.validates_presence\n self.validates_presence.each do |field|\n raise ArgumentError.new(\"Missing required field '#{field}'\") unless params[field]\n end\n end\n o = self.new\n o.id = params[:id].nil? ? o.next_id : params[:id]\n params[:rho__id] = params[:id]\n populate_model(o,params)\n populate_attributes(o,attributes)\n end",
"def find_or_initialize(id, friendly: false)\n friendly ? friendly_find(id) : model.find(id)\n rescue ::ActiveRecord::RecordNotFound\n model.new\n end",
"def save_or_create_profile\n if profile.present?\n profile.actor_id = id\n profile.save!\n else\n create_profile\n end\n end",
"def create(params_or_record)\n object = self.new(params_or_record).save\n return(object)\n end",
"def set_object\n set_model_instance(MODEL_CLASS.find(params[:id]))\n end",
"def Actor( name )\n return Actor.new name\nend",
"def save\n id.nil? ? create : update\n end",
"def create_or_update_by_api(params = {})\n babel = params_to_translator(params)\n record = find_by_translator(babel).first\n record.present? ? update_by_translator(babel, record) : create_by_translator(babel)\n end",
"def create(params)\n m = type.create(params)\n @id = m.id\n puts \" + #{type}: #{params.inspect} => #{@id}\"\n m\n end",
"def find_user(id)\n contact = find(id)\n\n create_user(contact.attributes)\n end",
"def create objid\n DataObj.new @repo, self, objid, true\n end",
"def new\n @model_id = params[:id]\n prepare_edit_or_new\n end",
"def create(params = {})\n model = new(params)\n model.save\n model\n end",
"def user(id)\n self.users[id] ||= User.supervise id, workflow_name: name\n user = self.users[id].actors.first\n user.load_data\n user\n end",
"def set_child_actor\n @child_actor = ChildActor.find(params[:id])\n end",
"def get id\n doc = database.get id\n new(doc)\n end",
"def add_actor(actor_id)\n if @actors.size < MAX_MEMBERS and not @actors.include?(actor_id)\n @actors.push(actor_id)\n $game_player.refresh\n end\n end",
"def find_or_create_by_name(name)\n obj = self.find_by_name(name)\n if obj == nil\n obj = self.create(name)\n end\n obj\n end",
"def add_actor(actor_id)\n @actors.push(actor_id) unless @actors.include?(actor_id)\n $game_player.refresh\n trigger_symbol = :\"actor_id_#{actor_id}\"\n unless $game_temp.effectus_triggers.include?(trigger_symbol)\n $game_temp.effectus_triggers << trigger_symbol\n end\n $game_map.effectus_need_refresh = true\n end",
"def set_film_actor\n @film_actor = FilmActor.find(params[:id])\n end",
"def save\n if self.id.nil?\n self.create\n else\n self.update\n end\n end",
"def create_or_update\n if self.id.is_a?(Numeric) && self.id.to_i.zero?\n self.id = nil\n @new_record = true\n end\n super\n end",
"def create_or_update(opts = {})\n raise 'Can only call for create or update!' unless ['create', 'update'].include?(action_name)\n klass = opts[:klass] || Kernel.const_get(controller_name.camelize.singularize)\n\n ivar_name = klass.to_s.underscore\n object_params = params[ivar_name]\n obj = klass.new(object_params) if 'create' == action_name\n obj ||= klass.find(params[:id])\n\n instance_variable_set(\"@#{ivar_name}\", obj)\n obj.update_attributes(opts[:options])\n\n valid = obj.save if 'create' == action_name\n valid ||= obj.update_attributes(object_params)\n respond_to do |format|\n if valid\n format.html do\n msg = \"#{klass} #{obj.try(:name)} successfully #{action_name}d\"\n if block_given?\n yield obj\n else\n redirect_to(obj, :notice => msg)\n end\n end\n format.json { render :json => obj.to_json }\n else\n format.html { render :action => { 'create' => 'new', 'update' => 'edit'}[action_name] }\n format.json { render :json => {:errors => obj.errors}.to_json, :status => :unprocessable_entity }\n end\n end\n end",
"def find(model, id)\n key = model.primary_key\n condition = {\"#{key}\" => id}\n data = store.read(condition, table: table_name).first\n fail RecordNotFound.new(condition, table_name) unless data\n\n model.new data\n end",
"def save\n if self.id.nil?\n create\n else\n update\n end\n end",
"def object_for(object_or_id, klass)\n case object_or_id\n when klass then object_or_id\n when Integer\n klass.find_by(id: object_or_id)\n else\n raise ArgumentError,\n \"must provide a #{ klass } or a valid #{ klass } id\"\n end\n end",
"def create\n\t\t\t@investor = params[:id].present? ? Investor.find(params[:id]) : Investor.new\n\t\tend",
"def create(params)\n update_model(params)\n end",
"def find_activity_object(id:)\n @find_activity_object ||= ActivityObject.find_by(id:)\n end",
"def find_by_id(id)\n results = one.find_by_id_ne(id)\n results && new(results) || nil\n end",
"def create!(params = {})\n association.build(model, params).tap(&:save!)\n end",
"def add_actor(actor_id)\n if not @actors.include?(actor_id)\n if @actors.size < MAX_MEMBERS\n @actors.push(actor_id)\n \n # Finds the free position for the new actor\n new_index = 0\n while @actor_positions.include?(new_index)\n new_index += 1 \n end\n @actor_positions.push(new_index)\n \n sort_arrays()\n \n $game_player.refresh\n else\n $game_faction.add_reserve_actor(actor_id)\n end\n end\n end",
"def replace identifier, object\n create(identifier, object)\n end",
"def add_actor(actor_id)\r\n # アクターを取得\r\n actor = $game_actors[actor_id]\r\n # パーティ人数が 4 人未満で、このアクターがパーティにいない場合\r\n if @actors.size < 4 and not @actors.include?(actor)\r\n # アクターを追加\r\n @actors.push(actor)\r\n # プレイヤーをリフレッシュ\r\n $game_player.refresh\r\n end\r\n end",
"def find id\n model.find id\n end",
"def add_actor(actor_id)\n # Original method\n large_party_add_actor(actor_id)\n # Get actor\n actor = $game_actors[actor_id]\n # If the party has less than 4 members and this actor is not in the party\n if @actors.size < @max_size and not @actors.include?(actor)\n # Add actor\n @actors.push(actor)\n # Refresh player\n $game_player.refresh\n end\n end",
"def object_by_id(id)\n @lock.synchronize do\n object_by_id_internal(id)\n end\n end",
"def create\n if params == [:tweet_id,:id]\n @tweet = Tweet.find(params[:tweet_id])\n @actor_tweet = ActorTweet.new(actor_tweet_params)\n respond_to do |format|\n if @actor_tweet.save\n format.html { redirect_to @actor_tweets, notice: 'Actor tweet creado correctamente.' }\n format.json { render :show, status: :created, location: @actor_tweet }\n else\n format.html { render :new }\n format.json { render json: @actor_tweet.errors, status: :unprocessable_entity }\n end\n end\n end\n if params == [:actor_id,:id]\n @actors = Actor.find(params[:actor_id])\n @actor_tweet = ActorTweet.new(actor_tweet_params)\n respond_to do |format|\n if @actor_tweet.save\n format.html { redirect_to @actor_tweets, notice: 'Actor tweet creado correctamente.' }\n format.json { render :show, status: :created, location: @actor_tweet }\n else\n format.html { render :new }\n format.json { render json: @actor_tweet.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def find_single(id, *args)\n data = get(id.to_s, *args)\n return nil unless data && !data.empty?\n instantiate(id, data)\n end",
"def get(id)\n return nil if id.nil?\n\n return objects[id] if objects.has_key?(id)\n\n type, content = get_object(id)\n\n klass = TYPE_CLASS[type] or raise NotImplementedError, \"type not supported: #{type}\"\n\n objects[id] = klass.new(self, id, content)\n end",
"def create\n @film_actor = FilmActor.new(film_actor_params)\n\n respond_to do |format|\n if @film_actor.save\n format.html { redirect_to @film_actor, notice: 'Film actor was successfully created.' }\n format.json { render :show, status: :created, location: @film_actor }\n else\n format.html { render :new }\n format.json { render json: @film_actor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n parent = Object.const_get(session[:team_type]).find(params[:id])\n begin\n Team.check_for_existing(parent, params[:team][:name], session[:team_type])\n @team = Object.const_get(session[:team_type] + 'Team').create(name: params[:team][:name], parent_id: parent.id)\n TeamNode.create(parent_id: parent.id, node_object_id: @team.id)\n undo_link(\"The team \\\"#{@team.name}\\\" has been successfully created.\")\n redirect_to action: 'list', id: parent.id\n rescue TeamExistsError\n flash[:error] = $ERROR_INFO\n redirect_to action: 'new', id: parent.id\n end\n end",
"def save\n self.id.nil? ? create : update\n end",
"def find_one(id)\n response = request(:get, \"/#{resource_name}/#{id}\")\n #puts response\n construct_record_from_singular(response)\n end",
"def new_solo\n @user = User.find(params[:id])\n @match = Match.new\n end",
"def create\n\n # process the dob\n params[:actor][:dob] = DateSelectHelper.to_datetime(params[:selected_date])\n\n @actor = Actor.new(params[:actor])\n\n # check for new dvds\n @dvd_ids = params[:dvds] ? params[:dvds][\"ids\"] : nil\n if @dvd_ids\n @dvd_ids.shift\n @actor.dvds << Dvd.find(@dvd_ids)\n end\n\n respond_to do |format|\n if @actor.save\n format.html { redirect_to @actor, notice: 'Actor was successfully created.' }\n format.json { render json: @actor, status: :created, location: @actor }\n else\n format.html { render action: \"new\" }\n format.json { render json: @actor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(params = {})\n association.build(model, params).tap(&:save)\n end",
"def create(params = {})\n record = new(params)\n record.save && record\n end",
"def update\n @person = Roxiware::Person.find(params[:id])\n _create_or_update(@person)\n end",
"def set_object\n @object = Object.find(params[:id])\nend",
"def create identifier, object\n @storage[identifier] = object\n end",
"def create_object!(clazz, id, attributes, options={})\n validate = options[:validate].nil? ? true : options[:validate]\n\n x = clazz.new\n x.attributes = attributes.reject { |k,v| !x.respond_to?(\"#{k}=\") }\n x.id = id\n x.save!(:validate => validate)\n x\n end",
"def id\r\n return @actor_id\r\n end",
"def create_saved_object(params, type, id = \"\", space_id = \"\")\n endpoint = if space_id.present?\n \"s/#{space_id}/api/saved_objects/#{type}/#{id}\"\n else\n \"api/saved_objects/#{type}/#{id}\"\n end\n\n request(\n http_method: :post,\n endpoint: endpoint,\n params: params.to_json\n )\n end",
"def new_record(params = {})\n @model_class.new(params)\n end",
"def new_record(params = {})\n @model_class.new(params)\n end",
"def create(model={})\n create_new_model(model, :create)\n end",
"def create\n model = model_class.new\n action = action_class.new(model, current_user)\n\n respond_with(action.create(resource_attributes))\n end",
"def find_or_create_by_name(name_to_find)\n found = self.find_by_name(name_to_find)\n if found == nil\n found = self.new(name_to_find)\n found.save\n end\n found\n end",
"def add(id, object)\n self.objects[id] = object\n end",
"def create_cast\n begin\n @cast = Actor.new( :job => Actor.default_job )\n @cast.movie = @movie\n @cast.comment = params[:cast][:comment]\n if select_or_create_person( :cast )\n @cast.save\n update_movie_cast_list @cast.job.department, :cast\n else\n render :inline => \"Error\".t, :status => 409\n end\n rescue ActiveRecord::RecordNotFound\n render :inline => \"Already destroyed\".t, :status => 404\n end\n end",
"def create\n @child_actor = ChildActor.new(child_actor_params)\n\n respond_to do |format|\n if @child_actor.save\n format.html { redirect_to @child_actor, notice: \"Child actor was successfully created.\" }\n format.json { render :show, status: :created, location: @child_actor }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @child_actor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @actor=Actor.find(params[:id])\n end",
"def model(ctx, params:, **)\n return unless params[:id]\n ctx[:model] = Song.new(params[:id])\n end",
"def create\n _create_or_update(@person)\n end",
"def create_or_update(ident,attributes={})\n raise \"updating id is not supported\" if attributes[:id] \n unless id = redis.get(\"#{name}:ident:#{ident}\") \n id = redis.incr \"#{name}:id\" #Replica:id\n redis.sadd \"#{name}:all\", id # Replica\n redis.hset colon(name,id), :ident, ident\n redis.set colon(name, :ident, ident ) ,id\n end\n new id, attributes\n end",
"def save\n create_or_update\n _id.present?\n end",
"def new\n @movie = Movie.new\n @actors = Actor.all\n end",
"def find_or_create_event_by_id(id, &blk) \n event = id ? find_event_by_id(id)[0] : nil\n\n if event\n setup_event(event, &blk)\n elsif id\n event = Event.new(id: id, new_event_with_id_specified: true)\n setup_event(event, &blk)\n else\n event = Event.new\n setup_event(event, &blk)\n end\n end",
"def create_or_update type, params\n setup_connection\n\n id = params.delete(:id)\n url = [type, id].compact.join('/')\n\n payload = params\n payload[:format] = 'json'\n\n @last_response = if id.present?\n @conn.put(url, params)\n else\n @conn.post(url, params)\n end\n\n JSON.parse @last_response.body\n end",
"def set_actor_tweet\n if params == [:tweet_id,:id]\n @tweet = Tweet.find(params[:tweet_id])\n end\n if params == [:actor_id,:id]\n @actors = Actor.find(params[:actor_id])\n end\n @actor_tweet = ActorTweet.find(params[:id])\n end",
"def find_or_create(owner_class, *args, &block); end",
"def setup_object(data, ar_relation)\n type = data[:type]\n klass = ar_relation || type.classify.constantize\n\n return klass.new if data[:id].blank?\n\n # such hack\n # assume it's a UUID and *klass* responds to find_or_initialize_by_uuid\n if data[:id].index('-') != nil\n if klass.respond_to? :find_or_initialize_by_uuid\n # handle Rails 3 ActiveRecord classes\n klass.find_or_initialize_by_uuid(data[:id])\n else\n # handle Rails 4 ActiveRecord classes\n klass.find_or_initialize_by(uuid: data[:id])\n end\n else\n klass.find_by_id(data[:id])\n end\n end",
"def employee(id)\n Employee.new(id: id)\n end",
"def find_record(id)\n @model_class.find(id)\n end",
"def find_record(id)\n @model_class.find(id)\n end",
"def create\n @imovel = Imovel.new(imovel_params)\n @imovel.created_by = current_user.id\n respond_to do |format|\n if @imovel.save\n format.html { redirect_to imovel_path(@imovel), notice: 'Imóvel criado com sucesso.' }\n format.json { render :show, status: :created, location: @imovel }\n else\n format.html { render :new }\n format.json { render json: @imovel.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_or_update!(hash={}, options = {:hard_update => true})\n hash.symbolize_keys!\n if hash[:id].blank?\n self.new(hash)\n else\n rec = self.find(hash[:id])\n if options[:hard_update]\n rec.update_attributes!(hash.except(:id))\n else\n rec.update_attributes(hash.except(:id))\n end\n rec\n end\n end",
"def retrieve(id)\n agent = Client.get(\"#{path}/#{id}\").with_indifferent_access\n new(\n agent[:id],\n agent[:name]\n )\n end",
"def find_or_create_by_api(params = {})\n babel = params_to_translator(params)\n find_by_translator(babel).first || create_by_translator(babel)\n end",
"def find_by_id(id)\n results = one.find_by_id_ne(id)\n results && !results['id'].blank? && new(results) || nil\n end",
"def new(&block)\n assign_attributes if params[model_identifier]\n respond_with(entry, &block)\n end",
"def _create(other_id, attrs, force)\n raise 'Cannot call create! on a non-join model' unless @find_method\n join = force ? nil : find(other_id)\n return join if (join && attrs.empty?)\n\n # create! short circuits if a join record already exists, and no\n # attrs are provided. otherwise a new or existing join model is\n # updated with attrs before being saved\n join ||= @target.new\n join.assign_attributes(attrs.merge!({\n \"#{@class_name}_id\" => @id,\n \"#{@other_name}_id\" => other_id\n }))\n join\n end"
] |
[
"0.6491675",
"0.6340175",
"0.62531507",
"0.6214431",
"0.6214431",
"0.6214431",
"0.6080644",
"0.6033748",
"0.5943735",
"0.5898148",
"0.58860064",
"0.58745116",
"0.58000165",
"0.57822293",
"0.57809085",
"0.5729493",
"0.57106215",
"0.56893176",
"0.5664932",
"0.5632625",
"0.56208694",
"0.55808574",
"0.5550311",
"0.554725",
"0.5523122",
"0.5507069",
"0.5501024",
"0.5490466",
"0.54705656",
"0.54615664",
"0.54609394",
"0.5433778",
"0.5428937",
"0.54267174",
"0.54222333",
"0.54068947",
"0.54067045",
"0.53998905",
"0.53963864",
"0.53961796",
"0.5391536",
"0.5388946",
"0.53593343",
"0.53425425",
"0.5332137",
"0.53319937",
"0.5314246",
"0.5314106",
"0.5313282",
"0.53118867",
"0.53116083",
"0.52937675",
"0.52901083",
"0.5289068",
"0.5285248",
"0.52823496",
"0.5273852",
"0.5259466",
"0.525879",
"0.5253348",
"0.5250456",
"0.5244636",
"0.5239874",
"0.52372324",
"0.5204793",
"0.5202981",
"0.5200622",
"0.5198301",
"0.5196911",
"0.51938903",
"0.51807934",
"0.5180625",
"0.5180625",
"0.5178879",
"0.51626515",
"0.5153165",
"0.5152385",
"0.5150946",
"0.51460826",
"0.51448023",
"0.5144198",
"0.5140661",
"0.51389235",
"0.51388997",
"0.51331925",
"0.5131583",
"0.51315564",
"0.5126453",
"0.5114621",
"0.51098216",
"0.5103231",
"0.51028454",
"0.51028454",
"0.5098101",
"0.5089309",
"0.5082436",
"0.5080581",
"0.5076356",
"0.50725067",
"0.507189"
] |
0.64547354
|
1
|
Creates or finds a library collection by description. If an actor is given, will use the actor to create the object. Otherwise, will just use the new method on the model given
|
def find_or_create_library_collection(description, user, params)
collection = LibraryCollection.where(desc_metadata__description_tesim: description).first
if collection.nil?
collection = LibraryCollection.new
collection.attributes = params
collection.apply_depositor_metadata(user.user_key)
collection.save!
end
collection
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def new_collection\n Models::Collection.new\n end",
"def find_or_create_collection(collection)\n\t # collection is response from sohpify api\n\t\tc = collections.find_by_shopify_collection_id(collection.id)\n \tRails.logger.debug(\"Found existing collection (#{collection.class.name}): #{c.title}\") if c\n\t\treturn c if c\n\n\t\tRails.logger.debug(\"No collection yet for this shopify collection: #{collection.inspect}\")\n\n\t\tcollections.create(\n\t\t\ttitle: collection.title,\n\t\t\tshopify_collection_id: collection.id #[:id], # Dont know what the actual id is called\n\t\t)\n\tend",
"def find_or_create_resource_for_collection(name)\r\n find_or_create_resource_for(name.to_s.singularize)\r\n end",
"def build(attrs, collection)\n collection.new(attrs)\n end",
"def find_or_create_resource_for_collection(name)\n find_or_create_resource_for(name.to_s.singularize)\n end",
"def create(title: \"\", description: \"\", private: false)\n params = {\n title: title,\n description: description,\n private: private\n }\n Unsplash::Collection.new JSON.parse(connection.post(\"/collections\", params).body)\n end",
"def find_or_new_collection(primary_id, title)\n collection_found = Collection.where(identifier_ssi: primary_id).last\n return collection_found if collection_found\n Collection.new(\n identifier: primary_id,\n title: title,\n depositor: job_owner,\n collection_type_gid: Tenejo::CsvImporter.default_collection_type.gid\n )\n end",
"def collection(objectName)\n Hirsute::Collection.new(objectName)\nend",
"def collection(model = name.to_s.classify.constantize)\n model\n end",
"def new_with_collection_path(collection, relative_path, site: Bridgetown::Current.site)\n collection = collection.label if collection.is_a?(Bridgetown::Collection)\n\n new(\"repo://#{collection}.collection/#{relative_path}\", site: site)\n end",
"def make_collection\n raise NotImplementedError\n end",
"def new\n @collection = Collection.new\n end",
"def find_or_create(model, actor, id, user, params)\n curation_concern = model.where(desc_metadata__identifier_tesim: id).first\n if curation_concern.nil?\n curation_concern = model.new(identifier: id)\n if actor.present?\n actor.new(curation_concern, user, params).create\n else\n curation_concern.attributes = params\n curation_concern.apply_depositor_metadata(user.user_key)\n curation_concern.save!\n end\n end\n curation_concern\nend",
"def initialize(collection={}, model = Occi::Model.new)\n collection = Hashie::Mash.new(collection) unless collection.kind_of? Occi::Collection\n\n @kinds = Occi::Core::Kinds.new\n @mixins = Occi::Core::Mixins.new\n @actions = Occi::Core::Actions.new\n @resources = Occi::Core::Resources.new\n @links = Occi::Core::Links.new\n\n @kinds.merge collection.kinds.to_a.collect { |kind| Occi::Core::Kind.new(kind.scheme, kind.term, kind.title, kind.attributes, kind.related, kind.actions, kind.location) }\n @mixins.merge collection.mixins.to_a.collect { |mixin| Occi::Core::Mixin.new(mixin.scheme, mixin.term, mixin.title, mixin.attributes, mixin.depends, mixin.actions, mixin.location, mixin.applies) }\n @actions.merge collection.actions.to_a.collect { |action| Occi::Core::Action.new(action.scheme, action.term, action.title, action.attributes) }\n @resources.merge collection.resources.to_a.collect { |resource| Occi::Core::Resource.new(resource.kind, resource.mixins, resource.attributes, resource.actions, resource.links, resource.location) }\n @links.merge collection.links.to_a.collect { |link| Occi::Core::Link.new(link.kind, link.mixins, link.attributes, link.actions, link.rel, link.target, link.source, link.location) }\n @action = Occi::Core::ActionInstance.new(collection.action.action, collection.action.attributes) if collection.action\n\n self.model = model if model\n end",
"def make_collection\n @resource.make_collection\n end",
"def create\n # Manual load and authorize necessary because Cancan will pass in all\n # form attributes. When `permissions_attributes` are present the\n # collection is saved without a value for `has_model.`\n @collection = ::Collection.new\n authorize! :create, @collection\n # Coming from the UI, a collection type gid should always be present. Coming from the API, if a collection type gid is not specified,\n # use the default collection type (provides backward compatibility with versions < Hyrax 2.1.0)\n @collection.collection_type_gid = params[:collection_type_gid].presence || default_collection_type.gid\n @collection.id = Californica::IdGenerator.id_from_ark(collection_params[\"ark\"])\n @collection.attributes = collection_params.except(:members, :parent_id, :collection_type_gid)\n @collection.apply_depositor_metadata(current_user.user_key)\n add_members_to_collection unless batch.empty?\n @collection.visibility = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE unless @collection.discoverable?\n if @collection.save\n after_create\n else\n after_create_error\n end\n end",
"def create\n attrs = create_attributes\n @object = klass.new\n object.reindex_extent = Hyrax::Adapters::NestingIndexAdapter::LIMITED_REINDEX\n run_callbacks :save do\n run_callbacks :create do\n klass == Collection ? create_collection(attrs) : work_actor.create(environment(attrs))\n end\n end\n log_created(object)\n end",
"def create_collection(name, template: nil, bare: nil)\n unless exists_collection? name\n create_wiki(name, @meta_wiki_name, {\n :bare => bare,\n :assert_valid_collection => false,\n :template => template\n })\n else\n true\n end\n end",
"def create\n @collection = Collection.new(collection_params)\n ensure_default_editors\n ensure_default_viewers\n authorize! :create, @collection\n flash[:notice] = 'Collection was successfully created.' if @collection.save\n respond_with(@collection)\n end",
"def model\n options.key?(:collection) ? call(:collection).klass : collection\n end",
"def new_collection(query, resources = nil, &block)\n Collection.new(query, resources, &block)\n end",
"def create\n @collection = Collection.new(collection_params)\n\n respond_to do |format|\n action_message_for('new')\n if create_collection\n format.html { redirect_to redirect_target(@collection), flash: @feedback_flash }\n format.json { render :show, status: :created, location: @collection }\n else\n format.html { render :new }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n collection = Collection.create(collection_params)\n\n render json: collection\n end",
"def collection\n Rails.logger.info \"XXXXX COLLECTION NAME #{collection_hash['collection name']}\"\n\n @collection ||= CollectionCreator.find_or_create_collection(\n collection_hash['collection name'],\n collection_hash['unit name'],\n collection_hash['collection description'],\n submitter_user_key\n )\n end",
"def new_collection(query, resources = nil, &block)\n self.class.new(query, resources, &block)\n end",
"def create\n @content_provider = current_user.content_provider;\n params[:collection][:archive] = Archive.find_by_title(params[:collection][:archive])\n params[:collection][:plugin] = @content_provider.placeholder_plugin;\n params[:collection].delete(:plugin_name_other)\n \n @collection = Collection.new(params[:collection])\n \n respond_to do |format|\n if @collection.save\n flash[:notice] = 'Collection was successfully created.'\n format.html { redirect_to :id => @collection.id, :action => :show }\n format.xml { render :xml => @collection, :status => :created, :location => @collection }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @collection.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new_collection\n primitive.new\n end",
"def find_or_create_by_api(params = {})\n babel = params_to_translator(params)\n find_by_translator(babel).first || create_by_translator(babel)\n end",
"def create\n book = Book.find(params[:book_id])\n @collection = current_user.collections.build(book: book)\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to collections_path, notice: 'Book added to your collection.' }\n format.json { render json: @collection, status: :created, location: @collection }\n else\n format.html { render action: \"new\" }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def collection_for(source, other_query=nil)\n Collection.new(source, target_model)\n end",
"def create(collection, entity)\n entity.id = command(collection).create(entity)\n entity\n end",
"def set_library\n @library = Library.find(params[:id])\n if @library.universities_id\n @university = University.find(@library.universities_id)\n else\n @university = University.new\n end\n end",
"def collection(name)\n Kernel.const_get(\"#{name}Collection\").new(@browser)\n end",
"def new_resource\n base_collection.new\n end",
"def set_collection\n @collection = Collection.friendly.find params[:id]\n end",
"def create\n @collection = Collection.new(params[:collection])\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to @collection, notice: 'Collection was successfully created.' }\n format.json { render json: @collection, status: :created, location: @collection }\n else\n format.html { render action: \"new\" }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @collection = Collection.new(params[:collection])\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to @collection, notice: 'Collection was successfully created.' }\n format.json { render json: @collection, status: :created, location: @collection }\n else\n format.html { render action: \"new\" }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n collection = @current_user.collections.create\n collection.set_attributes(params)\n \n if not collection.valid?\n collection_errors(collection)\n redirect_to :back and return\n else\n collection.save\n end\n redirect_to collection_path(:id => collection.id)\n end",
"def new\n # @collection = Collection.find(params[:collection_id])\n @book = @collection.books.build\n #original: @book = Book.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book }\n end\n end",
"def find_or_create(owner_class, *args, &block); end",
"def set_collection\n @collection = Collection.friendly.find(params[:id])\n end",
"def create(collection, entity)\n @mutex.synchronize do\n entity.id = command(collection).create(entity)\n entity\n end\n end",
"def create\n @collection = Collection.new(params[:collection])\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to @collection, :notice => 'Collection was successfully created.' }\n format.json { render :json => @collection, :status => :created, :location => @collection }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @collection.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n collection = @current_user.collections.create\n collection.set_attributes(params)\n\n if not collection.valid?\n collection_errors(collection)\n redirect_to :back and return\n else\n collection.save\n end\n redirect_to collection_path(:id => collection.id)\n end",
"def create_collection(name)\n @change_collections_mutex.synchronize do\n collection = native.collection(name)\n collection.create\n collections[name] = Robe::DB::Mongo::Collection.new(self, collection)\n end\n end",
"def [](collection_name)\n Collection.new(self, collection_name)\n end",
"def libraries\n @libs ||= Collection.new(klass: Library, client: @client,\n belongs_to: self)\n end",
"def create\n begin\n if params[:paper_id]\n # Create a tag for the paper\n paper = Paper.find(params[:paper_id])\n # Authenticate\n club_id = paper.club_id\n else\n club_id = params[:club_id]\n end\n # Authenticate\n club = can_access_club?(club_id)\n # Tag name is lowercase\n name = params[:name].downcase\n # Find or create the tag for the club\n new_tag = Tag.find_or_create_by_club_id_and_name( club_id, \n params[:name] )\n if params[:paper_id]\n new_collection = Collection.find_or_create_by_paper_id_and_tag_id(\n paper.id, new_tag.id)\n end\n render :json => new_tag \n rescue ActiveRecord::RecordNotFound\n error \"Can't access the club or the paper\"\n end\n end",
"def new_many\n @brief = Brief.find(params[:brief_id]) \n @kind_default = params[:kind]\n @item_count = 5\n end",
"def new_model(name, template = nil)\n template_ole = template ? template.ole_obj : app.ole_obj.ActiveDesignFile.DefaultModelReference\n el = app.ole_obj.ActiveDesignFile.Models.Add(template_ole, name, \"Added \")\n model_from_ole(el).activate\n end",
"def create\n run_callbacks :create do\n connection.post(collection_path, encode, self.class.headers).tap do |response|\n self.id = id_from_response(response)\n load_attributes_from_response(response)\n end\n end\n end",
"def add_model_to_mongo(model, manufacture_id, manufacture_name, device_type, description, note)\n model = {\n model: model,\n ManufacturerID: manufacture_id,\n ManufacturerNAME: manufacture_name,\n device_type: device_type,\n description: description,\n note: note,\n created: DateTime.now\n }\n mongo_client.imei_insert_model(model)\n end",
"def find_or_create_resource_for(name)\r\n resource_name = name.to_s.camelize\r\n resource_name.constantize\r\n rescue NameError\r\n resource = self.class.const_set(resource_name, Class.new(ActiveTamino::Base))\r\n resource.collection = self.class.collection\r\n resource.credentials = self.class.credentials\r\n resource.doctype = self.class.doctype\r\n resource\r\n end",
"def create(type:, **options)\n find(type).new(**options)\n end",
"def add(beer)\n \t$catalogue << beer\n end",
"def item_create\n @brief = Brief.find(params[:brief_id])\n @brief_vendor = @brief.brief_vendors.find_by_org_id(@cur_user.org_id)\n invalid_op unless @brief_vendor\n @brief_vendor.items << Item.new(params[:item]){|r|r.kind = params[:kind]}\n redirect_to vendor_show_brief_path(@brief)\n end",
"def collection(name=nil)\n if name\n @collection = db.collection(name: name)\n else\n @collection || raise('Please give a collection name for this model')\n end\n end",
"def find_or_create_resource(resource_descr, resource_type, authorizer)\n debug \"central find_or_create_resource: resource '#{resource_descr.inspect}' type: '#{resource_type}'\"\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 create\n json_response(Description.create!(description_params), :created)\n end",
"def make_item(sample:, object_type:, lot_number: nil, association_map: nil)\n raise ItemActionError, 'Sample ID is nil' if sample.nil?\n\n object_type = ObjectType.find_by_name(object_type) if object_type.is_a? String\n item = nil\n if object_type.handler == 'collection' # TODO find out why some ObjectTypes dont have .collection_type?\n item = Collection.new_collection(object_type)\n length = association_map.present? ? association_map.length : item.get_empty.length\n samples = Array.new(length, sample)\n zipped_map = if association_map.present?\n samples.zip(association_map)\n else\n samples\n end\n zipped_map.each do |samp, map|\n next if samp.nil?\n\n if map.nil?\n item.add_one(samp)\n next\n end\n item.set(map[:to_loc][0], map[:to_loc][1], samp)\n end\n else\n item = sample.make_item(object_type.name.to_s)\n end\n item.associate(LOT_NUM, lot_number) if lot_number.present?\n item\n end",
"def create\n @collection = Collection.new(collection_params)\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to root_path, notice: 'Collection was successfully created.' }\n format.json { render :show, status: :created, location: @collection }\n else\n format.html { render :new }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def instantiate_collection(collection)\n collection.collect! { |record| instantiate_record(record) }\n end",
"def find\n unless @release\n klass = list.detect { |impl| impl.applies_to? }\n @release = klass.new if klass\n end\n @release\n end",
"def find\n unless @release\n klass = list.detect { |impl| impl.applies_to? }\n @release = klass.new if klass\n end\n @release\n end",
"def _find_or_update_or_build_collection!\n return _flexi_collection if _flexi_collection.present?\n\n # Find existing collection\n self._flexi_collection = COLLECTION.where(\n namespace: self.class.get_flexi_namespace,\n name: self.class.flexi_collection_name,\n partition_id: self.class.flexi_partition_id\n ).first\n\n # Update if schema changed\n if self._flexi_collection\n _update_schema\n else\n _build_collection\n end\n\n self._flexi_collection\n end",
"def make_object klass\n obj = $manager.make_object klass\n inventory << obj if self.respond_to? :inventory\n obj\n end",
"def perform_request_with_object_from_collection(request_method, path, options, klass, collection_name) # rubocop:disable Metrics/ParameterLists\n options = {collection_name.to_sym => options} unless options.empty?\n\n response = perform_request(request_method, path, options).fetch(collection_name.to_sym)\n klass.new(response)\n end",
"def create\n @collection = @institution.collections.new(params[:collection])\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to [@collection.institution, @collection], notice: 'Collection was successfully created.' }\n format.json { render json: @collection, status: :created, location: @collection }\n else\n format.html { render layout: 'form', action: \"new\" }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def library(id, params = {})\n Library.find(id, params)\n end",
"def create\n @collection = Collection.new(collection_params)\n authorize! :create, @collection\n respond_to do |format|\n if @collection.save\n format.html { redirect_to admin_collections_url, notice: \"Collection '#{@collection.title}' was successfully created.\" }\n format.json { render :show, status: :created, location: @collection }\n else\n format.html { render :new }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def find_or_create_from_activedirectory local_params = {}\n ad_objs = find_activedirectory_objs local_params\n local_objs = []\n\n #Grab all of the objects in one query by GUID for efficiency\n guids = ad_objs.collect { |obj| obj[:objectguid] }\n db_objs_by_guid = {}\n\n #Make a hash map to do quick lookups\n where(:objectguid => guids).each do |db_obj|\n db_objs_by_guid[db_obj.objectguid] = db_obj\n end\n\n ad_objs.each do |ad_obj|\n guid = ad_obj[:objectguid]\n obj = db_objs_by_guid[guid] || new\n obj.copy_from_activedirectory!(:object => ad_obj) if obj.new_record?\n\n local_objs << obj\n end\n\n local_objs\n end",
"def cdsin_create_lib(name)\r\n cdslib = Cdslib.find_by_name(name)\r\n \r\n if cdslib\r\n cdslib.touch(:updated_at)\r\n else\r\n cdslib = Cdslib.create!(name: name)\r\n end\r\n \r\n return cdslib\r\n end",
"def find_or_create_by_name(title)\n find_by_name(title) || self.new(title) # + self.save ?\n end",
"def add_article(magazine, title)\n Article.new(magazine, title)\n\n end",
"def create_collection(collectionName=nil)\n if collectionName.class == String && block_given?\n @j_del.java_method(:createCollection, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(collectionName,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil) }))\n return self\n end\n raise ArgumentError, \"Invalid arguments when calling create_collection(#{collectionName})\"\n end",
"def collection(http_verb, action = nil, body = nil, options)\n actual_client(options).send(http_verb, path(action), body, options)\n end",
"def set_library\n @library = AdminLibrary.friendly.find(params[:id]) \n end",
"def set_book_collection\n @book_collection = BookCollection.find(params[:id])\n end",
"def create\n @collection = current_user.collections.build(params[:collection])\n\n # set some default values - set collection value to the number of current collections\n if Collection.where(\"name like ?\", \"%Untitled%\").count > 0\n count = Collection.where(\"name like ?\", \"%Untitled%\").order(\"created_at DESC\").first.name.sub('Untitled-Collection-','').to_i + 1\n else\n count = 1\n end\n \n @collection.name = \"Untitled-Collection-\"+count.to_s()\n @collection.user = current_user\n @collection.challenge = false\n @collection.privacy = \"unlisted\"\n\n respond_to do |format|\n if @collection.save\n @collection.update_attributes(:name => \"Untitled-Collection-\" + @collection.id.to_s)\n format.html { redirect_to @collection }\n format.json { render :json => @collection, :status => :created, :location => @collection }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @collection.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_or_update_by_api(params = {})\n babel = params_to_translator(params)\n record = find_by_translator(babel).first\n record.present? ? update_by_translator(babel, record) : create_by_translator(babel)\n end",
"def buy_cat(name)\n #passing a name and this owner object into the cat object\n cat = Cat.new(name, self) \n @cats << cat\n \n end",
"def add_to_collection_action (collection, item)\n\n api = Harvard::LibraryCloud::API.new\n path = 'collections/' + collection\n\n connection = Faraday.new(:url => api.get_base_uri + path) do |faraday|\n faraday.request :url_encoded\n faraday.response :logger\n faraday.adapter Faraday.default_adapter\n faraday.headers['Content-Type'] = 'application/json'\n faraday.headers['X-LibraryCloud-API-Key'] = ENV[\"LC_API_KEY\"]\n end\n\n raw_response = begin\n response = connection.post do |req|\n req.body = '[{\"item_id\": \"' + item + '\"}]'\n end\n { status: response.status.to_i, headers: response.headers, body: response.body.force_encoding('utf-8') }\n rescue Errno::ECONNREFUSED, Faraday::Error => e\n raise RSolr::Error::Http.new(connection, e.response)\n end\n end",
"def present_collection(collection = resource); nil; end",
"def get_object\n class_name.create_from_database(id)\n end",
"def create\n data = CatalogItem.new(name: params[:name], description: params[:description])\n data.save\n render json: data\n end",
"def create\n @category_collection = CategoryCollection.new(params[:category_collection])\n @collection = @category_collection.collection\n\n respond_to do |format|\n if @category_collection.save\n flash[:notice] = 'CategoryCollection was successfully created.'\n format.html { redirect_to(@collection) }\n format.xml { render :xml => @category_collection, :status => :created, :location => @category_collection }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @category_collection.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_by_api(params = {})\n create_by_translator params_to_translator(params)\n end",
"def create\n if params[:collection]\n @collection = Collection.new( params[:collection] )\n # Check: if user submitted an id, but it is not set, there was an error\n if params[:collection][:id] && params[:collection][:id] != @collection.id\n render_json :status => :bad_request, :messages => @collection.errors.full_messages and return\n end\n\n if @user && params[:collection][:owner_id]\n if @collection.indestructible\n render_json :status => :bad_request, :messages => \"Cannot set both: owner and indestructible\" and return\n elsif params[:collection][:owner_id] != @user.guid\n render_json :status => :bad_request, :messages => \"Owner cannot be different than logged in user.\" and return\n else\n @collection.owner = @user\n end\n else\n if params[:collection][:priv]\n render_json :status => :bad_request, :messages => \"Cannot set a collection private without an owner.\" and return\n end\n end\n else\n @collection = Collection.new\n end\n @collection.client = @client\n @collection.updated_by = @user ? @user.guid : @client.id\n\n if @collection.save\n render_json :status => :created, :entry => @collection.to_hash(@user, @client) and return\n else\n render_json :status => :bad_request, :messages => @collection.errors.full_messages and return\n end\n end",
"def addBook(book)\n\t\tinventories.create(book_id: book.id)\n\tend",
"def add(library)\n library = Library.new(library) unless Library === library\n\n #raise TypeError unless Library === library\n #begin\n entry = (@ledger[library.name] ||= [])\n\n case entry\n #when NilClass\n # raise \"serious shit! nil entry in ledger table!\"\n when Array\n entry << library unless entry.include?(library)\n else\n # Library is already active so compare and make sure they are the\n # same, otherwise warn. (Should this ever raise an error?)\n if entry != library # TODO: Is this the right equals comparison?\n warn \"Added library has already been activated.\"\n end\n end\n #rescue Exception => error\n # warn error.message if ENV['debug']\n #end\n\n library\n end",
"def find_collection\n @collection = Collection.find(params[:id])\n end",
"def add_article(title, magazine)\n #going to create a new article when\n # given title and magazine\n #I have to be sure that when creating\n #an article I give it a title,author,magazine\n Article.new(title, magazine,author)\n end",
"def perform_post_with_object_from_collection(path, options, klass, collection_name)\n perform_request_with_object_from_collection(:post, path, options, klass, collection_name)\n end",
"def create\n @collection = Collection.new(collection_params)\n\n respond_to do |format|\n if @collection.save\n format.html { redirect_to @collection, notice: 'Collection was successfully created.' }\n format.json { render action: 'show', status: :created, location: @collection }\n\n\n else\n format.html { render action: 'new' }\n format.json { render json: @collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n if is_amf\n @collection = Collection.new(params[0])\n # @collection.update_attributes(params[0])\n else\n @collection = Collection.new(params[:collection])\n end\n\n respond_to do |format|\n if @collection.save\n flash[:notice] = 'Collection was successfully created.'\n format.html { redirect_to(@collection) }\n format.xml { render :xml => @collection, :status => :created, :location => @collection }\n format.amf {render :amf =>\"Collection Saved\"}\n else\n format.html { render :action => \"new\"}\n format.xml { render :xml => @collection.errors, :status => :unprocessable_entity }\n format.amf {render :amf => @collection.errors}\n end\n end\n end",
"def add_entry(name)\n Library.create(name: name)\n end",
"def create\n @collection = Admin::Collection.new(collection_params)\n\n if @collection.save\n render json: @collection, status: :created#, location: @collection\n else\n render json: @collection.errors, status: :unprocessable_entity\n end\n end",
"def create_fedora_objects(attributes, files_directory, collection_id)\n factory_class = ::Importer::Factory.for(\"Item\")\n f = factory_class.new(attributes, files_directory, collection_id)\n f.run\n end",
"def make_collection\n# Dir.mkdir(file_path)\n# Created\n\n # ディレクトリなら末尾に「/」をつける。\n # (dstにもともと「/」が付いているかどうか、クライアントに依存している)\n # CarotDAV : 「/」が付いていない\n # TeamFile : 「/」が付いている\n collection!\n\n bson = @collection.find_one({:filename => file_path}) rescue nil\n\n # 0バイトのファイルを作成しディレクトリの代わりとする\n @filesystem.open(file_path, \"w\") { |f| } if !bson\n \n# @@logger.error('make_collection : ' + file_path)\n\n Created\n end",
"def create\n @collection = Collection.new(params[:collection])\n\n # scrape each resource URL to add those fields\n @collection.collectionizes.each do |each_collectionize|\n resource_object = Resource.scrape_data(each_collectionize.resource.raw_url)\n\n each_collectionize.resource\n resource_object = Resource.scrape_data(@resource.raw_url)\n each_collectionize.resource.keywords_scraped = resource_object[:keywords_scraped] ? resource_object[:keywords_scraped] : nil\n each_collectionize.resource.description_scraped = resource_object[:description_scraped] ? resource_object[:description_scraped] : nil\n each_collectionize.resource.title_scraped = resource_object[:title_scraped] ? resource_object[:title_scraped] : nil\n each_collectionize.resource.raw_html = resource_object[:raw_html] ? resource_object[:raw_html] : nil\n end\n\n respond_to do |format|\n if @collection.save\n redirect_to @collection, notice: 'Collection was successfully created.'\n else\n render action: \"new\"\n end\n end\n end"
] |
[
"0.55714256",
"0.5533466",
"0.55154943",
"0.5514012",
"0.54876447",
"0.5331431",
"0.53138965",
"0.52313167",
"0.52232236",
"0.52202266",
"0.5167979",
"0.515217",
"0.51007354",
"0.49806887",
"0.49253234",
"0.4910403",
"0.49039218",
"0.49008265",
"0.4878139",
"0.48753464",
"0.48620987",
"0.48422062",
"0.48402432",
"0.4816816",
"0.4802097",
"0.47894096",
"0.478744",
"0.47778073",
"0.47691584",
"0.47462058",
"0.47240573",
"0.47143143",
"0.47120717",
"0.470526",
"0.46923575",
"0.4690206",
"0.4690206",
"0.46884912",
"0.46856672",
"0.4683426",
"0.46805757",
"0.46789584",
"0.46773642",
"0.46726608",
"0.46638677",
"0.46633697",
"0.46544144",
"0.46494848",
"0.46422783",
"0.46370092",
"0.4634133",
"0.46297306",
"0.46226367",
"0.46139485",
"0.46081206",
"0.4607553",
"0.46072805",
"0.4604798",
"0.45961362",
"0.4588663",
"0.45869017",
"0.45853177",
"0.45840675",
"0.45840675",
"0.4583038",
"0.4581006",
"0.45766544",
"0.45741925",
"0.45694053",
"0.45545352",
"0.45516333",
"0.4551142",
"0.45428246",
"0.45405757",
"0.45400375",
"0.4531776",
"0.45299673",
"0.45269936",
"0.45245463",
"0.45229506",
"0.45193988",
"0.45189267",
"0.45179415",
"0.45174158",
"0.4517394",
"0.45159853",
"0.4514747",
"0.4508862",
"0.45009503",
"0.44995224",
"0.44986826",
"0.44971675",
"0.44968668",
"0.4494025",
"0.4490015",
"0.44894007",
"0.4485465",
"0.4485438",
"0.44823134",
"0.44720834"
] |
0.6880261
|
0
|
GET /sites GET /sites.json
|
def index
if current_user
if current_user.id == 1 && current_user.email == 'master@inruby.com'
@sites = Site.order("updated_at desc").page(params[:page] || 1)
else
@sites = current_user.sites.page(params[:page] || 1)
end
elsif current_member
@sites = current_member.sites.page(params[:page] || 1)
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n respond_to do |format|\n format.html do \n @sites = Site.all\n end\n format.json do\n render json: Site.all\n end\n end\n end",
"def index\n @parsed_sites = ParsedSite.all\n\n render json: @parsed_sites\n end",
"def index\n @sites = current_user.sites.page(params[\"page\"])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n set_user\n @sites = Site.all\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites.to_json }\n end\n end",
"def index\n @sites = fetch_sites\n\n @formattedSites = @sites.map do |site|\n {\n 'title' => {'value' => site.name, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'template' => {'value' => site.site_template&.name, 'searchable' => true, 'sortable' => true},\n 'preview' => {'value' => site.routes.first.host_with_scheme, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'edit' => {'value' => edit_admin_site_site_step_path(site_slug: site.slug, id: :name), 'method' => 'get'},\n 'delete' => {'value' => admin_site_path(slug: site.slug), 'method' => 'delete'}\n }\n end\n\n gon.sites = @formattedSites\n\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites }\n end\n end",
"def show\n render json: @parsed_site\n end",
"def index\n @sites = Site.paginate(:page=>params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n \n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def index\n add_breadcrumb \"all\", nil, \"glyphicon-list\"\n\n @sites = current_user.account.sites || []\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n @site = Site.find(params[:site_id])\n @visits = @site.visits\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @visits }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @site }\n end\n end",
"def index\n @supplysites = Supplysite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @supplysites }\n end\n end",
"def show\n respond_to do |format|\n format.html { render :show }\n format.json { render json: @site }\n end\n end",
"def get_sites_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.get_sites ...\"\n end\n # resource path\n local_var_path = \"/api/3/sites\"\n\n # query parameters\n query_params = {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'size'] = opts[:'size'] if !opts[:'size'].nil?\n query_params[:'sort'] = @api_client.build_collection_param(opts[:'sort'], :multi) if !opts[:'sort'].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;charset=UTF-8'])\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 = 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 => 'PageOfSite')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_sites\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n respond_to do |format|\n format.html do \n set_site\n @site\n end\n format.json do\n render json: @site\n end\n end\n end",
"def get_sites_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.get_sites ...'\n end\n # resource path\n local_var_path = '/api/3/sites'\n\n # query parameters\n query_params = {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'size'] = opts[:'size'] if !opts[:'size'].nil?\n query_params[:'sort'] = @api_client.build_collection_param(opts[:'sort'], :multi) if !opts[:'sort'].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;charset=UTF-8'])\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 = 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 => 'PageOfSite')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_sites\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def test_get_site_list\r\n endpoint = \"/sites\"\r\n uri = URI(\"#{@host}#{endpoint}\")\r\n request = Net::HTTP::Get.new(uri)\r\n request['Accept'] = 'application/json'\r\n \r\n test_start = Time.now\r\n response = Net::HTTP.start(uri.hostname, uri.port) do |http|\r\n http.request(request)\r\n end\r\n test_end = Time.now\r\n\r\n @results << {\r\n :api => 'GET /sites',\r\n :endpoint => endpoint,\r\n :start_time => test_start,\r\n :runtime => (test_end.to_f - test_start.to_f) * 1000.0,\r\n :status => response.code,\r\n :content_type => response['content-type']\r\n }\r\n end",
"def sites\n request('/web_properties.json').map do |site_data|\n Site.new self, site_data['uid'], site_data['name']\n end\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = current_user.sites\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = current_user.sites\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @user = self.current_user\n @sites = @user.find_sites(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @sites.to_xml }\n end\n end",
"def index\n\n sites = Site.all\n @sites = current_user.sites\n @needs_attention_reports = Report.needs_attention\n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @sites }\n # end\n\n respond_with(sites) do |format|\n format.html # { redirect_to site_user_sites_path }\n format.json { render :json => @sites.as_json }\n end\n end",
"def index\n @site_setups = SiteSetup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_setups }\n end\n end",
"def get_sites\n\t\ts = get_admin_section \"system.applicationHost/sites\"\n\t IisObjectCollection.new s.Collection, :site, Site, lambda { |site| site.id = s.Collection.Count + 1 }\n end",
"def index\n @watch_sites = WatchSite.includes(:team, :venue).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @watch_sites }\n end\n end",
"def index\n @sites = Cms::Site.all\n end",
"def index\n @sites = User.find(current_user.id).sites #Site.find(\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def show\n @website = Website.find(params[:id])\n\n render json: @website\n end",
"def index\n serialized = []\n Site.all.each do |site|\n attribute = format_site(site)\n serialized.push(attribute)\n end\n render(json:serialized)\n end",
"def index\n @urls = @site.urls.paginate(:page => params[:page])\n render json: @urls\n end",
"def index\n @servers = Server.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @servers.to_json(:include => { :websites => {:include => :plugins } }) }\n end\n end",
"def get_sites(opts = {})\n data, _status_code, _headers = get_sites_with_http_info(opts)\n data\n end",
"def get_sites(opts = {})\n data, _status_code, _headers = get_sites_with_http_info(opts)\n return data\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def show\n @subsite = Subsite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subsite }\n end\n end",
"def index\n @places = @site.places.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @places }\n end\n end",
"def index\n @sites = Site.all.order(:created_at)\n\n # @debug = scrape_all\n # @debug = scrape 'http://workingnews.blog117.fc2.com/?xml'\n \n # @spreadsheet = GoogleSpreadsheets::Enhanced::Spreadsheet.find('0ArhV7gTgs6Z8dHlSRUF2SzFXWjlkU1V2d29KR2pkdXc')\n # @worksheet = @spreadsheet.worksheets.find_by(title: 'site_rows')\n # @rows = @worksheet.rows\n # @site_rows = Site.site_rows\n \n # 同期実行\n # Site.sync_with_site_rows\n\n # スクレイピング\n # ApplicationController.helpers.scrape_update\n # ApplicationController.helpers.scrape \"http://alfalfalfa.com/index.rdf\"\n\n respond_to do |format|\n if Rails.env.development?\n format.html { render :html => @sites }\n end\n format.json { render :json => @sites.as_json }\n end\n end",
"def index\n @pages = current_site.pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end",
"def index\n @sites = @organization.sites.order(id: :desc).all\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html { render layout: false }\n format.json\n format.geojson\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @site }\n format.xml { render :xml => @site }\n end\n end",
"def index\n @servers = @site.servers\n end",
"def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_records }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html { render :template => \"admin_sites/index\" }\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.joins(:users)\n .where(users: {id: current_user.id})\n .order(params[:order] || 'created_at ASC')\n\n respond_to do |format|\n format.html { redirect_to management_path }\n format.json { render json: @sites }\n end\n end",
"def show\n @sitecity = Sitecity.find_by_url(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitecity }\n end\n end",
"def index\n p = Profile.where(:username=>session[:username]).first\n if(!p.nil?)\n @sites = Profile.mysite(p.id)\n if(p.id==1)\n @sites = Site.find(:all, :order => \"created_at DESC\")\n end\n else\n redirect_to '/' and return\n end\n @site = Site.new\n @profile_id = Profile.where(:username=>session[:username]).first.id\n @categories = p.categories.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def show\n @site_config = SiteConfig.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_config }\n end\n end",
"def index\n @apps = @client.apps\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @apps }\n end\n end",
"def show\n @watch_site = WatchSite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @watch_site }\n end\n end",
"def index\n # @events = Event.order('created_at desc').limit(15)\n @events = Event.by_site( current_user.sites )\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @events }\n end\n end",
"def show\n @system_site_map = SystemSiteMap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @system_site_map }\n end\n end",
"def show\n @site = Site.find_by_site(params[:id])\n @organisation = @site.organisation\n @total_data = WeeklyTotalData.new(@site.weekly_totals, Date.new(2012,10,17)..Date.today, true)\n @most_recent_hit_data = AggregratedMostRecentHitData.new(@site.aggregated_hits, @site.hits.most_recent_hit_on_date)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def index\n @site_editorials = SiteEditorial.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_editorials }\n end\n end",
"def show\n @supplysite = Supplysite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @supplysite }\n end\n end",
"def site_list\n @sites = Haiwet::Site.list\n @sites.each.with_index(1) do |site, i|\n puts \"\\n #{i}- #{site.name}\"\n end\n end",
"def index\n @mysites = Mysite.all\n end",
"def get_sites(site_type=nil)\r\n logger.debug \"Inside Get Sites of AMF controller\"\r\n if site_type.nil?\r\n if params.key?(0) \r\n site_type=params[0]\r\n else\r\n raise \"No site passed because #{params.length} and #{params[0].key?(\"site_type\")} to get_sites #{params.inspect()}\"\r\n end\r\n end\r\n\t\tsite_list=Site.data_sites(site_type)\r\n respond_to do |format|\r\n format.html\r\n format.xml { render :xml => site_list.to_x }\r\n format.amf { \r\n logger.debug \"Returning site_list\"\r\n logger.debug \"Returning #{site_list}\"\r\n render :amf => site_list \r\n }\r\n end\r\n end",
"def sites\n @sites ||= []\n end",
"def index\n @servers = Server.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @servers }\n end\n end",
"def show\n @site = Site.find(params[:site_id])\n @visit = Visit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @visit }\n end\n end",
"def show\n @site_setup = SiteSetup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_setup }\n end\n end",
"def blogs\n get(get_all_sites_uri)\n end",
"def index\n @urls = Url.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @urls }\n end\n end",
"def index\n @searches = @website.searches.all\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @searches }\n end\n end",
"def show\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitio }\n end\n end",
"def new\n @site = Site.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @sites = current_user.sites\n @post = current_user.posts.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end",
"def show\n respond_with(@site = Site.find(params[:id]))\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def yields_from_sites\n @sites = Yield.all.collect {|x| x.site}.compact.uniq\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n @blogs = Blog.all\n\n render json: @blogs\n end",
"def servers\n response = get \"server\"\n data = JSON.parse response.body\n data[\"servers\"][\"server\"]\n end",
"def servers\n response = get \"server\"\n data = JSON.parse response.body\n data[\"servers\"][\"server\"]\n end",
"def show\n add_breadcrumb \"all\", nil, \"glyphicon-screenshot\"\n\n @site = Site.find(id_from_params)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def list_sites\n r = execute(make_xml('SiteListingRequest'))\n arr = []\n if r.success\n r.res.elements.each('SiteListingResponse/SiteSummary') do |site|\n arr << SiteSummary.new(site.attributes['id'].to_i,\n site.attributes['name'],\n site.attributes['description'],\n site.attributes['riskfactor'].to_f,\n site.attributes['riskscore'].to_f)\n end\n end\n arr\n end",
"def show\n @server = Server.find(params[:id])\n add_breadcrumb @server.name, [@server]\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @server.to_json(:include => { :websites => {:include => :plugins } }) }\n end\n end",
"def show_domains\n render json: dme.show_domains\n end",
"def index\n @sites = Site.all.paginate(page: params[:page])\n end",
"def show\n @site_type = SiteType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_type }\n end\n end",
"def index\n @blogs = Blog.all\n render json: @blogs\n end",
"def index\n @services = SystemSiteMap.where(:system_site_map_id => 2)\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def sites\n if permission.value.positive?\n Site.all_cached\n else\n Rails.cache.fetch(\"user_#{id}_sites\", expires_in: 1.month, race_condition_ttl: 30.seconds) do\n puts 'user sites not cached'\n connections.map { |c| Site.find(c.site_id) }.sort_by(&:title)\n end\n end\n end"
] |
[
"0.77209103",
"0.77209103",
"0.7517273",
"0.7412494",
"0.73809344",
"0.7306581",
"0.7016558",
"0.6896694",
"0.684382",
"0.68408626",
"0.6827524",
"0.6827524",
"0.6827524",
"0.67936283",
"0.67904365",
"0.6769869",
"0.67423725",
"0.66910815",
"0.66882485",
"0.66785043",
"0.66521466",
"0.66424197",
"0.6613439",
"0.65869516",
"0.65869516",
"0.65869516",
"0.65869516",
"0.65869516",
"0.65869516",
"0.6562677",
"0.6562677",
"0.6551698",
"0.6536342",
"0.6525839",
"0.65226793",
"0.65177536",
"0.6511316",
"0.6471796",
"0.6469479",
"0.6468147",
"0.64573133",
"0.6426551",
"0.6393728",
"0.63544273",
"0.63501686",
"0.63501686",
"0.63501686",
"0.63501686",
"0.63501686",
"0.6310315",
"0.63024837",
"0.62726283",
"0.6272135",
"0.6269268",
"0.626544",
"0.6218962",
"0.6213384",
"0.62066585",
"0.6155453",
"0.6134405",
"0.6125617",
"0.6124111",
"0.6095611",
"0.60954916",
"0.6071191",
"0.6070038",
"0.6022135",
"0.60206896",
"0.60122335",
"0.59945947",
"0.59815735",
"0.59780544",
"0.5964147",
"0.59626627",
"0.59582084",
"0.59572524",
"0.59504825",
"0.5948615",
"0.5944582",
"0.5926657",
"0.59242934",
"0.59228754",
"0.59201735",
"0.5911206",
"0.5904415",
"0.5904415",
"0.5904415",
"0.5904415",
"0.5889802",
"0.5888312",
"0.58807516",
"0.58807516",
"0.5871328",
"0.58674216",
"0.5860515",
"0.58517873",
"0.5843197",
"0.58426565",
"0.58422554",
"0.58340263",
"0.58265984"
] |
0.0
|
-1
|
GET /sites/1 GET /sites/1.json
|
def show
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n @sites = current_user.sites.page(params[\"page\"])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n respond_to do |format|\n format.html do \n @sites = Site.all\n end\n format.json do\n render json: Site.all\n end\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n \n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def index\n set_user\n @sites = Site.all\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites.to_json }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @site }\n end\n end",
"def index\n @parsed_sites = ParsedSite.all\n\n render json: @parsed_sites\n end",
"def show\n respond_to do |format|\n format.html do \n set_site\n @site\n end\n format.json do\n render json: @site\n end\n end\n end",
"def index\n @site = Site.find(params[:site_id])\n @visits = @site.visits\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @visits }\n end\n end",
"def show\n respond_to do |format|\n format.html { render :show }\n format.json { render json: @site }\n end\n end",
"def show\n render json: @parsed_site\n end",
"def show\n @website = Website.find(params[:id])\n\n render json: @website\n end",
"def index\n @sites = fetch_sites\n\n @formattedSites = @sites.map do |site|\n {\n 'title' => {'value' => site.name, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'template' => {'value' => site.site_template&.name, 'searchable' => true, 'sortable' => true},\n 'preview' => {'value' => site.routes.first.host_with_scheme, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'edit' => {'value' => edit_admin_site_site_step_path(site_slug: site.slug, id: :name), 'method' => 'get'},\n 'delete' => {'value' => admin_site_path(slug: site.slug), 'method' => 'delete'}\n }\n end\n\n gon.sites = @formattedSites\n\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites }\n end\n end",
"def index\n @sites = Site.paginate(:page=>params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n add_breadcrumb \"all\", nil, \"glyphicon-list\"\n\n @sites = current_user.account.sites || []\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def show\n @subsite = Subsite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subsite }\n end\n end",
"def index\n @supplysites = Supplysite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @supplysites }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @site }\n format.xml { render :xml => @site }\n end\n end",
"def test_get_site_list\r\n endpoint = \"/sites\"\r\n uri = URI(\"#{@host}#{endpoint}\")\r\n request = Net::HTTP::Get.new(uri)\r\n request['Accept'] = 'application/json'\r\n \r\n test_start = Time.now\r\n response = Net::HTTP.start(uri.hostname, uri.port) do |http|\r\n http.request(request)\r\n end\r\n test_end = Time.now\r\n\r\n @results << {\r\n :api => 'GET /sites',\r\n :endpoint => endpoint,\r\n :start_time => test_start,\r\n :runtime => (test_end.to_f - test_start.to_f) * 1000.0,\r\n :status => response.code,\r\n :content_type => response['content-type']\r\n }\r\n end",
"def index\n @site_setups = SiteSetup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_setups }\n end\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def index\n @sites = Site.all\n end",
"def show\n @site_config = SiteConfig.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_config }\n end\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html { render layout: false }\n format.json\n format.geojson\n end\n end",
"def index\n @sites = User.find(current_user.id).sites #Site.find(\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def get_sites\n\t\ts = get_admin_section \"system.applicationHost/sites\"\n\t IisObjectCollection.new s.Collection, :site, Site, lambda { |site| site.id = s.Collection.Count + 1 }\n end",
"def show\n @sitecity = Sitecity.find_by_url(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitecity }\n end\n end",
"def index\n @sites = current_user.sites\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = current_user.sites\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def show\n @site_setup = SiteSetup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_setup }\n end\n end",
"def show\n @watch_site = WatchSite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @watch_site }\n end\n end",
"def index\n @user = self.current_user\n @sites = @user.find_sites(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @sites.to_xml }\n end\n end",
"def index\n @sites = Cms::Site.all\n end",
"def index\n @servers = @site.servers\n end",
"def show\n @supplysite = Supplysite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @supplysite }\n end\n end",
"def index\n serialized = []\n Site.all.each do |site|\n attribute = format_site(site)\n serialized.push(attribute)\n end\n render(json:serialized)\n end",
"def show\n add_breadcrumb \"all\", nil, \"glyphicon-screenshot\"\n\n @site = Site.find(id_from_params)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find(params[:site_id])\n @visit = Visit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @visit }\n end\n end",
"def show\n @site_type = SiteType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site_type }\n end\n end",
"def show\n respond_with(@site = Site.find(params[:id]))\n end",
"def show\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitio }\n end\n end",
"def sites\n request('/web_properties.json').map do |site_data|\n Site.new self, site_data['uid'], site_data['name']\n end\n end",
"def show\n @installation_site = InstallationSite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @installation_site }\n end\n end",
"def index\n @watch_sites = WatchSite.includes(:team, :venue).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @watch_sites }\n end\n end",
"def index\n\n sites = Site.all\n @sites = current_user.sites\n @needs_attention_reports = Report.needs_attention\n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @sites }\n # end\n\n respond_with(sites) do |format|\n format.html # { redirect_to site_user_sites_path }\n format.json { render :json => @sites.as_json }\n end\n end",
"def index\n p = Profile.where(:username=>session[:username]).first\n if(!p.nil?)\n @sites = Profile.mysite(p.id)\n if(p.id==1)\n @sites = Site.find(:all, :order => \"created_at DESC\")\n end\n else\n redirect_to '/' and return\n end\n @site = Site.new\n @profile_id = Profile.where(:username=>session[:username]).first.id\n @categories = p.categories.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def get_sites_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.get_sites ...\"\n end\n # resource path\n local_var_path = \"/api/3/sites\"\n\n # query parameters\n query_params = {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'size'] = opts[:'size'] if !opts[:'size'].nil?\n query_params[:'sort'] = @api_client.build_collection_param(opts[:'sort'], :multi) if !opts[:'sort'].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;charset=UTF-8'])\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 = 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 => 'PageOfSite')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_sites\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def get_sites_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.get_sites ...'\n end\n # resource path\n local_var_path = '/api/3/sites'\n\n # query parameters\n query_params = {}\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'size'] = opts[:'size'] if !opts[:'size'].nil?\n query_params[:'sort'] = @api_client.build_collection_param(opts[:'sort'], :multi) if !opts[:'sort'].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;charset=UTF-8'])\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 = 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 => 'PageOfSite')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_sites\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_records }\n end\n end",
"def show\n @system_site_map = SystemSiteMap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @system_site_map }\n end\n end",
"def index\n @urls = @site.urls.paginate(:page => params[:page])\n render json: @urls\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sites }\n end\n end",
"def new\n @site = Site.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def index\n @sites = Site.all.order(:created_at)\n\n # @debug = scrape_all\n # @debug = scrape 'http://workingnews.blog117.fc2.com/?xml'\n \n # @spreadsheet = GoogleSpreadsheets::Enhanced::Spreadsheet.find('0ArhV7gTgs6Z8dHlSRUF2SzFXWjlkU1V2d29KR2pkdXc')\n # @worksheet = @spreadsheet.worksheets.find_by(title: 'site_rows')\n # @rows = @worksheet.rows\n # @site_rows = Site.site_rows\n \n # 同期実行\n # Site.sync_with_site_rows\n\n # スクレイピング\n # ApplicationController.helpers.scrape_update\n # ApplicationController.helpers.scrape \"http://alfalfalfa.com/index.rdf\"\n\n respond_to do |format|\n if Rails.env.development?\n format.html { render :html => @sites }\n end\n format.json { render :json => @sites.as_json }\n end\n end",
"def index\n @servers = Server.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @servers.to_json(:include => { :websites => {:include => :plugins } }) }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @site = Site.find_by_site(params[:id])\n @organisation = @site.organisation\n @total_data = WeeklyTotalData.new(@site.weekly_totals, Date.new(2012,10,17)..Date.today, true)\n @most_recent_hit_data = AggregratedMostRecentHitData.new(@site.aggregated_hits, @site.hits.most_recent_hit_on_date)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def index\n @sites = @organization.sites.order(id: :desc).all\n end",
"def index\n @pages = current_site.pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end",
"def show\n @site = Site.find(params[:id])\n @noaa_table = @site.noaa_table\n @completed_reports = @site.reports.completed\n @needs_attention_reports = @site.reports.needs_attention\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @site }\n end\n end",
"def show\n @viaje = Viaje.find(params[:id])\n @sitio = Site.find(@viaje.site_id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @viaje }\n end\n end",
"def show\n @site = Site.find(params[:id])\n end",
"def show\n @early_vote_site = EarlyVoteSite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @early_vote_site }\n end\n end",
"def index\n @sites = Site.joins(:users)\n .where(users: {id: current_user.id})\n .order(params[:order] || 'created_at ASC')\n\n respond_to do |format|\n format.html { redirect_to management_path }\n format.json { render json: @sites }\n end\n end",
"def index\n @places = @site.places.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @places }\n end\n end",
"def show\n @sites = current_user.sites\n @post = current_user.posts.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @post }\n end\n end",
"def index\n @apps = @client.apps\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @apps }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html { render :template => \"admin_sites/index\" }\n format.xml { render :xml => @sites }\n end\n end",
"def index\n @services = SystemSiteMap.where(:system_site_map_id => 2)\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n @site=Site.find(params[:site_id])\n end",
"def index\n @websites = Website.where(client_id: current_client.uuid) \n end",
"def show\n @host = Host.find(params[:id])\n\n render json: @host\n end",
"def show\n @server = Server.find(params[:id])\n add_breadcrumb @server.name, [@server]\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @server.to_json(:include => { :websites => {:include => :plugins } }) }\n end\n end",
"def show\n @host = Host.find_by(hostname: params[:id])\n\n render json: @host\n end",
"def new\n @site = Site.new\n @site.url = 'http://'\n @site.creator = current_user.name if user_signed_in?\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def iis_site(name)\n command = \"Get-Website '#{name}' | Select-Object -Property Name,State,PhysicalPath,bindings,ApplicationPool | ConvertTo-Json\"\n cmd = @inspec.command(command)\n\n begin\n site = JSON.parse(cmd.stdout)\n rescue JSON::ParserError => _e\n return nil\n end\n\n bindings_array = site['bindings']['Collection'].map { |k|\n \"#{k['protocol']} #{k['bindingInformation']}#{k['protocol'] == 'https' ? \" sslFlags=#{k['sslFlags']}\" : ''}\"\n }\n\n # map our values to a hash table\n info = {\n name: site['name'],\n state: site['state'],\n path: site['physicalPath'],\n bindings: bindings_array,\n app_pool: site['applicationPool'],\n }\n\n info\n end",
"def show\n @site = Site.find(params[:id])\n\n respond_to do |format|\n format.html { render :template => \"admin_sites/show\" }\n format.xml { render :xml => @site }\n end\n end",
"def index\n # @events = Event.order('created_at desc').limit(15)\n @events = Event.by_site( current_user.sites )\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @events }\n end\n end",
"def site_list\n @sites = Haiwet::Site.list\n @sites.each.with_index(1) do |site, i|\n puts \"\\n #{i}- #{site.name}\"\n end\n end",
"def get_default_profile \n get(\"/profiles.json/default\")\nend",
"def yields_from_sites\n @sites = Yield.all.collect {|x| x.site}.compact.uniq\n\n respond_to do |format|\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: @site_plan }\n end\n end",
"def index\n @servers = Server.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @servers }\n end\n end",
"def index\n @urls = Url.get_top(25)\n # render json: @urls\n end",
"def index\n @mysites = Mysite.all\n end",
"def index\n @site_editorials = SiteEditorial.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @site_editorials }\n end\n end"
] |
[
"0.7444836",
"0.7444836",
"0.7214904",
"0.7204854",
"0.7108241",
"0.70891887",
"0.70891887",
"0.70891887",
"0.7068557",
"0.703299",
"0.69449097",
"0.68207115",
"0.68081486",
"0.67804134",
"0.67772996",
"0.6742932",
"0.67404276",
"0.6618609",
"0.656212",
"0.6556428",
"0.6555624",
"0.6493333",
"0.6458377",
"0.6431192",
"0.6414973",
"0.6414973",
"0.6414973",
"0.6414973",
"0.6414973",
"0.6414973",
"0.6398064",
"0.63972944",
"0.63871765",
"0.6378306",
"0.6373663",
"0.63594985",
"0.63594985",
"0.6351067",
"0.63500124",
"0.6340426",
"0.6266576",
"0.625721",
"0.62558734",
"0.62418216",
"0.624019",
"0.623966",
"0.6232907",
"0.6232029",
"0.6230657",
"0.6226175",
"0.6222117",
"0.6221106",
"0.62144166",
"0.62079835",
"0.62073827",
"0.61997145",
"0.6197133",
"0.61892974",
"0.6161971",
"0.61517394",
"0.61517394",
"0.61517394",
"0.61517394",
"0.61517394",
"0.61196244",
"0.6119034",
"0.6106811",
"0.6104623",
"0.6104623",
"0.6104623",
"0.6104623",
"0.60958534",
"0.60917354",
"0.6083017",
"0.6079121",
"0.60729706",
"0.6060818",
"0.6054528",
"0.60112417",
"0.5999064",
"0.59917974",
"0.5981275",
"0.5973849",
"0.5927887",
"0.5907821",
"0.59014565",
"0.59011805",
"0.58967024",
"0.58878267",
"0.5868145",
"0.5866233",
"0.5856979",
"0.58555007",
"0.5847525",
"0.58471704",
"0.58456635",
"0.58372766",
"0.5830401",
"0.5806269",
"0.5804993",
"0.57993335"
] |
0.0
|
-1
|
POST /sites POST /sites.json
|
def create
@site = Site.new(site_params)
@site.user_id = current_user.id if current_user
@site.member_id = current_member.id if current_member
@site.typo = ['personal', 'business'].delete(params[:typo].to_s.downcase) || 'personal'
respond_to do |format|
if @site.save!
if params[:typo] == 'business'
@site.site_payment.price = ENV["PRICE_BUSINESS"]
@site.site_payment.save!
end
if @site.template.property == 'free'
@site.set_free
end
#build site_page via template_page
Templates::Page.where(template_id: @site.template_id).order("position ASC").each do |temp_page|
@site.site_pages.create(
site_id: @site.id,
template_page_id: temp_page.id,
title: temp_page.title)
end
#add a comment
SiteComment.create(site_id: @site.id, name: '维斗喜帖', content: '小维斗来过,提前送上一声祝福~')
#send notice to admin
# if Rails.env == 'production'
# SmsSendWorker.perform_async(ENV['ADMIN_PHONE'].split('|').join(','), "#{@site.user.try(:email) || @site.member.try(:auth_id)}创建了应用:#{get_site_url(@site)}")
# end
#redirect
format.html { redirect_to site_site_steps_path(@site), notice: t('notice.site.created') }
format.json { render action: 'show', status: :created, location: @site }
else
format.html { render action: 'new' }
format.json { render json: @site.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n @site = current_user.sites.create(params[:site])\n respond_to do |format|\n if @site.save\n format.html { flash_and_redirect(\"successfully saved!\", sites_url) }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = current_user.sites.build(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to root_url(subdomain: @site.subdomain), notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n respond_to do |format|\n if @site = Site.find(entity_id_from_params(:site))\n current_user.account.sites << @site\n format.html { redirect_to root_path, notice: \"The site #{@site.name} @ #{@site.companies.last.name} was successfully added.\" }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = current_user.sites.build(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = @organization.sites.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to after_create_path, notice: 'Site was successfully created.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.create site_params\n respond_to do |format|\n if @site.errors.empty?\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to edit_site_path(@site), notice: 'Site was successfully created.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n flash[\"notice\"] = 'Site was successfully created.'\n format.html { redirect_to @site }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @institution = @navigation_context.institution\n return unless authorize_resource(@institution, CREATE_INSTITUTION_SITE)\n @site = @institution.sites.new(site_params(true))\n @sites = check_access(@institution.sites, READ_SITE)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to sites_path, notice: I18n.t('sites.create.success') }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n @site.agent = current_agent\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to site_path(@site), notice: t('.flash_created') }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n @site.created_by = current_user\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, :notice => 'Site was successfully created.' }\n format.json { render :json => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\", :layout=>\"site\" }\n format.json { render :json => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def index\n @sites = Site.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def create\n @subsite = Subsite.new(params[:subsite])\n\n respond_to do |format|\n if @subsite.save\n format.html { redirect_to @subsite, notice: 'Subsite was successfully created.' }\n format.json { render json: @subsite, status: :created, location: @subsite }\n else\n format.html { render action: \"new\" }\n format.json { render json: @subsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to sites_url, flash[:info]=\"Site was successfully created.\" }\n format.js { flash[:info]=\"Site was successfully created.\" }\n format.json { render json: @site, status: :created, location: @site }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(@site, :notice => 'Site was successfully created.') }\n format.json { render :json => @site, :status => :created, :location => @site }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @site.errors, :status => :unprocessable_entity }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n @site.user_id = current_user.id\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n flash[:notice] = \"Site was successfully created.\" if @site.save\n respond_with(@site)\n end",
"def create\n params[:site][:virtualhost] = nil if params[:site][:virtualhost] =~ /^\\s*$/\n @site = current_user.sites.build(params[:site])\n\n respond_to do |format|\n if @site.save\n flash[:notice] = 'Site was successfully created.'\n format.html { redirect_to(@site) }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Xmt::Press::Site.new(site_params)\n respond_to do |format|\n if @site.save\n format.html { redirect_to xmt_press_sites_url, notice: '站点创建成功.' }\n format.json { render :show, status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n respond_to do |format|\n if @site.save\n format.html { redirect_to user_path(@user), notice: 'サイトを作成しました' }\n format.json { render user_path(@user), status: :created, location: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @search_site = SearchSite.new(search_site_params)\n\n respond_to do |format|\n if @search_site.save\n format.html { redirect_to search_sites_url, notice: 'Search site was successfully created.' }\n format.json { render :show, status: :created, location: @search_site }\n else\n format.html { render :new }\n format.json { render json: @search_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @parsed_site = ParsedSite.new(parsed_site_params)\n\n if @parsed_site.save\n render json: @parsed_site, status: :created, location: @parsed_site\n else\n render json: @parsed_site.errors, status: :unprocessable_entity\n end\n end",
"def index\n @sites = fetch_sites\n\n @formattedSites = @sites.map do |site|\n {\n 'title' => {'value' => site.name, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'template' => {'value' => site.site_template&.name, 'searchable' => true, 'sortable' => true},\n 'preview' => {'value' => site.routes.first.host_with_scheme, 'link' => { 'url' => site.routes.first.host_with_scheme, 'external' => true}, 'searchable' => true, 'sortable' => true},\n 'edit' => {'value' => edit_admin_site_site_step_path(site_slug: site.slug, id: :name), 'method' => 'get'},\n 'delete' => {'value' => admin_site_path(slug: site.slug), 'method' => 'delete'}\n }\n end\n\n gon.sites = @formattedSites\n\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites }\n end\n end",
"def index\n respond_to do |format|\n format.html do \n @sites = Site.all\n end\n format.json do\n render json: Site.all\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n @site.user_id = current_user.id\n\n if params[:site][:size_ids].present?\n sizesgroup = Size.find params[:site][:size_ids]\n @site.sizes = sizesgroup\n end\n\n respond_to do |format|\n if @site.save\n format.json { render :index, status: :created, location: @site }\n\t\t#format.json { head :no_content }\n\t\tformat.js\n else\n format.json { render json: @site.errors, status: :unprocessable_entity }\n\t\tformat.js { render 'shared/errors' }\n end\n end\n end",
"def new\n @site = Site.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def create\n @watch_site = WatchSite.new(params[:watch_site])\n\n respond_to do |format|\n if @watch_site.save\n format.html { redirect_to @watch_site, notice: 'Watch site was successfully created.' }\n format.json { render json: @watch_site, status: :created, location: @watch_site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @watch_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @optimized_site = OptimizedSite.new(optimized_site_params)\n\n respond_to do |format|\n if @optimized_site.save\n format.html { redirect_to @optimized_site, notice: 'Optimized site was successfully created.' }\n format.json { render :show, status: :created, location: @optimized_site }\n else\n format.html { render :new }\n format.json { render json: @optimized_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @website = Website.new(website_params)\n\n if @website.save\n render json: @website, status: :created, location: @website\n else\n render json: @website.errors, status: :unprocessable_entity\n end\n end",
"def create\n @site = Site.new\n @site.mode = :off\n @site.status = :off\n respond_to do |format|\n if @site.update(params)\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site }\n else\n format.html { render :new }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_site_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.create_site ...\"\n end\n # resource path\n local_var_path = \"/api/3/sites\"\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;charset=UTF-8'])\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[:'site'])\n auth_names = []\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 => 'ReferenceWithSiteIDLink')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#create_site\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create\n @institution = Institution.find params[:site][:institution_id]\n return unless authorize_resource(@institution, CREATE_INSTITUTION_SITE)\n\n @site = @institution.sites.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to sites_path, notice: 'Site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @body_site = BodySite.new(body_site_params)\n\n respond_to do |format|\n if @body_site.save\n format.html { redirect_to @body_site, notice: 'Body site was successfully created.' }\n format.json { render :show, status: :created, location: @body_site }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @body_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_site_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.create_site ...'\n end\n # resource path\n local_var_path = '/api/3/sites'\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;charset=UTF-8'])\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[:'site'])\n auth_names = []\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 => 'ReferenceWithSiteIDLink')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#create_site\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create\n @study_site = StudySite.new(study_site_params)\n\n respond_to do |format|\n if @study_site.save\n format.html { redirect_to @study_site, notice: 'Study site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @study_site }\n else\n format.html { render action: 'new' }\n format.json { render json: @study_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Cms::Site.new(cms_site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to cms.sites_url, notice: '站点已创建.' }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n set_user\n @sites = Site.all\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @sites.to_json }\n end\n end",
"def create\n @trial_site = TrialSite.new(trial_site_params)\n\n respond_to do |format|\n if @trial_site.save\n format.html { redirect_to @trial_site, notice: 'Trial site was successfully created.' }\n format.json { render :show, status: :created, location: @trial_site }\n else\n format.html { render :new }\n format.json { render json: @trial_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def new\n @site = Site.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def create\n @site = Site.new(params[:site])\n \n # Domain Name\n re='((?:[a-z][a-z\\\\.\\\\d\\\\-]+)\\\\.(?:[a-z][a-z\\\\-]+))(?![\\\\w\\\\.])'\t\n @m=Regexp.new(re,Regexp::IGNORECASE)\n @host = @m.match(@site.linkws)[1] \n @site.host = @host\n \n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @student_site = StudentSite.new(student_site_params)\n\n respond_to do |format|\n if @student_site.save\n format.html { redirect_to @student_site, notice: 'Student site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @student_site }\n else\n format.html { render action: 'new' }\n format.json { render json: @student_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @site = Site.new \n puts \"Got here\"\n #2.times { @site.connections.build }\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @site }\n end\n end",
"def create\n @anatomic_site = AnatomicSite.new(anatomic_site_params)\n\n respond_to do |format|\n if @anatomic_site.save\n format.html { redirect_to @anatomic_site, notice: 'Anatomic site was successfully created.' }\n format.json { render :show, status: :created, location: @anatomic_site }\n else\n format.html { render :new }\n format.json { render json: @anatomic_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n update_and_decorate \n respond_to do |format|\n if !@site.errors.any?\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def site_payload\n {'site' => {'posts' => @posts}}\n end",
"def create\n @server = @site.servers.new(server_params.merge({used_at: (Time.now - 1.day)}))\n\n respond_to do |format|\n if @server.save\n format.html { redirect_to [:admin, @site], notice: 'Server was successfully created.' }\n format.json { render action: 'show', status: :created, location: [:admin, @site] }\n else\n format.html { render action: 'new' }\n format.json { render json: @server.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site_setup = SiteSetup.new(params[:site_setup])\n\n respond_to do |format|\n if @site_setup.save\n format.html { redirect_to @site_setup, notice: 'Site setup was successfully created.' }\n format.json { render json: @site_setup, status: :created, location: @site_setup }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site_setup.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @jobsite = Jobsite.new(jobsite_params)\n\n respond_to do |format|\n if @jobsite.save\n format.html { redirect_to @jobsite, notice: 'Jobsite was successfully created.' }\n format.json { render :show, status: :created, location: @jobsite }\n else\n format.html { render :new }\n format.json { render json: @jobsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site_url = SiteUrl.new(site_url_params)\n\n respond_to do |format|\n if @site_url.save\n format.html { redirect_to @site_url, notice: \"Site url was successfully created.\" }\n format.json { render :show, status: :created, location: @site_url }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @site_url.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @website = websites.new(website_params)\n\n respond_to do |format|\n if @website.save\n flash[:notice] = :success\n format.html { redirect_to @website, notice: 'Website was successfully created.' }\n format.json { render :show, status: :created, location: @website }\n else\n format.html { render :new }\n format.json { render json: @website.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n # @site = Site.new(params[:site])\n\n @site = current_user.sites.build(params[:site])\n # @site.lat = @lat\n # @site.long = @long\n # @site.save\n\n Rails.logger.debug 'User email is ' + @site.user.email.to_s\n Rails.logger.debug 'Site lat is ' + @site.lat.to_s\n Rails.logger.debug 'Site long is ' + @site.long.to_s\n\n # @project = Project.find(params[:project_id])\n # @site = @project.sites.build(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n # format.html { redirect_to project_site_path(@site.project_id, @site),\n # notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { flash.now[:error] = \"Error: See details below.\"\n render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n set_cors_headers\n @site = Site.find(params[:site_id])\n if params[:base_url] == @site.base_url\n @visit = @site.visits.create(:url => params[:url], :duration => params[:duration])\n end\n\n respond_to do |format|\n if @visit.save\n format.html { redirect_to site_visit_path(@site, @visit), notice: 'Visit was successfully created.' }\n format.json { render json: @visit, status: :created, location: @visit }\n else\n format.html { render action: \"new\" }\n format.json { render json: @visit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n @site.user_id = current_user.id if user_signed_in?\n respond_to do |format|\n if @site.save\n url = (user_signed_in?)? current_user_path : @site\n format.html { redirect_to url, notice: 'Site was successfully created.' }\n format.json { render json: @site, status: :created, location: @site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @parsed_sites = ParsedSite.all\n\n render json: @parsed_sites\n end",
"def create\n @jobsite = Jobsite.new(jobsite_params)\n\n respond_to do |format|\n if @jobsite.save\n format.html { redirect_to @jobsite, notice: 'Jobsite was successfully created.' }\n format.json { render action: 'show', status: :created, location: @jobsite }\n else\n format.html { render action: 'new' }\n format.json { render json: @jobsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n do_new_resource\n do_set_attributes(site_params)\n get_project_if_exists\n do_authorize_instance\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to [@project, @site], notice: 'Site was successfully created.' }\n format.json {\n if @project.nil?\n respond_create_success(shallow_site_path(@site))\n else\n respond_create_success(project_site_path(@project, @site))\n end\n }\n else\n format.html { render action: 'new' }\n format.json { respond_change_fail }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(@site) }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @site = Site.find(params[:site_id])\n @visit = Visit.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @visit }\n end\n end",
"def index\n @site = Site.find(params[:site_id])\n @visits = @site.visits\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @visits }\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(root_url, :notice => 'Site was successfully created.') }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(@site, :notice => 'Site was successfully created.') }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(@site, :notice => 'Site was successfully created.') }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(@site, :notice => 'Site was successfully created.') }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @mysite = Mysite.new(mysite_params)\n\n respond_to do |format|\n if @mysite.save\n format.html { redirect_to @mysite, notice: 'Mysite was successfully created.' }\n format.json { render :show, status: :created, location: @mysite }\n else\n format.html { render :new }\n format.json { render json: @mysite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_site(params = {})\n site_name.set params['site_name']\n client_division_site_number.set params['client_division_site_number']\n site_number.set params['site_number']\n address_1.set params['address_1']\n address_2.set params['address_2'] if params['address_2']\n zip_code.set params['zip_code']\n city.set params['city']\n country.select(params['country'], match: :first)\n sleep 2 # Wait for the state to be active #TODO: find a way to remove this sleep ~MD\n state.select(params['state']) unless state.disabled?\n study_env.select(params['study_env'])\n pi_email.set params['pi_email']\n pi_first_name.set(params['pi_first_name'])\n pi_last_name.set(params['pi_last_name'])\n pi_role.select(params['pi_role'])\n add_site_submit.click\n sleep 10 # Wait to create a site\n end",
"def create\n @sitecity = Sitecity.new(params[:sitecity])\n\n respond_to do |format|\n if @sitecity.save\n format.html { redirect_to @sitecity, notice: t(:sitecity_create_success) }\n format.json { render json: @sitecity, status: :created, location: @sitecity }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sitecity.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @sites = current_user.sites.page(params[\"page\"])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def create_site(params={name:random_string})\n\t\tnew_site = site[:new]\n\t\tparams[:site] = params[:name]\n\t\tnew_site[:params].merge!(params)\n\t\tnew_site[:params][:address] = append_ftp_value(new_site[:params][:address],new_site[:params][:ftp_type])\n\t\tpost(new_site)\n\tend",
"def create\n #render text: site_params.merge(user_id: current_user.id) and return\n\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n #build site_page via template_page\n Template::Page.where(template_id: @site.template_id).order(\"sort_id ASC\").each do |temp_page|\n @site.site_pages.create(user_id: current_user.id, \n site_id: @site.id, \n template_page_id: temp_page.id,\n short_title: get_short_title(@site),\n title: temp_page.title)\n end\n format.html { redirect_to edit_site_page_url(@site.site_pages.first), notice: 'Site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @site }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(site_params)\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to(root_url, :notice => 'Site was successfully created.') }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new_site_create(params={})\n study_study_sites.set params[:site_name]\n site_number.set params[:site_number]\n study_site_number.set params[:study_site_number]\n end",
"def create\n @site = Site.new(site_params.reject {|k,v|k==\"trade_items\"})\n respond_to do |format|\n if @site.save\n create_trade_items(@site, site_params[:trade_items])\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n else\n format.html { render action: 'new' }\n end\n end\n end",
"def sites\n request('/web_properties.json').map do |site_data|\n Site.new self, site_data['uid'], site_data['name']\n end\n end",
"def create\n @site = Site.new(site_params)\n\n session[:referral] = @site.referral\n\n respond_to do |format|\n if @site.save\n format.html { redirect_to @site, notice: 'Site was successfully created.' }\n format.json { render action: 'show', status: :created, location: @site }\n elsif Site.exists?(:domain => @site.domain)\n format.html { redirect_to site_path(Site.find_by(:domain => @site.domain)) }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n else\n format.html { render action: 'new' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site_config = SiteConfig.new(site_config_params)\n\n respond_to do |format|\n if @site_config.save\n format.html { redirect_to @site_config, notice: 'Site config was successfully created.' }\n format.json { render json: @site_config, status: :created, location: @site_config }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site_config.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site_page = SitePage.new(site_page_params)\n\n respond_to do |format|\n if @site_page.save\n format.html { redirect_to @site_page, notice: 'Site page was successfully created.' }\n format.json { render action: 'show', status: :created, location: @site_page }\n else\n format.html { render action: 'new' }\n format.json { render json: @site_page.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @site = Site.new(params[:site])\n\n respond_to do |format|\n if @site.save\n flash[:notice] = 'Site was successfully created.'\n format.html { redirect_to(@site) }\n format.xml { render :xml => @site, :status => :created, :location => @site }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @subsite = Subsite.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @subsite }\n end\n end",
"def create\n @siteblog = Siteblog.new(siteblog_params)\n\n respond_to do |format|\n if @siteblog.save\n format.html { redirect_to @siteblog, notice: 'Siteblog was successfully created.' }\n format.json { render :show, status: :created, location: @siteblog }\n else\n format.html { render :new }\n format.json { render json: @siteblog.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @supplysite = Supplysite.new(params[:supplysite])\n\n respond_to do |format|\n if @supplysite.save\n format.html { redirect_to @supplysite, notice: 'Angebotsort wurde erfolgreich angelegt.' }\n format.json { render json: @supplysite, status: :created, location: @supplysite }\n else\n format.html { render action: \"new\" }\n format.json { render json: @supplysite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @produktion_site = ProduktionSite.new(params[:produktion_site])\n\n respond_to do |format|\n if @produktion_site.save\n format.html { redirect_to @produktion_site, notice: 'Produktion site was successfully created.' }\n format.json { render json: @produktion_site, status: :created, location: @produktion_site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @produktion_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @orbituarysite = Orbituarysite.new(params[:orbituarysite])\n\n respond_to do |format|\n if @orbituarysite.save\n format.html { redirect_to @orbituarysite, notice: 'Orbituarysite was successfully created.' }\n format.json { render json: @orbituarysite, status: :created, location: @orbituarysite }\n else\n format.html { render action: \"new\" }\n format.json { render json: @orbituarysite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @sites = Site.paginate(:page=>params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\n end",
"def create\n @site_option = SiteOption.new(site_option_params)\n\n respond_to do |format|\n if @site_option.save\n format.html { redirect_to @site_option, notice: 'Site option was successfully created.' }\n format.json { render :show, status: :created, location: @site_option }\n else\n format.html { render :new }\n format.json { render json: @site_option.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n respond_to do |format|\n format.html { redirect_to controller: \"sites\", action: \"checklists_manager\" }\n format.json { head :no_content }\n end\n end",
"def create\n @site_admin = SiteAdmin.new(site_admin_params)\n\n respond_to do |format|\n if @site_admin.save\n format.html { redirect_to @site_admin, notice: 'Site admin was successfully created.' }\n format.json { render :show, status: :created, location: @site_admin }\n else\n format.html { render :new }\n format.json { render json: @site_admin.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @supplysites = Supplysite.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @supplysites }\n end\n end",
"def create\n\n owner = Owner.first\n @ooh_site = owner.ooh_sites.build(ooh_site_params)\n\n respond_to do |format|\n if @ooh_site.save\n format.html { redirect_to @ooh_site.becomes(OohSite), notice: 'Ooh site was successfully created.' }\n format.json { render :show, status: :created, location: @ooh_site }\n else\n format.html { render :new }\n format.json { render json: @ooh_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @admin_site_structure = Admin::SiteStructure.new(admin_site_structure_params)\n\n respond_to do |format|\n if @admin_site_structure.save\n format.html { redirect_to @admin_site_structure, notice: 'Site structure was successfully created.' }\n format.json { render :show, status: :created, location: @admin_site_structure }\n else\n format.html { render :new }\n format.json { render json: @admin_site_structure.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n\n sites = Site.all\n @sites = current_user.sites\n @needs_attention_reports = Report.needs_attention\n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @sites }\n # end\n\n respond_with(sites) do |format|\n format.html # { redirect_to site_user_sites_path }\n format.json { render :json => @sites.as_json }\n end\n end",
"def create\n @site_mst = SiteMst.new(site_mst_params)\n\n respond_to do |format|\n if @site_mst.save\n format.html { redirect_to @site_mst, notice: 'Site mst was successfully created.' }\n format.json { render :show, status: :created, location: @site_mst }\n else\n format.html { render :new }\n format.json { render json: @site_mst.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @sitio = Sitio.new(params[:sitio])\n\n respond_to do |format|\n if @sitio.save\n format.html { redirect_to @sitio, notice: 'Sitio was successfully created.' }\n format.json { render json: @sitio, status: :created, location: @sitio }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sitio.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.67946297",
"0.66968215",
"0.65516245",
"0.65030956",
"0.64209604",
"0.64209604",
"0.64209604",
"0.6335178",
"0.63177776",
"0.629245",
"0.62879896",
"0.6279627",
"0.6162099",
"0.61234045",
"0.6087425",
"0.6069964",
"0.6069242",
"0.6069242",
"0.6049953",
"0.60482645",
"0.6027714",
"0.6008308",
"0.5946945",
"0.5940789",
"0.5930085",
"0.59128",
"0.5912553",
"0.59026897",
"0.5900038",
"0.58981943",
"0.5886243",
"0.5881018",
"0.587883",
"0.58706814",
"0.58576125",
"0.58551747",
"0.5839119",
"0.5822788",
"0.5821884",
"0.5815708",
"0.5813551",
"0.5795696",
"0.57886434",
"0.5775404",
"0.5771868",
"0.5771868",
"0.5771868",
"0.5771868",
"0.57688767",
"0.5752614",
"0.5725386",
"0.5690916",
"0.5690528",
"0.5685785",
"0.56519794",
"0.56284463",
"0.5627255",
"0.5622927",
"0.56214035",
"0.56127566",
"0.5597449",
"0.5590266",
"0.5572945",
"0.55715895",
"0.5551745",
"0.5521188",
"0.55172145",
"0.55130666",
"0.5510282",
"0.54925954",
"0.54925954",
"0.54925954",
"0.5487893",
"0.54826856",
"0.5474841",
"0.54746145",
"0.54685783",
"0.5464754",
"0.5454374",
"0.5451683",
"0.54361165",
"0.54323626",
"0.5429332",
"0.54042006",
"0.54020476",
"0.54018027",
"0.53984636",
"0.53880304",
"0.5384811",
"0.53819895",
"0.5375863",
"0.5372479",
"0.53648573",
"0.536471",
"0.5360831",
"0.5343178",
"0.5341801",
"0.53391343",
"0.5322269",
"0.5313743",
"0.5305059"
] |
0.0
|
-1
|
PATCH/PUT /sites/1 PATCH/PUT /sites/1.json
|
def update
authorize!(@site)
respond_to do |format|
if @site.update(site_params)
format.html { redirect_to site_site_steps_path(@site), notice: t('notice.site.updated') }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @site.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n @site = current_user.sites.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { flash_and_redirect(\"successfully updated!\", sites_url) }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = current_user.sites.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, :notice => 'Site was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\", :layout=>\"site\"}\n format.json { render :json => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find_by_site(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def put_update(options = {})\n options[:id] ||= @website.id\n options[:website] ||= @attributes\n\n put :update,options\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n redirect_to \"/sites\" and return\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to sites_path, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to sites_url, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html {redirect_to sites_url, flash[:info]='Site was successfully updated.' }\n format.js { flash[:info]='Site was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch!\n request! :patch\n end",
"def update\n @site = Site.find params[:id]\n return unless authorize_resource(@site, UPDATE_SITE)\n\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to sites_path, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\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 respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n respond_to do |format|\n if @site.update(params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { render json: { result: :ok, notice: 'changes saved succesfully', site: @site } }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.json { head :ok }\n format.xml { head :ok }\n else\n format.html { render :action => '#edit' }\n format.json { render :json => @site.errors, :status => :unprocessable_entity }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n if params[:site][:manager_ids]\n format.html { redirect_to sites_url(subdomain: \"www\"), notice: 'Site was successfully updated.' }\n else\n format.html { redirect_to edit_site_url(subdomain: @site.subdomain), notice: 'Site was successfully updated.' }\n end\n format.json { head :no_content }\n format.js\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(id_from_params)\n\n respond_to do |format|\n current_user.account.sites.delete(@site)\n current_user.account.sites << @site\n if current_user.account.sites.exists? @site\n format.html { redirect_to root_path, notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"new\" }\n format.json { render json: @site.errors.errors, status: :unprocessable_entity }\n end\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to site_path(@site), notice: 'Site was successfully updated.' }\n # format.html { redirect_to project_site_path(@site.project, @site), notice: 'Site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { flash.now[:error] = \"Error: See details below.\"\n render action: \"edit\" }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to edit_site_path(@site), notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n if @sitio.update_attributes(params[:sitio])\n format.html { redirect_to @sitio, notice: 'Sitio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sitio.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @subsite = Subsite.find(params[:id])\n\n respond_to do |format|\n if @subsite.update_attributes(params[:subsite])\n format.html { redirect_to @subsite, notice: 'Subsite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @subsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if update_and_decorate\n respond_to do |format|\n format.html { redirect_to @site, notice: 'Site #{@site.name} was successfully updated.' }\n format.json {\n flash[:popup] = \"#{@site.name} updated\"\n render :update\n }\n end\n else\n if @site\n post_resource_errors @site\n else\n flash[:alert] = \"Couldn't fetch site\"\n end\n render :edit, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n format.html { redirect_to controller: \"sites\", action: \"checklists_manager\" }\n format.json { head :no_content }\n end\n end",
"def update\n @watch_site = WatchSite.find(params[:id])\n\n respond_to do |format|\n if @watch_site.update_attributes(params[:watch_site])\n format.html { redirect_to @watch_site, notice: 'Watch site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @watch_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def gu_update_site_from_app\n @app = App.find(params[:app]) rescue nil\n @site = !@app.nil? ? @app.site : nil\n\n respond_to do |format|\n format.html # gu_update_site_from_app.html.erb does not exist! JSON only\n format.json { render json: @site }\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: t('.flash_updated') }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.first\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(root_url, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to xmt_press_sites_url, notice: '站点更新成功.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end",
"def update\n do_load_resource\n get_project_if_exists\n do_authorize_instance\n\n @original_site_name = @site.name\n\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to [@project, @site], notice: 'Site was successfully updated.' }\n format.json { respond_show }\n else\n format.html do\n render action: 'edit'\n end\n format.json { respond_change_fail }\n end\n end\n end",
"def update options={}\n client.put(\"/#{id}\", options)\n end",
"def update(url, data)\n RestClient.put url, data, :content_type => :json\nend",
"def update\n @site_config = SiteConfig.find(params[:id])\n\n respond_to do |format|\n if @site_config.update_attributes(site_config_params)\n format.html { redirect_to @site_config, notice: 'Site config was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site_config.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site_setup = SiteSetup.find(params[:id])\n\n respond_to do |format|\n if @site_setup.update_attributes(params[:site_setup])\n format.html { redirect_to @site_setup, notice: 'Site setup was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @site_setup.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site.user_id = current_user.id\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n render json: Company.update(params[\"id\"], params[\"company\"])\n end",
"def update\n # TODO: see if mass-assigning gleaning_attributes works in Rails 5\n gleanings = params[:site].delete :gleaning_attributes\n if update_and_decorate\n if @site.errors.empty?\n @site.gleaning_attributes = gleanings\n respond_to do |format|\n format.html { redirect_to @site, notice: \"Site #{@site.name} was successfully updated.\" }\n format.json {\n flash[:popup] = \"#{@site.name} updated\"\n render :update\n }\n end\n return\n end\n end\n if @site\n resource_errors_to_flash @site\n else\n flash[:alert] = 'Couldn\\'t fetch site'\n end\n smartrender :action => :edit\n end",
"def update\n respond_to do |format|\n if @jobsite.update(jobsite_params)\n format.html { redirect_to @jobsite, notice: 'Jobsite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @jobsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n flash[:notice] = 'Site was successfully updated.'\n format.html { redirect_to(@site) }\n format.xml { head :ok }\n format.js\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n format.js\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n format.html { redirect_to(@site, :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @anatomic_site.update(anatomic_site_params)\n format.html { redirect_to @anatomic_site, notice: 'Anatomic site was successfully updated.' }\n format.json { render :show, status: :ok, location: @anatomic_site }\n else\n format.html { render :edit }\n format.json { render json: @anatomic_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @study_site.update(study_site_params)\n format.html { redirect_to @study_site, notice: 'Study site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @study_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @student_site.update(student_site_params)\n format.html { redirect_to @student_site, notice: 'Student site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @student_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def put!\n request! :put\n end",
"def update\n respond_to do |format|\n if @mysite.update(mysite_params)\n format.html { redirect_to @mysite, notice: 'Mysite was successfully updated.' }\n format.json { render :show, status: :ok, location: @mysite }\n else\n format.html { render :edit }\n format.json { render json: @mysite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n params[:site][:virtualhost] = nil if params[:site][:virtualhost] =~ /^\\s*$/\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n flash[:notice] = 'Site was successfully updated.'\n format.html { redirect_to(@site) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @stuff = Stuff.find(params[:id])\n\n respond_to do |format|\n if @stuff.update_attributes(params[:stuff])\n format.html { redirect_to @stuff, :notice => 'Stuff was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @stuff.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 respond_to do |format|\n if @site.update(cms_site_params)\n\n format.html { redirect_to cms.sites_url, notice: '站点已修改.' }\n format.json { head :no_content }\n else\n @cms_theme = Cms::Theme.all\n format.html { render action: 'edit' }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end",
"def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end",
"def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end",
"def update!(**args)\n @requests = args[:requests] if args.key?(:requests)\n end",
"def update\n put :update\n end",
"def update\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n if @sitio.update_attributes(params[:sitio])\n format.html { redirect_to(@sitio, :notice => 'Sitio was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @sitio.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update(request)\n end",
"def update(request)\n end",
"def patch(path, opts = {})\n request(:patch, path, opts).body\n end",
"def update\n @go_slim = GoSlim.find(params[:id])\n\n respond_to do |format|\n if @go_slim.update_attributes(params[:go_slim])\n format.html { redirect_to @go_slim, notice: 'Go slim was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @go_slim.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @website = Website.find(params[:id])\n\n if @website.update(website_params)\n head :no_content\n else\n render json: @website.errors, status: :unprocessable_entity\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!(**args)\n @site = args[:site] if args.key?(:site)\n @versioned_data = args[:versioned_data] if args.key?(:versioned_data)\n end",
"def update\r\n respond_to do |format|\r\n if @site_config.update(site_config_params)\r\n format.html { redirect_to action: :index, notice: t('Site config was successfully updated.') }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { render json: @site_config.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n respond_to do |format|\n if @jobsite.update(jobsite_params)\n format.html { redirect_to @jobsite, notice: 'Jobsite was successfully updated.' }\n format.json { render :show, status: :ok, location: @jobsite }\n else\n format.html { render :edit }\n format.json { render json: @jobsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @request = Request.find(params[:id])\n\n if @request.update(params[:request])\n head :no_content\n else\n render json: @request.errors, status: :unprocessable_entity\n end\n end",
"def update\n @site = Site.find(params[:id])\n flash[:notice] = \"Site was successfully updated.\" if @site.update_attributes(params[:site])\n respond_with(@site)\n end",
"def update\n @installation_site = InstallationSite.find(params[:id])\n\n respond_to do |format|\n if @installation_site.update_attributes(params[:installation_site])\n format.html { redirect_to @installation_site, notice: 'Installation site was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @installation_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n keystone.update_tenant({:id=>params[:id],:name=>params[:name],:description=>params[:description],:enabled=>params[:enabled]})\n respond_to do |format|\n format.html { redirect_to tenants_path, :notice => 'Tenant was successfully updated.' }\n format.json { head :ok }\n end\n end",
"def update\n @early_vote_site = EarlyVoteSite.find(params[:id])\n\n respond_to do |format|\n if @early_vote_site.update_attributes(params[:early_vote_site])\n format.html { redirect_to @early_vote_site, notice: 'EarlyVoteSite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @early_vote_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update # PATCH\n raise NotImplementedError\n end",
"def update\n respond_to do |format|\n if @microsite.update(microsite_params)\n format.html { redirect_to @microsite, notice: 'Microsite was successfully updated.' }\n format.json { render action: 'show', status: :ok, location: @microsite }\n else\n format.html { render action: 'edit' }\n format.json { render json: @microsite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to user_path(@user), notice: \"サイト[#{@site.name}]を編集しました\" }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @orbituarysite = Orbituarysite.find(params[:id])\n\n respond_to do |format|\n if @orbituarysite.update_attributes(params[:orbituarysite])\n format.html { redirect_to @orbituarysite, notice: 'Orbituarysite was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @orbituarysite.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n flash[:notice] = 'Site was successfully updated.'\n format.html { redirect_to(@site) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update_attributes(params[:site])\n flash[:notice] = 'Site was successfully updated.'\n format.html { redirect_to(@site) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n puts \"==========\"\n #puts params.require(:site).permit(:name, :url, :description)\n puts params[:url]\n puts params[:name]\n puts \"==========\"\n if @site.update(site_params)\n format.html { redirect_to @site, notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n logger.debug \"debug_update:params=#{params.inspect}\"\n @m_site = MSite.where(id: params[:id].to_i).first\n @m_site.name = params['app_job_offer_name']\n @m_site.password = params['app_password'].nil? ? '' : params['app_password']\n @m_site.no_scraping_flg = params['app_no_scraping_flg']\n #@m_site.recruitment_site_id = params['app_site_id'].nil? ? '' : params['app_site_id']\n @m_site.user_id = params['app_user_id'].nil? ? '' : params['app_user_id']\n @m_site.extra1 = params['extra1'].nil? ? '' : params['extra1']\n @m_site.extra2 = params['extra2'].nil? ? '' : params['extra2']\n @m_site.extra3 = params['extra3'].nil? ? '' : params['extra3'].to_i\n @m_site.enterprise_cnt = params['enterprise_cnt'].nil? ? 0 : params['enterprise_cnt']\n\n respond_to do |format|\n if @m_site.valid? && @error_msg.blank?\n @m_site.save\n format.html { redirect_to '/m_sites', notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @m_site }\n else\n format.html { render :edit }\n format.json { render json: @m_site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end",
"def update\n respond_to do |format|\n if @site.update(site_params)\n format.html { redirect_to after_update_path, notice: 'Site was successfully updated.' }\n format.json { render :show, status: :ok, location: @site }\n else\n format.html { render :edit }\n format.json { render json: @site.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end",
"def update\n @site = Site.find(params[:site_id])\n @visit = Visit.find(params[:id])\n\n respond_to do |format|\n if @visit.update_attributes(params[:visit])\n format.html { redirect_to site_visit_path(@site, @visit), notice: 'Visit was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @visit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update\n @server1 = Server1.find(params[:id])\n\n respond_to do |format|\n if @server1.update_attributes(params[:server1])\n format.html { redirect_to @server1, notice: 'Server was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @server1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @site_option.update(site_option_params)\n format.html { redirect_to @site_option, notice: 'Site option was successfully updated.' }\n format.json { render :show, status: :ok, location: @site_option }\n else\n format.html { render :edit }\n format.json { render json: @site_option.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def update\n #retrieve the site thanks to params[:id]\n @site = Site.find(params[:id])\n\n respond_to do |format|\n if @site.update(site_params)\n #1st argument of redirect_to is an array, in order to build the correct route to the nested resource site\n format.html { redirect_to([@site.customer, @site], :notice => 'Site was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @site.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @supplysite = Supplysite.find(params[:id])\n\n respond_to do |format|\n if @supplysite.update_attributes(params[:supplysite])\n format.html { redirect_to @supplysite, notice: 'Angebotsort wurde erfolgreich aktualisiert.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @supplysite.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
[
"0.66009605",
"0.6526346",
"0.63324624",
"0.6311438",
"0.6302069",
"0.6299964",
"0.6291095",
"0.6290031",
"0.6267976",
"0.62325794",
"0.61879224",
"0.61804986",
"0.6174384",
"0.6156619",
"0.61509115",
"0.6141815",
"0.6141815",
"0.6099228",
"0.6093527",
"0.60913587",
"0.6085397",
"0.6080492",
"0.6032595",
"0.60225767",
"0.5985041",
"0.5985041",
"0.597747",
"0.5930693",
"0.59243315",
"0.5913317",
"0.58996236",
"0.5898527",
"0.589006",
"0.5886424",
"0.58747464",
"0.5861105",
"0.583829",
"0.5833754",
"0.58132136",
"0.58098334",
"0.5806478",
"0.57995826",
"0.5783174",
"0.57824194",
"0.57805485",
"0.57735115",
"0.57693195",
"0.57646424",
"0.57646424",
"0.57646424",
"0.57646424",
"0.575966",
"0.5746942",
"0.57457405",
"0.57417697",
"0.57067287",
"0.570374",
"0.5701368",
"0.57005674",
"0.56974787",
"0.56965053",
"0.56965053",
"0.56965053",
"0.56965053",
"0.5693799",
"0.56936204",
"0.568723",
"0.568723",
"0.5686115",
"0.5682974",
"0.56801254",
"0.567652",
"0.567652",
"0.5674174",
"0.5672085",
"0.56695235",
"0.56651413",
"0.56621176",
"0.5657917",
"0.5650903",
"0.5646482",
"0.56428677",
"0.564191",
"0.5635931",
"0.563422",
"0.56315404",
"0.56315404",
"0.5622536",
"0.56215006",
"0.5619433",
"0.5612066",
"0.5611918",
"0.5605519",
"0.5601955",
"0.5594129",
"0.5591192",
"0.5588015",
"0.5588015",
"0.5586855",
"0.5584929"
] |
0.6248215
|
9
|
DELETE /sites/1 DELETE /sites/1.json
|
def destroy
authorize!(@site)
@site.destroy
respond_to do |format|
format.html { redirect_to sites_url }
format.json { head :no_content }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = current_user.sites.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { flash_and_redirect(\"successfully deleted\", sites_url) }\n format.json { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @site = Site.find(id_from_params)\n\n respond_to do |format|\n if current_user.account.sites.delete(@site)\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.json { head :ok }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find_by_site(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = current_user.sites.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_url, :notice => t('sites.destroy.completed') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_path, notice: 'Site was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n format.json { head :ok }\n end\n end",
"def destroy\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n return unless authorize_resource(@site, DELETE_SITE)\n\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_path, notice: I18n.t('sites.destroy.success') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @subsite = Subsite.find(params[:id])\n @subsite.destroy\n\n respond_to do |format|\n format.html { redirect_to subsites_url }\n format.json { head :no_content }\n end\n end",
"def delete\n delete_from_server single_url\n end",
"def destroy\n @study_site.destroy\n respond_to do |format|\n format.html { redirect_to study_sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @anatomic_site.destroy\n respond_to do |format|\n format.html { redirect_to anatomic_sites_url, notice: 'Anatomic site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site_url.destroy\n respond_to do |format|\n format.html { redirect_to site_urls_url, notice: \"Site url was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @orbituarysite = Orbituarysite.find(params[:id])\n @orbituarysite.destroy\n\n respond_to do |format|\n format.html { redirect_to root_url }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site = Site.find params[:id]\n return unless authorize_resource(@site, DELETE_SITE)\n\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to sites_path, notice: 'Site was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:site_id])\n @visit = Visit.find(params[:id])\n @visit.destroy\n\n respond_to do |format|\n format.html { redirect_to site_visits_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mysite.destroy\n respond_to do |format|\n format.html { redirect_to mysites_url, notice: 'Mysite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @watch_site = WatchSite.find(params[:id])\n @watch_site.destroy\n\n respond_to do |format|\n format.html { redirect_to watch_sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ooh_site.destroy\n respond_to do |format|\n format.html { redirect_to ooh_sites_url, notice: 'Ooh site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to xmt_press_sites_url, notice: '站点删除成功.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n #m_@site.destroy\n m_site = MSite.find(params[:id].to_i)\n m_site.del_flg = 1\n m_site.save\n\n respond_to do |format|\n format.html { redirect_to '/m_sites', notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def remove\n @site = Site.find(params[:id])\n @study.sites.delete(@site)\n\n respond_to do |format|\n format.xml { head :ok }\n format.js\n end\n end",
"def destroy\n @student_site.destroy\n respond_to do |format|\n format.html { redirect_to student_sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @jobsite.destroy\n respond_to do |format|\n format.html { redirect_to jobsites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @supplysite = Supplysite.find(params[:id])\n @supplysite.destroy\n\n respond_to do |format|\n format.html { redirect_to supplysites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n\n respond_to do |format|\n format.html { redirect_to(sites_url) }\n format.xml { head :ok }\n format.js\n end\n end",
"def destroy\n @optimized_site.destroy\n respond_to do |format|\n format.html { redirect_to optimized_sites_url, notice: 'Optimized site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site = Site.find(params[:id])\n @site.destroy\n \n @sites = Site.search(params[:search]).order(sort_column + \" \" + sort_direction).paginate(:page => params[:page], :per_page => 10)\n\n respond_to do |format|\n format.html { redirect_to sites_url, flash[:info]='Site was successfully deleted.' }\n format.js { flash[:info]='Site was successfully deleted.' }\n format.json { head :ok }\n end\n end",
"def destroy\n @site_config = SiteConfig.find(params[:id])\n @site_config.destroy\n\n respond_to do |format|\n format.html { redirect_to site_configs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @sitecity = Sitecity.find_by_url(params[:id])\n @sitecity.destroy\n\n respond_to do |format|\n format.html { redirect_to sitecities_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site_setup = SiteSetup.find(params[:id])\n @site_setup.destroy\n\n respond_to do |format|\n format.html { redirect_to site_setups_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @server.destroy\n respond_to do |format|\n format.html { redirect_to [:admin, @site] }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to after_destroy_path, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n # return if need_login true, true\n @site = Site.find params[:id]\n @site.destroy\n respond_to do |format|\n format.html { redirect_to sites_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @trial_site.destroy\n respond_to do |format|\n format.html { redirect_to trial_sites_url, notice: 'Trial site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n # retrieve the site thanks to params[:id]\n @site = Site.find(params[:id])\n @site.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 @microsite.destroy\n respond_to do |format|\n format.html { redirect_to microsites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n\t format.js { redirect_to sites_url }\n format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site.destroy\n respond_to do |format|\n format.html { redirect_to user_path(@user), notice: \"サイト[#{@site.name}]を削除しました\" }\n format.json { head :no_content }\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 @installation_site = InstallationSite.find(params[:id])\n @installation_site.destroy\n\n respond_to do |format|\n format.html { redirect_to installation_sites_url }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(url)\n @deleted = true\nend",
"def destroy\n @sitio = Sitio.find(params[:id])\n @sitio.destroy\n\n respond_to do |format|\n format.html { redirect_to sitios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @early_vote_site = EarlyVoteSite.find(params[:id])\n @early_vote_site.destroy\n\n respond_to do |format|\n format.html { redirect_to early_vote_sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @site_type = SiteType.find(params[:id])\n @site_type.destroy\n\n respond_to do |format|\n format.html { redirect_to site_types_url }\n format.json { head :no_content }\n end\n end",
"def delete\n api_client.delete(url)\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def destroy\n if @site.columns.size > 0\n flash[:error] = \"该站点存在多个栏目,不能删除\"\n else\n delete_file(@site.logo_file) if !@site.logo_file.blank?\n @site.destroy\n end\n\n respond_to do |format|\n format.html { redirect_to cms.sites_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @campsite.destroy\n respond_to do |format|\n format.html { redirect_to campsites_url, notice: \"Campsite was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @body_site.destroy\n respond_to do |format|\n format.html { redirect_to body_sites_url, notice: 'Body site 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\r\n site = @billing_site.site_id\r\n @billing_site.destroy\r\n respond_to do |format|\r\n # format.html { redirect_to billing_sites_url, notice: 'Billing site was successfully destroyed.' }\r\n format.html { redirect_to site_path(site), notice: 'Billing site was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end",
"def delete(connection)\n r = connection.execute(%(<SiteDeleteRequest session-id=\"#{connection.session_id}\" site-id=\"#{@id}\"/>))\n r.success\n end",
"def destroy\n @recycling_site = RecyclingSite.find(params[:id])\n @recycling_site.destroy\n\n respond_to do |format|\n format.html { redirect_to(recycling_sites_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @site_admin.destroy\n respond_to do |format|\n format.html { redirect_to site_admins_url, notice: 'Site admin was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @jobsite.destroy\n respond_to do |format|\n format.html { redirect_to jobsites_url, notice: 'Jobsite was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @website.destroy\n respond_to do |format|\n format.html { redirect_to websites_url, notice: 'Website was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(url)\n @deleted = true\n end",
"def delete(url)\n do_request(\"delete\", url)\n end",
"def destroy\n @selector_site = SelectorSite.find(params[:id])\n @selector_site.destroy\n\n respond_to do |format|\n format.html { redirect_to(selector_sites_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end",
"def destroy\n @admin_site_structure.destroy\n respond_to do |format|\n format.html { redirect_to admin_site_structures_url, notice: 'Site structure 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"
] |
[
"0.7356214",
"0.73258954",
"0.73258954",
"0.73258954",
"0.73258954",
"0.73258954",
"0.7317765",
"0.7289903",
"0.7289903",
"0.7289903",
"0.7289903",
"0.7289903",
"0.7289426",
"0.7267864",
"0.72534925",
"0.7246142",
"0.7225299",
"0.7222419",
"0.7191969",
"0.71299064",
"0.7100792",
"0.70838326",
"0.7065907",
"0.7065907",
"0.7065907",
"0.7065907",
"0.7065907",
"0.7065907",
"0.7065907",
"0.7025962",
"0.70216537",
"0.7006504",
"0.7006301",
"0.7002543",
"0.699657",
"0.6965492",
"0.6926902",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913184",
"0.6913068",
"0.6903164",
"0.6899006",
"0.68953234",
"0.6882028",
"0.68651164",
"0.6832747",
"0.6825529",
"0.6822853",
"0.6802334",
"0.675928",
"0.67562425",
"0.6754108",
"0.6749305",
"0.674523",
"0.6739229",
"0.67299837",
"0.67272466",
"0.66961074",
"0.6695226",
"0.6688247",
"0.6683663",
"0.6678659",
"0.66694427",
"0.66599226",
"0.665544",
"0.66542155",
"0.66483957",
"0.66401356",
"0.66363305",
"0.6604698",
"0.65990657",
"0.6595917",
"0.6589366",
"0.6577293",
"0.6572963",
"0.6571994",
"0.6565129",
"0.6554944",
"0.655231",
"0.6549458",
"0.65483844",
"0.653786",
"0.653786",
"0.653786",
"0.653786",
"0.6532605",
"0.6524095",
"0.65160686",
"0.65146583",
"0.6514247",
"0.65117556",
"0.65117556",
"0.65117556",
"0.65117556"
] |
0.7050253
|
29
|
Use callbacks to share common setup or constraints between actions.
|
def set_site
@site = Site.find_by(id: params[:id])
#for preview/themes/set_theme
@site ||= Site.find_by(id: params[:site_id])
not_found if @site.nil?
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
|
Never trust parameters from the scary internet, only allow the white list through.
|
def site_params
params.require(:site).permit(:user_id, :member_id, :template_id, :short_title, :title, :description, :domain, :is_publiched, :is_comment_show, :updated_by, :note, :typo)
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
|
expired, we used QRcode API to generate qrcode
|
def generate_qrcode_bak(page)
url = get_site_url(page)
return if url.blank?
qr = RQRCode::QRCode.new( url, :size => 6, :level => :h )
png = qr.to_img # returns an instance of ChunkyPNG
qr_dir = File.join(Rails.root, 'public', 'qrcode')
FileUtils.mkdir_p qr_dir
png_path = File.join(qr_dir, "#{page.id}.png")
if File.exist? png_path
#FileUtils.rm png_path
else
png.resize(120, 120).save(png_path)
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fetch_qr_code\n self.qr_code = QrCodeFetcher.qr_code(code)\n end",
"def qrcode\n @qr = RQRCode::QRCode.new(\"http://0.0.0.0:3000/visit/#{self.tag}\", :size => 6)\n return @qr\n end",
"def create_qrcode\n\t\t@qr = RQRCode::QRCode.new( qr_code_params[:text], size: 4)\n\t\tbyebug \n\tend",
"def qr!\n qr_private(true)\n end",
"def intend_qrcode\n data = params[:customer_token]\n customer = Customer.find_by_authentication_token(data)\n\n #on imprime le qrcode\n customer.print_qrcode\n\n #on recupere le chemin du qrcode\n @path = customer.qrcode_path\n rescue => e\n render json:{\n message: \"Impossible de trouver cet utilisateur : #{e}\"\n }\n end",
"def qrcode\n\n #integration de la gestion des erreurs 1.0\n # Il est important de noter que chaque transaction de QRCODE generé par le telephone\n # contient une clé unique, cela permet a quelqu'un qui a deja payé cette transaction via\n # ce QRCODE ne le repaye pas par erreur\n # Add new params\n # qr_id \t= params[:qrid]\n # TODO Update and add qrid to qrcode mobile app and add token header key\n\n begin\n\n data = Base64.strict_decode64(params[:data]).split(\"#\")\n\n #recheche du payeur\n payeur_data = data[0]\n\n #information du marchand\n marchand_data = data[1]\n\n #extraction des informations du payeur\n payeur = payeur_data.split(\"@\")\n\n @payeur = Customer.find_by_authentication_token(payeur[0])\n if @payeur.blank?\n puts \"Impossible de trouver ce customer\"\n render json: {\n status: 404,\n flag: :customer_not_found,\n message: \"Impossible de trouver cet utilisateur\"\n }\n else\n Rails::logger::info \"Recherche des informations sur le marchand\"\n marchand = marchand_data.split(\"@\")\n @marchand = Customer.find_by_authentication_token(marchand[0])\n if @marchand.blank?\n render json: {\n status: 404,\n flag: :customer_not_found,\n message: \"Ce marchand est inconnu.\"\n }\n else\n Rails::logger::info \"#{marchand[4]} ++ #{marchand[1]} ++ #{marchand[0]}\"\n render json: {\n message: true,\n context: marchand[4],\n name: @marchand.name,\n second_name: @marchand.second_name,\n amount: marchand[1],\n marchand_id: @marchand.authentication_token, #q.id,\n date: Time.now.strftime(\"%d-%m-%Y à %H:%M:%S\"),\n expire: 5.minutes.from_now #.strftime(\"%T\")\n }\n end\n end\n\n rescue ArgumentError => e\n\n render json: {\n message: false,\n content: \"Impossible de lire ce Qr Code : #{e}\"\n }\n\n\n end\n\n end",
"def create_qrcode\n\n end",
"def qr_code\n @patient = Patient.find(params[:id])\n @record_url = vacc_rec_patient_url(@patient)\n @qr = RQRCode::QRCode.new(@record_url, size: 10, level: :h)\n @png = @qr.as_png(\n bit_depth: 1,\n border_modules: 4,\n color_mode: ChunkyPNG::COLOR_GRAYSCALE,\n color: 'black',\n file: nil,\n fill: 'white',\n module_px_size: 6,\n resize_exactly_to: false,\n resize_gte_to: false,\n size: 400\n )\n end",
"def generateQRCode\n id = params[:id]\n\n #on recherche l'enregistrement correspondant\n query = Qrmodel.find(id)\n query_string = query.to_s\n\n #on commence le processus de rendu du qrcode\n qrcode = RQRCode::QRCode.new(query_string)\n qrmodel.qrcode.attach(\n qrcode.as_png(\n resize_gte_to: false,\n resize_exactly_to: false,\n fill: 'white',\n color: 'black',\n size: 360,\n border_modules: 4,\n module_px_size: 6,\n file: Rails.root.join(\"tmp/#{SecureRandom.hex(2).parameterize}.png\")\n )\n )\n\n end",
"def qrgen\n end",
"def upcoming_appointment_qrcode\n @patient = Patient.first\n upcoming_appointment = @patient.upcoming_appointment\n if upcoming_appointment\n url = \"https://www.mdme.us/clinics/#{upcoming_appointment.checkin_key}/checkin\"\n @qrcode = RQRCode::QRCode.new(url)\n respond_to do |format|\n format.png { send_data @qrcode.as_png(color: '#0097A7', size: 800), disposition: 'inline' }\n end\n end\n end",
"def qr_code_png\n data.qr_code_png\n end",
"def gen_qr_code data\r\n begin\r\n # Form query\r\n query = \"#{URL}#{QUERY}#{data}\"\r\n # Write file to output path\r\n File.open(QR_OUTPUT_PATH, \"wb\") do |file| \r\n file.write HTTParty.get(URI.escape query).parsed_response\r\n end\r\n # Update UI\r\n @qr_img_label.set_pixmap(Qt::Pixmap.new(QR_OUTPUT_PATH))\r\n @qr_data_label.set_text(data)\r\n rescue => e\r\n puts e.inspect\r\n title = \"QR Error\"\r\n error = \"Error: \\\"#{data}\\\" could not be rendered as QR Code!\"\r\n build_message_box(title, error)\r\n end\r\n end",
"def generate()\n @qrcode = @qr_generator.new(@url)\n @png = @qrcode.as_png(\n size: @size,\n border_modules: DEFAULT_BORDER_MODULES\n )\n end",
"def qr\n require 'rqrcode'\n str = params[:str] || \"\"\n\n qr = RQRCode::QRCode.new(str)\n\n qr_img_stream = qr.as_png(\n border_modules: 2,\n color: \"24292e\"\n ).to_s\n\n send_data(qr_img_stream, type: 'image/png', disposition: 'inline')\n end",
"def wechat_qrcode_url\n cache_key = \"wechat:qrcode:channel:#{id}\"\n if company.wechat_app && company.wechat_app.state.enabled?\n Rails.cache.fetch(cache_key) do\n scene = Wechat::Reducer.scan_scene(Wechat::Reducer::CHANNEL_SCAN, id)\n Wechat::Mp::Qrcode.generate(company.wechat_app.app_id, scene)\n end\n end\n rescue Wechat::Error::Unauthenticated\n nil\n end",
"def qrcode\n \"#{self.short_url}.qrcode\"\n end",
"def fetch_qr\n qrcode = RQRCode::QRCode.new(current_user.provisioning_uri, size: 10, level: :h )\n png = qrcode.as_png(bit_depth: 1, border_modules: 4, color_mode: ChunkyPNG::COLOR_GRAYSCALE, color: 'black', file: nil, fill: 'white', module_px_size: 6, resize_exactly_to: false, resize_gte_to: false)\n user_id = current_user.id\n image_path = Rails.root.join(\"public/#{user_id}.png\")\n File.open(image_path, 'wb'){|image_file| image_file.write png }\n image = Cloudinary::Uploader.upload(image_path)\n File.delete(\"./public/#{user_id}.png\")\n qrcode = image.as_json(only: [\"public_id\", \"url\"])\n render json: {status: 200, message: \"QR fetched\", qr: qrcode}\n end",
"def show\n @url = \"https://www.karmagrove.com/events/#{@event.id}/tickets/#{@ticket_purchase.ticket.id}/ticket_purchases/#{@ticket_purchase.id}\"\n @qr = RQRCode::QRCode.new( @url, :size => 7, :level => :h )\n end",
"def generate_forever_qrcode(scene_id)\n _generate_qrcode(scene_id, 'QR_LIMIT_SCENE')\n end",
"def generate_temporary_qrcode(scene_id)\n _generate_qrcode(scene_id, 'QR_SCENE')\n end",
"def show\n @geocach = Geocach.find(params[:id])\n qr_code = \"#{ENV['URL']}#{@geocach.random_code}\"\n @qr = RQRCode::QRCode.new( qr_code.to_s , :size => 10, :level => :h )\n\n \n @qr_code = \"#{ENV['URL']}#{@geocach.random_code}\"\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @geocach }\n format.png { render :qrcode => qr_code, :size => 10, :level => :h }\n format.gif { render :qrcode => qr_code, :size => 10, :level => :h }\n format.jpeg { render :qrcode => qr_code, :size => 10, :level => :h }\n end\n end",
"def create\n @qrcode = Qrcode.new(params[:qrcode])\n\n respond_to do |format|\n if @qrcode.save\n format.html { redirect_to action: :index, notice: 'Qrcode was successfully created.' }\n format.json { render json: @qrcode, status: :created, location: @qrcode }\n else\n format.html { render action: \"new\" }\n format.json { render json: @qrcode.errors, status: :unprocessable_entity }\n end\n end\n end",
"def rqrcode\n RQRCode::QRCode.new(data, :level => level, :size => size)\n end",
"def set_hand\n # La forme la plus avancée de génération du QR code\n # \"#{self.authentication_token}@amount@lat@long@context\"\n hand = \"#{self.authentication_token}@0000@0.0@0.0@plateform@#{Time.now}\"\n self.hand = Base64.strict_encode64(hand) #.delete(\"\\n\")\n end",
"def create\n @qr_code = QrCode.new(params[:qr_code])\n\n respond_to do |format|\n if @qr_code.save\n format.html { redirect_to(@qr_code, :notice => 'Qr code was successfully created.') }\n format.xml { render :xml => @qr_code, :status => :created, :location => @qr_code }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @qr_code.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def print_my_qrcode\n require 'rqrcode'\n\n qrcode = RQRCode::QRCode.new(\"http://api.paiemequick.com/u/p/#{self.authentication_token}/\")\n\n # NOTE: showing with default options specified explicitly\n svg = qrcode.as_svg(\n offset: 5,\n color: '000',\n shape_rendering: 'crispEdges',\n module_size: 6,\n standalone: true\n )\n\n # save SVG file to folder\n File.open(\"app/assets/images/#{self.phone}\", \"w\") do |line|\n line.puts svg\n end\n end",
"def barcode_exists?(barcode)\n\t\tcurrent_time = Time.now.to_i\n\t\tif current_time > self.expires_at\n\t\t\tself.connection = RestFirebase.new :site => SITE_URL,\n :secret => SECRET, :auth =>generate_access_token\n\t\tend\n\t\t\tself.connection.get(ENDPOINT, :orderBy => 'barcode', :equalTo => barcode)\n\tend",
"def show\n require 'rqrcode'\n require 'rqrcode_png'\n require 'chunky_png' # to_data_urlはchunky_pngのメソッド\n\n content = 'Hello World'\n size = 3 # 1..40\n level = :h # l, m, q, h\n\n qr = RQRCode::QRCode.new(content, size: size, level: level)\n # png変換->リサイズ->base64エンコード\n @qr_base64 = qr.to_img.resize(200, 200).to_data_url\n end",
"def generate_rucaptcha\n generate_rucaptcha_session_id\n\n res = RuCaptcha.generate\n session_val = {\n code: res[0],\n time: Time.now.to_i\n }\n RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in)\n res[1]\n end",
"def initialize(content)\n @qrcode = QRCode.generate_qrcode(content)\n end",
"def create\n @qrcode = Qrcode.new(params[:qrcode])\n @qrcode.userid = current_user.id\n\n respond_to do |format|\n if @qrcode.save\n format.html { redirect_to @qrcode, notice: 'Qrcode was successfully created.' }\n format.json { render json: @qrcode, status: :created, location: @qrcode }\n else\n format.html { render action: \"new\" }\n format.json { render json: @qrcode.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @qr = Qr.new(qr_params)\n\n respond_to do |format|\n if @qr.save\n format.html { redirect_to @qr, notice: 'Qr was successfully created.' }\n format.json { render :show, status: :created, location: @qr }\n else\n format.html { render :new }\n format.json { render json: @qr.errors, status: :unprocessable_entity }\n end\n end\n end",
"def render_qr_code(qr_code, **options)\n renderer = Renderer.new(qr_code, **options)\n renderer.render(self)\n end",
"def new\n @qrcode = Qrcode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @qrcode }\n end\n end",
"def get_two_factor_secret_qr_code(size = 9, level = :h)\n secret = self.two_factor_secret\n if secret\n totp = ROTP::TOTP.new(secret)\n raw_string = totp.provisioning_uri(\"RailsApp #{self.email}\")\n # at the default size of 9, we can accomodate ~ 100 8 bit characters\n return nil if raw_string.length >= 100\n RQRCode::QRCode.new(raw_string, :size => size, :level => level)\n end\n end",
"def generate_code\n loop do\n self.code = SecureRandom.urlsafe_base64(40)\n break if valid?\n end\n end",
"def send_qrcode_generated(parking)\n \t@parking = parking\n mail( :to => 'saketkumarjaiswal@gmail.com',\n :subject => 'New QR code is generated' )\n end",
"def create\n @check_in_out = CheckInOut.new(check_in_out_params)\n\n qrcode = RQRCode::QRCode.new(@check_in_out.check_in_no.to_s)\n # With default options specified explicitly\n png = qrcode.as_png(\n resize_gte_to: false,\n resize_exactly_to: false,\n fill: 'white',\n color: 'black',\n size: 120,\n border_modules: 4,\n module_px_size: 6,\n file: './app/assets/images/Check_in_out_QrCode/'+@check_in_out.check_in_no.to_s+'.png' # path to write\n )\n\n respond_to do |format|\n if @check_in_out.save\n\n NewCheckInMailer.notify_check_in(@check_in_out).deliver\n\n format.html { redirect_to check_in_outs_path, notice: 'Check in out was successfully created.' }\n format.json { render :show, status: :created, location: @check_in_out }\n else\n format.html { render :new }\n format.json { render json: @check_in_out.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_qr\n @qr = Qr.find(params[:id])\n end",
"def show\n @qrcode = Qrcode.find(params[:id])\n params[:quest_id]\n if @qrcode.imgloc == nil\n @qrcode.imgloc = request.protocol+request.host_with_port+request.fullpath+\".png\"\n @qrcode.save\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @qrcode }\n format.png { render :qrcode => @qrcode.ref }\n end\n end",
"def signed_qrcode_url( key, ttl=nil )\n return if key.blank?\n signed_url( QRCODE_PATH % key, ttl )\n end",
"def destroy\n @qrcode = Qrcode.find(params[:id])\n @qrcode.destroy\n\n respond_to do |format|\n format.html { redirect_to qrcodes_url }\n format.json { head :no_content }\n end\n end",
"def generate_qrcode_matrix(qrstring)\n\n\t\tqrcode_matrix = RQRCode::QRCode.new(qrstring, :level => :h )\n\n\t\tif @config[:debug] # debugging\n\t\t\tdebug_image_name = \"../testdata/qr_code_image_before_modification.png\" \n\t\t\tqr_code_image = self.generate_qr_code_image(qrcode_matrix)\n\t\t\tqr_code_image.write(debug_image_name)\n\t\t\tputs \"Writing debug image: #{debug_image_name}\" \n\t\tend\n\n\t\treturn qrcode_matrix\n\n\tend",
"def create_verify_code\n #session[:sms] = @sms.tap{|sms| sms.send_at = DateTime.current}\n #render :stub_create_verify_code\n #return\n #if verify_rucaptcha?\n @captcha = true\n less_than_one_minute = false\n if session[:sms]\n last_send_time = Time.parse(session[:sms]['send_at'])\n send_duration = Time.now - last_send_time\n less_than_one_minute = send_duration <= 60\n end\n if less_than_one_minute\n @sms.errors.add(:validate_code, \"验证码每分钟只能发送一次\")\n else\n # validate phone number\n if @sms.valid?\n # send successfully\n if @sms.send_for_sign_up\n session[:sms] = @sms\n end\n end\n end\n #else\n # @captcha = false\n #end\n end",
"def create\n @identity = Identity.new(identity_params)\n @identity['uuid'] = UUIDTools::UUID.random_create\n @identity['token'] = UnixCrypt::SHA256.build(@identity['token'])\n respond_to do |format|\n if @identity.save\n qrcode_content = \"http://3.128.155.87:3003/identities/s/\" + @identity.uuid\n qrcode = RQRCode::QRCode.new(qrcode_content, level: :m, size: 5)\n code = qrcode.as_svg(\n offset: 0,\n color: '000',\n shape_rendering: 'crispEdges',\n module_size: 11,\n standalone: true\n )\n IO.binwrite('app/assets/images/' + @identity.uuid+ '.svg', code.to_s ) \n url = \"/identities/s/\"+@identity['uuid']\n format.html { redirect_to url, notice: \"Identity was successfully created.\" }\n format.json { render :show, status: :created, location: @identity }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @identity.errors, status: :unprocessable_entity }\n end\n end\n end",
"def valid?\n !qrcode.nil?\n end",
"def url_for_rbgk(barcode)\r\n \"http://apps.kew.org/herbcat/getImage.do?imageBarcode=\" + barcode\r\nend",
"def show\n url = \"https://www.mdme.us/clinics/#{@clinic.slug}/checkin\"\n @qr = RQRCode::QRCode.new(url, size: 6)\n end",
"def generate_qr_code_image(qrcode_matrix)\n\n\t\tsquare_width = @config[:square_size_px]\n\t\tsquare_height = @config[:square_size_px]\n\n\t\timage_width = qrcode_matrix.module_count * square_width\n\t\timage_height = image_width\n\n\t\t# Create a completely transparent image as a starting point\n\t\tqr_code_img = Image.new(image_width,image_height) { self.background_color = \"transparent\" }\n\n\t\t# Loop over every QR code square\n\t\tqrcode_matrix.modules.each_index do |row| \n\t\t\tqrcode_matrix.modules.each_index do |col| \n\n\t\t\t\t# create the black or white square image\n\t\t\t\tif qrcode_matrix.dark?(row,col)\n\t\t\t\t\tbgcolor = self.get_dark_square_color(row,col)\n\t\t\t\telse\n\t\t\t\t\tbgcolor = \"white\"\t\t\t\t\t\n\t\t\t\tend\n\t\t\t\tsquare_img = Image.new(square_width,square_height) { self.background_color = bgcolor }\n\t\t\t\tsquare_img_pixels = square_img.get_pixels(0,0,square_width,square_height)\n\n\t\t\t\t# draw the square into the qr_code_img result\n\t\t\t\ty = row * square_height \n\t\t\t\tx = col * square_width\n\t\t\t\tqr_code_img.store_pixels(x,y,square_width,square_height,square_img_pixels)\n\n\t\t\tend\n\t\tend\n\n\t\tif @config[:debug] # debugging\n\t\t\tdebug_image_name = \"../testdata/qr_code_image_before_overlay.png\" \n\t\t\tqr_code_img.write(debug_image_name)\n\t\t\tputs \"Writing debug image: #{debug_image_name}\" \n\t\tend\n\n\t\treturn qr_code_img\n\n\tend",
"def expired?; end",
"def voucher_has_qr_code?\n voucher_has_qr_code\n end",
"def generate_code\n if Admin.authenticate(session[:admin_name], admin_params[:conf_pass_for_gen_code])\n begin\n code= SecureRandom.base64\n c=Code.find_by(:code => code)\n end while c!=nil\n calcultion=Calculation.first\n cc=Code.create!(:code => code, :date_released => Time.now, :expired_date => (Date.today+3.month),\n :value => calcultion.code_value, :valid => true, :verify => true, :admin_id => current_admin.id)\n @unused_codes = Code.where(\"admin_id=? and valid ='t'\", current_admin.id);\n @used_codes = Code.where(\"admin_id=? and valid ='f'\", current_admin.id);\n\n respond_to do |format|\n format.html\n format.js\n format.json\n end\n return\n else\n\n @unused_codes = Code.where(\"admin_id=? and valid ='t'\", current_admin.id);\n @used_codes = Code.where(\"admin_id=? and valid ='f'\", current_admin.id);\n flash.now[:error] = \"Please, enter a valid password\"\n respond_to do |format|\n format.html\n format.js\n format.json\n end\n return\n end\n #render 'codes'\n # redirect_to admin_codes_path\n end",
"def new\n @qrcode = Qrcode.new\n @quests= Quest.find_all_by_userid(current_user)\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @qrcode }\n end\n end",
"def qr_responses\n hashed_qr[appt_id]\n end",
"def show\n if @mobilesetting.uuid.blank?\n @mobilesetting.uuid = SecureRandom.hex(16)\n @mobilesetting.save\n end\n @t = {}\n @t['secret'] = @mobilesetting.securephrase\n @t['uuid'] = @mobilesetting.uuid\n @qrcode = RQRCode::QRCode.new(@t.to_json)\n end",
"def show\n @qrcode = RQRCode::QRCode.new(url_for(@service.lineup))\n @svg = @qrcode.as_svg(\n color: \"000\",\n shape_rendering: \"crispEdges\",\n module_size: 7,\n standalone: true,\n use_path: true\n )\n @pulll = \"ksksksksks\"\n end",
"def qr_data\n @qr_data ||= opts[:questionnaire_response]&.questionnaire_response_data\n end",
"def create\n @bar_code = BarCode.new(bar_code_params)\n gen = Barby::Code128B.new(@bar_code.text)\n send_data gen.to_png(:height => 50), :type => \"image/png\", :disposition => \"inline\"\n\n @bar_code.save\n\n\n\n end",
"def issn\n generate_barcode('barcode.issn')\n end",
"def refill(ccvcode, amount)\n result = @driver.RefillNow(:ApiKey => @apikey, :CreditCardCode => ccvcode, :Amount => amount)\n return result.refillNowResult.refillNow\n end",
"def random_code\n require 'securerandom'\n # Generate a secure random code\n randomize = SecureRandom.hex(16)\n # Store code generated on barcode_128 in string format\n @barcode_128 = randomize.to_s.downcase\n return @barcode_128\n end",
"def customQRcode(inputStr) \n qrcode = RQRCode::QRCode.new(inputStr).as_png(fill: 'white', color: 'black', file: 'abc.png')\n avatar = ChunkyPNG::Image.from_file('abc.png')\n\n # alogo.png being the logo file\n badge = ChunkyPNG::Image.from_file('alogo.png')\n\n print(\"height of backgound:\")\n print(avatar.height)\n print(\"height of logo:\")\n print(badge.height)\n\n #Alpha Blending\n avatar.compose!(badge, avatar.height/2 - badge.height/2, avatar.height/2 - badge.height/2)\n avatar.save('composited.png', :fast_rgba)\nend",
"def destroy\n #@qrcode = Qrcode.find(params[:id])\n #@qrcode.destroy\nQrcode.destroy(Qrcode.find(params[:id]))\n\n respond_to do |format|\n\t format.html #\n format.json { head :no_content }\n end\n end",
"def get_qr_code_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: Class1InstanceApi.get_qr_code ...'\n end\n # resource path\n local_var_path = '/qr_code'\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(['image/png'])\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] || 'File'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['instanceId', 'token']\n\n new_options = opts.merge(\n :operation => :\"Class1InstanceApi.get_qr_code\",\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: Class1InstanceApi#get_qr_code\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def valid_rc\n rcap = RingCaptcha::RingCaptcha.new(ENV['RING_CAPTCHA_APP_KEY'], ENV['RING_CAPTCHA_SECRET_KEY'])\n\n @validation = rcap.validate_pin_code(params[:pin_code], params[:token])\n\n pp @validation\n\n render json: @validation\n end",
"def create\n @good = Good.new(good_params)\n\n respond_to do |format|\n if @good.save\n #生成二维码\n url = Const::GOODS_SHOW_ADDR+'/admin/goods/'+@good.id.to_s\n short_url_object = ShortUrl.new\n short_url_object.value = url\n short_url_object.save\n short_url = Const::GOODS_SHOW_ADDR + '/s/' + ShortUrl.decb64(short_url_object.id)\n p short_url\n qr = RQRCode::QRCode.new(short_url, :size => 4, :level => :h )\n png = qr.to_img \n png.resize(90, 90).save(Rails.root.to_s+\"/public/uploads/good/qrcode/qrcode_\"+@good.id.to_s+\".png\")\n format.html { redirect_to [:admin, @good], notice: '商品成功创建' }\n format.json { render action: 'show', status: :created, location: @good }\n else\n format.html { render action: 'new' }\n format.json { render json: @good.errors, status: :unprocessable_entity }\n end\n end\n end",
"def barcode_generator\n require 'barby'\n require 'barby/barcode/code_128'\n require 'barby/outputter/png_outputter'\n\n code = @package.barcode_packet\n # Set a path to store png\n path = \"barcodes/#{code}.png\"\n\n\n # Create a barcode with secure barcode_128\n barcode = Barby::Code128B.new(code)\n # Set to BINARY because it can't convert assci 8 bit to a utf-8 8 bit image, so, convert: binary => base64 => utf-8\n # Save in path directory\n File.open(path, 'w:BINARY'){ |f|\n f.write barcode.to_png(:height => 40, :margin => 5)\n }\n end",
"def download\n self.rqrcode.to_blob\n end",
"def upload_qrcode(key, data)\n bucket.object( QRCODE_PATH % key ).put(\n acl: 'bucket-owner-full-control',\n content_type: 'image/png',\n body: data\n )\n end",
"def credit_card_expiry_date\n ::Date.today + (365 * rand(1..4))\n end",
"def generate(qrstring, logo_image)\n\n\t\t# get the QRCode matrix object from rQrCode\n\t\tqrcode_matrix = self.generate_qrcode_matrix(qrstring)\n\n\t\t# Create a completely transparent image with dimensions of target image\t\t\n\t\timage_width = self.image_width_pixels(qrcode_matrix.module_count) \n\t\ttransparent_img = Image.new(image_width,image_width) { self.background_color = \"transparent\" }\n\n\t\t# Center the logo in the transparent image created above\n\t\tqr_logo_raw_overlay_img = transparent_img.composite(logo_image, CenterGravity, OverCompositeOp)\n\n\t\t# Modify the qr code squares and whiten all squares which are overlapped by non-transparent areas of logo\n\t\tself.whiten_overlapped_squares(qrcode_matrix.modules, qr_logo_raw_overlay_img)\n\n\t\t# Generate the qr code image based on modified modules matrix\n\t\tqr_code_image = self.generate_qr_code_image(qrcode_matrix)\n\n\t\t# Composite with the logo overlay\n\t\tqr_code_image_plus_logo = qr_code_image.composite(qr_logo_raw_overlay_img, CenterGravity, OverCompositeOp)\n\n\t\t# Wrap in larger image to provide 1-square white margin\n\t\timage_width = ((qrcode_matrix.module_count + 2) * @config[:square_size_px])\n\t\ttransparent_img_margin = Image.new(image_width,image_width) { self.background_color = \"white\" }\n\t\tqr_code_logo_plus_margin = transparent_img_margin.composite(qr_code_image_plus_logo, CenterGravity, OverCompositeOp)\n\n\t\treturn qr_code_logo_plus_margin\n\t\n\tend",
"def request_token(*args)\n args_options = args.extract_options!\n uri = '/api_paynow/api_paynow.asmx/api_paynow_authentication_new'\n\n options ={\n body: {\n psbID: self.preferred_psbid, \n username: self.preferred_username, \n secureCode: self.preferred_securecode,\n inv: args_options[:invoice],\n itm: '1', \n amt: args_options[:amount],\n paypal_amt: '',\n curr_type: 'TH',\n com: '',\n method: 1,\n language: args_options[:lang],\n resp_front_url: \"#{self.preferred_domain}/orders/#{args_options[:order_id]}/checkout/paysbuy_return\",\n resp_back_url: \"#{self.preferred_domain}/paysbuy_callbacks/notify?encryted_order_number=#{self.class.encrypt args_options[:invoice]}\",\n opt_fix_redirect: 1,\n opt_fix_method: '',\n opt_name: args_options[:name],\n opt_email: args_options[:email],\n opt_mobile: '',\n opt_address: \"\",\n opt_detail: \"\"\n }\n }\n\n result = self.class.post(base_uri + uri, options)\n attempt = 0\n\n # if have got an unexpected result, try to get the correct result again\n # from API document, return result should start with '00'\n # if not start with '00' should try again (then, try 5 times)\n while(!(result.parsed_response[\"string\"] =~ /^00/) && \n (attempt <= 5)) do\n\n result = self.class.post(base_uri + uri, options)\n attempt += 1\n end\n\n result.parsed_response[\"string\"].gsub(/^00/, \"\")\n end",
"def two_factor_qr_code_uri\n issuer = Rails.application.credentials.dig(Rails.env.to_sym, :otp_2fa_issuer_name)\n label = [issuer, email].join(':')\n\n otp_provisioning_uri(label, issuer: issuer)\n end",
"def refresh_if_near_expiration; end",
"def two_factor_qr_code_uri\n issuer = ENV['OTP_2FA_ISSUER_NAME']\n label = [issuer, email].join(':')\n \n otp_provisioning_uri(label, issuer: issuer)\n end",
"def show\n respond_to do |format|\n format.html\n format.svg { render :qrcode => @code.url, :level => :l, :unit => 10 }\n format.png { render :qrcode => @code.url }\n format.gif { render :qrcode => @code.url }\n format.jpeg { render :qrcode => @code.url }\n end\n end",
"def wechat_valid_qrcode_scan_params(referrer)\n {\n 'ToUserName' => 'FAKE_VALID_USERNAME',\n 'FromUserName' => 'FAKE_VALID_FROMUSERNAME',\n 'CreateTime' => '1501489767',\n 'MsgType' => 'event',\n 'Event' => 'SCAN',\n 'EventKey' => \"{\\\"referrer\\\":{\\\"reference_id\\\":\\\"#{referrer.reference_id}\\\"} }\",\n 'Ticket' => 'gQH18DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyUDNiRDF4R29ibC0xMDAwMDAwN04AAgR_jHhZAwQAAAAA'\n }\nend",
"def destroy\n @qr.destroy\n respond_to do |format|\n format.html { redirect_to qrs_url, notice: 'Qr was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def generate_reset_token\n self.update reset_token: SecureRandom.urlsafe_base64\n end",
"def failed_purchase_response\n 'NUMTRANS=0000000000&NUMAPPEL=0000000000&NUMQUESTION=0000000000&SITE=1999888&RANG=99&AUTORISATION=&CODEREPONSE=00014&COMMENTAIRE=Demande trait?e avec succ?s ✔漢'\n end",
"def verify_expiration; end",
"def verify_expiration; end",
"def qr_params\n params.require(:qr).permit(:name, :path)\n end",
"def expired_response e, sign_in_request_token\n status 403\n $logger.error \"#{e} #{e.backtrace}\"\n sign_in_request = JWT.decode sign_in_request_token, \n $leihs_public_key, false, { algorithm: 'ES256' }\n\n <<-HTML.strip_heredoc\n <html>\n <head></head>\n <body>\n <h1>Error: Token Expired </h1>\n <p> Please <a href=\"#{sign_in_request[0]['server_base_url']}\"> try again. </a></p>\n </body>\n </html>\n HTML\n end",
"def purchase_response(code = '00000')\n \"NUMTRANS=0720248861&NUMAPPEL=0713790302&NUMQUESTION=0000790217&SITE=1999888&RANG=99&AUTORISATION=XXXXXX&CODEREPONSE=#{code}&COMMENTAIRE=Demande trait?e avec succ?s ✔漢\"\n end",
"def barcode_image_uri(data,symbology)\n\n # check to see if we don't already have this barcode image\n filename = CGI.escape(symbology) + '_' + CGI.escape(data) + '.png'\n fname = Rails.root.to_s + \"/public/Barcodes/\" + filename\n\n # if the barcode image doesn't already exist then generate and save it\n if ! File.exists?(fname)\n\n str = 'Barby::'+symbology+'.new(\"'+data+'\")'\n\n begin\n barcode = eval str\n rescue Exception => exc\n barcode = Barby::Code128B.new(data) # fall back to Code128 type B\n end\n\n File.open(fname, 'w') do |f|\n f.write barcode.to_png\n end\n\n end\n logger.info(\"#########{}\")\n \"#{filename}\"\n end",
"def get_qr_code(opts = {})\n data, _status_code, _headers = get_qr_code_with_http_info(opts)\n data\n end",
"def update\n @qrcode = Qrcode.find(params[:id])\n\n respond_to do |format|\n if @qrcode.update_attributes(params[:qrcode])\n format.html { redirect_to action: :index, notice: 'Qrcode was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @qrcode.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @qrcode = Qrcode.find(params[:id])\n\n respond_to do |format|\n if @qrcode.update_attributes(params[:qrcode])\n format.html { redirect_to @qrcode, notice: 'Qrcode was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @qrcode.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_token\n \t SecureRandom.urlsafe_base64\n \tend",
"def create_confirm_code\r\n \t\tself.confirm_code = SecureRandom.urlsafe_base64\r\n \tend",
"def two_factor_qr_code_uri\n issuer = ENV['OTP_2FA_ISSUER_NAME']\n label = [issuer, email].join(':')\n\n otp_provisioning_uri(label, issuer: issuer)\n end",
"def two_factor_qr_code_uri\n issuer = ENV['OTP_2FA_ISSUER_NAME']\n label = [issuer, email].join(':')\n\n otp_provisioning_uri(label, issuer: issuer)\n end",
"def failed_purchase_response\n end",
"def generate_invalid_qrda_text\n validation_ids.each do |validation_id|\n Random.new.rand(1..2).times do\n measure_id = determine_useful_measures(validation_id).sample\n measure = HealthDataStandards::CQM::Measure.find_by(_id: measure_id)\n doc = Document.create(\n name: HOSPITALS.sample,\n validation_id: validation_id,\n test_execution: self,\n measure_id: measure.hqmf_id,\n qrda: generate_qrda_text(measure)\n )\n Cedar::Invalidator.invalidate_qrda(doc)\n end\n update_qrda_progress\n end\n end",
"def retry_failed_payment\n end",
"def show\n @qrcode = Qrcode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @qrcode }\n end\n end",
"def destroy\n @qr_code_scan_history.destroy\n respond_to do |format|\n format.html { redirect_to admin_qr_code_scan_histories_url, notice: 'Qr code scan history was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def qrcode_exist?(format)\n qrcode_setup_if_not_exist\n \n qrcode_storage.file_exist?(format)\n end"
] |
[
"0.6940199",
"0.682166",
"0.6792996",
"0.6791151",
"0.6786073",
"0.6724819",
"0.6723486",
"0.6717326",
"0.67033046",
"0.6611236",
"0.6510714",
"0.64748716",
"0.64384496",
"0.6358037",
"0.6141618",
"0.6131795",
"0.6102591",
"0.6087611",
"0.6081585",
"0.6073607",
"0.6040163",
"0.60359544",
"0.60077894",
"0.58733386",
"0.5870856",
"0.58431417",
"0.58250386",
"0.5807859",
"0.57834667",
"0.5782169",
"0.57722855",
"0.5764338",
"0.57473886",
"0.57457536",
"0.56606555",
"0.5610636",
"0.55969465",
"0.5592332",
"0.55254215",
"0.55238146",
"0.5518647",
"0.5507565",
"0.5484197",
"0.54659015",
"0.54615307",
"0.5451386",
"0.54069203",
"0.5402236",
"0.5390718",
"0.5390436",
"0.5301725",
"0.5297723",
"0.5295779",
"0.5264087",
"0.5247058",
"0.52345824",
"0.52086437",
"0.5187244",
"0.5182546",
"0.51639473",
"0.5161073",
"0.5144003",
"0.51418144",
"0.51356685",
"0.51237696",
"0.51203775",
"0.51055187",
"0.51001406",
"0.5095825",
"0.50950485",
"0.50778925",
"0.5063673",
"0.50630194",
"0.50534666",
"0.5044365",
"0.50435233",
"0.5023874",
"0.5012221",
"0.50079167",
"0.5006633",
"0.50000185",
"0.4997531",
"0.4997531",
"0.49938986",
"0.49869174",
"0.49788973",
"0.49777386",
"0.4976482",
"0.49729186",
"0.496793",
"0.4965422",
"0.4963824",
"0.49534217",
"0.49534217",
"0.49401668",
"0.49377972",
"0.49373078",
"0.49372324",
"0.4928906",
"0.49274492"
] |
0.62623596
|
14
|
GET /roles/1 GET /roles/1.json
|
def show
@role = Role.find(params[:id])
@permissions = @role.permissions.group_by &:subject_class
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n authorize Role\n\n respond_to do |format|\n format.json { render json: @roles }\n end\n end",
"def get_user_roles\n @roles = @user.roles.pluck(:name)\n render json: @roles\n end",
"def GetRole id\n\n APICall(path: \"custom_roles/#{id}.json\")\n\n end",
"def index\n @roles = Role.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @roles }\n end\n end",
"def show\n @role = Role.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role }\n end\n end",
"def show\n @roles = Role.all\n end",
"def show\n @role = Role.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role }\n end\n end",
"def show\n @role = Role.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role }\n end\n end",
"def show\n @role = Role.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role }\n end\n end",
"def show\n if can?(:read, User)\n @user = User.find(params[:id])\n @roles = \"\"\n\n @user.roles.each do |role|\n if @roles == \"\"\n @roles += role.name\n else\n @roles += \", \" + role.name\n end\n end\n end\n\n respond_to do |format|\n format.json { render :json => @user }\n format.xml { render :xml => @user }\n format.html \n end\n\n rescue ActiveRecord::RecordNotFound\n respond_to_not_found(:json, :xml, :html)\n end",
"def index\n @roles = Rol.all\n end",
"def getRole\n @users = User.where(\"role = ?\", params[:role]).NameOrder\n render json: @users\n end",
"def show(id = @id, user = @@default_user)\n @attributes = send_request(\"roles/#{id}\", :get) do |req|\n req.params = {\n auth_token: user.auth_token\n }\n end\n end",
"def show\n render json: @role\n end",
"def role_data(id)\n @conn.get(\"/api/v1/roles/#{id}\")\n end",
"def index\n @roles = System::Role.all\n end",
"def show\n @role = @client.roles.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def index\n @roles = @client.roles\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @roles }\n end\n end",
"def index\n @roles = Role.all\n end",
"def index\n @roles = Role.all\n end",
"def index\n @roles = Role.all\n end",
"def index\n @roles = Role.all\n end",
"def index\n @roles = Role.all\n end",
"def index\n @roles = Role.all\n end",
"def roles!(access = {})\n json = Api::Request.new do |request|\n request[:access] = access\n request[:method] = :GET\n request[:path] = '/mgmt/{{client_id}}/roles'\n end.execute!\n\n json[:roles]\n end",
"def show\n @roles_and_permission = @roles.roles_and_permission.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @roles_and_permission }\n end\n end",
"def list\n # We don't use pagination here since we want to display the roles in a\n # nice tree. Additionally, there won't be more than ~100 roles in a\n # normal scenario anyway - far less!\n @roles = Role.find(:all)\n end",
"def roles\n response[\"roles\"]\n end",
"def roles\n self.dig_for_array(\"roles\")\n end",
"def roles_path\n @roles_path ||= '/api/v2/roles'\n end",
"def index\n @company = Company.find(params[:company_id])\n @roles = Role.where(:company_id => @company.id)\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @roles }\n end\n end",
"def index\n @roles = record.roles.includes(:resource)\n render jsonapi: @roles, include: %i[users groups resource]\n end",
"def index\n authorize Role\n @roles = Role.all\n end",
"def index\n\t\tparamsr\n\t\tglobal\n\t\t# render json: @roles, each_serializer: RoleSerializer, root: false\n\tend",
"def list\n\n @roles = Role.find(:all, :order => 'name')\n\n end",
"def index\n @roles = Role.page params[:page]\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @roles}\n end\n end",
"def index\n @users = User.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @user_roles }\n end\n end",
"def show\n @user = User.find(params[:id])\n @roles = @user.roles\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def show\n @role = Role.includes(:personal_roles => :person).find_by_slug!(params[:id])\n respond_to do |format|\n format.html\n format.json { render :json => @role }\n end\n end",
"def index\n @roles = Role.all\n \n respond_to do |format|\n format.html { render :layout => 'application' } # use client application's layout\n format.xml { render :xml => @roles }\n end\n end",
"def index\n @user_roles = UserRole.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n end\n end",
"def index\n client_application_id = current_user.client_application_id.to_s\n @roles = Role.where(client_application_id: client_application_id)\n end",
"def get_roles_list()\n\n query_parameters = {}\n query_parameters['apiKey'] = @api_key\n query_parameters['apiSecret'] = @api_secret\n\n resource_path = 'identity/v2/manage/role'\n get_request(resource_path, query_parameters, nil)\n end",
"def index\n @all_roles = Role.all\n @user = User.find(params[:user_id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @roles }\n end\n end",
"def index\n @app_roles = AppRole.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @app_roles }\n end\n end",
"def show\n @role_user = RoleUser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role_user }\n end\n end",
"def show\n @role = Role.find(params[:id])\n respond_with(@role)\n end",
"def show\n @role = Role.find_by_name(params[:name])\n @role_authorities = @role.authorities\n \n respond_to do |format|\n format.html { render :layout => 'application' } # use client application's layout\n format.xml { render :xml => @role }\n end\n end",
"def roles\n client.user_roles(id)\n end",
"def roles\n client.user_roles(id)\n end",
"def edit_role\n @user = User.find(params[:id])\n @roles = Role.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def index\n @roles = Role.order(\"name\").all\n @user_list = User.order(\"email\").all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @roles }\n end\n end",
"def edit\n @user = User.find(params[:id])\n if can?(:update, @user)\n @roles = \"\"\n\n @user.roles.each do |role|\n if @roles == \"\"\n @roles += role.name\n else\n @roles += \", \" + role.name\n end\n end\n else\n @user = nil\n end\n\n respond_to do |format|\n format.json { render :json => @user } \n format.xml { render :xml => @user }\n format.html\n end\n\n rescue ActiveRecord::RecordNotFound\n respond_to_not_found(:json, :xml, :html)\n end",
"def index\n @roles = Role.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @roles }\n format.json { render :json => @roles.to_json(:only => [:id, :code, :name, :definition]) }\n format.js { render (:update){ |page| page[dom_id_nested(:index)].replace :file => \"admin/roles/index\" } }\n end\n end",
"def index\n @roles = Role.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @roles }\n end\n end",
"def get(\n id,\n deadline: nil\n )\n return @roles.get(\n id,\n deadline: deadline,\n )\n end",
"def show\n @lab_role = LabRole.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lab_role }\n end\n end",
"def list_roles(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'ListRoles'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :marker\n\t\t\targs[:query]['Marker'] = optional[:marker]\n\t\tend\n\t\tif optional.key? :max_items\n\t\t\targs[:query]['MaxItems'] = optional[:max_items]\n\t\tend\n\t\tself.run(args)\n\tend",
"def index\n @movie_roles = @movie.roles\n end",
"def index\n @roles = Role.page params[:page]\n end",
"def index\n render json: [UserRole.find_by(user_id: params[:user_id],\n role_id: params[:role_id])],\n each_serializer: UserRoleSerializer\n end",
"def index\n @roles = policy_scope(Role).page(pagination[:page]).per(pagination[:per])\n end",
"def get_roles(options = {})\n request_params = {\n per_page: options.fetch(:per_page, nil),\n page: options.fetch(:page, nil),\n include_totals: options.fetch(:include_totals, nil),\n name_filter: options.fetch(:name_filter, nil)\n }\n get roles_path, request_params\n end",
"def index\n\t\tindex_\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.xml { render :xml => @roles }\n\t\tend\n\tend",
"def index\n @users_roles = UsersRole.all\n end",
"def edit_users\n @user = User.find(params[:id])\n @role = @user.roles.first.name\n end",
"def get_single_role(account_id,role,opts={})\n query_param_keys = [\n \n ]\n\n form_param_keys = [\n \n ]\n\n # verify existence of params\n raise \"account_id is required\" if account_id.nil?\n raise \"role is required\" if role.nil?\n # set default values and merge with input\n options = underscored_merge_opts(opts,\n :account_id => account_id,\n :role => role\n )\n\n # resource path\n path = path_replace(\"/v1/accounts/{account_id}/roles/{role}\",\n :account_id => account_id,\n :role => role)\n headers = nil\n form_params = select_params(options, form_param_keys)\n query_params = select_params(options, query_param_keys)\n if opts[:next_page]\n pagination_params = page_params_load(:get, path)\n query_params.merge! pagination_params if pagination_params\n end\n response = mixed_request(:get, path, query_params, form_params, headers)\n page_params_store(:get, path)\n Role.new(response)\n end",
"def show\n @app_role = AppRole.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @app_role }\n end\n end",
"def roles\n roles_from_users\n end",
"def get_roles_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UserApi.get_roles ...'\n end\n # resource path\n local_var_path = '/api/3/roles'\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;charset=UTF-8'])\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 = 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 => 'ResourcesRole')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UserApi#get_roles\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def rbac_role_resource\n url_for(:roles_role, credentials, id) \n end",
"def index\n @org_roles = OrgRole.all\n end",
"def show\n @lab_permissions_role = LabPermissionsRole.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lab_permissions_role }\n end\n end",
"def get(\n id,\n deadline: nil\n )\n req = V1::RoleGetRequest.new()\n if not @parent.snapshot_time.nil?\n req.meta = V1::GetRequestMetadata.new()\n req.meta.snapshot_at = @parent.snapshot_time\n end\n\n req.id = (id)\n tries = 0\n plumbing_response = nil\n loop do\n begin\n plumbing_response = @stub.get(req, metadata: @parent.get_metadata(\"Roles.Get\", req), deadline: deadline)\n rescue => exception\n if (@parent.shouldRetry(tries, exception))\n tries + +@parent.jitterSleep(tries)\n next\n end\n raise Plumbing::convert_error_to_porcelain(exception)\n end\n break\n end\n\n resp = RoleGetResponse.new()\n resp.meta = Plumbing::convert_get_response_metadata_to_porcelain(plumbing_response.meta)\n resp.rate_limit = Plumbing::convert_rate_limit_metadata_to_porcelain(plumbing_response.rate_limit)\n resp.role = Plumbing::convert_role_to_porcelain(plumbing_response.role)\n resp\n end",
"def index\n @cms_roles = Cms::Role.all\n end",
"def index\n\t\t#@data = {name: '角色', path: '/managers/roles'}\n\t\t@roles = Role.page(params[:page]).per(params[:rows])\n\t\trespond_with({rows: @roles, total: @roles.total_count}) \n\tend",
"def show\n @user_role = UserRole.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n end\n end",
"def index\n @program_roles = ProgramRole.all\n end",
"def index\n @user = User.find( params[:user_id] )\n @roles = Role.all\n\n respond_to do |format|\n format.js { render :roles }\n end\n end",
"def edit\n @user = User.find(params[:id],include: :roles)\n @roles = Role.all\n respond_to do |format|\n format.html\n end\n end",
"def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @course_roles }\n end\n end",
"def role_select\n @@Roles.list\n end",
"def claims\n get_all_roles\n end",
"def claims\n get_all_roles\n end",
"def index\n @roles = Role.paginate(:page => params[:page], per_page: 30)\n @number = Role.count\n\n respond_to do |format|\n format.html\n format.json { render :json => Role.all }\n end\n end",
"def show\n @project_role = ProjectRole.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project_role }\n end\n end",
"def index\n return unless check_permission\n\n @roles = Role.left_joins(:user)\n end",
"def startup_roles(id, options={})\n get(\"1/startups/#{id}/roles\", options)\n end",
"def list\n @roles = Role.all(:include => [:groups, :users])\n end",
"def index\n role = Role.find_by_name('Admin')\n @users = role.users\n end",
"def show\n @roles_user = RolesUser.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @roles_user }\n end\n end",
"def index\n @roles = Role.all(:order=>'name')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @roles }\n end\n end",
"def get_role(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'GetRole'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :role_name\n\t\t\targs[:query]['RoleName'] = optional[:role_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def get_role(role_name)\n request(\n 'Action' => 'GetRole',\n 'RoleName' => role_name,\n :parser => Fog::Parsers::AWS::IAM::SingleRole.new\n )\n end",
"def test_role_features\n\n # get members of role with guid 4\n get '/role/3/members'\n assert (last_response.status == 200), \"Get all members of role id 3: response is not 200\"\n\n # get available role attributes\n get '/role/attributes'\n assert (last_response.body.size > 50), \"Get available role attributes: response to small for valid data\"\n\n # get all roles\n get '/role'\n assert (last_response.body.size > 50), \"Get all roles: response to small for valid data\"\n\n # get role with guid \"3\"\n get '/role/3'\n assert (last_response.body.size > 50), \"Get role with id 3: response to small for valid data\"\n end",
"def show\n @role = Role.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @role }\n format.js { render :json => @role.to_json }\n end\n end",
"def roles(options = {})\n headers = extract_headers!(options)\n json = client.list(\"/v1/auth/approle/role\", options, headers)\n return Secret.decode(json).data[:keys] || []\n rescue HTTPError => e\n return [] if e.code == 404\n raise\n end",
"def new\n \n @roles_and_permission = @roles.roles_and_permission.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @roles_and_permission }\n end\n end",
"def show\n @admin = Admin.find(params[:id])\n @role = Role.all\n @had_role_ids = @admin.roles.map(&:id)\n\n end",
"def get_role(role_id)\n raise Auth0::MissingParameter, 'Must supply a valid role_id' if role_id.to_s.empty?\n\n get \"#{roles_path}/#{role_id}\"\n end",
"def show\n @role_permision = RolePermision.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @role_permision }\n end\n end"
] |
[
"0.78213215",
"0.758502",
"0.7496266",
"0.7405081",
"0.71934754",
"0.7189593",
"0.71655685",
"0.71655685",
"0.71655685",
"0.71500736",
"0.7138432",
"0.71365404",
"0.7123315",
"0.71224034",
"0.71155775",
"0.7091493",
"0.7074178",
"0.70495325",
"0.7039511",
"0.7039511",
"0.7039511",
"0.7039511",
"0.7039511",
"0.7039511",
"0.7013212",
"0.7002328",
"0.6997671",
"0.6961335",
"0.6943603",
"0.6940976",
"0.69381905",
"0.69252795",
"0.69055814",
"0.6895666",
"0.6871209",
"0.686356",
"0.6858452",
"0.68570966",
"0.6844976",
"0.6839168",
"0.68387634",
"0.68010277",
"0.67940146",
"0.6788685",
"0.6783575",
"0.67631966",
"0.67437744",
"0.67437315",
"0.6714349",
"0.6714349",
"0.671321",
"0.6692722",
"0.66853833",
"0.6659218",
"0.6639824",
"0.6634887",
"0.6622596",
"0.661545",
"0.6604822",
"0.66001076",
"0.6595716",
"0.65827054",
"0.6557434",
"0.6520396",
"0.65161896",
"0.6511376",
"0.64874035",
"0.6478267",
"0.6463165",
"0.645618",
"0.645576",
"0.64476675",
"0.6442466",
"0.64342594",
"0.6428507",
"0.64266205",
"0.642074",
"0.6418689",
"0.64185864",
"0.6417395",
"0.64099467",
"0.64039946",
"0.64039737",
"0.64039737",
"0.63937527",
"0.6382111",
"0.637554",
"0.63678145",
"0.6367299",
"0.63667417",
"0.63581634",
"0.63535887",
"0.63411444",
"0.63242865",
"0.6321193",
"0.6318642",
"0.6311836",
"0.630965",
"0.63018537",
"0.6290109",
"0.6288035"
] |
0.0
|
-1
|
GET /roles/new GET /roles/new.json
|
def new
permissions
@role = Role.new
#render layout: "users"
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role }\n end\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role }\n end\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role }\n end\n end",
"def new\n @role = Role.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role }\n end\n end",
"def new\n\t\t@roles_new = Role.all\n\t\tif can?(:update, Role)\n\t\t\t@roles_new = Role.all\n\t\tend\n\n @user = User.new if can?(:create, User)\n respond_to do |format|\n format.json { render :json => @user } \n format.xml { render :xml => @user }\n format.html\n end\n end",
"def new\n \n @roles_and_permission = @roles.roles_and_permission.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @roles_and_permission }\n end\n end",
"def new\n @role = Role.new\n respond_with(@role)\n end",
"def new\n @company = Company.find(params[:company_id])\n @role = Role.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role }\n end\n end",
"def new\n @role_user = RoleUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role_user }\n end\n end",
"def create\n if !grant_access(\"edit_roles\", current_user)\n head(403)\n end\n @role = Role.new(role_params)\n @role.user_id = current_user.id\n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n\t\t@role = Role.new\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml { render :xml => @role }\n\t\tend\n\tend",
"def new\n @project_role = ProjectRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project_role }\n end\n end",
"def new\n @role = Role.new\n end",
"def new\n @role = Role.new\n end",
"def new\n @role = Role.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @app_role = AppRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @app_role }\n end\n end",
"def new_role\n new_role = create_role(params[:role][:name])\n\n return redirect_to admin_roles_path, flash: { alert: I18n.t(\"administrator.roles.invalid_create\") } if new_role.nil?\n\n redirect_to admin_roles_path(selected_role: new_role.id)\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @role = Role.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def create\n @role = Role.new(params[:role])\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to admin_roles_path, notice: 'Role was successfully created.' }\n format.json { render json: @role, status: :created, location: @role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n submenu_item 'role-new'\n @role = Role.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @title = \"New User\"\n\n @user = User.new\n @user.user_roles.build\n respond_to do |format|\n format.html #new.html.erb\n format.js\n format.json { render json: @user }\n end\n end",
"def new\n @lab_permissions_role = LabPermissionsRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lab_permissions_role }\n end\n end",
"def new\n @user_role = UserRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def create\n @role = Role.new(params[:role])\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render json: @role, status: :created, location: @role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(params[:role])\n \n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render json: @role, status: :created, location: @role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @role_map = RoleMap.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role_map }\n end\n end",
"def new\n @user = User.new\n @roles = Role.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @course_role }\n end\n end",
"def new\n @member = Member.new\n user = @member.build_user\n @roles = Role.find(:all)\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @member }\n end\n end",
"def new\n @role_types = RoleTypes.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_types }\n end\n end",
"def new\n @role_user = RolesUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_user }\n end\n end",
"def new\n @role_permision = RolePermision.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role_permision }\n end\n end",
"def new\n @member = Member.new\n user = @member.build_user\n @roles = Role.find(:all)\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @member }\n end\n end",
"def create\n @role = Role.new(params[:role])\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to edit_role_path(@role), :notice => t('hurricane.notice.create_record_success', :type => t_type) }\n format.json { render json: @role, status: :created, location: @role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(role_params)\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(role_params)\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(role_params)\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to @role, notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(params[:role])\n\n if @role.save\n redirect_to admin_roles_url\n else\n render :action => \"new\"\n end\n end",
"def new\n @user_role = UserRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_role }\n end\n end",
"def new\n logger.debug(\"Role new\")\n @role=Role.new\n setup_role\n if params[:from] == 'organisation'\n @organisation = Organisation.find(params[:id])\n @from='organisation'\n else\n @person = Person.find(params[:id])\n @from='person'\n end\n # explicitly set role_type_id to nil\n # so that the first role type in the\n # list is not displayed in role type\n # drop-down\n @role.role_type_id = nil\n\t\n\tset_default_status(@role)\n \n end",
"def create\n chef_server_rest.post(\"roles\", self)\n self\n end",
"def new\n \t @employee = User.new\n @roles = Role.all\n puts \"ROLES ARE GOING NOW\"\n end",
"def create\n @role = Role.new(params[:role])\n\n respond_to do |format|\n if @client.roles << @role\n flash[:notice] = 'Role was successfully created.'\n format.html { redirect_to client_role_url(@client, @role) }\n format.xml { render :xml => @role, :status => :created, :location => [@client, @role] }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @role = Role.new(:category => 0)\n @possible_permissions = Permission.by_category(@role.category)\n\n respond_to do |format|\n format.xml { render :xml => @role }\n format.js #new.js.rjs\n end\n end",
"def new\n @role_type = RoleType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_type }\n end\n end",
"def new\n @userrole = Userrole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @userrole }\n end\n end",
"def new\n @role = Role.new\n end",
"def new\n @screen = session.active_screen\n @role = Role.new\n @all_users = User.find_active_users\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role }\n end\n end",
"def new\n @role_user = RoleUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_user }\n end\n end",
"def create\n \n if request.get?\n @role = Role.new\n else\n @role = Role.new(params[:role])\n\n # assign parent role\n if not params[:role][:parent].to_s.empty?\n @role.parent = Role.find(params[:role][:parent].to_i)\n end\n\n if @role.save\n # set the roles's static permissions to the static permission from the parameters \n params[:role][:static_permissions] = [] if params[:role][:static_permissions].nil?\n @role.static_permissions = params[:role][:static_permissions].collect { |i| StaticPermission.find(i) }\n\n # the above should be successful if we reach here; otherwise we \n # have an exception and reach the rescue block below\n flash[:success] = 'Role has been created successfully.'\n redirect_to :action => 'show', :id => @role.id\n else\n render :action => 'create'\n end\n end\n \n rescue ActiveRecord::RecordNotFound\n flash[:error] = 'You sent an invalid request.'\n redirect_to :action => 'list'\n end",
"def create\n error = ''\n \n if params[:roles]\n params[:roles].each do |role|\n @role = Role.new(role) unless role[:title].blank?\n error << model_errors(@role) unless @role.save\n end\n else\n @role = Role.new(params[:roles])\n error << model_errors(@role) unless @role.save\n end\n \n respond_to do |format|\n format.html do\n if error.blank?\n flash[:notice] = \"#{params[:roles].nil? ? 'Role has' : 'Roles have'} been created.\"\n redirect_back_or_default roles_path\n else\n flash[:error] = 'Oops, something went wrong.'\n @role.nil? ? render(:action => 'edit') : redirect_back_or_default(roles_path)\n end\n end\n \n format.js do\n if error.blank?\n flash.now[:notice] = \"#{params[:roles].nil? ? 'Role has' : 'Roles have'} been created.\"\n get_models\n render :action => 'index', :layout => false\n else\n flash.now[:error] = 'Oops, something went wrong.'\n render :action => 'edit', :layout => false\n end\n end\n end\n end",
"def create\n @role = Role.new(role_params)\n\n respond_to do |format|\n if role.save\n current_user.add_role :admin, role\n format.html { redirect_to admin_role_path(role), notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: role }\n else\n format.html { render :new }\n format.json { render json: role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @individual_role_record = IndividualRoleRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @individual_role_record }\n end\n end",
"def new\n @user = User.new\n @role = params[:role]\n end",
"def create\n @role = Role.new(role_params)\n\n respond_to do |format|\n if @role.save\n format.html {\n redirect_to dashboard_path\n flash[:success] = @role.name+' was successfully created.' }\n format.json { render json: @role.to_json }\n else\n format.html { render action: 'new' }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(params[:role])\n \n respond_to do |format|\n if @role.save\n format.html { redirect_to(@role, :notice => 'Role was successfully created.') }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @operations_role = OperationsRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @operations_role }\n end\n end",
"def create\n @role = @company.roles.new(safe_params)\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to [@company, @role], notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @company = Company.find( params[:company_id])\n @user = @company.users.build\n @roles = ROLE\n end",
"def new\n @story = Story.new\n @roles = Role.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @story }\n end\n end",
"def create\n @role = Role.new(params[:role])\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to(@role, :notice => 'Role was successfully created.') }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @role = System::Role.new\n end",
"def new\n @company = Company.find(params[:company_id])\n if !can?(:manage, @company)\n raise CanCan::AccessDenied.new(\"Usted no puede administrar otra compañia\", :manage, @company)\n end\n @user = User.new\n @roles = Role.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def create\n @lab_role = LabRole.new(params[:lab_role])\n\n respond_to do |format|\n if @lab_role.save\n format.html { redirect_to @lab_role, notice: 'Lab role was successfully created.' }\n format.json { render json: @lab_role, status: :created, location: @lab_role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lab_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @cms_role = Cms::Role.new(cms_role_params)\n\n respond_to do |format|\n if @cms_role.save\n format.html { redirect_to @cms_role, notice: 'Role was successfully created.' }\n format.json { render :show, status: :created, location: @cms_role }\n else\n format.html { render :new }\n format.json { render json: @cms_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(params[:role])\n respond_to do |format|\n if @role.save\n flash[:notice] = 'Role was successfully created.'\n format.html { redirect_to role_url(@role.code) }\n format.xml { head :created, :location => role_url(@role.code) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role.errors.to_xml }\n end\n end\n end",
"def create\n @role = Role.new(params[:role])\n respond_to do |format|\n if @role.save\n flash[:notice] = 'Role was successfully created.'\n format.html { redirect_to(@role) }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @page_role = PageRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page_role }\n end\n end",
"def create\n respond_to do |format|\n if @role.save\n format.html { redirect_to user_roles_path(@user), notice: I18n.t('controller.create_success_notice', model: '角色') }\n format.json { render action: 'show', status: :created, location: @role }\n else\n format.html { render action: 'new' }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @primary_role = PrimaryRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @primary_role }\n end\n end",
"def create\n @role = Role.new role_params\n flash[:notice] = 'Role was successfully created.' if @role.save\n respond_with @role\n end",
"def new\n @user = User.new :role_attributes => {:title => 'member'}\n end",
"def new\n @protocol_role = ProtocolRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @protocol_role }\n end\n end",
"def create\n @team_role = TeamRole.new(team_role_params)\n\n respond_to do |format|\n if @team_role.save\n format.html { redirect_to lab_team_roles_path(@lab), notice: 'Team role was successfully created.' }\n format.json { render action: 'show', status: :created, location: @team_role }\n else\n format.html { render action: 'new' }\n format.json { render json: @team_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def CreateRole params = {}\n \n APICall(path: 'custom_roles.json',method: 'POST',payload: params.to_json)\n \n end",
"def create\n @role = Role.new(params[:role])\n @role.save\n respond_with(@role)\n end",
"def create\n abilities = []\n client_application = current_user.client_application_id.to_s\n @abilities = Role.get_method_names.sort\n @role = Role.new(role_params)\n params[:role][:role_abilities].each do |ability|\n abilities << ability.to_sym\n end\n @role.role_abilities = [{\"action\"=> abilities, \"subject\"=>[:api]}]\n @role.client_application_id = client_application\n respond_to do |format|\n if @role.save\n format.html { redirect_to roles_path, notice: 'Role was successfully created.' }\n format.json { render :index, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @people = Person.all\n @role = get_role\n respond_with @event, @role\n end",
"def create\n respond_to do |format|\n if @course_role.save\n format.html { redirect_to course_roles_url, notice: 'Course role was successfully created.' }\n format.json { render json: @course_role, status: :created, location: @course_role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @course_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new prepare\n @role_permission = RolePermission.new\n @role_permission.role_id = params[:role_id]\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @role_permission }\n end\n end",
"def new\n @provider_role = ProviderRole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider_role }\n end\n end",
"def create\n @role = Role.new(params[:role])\n respond_to do |format|\n if @role.save\n flash[:notice] = 'Role was successfully created.'\n format.html { redirect_to(role_path(@role.slug)) }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @role = Role.new(role_params)\n respond_to do |format|\n if @role.save\n flash[:notice] = 'Role was successfully created.'\n format.html { redirect_to(role_path(@role.slug)) }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render \"new\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n submenu_item 'role_new'\n load_permissions\n ids=params[:permissions].select{|k,v| v=='1'}.map { |k,v| k.to_i } unless params[:permissions].nil?\n if ids.length > 0\n permissions=Permission.find(:all, :conditions => [\"id in (#{ids.join(',')})\"])\n params[:role][:permissions] = permissions\n @role = Role.new(params[:role])\n if @role.save\n flash[:notice] = \"创建角色成功\"\n redirect_to :action => 'index'\n else\n flash[:error] = \"创建角色失败\"\n render :action => 'new'\n end\n else\n flash[:error] = \"角色名或权限不能为空\"\n redirect_to :action => 'new'\n end\n\n end",
"def create\n @admin_role = RoleUser.new(params[:role_user])\n\n respond_to do |format|\n if @admin_role.save\n format.html { redirect_to @role_users_path, notice: 'Role was successfully created.' }\n format.json { render json: @admin_role, status: :created, location: @admin_role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @admin_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @entity_role = EntityRole.new(entity_role_params)\n\n respond_to do |format|\n if @entity_role.save\n format.html { redirect_to @entity_role, notice: 'Entity role was successfully created.' }\n format.json { render :show, status: :created, location: @entity_role }\n else\n format.html { render :new }\n format.json { render json: @entity_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\r\n @role = Role.new(role_params)\r\n @role.save\r\n end",
"def create\n @users_role = UsersRole.new(users_role_params)\n\n respond_to do |format|\n if @users_role.save\n format.html { redirect_to @users_role, notice: 'Users role was successfully created.' }\n format.json { render :show, status: :created, location: @users_role }\n else\n format.html { render :new }\n format.json { render json: @users_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @company = Company.find(params[:company_id])\n @role = Role.new(params[:role])\n @role.company_id = @company.id\n respond_to do |format|\n if @role.save\n format.html { redirect_to company_role_path(@company, @role), notice: 'El rol fue creado exitosamente.' }\n format.json { render json: @role, status: :created, location: @role }\n else\n format.html { render action: \"new\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @roles = Role.paginate :page => params[:page],\n :per_page => 15,\n :order => sort_order('name')\n @role= Role.new(params[:role])\n\n respond_to do |format|\n if @role.save\n format.html { redirect_to(roles_url, :notice => 'New User role successfully added.') }\n format.xml { render :xml => @role, :status => :created, :location => @role }\n else\n format.html { render :action => \"index\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @roles = Role.all\n @nrole = Role.new\n end",
"def create\n @role = Role.new role_params\n authorize @role\n flash.now[:notice] = 'Role was successfully created.' if @role.save\n respond_with @role\n end",
"def new\n @robots=\"noindex,nofollow\"\n authorize! :create, Roxiware::Person\n @person = Roxiware::Person.new({:show_in_directory=>true,\n :first_name=>\"First\",\n :middle_name=>\"\",\n :last_name=>\"Last\",\n :role=>\"Role\",\n :email=>\"email@email.com\",\n :bio=>\"Bio\"}, :as=>@role)\n respond_to do |format|\n format.html { render :partial =>\"roxiware/people/editform\" }\n format.json { render :json => @person.ajax_attrs(@role) }\n end\n end",
"def add_role\n\n\t\t@roles = Role.new(role_params)\n\t\tif @roles.save\n\t\t\tredirect_to '/details'\n\t\telse\n\t\t\trender 'index'\n\t\tend\n\n\tend",
"def create\n # rails 3 bug\n params[:user][:roles].reject!(&:blank?)\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_url, notice: I18n.t(:new_user_notify, name: @user.name, role: @user.role_str ) }\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 @role = System::Role.new(system_role_params)\n respond_to do |format|\n if @role.save\n format.html { redirect_to system_roles_url, notice: '添加角色成功.' }\n format.json { render :show, status: :created, location: @role }\n else\n format.html { render :new }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @lab_role = LabRole.new\n\n render :layout => \"blank\"\n end"
] |
[
"0.8056065",
"0.8056065",
"0.8056065",
"0.8047554",
"0.7925329",
"0.7899501",
"0.75905114",
"0.7552672",
"0.75305",
"0.7404623",
"0.73878103",
"0.73797524",
"0.73708034",
"0.73708034",
"0.73668516",
"0.73646253",
"0.73598355",
"0.73466617",
"0.73466617",
"0.73466617",
"0.73466617",
"0.7319681",
"0.73090357",
"0.72790754",
"0.72006667",
"0.71966416",
"0.7164784",
"0.71443903",
"0.7137173",
"0.71274626",
"0.70941854",
"0.70901513",
"0.7082152",
"0.7065805",
"0.7059749",
"0.7041859",
"0.7041197",
"0.7029444",
"0.7029444",
"0.7029444",
"0.7017208",
"0.7014363",
"0.70122373",
"0.69952184",
"0.6941265",
"0.6931404",
"0.6916441",
"0.69143164",
"0.68828624",
"0.6876309",
"0.68604463",
"0.6859469",
"0.6839785",
"0.68369466",
"0.68330896",
"0.6831358",
"0.6817967",
"0.6814961",
"0.6814382",
"0.67903286",
"0.6789971",
"0.6764996",
"0.6763802",
"0.675926",
"0.673668",
"0.67297494",
"0.6729637",
"0.6721937",
"0.67210925",
"0.67042553",
"0.66859615",
"0.6682522",
"0.6669702",
"0.6641736",
"0.663069",
"0.66184974",
"0.66184837",
"0.6615549",
"0.6607312",
"0.65941626",
"0.6591984",
"0.65918565",
"0.6583166",
"0.65803593",
"0.65798384",
"0.65740263",
"0.6571463",
"0.65701586",
"0.65585345",
"0.65478206",
"0.6545662",
"0.6540951",
"0.65338254",
"0.65320516",
"0.6531983",
"0.6515132",
"0.6514973",
"0.6501256",
"0.6474498",
"0.6471373"
] |
0.7036298
|
37
|
PUT /roles/1 PUT /roles/1.json
|
def update
@role = Role.find(params[:id])
if @role.update_attributes(params[:role])
msg= "Role updated successfully!"
else
msg= "Role update failed!"
end
redirect_to roles_path, :flash => { :notice => msg }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edit_role(id, *roles)\n request(:put, \"/users/#{id}.json\", default_params(:role_ids => roles))\n end",
"def UpdateRole params = {}\n \n APICall(path: 'custom_roles.json',method: 'PUT',payload: params.to_json)\n \n end",
"def update\n @role = Role.find(params[:id])\n @role.update_attributes(params[:role])\n respond_with(@role)\n end",
"def update\n @role = @client.roles.find(params[:id])\n\n respond_to do |format|\n if @role.update_attributes(params[:role])\n flash[:notice] = 'Role was successfully updated.'\n format.html { redirect_to client_role_url(@client, @role) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n \n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n \n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find_by_name(params[:name])\n \n respond_to do |format|\n @role.authorities = Authority.find_by_name(params[:authority_names])\n format.html { redirect_to(my_gem_role_path(@role.name),\n :notice => 'Role was successfully updated.') }\n format.xml { head :ok }\n end\n end",
"def update_role(id, name)\n current_path = \"/api/v1/roles/#{id}/update\"\n payload = { 'new_name' => name }.to_json\n @conn.put(current_path, payload)\n end",
"def update(role, id = @id, user = @@default_user)\n @attributes = send_request(\"roles/#{id}\", :put) do |req|\n req.body = {\n role: role,\n auth_token: user.auth_token\n }\n end\n end",
"def update\n if !grant_access(\"alter_roles\", current_user)\n head(403)\n end\n @role.user_id = current_user.id\n @role.start_point = false if !params[:role][:start_point]\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(value, options = {})\n id = value[:ID] || value['ID']\n raise Diplomat::IdParameterRequired if id.nil?\n\n role_name = value[:Name] || value['Name']\n raise Diplomat::NameParameterRequired if role_name.nil?\n\n custom_params = use_cas(@options)\n @raw = send_put_request(@conn, [\"/v1/acl/role/#{id}\"], options, value, custom_params)\n if @raw.status == 200\n parse_body\n elsif @raw.status == 400\n raise Diplomat::RoleMalformed, @raw.body\n else\n raise Diplomat::UnknownStatus, \"status #{@raw.status}: #{@raw.body}\"\n end\n end",
"def update\n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to admin_roles_path, notice: 'Role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save\n begin\n chef_server_rest.put(\"roles/#{@name}\", self)\n rescue Net::HTTPClientException => e\n raise e unless e.response.code == \"404\"\n\n chef_server_rest.post(\"roles\", self)\n end\n self\n end",
"def edit_roles\n if (@user = find_user(params[:id]))\n begin\n User.transaction(@user) do\n \n roles = params[:user][:roles].collect { |role_id| Role.find(role_id) }\n # add any new roles & remove any missing roles\n roles.each { |role| @user.roles << role if !@user.roles.include?(role) }\n @user.roles.each { |role| @user.roles.delete(role) if !roles.include?(role) }\n\n @user.save\n flash[:notice] = \"Roles updated for user '#{@user.login}'.\"\n end\n rescue\n flash[:warning] = 'Roles could not be edited at this time. Please retry.'\n ensure\n redirect_to :back\n end\n else\n redirect_back_or_default :action => 'list'\n end\n end",
"def update\n respond_to do |format|\n if role.update(role_params) && update_users_roles\n format.html { redirect_to admin_role_path(role), notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: role }\n else\n format.html { render :edit }\n format.json { render json: role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n abilities = []\n params[:role][:role_abilities].each do |ability|\n abilities << ability.to_sym\n end\n @role.role_abilities = [{\"action\"=> abilities, \"subject\"=>[:api]}]\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to roles_path, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n\n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to edit_role_path(@role), :notice => t('hurricane.notice.update_record_success', :type => t_type)}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user.roles=params[\"user\"][\"roles\"]\n respond_to do |format|\n if @user.update(event_params)\n format.html { redirect_to users_path, notice: 'User roles change successfully' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_role\n @user = User.find( params[:id] )\n @user.update_attributes(params[:user])\n redirect_to users_path\n end",
"def update\n @user = User.find(params[:id])\n params[:user][:roles].reject!(&:blank?)\n respond_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 update\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n \n @perms = params[:permissions[\"permissions\"]]\n if @perms != nil\n @permissions = @perms[\"permissions\"]\n end\n #logger.debug \"PERMISSIONS: #{@permissions.inspect}\"\n if @permissions == nil\n @role.read = 0\n @role.write = 0\n @role.execute = 0\n end\n if @permissions != nil\n if @permissions.include?(\"read\")\n @role.read = 1\n else\n @role.read = 0\n end\n if @permissions.include?(\"write\")\n @role.write = 1\n else\n @role.write = 0\n end\n if @permissions.include?(\"execute\")\n @role.execute = 1\n else\n @role.execute = 0\n end\n end\n\n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to @role, notice: t(:role_updated) }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_role\n\t\t@role = Role.find(params[:id])\n\n\t \trespond_to do |format|\n\t\t if @role.update_attributes(role_update_params)\n\t\t format.html { redirect_to(@role, :notice => 'Entry was successfully updated.') }\n\t\t format.json { respond_with_bip(@role) }\n\t\t else\n\t\t format.html { render :action => \"edit\" }\n\t\t format.json { respond_with_bip(@role) }\n\t\t end\n\n \t end\n\tend",
"def update\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: t('success_update') }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n\n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to(@role, :notice => 'Role was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @role = Role.find(params[:id])\n\n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to(@role, :notice => 'Role was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n flash.now[:notice] = 'Role was successfully updated.' if @role.update role_params\n respond_with @role\n end",
"def update\n respond_to do |format|\n if @role.update(system_role_params)\n format.html { redirect_to system_roles_url, notice: '更新角色成功.' }\n format.json { render :index, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @admin_role = Role.find(params[:id])\n\n respond_to do |format|\n if @admin_role.update_attributes(params[:admin_role])\n format.html { redirect_to @admin_role, notice: 'Role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @admin_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role.attributes = params[:role]\n respond_to do |format|\n if @role.save\n flash[:notice] = 'Role was successfully updated.'\n format.html { redirect_to role_url(@role.code) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role.errors.to_xml }\n end\n end\n end",
"def update_role\n @user = User.find(params[:id])\n\n # Limit access to authorized users\n authorize! :manage, @user\n\n @user.admin = params[:admin_role]\n respond_to do |format|\n if @user.save\n format.json { head :no_content }\n else\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 @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:user_id])\n @role = Role.find(params[:id])\n unless @user.has_role?(@role.name)\n @user.roles << @role\n end\n redirect_to :action => 'index'\n end",
"def update\n authorize(current_user)\n role = params[:user][:role_ids]\n roleModel =Role.find( role)\n if @user.setRole roleModel.name\n @user.save\n redirect_to users_path, :notice => \"Rolle geändert\"\n else\n redirect_to users_path, :notice => \"Rolle nicht geändert\"\n end\n end",
"def update\n flash[:notice] = 'Role was successfully updated.' if @role.update_attributes role_params\n respond_with @role\n end",
"def update\n @role = Role.find(params[:id])\n\n if @role.update_attributes(params[:role])\n redirect_to admin_roles_url\n else\n render :action => \"edit\"\n end\n end",
"def update\n ActiveRecord::Base.transaction do\n @role, hash = fill_role(Role.find(params[:id]), params[:role])\n\n respond_to do |format|\n if @role.update_attributes(hash) && @role.save\n flash[:notice] = 'Role was successfully updated.'\n format.html { redirect_to(@role) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end\n end",
"def edit_role\n @user = User.find(params[:id])\n @roles = Role.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def update\n resource.update_attributes params[params_key], as: current_role\n respond_with resource\n end",
"def set_role\n @role = RoleMaster.find_by_id(params[:id])\n if @role\n else\n \trender json: { valid: false}, status: 404\n end\n end",
"def update\n @role = Role.find(params[:role][:id])\n\n if @role.update_attributes(params[:role])\n flash['notice'] = 'Role was successfully updated.'\n redirect_to :action => 'edit', \n :id => params[:role][:id]\n else\n flash['notice'] = 'Role not updated'\n redirect_to :action => 'edit', \n :id => params[:role][:id]\n end\n \n\n end",
"def update\n authorize! :assign_roles, @user if params[:user][:assign_roles]\n if @user.update_attributes(params[:user])\n redirect_to @user, notice: 'User was successfully updated.'\n else\n render \"edit\"\n end\n end",
"def update\n @user = User.find(params[:user_id])\n @roles = Role.all\n \n if current_user.is_admin?\n @user.roles.clear\n @roles.each do |role|\n if (params[:role][:role][role.rolename][:hasrole].to_s == 1.to_s)\n @user.roles << role\n end\n end\n else\n @roles.each do |role|\n if !role.admin_only\n if @user.has_role?(role.rolename)\n @user.roles.destroy(role)\n end\n if (params[:role][:role][role.rolename][:hasrole].to_s == 1.to_s)\n @user.roles << role\n end\n end\n end\n end\n \n flash[:notice] = I18n.t(\"user.success.roles_updated\")\n reload_page\n \n end",
"def update\n @roles = Role.all\n\n role = user_params[:role_id] ? user_params[:role_id] : @user.role_id\n if user_params[:password].empty?\n new_params = { :role_id => role,\n :first_name => user_params[:first_name],\n :last_name => user_params[:last_name],\n :email => user_params[:email],\n :telephone => user_params[:telephone] }\n else\n new_params = { :role_id => role,\n :first_name => user_params[:first_name],\n :last_name => user_params[:last_name],\n :email => user_params[:email],\n :telephone => user_params[:telephone],\n :password => user_params[:password],\n :password_confirmation => user_params[:password_confirmation] }\n end\n p = new_params\n respond_to do |format|\n if @user.update(p)\n format.html { redirect_to @user, notice: 'Benutzerdaten wurden aktualisiert.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n if request.get?\n @role = Role.find(params[:id].to_i)\n else\n @role = Role.find(params[:id].to_i)\n\n # set parent role\n if not params[:role][:parent].to_s.empty?\n @role.parent = Role.find(params[:role][:parent])\n else\n @role.parent = nil\n end\n\n # get an array of static permissions and set the permission associations\n params[:role][:static_permissions] = [] if params[:role][:static_permissions].nil?\n permissions = params[:role][:static_permissions].collect { |i| StaticPermission.find(i) }\n @role.static_permissions = permissions\n\n if @role.update_attributes(params[:role])\n flash[:success] = 'Role has been updated successfully.'\n redirect_to :action => 'show', :id => @role\n else\n render :action => 'update'\n end\n end\n \n rescue RecursionInTree\n @role.errors.add :parent, \"must not be a descendant of itself\"\n render :action => 'update'\n rescue ActiveRecord::RecordNotFound\n flash[:error] = 'You sent an invalid request.'\n redirect_to :action => 'list'\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @role.update_attributes(params[:role])\n flash[:notice] = 'Role was successfully updated.'\n format.html { redirect_to(role_path(@role.slug)) }\n format.xml { head :ok }\n else\n format.html { render \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def set_role\r\n @role = Role.find(params[:id])\r\n end",
"def change_role(role)\n role_list.each do |old_role|\n remove_role old_role\n end\n puts role\n add_role role\n puts roles\n end",
"def update\n respond_to do |format|\n if @role.update(role_params)\n format.html {\n redirect_to dashboard_path\n flash[:success] = @role.name+' was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @company = Company.find(params[:company_id])\n @role = Role.find(params[:id])\n \n respond_to do |format|\n if @role.update_attributes(params[:role])\n format.html { redirect_to company_role_path(@company, @role), notice: 'El rol fue editado exitosamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @role.permissions = []\n @role.set_permissions(params[:permissions]) if params[:permissions]\n respond_to do |format|\n if @role.update(role_params)\n format.html { redirect_to @role, notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_role(role_id, data = {})\n raise Auth0::MissingParameter, 'Must supply a valid role_id' if role_id.to_s.empty?\n\n patch \"#{roles_path}/#{role_id}\", data\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def set_role\n @role = Role.find(params[:id])\n end",
"def update_role(token, server_id, role_id, name, colour, hoist = false, mentionable = false, packed_permissions = 36_953_089)\n request(\n __method__,\n :patch,\n \"#{api_base}/guilds/#{server_id}/roles/#{role_id}\",\n { color: colour, name: name, hoist: hoist, mentionable: mentionable, permissions: packed_permissions }.to_json,\n Authorization: token,\n content_type: :json\n )\n end",
"def update\n # @roles = Role.all\n params[:user][:role_ids] ||= []\n puts json: user_params\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to [:admin, @user], notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { redirect_to edit_admin_user_path(@user), alert: @user.errors.full_messages().join(', ') }\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 @role.update(safe_params)\n format.html { redirect_to [@company, @role], notice: 'Role was successfully updated.' }\n format.json { render :show, status: :ok, location: @role }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_role\n @role = Role.find(params[:id]) if params[:id].present?\n end",
"def update_role(auth, server_id, role_id, name, color, hoist, mentionable, permissions, reason = nil)\n MijDiscord::Core::API.request(\n :guilds_sid_roles_rid,\n server_id,\n :patch,\n \"#{MijDiscord::Core::API::APIBASE_URL}/guilds/#{server_id}/roles/#{role_id}\",\n {\n color: color, name: name, hoist: hoist,\n mentionable: mentionable, permissions: permissions\n }.delete_if {|_, v| v.nil? }.to_json,\n Authorization: auth,\n content_type: :json,\n 'X-Audit-Log-Reason': reason\n )\n end",
"def update_roles(roles)\n self.roles |= roles\n self.save!\n end",
"def save_roles user\n user.add_role(params[:role_name])\n end",
"def update\n respond_to do |format|\n if @users_role.update(users_role_params)\n format.html { redirect_to @users_role, notice: 'Users role was successfully updated.' }\n format.json { render :show, status: :ok, location: @users_role }\n else\n format.html { render :edit }\n format.json { render json: @users_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n load_permissions\n ids = params[:permissions].select {|k, v| v == \"1\"}.map {|k,v| k.to_i }\n if ids.length > 0\n permissions = Permission.find(:all, :conditions => [\"id in (#{ids.join(',')})\"])\n @role = Role.find(params[:id])\n params[:role][:permissions] = permissions\n if @role.update_attributes(params[:role])\n flash[:notice] = \"修改角色成功\"\n redirect_to :action => 'index'\n else\n flash[:error] = '修改角色失败'\n redirect_to :action => 'edit', :id => @role.id\n end\n else\n flash[:error] = \"角色名或权限不能为空\"\n redirect_to :action => 'edit', :id => @role.id\n end\n end",
"def modify_roles(email, role)\n\t\tresponse = @client.execute(api_method: @service.acl.insert,\n\t\t\t\t\t parameters: {'calendarId' => ENV['NSCS_Calendar_ID']}, body: JSON.dump({role: role, scope: {type: \"user\", \"value\": email}}))\n\tend",
"def update\n respond_to do |format|\n if @role.update_attributes(role_params)\n flash[:notice] = 'Role was successfully updated.'\n format.html { redirect_to(role_path(@role.slug)) }\n format.xml { head :ok }\n else\n format.html { render \"edit\" }\n format.xml { render :xml => @role.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_role(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'UpdateRole'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :new_assume_role_policy_document\n\t\t\targs[:query]['NewAssumeRolePolicyDocument'] = optional[:new_assume_role_policy_document]\n\t\tend\n\t\tif optional.key? :role_name\n\t\t\targs[:query]['RoleName'] = optional[:role_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def update\n respond_to do |format|\n if @sys_role.update(sys_role_params)\n format.html { redirect_to @sys_role, notice: 'Sys role was successfully updated.' }\n format.json { render :show, status: :ok, location: @sys_role }\n else\n format.html { render :edit }\n format.json { render json: @sys_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lab_role = LabRole.find(params[:id])\n\n respond_to do |format|\n if @lab_role.update_attributes(params[:lab_role])\n format.html { redirect_to @lab_role, notice: 'Lab role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lab_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find_by(email: params[:user][:email])\n @user.roles = params[:user][:roles]\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to root_path, notice: 'User was successfully updated.' }\n # format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_role\n role = Role.find_by_name(user_params[:role]) rescue nil\n role ? user_params_with_role(role) :\n (render json: { status: 400, error: \"Mention a proper Role for User\" })\n end",
"def update\n respond_to do |format|\n if @org_role.update(org_role_params)\n format.html { redirect_to @org_role, notice: 'Org role was successfully updated.' }\n format.json { render :show, status: :ok, location: @org_role }\n else\n format.html { render :edit }\n format.json { render json: @org_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @team_role.update(team_role_params)\n format.html { redirect_to lab_team_roles_path(@lab), notice: 'Team role was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @team_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @role.update(role_params)\n @role.permissions = params[:role][:permission].map do |key, value|\n index = value[\"index\"] == \"1\" ? true : false\n index = true if value[\"new\"] == \"1\" || value[\"edit\"] == \"1\" || value[\"remove\"] == \"1\"\n Permission.update(value[\"id\"], :index => index, :new => value[\"new\"], :edit => value[\"edit\"], :remove => value[\"remove\"], :import => value[\"import\"])\n end\n format.html { redirect_to management_roles_path }\n format.json { render json: @role, status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @required_role.update(required_role_params)\n format.html { redirect_to @required_role, notice: 'Required role was successfully updated.' }\n format.json { render :show, status: :ok, location: @required_role }\n else\n format.html { render :edit }\n format.json { render json: @required_role.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @roles_and_permission = @roles.roles_and_permission.find(params[:id])\n\n respond_to do |format|\n if @roles_and_permission.update_attributes(params[:roles_and_permission])\n format.html { redirect_to [@roles,@roles_and_permission], notice: 'Roles and permission was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @roles_and_permission.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_user_role(role)\n role_id = Role.where(role_type: role).first.id\n self.update_attributes(role_id: role_id) \n end",
"def update\n @user_role = UserRole.find(params[:id])\n\n respond_to do |format|\n if @user_role.update_attributes(params[:user_role])\n flash[:notice] = 'UserRole was successfully updated.'\n format.html { redirect_to([:admin, @user_role]) }\n else\n format.html { render :action => \"edit\" }\n end\n end\n end"
] |
[
"0.73883325",
"0.7328734",
"0.71556437",
"0.7143024",
"0.7127945",
"0.7085617",
"0.69865286",
"0.6953493",
"0.6936841",
"0.69317037",
"0.6862839",
"0.68599266",
"0.6855699",
"0.6850963",
"0.6815799",
"0.68097216",
"0.680326",
"0.67881626",
"0.6777378",
"0.6759132",
"0.6749898",
"0.6743721",
"0.674341",
"0.67385143",
"0.67385143",
"0.6736561",
"0.67261046",
"0.67261046",
"0.6666523",
"0.666092",
"0.66550696",
"0.6652414",
"0.6652295",
"0.6642869",
"0.66259134",
"0.6603401",
"0.6587859",
"0.6578259",
"0.657262",
"0.65627295",
"0.6549493",
"0.6541448",
"0.65400964",
"0.65314424",
"0.65312636",
"0.6530568",
"0.65119636",
"0.65081733",
"0.65081733",
"0.65081733",
"0.65081733",
"0.65081733",
"0.65081733",
"0.65081733",
"0.65081733",
"0.6501428",
"0.6497558",
"0.64967203",
"0.6496304",
"0.6494823",
"0.6490575",
"0.64669937",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.6440077",
"0.64386445",
"0.643306",
"0.6431893",
"0.6430314",
"0.64249223",
"0.64193904",
"0.6417028",
"0.6406739",
"0.6397948",
"0.63927144",
"0.6367333",
"0.6362418",
"0.63597554",
"0.6346679",
"0.6342329",
"0.6341154",
"0.6340364",
"0.63350934",
"0.632938",
"0.6323326",
"0.63158387",
"0.63156664",
"0.63053966",
"0.62857723"
] |
0.67518514
|
20
|
DELETE /roles/1 DELETE /roles/1.json
|
def destroy
@role = Role.find(params[:id])
if @role.destroy
msg= "Role deleted successfully!"
else
msg= "Role delete failed!"
end
redirect_to roles_path, :flash => { :notice => msg }
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n \n respond_to do |format|\n format.html { redirect_to roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = @client.roles.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n flash[:notice] = 'Role was successfully removed.' \n format.html { redirect_to(client_roles_url(@client)) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n chef_server_rest.delete(\"roles/#{@name}\")\n end",
"def destroy\n @admin_role = Role.find(params[:id])\n @admin_role.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_roles_url }\n format.json { head :no_content }\n end\n end",
"def DeleteRole id\n \n APICall(path: \"custom_roles/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n @rol.destroy\n respond_to do |format|\n format.html { redirect_to roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n role.destroy\n respond_to do |format|\n format.html { redirect_to admin_roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if !grant_access(\"alter_roles\", current_user)\n head(403)\n end\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to roles_url , :notice => t('hurricane.notice.delete_record_success', :type => t_type)}\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to system_roles_url, notice: '删除角色成功.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @roles_and_permission = @roles.roles_and_permission.find(params[:id])\n @roles_and_permission.destroy\n\n respond_to do |format|\n format.html { redirect_to roles_and_permissions_url }\n format.json { head :no_content }\n end\n end",
"def delete(id = @id, user = @@default_user)\n @attributes = send_request(\"roles/#{id}\", :delete) do |req|\n req.body = {\n auth_token: user.auth_token\n }\n end\n end",
"def destroy\n @user = User.find(params[:user_id])\n @role = Role.find(params[:id])\n if @user.has_role?(@role.name)\n @user.roles.delete(@role)\n end\n respond_to do |format|\n format.html {redirect_to :action => 'index' }\n format.xml { head :ok }\n end\n \n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to company_roles_url(@company), notice: 'Role was successfully removed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @core_user_role.destroy\n respond_to do |format|\n format.html { redirect_to core_user_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lab_role = LabRole.find(params[:id])\n @lab_role.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n \n @users = User.find_by_role_id(@role.id)\n respond_to do |format|\n if @users == nil\n @role.destroy\n format.html { redirect_to roles_url, :notice => t(:role_deleted) }\n format.json { head :no_content }\n else\n format.html { redirect_to roles_url, :alert => t(:role_inuse) }\n format.json { head :no_content }\n end\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to management_roles_url, notice: 'Perfil was successfully removed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find params[:user_id]\n @role = Role.find params[:id]\n\n @user.roles.delete @role\n flash[:notice] = 'Assigment was successfully destroyed.'\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role.destroy\n respond_with @role, location: roles_path\n end",
"def destroy\n @role.destroy\n respond_with @role, location: roles_path\n end",
"def destroy\n @users_role.destroy\n respond_to do |format|\n format.html { redirect_to users_roles_url, notice: 'Users role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ministerial_role.destroy\n respond_to do |format|\n format.html { redirect_to ministerial_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n respond_with(@role)\n end",
"def destroy\r\n @role.destroy\r\n respond_to do |format|\r\n format.html { redirect_to \"index\", notice: 'Role was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @roles_privilege.destroy\n respond_to do |format|\n format.html { redirect_to roles_privileges_url, notice: 'Roles privilege was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rolid = params[:id]\n Role.destroy(@rolid)\n end",
"def destroy\n @company = Company.find(params[:company_id])\n @role = Role.find(params[:id])\n @role.destroy\n \n respond_to do |format|\n format.html { redirect_to company_roles_path(@company) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n format.html { redirect_to user_roles_path }\n format.js\n format.json { head :no_content }\n end\n end",
"def destroy\n @role = Role.find_by_id(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_url, :notice => \"User role removed.\") }\n format.xml { head :ok }\n end\n end",
"def destroy\n @required_role.destroy\n respond_to do |format|\n format.html { redirect_to required_roles_url, notice: 'Required role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user_role = UserRole.find(params[:id])\n @user_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to(blog_roles_url(@blog)) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @app_role = AppRole.find(params[:id])\n @app_role.destroy\n\n respond_to do |format|\n format.html { redirect_to app_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @userrole = Userrole.find(params[:id])\n @userrole.destroy\n\n respond_to do |format|\n format.html { redirect_to(userroles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user_role = UserRole.find(params[:id])\n @user_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_user_roles_url) }\n end\n end",
"def destroy\n @role.destroy\n\n redirect_to roles_path\n end",
"def destroy\n @master_role.destroy\n respond_to do |format|\n format.html { redirect_to master_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n ActiveRecord::Base.transaction do\n @role = Role.find(params[:id])\n @role.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_url) }\n format.xml { head :ok }\n end\n end\n end",
"def destroy\n @titan_role.destroy\n respond_to do |format|\n format.html { redirect_to titan_roles_url, notice: 'Titan role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role_type = RoleType.find(params[:id])\n @role_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role_user = RolesUser.find(params[:id])\n @role_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(roles_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @mg_role.destroy\n respond_to do |format|\n format.html { redirect_to mg_roles_url, notice: 'Mg role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cms_role.destroy\n respond_to do |format|\n format.html { redirect_to cms_roles_url, notice: 'Role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lab_permissions_role = LabPermissionsRole.find(params[:id])\n @lab_permissions_role.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_permissions_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @team_role.destroy\n respond_to do |format|\n format.html { redirect_to lab_team_roles_path(@lab) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role_user = RoleUser.find(params[:id])\n @role_user.destroy\n\n respond_to do |format|\n format.html { redirect_to(role_users_url) }\n format.xml { head :ok }\n format.json { render :text => '{status: \"success\"}'}\n end\n end",
"def destroy\n @sys_role.destroy\n respond_to do |format|\n format.html { redirect_to sys_roles_url, notice: 'Sys role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @org_role.destroy\n respond_to do |format|\n format.html { redirect_to org_roles_url, notice: 'Org role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @profile_role.destroy\n respond_to do |format|\n format.html { redirect_to profile_roles_url, notice: 'Profile role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entity_role.destroy\n respond_to do |format|\n format.html { redirect_to entity_roles_url, notice: 'Entity role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project_role = ProjectRole.find(params[:id])\n @project_role.destroy\n\n respond_to do |format|\n format.html { redirect_to project_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role_funcion.destroy\n respond_to do |format|\n format.html { redirect_to role_funcions_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n return unless check_permission\n\n @role.destroy\n respond_to do |format|\n format.html { redirect_to roles_url, notice: 'Role was successfully destroyed.' }\n end\n end",
"def destroy\n @sulabh_user_role.destroy\n respond_to do |format|\n format.html { redirect_to sulabh_user_roles_url, notice: 'Sulabh user role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @operations_role = OperationsRole.find(params[:id])\n @operations_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(operations_roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role.destroy\n respond_to do |format|\n flash[:notice] = 'Role was successfully destroyed.'\n format.html { redirect_to roles_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user_to_role.destroy\n respond_to do |format|\n format.html { redirect_to user_to_roles_url, notice: 'User to role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role_auth_ref.destroy\n respond_to do |format|\n format.html { redirect_to role_auth_refs_url, notice: 'Role auth ref was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @movie_role.destroy\n respond_to do |format|\n format.html { redirect_to movie_roles_url, notice: 'Movie role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @venue_role.destroy\n respond_to do |format|\n format.html { redirect_to venue_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @security_agent_role.destroy\n respond_to do |format|\n format.html { redirect_to security_agent_roles_url, notice: 'Security agent role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @team_user_role.destroy\n respond_to do |format|\n format.html { redirect_to team_user_roles_url, notice: 'Team user role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n @role = Role.find(params[:id].to_i)\n \n if request.get?\n # render only\n else\n if not params[:yes].nil?\n @role.destroy\n flash[:success] = 'The role has been deleted successfully.'\n redirect_to :action => 'list'\n else\n flash[:success] = 'The role has not been deleted.'\n redirect_to :action => 'show', :id => params[:id]\n end\n end\n\n rescue CantDeleteWithChildren\n flash[:error] = \"You have to delete or move the role's children before attempting to delete the role itself.\"\n redirect_to :action => 'show', :id => params[:id]\n rescue ActiveRecord::RecordNotFound\n flash[:error] = 'This role could not be found.'\n redirect_to :action => 'list'\n end",
"def destroy\n @role_menu.destroy\n respond_to do |format|\n format.html { redirect_to role_menus_url, notice: 'Role menu was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete(role:, type:)\n\t\t\t\t\tconnection.post(build_path('removeRoles'), nil, roleNames: [role].flatten.join(','),\n\t\t\t\t\t\ttype: type).code == '200'\n\t\t\t\tend",
"def destroy\n @user = User.find(params[:id])\n @user.transaction do\n @user.user_roles.destroy_all\n @user.update_attribute(:admin, false)\n end\n respond_to do |format|\n format.html { redirect_to admin_roles_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n\n\nrol = Role.where(:id=>current_user.role).first\n if rol.nombre == \"ACRM\"\n\n @status_del_admitido = StatusDelAdmitido.find(params[:id])\n @status_del_admitido.destroy\nelse\n flash[:error] ='No tienes permiso para realizar esta accion'\n\nend\n \n \n\n respond_to do |format|\n format.html { redirect_to status_del_admitidos_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @user_space_role = UserSpaceRole.find(params[:id])\n @user_space_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_space_roles_url) }\n format.xml { head :ok }\n end\n end",
"def delete_role(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DeleteRole'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'https'\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :role_name\n\t\t\targs[:query]['RoleName'] = optional[:role_name]\n\t\tend\n\t\tself.run(args)\n\tend",
"def delete\n @role = Role.find(params[:id])\n \n if request.get?\n # render only\n else\n if not params[:yes].nil?\n @role.destroy\n flash[:success] = 'The role has been deleted successfully.'\n redirect_to roles_path\n else\n flash[:success] = 'The role has not been deleted.'\n redirect_to role_path(Role.find(params[:id]))\n end\n end\n\n rescue CantDeleteWithChildren\n flash[:error] = \"You have to delete or move the role's children before attempting to delete the role itself.\"\n redirect_to role_path(Role.find(params[:id]))\n rescue ActiveRecord::RecordNotFound\n flash[:error] = 'This role could not be found.'\n redirect_to roles_path\n end",
"def destroy\n\n\n\nrol = Role.where(:id=>current_user.role).first\n if rol.nombre == \"ACRM\"\n \n \n @rpm = Rpm.find(params[:id])\n @rpm.destroy\nelse\n flash[:error] ='No tienes permiso para realizar esta accion'\n\nend\n\n respond_to do |format|\n format.html { redirect_to rpms_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @role_privilege.destroy\n respond_to do |format|\n format.html { redirect_to role_privileges_url, notice: 'Veza je usšešno obrisana.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @role_in_a_movie = RoleInAMovie.find(params[:id])\n @role_in_a_movie.destroy\n\n respond_to do |format|\n format.html { redirect_to role_in_a_movies_url }\n format.json { head :ok }\n end\n end",
"def destroy\n\n @role.stop_user_id = session[:user_id]\n @role.stoped_at = DateTime.now\n @role.state = \"N\"\n @role.save\n respond_to do |format|\n format.html { redirect_to roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\n\n\nrol = Role.where(:id=>current_user.role).first\n if rol.nombre == \"ACRM\"\n @role_permision = RolePermision.find(params[:id])\n @role_permision.destroy\nelse\n flash[:error] ='No tienes permiso para realizar esta accion'\n\nend\n \n \n\n respond_to do |format|\n format.html { redirect_to role_permisions_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @role_types = RoleTypes.find(params[:id])\n @role_types.destroy\n\n respond_to do |format|\n format.html { redirect_to(role_types_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @role.destroy\n\n flash[:notice] = \"Role successfully destroyed.\"\n\n redirect_to roles_path\n end",
"def destroy\n @primary_role = PrimaryRole.find(params[:id])\n @primary_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(primary_roles_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @admin_role_ref.destroy\n respond_to do |format|\n format.html { redirect_to admin_role_refs_url, notice: 'Admin role ref was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @all_subject_role.destroy\n respond_to do |format|\n format.html { redirect_to all_subject_roles_url, notice: 'All subject role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n @role = get_role\n respond_with @event, @role\n end",
"def destroy\n @worship_role.destroy\n respond_to do |format|\n format.html { redirect_to worship_roles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n respond_to do |format|\n if @role.destroy\n format.html { redirect_to(@role) }\n format.js { render (:update) {|page| page[dom_id_nested(:item, @role)].remove() } }\n else\n flash[:notice] = 'Role was not deleted.'\n format.html { redirect_to roles_path }\n format.js { render (:update) { |page| page.alert(\"Cannot delete role #{@role.name}\") }}\n end\n end\n end",
"def destroy\n @role_permission.destroy\n respond_to do |format|\n format.html { redirect_to role_permissions_url, notice: 'Role permission was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @page_role = PageRole.find(params[:id])\n @page_role.destroy\n\n respond_to do |format|\n format.html { redirect_to(page_roles_url) }\n format.xml { head :ok }\n format.json { render :text => '{status: \"success\"}'}\n end\n end",
"def remove_role\n if @user.has_role? params[:role]\n @user.remove_role params[:role]\n render json: { :success => 'role successfully removed' } \n else \n render json: { :success => 'The user does not have this role' }\n end\n end",
"def destroy\n @opportunity_role = OpportunityRole.find(params[:id])\n @opportunity_role.destroy\n\n head :no_content\n end",
"def destroy\n @rolepermission.destroy\n respond_to do |format|\n format.html { redirect_to rolepermissions_url, notice: 'Rolepermission was successfully destroyed.' }\n format.json { head :no_content }\n end\n end"
] |
[
"0.7583307",
"0.7525977",
"0.7523992",
"0.75092655",
"0.74943435",
"0.7418692",
"0.738887",
"0.73744464",
"0.73679906",
"0.7358079",
"0.731516",
"0.72902375",
"0.72487247",
"0.72487247",
"0.72487247",
"0.72487247",
"0.72487247",
"0.72487247",
"0.723153",
"0.7230734",
"0.7230734",
"0.7227224",
"0.7214308",
"0.7201804",
"0.7190927",
"0.7176644",
"0.7172197",
"0.71712434",
"0.71385014",
"0.71350145",
"0.7123388",
"0.7123388",
"0.7122198",
"0.7118499",
"0.71058774",
"0.7089155",
"0.7087749",
"0.70845425",
"0.70701665",
"0.7060278",
"0.7054008",
"0.704454",
"0.70406395",
"0.7035393",
"0.7030372",
"0.7029945",
"0.69881266",
"0.6987008",
"0.6973966",
"0.69712913",
"0.6946726",
"0.6942139",
"0.6940438",
"0.693974",
"0.69389564",
"0.69330245",
"0.69206357",
"0.6885514",
"0.6866661",
"0.6866472",
"0.68619406",
"0.68404496",
"0.6839539",
"0.6839066",
"0.68311864",
"0.68264455",
"0.6813777",
"0.681195",
"0.68033737",
"0.68023103",
"0.6792266",
"0.67918336",
"0.67917085",
"0.67913747",
"0.67847526",
"0.6784274",
"0.6781957",
"0.67783487",
"0.67668307",
"0.6758518",
"0.673304",
"0.6731809",
"0.67282045",
"0.67267746",
"0.6725402",
"0.67175996",
"0.6707149",
"0.67005694",
"0.66993773",
"0.6698467",
"0.6694398",
"0.66940075",
"0.6686707",
"0.6666152",
"0.66604584",
"0.66567355",
"0.66524935",
"0.6648225",
"0.6644455",
"0.6630613"
] |
0.681107
|
68
|
Required function, gets the user's permissions
|
def get_permissions(username)
p = lookup_permissions(username)
if p
return p
else
return nil
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def permissions\n User.do_find_permissions session_id: kb_session_id\n end",
"def get_permissions_for_user(user)\n get_filtered_policy(0, user)\n end",
"def core_getUsersPermissions\n # definisco permessi iniziali\n initial_permissions = (1...11).to_a\n\n unpermitted = core_getHideUsersPermissionsSettings\n permitted_permissions = initial_permissions\n permitted_permissions = initial_permissions - unpermitted if unpermitted\n\n permissions = []\n names = core_getUsersPermissionsNamesSettings\n return permitted_permissions if !names\n\n permitted_permissions.each do |permission|\n names.each do |name|\n permissions.push([permission, name.last]) if permission === name.first.to_i\n end\n end\n\n return permissions\n end",
"def user_permissions\n if user_signed_in? && (current_user.is_logistics? || current_user.is_clerical? || current_user.is_vendor? || current_user.is_customer?)\n authorize! :edit, Element\n end\n end",
"def getPermissions\n perms = []\n perms.push :disseminate if params[:disseminate_perm] == \"on\"\n perms.push :withdraw if params[:withdraw_perm] == \"on\"\n perms.push :peek if params[:peek_perm] == \"on\"\n perms.push :submit if params[:submit_perm] == \"on\"\n perms.push :report if params[:report_perm] == \"on\" \n perms \n end",
"def permissions\n\t\tauthorize @user\n\t\t@permissions = []\n\t\tonly_theirs = \"Only theirs\"\n\t\tyes = \"Yes\"\n\t\tno = \"No\"\n\t\tnames = [\"View positions\", \"Create positions\", \"Edit positions\", \"Delete positions\",\n\t\t \"Apply\", \"View applications\", \"Edit applications\", \"Delete applications\",\n\t\t \"Change application submission status\"]\n\t\tadmin_permissions = [yes, yes, yes, yes, yes, \"All\", yes, yes, yes]\n\t\tmod_permissions = [yes, no, yes, no, yes, \"All but incomplete\", only_theirs, only_theirs, yes]\n\t\tuser_permissions = [yes, no, no, no, yes, only_theirs, only_theirs, only_theirs, no]\n\t\tnames.each_with_index do |permission, index|\n\t\t\t@permissions << { name: names[index], admin: admin_permissions[index], mod: mod_permissions[index], user: user_permissions[index]}\n\t\tend\n\n @title = 'Permissions'\n\tend",
"def get_permissions (user, store_name)\n s = \"\"\n [ :read, :write, :delegate ].each do |action|\n s << action.to_s[0, 1] \\\n if @auth_system.authorized?(user, store_name, action)\n end\n s\n end",
"def load_permissions \n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]} \n end",
"def get_permissions\n permissions.keys\n end",
"def get_permissions\n permissions.keys\n end",
"def get_permissions(poll_path, polls = read_polls_data)\n if signed_in?\n @user.permissions(poll_path, polls)\n else\n []\n end\n end",
"def permissions\n return @permissions\n end",
"def get_active_permissions\n set_access_token\n if @access_token && !@permissions && set_uid\n # if we don't have permissions set but have an access token\n # grab the user's info\n @rest = Facebook::RestAPI.new(@access_token) \n result = @rest.fql_query(\"select #{all_permissions.join(\",\")} from permissions where uid = #{@uid.to_s}\")\n result.first\n end \n end",
"def custom_permissions\n if current_user.admin?\n can :manage, :all\n end\n end",
"def project_permissions\n user.project_permissions(rule.project)\n end",
"def load_permissions\n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]}\n end",
"def user_permission\n has_controller_permission?('user')\n end",
"def permissions\n read_attribute(:permissions) || {}\n end",
"def custom_permissions\n discover_permissions\n export_sets_permissions\n batches_permissions\n preservation_events_permissions\n end",
"def permissions = {}",
"def load_permissions\n \n @current_permissions = current_user.role.permissions.collect{|i| [i.subject_class, i.action]}\n end",
"def fetch_granted_permissions(action:, user:, type:, target:, token:)\n permissions = granted_permissions_for_user(user: user, type: type, target: target, token: token)\n @read = permissions.include?('read')\n @create = permissions.include?('create')\n @update = permissions.include?('update')\n @delete = permissions.include?('delete')\n instance_variable_get(\"@#{action}\")\n end",
"def admin_grant_permissions\n @user = User.includes(:perms).find(params[:id])\n authorize @user\n user_perms = current_user.perms\n @perms = user_perms & [Perm.grant_permissions, Perm.modify_templates, Perm.modify_guidance, Perm.use_api, Perm.change_org_details]\n end",
"def permissions\n attribute_prop(5)\n end",
"def permissions_assignable_for_user(usr)\n return [] if usr.nil?\n if administrator?(usr)\n get_permissions.collect{|k| Permission.find_by_name(Lockdown.get_string(k)) }.compact\n else\n user_groups_assignable_for_user(usr).collect{|g| g.permissions}.flatten.compact\n end\n end",
"def permissions\n objects_from_response(Code42::Permission, :get, 'permission')\n end",
"def get_permissions\n permissions = Hash.new\n permissions[:CanEditAllTeams] = 1\n permissions[:CanEditAllPlayers] = 2\n permissions[:CanEditAllSeasons] = 3\n permissions[:CanEditAllDivisions] = 4\n permissions[:CanEditAllRatings] = 5\n permissions[:CanEditAllRoles] = 6\n permissions[:CanEditAllPermissions] = 7\n permissions[:CanImport] = 8\n permissions[:CanApproveRatings] = 10\n @permissions = permissions\n end",
"def permissions\n if @prm\n @prm\n else\n @maximum_prms\n end\n end",
"def permissions_assignable_for_user(usr)\n return [] if usr.nil?\n if administrator?(usr)\n get_permissions.collect do |k| \n ::Permission.find_by_name(Lockdown.get_string(k))\n end.compact\n else\n user_groups_assignable_for_user(usr).collect do |g| \n g.permissions\n end.flatten.compact\n end\n end",
"def permissions_for(game)\n self.permissions.where(\"user_roles.game_id = ?\", game.id)\n end",
"def custom_permissions\n if user_groups.include?(\"admin\")\n can :manage, :all\n end\n end",
"def permission\n Ricer::Irc::Permission.by_permission(self.permissions, authenticated?)\n end",
"def permission_grants\n return @permission_grants\n end",
"def get_current_permissions()\n\t\t\tkparams = {}\n\t\t\tclient.queue_service_action_call('permission', 'getCurrentPermissions', 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 permissions\n @attributes[:permissions]\n end",
"def permissions\n @attributes[:permissions]\n end",
"def user?\n permissions == 'user'\n end",
"def list_permissions\n BrickFTP::API::Permission.all\n end",
"def list_permissions\n BrickFTP::API::Permission.all\n end",
"def load_permissions\n authorize! :manage, :all\n end",
"def fb_permissions\n fb_user = FbGraph::User.new('me', :access_token => self.access_token)\n fb_user.permissions\n end",
"def permission_resources\n %w{roles sites employees classrooms students gapps_org_units}\n end",
"def show\n\t\t@all_permissions = Lockdown::System.permissions_assignable_for_user(current_user)\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user_group }\n end\n end",
"def access_rights_for_permission(perm)\n sym = Lockdown.get_symbol(perm)\n\n permissions[sym]\n rescue \n raise SecurityError, \"Permission requested is not defined: #{sym}\"\n end",
"def permissions\n [\"read_permissions\", \"update_permissions\", \"delete_permissions\"].each do |p|\n perms = self.send(p)\n perm_string = []\n AssetPermission::GROUP.each do |g, v|\n if perms & AssetPermission::GROUP[g] > 0\n perm_string << g\n end\n end\n puts \"#{self.name}: #{p}: #{perm_string.join(',')}\"\n end\n end",
"def permissions\n @resource_permissions\n end",
"def permission_level(repo, collaborator, options={})\n get \"#{Repository.path repo}/collaborators/#{collaborator}/permission\", options\n end",
"def user_permissions\n if current_user.id == params[:id].to_i\n @user = User.find(params[:id])\n else\n flash[:danger] = 'Unauthorized action.'\n redirect_to edit_user_path(current_user) \n end\n end",
"def my_permissions\n @my_permissions ||= self.roles.map {|r| r.permissions.map {|p| p.name}}.flatten.freeze\n end",
"def permissions\n Rails.cache.fetch(\"permissions_#{self.id}\", expire_in: 1.month) do\n self.roles.map(&:permissions).flatten\n end\n end",
"def permissions( force_reload = false )\n\n # Two levels of joins here, so can't use has_many :through\n if force_reload\n @permissions = nil \n @permissions_by_class_and_op = {}\n end\n\n cond_str = 'role_id in ' + self.class.role_assigned_cond( '?' )\n if !instance_variable_defined?(\"@permissions\") || @permissions.nil?\n @permissions ||= Permission.where([cond_str, self]).to_a\n end\n\n return @permissions\n end",
"def permissions(api_key=KillBillClient.api_key, api_secret=KillBillClient.api_secret)\n User.do_find_permissions :session_id => kb_session_id,\n :api_key => api_key,\n :api_secret => api_secret\n end",
"def permissions\n if @permissions.nil?\n perm_array = []\n roles.each { |r| perm_array << r.permission_ids }\n @permissions = perm_array.flatten.uniq\n else\n @permissions\n end\n end",
"def apply_superuser_permissions(permission_types)\n []\n end",
"def permissions\n Roles.type_map[role_type].permissions\n end",
"def perms\n if @perms.nil?\n @perms = {}\n permissions = ['comment', 'edit', 'reassign', 'prioritize', 'close', 'milestone']\n permissions.each do |p|\n if @task.project_id.to_i == 0 || current_user.can?(@task.project, p)\n @perms[p] = {}\n else\n @perms[p] = { :disabled => 'disabled' }\n end\n end\n\n end\n\n @perms\n end",
"def user_permissions(id:, **args)\n params = parameters(args) do\n optional_params\n end\n request(:get, \"users/#{id}/permissions\", params)\n end",
"def permissions_for(context=nil, force_context=nil)\n auth_scope do\n force_context ||= config.force_context\n context = Zuul::Context.parse(context)\n roles = roles_for(context)\n if force_context\n return role_and_subject_permissions_for(context, roles)\n else\n return role_and_subject_permissions_within(context, roles)\n end\n end\n end",
"def user_permission(paid, cancelled, signed_in, admin)\n\tif paid == \"no\" or cancelled == \"yes\"\n\treturn \"Go away!\"\n\telsif signed_in == \"yes\" and admin == \"yes\"\n\treturn \"You can see and change all the pages!\"\n\telsif signed_in == \"yes\" and admin == \"no\"\n\treturn \"You can see all the pages!\"\n\telsif signed_in == \"no\"\n\treturn \"You can't see any of the pages, please sign in!\"\n\tend\nend",
"def all_chanperms\n Ricer::Irc::Chanperm.where(:user_id => self.id)\n end",
"def calendar_permissions\n return @calendar_permissions\n end",
"def overall_permissions(thing)\n global_permissions.merge!(permissions_for(thing))\n end",
"def permission?(user, level, server)\n determined_level = if user.webhook? || server.nil?\n 0\n else\n user.roles.reduce(0) do |memo, role|\n [@permissions[:roles][role.id] || 0, memo].max\n end\n end\n\n [@permissions[:users][user.id] || 0, determined_level].max >= level\n end",
"def get_loging_permission\n # Note: we want to use \"find_by_id\" because it's OK to return a nil.\n # If we were to use User.find, it would throw an exception if the user can't be found.\n if session[:user_id]\n @has_permission = @current_user.role \n else\n nil\n end\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def permission\n return @children['permission'][:value]\n end",
"def users_with_permissions()\n\t return LiveStreamSeriesPermission.where(:live_stream_series_id => self.id).collect{|p| p.user}\n end",
"def admin_grant_permissions\n user = User.find(params[:id])\n authorize user\n\n # Super admin can grant any Perm, org admins can only grant Perms they\n # themselves have access to\n perms = if current_user.can_super_admin?\n Perm.all\n else\n current_user.perms\n end\n\n render json: {\n 'user' => {\n 'id' => user.id,\n 'html' => render_to_string(partial: 'users/admin_grant_permissions',\n locals: { user: user, perms: perms },\n formats: [:html])\n }\n }.to_json\n end",
"def permissions(ob, user, query)\n\n policy = ob.is_a?(Policy) ? ob : ob.contribution.policy\n\n def permission_node(view, download, edit, category, id = nil, layout = false)\n node = LibXML::XML::Node.new('permission')\n category_node = LibXML::XML::Node.new('category')\n category_node << category\n node << category_node\n if id\n id_node = LibXML::XML::Node.new('id')\n id_node << id\n node << id_node\n end\n if view\n privilege = LibXML::XML::Node.new('privilege')\n privilege['type'] = \"view\"\n node << privilege\n end\n if download\n privilege = LibXML::XML::Node.new('privilege')\n privilege['type'] = \"download\"\n node << privilege\n end\n if edit\n privilege = LibXML::XML::Node.new('privilege')\n privilege['type'] = \"edit\"\n node << privilege\n end\n if layout\n use_layout_node = LibXML::XML::Node.new('use-layout')\n use_layout_node << 'true'\n node << use_layout_node\n end\n\n if view || edit || download\n node\n else\n nil\n end\n end\n\n permissions = LibXML::XML::Node.new('permissions')\n permissions << permission_node([0,1,2].include?(policy.share_mode),\n policy.share_mode == 0,\n false,\n 'public')\n\n unless ob.is_a?(Policy)\n permissions['uri'] = rest_access_uri(policy)\n permissions['resource'] = rest_resource_uri(policy)\n permissions['id'] = policy.id.to_s\n permissions['policy-type'] = policy.group_policy? ? 'group' : 'user-specified'\n end\n\n policy.permissions.select {|p| p.contributor_type == \"Network\"}.each do |perm|\n permissions << permission_node(perm.view, perm.download, perm.edit, 'group', perm.contributor_id,\n policy.layout == perm.contributor.layout_name)\n end\n\n permissions\nend",
"def role_permissions\n return @role_permissions\n end",
"def perms_required_for( request )\n\t\tself.log.debug \"Gathering required perms for: %s %s\" % [ request.verb, request.app_path ]\n\n\t\t# Return the empty set if any negative auth criteria match\n\t\treturn [] if self.negative_perms_criteria_match?( request )\n\n\t\t# If there aren't any positive criteria, default to requiring authorization with\n\t\t# the app's ID as the permission\n\t\tif self.class.positive_perms_criteria.empty?\n\t\t\treturn [ self.default_permission ]\n\t\tend\n\n\t\t# Apply positive auth criteria\n\t\treturn self.union_positive_perms_criteria( request )\n\tend",
"def campus_patron_permissions\n anonymous_permissions\n end",
"def campus_patron_permissions\n anonymous_permissions\n end",
"def permissions_for_user_group(ug)\n sym = Lockdown.get_symbol(ug)\n perm_array = [] \n\n if has_user_group?(sym)\n permissions = user_groups[sym] || []\n else\n if ug.respond_to?(:permissions)\n permissions = ug.permissions\n else\n raise GroupUndefinedError, \"#{ug} not found in init.rb and does not respond to #permissions\"\n end\n end\n\n\n permissions.each do |perm|\n perm_sym = Lockdown.get_symbol(perm)\n\n unless permission_exists?(perm_sym)\n msg = \"Permission associated to User Group is invalid: #{perm}\"\n raise SecurityError, msg\n end\n\n perm_array << perm_sym\n end\n\n perm_array \n end",
"def get_fb_permissions\n if fb_access_token\n @graph = Koala::Facebook::API.new(fb_access_token)\n @graph.get_connections('me', 'permissions') rescue []\n else\n []\n end\n end",
"def permissions\n bv= 0\n @@bits.each do |a, v|\n bv |= instance_variable_get(\"@#{a}\") ? v : 0 \n end\n return bv\n end",
"def user_permission_keys\n new_record? ? [] : self.permissions(true).collect(&:key)\n end",
"def all_permissions\n return permissions unless role\n (permissions + role.permissions).uniq\n end",
"def get_current_privs\n query = @db_connection.query(\"SHOW GRANTS FOR current_user();\")\n query.each { |x| print_line(\"#{x[0]}\") }\n end",
"def get_permissions permissions_ds\n # default to rightsMetadata (like standard Hydra) if permissions_ds isn't set\n permissions_ds = \"rightsMetadata\" if permissions_ds.to_s == \"\"\n (datastreams[permissions_ds].groups.map {|x| {:type=>'group', :access=>x[1], :name=>x[0] }} + \n datastreams[permissions_ds].individuals.map {|x| {:type=>'user', :access=>x[1], :name=>x[0]}})\n\n (datastreams[permissions_ds].groups.map {|x| {:type=>'group', :access=>x[1], :name=>x[0] }} + \n datastreams[permissions_ds].individuals.map {|x| {:type=>'user', :access=>x[1], :name=>x[0]}})\n end",
"def permission?(permission_key)\n current_user_has_permission? permission_key\n end",
"def find_permissions\n\n return nil if @user.admin?\n\n groupnames = Group.find_groups(@user)\n\n StorePermission.find_all_by_groupname(groupnames).inject({}) do \n |result, permission|\n\n result[permission.storename] = permission\n result\n end\n end",
"def get_permission( model, action, options_for_permission )\n\n # Note 'ctrl' will be set to the *class*, not an instance. The exception\n # handler block lets us handle \"ModelsController\" in the common pluralized\n # case, then try \"ModelController\" in the unusual singleton resource case,\n # then drop out with 'nil' if something goes wrong.\n\n ctrl = begin\n \"#{ model.name.pluralize }Controller\".constantize\n rescue\n \"#{ model.name }Controller\".constantize\n end\n\n return true unless ctrl.nil? == false && ctrl.respond_to?( :hubssolib_permissions )\n\n # From-Artisan backwards compatibility: Options should be a User, but we\n # allow a hash with user_id too.\n\n if ( options_for_permission.is_a? Hash )\n user = User.find_by_id( options_for_permission[ :user_id ] )\n elsif ( logged_in? )\n user = controller.current_user() # (sic. - query current action's controller *instance* for current user)\n else\n user = nil\n end\n\n roles = HubSsoLib::Roles.new( user.nil? ? false : user.admin )\n permissions = ctrl.hubssolib_permissions()\n\n roles.clear if ( user.nil? )\n\n return permissions.permitted?( roles, action ) == true ? true : ''\n end",
"def get_permission_level\n if ( package_groups.length > 0)\n package_groups.order(\"permission_level asc\").first.permission_level\n else\n 0\n end\n end",
"def permissions?\n proprieties[:permissions]\n end",
"def permissions(username,path)\n # walk the path from the most specific to the least specific scanning the\n # rules at each way point, capturing any explicit user name match and merging\n # any matching group permissios. The first such match is the result\n #\n repo , dir = path.split(':')\n @path_routes.each do |point|\n next if !(path =~ /^#{point}/) && !(dir =~ /^#{point}/)\n gperms = []\n uperms = nil\n @paths[point].each do |selector,rule|\n fail \"Syntax error #{selector}='#{rule}'\" if rule.tr('^rw','')!=rule\n p = (rule=='rw')? ['r', 'w'] : [rule]\n if username==selector || @aliases[username]==selector\n uperms = p # user permssion\n elsif user_included?(username,selector)\n gperms |= p # group permission\n end\n end\n gperms |= [uperms] if !uperms.nil? # user perms extend group perms\n return gperms.sort.join('') if !gperms.empty?\n end\n '' # no matching rule\n end",
"def custom_permissions\n # Limits deleting objects to a the admin user\n #\n # if current_user.admin?\n # can [:destroy], ActiveFedora::Base\n # end\n\n # Limits creating new objects to a specific group\n #\n # if user_groups.include? 'special_group'\n # can [:create], ActiveFedora::Base\n # end\n end",
"def permissions(poll_path, polls = read_polls_data)\n poll = Poll.new(poll_path, polls)\n\n permissions = []\n\n permissions.push('vote') unless votes[poll.id]\n permissions.push('delete') if can_delete?(poll)\n permissions.push('reset') if username == 'admin'\n\n permissions\n end",
"def show\n @permissions = @role.permissions\n end",
"def permission\n perm = data.fetch(\"permissionSources\")\n .map { |i| i[\"permission\"] }\n .first\n .downcase\n GITHUB_TO_TERRAFORM_PERMISSIONS.fetch(perm)\n end",
"def custom_permissions\n can [:file_status, :stage, :unstage], FileSet\n\n if current_user.ingest_from_external_sources?\n end\n\n if current_user.manage_users?\n can [:show, :add_user, :remove_user, :index], Role\n end\n\n if current_user.manage_roles?\n can [:create, :show, :index, :edit, :update, :destroy], Role\n end\n\n if current_user.run_fixity_checks?\n can [:fixity], FileSet\n end\n # Limits deleting objects to a the admin user\n #\n # if current_user.admin?\n # can [:destroy], ActiveFedora::Base\n # end\n\n # Limits creating new objects to a specific group\n #\n # if user_groups.include? 'special_group'\n # can [:create], ActiveFedora::Base\n # end\n end",
"def access_rights_for_user(usr)\n return unless usr\n return :all if administrator?(usr)\n\n rights = standard_authorized_user_rights\n \n usr.user_groups.each do |grp|\n permissions_for_user_group(grp) do |perm|\n rights += access_rights_for_permission(perm) \n end\n end\n rights\n end",
"def get_permission_level\n if package_groups.length > 0\n package_groups.order(\"permission_level asc\").first.permission_level\n else\n 0\n end\n end",
"def permissions_info(sco_id, filter = nil)\n res = query(\"permissions-info\", \"acl-id\" => sco_id, \"filter\" => filter)\n\n return res.body\n data = XmlSimple.xml_in(res.body)\n if data['permissions'][0]\n return data['permissions'][0]\n end\n #puts YAML::dump(data)\n# if data[\"sco\"][0]\n# return data[\"sco\"][0]\n# end\n end",
"def custom_permissions\n # Limits deleting objects to a the admin user\n #\n # if current_user.admin?\n # can [:destroy], ActiveFedora::Base\n # end\n\n # Limits creating new objects to a specific group\n #\n # if user_groups.include? 'special_group'\n # can [:create], ActiveFedora::Base\n # end\n\n if current_user.admin?\n can [:create, :show, :add_user, :remove_user, :index, :edit, :update, :destroy], Role\n end\n\n# if current_user.contentadmin?\n# can [:create, :destroy], GwWork\n# can [:create, :destroy], GwEtd\n# end\n end",
"def defined_permissions\n FLAGS.collect { |value, name| (@bits & (1 << value)).positive? ? name : nil }.compact\n end",
"def can_access?\n allows_current_user_access_to? :access\n end",
"def custom_permissions\n # Limits deleting objects to a the admin user\n #\n # if current_user.admin?\n # can [:destroy], ActiveFedora::Base\n # end\nif current_user.admin?\n\t can [:create, :show, :add_user, :remove_user, :index], Role\n\t end\n # Limits creating new objects to a specific group\n #\n # if user_groups.include? 'special_group'\n # can [:create], ActiveFedora::Base\n # end\n\n\n\n end",
"def custom_permissions\n #Collection Manager Permissions\n #Higher power than edit user...[Dont want edit users to be able to DELETE a COLLECTION??, (Delete a DO?)]\n if current_user.applicable_policy?(SETTING_POLICY_COLLECTION_MANAGER)\n #Marked as being able to :manage_collection\n can :manage_collection_flag, :all\n can :create, [DRI::Batch, DRI::GenericFile]\n end\n\n\n #Admin Permissions\n if current_user.applicable_policy?(SETTING_POLICY_ADMIN)\n can :admin_flag, :all\n #Disabled for now..\n can :manage, :all\n end\n\n #Create_do flag (alias for :edit collection)\n can :create_do, String do |pid|\n test_create(pid)\n end\n\n can :create_do, DRI::Batch do |collection|\n test_create(collection)\n end\n end"
] |
[
"0.7721293",
"0.76671964",
"0.7524065",
"0.7485433",
"0.7480434",
"0.74454635",
"0.74011177",
"0.7354342",
"0.73300326",
"0.73300326",
"0.731497",
"0.72748226",
"0.7213902",
"0.71776867",
"0.7167066",
"0.7166284",
"0.7164",
"0.71080077",
"0.7106864",
"0.7092431",
"0.70769835",
"0.70696783",
"0.7033403",
"0.70310086",
"0.70187354",
"0.70139766",
"0.6994995",
"0.6991076",
"0.6964311",
"0.6954455",
"0.6919567",
"0.691092",
"0.6900459",
"0.6893229",
"0.68897367",
"0.68897367",
"0.6860971",
"0.6851628",
"0.6851628",
"0.68388385",
"0.681512",
"0.68108505",
"0.68094105",
"0.6808872",
"0.68012315",
"0.67702913",
"0.6760639",
"0.6741754",
"0.67244256",
"0.6721714",
"0.66862303",
"0.66717106",
"0.66640663",
"0.66385543",
"0.66344243",
"0.66214967",
"0.66131735",
"0.6583667",
"0.65548265",
"0.6546827",
"0.6546693",
"0.6543467",
"0.654012",
"0.65301317",
"0.6518579",
"0.6518579",
"0.6505726",
"0.65018773",
"0.64842826",
"0.6466033",
"0.6456538",
"0.6447587",
"0.64467657",
"0.64467657",
"0.64439887",
"0.6441257",
"0.6438435",
"0.6431321",
"0.6427544",
"0.64174473",
"0.6397978",
"0.63869077",
"0.63845325",
"0.6384015",
"0.6380205",
"0.63791174",
"0.6377762",
"0.6376164",
"0.63733816",
"0.6373185",
"0.6366507",
"0.6365007",
"0.6363452",
"0.635754",
"0.6349947",
"0.63447845",
"0.633193",
"0.63316625",
"0.632949",
"0.63259804"
] |
0.73144835
|
11
|
Required function, sets the user's permissions
|
def set_permissions(username,tags,is_admin = false)
begin
p = lookup_permissions(username)
if !p
# upsert
p = Permissions.create!
p.username = username
end
p[:tags] = tags
p[:is_admin] = is_admin
p.save!
if !p.persisted?
raise "Failed to save user data for #{username}"
end
return true
rescue
# TODO: log message?
return false
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_perms\n self.perms = Access.for_user(self)\n end",
"def add_user_permission(u)\n\t\t\n\tend",
"def set_permissions\n return if @permissions_set\n\n @permissions_set = true\n resource[:configure_permission] ||= configure_permission\n resource[:read_permission] ||= read_permission\n resource[:write_permission] ||= write_permission\n rabbitmqctl(\n 'set_permissions',\n '-p', should_vhost,\n should_user,\n resource[:configure_permission],\n resource[:write_permission],\n resource[:read_permission]\n )\n end",
"def set_user_permission(id, level)\n @permissions[:users][id] = level\n end",
"def setPermission( other_user, perm )\n if ( (not other_user.valid?) or ( other_user.is_a?(User) == false ) )\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n # d \"basic check failed\"\n # d other_user.type\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n return false\n end\n user = getUser()\n if ( other_user == user )\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n # d \"same user as owner\"\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n return true\n end\n if not self.special_users\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n # d \"creating special users group\"\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n self.special_users = {}\n end\n self.special_users[other_user.id.to_s] = perm\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n # d \"new permission:\"\n # d self.special_users\n # d \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n return true\n end",
"def set_permissions\n self.permissions ||= \"guest\"\n end",
"def setable_permissions\n setable_permissions = Erp::AccessControl.permissions - Erp::AccessControl.public_permissions\n setable_permissions -= Erp::AccessControl.members_only_permissions if builtin == BUILTIN_NON_MEMBER\n setable_permissions -= Erp::AccessControl.loggedin_only_permissions if builtin == BUILTIN_ANONYMOUS\n setable_permissions\n end",
"def set_permissions(*args)\n self.permissions = {}\n args.each do | permission |\n raise InvalidPermissionError.new(\"Permission #{permission} is invalid.\") unless ALLOWED_PERMISSIONS.include?(permission)\n self.permissions[permission] = true\n end\n end",
"def set_user\n @user = User.find(params[:id])\n \tauthorize [:admin, @user]\n end",
"def setPermissionEdit( other_user )\n return setPermission( other_user, Dfile::PP_MAYEDIT )\n end",
"def set_access(*args)\n options = args.extract_options!\n options[:object] ||= Array(@_controller).first.to_s.singularize.to_sym if @_controller.present?\n permissions.add(*args, options)\n end",
"def permissions=(value)\n @permissions = value\n end",
"def admin_grant_permissions\n @user = User.includes(:perms).find(params[:id])\n authorize @user\n user_perms = current_user.perms\n @perms = user_perms & [Perm.grant_permissions, Perm.modify_templates, Perm.modify_guidance, Perm.use_api, Perm.change_org_details]\n end",
"def user_permissions\n if user_signed_in? && (current_user.is_logistics? || current_user.is_clerical? || current_user.is_vendor? || current_user.is_customer?)\n authorize! :edit, Element\n end\n end",
"def set_user\n authorize\n @user = current_user\n end",
"def set_user\n @user = User.find(params[:user_id])\n authorize @user\n end",
"def create_user_permissions\n group.users.each do |user|\n create_permission_for(user)\n end\n end",
"def setPermissionView( other_user )\n return setPermission( other_user, Dfile::PP_MAYVIEW )\n end",
"def assign_permission\n company_admin,*company_admin_all = Role.company_admin.reorder(\"id ASC\")\n functions = company_admin.try(:function_ids) \n if company_admin_all.any?\n company_admin_all.each do |c_admin|\n c_admin.function_ids = functions\n end\n end\n end",
"def permits_write_access_for(user)\n end",
"def permissions = {}",
"def set_perms(data)\n permission = data[:permission] || 2 \n result = @client.api_request(\n :method => \"usergroup.massAdd\", \n :params => {\n :usrgrpids => [data[:usrgrpid]],\n :rights => data[:hostgroupids].map { |t| {:permission => permission, :id => t} }\n }\n )\n result ? result['usrgrpids'][0].to_i : nil\n end",
"def set_permission\r\n\r\n render :nothing => true\r\n return if params[:access_id].blank? || params[:set].blank?\r\n @access = Access.find(params[:access_id])\r\n return if @access.nil?\r\n @set = params[:set] == 'true'\r\n if params[:user_id]\r\n @user = User.find(params[:user_id])\r\n h = {:user_id => @user.id, :access_id => @access.id}\r\n if params[:prop]\r\n @ua = UserAccess.first(:conditions => h) || UserAccess.create(h)\r\n @ua.read = @set if params[:prop] == 'read'\r\n @ua.write = @set if params[:prop] == 'write'\r\n @ua.save\r\n else # aktion\r\n if @set\r\n UserAccess.create(h) unless UserAccess.exists?(h)\r\n else\r\n UserAccess.delete_all(h) if UserAccess.exists?(h)\r\n end\r\n end\r\n end\r\n if params[:profile_id]\r\n @profile = Profile.find(params[:profile_id])\r\n h = {:profile_id => @profile.id, :access_id => @access.id}\r\n if params[:prop]\r\n @pa = ProfileAccess.first(:conditions => h) || ProfileAccess.create(h)\r\n @pa.read = @set if params[:prop] == 'read'\r\n @pa.write = @set if params[:prop] == 'write'\r\n @pa.save\r\n else # aktion\r\n if @set\r\n ProfileAccess.create(h) unless ProfileAccess.exists?(h)\r\n else\r\n ProfileAccess.delete_all(h) if ProfileAccess.exists?(h)\r\n end\r\n end\r\n end\r\n end",
"def custom_permissions\n if current_user.admin?\n can :manage, :all\n end\n end",
"def set_user; end",
"def set_permissions(params, permissions_ds)\n # default to rightsMetadata (like standard Hydra) if permissions_ds isn't set\n permissions_ds = \"rightsMetadata\" if permissions_ds.to_s == \"\"\n perm_hash = permission_hash\n #params[:new_user_name].each { |name, access| perm_hash['person'][name] = access } if params[:new_user_name].present?\n params[:new_group_name].each { |name, access| perm_hash[\"group\"][name] = access } if params[:new_group_name].present?\n\n #params[:user].each { |name, access| perm_hash['person'][name] = access} if params[:user]\n params[:group].each { |name, access| perm_hash[\"group\"][name] = access} if params[:group]\n\n update_permissions(perm_hash, permissions_ds)\n end",
"def set_user\n @user = User.find(params[:id])\n authorize @user\n end",
"def set_user\n @user = User.find(params[:id])\n authorize @user\n end",
"def set_user\n @user = User.find(params[:id])\n authorize @user\n end",
"def update_permissions\n self.view_permission.update_attribute(:name, name + \" view\")\n self.signup_permission.update_attribute(:name, name + \" signup\")\n self.admin_permission.update_attribute(:name, name + \" admin\")\n end",
"def custom_permissions\n discover_permissions\n export_sets_permissions\n batches_permissions\n preservation_events_permissions\n end",
"def __set_synchromesh_permission_granted(old_rel, new_rel, obj, acting_user, args = [], &block)\n saved_acting_user = obj.acting_user\n obj.acting_user = acting_user\n new_rel.__synchromesh_permission_granted =\n obj.instance_exec(*args, &block) || (old_rel && old_rel.try(:__synchromesh_permission_granted))\n new_rel\n ensure\n obj.acting_user = saved_acting_user\n end",
"def set_privacy(user=nil,level=0)\n # TODO finish and test\n # currently 0 = public, 1 = public but read only, 2 = private, 3 = private and read only\n # in all cases if you are a member you can see it\n end",
"def set_user\n @user = User.find(params[:id])\n\n # only admins can CRUD non-regular users\n return if (@user.role == 'USER') || (current_user.role == 'ADMIN')\n render json: { error: 'Not allowed' }, status: :unauthorized\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def custom_permissions\n alias_action :show, :manifest, to: :read\n alias_action :color_pdf, :pdf, :edit, :browse_everything_files, :structure, :file_manager, to: :modify\n roles.each do |role|\n send \"#{role}_permissions\" if current_user.send \"#{role}?\"\n end\n end",
"def set_user\n\t\t@user = current_user\n\t\tif !current_user.is_admin?\n\t\t\t# redirects to the denied path if not\n\t\t\tredirect_to denied_path\n\t\tend\n\tend",
"def custom_permissions\n if user_groups.include?(\"admin\")\n can :manage, :all\n end\n end",
"def apply_superuser_permissions(permission_types)\n []\n end",
"def set_permissions_to(perm_level)\r\n unless self.relationshiptype_id == perm_level\r\n if self.new?\r\n self.relationshiptype_id = perm_level\r\n self.save! #for validation on create to happen\r\n else\r\n update_attribute(:relationshiptype_id, perm_level)\r\n end\r\n end\r\n \r\n if self.is_a?(Album)\r\n self.album_contents.each {|item| item.set_permissions_to(perm_level) }\r\n end\r\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def update!(**args)\n @permissions = args[:permissions] if args.key?(:permissions)\n end",
"def role_permissions=(value)\n @role_permissions = value\n end",
"def update!(**args)\n @permissions = args[:permissions] unless args[:permissions].nil?\n end",
"def update!(**args)\n @permissions = args[:permissions] unless args[:permissions].nil?\n end",
"def set_authorization\n @user ||= current_user\n authorize @user\n end"
] |
[
"0.7977588",
"0.7109746",
"0.70483655",
"0.70214736",
"0.6990836",
"0.6971471",
"0.6963179",
"0.69421303",
"0.69361514",
"0.69091797",
"0.6882876",
"0.68732065",
"0.68329626",
"0.68142605",
"0.66860443",
"0.66695046",
"0.66576314",
"0.6646836",
"0.6645479",
"0.6643446",
"0.6631748",
"0.6627323",
"0.6617078",
"0.6579389",
"0.6551315",
"0.65329915",
"0.65311676",
"0.65311676",
"0.6529042",
"0.65181595",
"0.65164405",
"0.65097386",
"0.6497058",
"0.64887595",
"0.64868486",
"0.64868486",
"0.64858717",
"0.6472362",
"0.64637226",
"0.6461961",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.6461733",
"0.64610267",
"0.6460485",
"0.6459971",
"0.6449755",
"0.6421218",
"0.64206433",
"0.64197576"
] |
0.6673354
|
15
|
Required function, enables a user
|
def enable_user(username)
begin
p = get_permissions(username)
if !p
raise "Username not found"
end
p[:enabled] = true
p.save!
if !p.persisted?
raise "Failed to save user data for #{username}"
end
return true
rescue
return false
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def enable\n account = Account.for(\"github\").with_username(params[:id]).first!\n @user = User.unscoped.where(id: account.user_id).first\n authorize! @user\n @user.enabled = true\n @user.save\n redirect_back fallback_location: root_path, notice: t(\"user.enabled\", name: @user.username)\n end",
"def enabled?\n user.present?\n end",
"def enable\n user = User.find_by_username params[:username]\n raise ActiveRecord::RecordNotFound unless user\n\n command = EnableUserCommand.new(user, current_user, request.remote_ip)\n begin\n command.execute\n rescue => e\n flash['error'] = \"#{e}\"\n else\n flash['success'] = \"User #{user.username} enabled.\"\n ensure\n redirect_back fallback_location: user_url(user)\n end\n end",
"def enable_admin\n if current_user.admin?\n user = User.find(params[:id])\n user.update_attribute(\"admin\", true)\n redirect_to \"/users\"\n else\n redirect_to \"/home\"\n flash[:warning] = \"Only admins can perform that action.\"\n end\n end",
"def approve_user\n # set the enabled flag to true for the user\n # send out approval notification\n end",
"def change_is_enabled\n member = Member.find params[:id]\n user = User.find(member.user_id)\n Member.change_student_status(member)\n if member.is_enabled == true\n redirect_to users_url, :flash => { :success => \"#{user.first_name} #{user.last_name} has been enabled.\" }\n else\n redirect_to users_url, :flash => { :success => \"#{user.first_name} #{user.last_name} has been disabled.\" }\n end\n end",
"def enable_or_disable\n @user = User.find(params[:id])\n begin\n if(@user.user_type == 'e')\n @user.user_type = 'd'\n if(@user.update_attributes(params[:user]))\n flash[:notice] = \"User #{@user.name} disabled\"\n end\n else if(@user.user_type == 'd')\n @user.user_type = 'e'\n if(@user.update_attributes(params[:user]))\n flash[:notice] = \"User #{@user.name} enabled\"\n end\n end\n end\n rescue Exception => e\n flash[:notice] = \"Exception in enable_or_disable: \" + e.message\n end\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def disabled?\n user.nil?\n end",
"def require_user\n end",
"def activate_user(user)\n user.status_id=0\n user.save\n end",
"def allow_user(user_id)\n create_entry(user_id, USER, true)\n end",
"def enable\n end",
"def activate\n @user.activate! if @user.pending?\n redirect_to root_url\n end",
"def user_onoff_flag\n @requested_user = User.find_by_account_number(params[:id])\n if @requested_user.is_active?\n @requested_user.update_columns(:is_active => false)\n redirect_to admin_index_path, :flash => {:notice => \"Requested user(#{@requested_user.first_name} #{@requested_user.last_name}) account successfully de-activated.\"}\n else\n @requested_user.update_columns(:is_active => true)\n redirect_to admin_index_path, :flash => {:notice => \"Requested user(#{@requested_user.first_name} #{@requested_user.last_name}) account successfully activated.\"}\n end\n end",
"def activate!(user)\n return false if self.active?\n\n @user = user\n\n create_hook!\n\n self.active = true\n self.save!\n end",
"def set_user; end",
"def make_first_user_admin\n return unless User.count.zero?\n\n self.is_admin = true\n self.approved = true\n end",
"def user_enabled\n redirected = false\n if ((producer_signed_in? && current_producer.enabled == false) || (customer_signed_in? && current_customer.enabled==false)) && redirected == false\n redirected = true\n render 'producers/not_allowed'\n end\n false\n end",
"def admin_enable_otp\n user = User.find(params[:id])\n authorize! :edit, @user #prevent other users from enabling OTP on another user.\n user.otp_secret = User.generate_otp_secret\n user.otp_required_for_login = true\n user.save!\n redirect_back(fallback_location: '/')\n end",
"def enable\n end",
"def require_valid_user!\n return true\n end",
"def is_require_accepting_user_to_match_invited_user_enabled=(value)\n @is_require_accepting_user_to_match_invited_user_enabled = value\n end",
"def toggle_enable_expiry\n @user = User.find(params[:id])\n\n respond_to do |format|\n @nav = 'show_nav'\n if (@local_manager.slave?)\n flash[:warning] = \"This action is prohibited on slave systems.\"\n format.html { redirect_to user_url(@user) }\n format.xml { render :xml => '<errors><error>This action is prohibited on slave systems.</error></errors>', :status => :not_acceptable }\n else\n @user.toggle_enable_expiry!\n @local_manager.log(:username => @session_user.username, :user_id=> @user.id, :message => \"Toggled enable expiry (current=#{@user.enable_password_expired?}) for user #{@user.username}.\")\n flash[:notice] = \"You must publish this user before changes will take effect on TACACS+ daemons.\"\n format.html { redirect_to user_url(@user) }\n format.xml { head :ok }\n end\n end\n end",
"def make_admin\n @user = User.find(params[:user_id])\n @user.admin = !@user.admin\n @user.save\n redirect_to users_path\n end",
"def is_potential_user?\n\t\ttrue\n\tend",
"def on_users_account\n true\n end",
"def approve\n @user.state = User::ENABLED\n @user.save\n \n respond_to do |format|\n format.html { redirect_to(registrations_users_path, :notice => \"User registration was successfully approved.\") }\n format.xml { head :ok }\n end\n end",
"def enabled!\n self\n end",
"def check_enabled\n return if current_user.enabled\n\n render(json: format_error(request.path, \"Estas inhabilitado\"), status: 401)\n end",
"def user\n\t\tfalse\n\tend",
"def activate\n user = User.find_by_username params[:username]\n if user && user.activation == params[:activation]\n user.activation = \"ACTIVATION_ACTIVE\"\n user.save()\n render status: 200, json: {error: false}\n else\n render status: 403, json: {error: true}\n end\n end",
"def disable\n authorize! @user\n @user.enabled = false\n @user.save\n @user.owned_extensions.update_all(enabled: false)\n redirect_to root_path, notice: t(\"user.disabled\", name: @user.username)\n end",
"def applies_to?(user); false end",
"def allow_user_submit(user)\n current? and !expired_for_user(user)\n end",
"def allow_user_submit(user)\n current? and !expired_for_user(user)\n end",
"def allow_user_submit(user)\n current? and !expired_for_user(user)\n end",
"def admin_reactivate\n user = User.find(params[:id])\n authorize! :edit, @user #prevent other users from disabling OTP on another user.\n user.deactivated = false\n user.save!\n flash[:notice] = \"Successfully Reactivated user.\"\n redirect_back(fallback_location: '/')\n end",
"def set_user\n @user = User.friendly.find(params[:id])\n if @user.banned\n require_admin\n end\n end",
"def enable\n key = SecurityKey.find_by_key(params[:key])\n if key\n if request.post?\n if params[:acceptance] == 'yes'\n account = key.securable\n account.update(password: params[:password])\n account.authenticate(session, cookies)\n key.destroy\n redirect_to homepage_url and return\n else\n flash.now[:error] = 'Please accept the Terms of Service.'\n end\n end\n else\n redirect_to login_url, flash: {error: 'That account is invalid or has already been activated.'} and return\n end\n end",
"def active_for_authentication? \n \tsuper && approved?\n \t\n\tend",
"def gt_enable!\n unless self.gt_enabled?\n self.gt_enabled = true\n\n self.cohorts << Settings::User.current_cohort unless self.cohorts.include? Settings::User.current_cohort\n GT::UserManager.ensure_users_special_rolls(self, true)\n\n self.save(:validate => false)\n\n public_roll = self.public_roll\n if (self.user_type == User::USER_TYPE[:real] || self.user_type == User::USER_TYPE[:converted])\n public_roll.roll_type = Roll::TYPES[:special_public_real_user]\n end\n public_roll.save(:validate => false)\n end\n end",
"def enable\n {\n method: \"Security.enable\"\n }\n end",
"def grant\n self.status = 'granted'\n save\n end",
"def authen_method_enable!()\n @authen_method = TAC_PLUS_AUTHEN_METH_ENABLE\n end",
"def enable!; end",
"def check_user_status\n user = current_user\n if user && user.status != 2\n redirect_to signupcode_settings_path\n end\n end",
"def update? ; user.account.active? ; end",
"def activate_account!\n update_attribute :is_active, true\n end",
"def update?\n @current_user.permission('Bid', :clerk)\n end",
"def set_user_tasking_mode_on\r\n if @current_user.facebook_user?\r\n @current_user.is_tasking = true\r\n @current_user.save(false)\r\n else\r\n @current_user.update_attribute(:is_tasking, true)\r\n end\r\n end",
"def disable\n\t\tif user = check_admin\n\t\t\ttarget_user = User.find_by(id: params[:id])\n\t\t\ttarget_user.toggle!(:enabled)\n\t\t\tredirect_back fallback_location: '/home'\n\t\tend\n\tend",
"def super_check\n if self.user_name == 'profbill'\n self.admin = true\n self.suspended = false\n self.icon = \"hand-peace-o\"\n end\n end",
"def requires_user_existence!\n if not e.user_exists?\n error \"You have to setup your user before you can perform this action.\"\n exit\n end\n end",
"def valid_user\n # unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id])) \n unless(@user && @user.activated?)\n redirect_to root_url\n end\n end",
"def set_Enable(value)\n set_input(\"Enable\", value)\n end",
"def enabled!\n self\n end",
"def edit\n require_user\n end",
"def enable!\n self.enabled = true\n end",
"def check_user_background\n self.status = Status::PENDING_ADMIN_ACTION if offender && offender.new_user?\n end",
"def activate\n if @user.inactive? && @user.created_by_admin?\n if @user.is_regular? && @user.profile.penultimate_step_complete?\n @user.activate!\n @user.save_profinda_profile\n render json: { status: 'active' }\n elsif @user.is_external? && @user.profile.first_step_completed?\n @user.activate!\n render json: { status: 'active' }\n else\n render json: { status: 'user can\\'t be activate' }\n end\n else\n render json: { status: 'user is active' }\n end\n end",
"def make_user\n end",
"def make_admin\n puts \"Creating Admin\"\n user = User.create!(:name => \"Admin\",\n :email => \"admin@home.no\",\n :password => \"adminpw\",\n :password_confirmation => \"adminpw\")\n user.toggle!(:admin)\n user.toggle!(:staff)\nend",
"def require_activation!\n self.enabled = false\n self.activation_code = Digest::MD5.hexdigest(self.object_id.to_s + Rauth::Encode.mksalt).upcase\n end",
"def admin_approve_user\n @user.update(approved: true)\n redirect_to admin_path, notice: \"User Approved\"\n end",
"def instruct_user!\n end",
"def permit\n user = User.find(params[:user_id])\n group = Group.find(params[:id])\n membership = Membership.find_by(user: user, group: group)\n if membership\n membership.update_column(:active, true)\n membership.touch # For showing on dashboard.\n end\n redirect_back fallback_location: '/'\n end",
"def become_user\n authorize User\n \n allowed = if current_user.is_core?\n session[:became_user] = true unless session[:became_user]\n session[:superuser_id] = current_user.id unless session[:superuser_id]\n become_user = User.find(params[:id])\n sign_in(:user, become_user)\n flash[:notice] = \"You are logged in as #{become_user.gamer.to_label}\"\n true\n else\n false\n end\n \n respond_to do |format|\n if allowed\n format.html { redirect_to root_path }\n else\n format.html { render_404 }\n end\n end\n end",
"def create?\n @current_user.permission('Bid', :clerk)\n end",
"def enabling_autoshare?\n params[:user][:autoshare_prefs].any? do |p|\n params[:user][:autoshare_prefs][p] == \"1\"\n end\n end",
"def approve!\n self.update_attribute(:status, ConfigCenter::User::APPROVED)\n end",
"def ensure_user\n current_user? || deny_access('You must be logged in to perform this action.')\n end",
"def set_user\n @user = User.find(params[:id])\n \tauthorize [:admin, @user]\n end",
"def activate_user(user_id)\n post(\"/users/#{user_id}/activate\")\n end",
"def activate\r\n Marketplace::Database.instance.delete_deactivated_user(self)\r\n Marketplace::Database.instance.add_user(self)\r\n Marketplace::Activity.create(Activity.USER_REACTIVATE, self, \"#{self.name} has been reactivated\")\r\n end",
"def enable_operation?(user,type=0)\n case self.current_state\n when ::WtypCzb::State::LOGGED\n if type ==0 \n return false\n else\n return true\n end\n when ::WtypCzb::State::ASSIGNED\n info = ( is_enabled(user) and user.hcz_czbl == 1 and self.czfzr.to_i == user.id)\n if (info.class==FalseClass) then\n return false\n else\n return true\n end\n when ::WtypCzb::State::FILLED\n info = ( is_enabled(user) and user.hcz_czsh == 1)\n if (info.class==FalseClass) then\n return false\n else\n return true\n end \n when ::WtypCzb::State::PASSED\n return false\n end\n end",
"def enable_otp\n current_user.otp_secret = User.generate_otp_secret\n current_user.otp_required_for_login = true\n current_user.save!\n redirect_back(fallback_location: '/')\n end",
"def status_getuser!()\n @status = TAC_PLUS_AUTHEN_STATUS_GETUSER\n end",
"def activate\n @user = User.find(params[:id])\n @user.activate\n redirect_to :back\n end",
"def status_getuser?()\n return true if (@status == TAC_PLUS_AUTHEN_STATUS_GETUSER)\n return false\n end",
"def activate\n authorize current_user\n\n user = User.find(params[:id])\n return if user.blank?\n\n begin\n user.active = !user.active\n user.save!\n render json: {\n code: 1,\n msg: format(_(\"Successfully %{action} %{username}'s account.\"),\n action: user.active ? _('activated') : _('deactivated'),\n username: user.name(false))\n }\n rescue StandardError\n render json: {\n code: 0,\n msg: format(_('Unable to %{action} %{username}'),\n action: user.active ? _('activate') : _('deactivate'),\n username: user.name(false))\n }\n end\n end",
"def active_for_authentication?\n # User is approved when harp_id is assigned.\n # Approved flag is set programmatically when harp_id is set by an admin.\n super && is_approved?\n end",
"def active_for_authentication? \n super && is_approved? \n end",
"def active_for_authentication? \n super && approved? \n end",
"def enable\n if disabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['512']\n )\n refresh\n else\n true\n end\n end",
"def is_active(user)\n user.status_id != 0\n end",
"def manage?\n super || (@user && @user.is_curator?)\n end",
"def creatable_by?(user)\n user.administrator?\n end",
"def update_user\n end",
"def set_user\n @user = User.find(params[:user_id])\n authorize @user\n end",
"def editable? usr\r\n (seller?(usr) || pixter?(usr) || usr.has_role?(:admin)) || usr.has_role?(:support)\r\n end",
"def is_user?\n user ? true : false\n end",
"def enable_authorize_button\n # @ui.authorize_button.enable(true)\n end",
"def isAllowUser(request) \n return httpRequest('check_newuser',request)\n end",
"def enable\n @enabled = true\n end",
"def admin_required\n session[:user_id] && (user = User.find(session[:user_id])) && user.is_admin\n end",
"def alert_user?\n # check the three necessary conditions\n # in order of increasing cost\n self.enabled? && have_statuses_changed?\n end",
"def require_user\r\n if ##LOGIC##\r\n redirect_to '/user/sign_in'\r\n end\r\n end",
"def user?\n get_mode == :user\n end",
"def active_user\n user = pending_user\n user.activate! if user.valid?\n user\n end",
"def permitted?; end"
] |
[
"0.7553401",
"0.75487393",
"0.7347638",
"0.72980523",
"0.7216887",
"0.71703404",
"0.703553",
"0.6938965",
"0.6922789",
"0.6870529",
"0.686023",
"0.6708095",
"0.6679455",
"0.6674792",
"0.6631365",
"0.6609623",
"0.65958905",
"0.6594616",
"0.65693635",
"0.65651494",
"0.65570587",
"0.6520724",
"0.6519605",
"0.6462679",
"0.64424574",
"0.64302546",
"0.6419696",
"0.64138293",
"0.6396623",
"0.63944614",
"0.63486874",
"0.63484925",
"0.63417596",
"0.6326183",
"0.6326183",
"0.6326183",
"0.6317124",
"0.6311778",
"0.63097006",
"0.6309369",
"0.6307571",
"0.6303122",
"0.63017416",
"0.6301429",
"0.6300963",
"0.62969977",
"0.6278082",
"0.62760234",
"0.6271674",
"0.62634355",
"0.6262204",
"0.62560934",
"0.6255286",
"0.625526",
"0.6254071",
"0.62374663",
"0.62342036",
"0.6232836",
"0.62307966",
"0.62305063",
"0.62302417",
"0.6228873",
"0.6228271",
"0.62230706",
"0.6215093",
"0.62135184",
"0.6211132",
"0.62105423",
"0.6203755",
"0.6202102",
"0.62008846",
"0.6198504",
"0.619351",
"0.6190468",
"0.61897284",
"0.6187703",
"0.61846405",
"0.6176265",
"0.6173142",
"0.6166957",
"0.61586577",
"0.61579114",
"0.6154909",
"0.61514753",
"0.61377317",
"0.6128734",
"0.61270267",
"0.61264753",
"0.6120897",
"0.6119798",
"0.6107573",
"0.60937005",
"0.60927653",
"0.60927063",
"0.6092093",
"0.6088926",
"0.60872537",
"0.60840374",
"0.6077244",
"0.6073953"
] |
0.7260108
|
4
|
Required function, disables a user
|
def disable_user(username)
begin
p = get_permissions(username)
if !p
raise "Username not found"
end
p[:enabled] = false
p.save!
if !p.persisted?
raise "Failed to save user data for #{username}"
end
return true
rescue
return false
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def disable\n\t\tif user = check_admin\n\t\t\ttarget_user = User.find_by(id: params[:id])\n\t\t\ttarget_user.toggle!(:enabled)\n\t\t\tredirect_back fallback_location: '/home'\n\t\tend\n\tend",
"def disable\n authorize! @user\n @user.enabled = false\n @user.save\n @user.owned_extensions.update_all(enabled: false)\n redirect_to root_path, notice: t(\"user.disabled\", name: @user.username)\n end",
"def disable!(current_user: nil, force_save: false)\n force_save! if force_save\n self.current_user ||= current_user\n update! disabled: true\n end",
"def disabled?\n user.nil?\n end",
"def disable\n user = User.find_by_username params[:username]\n raise ActiveRecord::RecordNotFound unless user\n\n command = DisableUserCommand.new(user, current_user, request.remote_ip)\n begin\n command.execute\n rescue => e\n flash['error'] = \"#{e}\"\n else\n flash['success'] = \"User #{user.username} disabled.\"\n ensure\n redirect_back fallback_location: user_url(user)\n end\n end",
"def disable_user(handle)\n request(Net::HTTP::Delete, \"/api/#{API_VERSION}/user/#{handle}\", nil, nil, false)\n end",
"def disable_admin\n if current_user.admin?\n user = User.find(params[:id])\n user.update_attribute(\"admin\", false)\n redirect_to \"/users\"\n else\n redirect_to \"/home\"\n flash[:warning] = \"Only admins can perform that action.\"\n end\n end",
"def destroy\n @user = User.find(params[:id])\n if @user.update_attribute(:enabled, false)\n flash[:notice] = \"User disabled\"\n else\n flash[:error] = \"There was a problem disabling this user.\"\n end\n redirect_to users_url\n end",
"def disable!\n @disabled = true\n end",
"def disable\n end",
"def reject_user\n # set the enabled flag to false for the user\n # clear activation code (prevents user from showing up as pending user)\n # send out rejection notification\n end",
"def disable\n @disabled = true\n end",
"def enable_or_disable\n @user = User.find(params[:id])\n begin\n if(@user.user_type == 'e')\n @user.user_type = 'd'\n if(@user.update_attributes(params[:user]))\n flash[:notice] = \"User #{@user.name} disabled\"\n end\n else if(@user.user_type == 'd')\n @user.user_type = 'e'\n if(@user.update_attributes(params[:user]))\n flash[:notice] = \"User #{@user.name} enabled\"\n end\n end\n end\n rescue Exception => e\n flash[:notice] = \"Exception in enable_or_disable: \" + e.message\n end\n respond_to do |format|\n format.html { redirect_to(users_url) }\n format.xml { head :ok }\n end\n end",
"def revoke_on_unenroll_disabled=(value)\n @revoke_on_unenroll_disabled = value\n end",
"def disable_two_factor(user_id)\n patch(\"/users/#{user_id}/disable_two_factor\")\n end",
"def disableUserInput _args\n \"disableUserInput _args;\" \n end",
"def disable_expired_users()\n confluence_user_names.each do |name|\n next if name == \"conflusa\" \n ldap_person = find_in_ldap(name)\n \n if ldap_person.nil? || !eligible_for_confluence?(ldap_person)\n user = find_in_confluence(name)\n user.disable()\n @disabled_users << user \n end\n end\n end",
"def disable!\n @enabled = false\n end",
"def disable_autogrow\n change_autogrow_status_link.click\n autogrow_status_select.select('No')\n submit_autogrow_status_btn.click\n wait_until{ success_messages == \"Autogrow protection disabled.\" }\n end",
"def disable\n {\n method: \"Security.disable\"\n }\n end",
"def deactivate!(user)\n return false unless self.active?\n\n @user = user\n\n remove_hook!\n\n self.active = false\n self.save!\n end",
"def disabled; end",
"def disable\n {\n method: \"WebAuthn.disable\"\n }\n end",
"def disable!\n @active = false\n change_status(:disabled)\n end",
"def deny_user(user_id)\n create_entry(user_id, USER, false)\n end",
"def disable!\n @enabled = false\n end",
"def denied\n end",
"def disable\n if enabled?\n Cratus::LDAP.replace_attribute(\n dn,\n Cratus.config.user_account_control_attribute,\n ['514']\n )\n refresh\n else\n true\n end\n end",
"def disable!\n self.enabled = false\n end",
"def revoke_on_unenroll_disabled\n return @revoke_on_unenroll_disabled\n end",
"def disable(other_user, reason)\n return false unless other_user&.system_admin?\n return false if other_user == self\n\n update_columns(\n disabled_by: other_user.email,\n disabled_at: Time.now,\n disabled_reason: reason,\n enabled: false\n ) && refresh_comments\n end",
"def disabled!\n self\n end",
"def disabled?; end",
"def disabled?; end",
"def deny_user(id)\n post(\"users/#{id}/deny\").user\n end",
"def disabled=(_arg0); end",
"def twofa_disable\n if current_user.update_attributes( :gauth_enabled => false )\n flash[:info] = \"Two-factor authentication has been disabled\"\n redirect_to admin_twofa_path\n return\n end\n \n flash[:error] = \"Something went wrong while trying to turn off two-factor authentication\"\n redirect_to admin_change_password_path\n end",
"def disable\n @enabled = false\n end",
"def toggle_disabled\n @user = User.find(params[:id])\n blue = params[:blue].to_i\n\n respond_to do |format|\n @nav = 'show_nav'\n if (@local_manager.slave?)\n format.html do\n render :update do |page|\n page.replace_html('flash_box' , '<p class=\"flash_warning\">This action is prohibited on slave systems.</p>')\n page.show('flash_box')\n page << \"new Effect.Fade('flash_box', { delay: 4.0 });\"\n end\n end\n format.xml { render :xml => '<errors><error>This action is prohibited on slave systems.</error></errors>', :status => :not_acceptable }\n elsif (@user.admin? && @session_user.user_admin?)\n format.html do\n render :update do |page|\n page.replace_html('flash_box' , '<p class=\"flash_warning\">You do not have permission to modify administrator accounts.</p>')\n page.show('flash_box')\n page << \"new Effect.Fade('flash_box', { delay: 4.0 });\"\n end\n end\n format.xml { render :xml => @user.errors, :status => :not_acceptable }\n else\n @user.toggle_disabled!\n @local_manager.log(:username => @session_user.username, :user_id=> @user.id, :message => \"Set account status = #{@user.account_status} for user #{@user.username}.\")\n format.html do\n render :update do |page|\n if @user.disabled?\n page.replace(\"user#{@user.id}\" , :partial => 'user_index',\n :locals => { :user => @user, :blue => blue, :user_class => 'disabled' })\n elsif (blue == 1)\n page.replace(\"user#{@user.id}\" , :partial => 'user_index',\n :locals => { :user => @user, :blue => blue, :user_class => 'shaded' })\n else\n page.replace(\"user#{@user.id}\" , :partial => 'user_index',\n :locals => { :user => @user, :blue => blue, :user_class => 'light_shaded' })\n end\n end\n end\n format.xml { head :ok }\n end\n end\n end",
"def disable\n unless @employee.can_be_disabled?\n redirect_to :back, :alert => \"First remove all assigned asset from #{@employee.name}\"\n else\n @employee.soft_delete! \n redirect_to :back, :notice => \"Employee #{@employee.name} has been disabled successfully\"\n end\n end",
"def deactivate\n admin = Administrator.find_by_user_id(params[:id])\n admin.status = false\n admin.save\n @users = User.all\n render 'index'\n end",
"def inactive_user(user_id)\n\tUserMission.find_by(user_id: user_id) ? false : true\nend",
"def deactivate_user_old(uid, pid)\n\n #user_id = \"f6059d2cd367193ac21f1af2b639a78f\"\n\n headers = {:x_storageapi_token => @kbc_api_token, :accept => :json, :content_type => :json}\n\n query = \"/gdc/projects/#{pid}/users\"\n\n payload = \"{\\\"user\\\": { \\\"content\\\": { \\\"status\\\": \\\"DISABLED\\\", \\\"userRoles\\\": [ \\\"/gdc/projects/#{pid}/roles/2\\\" ]}, \\\"links\\\": {\\\"self\\\": \\\"/gdc/account/profile/#{uid}\\\"}}}\"\n\n values = \"{\\n \\\"writerId\\\": \\\"#{@writer_id}\\\",\\n \\\"query\\\": \\\"#{query}\\\",\\n \\\"payload\\\": #{payload}\\n}\"\n\n response = RestClient.post \"#{@api_endpoint}/proxy\", values, headers\n\n return response\n\n end",
"def unscrape?\n @user.is_admin?\n end",
"def disable\n exclusively do\n @enabled = false\n @manual_toggle = true\n end\n\n save_state\n sync_control { stop_upkeep }\n end",
"def disable_flip\n # TODO: force a login\n begin\n jwt_payload = JWT.decode(params[:token], Rails.application.secrets.secret_key_base).first\n current_user_id = jwt_payload[\"id\"]\n Flipper[:beta_button].disable current_user if current_user && current_user.id == current_user_id\n rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError\n # head :unauthorized\n end\n redirect_to root_path\n end",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def disable_password_reset(username, first, last, app,config)\n puts \" Setting password reset to false for |#{username}|.\" if $options.verbose\n # need to get the admin setting code put in place NOTENOTENOTE\n # if config['source']['admins'].include?(nickname)\n # admin = true\n # else\n # admin = false\n # end\n admin = false\n begin\n result = app.provision.update_user(username, first, last, nil, nil, admin.to_s, nil, \"false\", nil )\n STDERR.puts \"Result: #{result}\" if $options.debug\n update = true\n rescue GData::GDataError => e\n if e.code == \"1300\"\n STDERR.puts \" => Set password reset to false #{username} exists\" if $options.verbose\n update = true\n elsif e.code == \"1000\"\n STDERR.puts \" => setting password reset to false #{username} unknown error\" if $options.verbose\n update = false\n #retry\n else\n STDERR.puts \"Error creating user: #{username}\" if $options.verbose\n raise e\n end\n end\nend",
"def disabled?\n\t\t\tuserAccountControl.to_i & UAC_ACCOUNT_DISABLED != 0\n\t\tend",
"def disable\n @bill.update_attribute :is_recurring, false\n account = Account.find(@bill.account_id)\n user = User.find(account.user_id)\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end",
"def admin_reactivate\n user = User.find(params[:id])\n authorize! :edit, @user #prevent other users from disabling OTP on another user.\n user.deactivated = false\n user.save!\n flash[:notice] = \"Successfully Reactivated user.\"\n redirect_back(fallback_location: '/')\n end",
"def disable\n @service.disabled = true\n end",
"def disable!\n @mutex.synchronize do\n @advised.each { | x | x.disable! }\n end\n self\n end",
"def disabled?\n false\n end",
"def disable\n {\n method: \"DOM.disable\"\n }\n end",
"def destroy\n @user = User.find(params[:id])\n\n if @user.admin? && User.admin_count == 1\n message = 'Can not disable last admin user.'\n else\n @user.disable\n message = 'User was successfully disabled.'\n end\n\n respond_to do |format|\n flash[:notice] = message\n format.html { redirect_to users_url }\n format.xml { head :ok }\n end\n end",
"def enabled?\n user.present?\n end",
"def disable(&block)\n @disable_block = block\n end",
"def disable(item)\n run(\"no #{ item }\")\n end",
"def disable_subject\n enable_disable_subject('Disabled')\n end",
"def no_login(user)\n # nada\n end",
"def deletable_by?(user)\n false\n end",
"def receive_disabled\n\n wrap_reply('disable' => Flor.true?(payload['ret']))\n end",
"def disable_check_box?(user)\n !((user.role?(\"team_manager\") || user.role?(\"secretary\")) && (user.eql?(current_user) || is_team_manager))\n end",
"def deactivate\n\t @user.update(:active => false)\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def disable\n \n orignial_state = @enabled\n @enabled = false\n \n if block_given?\n yield\n @enabled = orignial_state\n end\n \n return self\n \n end",
"def deny()\n if update_attributes({:level => Membership::LEVELS[:denied]})\n true\n else\n reload\n false\n end\n end",
"def deactivate\n @user = User.find(params[:id])\n @user.deactivate\n redirect_to :back\n end",
"def deny\n self.status = 'denied'\n save\n end",
"def block!\n self.update_attribute(:status, ConfigCenter::User::BLOCKED)\n end",
"def disableAI _obj, _args\n \"_obj disableAI _args;\" \n end",
"def deactivate_user(user_id)\n post(\"/users/#{user_id}/deactivate\")\n end",
"def disable(thing)\n toggle.disable(thing)\n end",
"def admin_deny_user\n @user.destroy\n redirect_to admin_path, notice: \"User Denied and Account Deleted\"\n end",
"def disable(id)\n change_status id, false\n end",
"def remove_readonly_user(opts)\n opts = check_params(opts,[:ro_user_info])\n super(opts)\n end",
"def disabled(&_block)\n @disabled = true\n yield\n ensure\n @disabled = false\n end",
"def unblock_user\n SecurityService.unblock_user(params[:id])\n redirect_to '/users/', notice: \"Käyttäjän blokkaus poistettu. Hän voi taas luoda kursseja.\"\n end",
"def read_only_disabled\n if !(@restaurant.creator_id == @review.user_id) \n \"disabled\"\n end\n end",
"def unban\n self.enabled = true\n save\n end",
"def disable\n {\n method: \"Page.disable\"\n }\n end",
"def off_org_users\n \n end",
"def is_disabled(user)\n ## check user\n return true if user.nil?\n\n ## check user custom field\n user_cf = UserCustomField.find_by_name(\"Hangouts Chat Disabled\")\n return true if user_cf.nil?\n\n ## check user custom value\n user_cv = user.custom_value_for(user_cf)\n\n ## user_cv is null\n return false if user_cv.nil?\n\n return true if user_cv.value == '1'\n\n return false\n end",
"def deactive\n user = User.find(params[:id])\n user.toggle!(:active)\n user.save\n if user.active == true \n redirect_to users_path, :notice => \"Activate User #{user.userName}\"\n else \n flash[:error] = \"Deactivate User #{user.userName}\"\n redirect_to users_path \n end\n end",
"def deny\n @ride = current_user.fares.find_by_id(params[:ride])\n @ride.deny(User.find_by_id(params[:passenger]))\n redirect_to user_path(current_user)\n end",
"def may_not_be_user_required\n\t\tcurrent_user.may_not_be_user?(@user) || access_denied(\n\t\t\t\"You may not be this user to do this\", user_path(current_user))\n\tend",
"def toggle_enable_expiry\n @user = User.find(params[:id])\n\n respond_to do |format|\n @nav = 'show_nav'\n if (@local_manager.slave?)\n flash[:warning] = \"This action is prohibited on slave systems.\"\n format.html { redirect_to user_url(@user) }\n format.xml { render :xml => '<errors><error>This action is prohibited on slave systems.</error></errors>', :status => :not_acceptable }\n else\n @user.toggle_enable_expiry!\n @local_manager.log(:username => @session_user.username, :user_id=> @user.id, :message => \"Toggled enable expiry (current=#{@user.enable_password_expired?}) for user #{@user.username}.\")\n flash[:notice] = \"You must publish this user before changes will take effect on TACACS+ daemons.\"\n format.html { redirect_to user_url(@user) }\n format.xml { head :ok }\n end\n end\n end",
"def is_disabled(user)\n\t\tflag = AssignmentFlag.find_by_assignment_id_and_user_id(self.id, user.id)\n\t\tif(flag.blank?)\n\t\t\treturn self.disabled\n\t\telse\n\t\t\treturn flag.disabled\n\t\tend\n\tend",
"def deactivate\n @this_user.update_attributes(:active => false)\n redirect_to :controller => 'user', :action => 'view', :display_name => params[:display_name]\n end",
"def require_admin\n deny_wrong_user if !admin?\n end",
"def disable_optional_module(user, optional_module, name)\n old_controller = @controller\n sign_in user\n @controller = Admin::OptionalModulesController.new\n patch :update, params: { id: optional_module, optional_module: { enabled: '0' } }\n assert_equal name, assigns(:optional_module).name\n assert_not assigns(:optional_module).enabled, 'Module should be disabled'\n assert_redirected_to admin_optional_module_path(assigns(:optional_module))\n sign_out user\n ensure\n @controller = old_controller\n end",
"def change_is_enabled\n member = Member.find params[:id]\n user = User.find(member.user_id)\n Member.change_student_status(member)\n if member.is_enabled == true\n redirect_to users_url, :flash => { :success => \"#{user.first_name} #{user.last_name} has been enabled.\" }\n else\n redirect_to users_url, :flash => { :success => \"#{user.first_name} #{user.last_name} has been disabled.\" }\n end\n end",
"def update!(**args)\n @disabled_user_deletion = args[:disabled_user_deletion] if args.key?(:disabled_user_deletion)\n @disabled_user_signup = args[:disabled_user_signup] if args.key?(:disabled_user_signup)\n end",
"def update!(**args)\n @disabled_user_deletion = args[:disabled_user_deletion] if args.key?(:disabled_user_deletion)\n @disabled_user_signup = args[:disabled_user_signup] if args.key?(:disabled_user_signup)\n end",
"def user_enabled\n redirected = false\n if ((producer_signed_in? && current_producer.enabled == false) || (customer_signed_in? && current_customer.enabled==false)) && redirected == false\n redirected = true\n render 'producers/not_allowed'\n end\n false\n end",
"def disable?\n false\n end",
"def disable\n admin_only do\n handle_recurring_schedule_failure 'disable', 'disabled' do\n # get the schedule object to be disabled.\n @test = get_test_with_rescue\n @test.active = nil\n @test.save!\n end\n redirect_to action: \"index\"\n end\n end",
"def user_onoff_flag\n @requested_user = User.find_by_account_number(params[:id])\n if @requested_user.is_active?\n @requested_user.update_columns(:is_active => false)\n redirect_to admin_index_path, :flash => {:notice => \"Requested user(#{@requested_user.first_name} #{@requested_user.last_name}) account successfully de-activated.\"}\n else\n @requested_user.update_columns(:is_active => true)\n redirect_to admin_index_path, :flash => {:notice => \"Requested user(#{@requested_user.first_name} #{@requested_user.last_name}) account successfully activated.\"}\n end\n end",
"def deactivate_user(users, path_to_users_file)\n puts \"Enter username to make inactive:\\n\"\n username = gets.strip.chomp\n if username == \"admin\"\n clear\n puts \"Sorry! You cannot deactivate this admin user.\"\n return\n end\n users.each do |user|\n if user['username'] == username and username != \"admin\" # cant delete admin user\n # confirm you want to deactivate the user\n puts \"You are about to deactivate #{user['username']}. Sure? (y/n)\"\n choice = gets.strip.chomp.downcase\n if choice.match(/^y/) \n # deactivate the user\n user['active']=false\n write_json_file(users, path_to_users_file)\n clear\n puts \"#{username} user has been deactivated\"\n return\n else\n clear\n puts \"User remains active\"\n return\n end\n end\n end\n clear\n puts \"User does not exist\"\nend"
] |
[
"0.780542",
"0.779273",
"0.76537454",
"0.75238055",
"0.74835455",
"0.73480237",
"0.7169268",
"0.71021056",
"0.7081415",
"0.7074036",
"0.70579636",
"0.7019934",
"0.6970868",
"0.683677",
"0.67915636",
"0.6782685",
"0.6763669",
"0.6744167",
"0.6735878",
"0.67284983",
"0.6693534",
"0.6677894",
"0.6671864",
"0.6653065",
"0.6652096",
"0.6643876",
"0.66329193",
"0.6628393",
"0.6600086",
"0.65899116",
"0.6555937",
"0.65535426",
"0.6547444",
"0.6547444",
"0.65276295",
"0.65221655",
"0.6468349",
"0.6456571",
"0.64533335",
"0.6407674",
"0.64064527",
"0.6368946",
"0.6363179",
"0.63570106",
"0.63413084",
"0.6326784",
"0.63194174",
"0.63194174",
"0.63194174",
"0.6315251",
"0.6308005",
"0.6305721",
"0.6300506",
"0.6269144",
"0.62576634",
"0.62523717",
"0.6251823",
"0.6247024",
"0.62416565",
"0.6240123",
"0.6234059",
"0.6230032",
"0.62193805",
"0.6208528",
"0.620552",
"0.6201214",
"0.6185787",
"0.61778355",
"0.6166084",
"0.6157067",
"0.6153816",
"0.6153557",
"0.6151791",
"0.6140712",
"0.61368185",
"0.6131503",
"0.6123852",
"0.61181366",
"0.61157745",
"0.61050576",
"0.60877824",
"0.6082281",
"0.6080018",
"0.6079614",
"0.6063217",
"0.604495",
"0.6033306",
"0.6022915",
"0.6020735",
"0.60165733",
"0.60147125",
"0.601387",
"0.60033906",
"0.5999979",
"0.5999979",
"0.59996957",
"0.5991736",
"0.59913826",
"0.5990789",
"0.5988573"
] |
0.7210115
|
6
|
Required function, returns the storage class for this module.
|
def get_storage_module(config)
return StorageMongo.new(config)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_storage_class\n return @m_storage_class\n end",
"def storage_class\n @storage_class || storage_loader.storage_class\n end",
"def storage_class\n raise NotImplementedError\n end",
"def storage_instance; end",
"def storage \n Trole::Storage::BaseOne\n end",
"def storage\n @storage ||= Fog::Storage.new(storage_config)\n end",
"def get_storage_adapter\n @storage_adapter.new(storage_adapter_config)\n end",
"def store\n @store ||= storage.new self\n end",
"def storage() @storage; end",
"def storage\n Boom.storage\n end",
"def storage\n @storage ||= in_memory\n end",
"def storage\n @storage ||= in_memory\n end",
"def storage\n require 'yaml/store'\n Storage[object_id] ||= YAML::Store.new(STORAGE_FILE)\n end",
"def storage_type\n @grpc.default_storage_type\n end",
"def hashtag_storage_class\n @hashtag_storage_class ||= Hshtg::Storage::InMemoryStore\n end",
"def storage\n @storage ||= in_memory\n end",
"def storage\n @storage ||= in_memory\n end",
"def storage\n @storage ||= in_memory\n end",
"def storage\n @plugins.detect { |p| p.is_a? BaseStorage }\n end",
"def storage\n uploader.storage\n end",
"def storage\n @_storage ||= in_memory\n end",
"def storage; end",
"def storage_type\n data[:storage_type]\n end",
"def storage_type\n data[:storage_type]\n end",
"def store\n return self.class.store\n end",
"def current_storage\n @attributes[:current_storage]\n end",
"def storage_adapter\n @storage_adapter ||= begin\n all_adapters = storage_adapters\n raise UndefinedSetting, \"No storage adapters configured\" if all_adapters.empty?\n adapter = all_adapters.detect do |potential_adapter|\n potential_adapter.use?(storage)\n end\n raise UndefinedSetting, \"Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}\" unless adapter\n adapter\n end\n end",
"def retrieve_store_class(store)\n # require_relative cannot be used here because the class might be\n # provided by another gem, like redis-activesupport for example.\n require \"active_support/cache/#{store}\"\n rescue LoadError => e\n raise \"Could not find cache store adapter for #{store} (#{e})\"\n else\n ActiveSupport::Cache.const_get(store.to_s.camelize)\n end",
"def driver\n storage_hash = get_api_node(['storage-pools', resource[:name]])\n driver = storage_hash['driver']\n return driver\n end",
"def store_with(storage, storage_id = nil, &block)\n @storages << Backup::Storage.const_get(\n last_constant(storage)\n ).new(storage_id, &block)\n end",
"def primary_storage_adapter\n @storage_adapters.first\n end",
"def instance_persistence_bucket\n\n bucket_instance = nil\n \n encapsulation = ::CascadingConfiguration::Core::Encapsulation.encapsulation( :default )\n \n unless bucket_instance = encapsulation.get_configuration( self, :instance_persistence_bucket )\n self.instance_persistence_bucket = to_s\n bucket_instance = super\n end\n \n return bucket_instance\n \n end",
"def uploader\n @uploader ||= shrine_class.new(storage_key)\n end",
"def ensure_store\n @store ||= LocalStorage.new\n end",
"def storage(domain)\n host = vhost(domain)\n host ? host.storage : @null\n end",
"def storage_type\n @dbi.storage_type\n end",
"def storage_type\n @dbi.storage_type\n end",
"def store\n case procedure.storage_name.to_sym\n when :s3 then Backup::Storage::S3.new(self)\n when :scp then Backup::Storage::SCP.new(self)\n when :ftp then Backup::Storage::FTP.new(self)\n when :sftp then Backup::Storage::SFTP.new(self)\n end\n end",
"def get_real_storage\n\n @application_context[:s_expression_storage__1]\n end",
"def store_with(name, storage_id = nil, &block)\n @storages << get_class_from_scope(Storage, name)\n .new(self, storage_id, &block)\n end",
"def lookup_storage(key)\n { memory: Storage::Memory, redis: Storage::Redis }[key]\n end",
"def find_storage(name)\n storages.each { |key, value| return value if key.to_s == name.to_s }\n raise Error, \"storage #{name.inspect} isn't registered on #{self}\"\n end",
"def entry_class_name\n ensure_loaded { StorageRoom.entry_class_for_name(entry_type)}\n end",
"def name()\n \"TestStorageHandler\"\n end",
"def storage\n @storage ||= Set.new\n end",
"def storage\n @storage ||= Set.new\n end",
"def store\n self.class.store\n end",
"def storage_instance=(_arg0); end",
"def get_fog_storage\n return Fog::Storage.new( :provider => 'AWS',\n :aws_access_key_id => CONFIG[:aws_access_key_id], \n :aws_secret_access_key => CONFIG[:aws_access_key],\n :region => \"us-east-1\" )\n end",
"def simpledb_type\n model.storage_name(DataMapper.repository.name)\n end",
"def storage(domain)\n @config.storage(domain)\n end",
"def executions\n @storage_class.instance\n end",
"def storage(arg=nil)\n set_or_return(:storage, arg, :kind_of => String)\n end",
"def storage_name\n @storage_name || name\n end",
"def service\n softlayer_client[:Network_Storage].object_with_id(self.id)\n end",
"def primary_model\n NfsStore::Manage::Container\n end",
"def klass\n @klass ||= compute_class(class_name)\n end",
"def klass\n @klass ||= compute_class(class_name)\n end",
"def klass\n @klass ||= compute_class(class_name)\n end",
"def storage_item_container(item_class)\n return @storage_items[@storage_name] if item_class == RPG::Item\n return @storage_weapons[@storage_name] if item_class == RPG::Weapon\n return @storage_armors[@storage_name] if item_class == RPG::Armor\n return nil\n end",
"def storage_location\n return @storage_location\n end",
"def find_class_or_module name\n @store.find_class_or_module name\n end",
"def klass\n class_name = self[\"_type\"]\n class_name ? class_name.constantize : nil\n end",
"def record_class(name, mod=ICloud::Records)\n sym = name.capitalize.sub(/s$/, \"\").to_sym\n mod.const_get(sym) if mod.const_defined?(sym)\n end",
"def store\n @store ||= Globot::Plugins.store.proxy_for(self)\n end",
"def klass\n self.class\n end",
"def root_storage\n @attributes[:root_storage]\n end",
"def store\n @@store ||= Store.get_store(0)\n end",
"def class\n Registry\n end",
"def _sdk_class\n return 'Wavefront::Distribution' if distribution?\n\n 'Wavefront::Write'\n end",
"def storage_options; end",
"def storage\n Imgurr.storage\n end",
"def storage_key\n self.class.member_path(self[self.class.param_name])\n end",
"def initialize(storage = {})\n @storage = storage\n end",
"def instance_persistence_bucket=( persistence_bucket_class_or_name )\n \n bucket = nil\n\n case persistence_bucket_class_or_name\n \n when nil\n\n bucket = super( nil )\n \n when ::String, ::Symbol\n \n if port = instance_persistence_port\n bucket = super( port.persistence_bucket( persistence_bucket_class_or_name.to_s ) )\n else\n bucket = super( ::Persistence.pending_bucket( self, persistence_bucket_class_or_name.to_s ) )\n end\n \n when ::Persistence::Bucket\n \n bucket = super( persistence_bucket_class_or_name )\n \n else\n\n if persistence_bucket_class_or_name.respond_to?( :persistence_bucket )\n bucket = super( persistence_bucket_class_or_name.persistence_bucket )\n end\n \n end\n\n return bucket\n \n end",
"def get_store\n ActiveRecord::MemoryStore.new\n end",
"def simpledb_type(model)\n model.storage_name(model.repository.name)\n end",
"def storage_participant\n engine.storage_participant\n end",
"def new_store\n Cache.new\n end",
"def store\n @store ||= Globot::Store.new(Globot.config.for_plugin('database'))\n end",
"def record_class\n @record_class ||= record_class_for(self)\n end",
"def db_instance_class\n data.db_instance_class\n end",
"def store\n @store ||= begin\n raise \"This is Maglev only\" unless defined?(Maglev)\n # In the future, it might be nice to use something\n # other than an IdentitySet. Set? Bag?\n Maglev::PERSISTENT_ROOT[self.to_s.intern] ||= IdentitySet.new\n end\n end",
"def storage_dir\n File.join(thirdpartydir,\"storage\")\n end",
"def derivative_storage(path)\n storage = self.class.derivatives_storage\n storage = instance_exec(path, &storage) if storage.respond_to?(:call)\n storage\n end",
"def model_class\n self.class.models[implementation_model_name]\n end",
"def storages\n reflective_auto_load_adapter_extension\n storages # call the overrided method\n end",
"def data_klass\n klass_type = self.class.name\n .gsub!('Spree::Wombat::Handler::', '')\n .gsub!('Handler', '')\n \"Integrations::#{sync_type.camelize}::#{klass_type}\"\n end",
"def persistent_config_manager_class\n self.class.persistent_config_manager_class\n end",
"def backend_klass; end",
"def storage\n ManagedImage.variants_storage\n end",
"def storage_path\n return nil unless db.running?\n db.storage_path\n end",
"def _pack\n class_name = self.class.to_s\n self.__pack = Aqua::Storage.new\n self.__pack.id = @id if @id\n self.__pack[:_rev] = _rev if _rev \n self.__pack[:keys] = []\n self.__pack[:stubs] = []\n self.__pack.merge!( _pack_object( self ) )\n _pack_singletons\n __pack\n end",
"def class\n __getobj__.class\n end",
"def object_class\n self.class.object_class\n end",
"def hashtag_storage_class=(value)\n @hashtag_storage_class = value\n end",
"def store\n @store ||= Moneta.new(:File, dir: 'ruby-elastic')\n end",
"def set_storage_type\n @storage_type = StorageType.find(params[:id])\n end",
"def storage_optimization\n @storage_optimization ||= StorageOptimization.new(\n plugin.adapters.values,\n graph.forecast_storage_order\n )\n end",
"def store\n @store ||= OpenStruct.new\n end"
] |
[
"0.87562126",
"0.8634465",
"0.8194757",
"0.75012326",
"0.72874165",
"0.7138072",
"0.70258355",
"0.6935941",
"0.68922484",
"0.6846309",
"0.6666178",
"0.6666178",
"0.6653607",
"0.6620355",
"0.66112405",
"0.66050255",
"0.66050255",
"0.66050255",
"0.6579115",
"0.6556527",
"0.65426165",
"0.65397745",
"0.65172094",
"0.65172094",
"0.64358574",
"0.6429003",
"0.63887435",
"0.6372723",
"0.6369474",
"0.63314646",
"0.63250494",
"0.63045645",
"0.6280128",
"0.62524104",
"0.6249233",
"0.6242934",
"0.6242934",
"0.6237667",
"0.62155336",
"0.62111855",
"0.6193873",
"0.61625737",
"0.61597306",
"0.614241",
"0.6114361",
"0.6114361",
"0.60754883",
"0.6067216",
"0.60266125",
"0.6015873",
"0.60114276",
"0.6006984",
"0.600644",
"0.59990996",
"0.5997076",
"0.5982357",
"0.5941458",
"0.5941458",
"0.5941458",
"0.5940627",
"0.5939846",
"0.590965",
"0.58981407",
"0.58856463",
"0.5870264",
"0.5869234",
"0.58628345",
"0.5860186",
"0.5856247",
"0.58517355",
"0.5845978",
"0.58443636",
"0.58435273",
"0.5837132",
"0.58035916",
"0.5794361",
"0.5793058",
"0.5778718",
"0.57786375",
"0.5777653",
"0.5773067",
"0.5753463",
"0.5740768",
"0.57350916",
"0.57305473",
"0.5720612",
"0.5720199",
"0.5707367",
"0.5704506",
"0.56976694",
"0.56891286",
"0.56884587",
"0.56795025",
"0.5673407",
"0.56714433",
"0.565272",
"0.5652457",
"0.5651724",
"0.5646954",
"0.56447303"
] |
0.7398641
|
4
|
Returns the name of the script. This can be used in blocks.
|
def name
@@name
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def raw_script_name\n File.basename($0)\n end",
"def script_name # not file name\n sname = fetch(:script_name)\n return sname if sname\n name = dklet_script.basename('.rb').to_s\n pname = script_path.basename.to_s\n \"#{pname}_#{name}\"\n end",
"def script_name\n return @request.script_name\n end",
"def script name\n @__client.scripts.find { |script| script.__name == name }\n end",
"def script_name\n return ENV['SCRIPT_NAME']\n end",
"def base_script_name\n raw_script_name.gsub(/-.*/, '')\n end",
"def this_script_filename\n Pathname.new($0).realpath\n end",
"def name\n File.basename(__FILE__, '.rb')\n end",
"def hook_script_name; end",
"def appname\n fetch(:appname) || script_name\n end",
"def program_name\n File.basename($0)\n end",
"def name\n file.basename('.rb').to_s if file\n end",
"def name\n file.basename('.rb').to_s if file\n end",
"def get_code_name\n code_name = $0\n code_name = Pathname.new(code_name)\n code_name = code_name.basename.to_s\n return code_name\nend",
"def name\n @module.name\n end",
"def program_name\n @program_name || File.basename($0, '.*')\n end",
"def name\n @name ||= filename.split(\".\").first.sub(/^_/, \"\")\n end",
"def ruby_name\n @ruby_name || @name\n end",
"def extract_script_name(line)\n script_name = line.split.delete_if { |line_part| NAME_STRINGS_TO_REMOVE.include?(line_part) }.join(' ').delete(\"'\")\n @script_names.push(script_name)\n end",
"def get_name(code)\n return code[1]\n end",
"def name\n load! if not @loaded\n @name\n end",
"def name\n @name ||= elf.shstrtab.name_at(header.sh_name)\n end",
"def task_name\n raise \"This Stage has not been bound to a name\" if @name.nil?\n name.name\n end",
"def name\n read_property('Name') || asmname || proj_filename_noext\n end",
"def name\n\t\tmodule_info['Name']\n\tend",
"def recipe_name\n File.basename(options[:runner_path]).gsub(/\\..*/, '')\n end",
"def from\n from = File.basename(caller[4])\n end",
"def get_default_tpl\n return self.script_name.sub(/^#{BASE_URL}\\//, '').sub(/\\..+?$/, '')\n end",
"def name\n @name ||= File.basename(Dir.pwd)\n end",
"def name\n File.basename(@root)\n end",
"def control_script_name\n @control_script_name ||= 'riak'\n end",
"def name\n @name ||= self.class.non_namespaced_name\n end",
"def generate_filename(script)\n (Zlib::Inflate.inflate(script[2]) != '' ? \"#{fix_name(script[1])}.rb\" : 'EMPTY')\nend",
"def base_script\n base_language.standard_script\n end",
"def name\n @name ||= source.name\n end",
"def name()\n basename.to_s\n end",
"def program_name\n Quickl.program_name\n end",
"def source_name\r\n \"The console.\"\r\n end",
"def script_path(file_name)\n LUA_PATHNAME.join(\"#{file_name}.lua\")\n end",
"def command_name\n @command_name ||= if command = name.to_s.split(\"::\").last\n command.chomp!(\"Command\")\n command.underscore\n end\n end",
"def name\n return \"#{@code}\"\n end",
"def name\n $0.split(\"/\").last\n end",
"def filename\n \"#{action_name.to_underscore}_command.sh\"\n end",
"def name\n [::Chef.node.run_state['fragments']['cluster']['name'], @suffix].join('-')\n end",
"def name\n @name ||= path.split('/').last\n end",
"def name\n @name ||= File.basename(path)\n end",
"def name\n @name ||= File.basename(path)\n end",
"def template_name\n name.split(\"::\").last.downcase.gsub(/onebox/, \"\")\n end",
"def name\n if !block_given?\n return @j_del.java_method(:name, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling name()\"\n end",
"def name\n if !block_given?\n return @j_del.java_method(:name, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling name()\"\n end",
"def name\n @name ||= ::File.basename(@path)\n end",
"def name\n @name ||= File.basename(file).chomp(File.extname(file))\n end",
"def name\n name = nil\n if root?\n name = path.to_s\n else\n name = @path.basename.to_s\n end\n return name\n end",
"def name()\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n result = Native.RunMetadataVariable_name(@handle.ptr)\n result\n end",
"def script_contents\n @script_contents ||= File.read(File.join(SCRIPT_ROOT, \"#{@name}.lua\"))\n end",
"def name\n @name ||= File.basename(path)\n end",
"def active_path\n if script = script_object()\n if path = script.path\n return path.dup\n end\n end\n\n # If for some reason that didn't work, return the compile time filename.\n method.file.to_s\n end",
"def name\n @name ||= Rails.application.class.parent_name.underscore\n end",
"def get_name\n # The last sentence in a function is always returned so no need to mention return\n @name\n end",
"def object_name\n @name ||= File.split(@source_path).last.gsub('.txt', '')\n end",
"def my_name\n @my_name ||= self.class.name.split(\"::\").last\n end",
"def __name__\n ɴ = self.class.__instances__[ self ]\n namespace.name_get_hook.( ɴ ) if ɴ\n end",
"def name() @filename end",
"def fully_qualified_ruby_name\n return \"::#{self.package.gsub('.', '::')}\"\n end",
"def module_name\n File.basename(File.dirname(__FILE__)).sub(/^[A-Za-z]*?-/, '')\nend",
"def index_filename\n return @index_filename if @index_filename\n if !ARGV.grep(/\\-\\-util[ =]update$/).empty?\n @index_filename = File.join(VSCODE_SCRIPT_PATH, 'script_update_index.txt')\n # Prevent RMXP Scripts from loading\n Kernel.define_method(:eval) { |*args| }\n elsif !(matches = ARGV.grep(/\\-\\-script_context[ =].+\\.txt$/)).empty?\n @index_filename = File.join(VSCODE_SCRIPT_PATH, matches.first.match(/\\-\\-script_context[ =](.*)/).captures.first)\n # We also don't want custom script in that context\n Kernel.define_method(:eval) { |*args| }\n else\n @index_filename = SCRIPT_INDEX_PATH\n end\n puts \"Script Index : #{@index_filename}\"\n return @index_filename\n end",
"def name\n @name ||= to_s.split(\"#\").last.delete(\">\")\n end",
"def name\n lines[0]\n end",
"def script_file\n staged_root.join(\"script.sh\")\n end",
"def name\n if !block_given?\n if @cached_name != nil\n return @cached_name\n end\n return @cached_name = @j_del.java_method(:name, []).call()\n end\n raise ArgumentError, \"Invalid arguments when calling name()\"\n end",
"def template_name\n command.text_value\n end",
"def name\n filename\n end",
"def name\n filename\n end",
"def base_name\n File.basename @relative_name\n end",
"def script_source(file_name)\n Template.new(LUA_PATHNAME).render(script_path(file_name))\n end",
"def name\n (@name ||= namespace).to_s.underscore.symbolize\n end",
"def name\n raise \"No name defined for #{self.class}\"\n end",
"def plugin_name(path)\r\n File.basename(path)\r\n end",
"def ident\n \"<Command name=#{name}>\"\n end",
"def job_name\n return settings[:job_name] if settings[:job_name]\n relevant_filename = args.compact.uniq.map { |path| File.basename(path, '.rb') }.join('-')\n \"#{relevant_filename}---#{input_paths}---#{output_path}\".gsub(%r{[^\\w/\\.\\-\\+]+}, '')\n end",
"def get_name_with_code\n '@{code}-@{name}'\n end",
"def base_name\n name\n end",
"def name\n File.basename(self.path)\n end",
"def script\n @source\n end",
"def game_name()\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n result = Native.Run_game_name(@handle.ptr)\n result\n end",
"def command_name\n return self.class.to_s.split(\"::\").last.downcase.gsub(/command/,\"\")\n end",
"def name\n File.basename(@path)\n end",
"def name\n File.basename(@path)\n end",
"def name\n File.basename(@path)\n end",
"def my_name \n @my_name ||= self.class.name.split(\"::\").last\n end",
"def name\n @args['name']\n end",
"def getName()\n\t\t\treturn @_name\n\t\tend",
"def filename()\n #This is a stub, used for indexing\n end",
"def command_name\n return @command_name\n end",
"def template_module_name(path); end",
"def base_name\n @base_name ||= if base = name.to_s.split(\"::\").first\n base.underscore\n end\n end",
"def basename\n @generator.basename\n end",
"def name\n @name ||= section.symstr.name_at(header.st_name)\n end",
"def script_location\n File.dirname(script)\n end",
"def name\n chunk_name = nil\n File.open(@file_name) do |file|\n file.seek(@offset, IO::SEEK_CUR)\n chunk_name = file.read(4)\n end\n puts \"[WARNING] - Doesn't look like a valid chunk name: #{chunk_name}\" if @warnings && !(chunk_name =~ /^[\\w ]{4}$/)\n chunk_name\n end",
"def name\n @name ||= (@config[:name] || self.class.name.split(/::/).last.titleize)\n end"
] |
[
"0.82970184",
"0.8199234",
"0.81594294",
"0.7578686",
"0.74230343",
"0.7398198",
"0.7313718",
"0.6917737",
"0.67348295",
"0.6654268",
"0.6600941",
"0.65731126",
"0.65731126",
"0.6366667",
"0.6302989",
"0.6214558",
"0.6150102",
"0.6139151",
"0.61264306",
"0.610206",
"0.6100191",
"0.60629785",
"0.6031531",
"0.60314244",
"0.60301566",
"0.60245174",
"0.6001779",
"0.5997498",
"0.5979934",
"0.59788",
"0.5975056",
"0.59714466",
"0.5964097",
"0.5950889",
"0.5949065",
"0.5945487",
"0.594192",
"0.59347177",
"0.59231347",
"0.5917879",
"0.591358",
"0.5912592",
"0.59107924",
"0.59077454",
"0.58955485",
"0.5892178",
"0.5892178",
"0.5882498",
"0.5881954",
"0.5881954",
"0.58779263",
"0.5876591",
"0.5871726",
"0.5858905",
"0.58523816",
"0.584942",
"0.5826176",
"0.58247167",
"0.5817059",
"0.5815723",
"0.5812001",
"0.5810504",
"0.5802782",
"0.58001703",
"0.57937473",
"0.5791453",
"0.57810146",
"0.57787573",
"0.5770221",
"0.576461",
"0.5755466",
"0.5750828",
"0.5750828",
"0.5748784",
"0.5744795",
"0.5737789",
"0.57346845",
"0.57255983",
"0.5708549",
"0.57076555",
"0.5700078",
"0.56975275",
"0.5696172",
"0.56953394",
"0.56920326",
"0.5682643",
"0.56781507",
"0.56781507",
"0.56781507",
"0.56780577",
"0.567568",
"0.56748825",
"0.56706977",
"0.56659216",
"0.56638926",
"0.5660203",
"0.56576633",
"0.5655165",
"0.5653499",
"0.5649007",
"0.5647984"
] |
0.0
|
-1
|
Prints the usage message. This can be used in blocks.
|
def print_usage
puts @@usage
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def usage\n puts @usage_text\n end",
"def print_usage; end",
"def printUsage\n \n print \"usage -- main.rb <structureFile> <outFile>\\n\"\n print \" <numTimesteps> - total number of timesteps to run\\n\"\n print \" <structureFile> - the PDB file to read in\\n\"\n print \" <outFilePrefix> - MD output (.out, .xyz)\\n\"\n \n end",
"def print_usage_and_exit\n puts usage\n exit\n end",
"def print_usage(msg = \"\")\n puts msg if msg\n\n puts <<MSG\nAll options are required.\nUsage: $0\n --hadoop-path [Hadoop directory],\n --bwa-path [Directory to compiled bwa - default hdfs://bwa-tools/bwa.tgz]\n --hadoop-bam-path [Directory that contains hadoop-bam jar and associated jars OPTIONAL]\n --reference [HDFS directory that contains the reference genome with index]\n --read-pair-dir [Directory that contains read files]\n --hdfs-path [HDFS directory for outputs]\n\n\n --help [See this message]\nMSG\n exit(-1)\nend",
"def usage(text)\n help('Usage', text)\n end",
"def usage\n\t\t$stderr.printf \"usage: %s [ options ]\\n\",$0\n\t\t$stderr.printf \"\\n%s\\n\",$help\n\t\texit 0\n\tend",
"def printUsage\n print \"usage -- Moldyne.rb <numTimesteps> <structureFile> <outFile>\\n\"\n print \" <numTimesteps> - total number of timesteps to run\\n\"\n print \" <structureFile> - the PDB file to read in\\n\"\n print \" <outFilePrefix> - prefix for two output files (.out, .xyz)\\n\"\n end",
"def usage\n puts \"#{@description}\\n\\n\" unless @description.nil?\n puts 'Usage:'\n\n _commands_usage $PROGRAM_NAME\n end",
"def usage message\n puts \"error: #{message}\" unless nil == message\n printf USAGE_MESSAGE, VERSION\n exit 1\nend",
"def usage #:nodoc:\n usage = name.to_s\n usage += ' [command options]' if !flags.empty? || !switches.empty?\n usage += ' ' + @arguments_description if @arguments_description\n usage\n end",
"def usage(s)\n puts s\n print <<EOM\nUsage:\n #{$0} [--debug]\n [--conf file]\n [--image image_file]\n [--interval sec]\n [--thres n]\n [--txt text]\n [--allow pat1] [--allow pat2] ...\n [--version]\nExample:\n\nEOM\nend",
"def usage(message = nil)\n returnCode = 0\n if (message != nil && message.length > 0)\n puts 'Error: '+message\n puts\n returnCode = 1\n end\n \n puts <<-END\nUsage:\n#{$0} -d dir -s url [ -w delay ] [ -m id ]\n\nOptions:\n-?: Display this usage information.\n-h: Display this usage information.\n-d: A directory containing raw images and tile sets.\n-m: An optional map ID to process (instead of all maps).\n-s: A server URL from which map metadata can be queried.\n-w: An optional delay (in seconds) to wait in between runs.\n-p: A server URL where maps are going to be available.\nEND\n returnCode\n end",
"def usage(err = true)\n\t\tdst = err ? $stderr : $stdout\n\t\tdst.print(@banner)\n\t\tself.class::COMMANDS.each do |cmd|\n\t\t\tif (self.respond_to?(cmd))\n\t\t\t\tputs(\"\\n\")\n\t\t\t\tif (self.respond_to?(\"help_\" + cmd))\n\t\t\t\t\tprint(self.send(\"help_\" + cmd))\n\t\t\t\telse\n\t\t\t\t\tprint(\"*** Command '#{cmd}' supported but no help available!\\n\")\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend",
"def usage(s)\n $stderr.puts(s)\n $stderr.puts(\"Usage: #{File.basename($0)}: [-m module] [-o outdir] program [args]\")\n exit(2)\nend",
"def usage(msg)\n\tSTDERR.print msg, \"\\n\\n\"\n\tSTDERR.print \"Usage: #{File.basename($0)} statefile [statefile ...]\\n\\n\"\n\tSTDERR.print \"export iroffer statefile to text.\\n\"\n\texit 64\nend",
"def usage\n s = \"#{USAGE_HEADER}\\n\"\n s << \"\\n\"\n s << \" ABOUT\\n\"\n s << \" The 'help' command prints usage info for the Bake utility overall, or for a\\n\"\n s << \" given command.\\n\"\n s << \"\\n\"\n s << \" USAGE\\n\"\n s << \" bake help [command]\\n\"\n s << \"\\n\"\n return s\n end",
"def usage\n puts <<End\n\nWarning: This currently attempts to run blkid, fdisk -l, and hdparm -i with sudo, which may prompt for a password.\nThis command may not pass on the password prompt to you but will just sit there.\nIt is recommended that you add those commands to your sudoers file with NOPASSWD so that it won't prompt for a password.\n\nusername ALL = NOPASSWD: \\\n ...\n /usr/bin/du, \\\n /bin/df, \\\n /usr/sbin/smartctl, \\\n /usr/sbin/hddtemp, \\\n /sbin/vol_id, \\\n /sbin/hdparm, \\\n /sbin/blkid, \\\n /sbin/fdisk -l, \\\n\nOptions:\n -d, --device -- groups by device, and shows model name/serial number/disk capacity of each physical device (this is now the default)\n\n --no-color -- disable color\nEnd\n exit 1\nend",
"def usage\n str = @appname + \"\\n\\n\"\n unless @description.empty?\n str += \"DESCRIPTION\\n\"\n str += @description.join + \"\\n\"\n end\n unless @examples.empty?\n str += \"EXAMPLES\\n\"\n str += @examples.join + \"\\n\"\n end\n str += \"OPTIONS\"\n str += @parser.to_s.rstrip + \"\\n\"\n str\n end",
"def show_usage(*args)\n args_def.show_usage(*args)\n end",
"def usage\n usage = \"#{@name}\"\n\n @arguments.each do |arg,format|\n usage << ' ' << case format\n when Array then \"[#{format.join('|')}]\"\n when Regexp then format.source\n when Symbol then arg.to_s.upcase\n else format.to_s\n end\n end\n\n return usage\n end",
"def usage\n if @commands.empty?\n @output.write 'No commands are available.'\n return\n end\n\n @output.write <<-USAGE\nUsage: #{@name} <command> [<parameter> [...]] [<body>]\n\nHelp topics, type \"#{@name} help <topic>\" for more details:\n\nUSAGE\n\n name_width = @commands.keys.max_by { |key| key.size }.size\n @commands.sort.each do |name, command|\n name = name.ljust(name_width)\n description = command.description\n @output.puts(\" #{name} #{description}\")\n end\n end",
"def usage()\n $stderr.puts \"Usage:\\t#{$0} [options] xx:xx:xx:xx:xx:xx\"\n $stderr.puts \"Wake the sleeping computer with MAC address xx:xx:xx:xx:xx:xx from another\\nmachine.\"\n $stderr.puts\n $stderr.puts \"\\t-i, --ip=ip_addr\\tSpecify IP address to send the wake packet to\"\n $stderr.puts \"\\t-h, --help\\t\\tPrint this usage summary\"\n $stderr.puts \"\\t-v, --version\\t\\tPrint version information\"\n end",
"def print_usage\n puts \"USAGE: #{PROGNAME} <ip|host> [warning,critical] [snmp_community]\"\n puts \" Default values: warning=80, critical=90, snmp_community=public\"\nend",
"def usage()\n\tputs \"Usage:\"\n\tputs \"\t\" + $0 + \" banner.bnr outfolder\"\nend",
"def usage_presentation\n \" #{command.syntax}\"\n end",
"def display_usage\n end",
"def usage()\n puts <<-\"USAGE\"\n\n Usage: #{$0} path/to/file.ofx\n\n USAGE\n exit 1\nend",
"def usage_start\n \"\\\\usage{\"\n end",
"def docopt_usage \n doc = [\"\\nUsage:\"];\n @actions.each do |_name, action|\n doc << \" run #{action.usage}\" unless action.usage == false\n end\n basic_flags = @version ? \"(-h|--help|--version)\" : \"(-h|--help)\"\n if @superspace\n doc << \" run #{@superspace} #{basic_flags}\\n\"\n else\n doc << \" run #{basic_flags}\\n\"\n end\n doc\n end",
"def usage(args_and_such=nil)\n _banner = \"usage: #{File.basename($0)}\"\n (_banner << ' ' << args_and_such) if args_and_such\n @option_parser.banner = _banner\n end",
"def basic_usage\n return '' if args.nil?\n usage_args.map {|e|\n (e.size < 2) ? e[0].upcase : \"[#{e[0].upcase}]\"\n }.join(' ')\n end",
"def printUsageMessage()\n\n print \"Check the last NAMD log file in a directory to make sure the run either completed\\n\"\n print \"successfully or died after all necessary restart files were written. Then restart\\n\"\n print \"the run or print an error message.\\n\"\n print \" autoNamdRun.rb <configFile>\\n\"\n print \" <configFile> - file listing all NAMD jobs to check\\n\"\n\n return\nend",
"def usage\n basename = File.basename($0)\n necessary_inputs = \"<omsadmin_conf> <cert> <key> <pid> <proxy> <os_info> <install_info>\"\n print(\"\\nTelemetry tool for OMS Agent\\n\"\\\n \"ruby #{basename} #{necessary_inputs}\\n\"\\\n \"\\nOptional: Add -v for verbose output\\n\")\nend",
"def output_usage\n print \"== Usage \n karmabyns number_of_dice value_sought\"\n end",
"def usage_string\n result = [full_name]\n result << \"[command]\" if commands.any?\n args.each do |arg|\n result << arg.usage_string\n end\n result << \"[options]\" unless flags.empty?\n result << catch_all_usage if catch_all\n result.join \" \"\n end",
"def banner\n \"#{basename} #{self_command.formatted_usage(self, false)}\"\n end",
"def usage\n puts <<EOU\nAnvändning:\n #{__FILE__} [LÄNGD] [ARGUMENT]\n\nGenerera lösenord\n\nExempel:\n #{__FILE__} 5\n #{__FILE__} 7 -l se\n\nArgument:\n -h, --help Visa denna information\n\n -l, --lang LANG Använd språket LANG för lösenordet (en = Engelska, se = Svenska)\n\n LÄNGD Antal ord i lösenorder\n\nGenererar ett lösenord bestående av LÄNGD antal slumpade ord (Standardlängden är 4 ord).\nKan generera lösenord på både svenska och engelska.\n\nEtt antal slumpade ord hämtas först från en extern ordlista, av dem slumpas sedan LÄNGD antal ord för att bilda lösenordet.\n\nOBS! Mellanslagen är en del av lösenordet!\nEOU\n\n # We also exit the script here..\n exit(0)\nend",
"def print_help\r\n print <<~HEREDOC\r\n Usage: ruby caesar_cipher.rb [options] [message string]\r\n \\t-d, --decode\r\n \\t\\tset the program to decode (default is decode)\r\n \\t-e, --encode\r\n \\t\\tset the program to encode (default is decode)\r\n \\t-f=FILEPATH, --file=FILEPATH\r\n \\t\\tset a file to read from\r\n \\t-h, --help\r\n \\t\\tprint this message\r\n \\t-n, --negative\r\n \\t\\tnegate the offset. Can also pass a negative offset\r\n \\t-o=NUMBER, --offset=NUMBER\r\n \\t\\tset the offset used by the cipher. Default is 2\r\n \\t-p=FILEPATH, --path=FILEPATH\r\n \\t\\tsee -f\r\n HEREDOC\r\n end",
"def usage_page\n Format.usage(\"You can run me with the following flags: #{File.basename(__FILE__)} -[d|e|h] -[f] <path/to/file/if/any>\")\n exit\nend",
"def usage\n \"#{balance_details 2}GB of #{balance_details 3}GB remaining\"\n end",
"def usage\n puts <<EOU\nUSAGE:\n #{__FILE__} [ARGUMENT]\n\nArgument:\n -h, --help Visa denna information\n\n -a, --alias ALIAS Lista alias vars 'alias' matchar ALIAS\n -r, --reciever MOTTAGARE Lista alias vars 'mottagare' matchar MOTTAGARE\n\nTIPS: Använd tillsammans med less om listan är för lång:\n\n #{__FILE__}|less\n\nEOU\n\n # We also exit the script here..\n exit(0)\nend",
"def usage\n puts <<EOU\nUSAGE:\n #{__FILE__} ALIAS E-POST [ARGUMENT]\n\nTa bort ett e-postalias från mailservern\n\nExempel:\n #{__FILE__} arthur@example.com arthur.dent@example.com\n #{__FILE__} zaphod@example.net zaphod@example.com\n\nArgument:\n -h, --help Visa denna information\n -s, --simulate Simulera allt, gör inga ändringar i filsystem eller databas\n\nFör att ta bort ett alias måste \"hela\" aliaset anges (Dvs både ALIAS och MOTTAGARE).\nI nuvarande version går det inte att ta bort alla mottagare för ett alias på en gång!\nEOU\n\n # We also exit the script here..\n exit(0)\nend",
"def help\n\t\tself.usage(false)\n\t\texit EX_OK\n\tend",
"def usage(msg)\n\tprint msg, \"\\nUsage: #{File.basename($0)} xdccfile [xdccfile ...]\\n\\n\"\n\tprint \"add size info to iroffer xdccfile\\n\"\n\texit 64\nend",
"def usage(s,c)\n\t$stderr.puts(s + getusage())\n\texit(c)\nend",
"def print_usage \n puts \"Usage: packagize [-h] [-v] [-r] [-s source_dir] [-d dest_dir]\"\n puts \"\\tSource and destination default to the current working directory.\"\n puts \"\\t-r search directory and all subdirectories. Defaults to true.\"\n puts \"\\t-v display verbose output. Defaults to false.\"\n puts \"\\t-h display this text.\"\nend",
"def show_help\n puts HELP_MESSAGE\n end",
"def show_help\n puts HELP_MESSAGE\n end",
"def usage\n\tputs <<EOU\nUsage:\tausgaben {j,c,w}[g]add BETRAG [TAGS]\n\tausgaben sum {jo|caro|wir} [MONAT] [JAHR]\n\tausgaben list {jo|caro|wir} [MONAT] [JAHR]\n\tausgaben ausgleich [MONAT] [JAHR]\nEOU\n\texit\nend",
"def usage\n puts <<EOU\nUSAGE:\n #{__FILE__} DOMÄN [ARGUMENT]\n\nTa bort en domän från mailservern\n\nArgument:\n -h, --help Visa denna information\n -s, --simulate Simulera allt, gör inga ändringar i filsystem eller databas\n\nTar bort domänen DOMÄN från mailservern.\nOBSERVERA att skriptet även har möjlighet att ta bort all tillhörande e-postkonton!\nEOU\n\n # We also exit the script here..\n exit(0)\nend",
"def test_usage\n assert_equal 1, go_with_args(%w(-h))\n assert_match(/^Usage: /, @stderr_io.string )\n end",
"def banner\r\n \"Usage: #{$0} generator [options] [args]\"\r\n end",
"def usage()\n $stderr.puts \"Uasge: ruby nbeparse <args> <nbe output>\"\n $stderr.puts\n $stderr.puts \"Arguments:\"\n $stderr.puts \"-l Display log message results\"\n $stderr.puts \"-h Display security holde results\"\n $stderr.puts \"-n Display security note results\"\n $stderr.puts \"-w Display security warning results\"\n $stderr.puts \"-ni Display results but don't display IP addresses\"\n $stderr.puts \"-i <ip address> Display only results with the given IP address\"\n exit(2)\nend",
"def print_usage(options,on_boot,terminal)\n puts\n puts \"Usage: \"+$0+\" -[\"+options+\"]\"\n puts\n puts \"-V:\\tDisplay version information\"\n puts \"-h:\\tDisplay usage information\"\n puts \"-i:\\tImport file\"\n puts \"-o:\\tOutput file\"\n puts \"-j:\\tConvert hosts file to a JSON file\"\n puts \"-t:\\tOutput to standard IO\"\n puts \"-T:\\tSet Terminal application (default #{terminal})\"\n puts \"-l:\\tStart Shuttle at login (default #{on_boot})\"\n puts\n return\nend",
"def print_usage\n puts \"usage: #{$0} URI [URI2 URI3..]\"\n puts \"\"\n puts \"Downloads resource from webdav server. File is \"\n puts \"uploaded back to webdav server when file us updated\"\n puts \"on local disk. \"\n exit\nend",
"def usage\n puts <<USAGE\n== Synopsis\n\nopm list-available-cartridges: Prints a list of all available cartridges and provided features\n\n== Usage\n\nopm list-available-cartridges\n\nOptions:\n-h|--help:\n Prints this message\nUSAGE\nend",
"def usage\n return @usage\n end",
"def usage\n usages = <<-EOF\n #{program_name} list probe_packages [options] > OUTPUT/FILE\n Or: #{program_name} create mo < INPUT/JSON/FILE > OUTPUT/FILE\n EOF\n usages.gsub!(/^\\s+/, '')\n usages.gsub!(/\\n$/, '')\n usages\n end",
"def usage\n txt = [\"\\nOPTIONS:\\n\"]\n\n fmt.sort.each do |entry|\n fmtspec, val = entry\n opt = val[0] ? \" <opt> \" : \" \"\n txt << \" #{fmtspec.ljust(longest.length)}#{opt}#{val[1]}\"\n end\n\n txt << \"\"\n txt.join(\"\\n\")\n end",
"def usage\n usage = \"#{$0} -r HTTP_R -k KEY -u URL [options] [param=value param=value ...]\"\n usage += \"\\n\\n\\tTry: #{$0} -h for more information.\"\n return usage\nend",
"def usage_message(user)\n PFM::Text.set_pkname(user)\n scene.display_message(parse_text_with_pokemon(8999 - GameData::Text::CSV_BASE, 12, user, PFM::Text::MOVE[0] => name))\n PFM::Text.reset_variables\n end",
"def usage_instructions\n \"Usage: #{$0} (--ec2-user-id | -u) (--aws-access-key-id | -a) (--aws-secret-access-key | -s) (--host_role | -r) (--snapshot | (--restore-most-recent | --start-most-recent) ) [--volume-size] [--tell] [--debug]\"\n end",
"def help_message\n make_response %(*Usage:*\n\n To get stats about all players:\n `foosey stats`\n\n To do anything else:\n http://foosey.futbol)\nend",
"def print_error\n puts @error_text if @error_text\n print_usage\n end",
"def usage()\n puts \"\\nUsage: #{File.basename($0)}\"\n puts \"\\t-d --device\\t\\t\\tList of devices to configure (file).\"\n puts \"\\t-c --config\\t\\t\\tConfiguration file to commit.\"\n puts \"\\t-u --username\\t\\t\\tSSH username.\"\n puts \"\\t-p --password\\t\\t\\t(Optional) SSH password.\"\n puts \"\\t-h --help\\t\\t\\tDisplay the usage.\\n\\n\"\n puts \"* If you have spaces in the path to your file(s), please enclose them in quotes \\\"\\\".\\n\\n\"\n exit\nend",
"def print_usage(options)\n puts\n puts \"Usage: \"+$0+\" -[\"+options+\"]\"\n puts\n puts \"-V:\\tDisplay version information\"\n puts \"-h:\\tDisplay usage information\"\n puts \"-a:\\tProcess all PDFs\"\n puts \"-d:\\tSet PDF directory\"\n puts \"-f:\\tProcess a file\"\n puts \"-l:\\tList all pdf files\"\n puts \"-p:\\tSet product\"\n puts \"-r:\\tSet release\"\n puts \"-o:\\tOutput to file\"\n puts \"-t:\\tOutput in TXT mode\"\n puts \"-c:\\tOutput in CSV mode\"\n puts \"-x:\\tOutput in XLS mode\"\n puts \"-v:\\tVerbose mode\"\n puts\n return\nend",
"def usage\n puts <<EOU\nUSAGE:\n #{__FILE__} E-POST [ARGUMENT]\n\nTa bort e-postkontot för E-POST\n\nArgument:\n -h, --help Visa denna information\n -s, --simulate Simulera allt, gör inga ändringar i filsystem eller databas\nEOU\n\n # We also exit the script here..\n exit(0)\nend",
"def usage()\n\tputs \"Usage: #{$0} [width resolution in pixels] [height resolution in pixels] [diagnonal size in inch]\"\nend",
"def usage\n [\n \"#{at_nick} mahlzeit - #{nick} fragt wer zu Mittag fahren will\",\n \"#{at_nick} stats - #{nick} sendet dir deine Statistik\",\n \"#{at_nick} ich - #{nick} fuegt dich zur Liste hinzu\",\n ]\n end",
"def usage()\n STDOUT.puts \"USAGE: ruby find-missing-developers-in-git-commits.rb LOGS_FILE\"\nend",
"def help\n command_object.display_usage(cli.command)\n exit\n end",
"def usage\n puts\n puts \"ruby bj_play.rb [OPTIONS]\"\n puts\n puts \" -c, --cash [integer]:\"\n puts \" set the player's starting cash\"\n puts\n puts \" -d, --debug:\"\n puts \" debug mode; shows deck and dealer hands\"\n puts\n puts \" -h, --help:\"\n puts \" show help\"\n puts\nend",
"def show_usage_message\n puts('Usage: ')\n puts('ruby ruby_rush.rb *seed* *num_prospectors* *num_turns*')\n puts('*seed* should be an integer')\n puts('*num_prospectors* should be a non-negative integer')\n puts('*num_turns* should be a non-negative integer')\n exit(1)\nend",
"def usage; end",
"def usage; end",
"def usage\n self.class.const_get(:USAGE)\n end",
"def print_usage\n puts \"Usage: \" + File.basename($0)\n puts \" \" + File.basename($0) + \" -n N (N number of random people)\"\n puts \" \" + File.basename($0) + \" -g N (Groups of N random people)\"\n puts \" \" + File.basename($0) + \" -G N (N Groups of random people)\"\nend",
"def show_usage\n puts \"Usage: #{$PROGRAM_NAME} pattern [filename]\"\n exit\nend",
"def usage(stream=$stderr, status=1)\n stream.puts File.readlines(__FILE__).\n grep(/^#\\//).\n map { |line| line.sub(/^#. ?/, '') }.\n join\n exit status\nend",
"def usage\n puts <<EOF\nusage: oo-cgroup-read [-h|--help] <option>\n\noption: 1) the name of the cgroup attribute requested\n or 2) \"all\" to list all attribute names.\n or 3) \"report\" to list all attribute names and values in JSON\nEOF\n\nend",
"def usage(result, out)\n Usage.call(result, out)\n exit(1)\n end",
"def usage(stream=$stderr, status=1)\n stream.puts File.readlines(__FILE__).\n grep(/^#\\//).\n map {|line| line.sub(/^#. ?/, '')}.\n join\n exit status\nend",
"def help\n\tputs <<-EOH\nUsage: #{$PROGRAM_NAME} <option> [name]\n options:\n\t-s\t--show\tshow instructions to install package specified by name\n\t-l\t--list\tlist available packages\n\t-h\t--help\tshow this help message and exit\n\tEOH\n\t0\nend",
"def usage()\n $stderr.puts option_parser\n exit 1\n end",
"def gen_usage\n puts 'Usage:'\n puts ' poole [ACTION] [ARG]'\n puts ''\n puts 'Actions:'\n puts ' draft Create a new draft in _drafts with title SLUG'\n puts ' post Create a new timestamped post in _posts with title SLUG'\n puts ' publish Publish the draft with SLUG, timestamping appropriately'\n puts ' unpublish Move a post to _drafts, untimestamping appropriately'\n exit\n end",
"def usage\n \"#{at_nick} calc <calculation> - replies with the result of <calculation>\"\n end",
"def usage_displayed(is_exit_zero)\n expect_output 'foodcritic [cookbook_paths]'\n\n usage_options.each do |option|\n expect_usage_option(option[:short], option[:long], option[:description])\n end\n\n if is_exit_zero\n assert_no_error_occurred\n else\n assert_error_occurred\n end\n end",
"def usage\n print_line(\"Meterpreter Script to flood host with a process\")\n print_line(@exec_opts.usage)\n raise Rex::Script::Completed\nend",
"def run\n msg = nil\n \n if @command\n command = Incline::CLI::valid_commands.find{|c| c[0] == @command}\n if command\n msg = \"Usage: #{$PROGRAM_NAME} #{command[0]}\"\n pend = ''\n command[2].each do |t,p|\n msg += ' '\n if t == :req\n msg += p.to_s\n elsif t == :opt\n msg += '[' + p.to_s\n pend += ']'\n else\n msg += '<...>'\n end\n msg += pend\n end\n msg = ANSI.ansi(:bold) { msg }\n msg += \"\\n\"\n comment = get_run_comment(command[1])\n comment = \"(No additional information)\" if comment.to_s.strip == ''\n comment = ' ' + comment.gsub(\"\\n\", \"\\n \")\n msg += comment + \"\\n\"\n end\n end\n \n unless msg\n commands = Incline::CLI::valid_commands.sort{|a,b| a[0] <=> b[0]}\n \n msg = ANSI.ansi(:bold) { \"Usage: #{$PROGRAM_NAME} command <arguments>\" }\n if @command\n msg += \"\\nInvalid Command: #{@command}\\n\"\n end\n msg += \"\\nValid Commands:\\n\"\n commands.each do |(name,_,params)|\n msg += \" #{name}\"\n pend = ''\n params.each do |t,p|\n msg += ' '\n if t == :req\n msg += p.to_s\n elsif t == :opt\n msg += '[' + p.to_s\n pend += ']'\n else\n msg += '<...>'\n end\n end\n msg += pend + \"\\n\"\n end\n \n end\n \n\n STDOUT.print msg\n msg\n end",
"def output_help\n RDoc::usage()\n end",
"def usage(message = '', end_of_story = true)\n\tputs message + '\\n' unless message.length() == 0\n\tputs\n\tputs 'Usage: push-historic-from-csdl.rb <username> <api_key> \\\\'\n\tputs ' <csdl_filename> <output_type> <name> ...'\n\tputs\n\tputs 'Where: csdl_filename = a file containing the CSDL'\n\tputs ' start_date = Historics query start date (yyyymmddhhmmss)'\n\tputs ' end_date = Historics query end date (yyyymmddhhmmss)'\n\tputs ' sources = comma separated list of sources (twitter,digg,etc)'\n\tputs ' sample = percentage of matches to return'\n\tputs ' output_type = see http://dev.datasift.com/docs/push/connectors'\n\tputs ' name = a friendly name for the subscription'\n\tputs ' key=val = output_type-specific arguments'\n\tputs\n\tputs 'Example'\n\tputs ' push-historic-from-csdl.rb csdl.txt csdl.txt 20120101000000 \\\\'\n\tputs ' 20120101235959 twitter 100 http PushName delivery_frequency=10 \\\\'\n\tputs ' url=http://www.example.com/push_endpoint auth.type=none'\n\tputs\n\texit 1 unless not end_of_story\nend",
"def dump_help extra_msg=nil\n $stderr.puts help\n $stderr.puts \"\\n\\n\"+extra_msg unless extra_msg.blank?\n $stderr.puts ''\n end",
"def display_help\n\t# define the help variable which holds the help text\n\thelp = \"Usage: ruby inventory.rb [?|-h|help|[-u|-o|-z <infile>|[<outfile>]]]\\nParameters:\n ? displays this usage information\n -h displays this usage information\n help displays this usage information\n -u <infile> update the inventory using the file <infile>.\n The filename <infile> must have a .csv\n extension and it must be a text file in comma\n separated value (CSV) format. Note that the\n values must be in double quote.\n -z|-o [<outfile>] output either the entire content of the\n database (-o) or only those records for which\n the quantity is zero (-z). If no <outfile> is\n specified then output on the console otherwise\n output in the text file named <outfile>. The\n output in both cases must be in a tab separated\n value (tsv) format.\n -d deletes an item specified by the user from the \n database\"\n\t# print the help screen\n\tputs help\nend",
"def banner\n \"Usage: #{$0} #{spec.name} <action>\"\n end",
"def usage(description = nil)\n return @usage unless description\n @usage = description\n end",
"def print_usage\n log.puts \"Usage: yri [options] <Path to object>\"\n log.puts \"See yri --help for more options.\"\n end",
"def help\n\tusage\n\tputs \"This tool is oriented to separate web pages into segments called blocks, based on the structural and visual properties\"\nend",
"def usage\n puts \"$ #{__FILE__} SRC_PATH TARGET_PATH THREAD_COUNT\"\n puts \"$ #{__FILE__} user.url . 8\"\n exit\nend",
"def usage\n puts 'Usage: %s.rb' % NAME\n exit!\nend"
] |
[
"0.7909556",
"0.7436143",
"0.7390462",
"0.7385388",
"0.7350944",
"0.7316139",
"0.73084694",
"0.7294692",
"0.72527647",
"0.72032785",
"0.71514326",
"0.71102524",
"0.70941794",
"0.70545274",
"0.7014615",
"0.6957898",
"0.6949345",
"0.69478637",
"0.6907171",
"0.68970203",
"0.6880057",
"0.6876672",
"0.68738735",
"0.68314564",
"0.68100977",
"0.6790183",
"0.67881846",
"0.67872584",
"0.6772992",
"0.6754233",
"0.6746449",
"0.6724439",
"0.67235076",
"0.67053455",
"0.66986936",
"0.6691431",
"0.66822535",
"0.6680511",
"0.66714436",
"0.6629726",
"0.6617784",
"0.66057056",
"0.65826577",
"0.6578215",
"0.65721464",
"0.6570236",
"0.65310293",
"0.6501474",
"0.6501474",
"0.65012866",
"0.65005225",
"0.6489941",
"0.6488872",
"0.648832",
"0.6485822",
"0.6480435",
"0.6463268",
"0.6456293",
"0.64545524",
"0.6443917",
"0.64409286",
"0.6436646",
"0.643047",
"0.64265484",
"0.64171696",
"0.6414308",
"0.64135456",
"0.64128983",
"0.6411742",
"0.6405695",
"0.6386846",
"0.6386018",
"0.6378553",
"0.6368982",
"0.63679826",
"0.63679826",
"0.63599336",
"0.63418126",
"0.63401824",
"0.63294613",
"0.63251",
"0.6323187",
"0.63133615",
"0.63057154",
"0.6299805",
"0.62979394",
"0.629687",
"0.629214",
"0.6280303",
"0.62787014",
"0.6276064",
"0.62564963",
"0.6251298",
"0.624848",
"0.6247072",
"0.62418145",
"0.6237143",
"0.62293583",
"0.62210745",
"0.6219981"
] |
0.71498704
|
11
|
A string of all possible options. Use split to get an array of all options. This can be used in blocks.
|
def options
@@auto_completion.inject do |opts,opt|
opts + " " + opt
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def options\n self.read_attribute(:options).split(\"\\n\") unless self.read_attribute(:options).nil?\n end",
"def options # :nodoc:\n [].tap do |o|\n o << \"Lazy\" if lazy?\n o << \"Reverse\" if reverse?\n o << \"Exclude [#{all_excluded_words.join(\", \")}]\" if excluded_words.any?\n o << \"No Options\" if o.empty?\n end\n end",
"def valid_options\n self::OPTIONS.map(&:to_s).join(', ')\n end",
"def options_text\n options.map{ |opt| opt.text}\n end",
"def options(opt)\n []\n end",
"def valid_options\n %i(\n\n ) # end array\n end",
"def options(opt); end",
"def options(opt); end",
"def option_names\n standard_option_names\nend",
"def make_list(options)\n list = []\n to_switches(options).split(\" \").each do |a|\n list << a.gsub('\"', \"\")\n end\n list\n end",
"def get_options\n if parts = @text.match(/([\\d]*) (.*)/)\n return parts[1].strip, parts[2].split(\",\").map(&:strip)\n end\n end",
"def yardopts\n IO.read(options_file).shell_split\n rescue Errno::ENOENT\n []\n end",
"def options(opt)\n end",
"def parse_options; end",
"def parse_options; end",
"def options(*excludes)\n excludes = excludes.flatten.collect { |exc| exc.to_sym }\n @options.inject(\"\") do |str, opt|\n if opt[1].nil? || excludes.include?(opt[0].to_sym)\n str\n else\n val = opt[1] == true ? '' : opt[1]\n option = opt[0].to_s\n option = (option.length == 1 ? \"-\" : \"--\") + option.gsub('_', '-')\n \"#{str} #{option} #{val}\".strip\n end\n end\n end",
"def extract(_options_str = nil)\n @options_str = _options_str if _options_str # hook for testing\n @extract ||= begin\n lines_containing_options = options_str.split(/\\n/).grep(/^[\\s\\t]+-/)\n all_options = lines_containing_options.inject([]) do |list, line|\n list + line.scan(/(?:^\\s+|,\\s)(-[\\w-]+)/).flatten\n end\n long_options = all_options.grep(/^--/).sort\n short_options = hide_short_flags? ? [] : (all_options - long_options).sort\n long_options + short_options\n end\n end",
"def options\n regopt.children.map { |opt| OPTIONS.fetch(opt) }.inject(0, :|)\n end",
"def make_option_list\n end",
"def make_option_list\n end",
"def options() end",
"def credential_options\n %w[username password].map do |option|\n next if send(option).nil? or send(option).empty?\n \"--#{option}='#{send(option)}'\"\n end.compact.join(\"\\s\")\n end",
"def raw_options(options, indent=0)\n out = []\n options.each do |option|\n out << \"#{' '*indent}#{option};\"\n end if options\n out << ''\n end",
"def options\n\t\t\tVALID_OPTIONS_KEYS.inject({}) do |option,key|\n\t\t\t\toption.merge!(key => send(key))\n\t\t\tend\n\t\tend",
"def getOptions\n @options = Array.new\n # format of options argument\n optionsPattern = Regexp.new(/\\-[\\w]+/)\n # check to see if options are formatted correctly\n if optionsPattern.match(ARGV[0])\n # get each option and push them to an array \n # start at 1 to ignore - \n for i in 1..ARGV[0].length - 1\n @options.push(ARGV[0][i])\n end # -- end for loop to get options\n else\n abort(\"First argument needs to be an option.\\nExample:\\n\\t ruby OSQuery -i Blood_rune\")\n end # -- end valid options check\nend",
"def variant_options(v, options={})\n v.options_text\n end",
"def _parse_options(option_string)\n\n return [] unless option_string\n\n options_list = []\n options_list = option_string.split(@delim).map do |option|\n { \"name\" => option.split(\"=\").first, \"value\" => option.split(\"=\").last }\n end\n\n puts \"Got options: #{options_list}\" if @debug\n\n options_list\n end",
"def credential_options\n %w[username password].map do |option|\n next if send(option).to_s.empty?\n \"--#{option}='#{send(option)}'\"\n end.compact.join(' ')\n end",
"def options\n OPTIONS.each_with_object({}) do |name, hash|\n hash[name] = raw.fetch(name, nil)\n end\n end",
"def options\n OPTIONS.each_with_object({}) do |name, hash|\n hash[name] = raw.fetch(name, nil)\n end\n end",
"def options\n VALID_OPTIONS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def for_option_parser\n [short, long, return_type, description].flatten.reject{ |o| o.to_s.empty? }\n end",
"def options(*args, &block); end",
"def options\n OPTIONS.each_with_object({}) do |name, hash|\n hash[name] = raw.fetch(name, nil)\n end\n end",
"def options\n Hash[VALID_OPTIONS.map { |key| [key, send(key)] }]\n end",
"def options_string=(str)\n self.form_field_options.delete_all\n arr = str.split(',')\n arr.each_with_index {|l, i| self.form_field_options.build(:label => l.strip, :value => l.strip, :position => i)}\n end",
"def options\n Hash[ * VALID_OPTIONS_KEYS.map { |key| [key, send(key)] }.flatten ]\n end",
"def prepare_options(opts = [])\n opts.inject('') do |string, (option, value)|\n string += case\n when value\n create_option(option, value)\n when option.respond_to?(:each_pair)\n prepare_options(option)\n else\n create_option(option)\n end\n end\n end",
"def to_s\n OPTIONS\n .reject { |v| send(v).nil? }\n .map { |v| \"#{v}=#{send(v)}\" }\n .join(',')\n end",
"def options_string(options)\n return nil if Hash(options).size.zero?\n\n options.map do |k, v|\n [k.to_s, v.to_s].join\n end.join.gsub(/[^A-Za-z0-9\\-_]/, '')\n end",
"def option_tag(text); end",
"def program_options\n [\n # The values of the array are,\n # [long_option, short_option and parameter, description, code to execute] \n ['--to', '-t TO', \"Send email to recipent\",\n lambda { |value| options.to = value }\n ],\n ['--message', '-m MESSAGE', \"Include the message.\",\n lambda { |value| options.message = value }\n ],\n ['--subject', '-s SUBJECT', \"Include the subject.\",\n lambda { |value| options.subject = value }\n ],\n ['--verbose', '-v', \"Log to standard output.\",\n lambda { |value| options.verbose = true }\n ],\n ['--version', '-V', \"Display the program version.\",\n lambda { |value|\n puts \"#{program_name}, version #{PROGRAM_VERSION}\"\n exit\n }\n ]\n ]\nend",
"def options; [] end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n {\n version: @version,\n delim: @delim,\n randomized: @flags[0],\n ordered: @flags[1],\n rotated: @flags[2],\n comments: @flags[3]\n }\n end",
"def options\n @options || parse_and_return(:@options)\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options\n VALID_OPTIONS_KEYS.inject({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def program_options\n [\n # The values of the array are,\n # [long_option, short_option and parameter, description, code to execute]\n ['--google', '-g', \"Format for Google blogger.\",\n lambda { |value| options.google = true }\n ],\n ['--jayway', '-j', \"Format for Jayway blog.\",\n lambda { |value| options.jayway = true }\n ],\n ['--utf', '-u', \"Include meta charset utf8\",\n lambda { |value| options.utf = true }\n ],\n ['--stylesheet', '-s', \"Add a stylesheet, md.css\",\n lambda { |value| options.stylesheet = true }\n ],\n ['--verbose', '-v', \"Log to standard output.\",\n lambda { |value| options.verbose = true }\n ],\n ['--version', '-V', \"Display the program version.\",\n lambda { |value|\n puts \"#{program_name}, version #{PROGRAM_VERSION}\"\n exit\n }\n ]\n ]\nend",
"def options\n # If there's no existing TODO file, generate one\n return DEFAULT_OPTIONS unless todo_exists?\n\n match = generation_command.match(COMMAND_REGEX)\n return DEFAULT_OPTIONS unless match\n\n options = match[1].split(' ')\n Options.new.parse(options).first\n end",
"def build_selected_options options=nil\n options ||= vote_proposal_options\n options.map(&:name).sort.join(\"|\") \n end",
"def options\n opts = \"\"\n @options.each do |key,val|\n unless val.nil?\n val = val.shellescape if key == 'uri'\n opts << \"--#{key}=#{val} \"\n end\n end\n opts.gsub!(\"--hog=true\", \"--hog\")\n opts.gsub!(\"--hog=false\", \"\")\n opts.gsub!(\"--verbose=true\", \"--verbose\")\n opts.gsub!(\"--verbose=false\", \"\")\n opts.gsub!(\"--session-cookies=true\", \"--session-cookies\")\n opts.gsub!(\"--session-cookies=false\", \"\")\n opts\n end",
"def to_switches(options)\n options.map do |key, value|\n case value\n when true\n \"--#{key}\"\n when Array\n \"--#{key} #{value.map { |v| v.inspect }.join(\" \")}\" unless value.empty?\n when Hash\n \"--#{key} #{value.map { |k, v| \"#{k}:#{v}\" }.join(\" \")}\" unless value.empty?\n when nil, false\n \"\"\n else\n \"--#{key} #{value.inspect}\"\n end\n end.join(\" \")\n end",
"def get_options; end",
"def options_text\n versioned_definition.options_text\n end",
"def get_options(options_string)\n opts = Slop.new :autocreate => true\n opts.parse options_string\n\n opts.to_hash.delete_if { |k,v| v.nil? }\n end",
"def get_options()\n\n all_options = []\n\n @raw.raw_options.each do |set|\n \n set.each do |option|\n all_options.push(option)\n end\n\n end\n\n @options = all_options.flatten.uniq.sort_by(&:downcase)\n\n end",
"def full_options\n options_collection_as_string self\n end",
"def parse_options(options_array = {})\n options_array.inject(\"\"){|acc, elem| acc += \" #{elem[0].to_s}='#{elem[1]}'\"}\n end",
"def transform_options(options)\n options.inject([]) do |result, (option, value)|\n option = option.to_s.gsub(/_/, '-')\n \n result << if option.size == 1\n value == true ? \"-#{option}\" : \"-#{option} '#{e(value)}'\" \n else\n value == true ? \"--#{option}\" : \"--#{option}='#{e(value)}'\" \n end\n end\n end",
"def parse_option\n case params[:option]\n when \"id\", \"single_id\"\n # Render the id select field.\n \"shared/id_select\"\n when \"id_list\", \"id_array\"\n # Render the id multi select field.\n \"shared/id_multi_select\"\n when \"conditions_array\", \"conditions_hash\"\n # Render the conditions fields.\n @partial = \"shared/conditions\"\n when \"sub_method\", \"amount\", \"dynamic_find_by\", \"batches\", \"attributes\"\n # Render the corresponding option field(s).\n params[:option]\n end\n end",
"def valid_options\n []\n end",
"def option_methods\n @option_methods ||= []\n end",
"def option *keys\n key = keys.map(&:to_s).join('.').gsub(/::/, '.').split('.')\n\n MX.synchronize {\n # options.foo!.bar!.baz!\n [key, key[1..-1]].map do |candidate|\n candidate && candidate.inject(options) do |memo, k|\n memo.public_send(k.to_s) unless memo.nil?\n end\n end.compact.first\n }\n end",
"def options\n VALID_OPTIONS_KEYS.reduce({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def options1 \n <<~OPTIONS\n\n What would you like to know about? :\n\n 1. Traits\n 2. Physical Traits\n 3. Ruling Planet\n 4. Compatible signs\n 5. Dates\n 6. Favorite things\n 7. More\n OPTIONS\n end",
"def options\n VALID_OPTIONS_KEYS.reduce({}) do |option, key|\n option.merge!(key => send(key))\n end\n end",
"def process\n begin\n aux_option = remove_unwanted_chars(@_option)\n\n # unprocessed option list\n option_list = aux_option.split(%r{\\*/|\\];})\n\n option_list.each do |op|\n begin\n if op.to_s.index('=[') != nil\n ntec_option = NtecOption.new\n ntec_option.options = []\n\n # get option name\n ntec_option.name = op[0..op.index('=[')-1].strip\n\n # get unprocessed option\n unprocessed_option = op[op.index('=[')+2..op.length]\n\n # process option\n if (unprocessed_option.to_s.index('],')) == nil\n\n #removes [] if its just like this data=[[zczczxc]];\n unprocessed_option = process_item_list(unprocessed_option)\n\n ntec_option.options.push(unprocessed_option.strip) # return just one item...\n else\n # split option list [A], [b], [C]\n option_items = unprocessed_option.split(%r{\\],})\n\n option_items.each do |item|\n aux_item = item.strip\n\n if aux_item != ''\n processed_item = process_item_list(aux_item)\n ntec_option.options.push(processed_item)\n end\n end\n end\n @ntec_option_list.push(ntec_option)\n end\n\n rescue Exception => e\n puts 'Error processing option: ' + e.message\n end\n end\n\n rescue Exception => e\n throw 'Error processing options: ' + e.message\n end\n end",
"def option_list\n result = @options.dup\n result << \"-o\" << @rdoc_dir\n result << \"--main\" << main if main\n result << \"--markup\" << markup if markup\n result << \"--title\" << title if title\n result << \"-T\" << template if template\n result << '-f' << generator if generator\n result\n end",
"def friendly_options(options)\n options\n end",
"def option_keys\n []\n end",
"def options\n Hash[VALID_OPTIONS_KEYS.map {|key| [key, send(key)] }]\n end",
"def string(*args, &block)\n args = [{ :using => Option, :kind => String }, *args]\n da = option(*args, &block)\n end",
"def create_standard_options\n option_separator\n option_separator 'Standard options:'\n option_config_name\n option_logging\n end",
"def all\n self::OPTIONS.map {|e| build(e) }\n end",
"def advanced_options\n return nil unless @options[:advanced]\n raise(ArgumentError, ':advanced cannot be empty.') if @options[:advanced].empty?\n\n arr = []\n @options[:advanced].each do |k, v|\n arr.push \"-#{k} #{v}\"\n end\n arr.join(' ') + ' '\n end",
"def expand_options(options)\n # its deprecated but still work to do to deprecate it fully\n # Chef.deprecated(:package_misc, \"expand_options is deprecated, use shell_out instead\")\n if options\n \" #{options.is_a?(Array) ? Shellwords.join(options) : options}\"\n else\n \"\"\n end\n end",
"def _parse_options(option_string)\n\n return [] unless option_string\n\n options_list = []\n options_list = option_string.split(\"#\").map do |option|\n { \"name\" => option.split(\"=\").first, \"value\" => option.split(\"=\").last }\n end\n\n options_list\n end",
"def parse!() options.parse!(self) end",
"def parse_options(options)\n options.collect do |key, val|\n str = \"#{key}: \"\n if val.kind_of? Hash\n str += \"{\" + parse_options(val) + \"}\"\n elsif val.kind_of? Array\n str += \"[ \" + val.collect { |v| \"'#{v}'\" }.join(\", \") + \" ]\"\n else\n str += (val.kind_of?(String) ? \"'#{val}'\" : val.to_s)\n end\n str\n end.join(',')\n end",
"def to_s\n @options.join \" \"\n end",
"def base_options\n [valid?(new_resource._?(:secure_storage, '-sSF')),\n valid?(new_resource._?(:master_passwd, '-mPF')),\n new_resource._?(:accept_license, '-acceptLicense'),\n ((new_resource.output == :silent) ? '-s' :\n (new_resource.output == :verbose) ? '-sP' :\n (new_resource.output == :debug) ? '-sVP' : '-sP')]\n end",
"def parse_options(opt_string)\n options = []\n string_delimiter = word = \"\"\n in_regexp = in_string = false\n\n opt_string.each_char do |c|\n if !(in_string || in_regexp) && (c == '\"' || c == '\\'')\n in_string = true\n string_delimiter = c\n elsif in_string && c == string_delimiter\n in_string = false\n elsif !(in_regexp || in_string) && c == '/'\n word << c\n in_regexp = true\n elsif in_regexp && c == '/'\n word << c\n in_regexp = false\n elsif c =~ /\\s/ && !in_string && !in_regexp\n options << word unless word.chomp == ''\n word = \"\"\n else\n word << c\n end\n end\n\n # Add the last argument\n if in_string\n raise \"Unterminated string!\"\n else\n options << word\n end\n\n options\nend",
"def separator(str)\n # We store separators as simple strings in the options array to maintain\n # order. They are ignored by the parser.\n @@options << str\n end",
"def parse_options(options)\n parsed_options = \"\"\n parsed_options << translate_option_key(:admin_email, \"ServerAdmin\", options)\n parsed_options << translate_option_key(:document_root, \"DocumentRoot\", options)\n parsed_options << translate_option_key(:aliases, \"ServerAlias\", options)\n parsed_options << translate_option_key(:directory_index,\"DirectoryIndex\", options)\n parsed_options << translate_option_key(:error_log, \"ErrorLog\", options)\n parsed_options << translate_option_key(:custom_log, \"CustomLog\", options)\n end",
"def options\n options_string, options = @match[10], {database: database}\n\n unless options_string.nil?\n options_string.split(/\\&/).each do |option_string|\n key, value = option_string.split(/=/)\n\n if value == \"true\"\n options[key.to_sym] = true\n elsif value == \"false\"\n options[key.to_sym] = false\n elsif value =~ /[\\d]/\n options[key.to_sym] = value.to_i\n else\n options[key.to_sym] = value.to_sym\n end\n end\n end\n\n options\n end",
"def options\n ops = {}\n @options.each_value do |data|\n if data.given?\n if !data.short_name.nil?\n ops[data.short_name] = nil\n else\n ops[data.long_name] = nil\n end\n end\n end\n return ops.keys\n end",
"def all\n @options\n end",
"def putOptionsSimple\n puts 'Option 1: Print code'\n puts 'Option 2: Print name'\n puts 'Option 3: Print country'\n puts 'Option 4: Print continent'\n puts 'Option 5: Print Timezone'\n puts 'Option 6: Print Latituted and Longitude'\n puts 'Option 7: Print population'\n puts 'Option 8: Print region'\n puts 'Option 9: List cities within reach'\n puts 'Option 10: Escape'\n \n option = gets\n option = checkEndCon(option.to_i, 1, 10)\n return option\n end",
"def additional_options\n @additional_options.join(\"\\s\")\n end",
"def options_string\n self.form_field_options.map {|ffo| ffo.label}.join(', ')\n end",
"def strings\n @options[:strings].\n sort_by {|k, v| k}.\n map {|(k,v)| v.join(\"\")}.\n join(\"\")\n end",
"def normalize_options(options)\n # Set default values\n options[:num_blocks] ||= 0\n options[:block_size] ||= 0\n options[:split_across] = true if options[:split_across].nil?\n options[:num_words] ||= 0\n\n # If we get num_blocks and block_size, then the user's done something\n # wrong; just take block_size\n if options[:num_blocks] > 0 && options[:block_size] > 0\n options[:num_blocks] = 0\n end\n\n # Default to a single block unless otherwise specified\n if options[:num_blocks] <= 0 && options[:block_size] <= 0\n options[:num_blocks] = 1\n end\n\n # Make sure num_words isn't negative\n if options[:num_words] < 0\n options[:num_words] = 0\n end\n\n # Copy over the parameters to member variables\n @num_blocks = options[:num_blocks]\n @block_size = options[:block_size]\n @split_across = options[:split_across]\n @num_words = options[:num_words]\n\n # We will eventually set both @num_blocks and @block_size for our inner\n # loops, so we need to save which of these is the \"primary\" one, that\n # was set by the user\n if @num_blocks > 0\n @block_method = :count\n else\n @block_method = :words\n end\n end",
"def compile_options\n str = String.new\n @options.each { |o| str = str + ' ' + o.compile }\n return str\n end",
"def assign_all_options_array\n @start_rest_options_array ||= 0.step(3600,5).collect{ |x| [(x > 0 ? sprintf(\"%2s\\'%02.0f\\\"\",x/60, x%60) : '-'), x] }\n @pause_options_array ||= 0.step(1800,5).collect{ |x| [(x > 0 ? sprintf(\"%2s\\'%02.0f\\\"\",x/60, x%60) : '-'), x] }\n #@exercise_options_array ||= [[nil,nil]] + Exercise.to_dropdown()\n @exercise_options_array ||= [[nil,nil]] + Exercise.to_dropdown( nil, :id, :get_friendly_description )\n @step_type_options_array ||= TrainingStepType.to_unsorted_dropdown( nil, :id, :i18n_short )\n @arm_aux_options_array ||= ArmAuxType.to_dropdown( nil, :id, :i18n_description )\n @kick_aux_options_array ||= KickAuxType.to_dropdown( nil, :id, :i18n_description )\n @body_aux_options_array ||= BodyAuxType.to_dropdown( nil, :id, :i18n_description )\n @breath_aux_options_array ||= BreathAuxType.to_dropdown( nil, :id, :i18n_description )\n end",
"def program_options\n [\n # The values of the array are,\n # [long_option, short_option and parameter, description, code to execute]\n ['--verbose', '-v', \"Log to standard output.\",\n lambda { |value| options.verbose = true }\n ],\n ['--version', '-V', \"Display the program version.\",\n lambda { |value|\n puts \"#{program_name}, version #{PROGRAM_VERSION}\"\n exit\n }\n ]\n ]\nend"
] |
[
"0.68131024",
"0.67295176",
"0.66375643",
"0.6523511",
"0.6333441",
"0.62912744",
"0.6160395",
"0.6158594",
"0.61347073",
"0.61346024",
"0.5998505",
"0.5959725",
"0.59404093",
"0.5923119",
"0.5923119",
"0.58971095",
"0.5851608",
"0.58389515",
"0.5818988",
"0.5818988",
"0.58188105",
"0.5815511",
"0.5798305",
"0.57945925",
"0.5792077",
"0.5775237",
"0.5771155",
"0.5769367",
"0.57669944",
"0.5766769",
"0.57470953",
"0.57399875",
"0.5737993",
"0.57230294",
"0.57116014",
"0.57046515",
"0.56966877",
"0.5687394",
"0.5685657",
"0.5682071",
"0.56744945",
"0.56739926",
"0.5672622",
"0.56725097",
"0.5671496",
"0.56628984",
"0.5651951",
"0.5651951",
"0.5651951",
"0.5651951",
"0.5651951",
"0.5651951",
"0.5651535",
"0.5649037",
"0.5644462",
"0.5642612",
"0.5637055",
"0.5635542",
"0.56307167",
"0.56286216",
"0.5628569",
"0.56173897",
"0.5614851",
"0.5613901",
"0.56110317",
"0.55962735",
"0.5594089",
"0.5588732",
"0.5573333",
"0.557216",
"0.5562942",
"0.5562886",
"0.55619967",
"0.55615276",
"0.55576867",
"0.5555474",
"0.55537975",
"0.55261326",
"0.55216646",
"0.5520525",
"0.552047",
"0.55152625",
"0.5514831",
"0.5506024",
"0.55035895",
"0.55034316",
"0.55012393",
"0.5500161",
"0.54987776",
"0.5490272",
"0.5464549",
"0.54641956",
"0.5461871",
"0.545938",
"0.5454742",
"0.54539484",
"0.5453843",
"0.5442157",
"0.54315495",
"0.5425314"
] |
0.5540982
|
77
|
An array of the argument types of a given option. This can be used in blocks.
|
def arguments command
@@auto_completion_arguments[command]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def argument_types\n @arguments.map(&:type)\n end",
"def types\n @opt_types.values\n end",
"def valid_argument_list!(rest, *types)\n if rest.size == types.size\n result = rest.zip(types).collect do |arg, type|\n if String == type\n arg.to_s\n elsif Symbol == type\n arg.to_sym\n elsif Integer\n arg.to_i\n else\n raise OptionParser::InvalidArgument, arg\n end\n end\n result.size == 1 ? result[0] : result\n elsif rest.size < types.size\n raise OptionParser::MissingArgument\n else\n raise OptionParser::NeedlessArgument, rest\n end\n end",
"def argument_types?(*value)\n true\n end",
"def each_argT(&ruby_block)\n # No ruby block? Return an enumerator.\n return to_enum(:each_argT) unless ruby_block\n # A ruby block? Apply it on each agument type.\n @argTs.each(&ruby_block)\n end",
"def command_arguments(options={})\n args = []\n args.concat(['--type', options[:type].to_s]) if options[:type]\n args.concat(['--line-break', options[:line_break].to_s]) if options[:line_break]\n args.concat(['--charset', options[:charset].to_s]) if options[:charset]\n\n if options[:type].to_s == 'js'\n args << '--nomunge' unless options[:munge]\n args << '--preserve-semi' if options[:preserve_semicolons]\n args << '--disable-optimizations' unless options[:optimize]\n end\n\n args\n end",
"def argument_types=(*value)\n end",
"def typeOf _args\n \"typeOf _args;\" \n end",
"def archetype_args\n tok = []\n @returns.map { |ent| tok << \"&#{ent.name}\" }\n @accepts.map { |ent| tok << ent.name }\n tok.join(', ')\n end",
"def type _args\n \"type _args;\" \n end",
"def names\n @opt_types.keys.map {|e| undasherize e }\n end",
"def args\n return [] unless options[\"args\"]\n options[\"args\"].map do |options|\n Argument.new options\n end\n end",
"def options_for_supported_types\n Mapping::SUPPORTED_TYPES.map do |type|\n [type.titleize.to_s, type]\n end\n end",
"def cmd_types argv\n setup argv\n response = @api.types\n msg response\n return response\n end",
"def valid_options\n %i(\n\n ) # end array\n end",
"def types=(_arg0); end",
"def describe_types\n [@options[:type]].flatten.join('/')\n end",
"def arg_val_list(args_count)\n return \"void\" if (args_count == 0)\n arguments = []\n args_count.times { |i| arguments << \"ARG#{i}_TYPE arg#{i}\" }\n arguments.join(\", \")\nend",
"def infer_args(opts)\n opts.map do |hash|\n if hash.has_key?(:name)\n hash\n else\n check = [:type, :match, :constraint, :within, :default]\n if check.any? {|key| hash.has_key?(key) }\n hash.merge! :name => 'arg'\n end\n\n if hash.has_key?(:default) && !hash.has_key?(:optional)\n hash.merge! :optional => true\n end\n\n hash\n end\n end\n end",
"def params() @param_types end",
"def option_metas\n meta_or ['options', 'opts', 'vars'], []\n end",
"def option_type; end",
"def my_function(argument_a, argument_b, *args)\n puts argument_a\n puts argument_b\n p args.class.name # this is now an array\n puts args\nend",
"def options(opt)\n []\n end",
"def parameter_types; end",
"def find_argument_variations(args)\n return @variations if args.first.is_a?(Symbol) and args.last == :any\n @variations.select { |ar| ar.args == args }\n end",
"def get_input_types(env, receiver)\n inputs.map{|input| get_type(env, input, receiver)}\n end",
"def all_types(arg_type)\n arg_type.ancestors\n end",
"def args_of(opt)\n args_of_opt = []\n\n # Return an array of the arguments between opt and the next option,\n # which all start with \"-\"\n @@args.slice(@@args.index(opt)+1, @@args.length).select do |arg|\n if arg[0].chr != \"-\"\n args_of_opt << arg\n else\n break\n end\n end\n args_of_opt\n end",
"def types(options={})\n select_from_hash_array(TRANSACTION_METHODS, :type, {}, options)\n end",
"def types(options={})\n select_from_hash_array(TRANSACTION_METHODS, :type, {}, options)\n end",
"def option_type_config; end",
"def for_option_parser\n [short, long, return_type, description].flatten.reject{ |o| o.to_s.empty? }\n end",
"def slot_type_for(name)\n if index = @callable.arguments_type.variable_index(name)\n return [\"arg#{index}\".to_sym]\n end\n index = @callable.frame_type.variable_index(name)\n raise \"no such local or argument #{name} for #{callable.name}:#{callable.frame_type.hash}\" unless index\n return [\"local#{index}\".to_sym]\n end",
"def get_validation_on_options(type,*args)\n validations_options=[:allow_nil,:allow_blank,:message,:on]\n case type\n when :kinds\n result=[]\n args.each do |a| \n a=a.keys.first if a.is_a?(Hash)\n result << a unless validations_options.include?(a)\n end\n when :attribute_options\n result={}\n args.each{|a| if a.is_a?(Hash) && validations_options.include?(a.keys.first) then result=result.merge(a) end}\n when :kind_options\n result=[]\n formated_options={}\n args.each do |a|\n if a.is_a?(Hash)\n a.each do |k,v|\n unless validations_options.include?(k)\n formated_options[:kind],formated_options[:options]=k,a[k]\n result << formated_options.dup\n end\n end\n end\n end\n when :message\n result=args.last if args.last.is_a?(String)\n end\n result \n end",
"def options(*args, &block); end",
"def validate_choice_array(opts)\n if opts[:choice].is_a?(Array)\n case opts[:type]\n when \"string\"\n validator = [ String ]\n when \"array\"\n validator = [ Array ]\n when \"hash\"\n validator = [ Hash ]\n when \"symbol\"\n validator = [ Symbol ]\n when \"boolean\"\n validator = [ TrueClass, FalseClass ]\n when \"numeric\"\n validator = [ Numeric ]\n end\n\n opts[:choice].each do |choice|\n validate( { choice: choice }, { choice: { kind_of: validator } } )\n end\n end\n end",
"def types(array)\n yield(array)\nend",
"def getOptions\n @options = Array.new\n # format of options argument\n optionsPattern = Regexp.new(/\\-[\\w]+/)\n # check to see if options are formatted correctly\n if optionsPattern.match(ARGV[0])\n # get each option and push them to an array \n # start at 1 to ignore - \n for i in 1..ARGV[0].length - 1\n @options.push(ARGV[0][i])\n end # -- end for loop to get options\n else\n abort(\"First argument needs to be an option.\\nExample:\\n\\t ruby OSQuery -i Blood_rune\")\n end # -- end valid options check\nend",
"def have_all_types?\n @args.each do |a|\n unless @argtype.has_key? a\n return false\n end\n end\n true\n end",
"def types(types); end",
"def args_for_node(node)\n Array(node)[1..-1].select { |arg| arg.is_a? Symbol }\n end",
"def test_getOptions\n testMe = InputProcessor.new\n assert_instance_of Array, testMe.getOptions, \"getOption does not return array class\" \n testMe.getOptions.all? do |x|\n assert(x.size == 2, \"Illegal data #{x.inspect} data size mismatch\")\n assert_kind_of String, x.first, \"First element #{x.first.inspect} is not kind of String\"\n assert_kind_of Fixnum, x.last, \"Last element #{x.last.inspect} is not kind of Fixnum\"\n end \n end",
"def syntax\n t = @cmd_args\n t = [[t]] if !t.is_a? Array\n\n args = [] \n count = 0\n t.each do |expected_array|\n count += 1\n if count == 1\n str = \"Syntax: #{@cmd_name}\"\n else\n str = \" #{@cmd_name}\"\n end\n expected_array.each do |expected|\n # each expected arg.\n str += case expected\n when :arg_none then \"\"\n when :arg_dir! then \" <direction>\"\n when :arg_str! then \" <string literal>\"\n when :arg_word!then \" <word>\"\n when :arg_int! then \" <#>\"\n when :arg_obj_inv! then \" <item>\"\n when :arg_obj_room! then \" <item>\"\n when :arg_obj_inv_or_room! then \" <item>\"\n when :arg_class! then \" <Class>\"\n when :arg_player_in_game! then \" <player in game>\"\n when :arg_player_offline! then \" <any player>\"\n when :arg_actor_room! then \" <npc/player>\"\n when String then \" \" + expected \n else \"\"\n \n end\n end \n args << str\n end\n return args\n end",
"def alternative_types\n [self]\n end",
"def ktlint_arguments(options)\n (options.\n # filter not null\n reject { |_key, value| value.nil? }.\n # map booleans arguments equal true\n map { |key, value| value.is_a?(TrueClass) ? [key, \"\"] : [key, value] }.\n # map booleans arguments equal false\n map { |key, value| value.is_a?(FalseClass) ? [\"no-#{key}\", \"\"] : [key, value] }.\n # replace underscore by hyphen\n map { |key, value| [key.to_s.tr('_', '-'), value] }.\n # prepend '--' into the argument\n map { |key, value| [\"--#{key}\", value] }.\n # reduce everything into a single string\n reduce('') { |args, option| option[1] == \"\" ? \"#{args} #{option[0]}\" : \"#{args} #{option[0]}=#{option[1]}\" }).\n # strip leading spaces\n strip\n end",
"def determine_arguments\n s = Marshal.load(Marshal.dump(self)) # sexp handling is not clean cut\n raise \"what is this?\" unless s.sexp.sexp_type == :iter && s.sexp[1].sexp_type == :call && s.sexp[1][1] == nil && s.sexp[1][2] == :proc && s.sexp[1][3].sexp_type == :arglist\n\n block_args = s.sexp[2]\n if block_args\n if block_args[0]==:lasgn\n # single argument\n args = [block_args[1]]\n elsif block_args[0]==:masgn\n # multiple arguments\n args = block_args[1]\n raise \"unsupported argument type #{args}\" unless args[0]==:array\n args = args[1..-1].map{ |arg|\n raise \"unsupported argument type #{arg}\" unless arg[0]==:lasgn\n arg[1]\n }\n else\n raise \"unsupported argument type #{args}\"\n end\n end\n\n # maybe we can fix the input so we don't have to repair it here?\n @args = @args[-args.size..-1] if args and args.size != @args.size\n\n @named_args = Hash[*args.zip(@args[-args.size..-1]).flatten] if args\n @named_args ||= {}\n end",
"def param_array(keys)\n puts \"Entering param_array '#{@sy}'\" if DEBUG\n type = nil\n \n if @sy.type == TokenType::ARRAY_TOKEN\n next_token\n if @sy.type == TokenType::OF_TOKEN\n next_token\n type = param_type(keys | Array.follow)\n else\n error(\"Line #{@sy.line_number} expected 'of', but saw '#{@sy.text}'\", keys | Array.follow)\n end\n else\n error(\"Line #{@sy.line_number} expected 'array', but saw '#{@sy.text}'\", keys | Array.follow)\n end\n puts \"Leaving param_array '#{@sy}'\" if DEBUG\n \n TypeNode.new \"array of #{type.type}\"\n end",
"def process_args(exp)\n args = []\n\n until exp.empty? do\n arg = exp.shift\n name = arg.first.to_s.sub(/^\\*/, '').intern\n type = arg.c_type\n @env.add name, type\n args << \"#{self.class.c_type(type)} #{name}\"\n end\n\n return \"(#{args.join ', '})\"\n end",
"def parameterize *opts\n opts[0].each_with_index do |a, index|\n return nil if opts[0].count == 1\n next if index == 0\n return a if a.is_a?(opts[1])\n end\n return nil\n end",
"def value_types=(_arg0); end",
"def check_arguments arguments\n arguments.each_with_index do |argument, index|\n next if argument.is_a? Numeric\n next if argument.is_a? String\n next if argument.is_a? Symbol\n next if argument.is_a? Hash\n next if argument.is_a? NilClass\n next if argument.is_a? TrueClass\n next if argument.is_a? FalseClass\n\n raise ArgumentError, \"Cannot send complex data for block argument #{index + 1}: #{argument.class.name}\"\n end\n\n arguments\n end",
"def extract_opt_args\n if args.last.is_a?(Sexp) and args.last.type == :block\n opt_args = args.pop\n opt_args.shift\n opt_args\n end\n end",
"def type(*args); end",
"def source_type_options_all\n options = []\n Description.all_source_types.each do |type|\n options << [:\"form_description_source_#{type}\".l, type]\n end\n options\n end",
"def arg_check(args, types = nil, server = nil)\n return args unless types\n\n args.each_with_index.map do |arg, i|\n next arg if types[i].nil? || types[i] == String\n\n if types[i] == Integer\n begin\n Integer(arg, 10)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Float\n begin\n Float(arg)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Time\n begin\n Time.parse arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == TrueClass || types[i] == FalseClass\n if arg.casecmp('true').zero? || arg.downcase.start_with?('y')\n true\n elsif arg.casecmp('false').zero? || arg.downcase.start_with?('n')\n false\n end\n elsif types[i] == Symbol\n arg.to_sym\n elsif types[i] == Encoding\n begin\n Encoding.find arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == Regexp\n begin\n Regexp.new arg\n rescue ArgumentError\n nil\n end\n elsif types[i] == Rational\n begin\n Rational(arg)\n rescue ArgumentError\n nil\n end\n elsif types[i] == Range\n begin\n if arg.include? '...'\n Range.new(*arg.split('...').map(&:to_i), true)\n elsif arg.include? '..'\n Range.new(*arg.split('..').map(&:to_i))\n end\n rescue ArgumentError\n nil\n end\n elsif types[i] == NilClass\n nil\n elsif [Discordrb::User, Discordrb::Role, Discordrb::Emoji].include? types[i]\n result = parse_mention arg, server\n result if result.instance_of? types[i]\n elsif types[i] == Discordrb::Invite\n resolve_invite_code arg\n elsif types[i].respond_to?(:from_argument)\n begin\n types[i].from_argument arg\n rescue StandardError\n nil\n end\n else\n raise ArgumentError, \"#{types[i]} doesn't implement from_argument\"\n end\n end\n end",
"def types\n Tk.execute(:image, :types).to_a(&:to_sym)\n end",
"def paramstype\n \"Array\"\n end",
"def required_args\n args.select &:required\n end",
"def isArray _args\n \"isArray _args;\" \n end",
"def new_option_type_option_types\n [\n {'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1},\n {'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'displayOrder' => 2},\n {'shorthand' => '-l', 'fieldName' => 'labels', 'fieldLabel' => 'Labels', 'type' => 'text', 'required' => false, 'noPrompt' => true, 'processValue' => lambda {|val| parse_labels(val) }, 'displayOrder' => 3},\n {'fieldName' => 'fieldName', 'fieldLabel' => 'Field Name', 'type' => 'text', 'required' => true, 'description' => 'This is the input property that the value gets assigned to.', 'displayOrder' => 4},\n {'code' => 'optionType.type', 'fieldName' => 'type', 'fieldLabel' => 'Type', 'type' => 'select', 'selectOptions' => [{'name' => 'Text', 'value' => 'text'}, {'name' => 'Password', 'value' => 'password'}, {'name' => 'Number', 'value' => 'number'}, {'name' => 'Checkbox', 'value' => 'checkbox'}, {'name' => 'Select', 'value' => 'select'}, {'name' => 'Hidden', 'value' => 'hidden'}], 'defaultValue' => 'text', 'required' => true, 'displayOrder' => 5},\n {'fieldName' => 'optionList', 'fieldLabel' => 'Option List', 'type' => 'select', 'optionSource' => 'optionTypeLists', 'required' => true, 'dependsOnCode' => 'optionType.type:select', 'description' => \"The Option List to be the source of options when type is 'select'.\", 'displayOrder' => 6},\n {'fieldName' => 'fieldLabel', 'fieldLabel' => 'Field Label', 'type' => 'text', 'required' => true, 'description' => 'This is the input label that shows typically to the left of a custom option.', 'displayOrder' => 7},\n {'fieldName' => 'placeHolder', 'fieldLabel' => 'Placeholder', 'type' => 'text', 'displayOrder' => 8},\n {'fieldName' => 'helpBlock', 'fieldLabel' => 'Help Block', 'type' => 'text', 'description' => 'This is the explaination of the input that shows typically underneath the option.', 'displayOrder' => 9},\n {'fieldName' => 'defaultValue', 'fieldLabel' => 'Default Value', 'type' => 'text', 'displayOrder' => 10},\n {'fieldName' => 'required', 'fieldLabel' => 'Required', 'type' => 'checkbox', 'defaultValue' => false, 'displayOrder' => 11},\n {'fieldName' => 'exportMeta', 'fieldLabel' => 'Export As Tag', 'type' => 'checkbox', 'defaultValue' => false, 'description' => 'Export as Tag.', 'displayOrder' => 12},\n {'fieldName' => 'verifyPattern', 'fieldLabel' => 'Verify Pattern', 'type' => 'text', 'dependsOnCode' => 'optionType.type:text', 'description' => 'A regexp string that validates the input, use (?i) to make the matcher case insensitive', 'displayOrder' => 13},\n ]\n end",
"def to_options_array\n options_array = []\n attributes.each do |attr_name, value|\n next if value.blank?\n\n # explicit check for == true to flag-only options that have no value, like --extract \"['cluster', 'metadata']\"\n if value == true\n options_array << Parameterizable.to_cli_opt(attr_name)\n else\n options_array += [Parameterizable.to_cli_opt(attr_name), value.to_s]\n end\n end\n options_array << self.class::PARAMETER_NAME if defined? self.class::PARAMETER_NAME\n options_array\n end",
"def option_methods\n @option_methods ||= []\n end",
"def param_types\n schema.param_types\n end",
"def type_params; end",
"def type_params; end",
"def type_params; end",
"def type_params; end",
"def type_params; end",
"def options(opt); end",
"def options(opt); end",
"def additional_spec_options_collection\n args.collect do |key, value|\n case key.to_s\n when \"minimum\"\n \"is_at_least(#{value})\"\n when \"maximum\"\n \"is_at_most(#{value})\"\n when \"in\", \"within\"\n \"is_at_least(#{value.first}).is_at_most(#{value.last})\"\n when \"is\"\n \"is_equal_to(#{value})\"\n else\n raise(ArgumentError, \"Unknown property: #{key}\")\n end\n end\n end",
"def process_arguments(args, sender, type_registry)\n variables = []\n @bareword_slots.each_with_index do |bareword, i|\n if bareword # Bare words must match all incoming arguments or fail.\n return nil if args[i] != bareword \n elsif @words[i].type # This is a typed variable (apply type converter).\n variables << process_typed_argument(args, i, sender, type_registry)\n else # Untyped-variable. \n variables << args[i]\n end\n end\n\n variables\n end",
"def valid_args(type)\n case type\n when 'search' then %i[q format addressdetails extratags namedetails viewbox bounded exclude_place_ids limit accept-language email]\n when 'reverse' then %i[format lat lon zoom addressdetails extratags namedetails accept-language email]\n else []\n end\n end",
"def multi_manipulate_option(options)\n if options == nil\n return\n end\n options.each do |manip_type, *args|\n if manip_type != nil\n manipulate_option_raw(manip_type.to_sym, *args )\n print \".\"\n end\n end\n end",
"def optparse_args\n if short\n [\"--#{name}\", \"-#{short}\", desc, :REQUIRED]\n else\n [\"--#{name}\", desc, :REQUIRED]\n end\n end",
"def arguments_valid?\n begin\n @validoptions = BoilermakerOptions.new(options)\n @validoptions.validate\n # pp @validoptions.args\n return @validoptions.args\n rescue => error\n # pp x.args\n puts error.message + \"\\n\"\n exit\n end\n end",
"def parse_yardopts_options(*args); end",
"def supported_hook_type_classes\n supported_hook_types.map do |file|\n file.split('-').map(&:capitalize).join\n end\n end",
"def options(opt)\n end",
"def type_opts\n opts.reject{ |key, value| NON_TYPE_OPTS.include? key }\n end",
"def arglists\n if @call_seq then\n @call_seq\n elsif @params then\n \"#{name}#{param_seq}\"\n end\n end",
"def arglists\n if @call_seq then\n @call_seq\n elsif @params then\n \"#{name}#{param_seq}\"\n end\n end",
"def types\n @stmt.types\n end",
"def list_selected_options\n list_selected_options = []\n @selected_options.each do |option|\n list_selected_options << option.type\n end\n return list_selected_options\n end",
"def detail_args_for(options); end",
"def get_args( from: '', required: false, default_value: [], comment: '' )\n cmd_options = @options['command_line_options'][from]\n # Auto documentation of this option\n @doc.push \"Option to pass arguments from: #{from},\\tdefault_value :#{default_value},\\tcomment :#{comment}\"\n if cmd_options.class == Array\n cmd_options = cmd_options.join ' '\n cmd_options = \"\\\"#{cmd_options}\\\"\" # return with quotes\n else\n @errors.push \" Arguments option #{from} should be an Array. #{cmd_options.class} found\"\n end\n end",
"def check_arg_structure(args)\n valid = true\n valid &&= args.class == Array\n \n args.each do |a|\n valid &&= a.class == Array \n valid &&= a.size == 2\n a.each do |s|\n valid &&= s.class == String\n end\n end\n\n raise \"Imported function arguments in invalid form\" unless valid\n end",
"def check_arg_structure(args)\n valid = true\n valid &&= args.class == Array\n \n args.each do |a|\n valid &&= a.class == Array \n valid &&= a.size == 2\n a.each do |s|\n valid &&= s.class == String\n end\n end\n\n raise \"Imported function arguments in invalid form\" unless valid\n end",
"def types\n @types ||= []\n end",
"def required_options\n []\n end",
"def required_options\n []\n end",
"def gen_each_arg(joinwith=\"\\n\")\n s = []\n args.each do |name|\n t = yield name, argtype[name]\n s << t unless t.nil?\n end\n return s.join(joinwith)\n end",
"def thor_options_to_optparse\n flags = []\n %i[color progress debug interactive].each do |option|\n if options[option] then flags << \"--#{option}\"\n else flags << \"--no-#{option}\"\n end\n end\n flags\n end",
"def accept_args(args)\n while /^-+(.+)/ === args[0]\n option = args.shift\n option_method_name = \"option_#{$1}\"\n unless respond_to?(option_method_name)\n raise UsageException, \"Unrecognised option: #{option}\"\n end\n option_method = method(option_method_name)\n parameters = []\n option_method.arity.times { parameters << args.shift }\n option_method.call(*parameters)\n end\n @targets = args\n self\n end",
"def option_keys\n []\n end",
"def scan_arguments(*how)\n if how.count == 1\n pattern = how.first\n else\n left_delimiter = how[0] || self.left_delimiter\n right_delimiter = how[1] || self.right_delimiter\n\n return [] unless left_delimiter && right_delimiter\n\n pattern = Regexp.new(Regexp.escape(left_delimiter) + '(.*?)' + Regexp.escape(right_delimiter))\n end\n\n @arguments = @base.scan(pattern).flatten\n end",
"def arguments(required, *optional)\n puts \"required: #{required}\"\n puts \"optional: #{optional}\"\nend",
"def options\n args = []\n\n # add all subtask options\n @subtasks.each_value do |task|\n args += task.arguments\n end\n\n # add the task options\n @options.each do |name,value|\n opt = get_option(name)\n args += opt.arguments(value) if opt\n end\n\n return args\n end",
"def array?\n GtaScm::Types::ARRAY_TYPES.include?(self.arg_type_id)\n end",
"def arguments\r\n args = OpenStudio::Ruleset::OSArgumentVector.new\r\n\r\n #make choice argument for facade\r\n choices = OpenStudio::StringVector.new\r\n choices << \"MessagePack\"\r\n choices << \"CSV\"\r\n choices << \"Both\"\r\n output_format = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"output_format\", choices)\r\n output_format.setDisplayName(\"Output Format\")\r\n output_format.setDefaultValue(\"Both\")\r\n args << output_format\r\n\r\n args\r\n end"
] |
[
"0.76946187",
"0.69814646",
"0.62571347",
"0.6144715",
"0.6029329",
"0.60183674",
"0.5975797",
"0.5949074",
"0.5856",
"0.5834082",
"0.5785334",
"0.5737654",
"0.57023454",
"0.5683804",
"0.5661047",
"0.56579965",
"0.5611273",
"0.56039774",
"0.5590399",
"0.5587844",
"0.55810493",
"0.557795",
"0.55512935",
"0.55486286",
"0.55366015",
"0.5536345",
"0.5459294",
"0.5437268",
"0.54371434",
"0.54185104",
"0.54185104",
"0.54110163",
"0.5406572",
"0.53797334",
"0.5370827",
"0.5367554",
"0.5362328",
"0.533944",
"0.53152335",
"0.53062713",
"0.5300662",
"0.5298372",
"0.52955735",
"0.5295329",
"0.52858365",
"0.52588576",
"0.5254629",
"0.52466106",
"0.5245455",
"0.52423716",
"0.52420485",
"0.522422",
"0.521689",
"0.520355",
"0.5196536",
"0.5195551",
"0.518704",
"0.51845586",
"0.51826966",
"0.51800597",
"0.51625526",
"0.51613647",
"0.5161311",
"0.51458704",
"0.5133027",
"0.5133027",
"0.5133027",
"0.5133027",
"0.5133027",
"0.5123194",
"0.5121744",
"0.5119891",
"0.5108297",
"0.5100983",
"0.5095907",
"0.50941664",
"0.5092962",
"0.50920427",
"0.5086125",
"0.5072381",
"0.50718135",
"0.5071707",
"0.5071707",
"0.50647557",
"0.50628674",
"0.50613135",
"0.50589085",
"0.5051818",
"0.5051818",
"0.50456494",
"0.503598",
"0.5026152",
"0.50255287",
"0.50246686",
"0.50178933",
"0.50133973",
"0.5005244",
"0.500494",
"0.4999781",
"0.49979603",
"0.4994058"
] |
0.0
|
-1
|
Remembers the current directory. It can be restored with restore_dir. This can be used in blocks.
|
def store_dir
@dir = Dir.pwd
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def restore_dir\n cd @dir\n end",
"def pop_dir\n # the first time we pop, we need to put the current on stack\n @visited_dirs.push Dir.pwd unless @visited_dirs.index(Dir.pwd)\n ## XXX make sure thre is something to pop\n d = @visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n @visited_dirs.push d\n Dir.chdir d\n @current_dir = Dir.pwd # 2019-04-24 - earlier was in post_cd but too late\n post_cd\n rescan_required\nend",
"def restore_directory\n config[\"restore_dir\"] ||= begin\n dir_name = File.join(tmp_dir, backup_name)\n if File.directory?(dir_name)\n # clean restore directory if it exists\n FileUtils.rm_r(Dir.glob(\"#{dir_name}/*\"))\n else\n FileUtils.mkdir_p(dir_name)\n end\n dir_name\n end\n end",
"def reset!\n @base_dir = @path = nil\n end",
"def teardown\n Dir.chdir @previous_wd # restore the working directory to what it was previously\n end",
"def cd( path = File.expand_path('~') )\n new_last_path = FileUtils.pwd\n if path == '-'\n if @last_path\n path = @last_path\n else\n warn 'Sorry, there is no previous directory.'\n return\n end\n end\n cd path\n @last_path = new_last_path\n ls\n end",
"def reset_repo(&block)\n yield\n=begin\n Dir.chdir(@saved_cwd){\n system 'rm', '-rf', repo4test\n if !File.directory?(repo4test)\n repo = File.join(repo4test, Juli::REPO)\n FileUtils.mkdir_p(repo)\n FileUtils.cp(File.join(repo4test, '../data/config'), repo,\n :preserve=>true)\n end\n Dir.chdir(repo4test){\n yield\n }\n }\n=end\n end",
"def cd( path = '~' )\n new_last_path = FileUtils.pwd\n if path == '-'\n unless path = Irbtools.instance_variable_get(:@last_cd_path)\n warn 'Sorry, there is no previous directory.'\n return\n end\n end\n super(File.expand_path(path))\n Irbtools.instance_variable_set(:@last_cd_path, new_last_path)\n ls\n end",
"def pop_dir\n return # 2014-07-25 - 22:43 \n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n $filterstr ||= \"M\"\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}#{$filterstr})'`.split(\"\\n\")\n post_cd\nend",
"def pop_dir\n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n display_dir\n\n return\n # old stuff with zsh\n $filterstr ||= \"M\"\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}#{$filterstr})'`.split(\"\\n\")\n post_cd\nend",
"def pristine_dir\n File.join pristine_dir_parent, name\n end",
"def reset_dir(pathname)\n\tputs \" Deleting and recreating #{pathname} folder\"\n\tFileUtils.rm_rf(pathname) unless not Dir.exist?(pathname)\n\tDir.mkdir(pathname)\nend",
"def chdir; end",
"def inside_cookbook(&block)\n cookbook_path = File.join(Strainer.sandbox_path.to_s, @cookbook.cookbook_name)\n Strainer.ui.debug \"Changing working directory to '#{cookbook_path}'\"\n original_pwd = ENV['PWD']\n\n ENV['PWD'] = cookbook_path\n success = Dir.chdir(cookbook_path, &block)\n ENV['PWD'] = original_pwd\n\n Strainer.ui.debug \"Restoring working directory to '#{original_pwd}'\"\n success\n end",
"def clean_up\n FileUtils.rm_rf \"#{@path}\" unless create_in_current_directory?\n FileUtils.rm_rf \"#{@cache}\"\n end",
"def undo()\r\n Dir.delete(@DirectoryPath)\r\n end",
"def temp_dir temp='tmp/trash'\n FileUtils.rm_rf temp\n FileUtils.mkpath temp\n Dir.chdir(temp) { yield }\n FileUtils.rm_rf temp\nend",
"def chdir(&block)\n Dir.chdir(top_level, &block)\n end",
"def pop_dir\n # the first time we pop, we need to put the current on stack\n if !$visited_dirs.index(Dir.pwd)\n $visited_dirs.push Dir.pwd\n end\n ## XXX make sure thre is something to pop\n d = $visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n $visited_dirs.push d\n Dir.chdir d\n $files = `zsh -c 'print -rl -- *(#{$sorto}#{$hidden}M)'`.split(\"\\n\")\n $patt=nil\nend",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n require 'tmpdir'\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def popd\n cd @dir_history.pop, pushd: false if @dir_history.any?\n end",
"def write_curdir\n f = File.expand_path('~/.fff_d')\n s = Dir.pwd\n File.open(f, 'w') do |f2|\n f2.puts s\n end\n # puts \"Written #{s} to #{f}\"\nend",
"def leave_test_directory(retain = false)\n raise IllegalStateException, \"No test directory found\" if !@original_directory\n Dir.chdir(@original_directory)\n @original_directory = nil\n FileUtils.rm_rf(@test_dir) if !retain\n end",
"def chdir(&block)\n Dir.chdir(self, &block)\n end",
"def working_dir(&block)\n return Dir.chdir(@working_dir, &block) if block_given?\n @working_dir\n end",
"def redo_path\n self.path = @temp_path\n end",
"def workdir\n result = base.join('cache')\n result.mkpath\n result\n end",
"def reset\n FileUtils.remove_file(@path)\n end",
"def push_dir(dir = nil)\n @directory_stack.push(Dir.pwd)\n self.chdir(dir)\n end",
"def restart_dir; end",
"def backup_dir\n @backup_dir ||= create_backup_dir\n end",
"def change_dir f\n unless File.directory? f\n perror \"#{f} is not a directory, or does not exist.\"\n return\n end\n\n # before leaving a dir we save it in the list, as well as the cursor\n # position, so we can restore that position when we return\n @visited_dirs.insert(0, Dir.pwd)\n save_dir_pos\n\n f = expand_path(f)\n Dir.chdir f\n @current_dir = Dir.pwd # 2019-04-24 - earlier was in post_cd but too late\n read_directory\n post_cd\n\n redraw_required\nend",
"def chdir(dir)\n previous_dir = File.expand_path(\".\")\n\n Dir.chdir(dir)\n begin\n @p4.cwd = File.expand_path(\".\")\n rescue\n Dir.chdir(previous_dir)\n raise\n end\n\n if block_given?\n begin\n yield dir\n ensure\n Dir.chdir(previous_dir)\n @p4.cwd = previous_dir\n end\n end\n end",
"def current_dir; end",
"def sync_dir(dir=Dir.getwd)\n @r.cmd \"setwd('#{dir}')\"\n end",
"def user_directory\n File.expand_path('~')\n end",
"def exitLocal\n @currentPath.exitName\n @root = nil if @currentPath.empty?\n end",
"def reset_signup_folder\n FileUtils.rm_rf('./tmp/signup')\nend",
"def chdir(&block)\n Dir.chdir(ROOT.join(name), &block)\n end",
"def current path=nil\n current = `pwd`.strip + \"/\"\n if path\n current + path \n else\n current\n end\nend",
"def reset\n LegacyFacter.reset\n Options[:custom_dir] = []\n Options[:external_dir] = []\n SessionCache.invalidate_all_caches\n nil\n end",
"def chdir(&block)\n ::Dir.chdir(path, &block)\n end",
"def preserve_directory(directory)\n path = File.join(directory, '.gitkeep')\n create_file path, ''\nend",
"def current_directory\n File.expand_path @current_directory\n end",
"def setup_path\n if !@repo.clone_path.nil? and !@repo.clone_path.empty?\n Dir.chdir(@repo.clone_path)\n else\n initial_path_setup\n end\n end",
"def exec_in_git_dir(&block)\n Dir.chdir(top_level, &block)\n end",
"def chdir # :yields: the Git::Path\n Dir.chdir(dir.path) do\n yield dir.path\n end\n end",
"def cd(dir = '~', pushd: true)\n dir = load_item path: expand_path(dir) unless dir.is_a? Item\n unless dir.zip?\n Dir.chdir dir\n @current_zip = nil\n else\n @current_zip = dir\n end\n @dir_history << current_dir if current_dir && pushd\n @current_dir, @current_page, @current_row = dir, 0, nil\n main.activate_pane 0\n ls\n @current_dir\n end",
"def in_temp_dir(&block)\n old_dir,ret_val = Dir.pwd, nil\n # Don't use mktemp from system since osx and linux mktemp are diferentes.\n tmpdir = File.expand_path(File.join(Dir.tmpdir,'rgithook-'+Time.now.usec.to_s+rand.to_s[2..-1]))\n \n FileUtils.mkdir_p(tmpdir)\n Dir.chdir tmpdir\n ret_val = yield tmpdir\n ensure\n Dir.chdir old_dir\n FileUtils.remove_dir(tmpdir)\n ret_val\n end",
"def store!\n unlink! @original_path\n return nil unless @tempfile_path\n\n new_path = path\n FileUtils.mkdir_p File.dirname(new_path)\n result = if @tempfile_path =~ /\\/te?mp\\//\n FileUtils.move @tempfile_path, new_path\n else\n FileUtils.copy @tempfile_path, new_path\n end\n File.chmod 0644, new_path\n reset\n result\n end",
"def clean_dir\n\n path = self.get_dir\n _clean_dir(path)\n end",
"def reset\n if File.exists?(@identity_dir) and File.directory?(@identity_dir)\n\n @files_to_clean.each do |f|\n FileUtils.rm_f(f)\n end\n \n FileUtils.mkdir_p(@identity_dir)\n\n @csr = EZSSL_CSR.new\n end\n end",
"def original_dir_path\n ::Paths::PathnameWrap.new(old_original_dir())\n end",
"def in_path(path, &blk)\n old = Dir.pwd\n Dir.chdir path\n say_status :cd, path\n yield\n Dir.chdir old\n end",
"def set_current_path; end",
"def within_dir dir, &blk\n cur_dir = Dir.getwd\n Dir.chdir(dir)\n yield\n Dir.chdir(cur_dir)\n end",
"def store_dir\n nil\n end",
"def chdir(dest, &block)\n if block\n Dir.chdir(dest, &block)\n else\n if !defined? @original_dir\n @original_dir = Dir.pwd\n @cleaners << -> { Dir.chdir(@original_dir); @original_dir=nil }\n end\n Dir.chdir(dest)\n end\n end",
"def within(directory)\n _guard_dir!(File.join(_config_store.active_backend.pwd + [directory]))\n\n _config_store.add_pwd directory\n\n yield if block_given?\n ensure\n _config_store.pop_pwd\n end",
"def original_dir\n application.original_dir\n end",
"def original_dir\n application.original_dir\n end",
"def original_dir\n application.original_dir\n end",
"def exec_in_git_dir(&block)\n curr = Dir.getwd\n result = nil\n begin\n Dir.chdir top_level\n result = yield\n rescue\n raise\n ensure\n Dir.chdir curr\n end\n result\n end",
"def pwd\n @local\n end",
"def pristine_dir_parent\n if subpath.empty?\n pristine_dir_root\n else\n File.join pristine_dir_root, subpath\n end\n end",
"def current_dir\n File.dirname(file_path)\n end",
"def cd(dir = nil)\n dir ||= homedir\n dir = expand_path(dir)\n @cwd = dir\n end",
"def set_path\n self.path = File.join(self.store_dir, self.filename)\n end",
"def cd(path,&block)\n if block\n cwd = Dir.pwd\n\n Dir.chdir(path)\n block.call()\n Dir.chdir(cwd)\n else\n Dir.chdir(path)\n end\n end",
"def temp_dir\n dir = make_temp_dir\n chown(dir, user)\n dir\n end",
"def ref_dup\n git = ::Git.open(base_path)\n git.checkout(ref)\n git.pull(\"origin\", ref)\n self.ref = git.log.first.sha\n self.path = Utility.join_path(cache_path, \"git\", ref)\n unless File.directory?(path)\n FileUtils.mkdir_p(path)\n FileUtils.cp_r(Utility.join_path(base_path, \".\"), path)\n FileUtils.rm_rf(Utility.join_path(path, \".git\"))\n end\n path\n end",
"def set_current_path(path)\n @current_path = path\nend",
"def chdir(path)\n ensure_relative_path! :chdir, path\n @path += path\n end",
"def save_dir_pos\n # the next line meant that it would not save first directory.\n # return if @sta == 0 && @cursor == 0\n\n @dir_position[Dir.pwd] = [@sta, @cursor]\nend",
"def chdir(&block)\n warn \"Path::Name#chdir is obsoleted. Use Dir.chdir.\"\n Dir.chdir(path, &block)\n end",
"def restore\n end",
"def revert_dir_pos\n @sta = 0\n @cursor = 0\n a = @dir_position[Dir.pwd]\n if a\n @sta = a.first\n @cursor = a[1]\n raise \"sta is nil for #{Dir.pwd} : #{@dir_position[Dir.pwd]}\" unless @sta\n raise 'cursor is nil' unless @cursor\n end\nend",
"def [](fpath=nil)\n if fpath.nil? || fpath.index('/') == 0\n @rye_current_working_directory = fpath\n else\n # Append to non-absolute paths\n if @rye_current_working_directory\n newpath = File.join(@rye_current_working_directory, fpath)\n @rye_current_working_directory = newpath\n else\n @rye_current_working_directory = fpath\n end\n end\n debug \"CWD: #{@rye_current_working_directory}\"\n self\n end",
"def reset_app_sandbox_internal_shared\n [app_documents_dir, app_tmp_dir].each do |dir|\n FileUtils.rm_rf dir\n FileUtils.mkdir dir\n end\n end",
"def mktmpdircd(&block)\n if block\n Dir.mktmpdir do |dir|\n Dir.chdir(dir) do\n yield(dir)\n end\n end\n else\n dir = Dir.mktmpdir\n Dir.chdir(dir)\n return dir\n end\nend",
"def symlink_current_dir\n @shell.symlink self.checkout_path, self.current_path\n end",
"def reset_default\n \n w=WinReg.new(@file)\n w.debug=@debug\n FOLDER_DEFAULTS.each do |key|\n w.write_key(FOLDERS_BASE+'\\\\'+key[:name],PROFILE_BASE+'\\\\'+key[:dir])\n end\n end",
"def current_working_directory; @rye_current_working_directory; end",
"def store_dir\n File.expand_path(self.relative_store_dir, @options[:root_dir])\n end",
"def cd(target = ENV['HOME'])\n Dir.chdir(target.strip)\n \"Directory changed to #{Dir.pwd}\"\n end",
"def restore\n RESTORE\n end",
"def teardown\n Dir.chdir '..'\n FileUtils.rm_rf @tempdirname\n end",
"def chdir(dir)\n puts Dir.pwd\n\n Dir.chdir(dir) do\n puts Dir.pwd\n end\nend",
"def get_clone_directory()\n\n if @to\n folder_exists = File.directory?( @to )\n FileUtils.mkdir_p( @to ) unless folder_exists\n return @to\n end\n\n if @verse.has_key?( Indices::GIT_CLONE_BASE_PATH )\n folder_exists = File.directory?( @verse[ Indices::GIT_CLONE_BASE_PATH ] )\n FileUtils.mkdir_p( @verse[ Indices::GIT_CLONE_BASE_PATH ] ) unless folder_exists\n return @verse[ Indices::GIT_CLONE_BASE_PATH ]\n end\n\n return Dir.pwd()\n\n end",
"def localstate_default_directory\n default_dir = File.join( Config::CONFIG['localstatedir'], basedir )\n return default_dir if is_tyrant_root?( default_dir )\n return nil\n end",
"def undo()\r\n oldname = @FilePath.basename\r\n @CopiedFilePath = \"#{@CopiedFilePath}/#{oldname}\"\r\n origfolder = @FilePath.dirname\r\n @FilePath = origfolder\r\n FileUtils.mv(@CopiedFilePath, @FilePath)\r\n end",
"def changePath(path, &block)\n currPath = Dir.pwd\n begin\n Dir.chdir(path)\n result = block.call\n Dir.chdir(currPath)\n result\n rescue\n Dir.chdir(currPath)\n raise $!\n end\nend",
"def clean_dir_root\n File.join(root_dir, \"test\", \"tmp\", \"cleanreps\")\n end",
"def clear_base_location\n tmpdir = dir + \"base_removed\"\n base_location.move(tmpdir)\n base_location.mkdir\n tmpdir.delete\n end",
"def pwd\n Dir.pwd\n end",
"def prefix\n @md5 ||= Digest::MD5.new\n @md5.update Dir.pwd\n end",
"def clean_dir\n File.join clean_dir_parent, name\n end",
"def chroot\n warn \"Path::Name#chroot is obsoleted. Use Dir.chroot.\"\n Dir.chroot(path)\n end"
] |
[
"0.78397775",
"0.681919",
"0.66100454",
"0.6450121",
"0.616536",
"0.61498183",
"0.6125742",
"0.6103921",
"0.60885924",
"0.60654163",
"0.6063722",
"0.5972469",
"0.5951613",
"0.5904455",
"0.5887028",
"0.58789873",
"0.5850239",
"0.58397055",
"0.5826174",
"0.582608",
"0.582608",
"0.57964665",
"0.5777287",
"0.5738761",
"0.5717812",
"0.5716379",
"0.5710029",
"0.5706437",
"0.5694754",
"0.5668173",
"0.56422645",
"0.5584343",
"0.5569337",
"0.55620813",
"0.55531555",
"0.5520976",
"0.5510453",
"0.5500037",
"0.54910284",
"0.54898715",
"0.5466539",
"0.5404482",
"0.5398331",
"0.53936607",
"0.53770846",
"0.5365376",
"0.5354186",
"0.5344163",
"0.53295314",
"0.5320376",
"0.5320136",
"0.5294576",
"0.52848274",
"0.52819467",
"0.5275499",
"0.52662385",
"0.5255648",
"0.52522707",
"0.5251425",
"0.5249892",
"0.52420014",
"0.52340573",
"0.52340573",
"0.52340573",
"0.52293813",
"0.5219524",
"0.5212952",
"0.52122307",
"0.5208629",
"0.5193949",
"0.5183238",
"0.51809675",
"0.5179439",
"0.51761734",
"0.51742774",
"0.51731104",
"0.5157503",
"0.51538116",
"0.5152939",
"0.5152742",
"0.51520914",
"0.5135182",
"0.51229095",
"0.5121701",
"0.511974",
"0.5116207",
"0.5112615",
"0.5108232",
"0.51025987",
"0.510042",
"0.5098455",
"0.507972",
"0.50743616",
"0.5071416",
"0.5066777",
"0.50661796",
"0.5062659",
"0.5061447",
"0.505769",
"0.50573784"
] |
0.67519134
|
2
|
Sets the working directory to the previously remembered directory. This can be used in blocks.
|
def restore_dir
cd @dir
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def working_dir(&block)\n return Dir.chdir(@working_dir, &block) if block_given?\n @working_dir\n end",
"def set_workdir(filename)\n @workdir = File.dirname(filename)\n end",
"def work_dir=(path)\n path << '/' unless path.end_with?('/')\n @work_dir = path\n end",
"def store_dir\n @dir = Dir.pwd\n end",
"def chdir(&block)\n Dir.chdir(top_level, &block)\n end",
"def chdir(&block)\n Dir.chdir(self, &block)\n end",
"def working_directory(v)\n @options[:working_directory] = v\n end",
"def inside_cookbook(&block)\n cookbook_path = File.join(Strainer.sandbox_path.to_s, @cookbook.cookbook_name)\n Strainer.ui.debug \"Changing working directory to '#{cookbook_path}'\"\n original_pwd = ENV['PWD']\n\n ENV['PWD'] = cookbook_path\n success = Dir.chdir(cookbook_path, &block)\n ENV['PWD'] = original_pwd\n\n Strainer.ui.debug \"Restoring working directory to '#{original_pwd}'\"\n success\n end",
"def working_directory=(directory)\n @link.WorkingDirectory = directory.tr('/', \"\\\\\")\n end",
"def chdir(dir)\n previous_dir = File.expand_path(\".\")\n\n Dir.chdir(dir)\n begin\n @p4.cwd = File.expand_path(\".\")\n rescue\n Dir.chdir(previous_dir)\n raise\n end\n\n if block_given?\n begin\n yield dir\n ensure\n Dir.chdir(previous_dir)\n @p4.cwd = previous_dir\n end\n end\n end",
"def cd(dir = nil)\n dir ||= homedir\n dir = expand_path(dir)\n @cwd = dir\n end",
"def [](fpath=nil)\n if fpath.nil? || fpath.index('/') == 0\n @rye_current_working_directory = fpath\n else\n # Append to non-absolute paths\n if @rye_current_working_directory\n newpath = File.join(@rye_current_working_directory, fpath)\n @rye_current_working_directory = newpath\n else\n @rye_current_working_directory = fpath\n end\n end\n debug \"CWD: #{@rye_current_working_directory}\"\n self\n end",
"def working_dir(*path)\n if _working_dir.nil?\n @_working_dir = ENV['PROJECT_WORKING_DIR']\n if _working_dir != nil\n @_working_dir = Pathname.new(expand_variables _working_dir)\n Dir.chdir _working_dir.to_s\n\n elsif run_mode == :daemon\n @_working_dir = state_dir\n Dir.chdir _working_dir.to_s\n\n else\n @_working_dir = Pathname.getwd\n end\n\n raise \"working_dir not a directory: #{_working_dir.safe_s}\" unless _working_dir.directory?\n end\n [_working_dir, *path].reduce(:+)\n end",
"def chdir; end",
"def teardown\n Dir.chdir @previous_wd # restore the working directory to what it was previously\n end",
"def cd( path = File.expand_path('~') )\n new_last_path = FileUtils.pwd\n if path == '-'\n if @last_path\n path = @last_path\n else\n warn 'Sorry, there is no previous directory.'\n return\n end\n end\n cd path\n @last_path = new_last_path\n ls\n end",
"def working_dir\n @_working_dir ||= File.expand_path(options['merb-root'] || Dir.pwd)\n end",
"def working_dir\n @_working_dir ||= File.expand_path(options['merb-root'] || Dir.pwd)\n end",
"def working_dir\n @_working_dir ||= File.expand_path(options['merb-root'] || Dir.pwd)\n end",
"def reset!\n @base_dir = @path = nil\n end",
"def excel_change_directory(new_wd)\n new_wd = File.expand_path(new_wd)\n raise ExcelError.new(\"Cannot change working directory - '#{new_wd}' does not exist\") unless File.exist?(new_wd)\n\n begin\n orig_wd_w = Converter.to_windows_path(Dir.pwd)\n new_wd_w = Converter.to_windows_path(new_wd)\n # In some machines, ChDir will not change the directory immediately.\n # So to make sure, first change the drive and then change the directory if the directory is absolute.\n excel_call('ChangeWorkingDrive', new_wd_w[0..1]) if new_wd_w[1] == ?:\n excel_call('ChangeWorkingDirectory', new_wd_w)\n current_dir = excel_call('ShowWorkingDirectory')\n @logger.trace('Changed Excel.exe working directory: ' + current_dir)\n # Execute the provided block.\n yield\n ensure\n # All done, reset working directory.\n excel_call('ChangeWorkingDrive', orig_wd_w[0..1]) if orig_wd_w[1] == ?:\n excel_call('ChangeWorkingDirectory', orig_wd_w)\n current_dir = excel_call('ShowWorkingDirectory')\n @logger.trace('Reset Excel.exe working directory: ' + current_dir)\n end\n end",
"def change_dir f\n unless File.directory? f\n perror \"#{f} is not a directory, or does not exist.\"\n return\n end\n\n # before leaving a dir we save it in the list, as well as the cursor\n # position, so we can restore that position when we return\n @visited_dirs.insert(0, Dir.pwd)\n save_dir_pos\n\n f = expand_path(f)\n Dir.chdir f\n @current_dir = Dir.pwd # 2019-04-24 - earlier was in post_cd but too late\n read_directory\n post_cd\n\n redraw_required\nend",
"def chdir=(dir)\n @chdir = dir.to_s\n end",
"def cd( path = '~' )\n new_last_path = FileUtils.pwd\n if path == '-'\n unless path = Irbtools.instance_variable_get(:@last_cd_path)\n warn 'Sorry, there is no previous directory.'\n return\n end\n end\n super(File.expand_path(path))\n Irbtools.instance_variable_set(:@last_cd_path, new_last_path)\n ls\n end",
"def chdir(&block)\n ::Dir.chdir(path, &block)\n end",
"def working_dir\n ENV['PWD'] || Dir.pwd\n end",
"def chdir(&block)\n Dir.chdir(ROOT.join(name), &block)\n end",
"def chdir(dir=nil)\n @chdir = dir.to_s if dir\n @chdir\n end",
"def current_working_directory; @rye_current_working_directory; end",
"def set_git_path basedir\n @git_path = basedir\n end",
"def chdir(&block)\n warn \"Path::Name#chdir is obsoleted. Use Dir.chdir.\"\n Dir.chdir(path, &block)\n end",
"def cd(path,&block)\n if block\n cwd = Dir.pwd\n\n Dir.chdir(path)\n block.call()\n Dir.chdir(cwd)\n else\n Dir.chdir(path)\n end\n end",
"def changePath(path, &block)\n currPath = Dir.pwd\n begin\n Dir.chdir(path)\n result = block.call\n Dir.chdir(currPath)\n result\n rescue\n Dir.chdir(currPath)\n raise $!\n end\nend",
"def chdir(path)\n ensure_relative_path! :chdir, path\n @path += path\n end",
"def set_current_path(path)\n @current_path = path\nend",
"def cd(target = ENV['HOME'])\n Dir.chdir(target.strip)\n \"Directory changed to #{Dir.pwd}\"\n end",
"def push_dir(dir = nil)\n @directory_stack.push(Dir.pwd)\n self.chdir(dir)\n end",
"def exec_in_git_dir(&block)\n Dir.chdir(top_level, &block)\n end",
"def in_directory(working_dir)\n old_dir = Dir.pwd\n begin\n Dir.chdir working_dir\n yield\n ensure\n Dir.chdir old_dir\n end\n end",
"def within_dir dir, &blk\n cur_dir = Dir.getwd\n Dir.chdir(dir)\n yield\n Dir.chdir(cur_dir)\n end",
"def exec_in_git_dir(&block)\n curr = Dir.getwd\n result = nil\n begin\n Dir.chdir top_level\n result = yield\n rescue\n raise\n ensure\n Dir.chdir curr\n end\n result\n end",
"def cd(dir = nil)\n d = dir\n case d\n when File, Dir\n d = d.path if File.directory?(d.path)\n end\n $env.chdir(d)\nend",
"def set_dir(new_dir)\n # checking for / at the end of the env variable\n new_dir = '' unless new_dir\n new_dir += '/' unless new_dir[-1, 1] == '/'\n @dir = new_dir\n end",
"def write_curdir\n f = File.expand_path('~/.fff_d')\n s = Dir.pwd\n File.open(f, 'w') do |f2|\n f2.puts s\n end\n # puts \"Written #{s} to #{f}\"\nend",
"def set_path\n self.path = File.join(self.store_dir, self.filename)\n end",
"def set_current_path; end",
"def change_dir(iDir)\n lOldDir = Dir.getwd\n Dir.chdir(iDir)\n begin\n yield\n rescue Exception\n Dir.chdir(lOldDir)\n raise\n end\n Dir.chdir(lOldDir)\n end",
"def setPath(path)\n @currentPath = path.clone\n @root = @currentPath.getRoot unless path.empty?\n end",
"def workdir\n result = base.join('cache')\n result.mkpath\n result\n end",
"def chdir(dir)\n puts Dir.pwd\n\n Dir.chdir(dir) do\n puts Dir.pwd\n end\nend",
"def working_directory\n @options[:working_directory]\n end",
"def sync_dir(dir=Dir.getwd)\n @r.cmd \"setwd('#{dir}')\"\n end",
"def cwd\n @cwd ||= begin\n exec! 'pwd'\n rescue => e\n raise e\n '/'\n end\n end",
"def chdir(dest, &block)\n if block\n Dir.chdir(dest, &block)\n else\n if !defined? @original_dir\n @original_dir = Dir.pwd\n @cleaners << -> { Dir.chdir(@original_dir); @original_dir=nil }\n end\n Dir.chdir(dest)\n end\n end",
"def in_path(path, &blk)\n old = Dir.pwd\n Dir.chdir path\n say_status :cd, path\n yield\n Dir.chdir old\n end",
"def chdir(dir, &block)\n Dir.chdir(File.expand_path(dir), &block)\n end",
"def pop_dir\n # the first time we pop, we need to put the current on stack\n @visited_dirs.push Dir.pwd unless @visited_dirs.index(Dir.pwd)\n ## XXX make sure thre is something to pop\n d = @visited_dirs.delete_at 0\n ## XXX make sure the dir exists, cuold have been deleted. can be an error or crash otherwise\n @visited_dirs.push d\n Dir.chdir d\n @current_dir = Dir.pwd # 2019-04-24 - earlier was in post_cd but too late\n post_cd\n rescan_required\nend",
"def cd(path,&block)\n @history << ['cd', path]\n\n if block\n block.call() if block\n\n @history << ['cd', '-']\n end\n end",
"def cd(path)\n Dir.chdir(path)\n \"cd #{path}\"\n end",
"def chroot\n Dir.chdir '/'\n File.umask 0000\n end",
"def chdir # :yields: the Git::Path\n Dir.chdir(dir.path) do\n yield dir.path\n end\n end",
"def chroot(&block)\n ::Dir.chroot(path, &block)\n end",
"def reset_dir(pathname)\n\tputs \" Deleting and recreating #{pathname} folder\"\n\tFileUtils.rm_rf(pathname) unless not Dir.exist?(pathname)\n\tDir.mkdir(pathname)\nend",
"def there(&block)\n Dir.chdir File.join(@repo.dir, @path), &block\n end",
"def build_working_dir(&block)\n file_name =\n if block.respond_to?(:source_location)\n block.source_location[0]\n else\n eval(\"__FILE__\", block.binding)\n end\n\n @working_dir = File.expand_path(\n File.join(File.dirname(file_name), \"generated\"))\n end",
"def workdir=(dir)\n workdir = GitLib.find_workdir(dir)\n if workdir.nil?\n @workdir = dir\n logger.info { \"Initializing new repository at #{dir}\" }\n return command(:init)\n else\n @workdir = workdir\n logger.debug { \"Opening existing repository at #{dir}\" }\n end\n end",
"def chroot\n warn \"Path::Name#chroot is obsoleted. Use Dir.chroot.\"\n Dir.chroot(path)\n end",
"def there(&block)\n Dir.chdir @repo.dir, &block\n end",
"def save_dir_pos\n # the next line meant that it would not save first directory.\n # return if @sta == 0 && @cursor == 0\n\n @dir_position[Dir.pwd] = [@sta, @cursor]\nend",
"def within(directory)\n _guard_dir!(File.join(_config_store.active_backend.pwd + [directory]))\n\n _config_store.add_pwd directory\n\n yield if block_given?\n ensure\n _config_store.pop_pwd\n end",
"def chdir(path)\n ensure_relative_path! :chdir, path\n @ftp.chdir path\n end",
"def current_dir; end",
"def temp_dir temp='tmp/trash'\n FileUtils.rm_rf temp\n FileUtils.mkpath temp\n Dir.chdir(temp) { yield }\n FileUtils.rm_rf temp\nend",
"def restart_dir; end",
"def reset_repo(&block)\n yield\n=begin\n Dir.chdir(@saved_cwd){\n system 'rm', '-rf', repo4test\n if !File.directory?(repo4test)\n repo = File.join(repo4test, Juli::REPO)\n FileUtils.mkdir_p(repo)\n FileUtils.cp(File.join(repo4test, '../data/config'), repo,\n :preserve=>true)\n end\n Dir.chdir(repo4test){\n yield\n }\n }\n=end\n end",
"def with_tmp_dir(&block)\n Dir.mktmpdir do |tmp_dir|\n Dir.chdir(tmp_dir, &block)\n end\n end",
"def cwd\n File.expand_path(@options[:cwd] || \".\")\n end",
"def redo_path\n self.path = @temp_path\n end",
"def current_directory\n File.expand_path @current_directory\n end",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def current_directory\n @current_directory ||=\n if __FILE__ =~ %r{\\Ahttps?://}\n require 'tmpdir'\n tempdir = Dir.mktmpdir(\"rails-templates\")\n at_exit { FileUtils.remove_entry(tempdir) }\n git clone: [\n \"--quiet\",\n \"https://github.com/nimbl3/rails-templates.git\",\n tempdir\n ].map(&:shellescape).join(\" \")\n\n tempdir\n else\n File.expand_path(File.dirname(__FILE__))\n end\nend",
"def path=(path=\"\")\n path = Dir.pwd if not path or path.empty?\n @path = File.expand_path(path)\n end",
"def prepare_working_dir\n FileUtils.mkdir_p @working_dir unless File.directory?(@working_dir)\n FileUtils.rm_rf Dir[\"#{@working_dir}/*\"] if @force_rebuild\n end",
"def cd(dir = '~', pushd: true)\n dir = load_item path: expand_path(dir) unless dir.is_a? Item\n unless dir.zip?\n Dir.chdir dir\n @current_zip = nil\n else\n @current_zip = dir\n end\n @dir_history << current_dir if current_dir && pushd\n @current_dir, @current_page, @current_row = dir, 0, nil\n main.activate_pane 0\n ls\n @current_dir\n end",
"def jump_to(path, &block)\n Dir.chdir(test_content_dirs(path), &block)\nend",
"def with_tmp_dir(&block)\n Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir|\n Dir.chdir(tmp_dir, &block)\n end\n end",
"def user_directory\n File.expand_path('~')\n end",
"def cwd\n @target.is_a?(String) && File.directory?(@target) ? @target : \"./\"\n end",
"def work_dir; end",
"def run_cwd(dir = resource[:path])\n result = nil\n Dir.chdir(dir) do\n result = yield.chomp\n end\n result\n end",
"def dir\n @working_directory\n end",
"def cd(path)\n @history << ['cd', path]\n\n if block_given?\n yield\n @history << ['cd', '-']\n end\n end",
"def setup_path\n if !@repo.clone_path.nil? and !@repo.clone_path.empty?\n Dir.chdir(@repo.clone_path)\n else\n initial_path_setup\n end\n end",
"def cwd\n Dir.getwd\n end",
"def path=(path = nil)\n path = Dir.pwd if not path or path.strip.empty?\n @path = File.expand_path(path)\n end",
"def set_root_path!\n raise 'IRONNAILS_ROOT is not set' unless defined?(::IRONNAILS_ROOT)\n raise 'IRONNAILS_ROOT is not a directory' unless File.directory?(::IRONNAILS_ROOT)\n\n @root_path =\n # Pathname is incompatible with Windows, but Windows doesn't have\n # real symlinks so File.expand_path is safe.\n if ENV['OS'] == 'Windows_NT'.freeze\n File.expand_path(::IRONNAILS_ROOT)\n\n # Otherwise use Pathname#realpath which respects symlinks.\n else\n Pathname.new(::IRONNAILS_ROOT).realpath.to_s\n end\n\n Object.const_set(:RELATIVE_IRONNAILS_ROOT, ::IRONNAILS_ROOT.dup) unless defined?(::RELATIVE_IRONNAILS_ROOT)\n\n ::IRONNAILS_ROOT.replace @root_path\n end",
"def cwd_default_directory\n default_dir = Dir.pwd\n return default_dir if is_tyrant_root?( default_dir )\n return nil\n end",
"def local=(dir)\n @local = dir ? File.expand_path(dir) : nil\n end",
"def initialize\n super\n destination_root = Dir.getwd\n end"
] |
[
"0.70690095",
"0.67744815",
"0.66051114",
"0.6562462",
"0.6540574",
"0.6527892",
"0.6491792",
"0.64081013",
"0.6394955",
"0.6367231",
"0.6363701",
"0.63587695",
"0.63111115",
"0.63071555",
"0.62982917",
"0.6174338",
"0.61456275",
"0.61456275",
"0.61456275",
"0.6143104",
"0.6114748",
"0.611112",
"0.61031175",
"0.6088046",
"0.6085522",
"0.6056021",
"0.60070896",
"0.59927845",
"0.59821206",
"0.5974617",
"0.5969485",
"0.5950615",
"0.5928379",
"0.59271276",
"0.59007204",
"0.58960754",
"0.5886949",
"0.58828676",
"0.587743",
"0.5858813",
"0.58146477",
"0.5794115",
"0.5792674",
"0.5789704",
"0.57723385",
"0.57576203",
"0.5744495",
"0.57370776",
"0.57305306",
"0.5710901",
"0.57077265",
"0.57056177",
"0.5704518",
"0.5693742",
"0.5690297",
"0.56795084",
"0.5673623",
"0.5640217",
"0.5589541",
"0.55754006",
"0.55677855",
"0.55436003",
"0.54902726",
"0.548867",
"0.5475033",
"0.5470768",
"0.5465652",
"0.5464786",
"0.5463291",
"0.5444096",
"0.5423236",
"0.5416119",
"0.54079247",
"0.53989774",
"0.53775346",
"0.5366115",
"0.5364201",
"0.53597766",
"0.5358563",
"0.53472644",
"0.53472644",
"0.5337501",
"0.5334757",
"0.53288317",
"0.53269416",
"0.5315716",
"0.5312604",
"0.53121954",
"0.5311521",
"0.53063124",
"0.5303659",
"0.5290646",
"0.5289659",
"0.52877647",
"0.52792835",
"0.52717793",
"0.52506495",
"0.5232085",
"0.5227268",
"0.52062935"
] |
0.65541875
|
4
|
Call once per request to determine how long to sleep.
|
def get_delay
@call_times << Time.now
if @call_times.size < 2 then
return 0
else
@call_times.shift while @call_times.size > @history_size
first = @call_times[0]
last = @call_times[-1]
expected = (@call_times.size / (@calls_per_minute / 60.0))
actual = last - first # float: number of seconds
delay = [0, expected-actual].max
return delay
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def sleep_time\n\t\t\t# TODO: Hard-coded for now. See doc/app_manager.rdoc for some\n\t\t\t# thoughts on this.\n\t\t\t1\n\t\tend",
"def find_with_sleep\n sleep(request.sleep || 1)\n response.name = 'Request should have timed out'\n end",
"def sleep_time\n 60\n end",
"def poll_sleep\n @sleeping = true\n handle_shutdown { sleep 5 }\n @sleeping = false\n true\n end",
"def sleep_for\n @sleep_for ||= 5\n end",
"def sleep_if_set\n sleep_sec = config[:sleep].to_i\n if sleep_sec > 0\n info(\"Sleep #{config[:sleep]} seconds...\")\n sleep sleep_sec\n end\n end",
"def pre_sleep; end",
"def wait_before_new_request\n return unless @last_request # this is the first request\n diff = Time.now - @last_request\n if diff < SECONDS_BEFORE_NEW_REQUEST\n sleep(SECONDS_BEFORE_NEW_REQUEST - diff)\n end\n end",
"def sleep(dur=0) end",
"def sleep\n sleep_after(0)\n end",
"def sleep\n @property_hash['sleep'] || 0\n end",
"def calculate_sleep\n if @timeouts.empty?\n @sleep_for = DefaultSleepFor\n else\n diff = @timeouts.first.value.timeout_at.to_f - Time.now.to_f\n\n if diff < 0.0\n @sleep_for = 0\n else\n @sleep_for = diff\n end\n end\n end",
"def time_request\n time do\n do_request\n end\n end",
"def sleep_time\n 1.0/(rand(10) + 1)\n end",
"def pause_for_roundtime\n if $_api_current_rt > 0\n api_sleep $_api_current_rt + $rt_adjust\n end\nend",
"def sleep_some_time\n sleep 1\n end",
"def sleep_value\n 20\n end",
"def sleep_until(t)\n dt = (t - Time.zone.now).ceil \n blather(\"sleep_until #{t} (#{dt} seconds)\")\n sleep(dt) if dt > 0.0\n end",
"def idle_time_before_sleep_in_seconds\n return @idle_time_before_sleep_in_seconds\n end",
"def watch_delay\n @conn.watch(Web.keys[:delay]) do\n yield if block_given?\n end\n end",
"def throttle\n sleep @throttle if @@last_request + @throttle > Time.now\n @@last_request = Time.now\n end",
"def sleep_if_set\n config[:sleep].to_i.times do\n print '.'\n sleep 1\n end\n end",
"def delay_request\n\t\tif config[:strategy][:type] == \"linear\"\n\t\t\tdelay = Random.rand( config[:strategy][:delaymin] .. config[:strategy][:delaymax]).to_f\n\t\t\t\n\t\t\tdebug.print(3, \"Delaying\", delay, \" before adding another request in queue\", File.basename(__FILE__), __LINE__)\n\t\t\t\n\t\t\tsleep(delay)\n\t\tend\n\tend",
"def wait!\n sleep(@sleep)\n end",
"def wait_for_seconds\n\t\tsleep(1 * rand + 1)\n\tend",
"def wait_time\n if rate_limit_remaining < 50\n [rate_limit_reset - Time.zone.now, 0.001].sort.last\n else\n 3600.0 / rate_limiting\n end\n end",
"def sleep_before_next_attempted_login\n sleep 900\n end",
"def sleep_before_next_attempted_login\n sleep 900\n end",
"def slow_down_api_request\n sleep 1.0\n end",
"def waitTillLimitReset\n timeTillReset = CLIENT.rate_limit.resets_in + 5\n @logger.info(\"API limit reached while fetching... Sleeping for #{timeTillReset} seconds 😴 brb\")\n sleep(timeTillReset)\nend",
"def sleep(n)\n Kernel.sleep(n)\n end",
"def sleepfor \n\ttimetorun = $hours * 60 * 60\n\tsleep(timetorun)\nend",
"def implicit_wait=(seconds); end",
"def sleep seconds\n w = Fiber.current.worker\n dt = Time.now.to_i\n f = Finishable.new do\n return (Time.now.to_i - dt) >= seconds\n end\n wait_for f\n end",
"def sleeper\n\t\tsleep(0.4)\n\tend",
"def lock_on_sleep?\n get_settings[:lock_on_sleep] != 0\n end",
"def sleep_test\n sleep(10)\n \"slept for 10 sec!\"\n end",
"def sleep\n @awake = false\n end",
"def snooze(t)\n sleep(t)\n end",
"def io_sleep\n # sleep 2.5/1000.0\n end",
"def brute_wait(delay)\n sleep(delay)\n end",
"def sleep\n #sleeps\n puts \"*sleeps*\"\n end",
"def delay_query\n @time ||= Time.now\n delay = 0.5\n wait_time = delay - (Time.now - @time).to_f\n sleep(wait_time) unless wait_time <= 0\n x = yield\n @time = Time.now\n return x\n end",
"def simulate_latency\n sleep 0.5\n end",
"def sleepy_run; end",
"def perform_sleepily!(timeout, &block)\n @on_complete = block if block_given?\n Thread.new {\n before_send.call(self) if before_send\n \n nap = sleepy.get(\"#{round_time(Time.new.to_i, timeout)}:#{uri}\") rescue nil\n \n unless nap.blank?\n STDERR.puts \"Return cached result #{nap.inspect}\"\n nap\n else\n req = http.request(request)\n \n response = Response.new(req, self)\n begin\n if response.redirected?\n response = response.follow_redirect\n else\n on_complete.call(response) if on_complete\n response\n end\n if response.code && response.code == 200\n sleepy.set(\"#{round_time(Time.new.to_i, timeout)}:#{uri}\", response)\n sleepy.set(\"0:#{uri}\", response)\n end\n rescue\n response = sleepy.get(\"0:#{uri}\") rescue nil\n end\n response\n end\n }\n end",
"def sleepy_run\n cleanup if should_cleanup?\n sleep(@interval)\n increment_cycle\n end",
"def time_to_discover?\n if((@request_count%10 == 0) or (Time.now > (@last_polled_time + 10.seconds)))\n @last_polled_time = Time.now\n return true\n else\n return false\n end\n end",
"def wait(per = nil)\n @target += per || @period\n error = @target - Time.now\n sleep error if error > 0\n true\n end",
"def simulate_latency\n sleep(rand(2)) if Rails.env == 'development'\n end",
"def pause_after_run\n sleep @sleep_seconds\n end",
"def sleep? module_name = nil, refresh_delay = 60 # {{{\n\n # Pre-condition check # {{{\n raise ArgumentError, \"Module name cannot be nil, but it is\" if( module_name.nil? )\n raise ArgumentError, \"Module name should be of type string, but it is (#{module_name.class.to_s})\" unless( module_name.is_a?(String) )\n # }}}\n\n # Main\n sleep_time = 60 # make sure we always wait 60 s if we get no valid feedback\n\n website = Website.first( :name => module_name )\n\n # We have never accessed this website so we need to create an initial DB entry\n if( website.nil? )\n new = Website.new\n new.name = module_name\n new.last_access = Time.now\n new.save!\n website = new\n end\n\n last_access = Time.parse( website.last_access.to_s )\n\n raise ArgumentError, \"last_access cannot be nil\" if( last_access.nil? )\n raise ArgumentError, \"last_access needs to be of type Time, but is (#{last_access.class.to_s})\" unless( last_access.is_a?( Time ) )\n\n now = Time.now\n diff = ( now - last_access ).to_i\n\n @log.message :debug, \"Sleep function result is - Now (#{now.to_s}) - Last Access (#{last_access.to_s}) - Mandatori Refresh Delay (#{refresh_delay.to_s}) - Now-Last (#{diff.to_s}) - Sleep (#{diff.to_s})\"\n\n sleep_time = ( diff > refresh_delay ) ? ( 0 ) : ( refresh_delay - diff )\n\n # Post-condition check\n raise ArgumentError, \"Result of this function is supposed to be of type integer, but is (#{sleep_time.class.to_s})\" unless( sleep_time.is_a?(Integer) )\n\n sleep_time\n end",
"def maybe_fake_delay!\n if (auth_db_delay = env.params['auth_db_delay'].to_f) > 0\n enqueue_acceptor(:sleepy){|acc| EM.add_timer(auth_db_delay){ acc.succeed } }\n end\n end",
"def keep_alive_time; end",
"def backoff_sleep(tries)\n # Exponential with some randomization\n sleep_time = 2**tries\n puts \"Sleeping for #{sleep_time} seconds after attempt #{tries}...\"\n sleep sleep_time\n nil\n end",
"def wait(seconds)\n @waiting = seconds * 1000\n end",
"def delay_me\n\t\tsleep(10.0) # sleep for 10 seconds between queries\n\tend",
"def wait_for_launching\n sleep @delay\n end",
"def take_a_nap\n sleep(2)\nend",
"def sleep_before_retry_on_limit_error\n sleep 15\n end",
"def sleep(timeout = nil)\n unlock\n begin\n timeout ? Kernel.sleep(timeout) : Kernel.sleep\n ensure\n lock\n end\n end",
"def test_concurrent_requests\n app do\n get '/sleep/:i' do\n t = params[:i].to_i * FACTOR\n sleep t\n \"Slept #{t}\"\n end\n end\n \n time = Benchmark.realtime do\n (1..REQUESTS).map do |i|\n Thread.new(i) do |i|\n get \"/sleep/#{i}\"\n \n assert_equal(200, response.status)\n assert_equal(\"Slept #{i * FACTOR}\", response.body)\n end\n end.each(&:join)\n end\n \n assert_in_delta REQUESTS * FACTOR, time, 0.05 # 0.05 is a empirically found ‘overhead’ time\n end",
"def sleep _args\n \"sleep _args;\" \n end",
"def ensure_rate_limits\n sleep 1 / REQUST_LIMIT_PER_MINUTE.to_f\n end",
"def sleep_for(rate)\r\n -Math.log(1.0 - Random.rand) / rate\r\n end",
"def sleep_time(attempt)\n 1 + (2**attempt) + rand(2**attempt)\n end",
"def watchful_sleep(seconds)\n seconds.times { sleep 1 if !@interrupted }\n end",
"def poll(seconds = 5)\n count = seconds * 100\n\n while count > 0 && !yield\n count -= 1\n sleep 0.01\n end\n\n raise 'Poll timeout.' unless yield\nend",
"def sleep(time_fell_asleep)\n max_timeout = 30 - (Time.now - time_fell_asleep).to_i\n\n if max_timeout > 0\n # Use IO::select to wait for available connection data\n @connection_pool.poll_connections(max_timeout)\n end\n\n # If 30 seconds have passed, then wakeup\n time_asleep = (Time.now - time_fell_asleep).to_f\n @status = :wakeup if time_asleep >= 30\n \n # We didn't sleep for >= 30s, so we need to check for a NOOP\n if (@status == :waiting)\n @connection_pool.with_all_connections do |connection|\n begin\n type, data = connection.read_response(@network_timeout_sec)\n\n # Wake up if we receive a NOOP packet\n if (type == :noop)\n logger.debug \"Received NOOP while sleeping... waking up!\"\n @status = :wakeup\n else\n logger.warn \"Received something other than a NOOP packet while sleeping: #{type.to_s}\"\n end\n rescue SocketTimeoutError\n # This is okay here.\n end\n end\n end\n end",
"def sleep_time(attempt)\n 1 + (2**attempt) + rand(2**attempt)\n end",
"def delay\n @delay ||= 600\n end",
"def delay_time\n end",
"def wait!\n now = Time.now.utc.to_i\n duration = (reset.to_i - now) + 1\n\n sleep duration if duration >= 0\n\n yield if block_given?\n\n duration\n end",
"def delay_1() sleep(3) end",
"def idle_time_before_sleep_in_seconds=(value)\n @idle_time_before_sleep_in_seconds = value\n end",
"def reliable_sleep(wait_second)\n loop do\n actual = Benchmark.realtime { sleep(wait_second) }\n break if actual >= wait_second\n log.error(\"#{Thread.current.object_id} sleep failed expected #{wait_second} but slept #{actual}\")\n wait_second -= actual\n end\n end",
"def work()\n # FIXME : .rel[...].get doesn't update $client.rate_limit...\n\n rate_limit = $client.rate_limit\n dbgp \"#{rate_limit.remaining} API calls left.\"\n\n # A little buffer in case we use a feature from octokit\n # which doesn't update rate_limit on `$client`.\n if rate_limit.remaining < 5 then\n reset = rate_limit.resets_in + 10\n puts \"💤 zleepy timez (back in #{reset} seconds)\"\n sleep(reset)\n end\n\n begin\n yield\n rescue Octokit::BadGateway, Octokit::InternalServerError => e\n puts \"Uuuh... github is having a bad time :( #{e.response_status}\"\n pp \"=====\"\n pp \"=====\"\n pp e.response_body\n pp \"=====\"\n pp e.response_headers\n pp \"=====\"\n pp \"=====\"\n sleep 10\n retry\n end\nend",
"def wait(duration)\n info \"Request from Experiment Script: Wait for #{duration}s....\"\n warn \"Calling 'wait' or 'sleep' will block entire EC event loop. Please try 'after' or 'every'\"\n sleep duration\n end",
"def find_time_asleep\n @total_time_asleep = 0\n @wake_times.each_with_index do |wake_time, index|\n @total_time_asleep += ( wake_time - @sleep_times[index] )\n end\n end",
"def admiral_sleep(sec)\n IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return\n SELF_PIPE[0].kgio_tryread(11)\n end",
"def long_calculation\n sleep(5) # do some complex operation like hit an API\nend",
"def wait(sec = 5)\n Logbook.message(\"Waiting #{sec} sec >>\" + \"\\n\")\n sec.instance_of?(Integer) ? sleep(sec) : Logbook.message(\"Waiting time is not integer: [#{sec}]\" + \"\\n\")\n end",
"def throttled_response; end",
"def run!\n current = 0\n while current < @timeout\n return 0 if done?\n\n sleep @sleep_time\n current += @sleep_time\n end\n\n 1\n end",
"def page_delay\n if $TESTWISE_PAGE_DELAY && $TESTWISE_PAGE_DELAY.to_i > 0 && $TESTWISE_PAGE_DELAY.to_i < 100\n sleep $TESTWISE_PAGE_DELAY.to_i\n end \n end",
"def wait_time_span\n return @retry_period unless @use_backoff\n time_span = [ 2 ** @iteration * @retry_period, @max_retry_period ].min\n @iteration += 1\n time_span\n end",
"def not_too_fast(start, minimum_duration = 0.5)\n duration = Time.now - start\n sleep minimum_duration - duration if duration < minimum_duration\nend",
"def first_data_timeout(seconds); end",
"def delay\n puts \"Delaying ...\"\n sleep 1\n end",
"def wait_second\n now = Time.now.to_i\n # p [ 'wait_second', now, $lastpage ]\n unless @lastpage.nil?\n if now <= @lastpage + 2\n sleep 2\n now = Time.now.to_i\n end\n end\n @lastpage = now\n end",
"def interval_sleep(sec)\n unless SELF_PIPE.empty?\n # mimic sleep with a timeout on IO.select, listening for signals setup in #setup_signal_handlers\n return unless IO.select([ SELF_PIPE[0] ], nil, nil, sec)\n\n signal = SELF_PIPE[0].getc.chr\n\n return if signal == IMMEDIATE_RUN_SIGNAL # be explicit about this behavior\n\n # we need to sleep again after reconfigure to avoid stampeding when logrotate runs out of cron\n if signal == RECONFIGURE_SIGNAL\n reconfigure\n interval_sleep(sec)\n end\n else\n sleep(sec)\n end\n end",
"def nap\n @awake = false\n time_passed\nend",
"def delay(seconds); end",
"def delay(seconds); end",
"def initialize(sleep_time)\n @sleep = sleep_time.to_f\n end",
"def keep_alive_time=(_arg0); end",
"def while_time_remaining; end",
"def sleep(duration)\n if sleep_procs.any?\n sleep_procs.each { |_name, a_proc| instance_exec(duration, &a_proc) }\n else\n Kernel.sleep(duration)\n end\n end",
"def response_times\n times = []\n start_time = Time.now\n final_time = Time.now + @max_time\n counter = 1\n while Time.now < final_time do\n times << @request_builder.call(@url, counter)\n sleep(@sleep_time)\n counter += 1\n end\n times\n end",
"def master_sleep(sec)\n IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return\n SELF_PIPE[0].kgio_tryread(11)\n end",
"def delay\n sleep(rand / 100)\n end"
] |
[
"0.7475334",
"0.73335546",
"0.7328012",
"0.7303496",
"0.71901864",
"0.7125286",
"0.6984744",
"0.6844913",
"0.6777024",
"0.6771848",
"0.67280704",
"0.67259413",
"0.6720418",
"0.66785264",
"0.66757053",
"0.666766",
"0.66594046",
"0.6642802",
"0.66375846",
"0.6629606",
"0.65945506",
"0.6529513",
"0.65195304",
"0.651226",
"0.64808077",
"0.6447542",
"0.64345765",
"0.64345765",
"0.64246005",
"0.6412374",
"0.63970065",
"0.6394948",
"0.6356017",
"0.6334916",
"0.6328193",
"0.63263917",
"0.6302381",
"0.62711287",
"0.6227121",
"0.6203558",
"0.618084",
"0.61608297",
"0.6144818",
"0.61378807",
"0.6134846",
"0.6128447",
"0.61234516",
"0.6117058",
"0.6106815",
"0.61010146",
"0.6099042",
"0.60943943",
"0.60695046",
"0.60572815",
"0.60520005",
"0.60490733",
"0.604145",
"0.60371244",
"0.6034559",
"0.6025169",
"0.60212797",
"0.6009661",
"0.5995073",
"0.5994517",
"0.59842485",
"0.5980415",
"0.59732074",
"0.59722126",
"0.5971501",
"0.59686124",
"0.59674823",
"0.5946215",
"0.59426546",
"0.59338874",
"0.5923127",
"0.58974904",
"0.58939505",
"0.5885232",
"0.5881829",
"0.5875481",
"0.5866348",
"0.58654696",
"0.58625627",
"0.5853969",
"0.58514935",
"0.58435005",
"0.5834386",
"0.5822795",
"0.58169687",
"0.58161235",
"0.58025",
"0.5791603",
"0.57881147",
"0.57881147",
"0.578635",
"0.5783386",
"0.57806116",
"0.5780028",
"0.57751065",
"0.5774539",
"0.5770043"
] |
0.0
|
-1
|
Checkin date should not be less than today's date.
|
def checkin_at_after_or_on_today
return if dates_blank
if checkin_at < Date.today
self.errors.add(:checkin_at, ": Should be greater than or equal to today's date")
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def check_in_cannot_be_in_the_past\n if check_in.present? && check_in < Date.today\n errors.add(:check_in, \"can't be in the past\")\n end\n end",
"def checkout_before_checkin\n errors.add(:guest_id, \"Check out date must be before Check In date\") if checkin != nil && checkout != nil && checkout < checkin || checkout == checkin\n end",
"def checkin_not_before_checkout\n if checkin && checkout\n if checkin >= checkout\n errors.add(:checkout, \"Re-evaluate your dates please\")\n end\n end\n end",
"def check_out_should_be_less_than_check_in\n if check_in.present? && check_out.present? && check_out < check_in\n errors.add(:check_out, \"can't be less than check in date\")\n end\n end",
"def invalid_checkin_checkout\n if !self.checkin.nil? && !self.checkout.nil?\n if self.checkin >= self.checkout \n errors.add(:invalid_dates, \"Dates are invalid\")\n end\n end\n end",
"def checkout_at_after_checkin_at \n return if dates_blank \n if checkout_at <= checkin_at\n self.errors.add(:checkout_at, ': Should be greater than checkin date ')\n end\n end",
"def date_check\n if due_date.present? && due_date < Date.today\n errors.add(:due_date, \"can't be before today\")\n end\n end",
"def no_past\n if check_in < Date.now\n errors.add(:check_in, \"You can not book in the past\")\n end\n end",
"def check_appointment_date\n if date < Date.today\n errors.add(:appointment_date, \"can't be in the past\")\n end\n end",
"def validate_dated_around_now\n self.errors.add(:exam_date, \"ist kein korrektes Datum, bitte versuche es erneut.\") unless ((Date.today)..(5.years.from_now)).include?(self.exam_date)\n end",
"def validate_dated_around_now\n self.errors.add(:exam_date, \"ist kein korrektes Datum, bitte versuche es erneut.\") unless ((Date.today)..(5.years.from_now)).include?(self.exam_date)\n end",
"def checkin_before_6_months\n return if dates_blank\n if checkin_at >= (Date.today + 6.months)\n self.errors.add(:checkin_at, ': Should be less than or equal to 6 months')\n end\n end",
"def validate_date\n if self.date.present? && self.date < Date.today\n errors.add(:date, \"can't be in the past\")\n end\n end",
"def check_before_date_requirements(date)\n return true unless release_before_date? && release_date.present?\n date <= release_date\n end",
"def is_date_valid?\n\t\tunless self.date_of_booking >= Time.zone.now.beginning_of_day \n\t\t\tself.errors[:date_validation] << \"=> You can't book resource for previous day\"\n\t\tend\n\tend",
"def date_restricted?\n\n now = Date.today\n\n !((valid_from.nil? or now >= valid_from) and (valid_until.nil? or now <= valid_until))\n\n end",
"def reservation_date_not_in_past\n if date < Date.yesterday\n errors.add(:date, \" cannot be in the past!\")\n end\n end",
"def check_start_date\n if self.current_state == 3\n if self.starts_at.blank?\n self.starts_at = Date.today\n else\n if self.starts_at > Date.today\n self.starts_at = Date.today\n end\n end\n end\n end",
"def overdue?\n Date.today > to_date\n end",
"def check_in_date\n check_in && Date.parse(check_in)\n rescue ArgumentError\n # check-in parameter is not a valid date\n end",
"def date_cannot_be_in_the_future\n if date > Date.today\n errors.add(:date, \"You can't have meal in the future now...\")\n end\n end",
"def exam_in_the_future\n if self.date < Date.today\n errors.add(:date, 'is in the past')\n end\n end",
"def check_date()\n event = Event.find_by(id: self.event_id) \n if Time.now > event.start_date then\n halt msg: 'check_date() fail' \n false\n else\n true\n end\n end",
"def overdue\n @date > Date.today\n end",
"def validate_date(input_date) \n too_early = Date.parse(\"31 December 2019\")\n too_late = (Date.today)+1\n raise DateError unless ((input_date > too_early) && (input_date < too_late))\n end",
"def valid_dates\n device_request = DeviceRequest.find(device_request_id)\n current_date = Date.today\n if self.on_date.present?\n self.errors.add :on_date, \"Quotation date can't be future\" if self.on_date > current_date\n self.errors.add :on_date, \"Quotation date should be onwards #{device_request.on_date}\" if self.on_date < device_request.on_date\n end\n end",
"def overdue?\n @due_date < Date.today\n end",
"def has_valid_date?\n self.time_event < Time.now.advance(days: 1)\n end",
"def is_status_free (date)\n that_date = date\n return that_date < Date.today \n #komentarz na przyszlosc: #Date.new(2009,6,13)\n end",
"def date_is_not_ancient?(date)\n date > Date.new(1900)\n end",
"def validacion_fecha\n if !check_in.blank? && check_in < Date.today\n errors.add(:check_in, \"menor a fecha actual\")\n \t elsif !check_out.blank? && check_out < Date.today\n \t errors.add(:check_out, \" menor a fecha actual\")\n \t elsif !check_out.blank? && check_out < check_in\n \t errors.add(:check_out, \"no puede ser menor al check_in\")\t\n end\n end",
"def created_date_must_be_before_showtime\n unless showing.tickets_available\n errors.add(:created_at, \"The showing you are trying to purchase is no longer available\")\n end\n end",
"def expiration_date_cannot_be_in_the_past\n if expiration_date.present? && expiration_date < Date.today\n errors.add(:expiration_date, \"can't be in the past\")\n end\n end",
"def new?\n available_on + 1.month >= Time.zone.today ? true : false\n rescue\n false\n end",
"def check_in()\n @due_date = nil\n end",
"def check_in()\n @due_date = nil\n end",
"def check_out_date\n check_out && Date.parse(check_out)\n rescue ArgumentError\n # check-out parameter is not a valid date\n end",
"def due_today?\n @date == Date.today.to_s\n end",
"def mobilisation_start_date_validation\n mobilisation_start_date = initial_call_off_start_date - mobilisation_period.weeks - 1.day\n errors.add(:mobilisation_start_date, :greater_than) if mobilisation_start_date <= Time.zone.today\n end",
"def not_in_past\n return unless due_date < Time.zone.today || start_date < Time.zone.today\n errors.add(:base, \"Cannot create reservation in the past.\\n\")\n end",
"def release_date_is_in_the_past\n if release_date.present?\n errors.add(:release_date, \"should be in the past\") if release_date > Date.today\n end\n end",
"def pending?\n start_date > Date.today\n end",
"def appointment_on_is_valid\n return if appointment_on.nil? || !appointment_on_changed?\n\n unless (appointment_on.to_date - Date.today) >= MINIMUM_DAYS\n errors[:appointment_on] << \"should be at least #{MINIMUM_DAYS} days from today\"\n end\n end",
"def valid_date?\n errors.add(:date, \"can't be in the past\") if !date.blank? and date < Date.today\n end",
"def virtually_over?\n end_date < Date.today\n end",
"def overdue?\n next_payment_at && next_payment_at.to_date < Date.today\n end",
"def expiration_date_cannot_be_in_the_past\n if !expiration_date.blank? and expiration_date < Date.today\n #add messages to the errors collection\n errors[:expiration_date] << \"can't be in the past\"\n end\n end",
"def start_date_cannot_be_in_the_past\n errors.add(:start_date, 'cannot be in the past') if\n start_date < Time.zone.today\n end",
"def available_today?(date)\n raise 'Date must be a String or Date object' unless(date.is_a?(String) || date.is_a?(Date))\n date = Date.strptime(date, '%Y-%m-%d') if date.is_a?(String)\n Date.current >= date\n end",
"def before_period?\n if Time.now >= self.orderDate \n errors.add(:orderDate, \"Can't be in the past\")\n end\n end",
"def active_on?(date)\n relieving_date.nil? || relieving_date >= date\n end",
"def background_check_valid?\n if background_check_date.present?\n background_check_date >= 36.months.ago.midnight\n else\n false\n end\n end",
"def\n check_in()\n @due_date = nil\n end",
"def in_the_past?\n if self.date < Date.today\n errors.add(:date, \"of reservation cannot be in the past.\")\n end\n end",
"def stale_date?(val)\n _to_date(val) < Time.now() - (3600 * 30 + 10)\n end",
"def past?\n start_date < Time.now\n end",
"def before date\n @before = date\n end",
"def covered?\n unless expr_date.nil?\n return ((expr_date<=>Date.today )> 0 ) ? true : false\n end\n false\n end",
"def date_valid?(date)\n\tvalid_dates = Date.parse(DATA_START_DATE)..Date.today\n\tif valid_dates.cover?(date)\n\t\treturn true\n\telse\n\t\tputs \"\\n Date must be after #{DATA_START_DATE} and before today.\"\n\t\treturn false\n\tend\nend",
"def check_date(event)\n if close_date(event)\n event.reminded = true\n end\n end",
"def checked_in?\n !check_in_time.blank?\n end",
"def initialize(checkin_date, checkout_date)\n if !checkin_date.is_a?(Date) || !checkout_date.is_a?(Date)\n raise ArgumentError.new(\"Checkin or Checkout dates is not Date object\")\n end\n\n if checkin_date > checkout_date\n raise ArgumentError.new(\"Checkin date must be before Checkout date\")\n end\n\n @checkin_date = checkin_date\n @checkout_date = checkout_date\n end",
"def check_no_delay_requirements(date)\n return true unless release_no_delay?\n date == Time.zone.today\n end",
"def past?\n due_on < Date.today\n end",
"def day_before_birthday?\n return false unless @birthday.present?\n @birthday == (Date.today + 1).strftime('%m/%d')\n end",
"def due_today?\n @due_date == Date.today\n end",
"def check_date\n\t\tif self.hasError\n\t\t\terrors.add(\"\", \"You entered Invalid date: \\n - \"+self.interviewer.name)\n\t\t\t# puts \"===================CHECKDATE===================\"\n\t\telsif Time.at(self.sched_end.to_i) <= Time.at(self.sched_start.to_i)\n\t\t\terrors.add(\"\", \"Start time cannot be greater than end time \\n - \"+self.interviewer.name)\n\t\tend\n\tend",
"def birth_date_cannot_be_in_the_future\n if birthdate.present? && birthdate >= Date.today\n errors.add(:birthdate, \"Can't be in the future\")\n end\n end",
"def lessthan?\n if self.contractendon < 14.day.since.to_date && self.contractendon > Time.now.to_date\n return true\n end\n end",
"def is_start_date_correct?\n if start_date < Date.today || start_date > Date.today + 5.years\n errors.add(:start_date, \" must be between the next 30 minutes : #{(Time.now + 30.minutes).strftime '%H:%M'} and before : #{Date.today + 5.years}\")\n end\n end",
"def check_out_date_length\n errors.add(:check_out_at, \"must be less than 12 hours after check in at\") if\n check_out_at > (check_in_at + 12.hours)\n end",
"def out_of_date?\n time_diff = Time.zone.now - updated_at\n time_diff >= 2.weeks\n end",
"def date_valid?(date)\n valid_dates = Date.parse(DATA_START_DATE)..Date.today\n if valid_dates.cover?(date)\n return true\n else\n puts \"\\nDate must be after #{DATA_START_DATE} and before today.\"\n return false\n end\nend",
"def checked_in\n self.check_in= DateTime.now\n end",
"def today?\n @date == Date.today\n end",
"def start_date_cannot_be_in_the_past\n errors.add(:start_date, 'can not be in past') if start_date.present? && start_date < Date.today\n end",
"def not_in_past\n if due_date < Date.current || start_date < Date.current\n errors.add(:base, \"Cannot create reservation in the past\\n\")\n end\n end",
"def date_of_birth_cannot_be_in_the_future\n if date_of_birth > Date.today\n errors.add(:date_of_birth, \"can't be in the future\")\n end\n end",
"def date_of_birth_cannot_be_in_the_future\n if date_of_birth > Date.today\n errors.add(:date_of_birth, \"You cannot be born in the future...\")\n end\n end",
"def not_in_past?\n #return true if self.class == Reservation && self.status != 'reserved'\n if (start_date < Date.today) || (due_date < Date.today)\n errors.add(:base, \"Reservation cannot be made in the past.\\n\")\n return false\n end\n return true\n end",
"def test_date\n if test_execution_date and test_delivery_date\n if test_execution_date > test_delivery_date\n errors.add(:test_delivery_date, \"should be greater then test date.\")\n end\n end\n end",
"def check_dates\n # TODO the init_time must be less then the end_time\n true\n end",
"def send_today?\n day_today = (Date.today - @config['start_date']).round\n (day_today % 28) < 21\nend",
"def check_reorder_date\n if reorder_on <= Date.today\n reorder_on = Date.tomorrow\n save\n end\n end",
"def due_today?\n due_date == Date.due_today\n end",
"def overdue? ()\n\t\t@due_date < Time.now\n end",
"def check_out_past\n errors.add(:check_out_at, \"cannot be in the past\") if\n check_out_at < Time.now\n end",
"def legacy?\n date < Date.new(2014, 06, 06)\n end",
"def expiration_date_after_today\n errors.add(:expiration_date, 'must be after today') if expiration_date <= Time.now\n end",
"def ticket_cannot_be_created_after_start_date\n event_start_date = self.event.start_date\n if Date.today > event_start_date\n errors.add(:created_at, \"ticket cannot be created after start date of event\" )\n end\n end",
"def validate_dates_cannot_be_in_the_past\n if self.promised_pickup_date.present? && self.promised_pickup_date_changed? && (self.promised_pickup_date.in_time_zone < Date.today.in_time_zone) && self.in_or_before_state?(:wtg_for_trip_confirmation)\n self.errors.add(:promised_pickup_date, I18n.t(\"models.vehicle.errors.date_cannot_be_past\"))\n end\n if self.hold_for_pickup_date.present? && self.hold_for_pickup_date_changed? && self.hold_for_pickup_date < Date.today\n self.errors.add(:hold_for_pickup_date, I18n.t(\"models.vehicle.errors.date_cannot_be_past\"))\n end\n if self.sale_hold_action_date.present? && self.sale_hold_action_date_changed? && self.sale_hold_action_date < Date.today\n self.errors.add(:sale_hold_action_date, I18n.t(\"models.vehicle.errors.date_cannot_be_past\"))\n end \n end",
"def reiwa?\n Date.new(2019, 5, 1) <= self\n end",
"def upcoming?\n (start_date > Date.today)\n end",
"def expired?\n !expiration_date || expiration_date <= Date.today\n end",
"def check_end_date\n if end_date < Date.today\n \n errors.add(:end_date, \"End Date can only be later than today\")\n end\n end",
"def past?\n (end_date < Date.today)\n end",
"def show_date_condition\n false\n end",
"def deadline_over?(risk_register)\n return date_difference(Date.today, risk_register.target_date) < 0\n end",
"def overdue?\n due < Date.current\n end",
"def future_pickup_date\n # Model does not have access to session (and thus the products in the shopping cart);\n # need to pass in the earliest allowable pickup date\n earliest_date = earliest_pickup_date\n earliest_date = Date.today if earliest_date.nil?\n if pickup_date < earliest_date\n errors.add(pickup_date_error, \"#{I18n.t('orders.date_must_be')} #{earliest_date} #{I18n.t('orders.or_later')}\") # \" - The pickup date must be #{earliest_date} or later.\"\n end\n end"
] |
[
"0.7624395",
"0.7586155",
"0.7478645",
"0.7250873",
"0.72344786",
"0.72283113",
"0.7192968",
"0.7068701",
"0.699601",
"0.6960622",
"0.6960622",
"0.68803966",
"0.6801893",
"0.67565036",
"0.6746318",
"0.67265224",
"0.6720884",
"0.67051125",
"0.666174",
"0.66460663",
"0.6625849",
"0.65957874",
"0.6564892",
"0.65546745",
"0.65369767",
"0.6533216",
"0.64998525",
"0.64814657",
"0.6469044",
"0.6459234",
"0.6441347",
"0.6434375",
"0.64288855",
"0.6427652",
"0.6418476",
"0.6418476",
"0.64092857",
"0.64046067",
"0.64015186",
"0.6381465",
"0.6380663",
"0.6369963",
"0.63632077",
"0.6354349",
"0.6348464",
"0.6346706",
"0.63466424",
"0.6324025",
"0.63231057",
"0.63169414",
"0.63069683",
"0.6298206",
"0.62971145",
"0.62970316",
"0.6293147",
"0.629038",
"0.6284948",
"0.6271672",
"0.6270565",
"0.6269069",
"0.62668777",
"0.6261111",
"0.6252075",
"0.6248752",
"0.62395465",
"0.6235303",
"0.62315506",
"0.6223772",
"0.6223007",
"0.62171376",
"0.6212869",
"0.62123513",
"0.62079203",
"0.6203335",
"0.62001836",
"0.61823153",
"0.6173351",
"0.6171084",
"0.6167043",
"0.61652327",
"0.6163682",
"0.6162347",
"0.6162265",
"0.61585915",
"0.6150659",
"0.6144558",
"0.61431086",
"0.6142314",
"0.6135475",
"0.6134296",
"0.61299133",
"0.6116659",
"0.6100727",
"0.60959786",
"0.6091835",
"0.60890615",
"0.60859513",
"0.60847455",
"0.6083633",
"0.607724"
] |
0.7987446
|
0
|
Booking should only be for day1 to day2 as booking is done for night for example today's 12pm to next day's 12pm.
|
def checkout_at_after_checkin_at
return if dates_blank
if checkout_at <= checkin_at
self.errors.add(:checkout_at, ': Should be greater than checkin date ')
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n @status = \"Booked\"\n @status_notice = 'booking was successfully created.'\n @bookings = Booking.where(:conference_room_id => params[:conference_room_id])\n @bookings.each do |booking| \n if (booking.start_time..booking.end_time).cover?(params[:booking][:start_time]) || (booking.start_time..booking.end_time).cover?(params[:booking][:end_time]) || (params[:booking][:start_time]..params[:booking][:end_time]).cover?(booking.start_time) || (params[:booking][:start_time]..params[:booking][:end_time]).cover?(booking.end_time)\n @status = \"Pending\"\n @status_notice = \"Sorry, Your requested slot is already Booked. so your requestis Pending state.\"\n end\n end\n\n respond_to do |format|\n if params[:booking][:start_time].to_date.wday == 0 || params[:booking][:end_time].to_date.wday == 0 || params[:booking][:start_time].to_date.wday == 6 || params[:booking][:end_time].to_date.wday == 6\n format.html { redirect_to portal_conference_room_bookings_url, alert: 'Sorry!, Bookings are not allowed on Weekend.' }\n else \n if Time.now < params[:booking][:start_time] && params[:booking][:start_time] < params[:booking][:end_time]\n @booking = Booking.new(:conference_room_id => params[:conference_room_id], :status => @status, :user_id => current_user.id, :start_time => params[:booking][:start_time], :end_time => params[:booking][:end_time], :created_at => Time.now)\n if @booking.save!\n \n @user = User.find(@booking.user_id)\n if @status == \"Booked\"\n ExampleMailer.booking_email(@user, @booking).deliver\n elsif @status == \"Pending\"\n ExampleMailer.pending_email(@user, @booking).deliver\n end\n\n format.html { redirect_to portal_conference_room_bookings_url, notice: @status_notice }\n format.json { render :show, status: :created, location: @booking }\n else\n format.html { render :new }\n format.json { render json: @booking.errors, status: :unprocessable_entity }\n end\n else\n format.html { redirect_to portal_conference_room_bookings_url, alert: 'Please Book Conference Room for future date.' }\n end \n end\n end\n end",
"def create\n\n @booking = Booking.new(booking_params)\n \n start_time=@booking.start_time.time\n end_time=@booking.end_time.time\n\n # General case 1 : The starting time should always be lesser than the Ending time\n # General case 2 : One player should not play for more than 4 hours\n \n if start_time>=end_time || TimeDifference.between(start_time, end_time).in_hours > 4 || TimeDifference.between(start_time, end_time).in_minutes < 10\n flash[:notice]=\"Invalid BookingTime\"\n return redirect_to new_booking_path\n end\n \n if Booking.where(:date=>@booking.date).select(:start_time,:end_time,:date).present?\n\n @b=Booking.where(:date=>@booking.date).select(:start_time,:end_time,:date)\n else\n @booking.save\n flash[:notice]=\"Booking saved\"\n\n return redirect_to home_index_path\n end\n\n @count=0\n @b.each do |booking|\n\n \n if (start_time.hour..end_time.hour).overlaps?(booking.start_time.hour..booking.end_time.hour)\n @count=@count+1\n if(start_time.hour==booking.end_time.hour && start_time.min>=booking.end_time.min)\n @count=@count-1\n end\n \n if(end_time.hour==booking.start_time.hour && end_time.min<=booking.start_time.min)\n @count=@count-1\n end\n end\n\n end\n\n if @count<4\n flash[:notice]=\"Available\"\n @booking.save\n redirect_to @booking\n else\n redirect_to new_booking_path\n flash[:notice]= \"Slot not available\"\n end\n\n end",
"def schedule(guest)\n currentday = Time.now.strftime(\"%A\")\n currenttime = Time.now.strftime(\"%H:%M:%S\")\n\n goodtogo = false\n\n guest.schedules.each do |schentry|\n if schentry.day == currentday && schentry.start_time.strftime(\"%H:%M:%S\") < currenttime && schentry.stop_time.strftime(\"%H:%M:%S\") > currenttime\n goodtogo = true\n end\n end\n\n return goodtogo\n end",
"def create\n @booking = Booking.new(booking_params)\n @current_room_bookings = Booking.where('room_id=?', @booking.room_id);\n overlap = false;\n @current_room_bookings.each do |old_booking|\n endTime = old_booking.booking_start_time + 2*60*60;\n currentEndTime = @booking.booking_start_time + 2*60*60;\n if(@booking.booking_start_time...currentEndTime).overlaps?(old_booking.booking_start_time...endTime)\n respond_to do |format|\n format.html { redirect_to new_booking_path, notice: \"Booking for that time slot already exists!\" }\n format.json { render json: @booking.errors, status: :unprocessable_entity }\n end\n overlap = true;\n break;\n end\n end\n if(!overlap)\n respond_to do |format|\n if @booking.save\n format.html { redirect_to home_path, notice: 'Booking was successfully created.' }\n format.json { render :show, status: :created, location: @booking}\n UserMailer.welcome_email(@booking).deliver!\n else\n format.html { render :new }\n format.json { render json: @booking.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def no_time_overlap\n @other_bookings = Booking.where(:date => date)\n @other_bookings.each do |other_booking|\n if other_booking.time.strftime(\"%I:%M%p\") == time.strftime(\"%I:%M%p\") && other_booking.room_id == room_id\n errors.add(:time, \"Cannot book, overlapping sessions!\")\n end\n end\n end",
"def overlapping_dates\n reservation = Reservation.find(params[:id])\n space = reservation.space\n\n start_date = reservation.start_date.to_date\n end_date = reservation.end_date.to_date\n\n confirmed_bookings = space.reservations.where(approved: true)\n\n check = confirmed_bookings.where('? <= DATE(start_date) AND DATE(end_date) <= ?', start_date, end_date)\n return unless check.any?\n\n flash[:danger] = 'You already confirmed another booking request with overlapping dates.'\n redirect_to your_reservations_path\n end",
"def check_dates\r\n self.start_time -= 8.hours\r\n self.end_time -= 8.hours\r\n end",
"def validate_for_another_reservation\n if start_at && end_at && BUSY_STATUSES.include?(self.status)\n errors.add(:start_at, 'Another reservation already exists for these dates.') if exists_other_reservations_in_same_period?\n end\n end",
"def on_same_day?(reservation)\n (reservation.blank? || reservation.start_dt.blank?) ? false : reservation_on_day?(\"start_day\", reservation.start_dt.strftime('%Y-%m-%d'))\n end",
"def show\n @booking = @boat.bookings.build(user: current_user)\n @booking.start_time = Time.zone.tomorrow + 9.hours\n @booking.end_time = Time.zone.tomorrow + 18.hours\n @booking.people_on_board = 1\n #TODO disable also booked(accepted) days\n end",
"def available_time_slot date_of_booking\n\t\tif date_of_booking.gsub(/[-]+/,\"\").to_i != Time.zone.now.strftime(\"%Y%m%d\").to_i\n\t\t\tresource_slot = self.timeslots\n\t\t\tif self.bookings.where(date_of_booking:date_of_booking).where(status:1)\n\t\t\t\tbookings_of_day = self.bookings.where(date_of_booking: date_of_booking).where(status:1)\n\t\t\t\tbookings_of_day.each do |x|\n\t\t\t\t\tresource_slot.delete_at(x.slot)\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tresource_slot = next_time_slots\n\t\tend\n\t\tresource_slot\n\tend",
"def check_overlapping_dates\n #compare this new reservation against existing reservations\n listing.reservations.each do |old_booking|\n if overlap?(self, old_booking)\n return errors.add(:overlapping_dates, \"The booking dates are not available\")\n end\n end\n\n end",
"def doctor_double_booked\n this_start = self.start_time\n this_end = self.end_time\n conflict = doctor.appointments.any? do |appointment|\n other_start = appointment.start_time \n other_end = appointment.end_time\n other_start < this_end && this_end < other_end || other_start < this_start && this_start < other_end\n end\n if conflict\n errors.add(:doctor, 'has a conflicting appointment')\n end\n end",
"def date_time_check?\n booking_date_time = booking_date.to_datetime\n booking = Booking.where(\"cleaner_id = ? and booking_date > ? and booking_date < ?\", cleaner_id, booking_date_time - 2.hours, booking_date_time + 2.hours)\n if booking.present?\n errors.add('Sorry', \"This Cleaner #{cleaner.first_name} is not available in your select time\")\n end\n end",
"def schedule_next_check time_to_check\n # TODO if time to check is not between 6:55 AM and 9:00 AM on a weekday, \n # TODO then schedule for 6:55 AM on the next weekday\n puts \"Is weekday? #{time_to_check.wday.between?(1,6)}\"\n puts \"Is after 9:00 AM on weekday? #{time_to_check.hour.between?(6,9)}\"\n puts \"Will check for bus at #{time_to_check}\"\n @sched.at time_to_check do\n check_for_bus\n end\n @sched.join\n end",
"def calculate_time_from_to_cost\n\n time_cost = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable_out_price', '0')\n if time_cost != '0'\n\n # Check if the reservation correspond to the main season or not\n main_season_month_from = SystemConfiguration::Variable.get_value('booking.pickup_return_main_season.month_from', 1).to_i\n main_season_day_from = SystemConfiguration::Variable.get_value('booking.pickup_return_main_season.day_from', 1).to_i\n main_season_month_to = SystemConfiguration::Variable.get_value('booking.pickup_return_main_season.month_to', 12).to_i\n main_season_day_to = SystemConfiguration::Variable.get_value('booking.pickup_return_main_season.day_to', 31).to_i\n\n if main_season_month_from == 1 and main_season_day_from == 1 and main_season_month_to == 12 and main_season_day_to == 31\n timetable_id = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable','0').to_i\n else\n # JAN DIC\n # -------------------------------------\n # ^=======================^\n # from to\n if main_season_month_from <= main_season_month_to or \n (main_season_month_from == main_season_month_to and main_season_day_from <= main_season_day_to) \n if (@date_from.month >= main_season_month_from or \n (@date_from.month == main_season_month_from and @date_from.day >= main_season_day_from)) and\n (@date_to.month <= main_season_month_to or \n (@date_to.month == main_season_month_to and @date_to.day <= main_season_day_to)) # In main season\n timetable_id = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable','0').to_i\n else # Out of season\n timetable_id = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable_out_of_season','0').to_i\n end\n else\n # JAN DIC\n # -------------------------------------\n # ======^ ^======\n # to from\n if ((@date_from.month >= main_season_month_from or\n (@date_from.month == main_season_month_from and @date_from.day >= main_season_day_from)) or\n (@date_from.month <= main_season_month_to or \n (@date_from.month == main_season_month_to and @date_from.day <= main_season_day_to))\n ) and\n ((@date_to.month >= main_season_month_from or\n (@date_to.month == main_season_month_from and @date_to.day >= main_season_day_from)) or\n (@date_to.month <= main_season_month_to or\n (@date_to.month == main_season_month_to and @date_to.day <= main_season_day_to))) # In main season\n timetable_id = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable','0').to_i\n else # Out of season\n timetable_id = SystemConfiguration::Variable.get_value('booking.pickup_return_timetable_out_of_season','0').to_i\n end\n end\n end\n\n #p \"timetable_id: #{timetable_id} -- main season: #{main_season_day_from}-#{main_season_month_from} #{main_season_day_to}-#{main_season_month_to}\"\n\n time_cost = BigDecimal.new(time_cost)\n if timetable_id > 0\n if timetable = ::Yito::Model::Calendar::Timetable.get(timetable_id)\n @time_from_cost = calculate_time_cost(@date_from, @time_from, time_cost, timetable)\n @time_to_cost = calculate_time_cost(@date_to, @time_to, time_cost, timetable)\n end\n end\n\n end\n end",
"def init_days\n (start_time.to_date..end_time.to_date).each do |t|\n Day.create date: t, availability: self.aasm_state, boat: boat, booking: self\n end\n end",
"def check_conflicts_with_room(booking, room, devices, capacity, recurring_days)\n\n if devices != room.devices\n if devices != 0\n return true\n end\n end\n\n logger.info \"capacity is #{capacity.to_i} and rooms capacity is #{room.capacity}\"\n if !capacity.nil?\n\n if capacity.to_i > room.capacity\n return true\n end\n end\n\n dates = split_booking booking.startdate,recurring_days\n\n splited_bookings = Array.new\n dates.each do |date|\n tmp_booking = Booking.new\n tmp_booking.enddate = booking.enddate\n tmp_booking.starttime = booking.starttime\n tmp_booking.endtime = booking.endtime\n tmp_booking.recurring = booking.recurring\n tmp_booking.startdate = date\n splited_bookings << tmp_booking\n end\n\n bookings = Booking.find_all_by_room_id room.id\n\n\n\n bookings.each do |booking_at_room|\n\n splited_bookings.each do |splited_booking|\n if check_conflicts_with_specific splited_booking,booking_at_room\n hour_bits_1 = build_hour_bits splited_booking\n hour_bits_2 = build_hour_bits booking_at_room\n if hour_bits_1 & hour_bits_2 != 0\n return true\n end\n end\n end\n\n end\n\n return false\n\n end",
"def checkIfBooked\n booking_start_time = Time.parse(get_booking[\"date\"].to_s)\n hours_booked = get_booking[\"hours_booked\"].to_i\n booking_stop_time = booking_start_time + (3600 * hours_booked)\n dates_booked = get_tutor[\"dates_booked\"]\n lesson_block = 14400\n bookings_array = []\n dates_booked.each do |date|\n start_time = Time.parse(date[\"date\"].to_s)\n stop_time = start_time + lesson_block\n if(booking_start_time >= start_time && booking_start_time <= stop_time)\n bookings_array.push(date)\n elsif(start_time >= booking_start_time && start_time <= booking_stop_time)\n bookings_array.push(date)\n end\n \n end\n if(bookings_array.length >= 1)\n return true\n else\n return false\n end\n end",
"def make_booking!(start_time, end_time)\n starthour = Time.parse(start_time).strftime(\"%k:%M\")\n endhour = Time.parse(end_time).strftime(\"%k:%M\")\n startmonth = Time.parse(start_time).strftime(\"%B\" )\n endmonth = Time.parse(end_time).strftime(\"%B\")\n startday = Time.parse(start_time).strftime(\"%d\")\n endday = Time.parse(end_time).strftime(\"%d\")\n \n if is_available?(start_time, end_time)\n @parking_space[:bookings].push({start_time: start_time, end_time: end_time})\n puts \"Your parking has been booked for €#{calculate_price(start_time, end_time)}\"\n else\n if days_between(start_time, end_time) == 0\n puts \"There are no spaces available on #{startday}#{ordinal(startday)} #{startmonth} from #{starthour} to #{endhour}.\"\n else \n puts \"There are no spaces available from #{startday}#{ordinal(startday)}, #{startmonth} - #{endday}#{ordinal(endday)}, #{endhour}.\"\n end\n end\n\n puts \"\"\nend",
"def time_is_within_scheduled_days\n \tif start_time\n \t\tschedule = Schedule.find_by(id: Piece.find_by(id: piece_id).schedule_id)\n\t update_day = nil\n\t schedule.days.each do |day|\n\t \t\tupdate_day = day if start_time >= day.start_time and start_time <= day.end_time\n\t \t\tbreak if !update_day.nil?\n\t end\n\t update_day.nil? ? errors.add(:start_time, \"must be during one of the scheduled times\") : update_attribute(:day, update_day)\n\t else\n\t \tupdate_attribute(:day, nil)\n\t end\n end",
"def availability(room_number, end_date, start_date)\n\n @reservations.each do |reservation|\n\n # i am trying to look throught all the reservation instances and\n # see what dates are available to reserve a reservation.\n\n if room_number == reservation.room_number && reservation.does_overlap(end_date,start_date)\n\n # if reservation.start_date == start_date && reservation.end_date == end_date\n # return false\n # elsif reservation.start_date > start_date && reservation.start_date < end_date\n # next #true\n # elsif reservation.start_date < start_date && reservation.start_date < end_date\n # next #true\n # elsif reservation.start_date > start_date && reservation.start_date > end_date\n # next #false , i think i need only\n # else\n # end\n\n\n\n\n\n end\n\n end\nend",
"def create_booking(day)\n new_booking = Booking.create(host_id: self.id,day: day)\n puts \"A new booking has been created for #{self.name} on #{day}.\"\n new_booking.assign_waiter\n puts \"#{new_booking.waiter.name} has been assigned to #{self.name}'s booking'.\"\n end",
"def set_time days\r\n days.each do |day,times|\r\n periods = times.split(\",\")\r\n periods.each do |period|\r\n start_time,end_time = period.split(\"-\")\r\n raise unless Time.parse(start_time) < Time.parse(end_time) \r\n #this will throw an exception if the day is invalid\r\n KlassSchedule.create :klass_id=>self.id,:start_time=>start_time,\r\n :end_time=>end_time,:day_of_week=>day\r\n end\r\n end \r\n end",
"def time_slots\n\n # you can book by the hour, and you can stay for an hour\n reservation_interval = 1.hour\n\n # Determine the earliest time we will allow reservation\n # It can't be in the past, we'll start 10 minutes from now\n start_time = Time.zone.now + 10.minutes\n # Then we have to round to the next hour block\n start_time = Time.zone.at( (start_time.to_f / reservation_interval).ceil * reservation_interval )\n # Then, if we are still earlier than opening hour, just use the opening hour\n # We can use the 'max' Array method\n start_time = [start_time, start_time.change(hour: opening_hour)].max\n\n # Determine the furthest in the future we will allow reservations\n end_time = (start_time + 3.days).change(hour: closing_hour)\n\n # Now, we want to make a list of every hour between our start_time and our end_time\n # For this we can use a begin... end while condition loop.\n # We'll start with an empty array that will hold all the hours,\n # and a variable to hold each hour, which we will keep increasing by 1 hour, and then add to our array\n # Our loop condition will have us stop looping once we've reached the end time\n\n all_times = []\n a_time = start_time\n\n begin\n\n # add this time to our list of times\n all_times << a_time\n\n # increment the time\n a_time += reservation_interval\n\n # Once we get to closing time, we have to skip ahead to the next day's opening\n # That way you can't make a reservation at 2am\n if (a_time + reservation_interval) > a_time.change(hour: closing_hour)\n a_time = (a_time + 1.day).change(hour:opening_hour)\n end\n\n end while a_time < end_time\n\n all_times\n end",
"def meeting_conflict?(other)\n return false if self.start_time.nil? or other.start_time.nil?\n section_days = other.days.split(\"\")\n section_days.each do |day|\n if( self.days.include?(day) )\n if (self.start_time.to_i >= other.start_time.to_i and self.start_time.to_i <= other.end_time.to_i) or \n (other.start_time.to_i >= self.start_time.to_i and other.start_time.to_i <= self.end_time.to_i)\n return true\n end \n end\n end\n return false\n end",
"def reserved_slots(date)\n Reservation.confirmed.where(nook_id: self.id)\n .happening_within(date.beginning_of_day..date.end_of_day)\n .map do |r|\n r.start.strftime('%H%M').to_i..\n (r.end + 1.seconds).strftime('%H%M').to_i\n end\n end",
"def check_overlapping_dates\n # compare this new booking againsts existing bookings\n listing.bookings.each do |old_booking|\n if overlap?(self, old_booking)\n return errors.add(:overlapping_dates, \"The booking dates conflict with existing bookings\") \n end\n end\n\n end",
"def doctor_double_booked #We check this against all of the doctors appointments \n this_start = self.start_time #Instance methods that are called on a particular doctor's appointment \n this_end = self.end_time \n conflict = doctor.appointments.any? do |appointment| \n #Look through all of the doctors appointments and checks if there are any overlapping appointments (start_time, end_time). \n #any? returns true or false. \n \n other_start = appointment.start_time \n other_end = appointment.end_time\n other_start < this_end && this_end < other_end || other_start < this_start && this_start < other_end\n # other_start < this_end && this_end < other_end \n #This means that this appointment ends in the middle of an existing appointment.\n \n # other_start < this_start && this_start < other_end \n #This means that this appointment starts in the middle of an existing appointment. \n end\n if conflict #true or false \n errors.add(:doctor, 'has a conflicting appointment') \n # Adds an error message to the appointment with an error message about the doctor. The doctor is the key, the message is the value. \n end\n end",
"def check_overlapping_dates\n\t # compare this new booking againsts existing bookings\n\t listing.reservations.each do |old_reservation|\n\t if overlap?(self, old_reservation)\n\t return errors.add(:overlapping_dates, \"The booking dates conflict with existing bookings\") \n\t end\n\t end\n\tend",
"def check_schedule(range_of_days)\n\tif 1 > range_of_days.to_i\n\t\traise \"The schedule of the diary must last for at least one day.\"\n\telsif 40 < range_of_days.to_i\n\t\traise \"Save paper! Don't generate schedule for >40 days.\"\n\tend\n\t\n\t# Set the duration of the food diary\n\t$duration = range_of_days.to_i\nend",
"def booking(room, params)\n if @browser.element(css: '#ajaxRoomList > div.listDiv.initialized > table > tbody > tr:nth-child(' + room.to_s + ')').present?\n @browser.element(css: '#ajaxRoomList > div.listDiv.initialized > table > tbody > tr:nth-child(' + room.to_s + ')').click\n else\n @browser.element(css: '#ajaxRoomList > div:nth-child(2) > div.PageSelectorControls > div.imgNextArrow').click\n room = room.to_i - 30\n @browser.element(css: '#ajaxRoomList > div.listDiv.initialized > table > tbody > tr:nth-child(' + room.to_s + ')').click\n end\n @browser.select_list(:id, 'cboDuration').select(params[:duration].to_s)\n @browser.element(css: '#btnAnyDate').click\n BookRoom.search_day(@browser, params[:day], BookRoom.search_month(@browser, params[:month]))\n page_html = ScraperModule.parse_html(@browser)\n i = 1\n acum = 1\n while i < 29\n date = page_html.xpath('//*[@id=\"roomavailability\"]/div/div/div[2]/table/tbody/tr[' + i.to_s + ']/td[1]').text\n if page_html.at_css('#roomavailability > div > div > div.listDiv.initialized.RoomAvailabilityList.NoPadding.NoEntityType.TableLayoutAuto > table > tbody > tr:nth-child(' + i.to_s + ') > td:nth-child(2) > input')\n puts i.to_s + ') ' + date.to_s + ' >> Room is available'\n @time[i.to_s] = @browser.element(css: '#roomavailability > div > div > div.listDiv.initialized.RoomAvailabilityList.NoPadding.NoEntityType.TableLayoutAuto > table > tbody > tr:nth-child(' + i.to_s + ') > td:nth-child(2) > input')\n else\n puts i.to_s + ') ' + date.to_s + ' >> Room is unavailable'\n acum += 1\n end\n i += 1\n end\n if acum == 28\n return false\n else\n return true\n end\n end",
"def create\n # Check for dates/times overlapping\n puts current_user[:id], \"CURRENT USER\"\n overlap = Booking.where('end_date > ? AND start_date < ?', booking_params[:start_date], booking_params[:end_date])\n\n # If room is free, create booking\n if overlap.length.zero? \n booking = Booking.create!(booking_params)\n render json: { status: 'SUCCESS', message: 'Booking created', data: booking }, status: :ok\n else\n render json: { status: 'ERROR', message: 'Cannot create booking, date already booked' }, status: :unprocessable_entity\n end\n end",
"def check_overlap\n bookings = @parking_space.booking.all\n booking = booking_params.values\n for currentBooking in bookings\n if booking.at(3).to_i < currentBooking.finish_time.to_i && currentBooking.start_time.to_i < booking.at(4).to_i\n return true\n end \n end\n return false\n end",
"def create\n\n @course = Course.find params[:booking][:course_id]\n\n @classroom = Classroom.find params[:booking][:classroom_id]\n @start = @course.start_date\n @end = @course.end_date\n @timeslot = params[:booking][:b_time]\n \n\n @days_of_week = params[:days_of_week]\n\n if @days_of_week.nil?\n render action: 'new', notice: 'please select at least one day'\n end\n\n @course_days = (@course.start_date..@course.end_date).to_a.map do |day|\n if @days_of_week.include? day.strftime('%A')\n day \n end\n end.compact\n\n @book_array = []\n @course_days.each do |d|\n if Booking.where('classroom_id = ? AND b_date = ? AND (b_time = ? OR b_time = ?)', @classroom.id, d.to_date, @timeslot, 'Day').count > 0\n redirect_to new_booking_path, notice: \"this classroom is not available on #{d} during #{@slot}\" and return\n else \n @book_array << Booking.new(classroom_id: @classroom.id, course_id: @course.id, b_date: d, b_time: @timeslot)\n end\n end\n \n @book_array.each do |b|\n b.save\n end\n redirect_to bookings_url\n\n end",
"def check_overlapping_dates\n # compare this new reservation againsts existing reservations\n if start_date.present? and end_date.present?\n listing.reservations.each do |old_reservation|\n if overlap?(self, old_reservation)\n return errors.add(:The_dates_are_not_available, \"\")\n end\n end\n end\n end",
"def check_dates\n dates_already_booked = [date_in, date_out]\n body.bookings.each do |b|\n dates_already_booked << b.date_in\n dates_already_booked << b.date_out\n end\n dates_already_booked.sort!\n idx_in = dates_already_booked.index(date_in)\n idx_out = dates_already_booked.index(date_out)\n if idx_in + 1 == idx_out && idx_in % 2 == 0\n true\n else\n throw(:abort)\n end\n end",
"def override_all_day_based_on_duration\n starts_on = starts_at.to_date\n ends_on = ends_at.to_date\n if starts_on != ends_on\n self.all_day = true\n end\n true\n end",
"def create\n\n @booking = Booking.new(booking_params)\n @room = Room.where(\"roomno = ?\", @booking.roomno)\n if @room.nil? or @room.empty?\n flash[:notice] = \"Room not found !\"\n render 'bookings/new' and return\n end\n if current_user.usertype != \"Admin\" and current_user.usertype != 'Super Admin'\n @user = User.where(\"email LIKE ?\", @booking.booked_user)\n else\n @user = User.where(\"email LIKE ?\", @booking.booked_user)\n if @user.nil? or @user.empty?\n flash[:notice] = \"User not found !\"\n render 'bookings/new' and return\n end\n end\n if @booking.starttime.past?\n flash[:notice] = \"You cannot book for the day before today !\"\n render 'bookings/new' and return\n end\n if (@booking.starttime-7.days).future?\n flash[:notice] = \"You cannot book for a day i.e 7 days after today !\"\n render 'bookings/new' and return\n end\n @current_bookings = Booking.where(\"roomno = ? and ? <= endtime and starttime <= ? \", @booking.roomno,\n @booking.starttime, @booking.endtime)\n if not @current_bookings.nil? and not @current_bookings.empty?\n puts @current_bookings.first.starttime\n puts @current_bookings.first.roomno\n flash[:notice] = \"This room is not available at this time. There is another booking which starts at #{@current_bookings.first.starttime} \"\n render 'bookings/new' and return\n end\n if @booking.starttime > @booking.endtime\n flash[:notice] = \"Booking start time can't be greater than end time\"\n render 'bookings/new' and return\n end\n\n if @booking.starttime + 2.hours < @booking.endtime\n flash[:notice] = \"Booking can be made only for 2 hours at a time\"\n render 'bookings/new' and return\n end\n @booking.room_id = @room.first.id\n @booking.user_id = @user.first.id\n flash[:notice] = \"#{@booking.user_id}\"\n @newroom = Room.find(@booking.room_id)\n BookingMailer.booking_email(@booking.starttime,@booking.endtime,@booking.booked_user,@booking.roomno,@newroom.building).deliver_now!\n emails=params[:emails]\n values=emails.split(\",\")\n values.each do |value|\n BookingMailer.booking_email(@booking.starttime,@booking.endtime,value,@booking.roomno,@newroom.building).deliver_now!\n end\n respond_to do |format|\n\n if @booking.save\n format.html { redirect_to @booking, notice: 'Booking was successfully created.' }\n format.json { render :show, status: :created, location: @booking }\n else\n format.html { render :new }\n format.json { render json: @booking.errors, status: :unprocessable_entity }\n end\n end\n\n end",
"def create\n @reservation = Reservation.new(reservation_params)\n @room = Room.where(\"room_number LIKE ?\", @reservation.room_number)\n if session[:role] != \"admin\"\n @member = Member.where(\"email LIKE ?\", session[:email])\n else\n @member = Member.where(\"email LIKE ?\", params[:members_email])\n if @member.nil? or @member.empty?\n flash[:notice] = \"Member not found !\"\n render 'reservations/newreservation' and return\n end\n end\n @current_reservations = Reservation.where(\"room_number LIKE ? and ? <= end_time and start_time <= ? \", @reservation.room_number,\n @reservation.start_time, @reservation.end_time)\n if not @current_reservations.nil? and not @current_reservations.empty?\n flash[:notice] = \"This room is not available at this time. Conflicts with other reservation which starts at #{@current_reservations.first.start_time} \"\n render 'reservations/newreservation' and return\n end\n\n\n if @reservation.start_time > @reservation.end_time\n flash[:notice] = \"ERROR: Booking start time can't be greater than end time\"\n render 'reservations/newreservation' and return\n end\n\n if @reservation.start_time + 2.hours < @reservation.end_time\n flash[:notice] = \"ERROR : Reservation can be made only for 2 hours at a time\"\n render 'reservations/newreservation' and return\n end\n\n if Time.now + 7.days < @reservation.start_time\n flash[:notice] = \"ERROR : Reservation can be made only 1 week in advance from today\"\n render 'reservations/newreservation' and return\n end\n\n if @reservation.start_time == @reservation.end_time\n flash[:notice] = \"ERROR: Please book the room for atleast 1 minute!\"\n render 'reservations/newreservation' and return\n end\n\n if @reservation.start_time > @reservation.end_time\n flash[:notice] = \"ERROR: Booking start time can't be greater than end time\"\n render 'reservations/newreservation' and return\n end\n\n if Time.now - 5.minutes >= @reservation.start_time\n flash[:notice] = \"ERROR: Booking start time should not be less than current time\"\n render 'reservations/newreservation' and return\n end\n\n #User can only reserve one room at a perticular date and time without extra permission from admin\n @user_reservations = Reservation.where(\"members_id = ? and ? <= end_time and start_time <= ? \", @member.first.id,\n @reservation.start_time, @reservation.end_time)\n if not @user_reservations.empty? and @member.first.isMultipleReservationAllowed != \"Yes\"\n flash[:notice] = \"ERROR : You already have reservation from #{@reservation.start_time} to #{@reservation.end_time} .\n You can't book room during this time interval. Contact Administrator if you want to book multiple rooms with\n overlapping time intervals\"\n render 'reservations/newreservation' and return\n end\n\n @reservation.room_id = @room.first.id\n @reservation.status = \"Booked\"\n @member.first.reservations << @reservation\n SendEmail.reservation_email(@member.first, @reservation).deliver\n\n\n respond_to do |format|\n if @member.first.save\n @member.first.reservations.each do |res|\n end\n\n format.html { redirect_to @reservation, notice: 'Reservation was successfully created.' and return }\n format.json { render :show, status: :created, location: @reservation }\n else\n format.html { render :new }\n format.json { render json: @reservation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n flag=0\n @@bookinfomail = Booking.new(booking_params)\n @booking = Booking.new(booking_params)\n @user=User.find(session[:user_id])\n if not @user.Admin\n # debugger\n @booking.name = User.find(session[:user_id]).email\n flag=1\n end\n #name is in fact the email of the person who books the room (By Lei Zhang)\n @booking.bookday=Time.new\n #<begin> edit by Lei Zhang\n starttime_string = booking_params[:starttime]\n if starttime_string.length == 4\n starttime_string = \"0\" + starttime_string\n end\n endtime_string = booking_params[:endtime]\n if endtime_string.length == 4\n endtime_string = \"0\" + endtime_string\n end\n \n @booking.endtime = Time.parse(\"%04d-%02d-%02d %s:00\" %[booking_params[\"date(1i)\"], booking_params[\"date(2i)\"], booking_params[\"date(3i)\"], endtime_string])\n @booking.starttime = Time.parse(\"%04d-%02d-%02d %s:00\" %[booking_params[\"date(1i)\"], booking_params[\"date(2i)\"], booking_params[\"date(3i)\"], starttime_string])\n #debugger\n #<end> edited by Lei Zhang\n #--------------\n @bookingrecord=Booking.where(\"room_id= ? and date = ?\",booking_params[:room_id],@booking.date)\n @record=Booking.where(\"name=? and date = ?\", @booking.name,@booking.date)\n #-------------\n #<begin> edited by Lei Zhang\n #debugger\n duration = @booking.endtime - @booking.starttime\n if ((duration/1800 > 4) || (duration<=0))\n flash[:danger] = \"Cannot book for more that 2 hours or less than 0 hours\"\n redirect_to bookings_path\n elsif not (timeconstrain(@bookingrecord,@booking))\n flash[:danger] = \"The room is booked during that period. Try another room or another time\"\n redirect_to bookings_path\n elsif (@booking.starttime <= Time.new) ||((Time.parse(@booking.date.strftime('%Y-%m-%d'))-Time.parse(Time.new.strftime('%Y-%m-%d'))).round/(3600*24)>7)\n flash[:danger] = \"The time period is not correct\"\n redirect_to bookings_path\n elsif (flag==1)&&( not (bookroom_constrain(@record,@booking.starttime,@booking.endtime)))\n flash[:danger] = \"A library member can reserve only one room at a particular date and time\"\n redirect_to bookings_path\n else\n # respond_to do |format|\n # if @booking.save\n # format.html { redirect_to @booking, notice: 'Booking was successfully created.' }\n # format.json { render :show, status: :created, location: @booking }\n # else\n # format.html { render :new }\n # format.json { render json: @booking.errors, status: :unprocessable_entity }\n # end\n # end\n if @booking.save\n #debugger\n flash[:success] = \"Room successfully booked\"\n # redirect_to bookings_path\n # redirect_to bookings_path\n redirect_to send_mail_path\n else\n flash[:danger] = \"Cannot book room now. Please try again later\"\n redirect_to bookings_path\n end\n end\n end",
"def tutor_double_booked\n lesson_start = self.start_time\n lesson_end = self.end_time\n overlap = tutor.appointments.any? do |appointment|\n check_start = appointment.start_time\n check_end = appointment.end_time\n check_start < lesson_end && lesson_end < check_end || check_start < lesson_start && lesson_start < check_end\n end\n if overlap\n errors.add(:tutor, 'there is a conflictiong appointment')\n end\n end",
"def has_appointment?(date, time)\n datetime = Temporal.generate_datetime(date, time)\n\n !is_available?(datetime, 20) #the time is broken up into 20 minute blocks\n end",
"def index\n # @bookings = Booking.all\n @booking = Booking.new\n @room = Room.new\n @rooms = Room.all\n @selected_date = DateTime.now\n @bookings = Booking.where(:start_time => @selected_date.beginning_of_day..@selected_date.end_of_day)\n @timeNow = Time.now\n @startTime = @timeNow.beginning_of_day() + (8*60*60)\n @endTime = @timeNow.beginning_of_day() + (18*60*60)\n\n end",
"def find_day_reservations(date)\n day_reservations = all_reservations.select do |number, reservation|\n start_date = reservation.check_in\n end_date = reservation.check_out\n (start_date...end_date).include?(Date.parse(date)) && reservation.status == :CONFIRMED\n end\n \n return day_reservations\n end",
"def get_available_space_sunday(bookings_by_day)\n @bookings = bookings_by_day\n return_hash = Hash.new\n hash_of_times=[[12,00],[12,30],[13,00],[13,30],[14,00],[14,30],[15,00]]\n hash_of_times.each do |time|\n booking = @bookings.first.booking_date_time.change({ hour: time.first, min: time.second })\n \n if get_total_diners_for_current_time(booking) < max_diners_at_current_time(@bookings.first[:restaurant_id])\n return_hash[booking.strftime(\"%H:%M\")]= (max_diners_at_current_time(@bookings.first[:restaurant_id])- (get_total_diners_for_current_time(booking)))\n else\n end \n end\n return return_hash\n end",
"def isBusy(meeting_start, meeting_end, start_time, end_time)\n if start_time > meeting_start && end_time < meeting_end\n return true\n end \n return false\nend",
"def can_work( day, times )\n @avail[day] = parse_times(times)\n\n @prefers[day] = if times =~ /\\((?:prefers )?([^)]+)\\s*\\)/\n parse_times($1)\n else\n Hour.new(\"12 AM\")..Hour.new(\"11 PM\")\n end\n end",
"def time_greetings\n if 5 <= Time.now.hour && Time.now.hour <= 12 \n puts \"good morning!\"\nelsif 12 <= Time.now.hour && Time.now.hour <= 18 \n puts \"good afternoon!\"\nelsif 18 <= Time.now.hour && Time.now.hour <= 20 \n puts \"good evening!\"\nelsif 20 <= Time.now.hour || Time.now.hour <= 5\n puts \"salutations comrade!\"\n end\nend",
"def confirm_date(start_date, end_date)\n confirm = 0\n for booking in @bookings\n if start_date >= booking[0] && start_date < booking[1]\n confirm += 1\n elsif end_date > booking[0] && end_date <= booking[1]\n confirm += 1\n elsif start_date <= booking[0] && end_date >= booking[1]\n confirm += 1\n end\n end\n return confirm\n # if confirmation is 1 then there is a clash. 0 if not.\n end",
"def invalid_dates\n self.listing.reservations.each do |reservation|\n existing_reservations = reservation.checkin..reservation.checkout \n if existing_reservations.include?(self.checkin) || existing_reservations.include?(self.checkout)\n errors.add(:checkin_taken, \"The date is already taken\")\n end\n end \n end",
"def is_available\n return unless start_time.present? && end_time.present?\n\n reservation_hours = (end_time - start_time) / 1.hour\n day = start_time.wday\n st = start_time\n et = reservation_hours > 24 ? end_time.end_of_day : end_time\n while reservation_hours > 0 do\n unless available_at(st, et, day)\n errors.add(:start_time, I18n.t('activerecord.errors.models.reservation.attributes.date.available_hours'))\n return\n end\n if overnight?\n st = start_time.beginning_of_day\n end\n et = reservation_hours > 24 ? end_time.end_of_day : end_time\n day = (day + 1) % 7\n reservation_hours -= 24\n end\n end",
"def get_lunch_bookings_over_four(one_day_of_bookings)\n @bookings = one_day_of_bookings\n return_string = \"-\"\n find_values = [5,6,7,8,9,10,11,12]\n time_compare = @bookings.first.booking_date_time.change({ hour: 16, min: 55 })\n \n @bookings.each do |booking|\n unless booking.booking_date_time > time_compare\n if find_values.include?(booking.number_of_diners)\n return_string = return_string+booking.number_of_diners.to_s+\"-\"\n end\n end\n end\n return return_string\n end",
"def create\n @meeting = Meeting.new(meeting_params)\n\n new_start_date = @meeting.start_date.to_date\n new_end_time = @meeting.end_time.to_date\n # p \"new_start_date = #{new_start_date}\"\n # p \"new_end_time = #{new_end_time}\"\n\n flag = false\n @meetings = Meeting.all\n @meetings.each do |meeting|\n # p \"meetings : #{meeting.id}\"\n\n startdate = (meeting.start_date).to_date\n enddate = (meeting.end_time).to_date\n # p \"startdate = #{startdate}\"\n # p \"enddate = #{enddate}\"\n range_date = (startdate..enddate).to_a\n\n unless range_date.include?(\"#{new_start_date}\") || range_date.include?(\"#{new_end_time}\")\n p \"YES - #{new_start_date}\"\n flag = true\n end\n\n\n # p \"range_date = #{range_date}\"\n # range_date.each do |day|\n # day_date = day.to_date\n # p \"day : #{day.to_date}\"\n #\n # range_date2.each do |day2|\n # day_date2 = day2.to_date\n # p \"day2 : #{day2.to_date}\"\n # if day_date2 == day_date\n # p \"Período de data já cadastrada\"\n # flag = true\n # end\n # end\n #\n # end\n\n\n end\n\n if flag\n respond_to do |format|\n format.js\n end\n # redirect_to request.referrer\n else\n respond_to do |format|\n if @meeting.save\n format.html { redirect_to @meeting, notice: 'Meeting was successfully created.' }\n format.json { render :show, status: :created, location: @meeting }\n else\n format.html { render :new }\n format.json { render json: @meeting.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def exclusive_schedule\n if Schedule.where('init >= ? AND init <= ?', init, finish).any?\n errors.add(:base, \"Já existe uma reserva para esse horário\")\n end\n end",
"def sleep_in? (weekday, vacation)\n\tif vacation \n\t\treturn true\n\tend\n\n\tif weekday \n\t\treturn false\n\tend\n\n\tif !weekday\n\t\treturn true\n\tend\n\n\nend",
"def check_if_consistent_times(starting_hour, default_time_hour, ending_hour)\n\t\t(starting_hour <= default_time_hour) && (default_time_hour <= ending_hour)\n\tend",
"def all_actual_meetings\n # Exceptions are positive (Tue/Thu class meeting on Wed)\n # or negative (Tue/Thu class doesn't meet on Tue)\n positive_exceptions = exceptions_as_dates - all_potential_meetings\n all_potential_meetings - exceptions_as_dates + positive_exceptions\n end",
"def book_once_aday\n errors.add(:user, 'Guest can book only once a day') if booked_in_same_day?\n end",
"def vacant_slots(from, to)\n\n end",
"def get_available_space_sunday_adjusted(bookings_by_day)\n @bookings = bookings_by_day\n return_hash = Hash.new\n hash_of_times=[[12,00],[12,30],[13,00],[13,30],[14,00],[14,30],[15,00]]\n hash_of_times.each do |time|\n booking = @bookings.first.booking_date_time.change({ hour: time.first, min: time.second })\n current_big_tables = get_bookings_over_seven_array(@bookings)\n \n if get_total_diners_for_current_time(booking) < max_diners_at_current_time(@bookings.first[:restaurant_id])\n unless ((max_diners_at_current_time(@bookings.first[:restaurant_id])-2)- (get_total_diners_for_current_time(booking)))<= 0\n \n return_hash[booking.strftime(\"%H:%M\")]= (((max_diners_at_current_time(@bookings.first[:restaurant_id]))- (get_total_diners_for_current_time(booking)))-2)\n end\n else\n end \n end\n return return_hash\n end",
"def refresh_trip_schedules!\n excluded_dates = exclusion_dates.order(:excluded_date).map(&:excluded_date)\n\n # Try to build a list of valid trip schedules between the two trip\n # boundries\n updated_trip_schedules = [] \n working_date = boundry_start\n while working_date + duration.days < boundry_end do\n potential_start = working_date.to_date\n potential_end = (working_date + duration.days).to_date\n potential_range = (potential_start..potential_end)\n\n # tick the working date\n working_date = working_date + 1.day\n\n # Check trip day of week exclusions\n # next unless potential_range.any? { |date| dow_restriction_indexes.any? { |exclusion| exclusion.include? date.wday }}\n next unless dow_restriction_indexes.any? { |required_dows| required_dows.all? { |required_dow| potential_range.any? { |date| required_dow == date.wday }}}\n\n # Check excluded dates\n next if excluded_dates.any? { |excluded_date| (potential_range).include? excluded_date.to_date }\n\n # Create a trip schedule if it doesn't already exist\n ap potential_start\n updated_trip_schedules << TripSchedule.where(\n :trip => self,\n :start_date => potential_start.in_time_zone('EST'),\n :end_date => potential_end.in_time_zone('EST')\n ).first_or_initialize\n end\n\n self.trip_schedules = updated_trip_schedules\n save!\n end",
"def send_today?\n day_today = (Date.today - @config['start_date']).round\n (day_today % 28) < 21\nend",
"def valid_appointments(base_time)\n transform_blocks_to_appointments(valid_blocks(base_time))\n end",
"def bookable?(date)\n date < booking_date_limit\n end",
"def hours\n\n today = Date.today\n hours = {}\n #if @traveler.is_visitor? or @traveler.is_api_guest? #Return a wide range of hours\n if not @traveler or not @traveler.registered?\n (0..30).each do |n|\n hours[(today + n).to_s] = {open: \"07:00\", close: \"22:00\"}\n end\n\n else # This is not a guest, check to see if the traveler is registered with a service\n\n # NOTE(wilsonj806) For now this implementation does not let registered users\n #...book trips on weekends. Eventually we want to change that so they can do so\n\n if @traveler.booking_profiles.count > 0 #This user is registered with a service\n booking_profile = @traveler.booking_profiles.first\n service = booking_profile.service\n\n min_notice_days = (service.booking_details[:min_days] || 2).to_i\n max_notice_days = (service.booking_details[:max_days] || 14).to_i\n\n \n if service.booking_details[:trusted_users] and booking_profile.external_user_id.in? service.booking_details.try(:[], :trusted_users).split(',').map{ |x| x.strip }\n (1..21).each do |n|\n hours[(today + n).to_s] = {open: \"00:00\", close: \"23:59\"}\n end\n elsif service.schedules.count > 0 #This user's service has listed hours. This is the most common case.\n \n #Find out if we are past the cutoff for today. If so, start counting from tomorrow\n if service.booking_details[:cutoff_time] and (Time.now.in_time_zone.seconds_since_midnight > service.booking_details[:cutoff_time].to_i)\n day = Time.now + 1.days \n else\n day = Time.now\n end\n \n biz_days_count = 0\n (0..max_notice_days).each do |n|\n if service.open_on_day? day\n if biz_days_count >= min_notice_days\n schedule = service.schedules.where(day: day.wday).first\n if schedule\n hours[day.strftime('%Y-%m-%d')] = {open: schedule.schedule_time_to_military_string(schedule.start_time), \n close: schedule.schedule_time_to_military_string(schedule.end_time)}\n end\n end\n biz_days_count += 1\n end\n day = day + 1.days \n end\n\n else #This user is registered with a service, but that service has not entered any hours\n\n (min_notice_days..max_notice_days).each do |n|\n unless (today + n).saturday? or (today + n).sunday?\n hours[(today + n).to_s] = {open: \"08:00\", close: \"17:00\"}\n end\n end\n\n end\n\n else #This user is logged in but isn't registered with a service\n\n (1..14).each do |n|\n unless (today + n).saturday? or (today + n).sunday?\n hours[(today + n).to_s] = {open: \"08:00\", close: \"17:00\"}\n end\n end\n\n end # if #traveler.user_profile.user_services.count > 0\n end # if @travler.is_visitor\n\n render status: 200, json: hours\n\n end",
"def crossed_day_change_boundary?(start_time, end_time)\n start_time.hour < 4 && end_time.hour >= 4\n end",
"def create\n require 'active_support/core_ext'\n @reservation = Reservation.new(reservation_params)\n #Same date constraints\n if @reservation.date!=@reservation.start_time.to_date\n redirect_to rooms_path, notice:'Dates should match' and return\n end\n #duration constraint=>automatically assigned\n if params[:duration].to_i==0\n @reservation.end_time=@reservation.start_time+60.minutes\n else \n @reservation.end_time=@reservation.start_time+params[:duration].to_i.minutes\n end\n #Date Constraints\n if (@reservation.date < Date.current() || @reservation.date - Date.current() >7)\n redirect_to rooms_path, notice:'Failed due to date constraints' and return\n end\n #Time Constraints\n if (@reservation.start_time<Time.now)\n redirect_to rooms_path, notice: 'Failed due to time constraints' and return\n end\n #Member Overlap\n @reservations = Reservation.where(\"member_id=? AND date=? AND (start_time, end_time) overlaps (?,?)\", @reservation.member_id, @reservation.date, @reservation.start_time, @reservation.end_time)\n if !(is_admin?)\n if !(@reservations.empty?)\n redirect_to rooms_path, notice: 'Failed due to member constraint' and return\n end\n end\n #Room Overlap\n @reservations = Reservation.where(\"room_id=? AND date=? AND (start_time, end_time) overlaps (?,?)\", @reservation.room_id, @reservation.date, @reservation.start_time, @reservation.end_time)\n if !(@reservations.empty?)\n redirect_to rooms_path, notice: 'Failed due to room overlap' and return\n end\n respond_to do |format|\n if @reservation.save\n if !params[:emails].blank?\n temp_emails = params[:emails] #.split(',').strip(' ')\n UserMailer.invite_email(temp_emails, @reservation).deliver\n end\n format.html { redirect_to @reservation, notice: @reservation.end_time}\n format.json { render :show, status: :created, location: @reservation }\n else\n format.html { redirect_to rooms_url }\n format.json { render json: @reservation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def time_collision_validation\n\t\tappointments = Appointment.all\n\n\t\t#if duration is equals to 0, it means it is fixed pay. \n\t\t#Here, duration is set to 0 so it will not be validated \n\t\t#This will execute if is_pay_per hour is set to 0\n\t\tif @start_date.present? && @start_time.present? && duration == 0.to_s\n\t\t\tstart_at = Time.parse(\"#{@start_date} #{@start_time}\") + (1.hours)\n\t\t\t\n\t\t\tappointments.each do |a|\n\t\t\t\t# will ensure that the appointment to compare will not be compared to itself in the database if it exists\n\t\t\t\tif a.id.to_s != @appointment_id.to_s\n\t\t\t\t\t# compare fixed-pay input to pay per hour appointment\n\t\t\t\t\tif a.task.is_pay_per_hour && start_at < a.end_at && start_at >= a.start_at \n\t\t\t\t\t\terrors.add(:start_time, \"Please select a different date or time.\")\n\t\t\t\t\t\terrors.add(:start_date, \"An appointment is already \n\t\t\t\t\t\t\tset at #{a.start_at.strftime(\"%I:%M%p\")}, #{a.start_at.strftime(\"%d/%m/%Y\")} \n\t\t\t\t\t\t\tto #{a.end_at.strftime(\"%I:%M%p\")} on #{a.end_at.strftime(\"%d/%m/%Y\")}. \n\t\t\t\t\t\t\tPlease select a different date or time.\")\n\t\t\t\t\t\tbreak\n\n\n\t\t\t\t\t\t#compare fixed-pay input to fixed pay appointment\n\t\t\t\t\telsif !a.task.is_pay_per_hour && start_at == a.start_at \n\t\t\t\t\t\terrors.add(:start_time, \"Please select a different date or time.\")\n\t\t\t\t\t\terrors.add(:start_date, \"A fixed pay appointment is aleady set at #{a.start_at.strftime(\"%I:%M%p\")}\n\t\t\t\t\t\t\t, #{a.start_at.strftime(\"%d/%m/%Y\")}. \n\t\t\t\t\t\t\tPlease select a different date or time.\")\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend \t\n\t\t\t\tend \t\n\t\t\tend\n\n\n\t\t\t\t#Here, duration should be present and will be always validated\n\t\t\t\t#This will execute if is_pay_per hour is set to 1\n\t\t\telsif @start_date.present? && @start_time.present? && duration.present?\n\t\t\t\tstart_at = Time.parse(\"#{@start_date} #{@start_time}\") + (1.hours)\n\t\t\t\tend_at = Time.parse(\"#{@start_date} #{@start_time}\") + (@duration.to_f.hours+ (1.hours))\n\n\t\t\t\tappointments.each do |a|\n\t\t\t\t\t# will ensure that the appointment to compare will not be compared to itself in the database if it exists\n\t\t\t\t\tif a.id.to_s != @appointment_id.to_s\n\t\t\t\t\t\t# compare pay per hour input to pay per hour appointment\n\t\t\t\t\t\tif a.task.is_pay_per_hour && start_at < a.end_at && a.start_at < end_at \n\n\t\t\t\t\t\t\terrors.add(:start_time, \"Please select a different date or time.\")\n\t\t\t\t\t\t\terrors.add(:start_date, \"An appointment already \n\t\t\t\t\t\t\t\texists at #{a.start_at.strftime(\"%I:%M%p\")}, #{a.start_at.strftime(\"%d/%m/%Y\")} \n\t\t\t\t\t\t\t\tto #{a.end_at.strftime(\"%I:%M%p\")} on #{a.end_at.strftime(\"%d/%m/%Y\")}. \n\t\t\t\t\t\t\t\tPlease select a different date or time.\")\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t#compare pay per hour input to fixed pay appointment\n\t\t\t\t\t\telsif !a.task.is_pay_per_hour && a.start_at <= end_at && a.start_at >= start_at\n\n\t\t\t\t\t\t\terrors.add(:start_time, \"Please select a different date or time.\")\n\t\t\t\t\t\t\terrors.add(:start_date, \"A fixed pay appointment is aleady set at #{a.start_at.strftime(\"%I:%M%p\")}\n\t\t\t\t\t\t\t\t, #{a.start_at.strftime(\"%d/%m/%Y\")}. \n\t\t\t\t\t\t\t\tPlease select a different date or time.\")\n\t\t\t\t\t\t\tbreak\t\t\t\t\n\t\t\t\t\t\tend\t\t\t\n\t\t\t\t\tend \n\t\t\t\tend\n\t\t\tend \n\t\tend",
"def week_day_conflict?(event)\n @start.wday == event.start.wday\n end",
"def booking_is_available?(user, service, order_time)\n order_time > Time.new + 6.hours and user.id != service.user_id\n end",
"def create_or_update_booking_dates\n if check_in_changed? || check_out_changed?\n # Delete all booking dates if check in or check out changed\n booking_dates.delete_all\n # Adding all the dates of the check_in and check_out range into the reserved dates\n (check_in..check_out).each do |reserved_date| \n # Createing booking dates with specified reserved_date\n booking_dates.create(reserved_date: reserved_date)\n end\n end\n end",
"def rr_for_same_day?\n # find date of reservation as comparable object\n reservation_day = @start_dt.strftime('%Y%m%d').to_i\n # or if they made a reservation for the selected day already\n @rr_for_same_day = Reservation.active_non_blocks.where(\"user_id = ? AND DATE_FORMAT(start_dt,'%Y%m%d') = ?\", @user.id, reservation_day)\n return false if @rr_for_same_day.blank? || @user.user_attributes[:room_reserve_admin]\n return true\n end",
"def are_reservable?\n reservable = true\n @restaurant.tables.find_each do |table|\n table.bookings.find_each do |booking|\n next unless @end_date.between?(booking.start_time, booking.end_time) ||\n @start_date.between?(booking.start_time, booking.end_time)\n reservable = false\n end\n end\n reservable\n end",
"def set_day_time_slot_for_non_selected\n if is_friday == true\n self.day2 = 0\n self.time_slot2 = 0\n elsif is_friday != true \n self.is_friday = false\n self.time_slot = 0\n end \n end",
"def timeslot_contains_reservations?\n return start_dt.blank? || end_dt.blank? || existing_reservations?\n end",
"def should_not_overlap\n if table.reservations.where(\"time_from <= ? AND time_to > ? AND NOT id = ?\", time_from, time_from, id).count > 0\n errors.add(:time_from, \"shouldn't overlap with existing reservation\")\n end\n if table.reservations.where(\"time_from < ? AND time_to >= ? AND NOT id = ?\", time_to, time_to, id).count > 0\n errors.add(:time_from, \"shouldn't overlap with existing reservation\")\n end\n if table.reservations.where(\"time_from >= ? AND time_to <= ? AND NOT id = ?\", time_from, time_to, id).count > 0\n errors.add(:time_from, \"shouldn't overlap with existing reservation\")\n end\n end",
"def free_time_frame?\n started_booking_time = Booking.where(start_time: start_time)\n\n if started_booking_time.present? && (started_booking_time.ids.first != id)\n errors.add(:start_time, 'Sorry, this hour is already booked')\n end\n end",
"def overlaps_with?(other_meeting) \n if day == other_meeting.day\n if (other_meeting.start_time < end_time) && (other_meeting.end_time > start_time)\n return true\n end\n end\n return false\n end",
"def should_consider_traveling_to?(other_game)\n # other_game.week - self.week <= 1\n other_game.must_arrive_no_later_than_in_seconds_since_epoch < self.next_game_threshold_in_seconds_since_epoch\n end",
"def create\n @booking = Booking.new(booking_params)\n Room.where(:room_type_id => @booking.room_type_id).each do |room| \n @booking.room = room \n if (Booking.overlapping(@booking)).size == 0\n respond_to do |format|\n if @booking.save\n format.html {\n redirect_to \"/bookings/#{@booking.id}/payment\", notice: 'Booking was successfully created.' \n return;\n }\n format.json { render :show, status: :created, location: @booking }\n else\n format.html { \n render :new \n return\n }\n format.json { render json: @booking.errors, status: :unprocessable_entity }\n end\n end\n end\n \n end\n\n end",
"def perfectDayChecker day\n\t\t\t# If all five prayers were performed\n\t\t\tif day[:fajr] == 2 && day[:zuhr] == 2 && day[:asr] == 2 && day[:maghrib] == 2 && day[:isha] == 2\n\t\t\t \ttrue \t# Return true\n\t\t\telse\n\t\t\t\tfalse\t# Return false\n\t\t\tend\n\t\tend",
"def is_available?(date, start_time)\n\t\tcase date.wday\n\t\t\twhen 1\n\t\t\t\tself.monday_available_from <= start_time && start_time <= self.monday_available_to\n\t\t\twhen 2\n\t\t\t\tself.tuesday_available_from <= start_time && start_time <= self.tuesday_available_to\n\t\t\twhen 3\n\t\t\t\tself.wednesday_available_from <= start_time && start_time <= self.wednesday_available_to\n\t\t\twhen 4\n\t\t\t\tself.thursday_available_from <= start_time && start_time <= self.thursday_available_to\n\t\t\twhen 5\n\t\t\t\tself.friday_available_from <= start_time && start_time <= self.friday_available_to\n\t\t\twhen 6\n\t\t\t\tself.saturday_available_from <= start_time && start_time <= self.saturday_available_to\n\t\t\twhen 7\n\t\t\t\tself.sunday_available_from <= start_time && start_time <= self.sunday_available_to\n\t\t\telse\n\t\t\t\tfalse\n\t\tend\n\tend",
"def is_booking_possible?(member, tour)\n return false unless tour.current_bookings.to_i < tour.max_capacity\n return false unless tour.difficulty <= member.ability\n return false if member.tours.include?(tour)\n return true\n end",
"def new_reservation(room, checkin_date, checkout_date)\n (checkin_date...checkout_date).each do |day|\n if !room.is_available?(day)\n raise ArgumentError.new(\"Room#{room.room_num} is not available\")\n end\n end\n reservation = BookingSystem::Reservation.new(room: room, checkin_date: checkin_date, checkout_date: checkout_date)\n add_reservation(reservation)\n room.add_reservation(reservation)\n end",
"def not_overlapping\n @meetingsRD = Meeting.where(\"day = ? and room = ?\", day, room)\n overlap = false\n @meetingsRD.each do |mtng|\n if (id != mtng.id)\n if ((finish <= mtng.start) || (start >= mtng.finish))\n overlap = false\n else\n overlap = true\n errors.add(:finish, 'Sorry! It overlaps ' + (mtng.subject).upcase + ' meeting')\n errors.add(:start, 'Sorry! It overlaps ' + (mtng.subject).upcase + ' meeting')\n break #if overlap, finish the loop\n end\n end\n end\n end",
"def schedule_days(day_ints = [1,3,5])\n (0..6).each {|day_int|\n is_checked = day_checked?(day_int)\n # puts \"is checked : #{is_checked}\"\n should_be_checked = day_ints.include?(day_int)\n # puts \"should_be_checked : #{should_be_checked}\"\n if (!is_checked && should_be_checked)\n click_day_picker(day_int)\n elsif (is_checked && !should_be_checked)\n click_day_picker(day_int)\n else\n\n end\n } \n current_scheduled_days\n end",
"def booked_room\n start_date = Date.parse(params[:start_date])\n end_date = Date.parse(params[:end_date])\n (start_date..end_date).each do |date|\n booked_room = BookingStatus.new(\n start_date: date,\n user_id: current_user.id,\n room_id: params[:room_id]\n )\n\n booked_room.save\n end\n end",
"def create\n check = 0\n @booking_history = BookingHistory.new(booking_history_params)\n # @booked_list = BookingHistory.all\n #@booked_entry = @booked_list.select do |bh|\n # bh.room_num == @booking_history.room_num && bh.date == Date.today + 7.days\n #end\n @room_details = LibraryRoom.find_by_number(@booking_history.room_num)\n @booking_history.building = @room_details.building\n @booking_history.size = @room_details.size\n @booked_entry = BookingHistory.where(\"room_num = ? AND date = ?\",@booking_history.room_num,@booking_history.date ).order(:start_t)\n\n @booked_entry.each do |entry|\n if entry != nil\n then\n\n if (((@booking_history.end_t <= entry.start_t)\\\n || (@booking_history.start_t >= entry.end_t))\\\n && ((@booking_history.start_t == @booking_history.end_t - 1) || (@booking_history.start_t == @booking_history.end_t - 2 )))\n then\n check = 0\n else\n check = 1\n end\n end\n end\n\n\n\n respond_to do |format|\n if check ==0\n if (@booking_history.save)\n flash[:notice] = \"Booking was successfully created. Booking id #{@booking_history.id}\"\n format.html { redirect_to booking_histories_path}\n # format.json { render :show, status: :created, location: @booking_history }\n else\n flash[:notice] = \"Booking was failed. Booking id #{@booking_history.id}\"\n format.html { redirect_to booking_histories_path }\n # format.json { render json: @booking_history.errors, status: :unprocessable_entity }\n end\n else\n if((@booking_history.start_t == @booking_history.end_t - 1) || (@booking_history.start_t == @booking_history.end_t - 2 ))\n flash[:notice] = \"Cannot book for more than 2 hours\"\n else\n flash[:notice] = \"Booking failed due to time conflict. Booking id #{@booking_history.id}\"\n end\n format.html { redirect_to booking_histories_path }\n end\n\n end\n end",
"def send_booking_reminder(user, booking)\n @user = user\n @booking = booking\n\n mail( :to => @user.email,\n :subject => \"You have an upcoming booking in 24 hours\" )\n end",
"def time_period_for_room_reservation\n time_period = (self.start_date.year * 12 + self.start_date.month) - (Date.today.year * 12 + Date.today.month)\n errors.add(:start_date, \"you can book your room before 6 months only\") if time_period > 6\n end",
"def available?(start_date, end_date)\n unless self.reservations.any? { |res| start_date.to_date.between?(res.checkin, res.checkout) || end_date.to_date.between?(res.checkin, res.checkout)} \n true\n end\n end",
"def check_overlap\n appointments = Appointment.all\n current_start = DateTime.strptime(self.start_time,\"%m/%d/%y %H:%M\").to_time\n current_end = DateTime.strptime(self.end_time,\"%m/%d/%y %H:%M\").to_time\n\n appointments.each do |appt|\n appt_start = DateTime.strptime(appt.start_time,\"%m/%d/%y %H:%M\").to_time\n appt_end = DateTime.strptime(appt.end_time,\"%m/%d/%y %H:%M\").to_time\n\n ## if the appointment being checked is a new appointment ##\n if @new_appt\n if current_start >= appt_start && current_start <= appt_end\n @valid = false\n elsif current_end >= appt_start && current_end <= appt_end\n @valid = false\n end\n\n ## if the appointment being checked is an old appointment being updated ##\n else\n if current_start > appt_start && current_start < appt_end\n @valid = false\n elsif current_end > appt_start && current_end < appt_end\n @valid = false\n end\n end\n\n end\n @valid\n p @valid\n end",
"def check_schedule()\n create_daily_tests()\n create_weekly_tests()\n end",
"def booking_range\n ary = [I18n.localize(begin_date, format: DATE_AND_TIME)]\n if same_day?(begin_date, end_date)\n ary << I18n.localize(end_date, format: '%R') # example: 09:00\n else\n ary << I18n.localize(end_date, format: DATE_AND_TIME)\n end\n ary.join ' - '\n end",
"def search_by_room_date(room, first_date, second_date)\n\t\t\traise ArgumentError, \"Room #{room} does not exist\" if @rooms.last.id < room\n\n\t\t\treservation_room_date = []\n\n\t\t\t@reservation_blocks.each do |reservation_block|\n\t\t\t\tfound_room = reservation_block.room_ids.include? room\n\t\t\t\tif reservation_block.check_reservation_range(first_date,second_date) && found_room\n\t\t\t\t\treservation_room_date << reservation_block\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\treturn reservation_found?(reservation_room_date, \"reservations\")\n\t\tend",
"def available?(meeting_start, meeting_end)\n # if for any meeting schedule for the room, start/end is between them, return false\n meetings.each do |meeting|\n return false if meeting_start.between?(meeting.meeting_start, meeting.meeting_end)\n return false if meeting_end.between?(meeting.meeting_start, meeting.meeting_end)\n end\n\n # if there are no schedule conflicts, return true\n true\n end",
"def check_conflict\n\n params[:id] = params[:id] ? params[:id] : 0\n flag = false\n arr_wd_sche_now = params[:a_day_check].each.map{|c| c.to_i}\n if params[:repeat_sche] == \"false\"\n start_date = format_date(params[:start_date])\n end_date = format_date(params[:end_date])\n @schedules = current_user.working_schedules.where(\"(:start_date BETWEEN start_date AND end_date) AND (:end_date BETWEEN start_date AND end_date) AND active = TRUE\",start_date: start_date, end_date: end_date).where.not(id: params[:id])\n @schedules.each do |sc|\n arr_wd_sches = sc.working_days.select(\"day_of_week\").where(open: true).map{ |w| w.day_of_week}\n arr_wd_sches.each do |c|\n if arr_wd_sche_now.include? c\n flag = true\n end\n end\n end\n render json: flag\n else\n start_date = format_date(params[:start_date])\n @schedules = current_user.working_schedules.where(\"(end_date >= :today) AND active = TRUE\",today: Date.today).where.not(id: params[:id])\n @schedules.each do |sc|\n arr_wd_sches = sc.working_days.select(\"day_of_week\").where(open: true).map{ |w| w.day_of_week}\n arr_wd_sches.each do |c|\n if arr_wd_sche_now.include? c\n flag = true\n end\n end\n end\n render json: flag\n end\n end",
"def schedulable?(start_date, end_date)\n !scheduled?(start_date - lead_days, end_date)\n end",
"def schedulable?(start_date, end_date)\n !scheduled?(start_date - lead_days, end_date)\n end",
"def schedulable?(start_date, end_date)\n !scheduled?(start_date - lead_days, end_date)\n end"
] |
[
"0.6871077",
"0.66731143",
"0.6518779",
"0.6506147",
"0.6464772",
"0.6320888",
"0.6309181",
"0.62830985",
"0.62649715",
"0.6259603",
"0.6251623",
"0.6242036",
"0.6233639",
"0.62059397",
"0.6191687",
"0.61739093",
"0.6173694",
"0.6172085",
"0.614515",
"0.61417675",
"0.61385643",
"0.6133634",
"0.6129783",
"0.61263585",
"0.61013126",
"0.6099772",
"0.6098815",
"0.6069404",
"0.6062438",
"0.60443",
"0.60334456",
"0.6030248",
"0.602762",
"0.60181653",
"0.60012245",
"0.59891975",
"0.5962323",
"0.5948168",
"0.59397423",
"0.5931594",
"0.5930495",
"0.59271634",
"0.5922014",
"0.5917837",
"0.59158146",
"0.59089833",
"0.58988774",
"0.588615",
"0.588148",
"0.5855576",
"0.5850869",
"0.58316416",
"0.5829801",
"0.5807543",
"0.58031917",
"0.57862276",
"0.57857496",
"0.5778248",
"0.57739973",
"0.5773469",
"0.5766872",
"0.5764572",
"0.57584655",
"0.57484204",
"0.5735793",
"0.5734118",
"0.5733876",
"0.57292604",
"0.5723561",
"0.5723461",
"0.5713388",
"0.5713022",
"0.5712711",
"0.5683529",
"0.56760657",
"0.56735325",
"0.56707895",
"0.56634897",
"0.56538177",
"0.5652722",
"0.5651795",
"0.5649651",
"0.56453085",
"0.562697",
"0.56249416",
"0.5622822",
"0.5604566",
"0.56022865",
"0.5600841",
"0.5599997",
"0.5593149",
"0.5581019",
"0.5574334",
"0.55729806",
"0.55686116",
"0.5543016",
"0.5531832",
"0.55302775",
"0.55290526",
"0.55290526",
"0.55290526"
] |
0.0
|
-1
|
Restriction to book only upto 6 months. User can do checkin within 6 months. Checkout is not restricted.
|
def checkin_before_6_months
return if dates_blank
if checkin_at >= (Date.today + 6.months)
self.errors.add(:checkin_at, ': Should be less than or equal to 6 months')
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def time_period_for_room_reservation\n time_period = (self.start_date.year * 12 + self.start_date.month) - (Date.today.year * 12 + Date.today.month)\n errors.add(:start_date, \"you can book your room before 6 months only\") if time_period > 6\n end",
"def bookable?(date)\n date < booking_date_limit\n end",
"def checkout(user, book)\n if user.can_rent_books? && book.status = \"available\"\n book.status = \"checked out\"\n book.due_date = Time.now + (7*24*60*60)\n user.checkout_book(book)\n else\n puts \"Sorry, that book can't be checked out.\"\n end\n end",
"def months_between(checkin, checkout)\n start = checkin.year * 100 + checkin.month\n finish = checkout.year * 100 + checkout.month\n table.where{year * 100 + month >= start}\n .where{year * 100 + month <= finish}\n end",
"def checkin_not_before_checkout\n if checkin && checkout\n if checkin >= checkout\n errors.add(:checkout, \"Re-evaluate your dates please\")\n end\n end\n end",
"def get_eligible\n #older than 1 day, not older than X date (whenever they get these cards).\nend",
"def book_count_within_limit\n if self.student.book_transactions.where(:return_date => nil).count >= 3\n errors.add(:base, \"Student can borrow maximum 3 book at a time\")\n end\n end",
"def must_pay_to_avoid_cancellation\n\t\tif @event.start_date < (Time.now + 1.week) && @event.paid == false \n\t\t\t#cannot book event\n\t\tend\n\tend",
"def expiration_month\n @months = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n end",
"def referrals_needed_per_month\n 5 * monthly_transaction_goal\n end",
"def booking_is_available?(user, service, order_time)\n order_time > Time.new + 6.hours and user.id != service.user_id\n end",
"def new?\n available_on + 1.month >= Time.zone.today ? true : false\n rescue\n false\n end",
"def check_buyer_frequency\n month_ago = (self.day_of_month - 1.month)\n frequency = Appointment\n .where(['day_of_month > ? AND day_of_month <= ?', month_ago, self.day_of_month])\n .where(:buyer => self.buyer).count\n\n errors.add(:buyer, \"#{:buyer} has paid to many times this month\") unless frequency < 3\n\n end",
"def paid_thru_now\n # Turn off March 1 of year following paid year\n paid_thru_year >= (Date.today - 59).year\n end",
"def make_premium(month_number)\n self.premium_expiry_date = Time.now + month_number.to_i.months\n self.save\n end",
"def has_bookings_at_period(checkin_date, checkout_date)\n # convert to date if string\n checkin_date = Date.parse(checkin_date) if checkin_date.is_a? String\n checkout_date = Date.parse(checkout_date) if checkout_date.is_a? String\n # if no consistency in period\n return true if checkout_date < checkout_date\n # prevent charging dataset for more than 100 days long\n return true if (checkout_date-checkin_date) >= 100\n # raise error ?\n self.bookings.each do |booking|\n (booking.checkin..booking.checkout).each do |d|\n # booking for this outfit at these dates\n return true if (checkin_date..checkout_date).include? d\n end\n end\n # no booking at this date\n return false\n end",
"def dmail_inactive_approvers!\n days_until_next_month = (Date.current.next_month.beginning_of_month - Date.current).to_i\n return unless days_until_next_month <= 21\n\n inactive_approvers.each do |user|\n Dmail.create_automated(to: user, title: \"You will lose approval privileges soon\", body: <<~BODY)\n You've approved fewer than #{MINIMUM_APPROVALS} posts in the past\n #{APPROVAL_PERIOD.inspect}. You will lose your approval privileges in\n #{days_until_next_month} #{\"day\".pluralize(days_until_next_month)}\n unless you have approved at least #{MINIMUM_APPROVALS} posts by the end\n of the month.\n BODY\n end\n end",
"def borrow\n if self.lent_out? == true\n# self. is a class method\n return false\n else\n self.due_date = Book.current_due_date\n @@on_shelf.delete(self)\n# Deletes due date since book is returned\n @@on_loan << self\n# This adds the book back to the shelf if it reaches the due date\n return true\n end\n end",
"def check_for_buyout\n if self.is_bought_out\n if self.bought_out_by_team_id\n self.subcontracts.future_years.each do |sub|\n sub.salary_amount *= 0.6\n sub.this_is_a_buyout = true\n sub.save!\n\n # update GM's annual actions to not allow more buyouts\n actions = AnnualGmAction.find_by_team_id_and_year(self.bought_out_by_team_id, current_year)\n actions.has_bought_out = true\n actions.bought_out_player_id = self.player.id\n actions.save!\n end\n end\n end\n end",
"def borrow\n # This instance method is how a book is taken out of the library. Otherwise, use current_due_date to set the due_date of the book and move it from the collection of available books to the collection of books on loan, then return true.\n # This method should use lent_out? to check if the book is already on loan,\n if self.lent_out? == false\n @@due_date = Book.current_due_date\n @@on_shelf.delete(self)\n @@on_loan << self\n return true\n else\n return false\n end\n\n end",
"def expires_on\n self.expires_on = Date.strptime(expiration_date,'%m/%Y')+1.month\n end",
"def invoiceable?\n has_user_id = self.user.present?\n grace_date = self.created_at.to_date + GRACE_PERIOD\n\n self.employee? && has_user_id && grace_date < Date.today\n end",
"def invoiceable?\n has_user_id = self.user.present?\n grace_date = self.created_at.to_date + GRACE_PERIOD\n\n self.employee? && has_user_id && grace_date < Date.today\n end",
"def check_out(book,user)\n\t\tif user.book_count > 2\n\t\t\tputs \"Sorry! You can't check out any more books.\"\n\t\telsif user.checked_out_books.any? { |book| book.overdue? == true}\n\t\t\tputs \"Sorry! You have an overdue book.\"\n\t\telsif book.status == \"available\" \n\t\t\tbook.due_date = Time.now + (7*24*3600)\n user.checked_out_books << book\n\t\t\tuser.borrow(book)\n book.status = \"checked out\"\n\t\t\tputs \"You have checked out #{book.title}.\"\n\t\telse \n\t\t\tputs \"#{book.title} is checked out. Please check back soon.\"\n\t\tend\n\tend",
"def test_ID_25840_edit_profile_resident_since_02\n login_as_user1\n go_to_edit_profile_page\n verify_month_can_only_be_selected_from_Jan_to_Dec \"test_ID_25835_edit_profile_desc\", 1, 12\n end",
"def available\n self.listing.reservations.each do |r|\n if self.checkin.nil? || !(r.checkin && r.checkin < self.checkin)\n errors.add(:checkin, \"checkin and checkout unavailable\")\n # elsif (r.checkin && r.checkin < self.checkin) == false\n # errors.add(:checkin, \"checkin and checkout unavailable\")\n end\n end\n end",
"def destroy_booking?\n if user_signed_in? && current_user.bookings.last != nil\n current_user.bookings.where(paid: false).destroy_all if (Time.now - current_user.bookings.last.created_at ) / 60 >= 5\n end\n end",
"def check_release_datetime\n\t\tif self.release_datetime > Date.today + 3.months\n\t\t\tself.errors.add(:release_datetime, \"Cannot be greater than 3 months\")\n\t\tend\t\n\tend",
"def calculate_dates\n self.inactive_date = Time.now + 2.months\n self.delete_date = Time.now + 4.months\n end",
"def fined \n @item = Item.find(params[:id])\n # finding all the users orders \n @user_items = current_user.user_items.pluck(:id).uniq\n @all_user_items = UserItem.where(id: @user_items)\n\n if(@item.borrowable?)\n # if the users order created_at date is less than the date today - 2 and it hasn't been returned then display an error\n if(@all_user_items.where('created_at < ? and returned = ?', DateTime.now-2.days, false).present?)\n flash[:danger] = \"Item cannot be borrowed, you currently have a fine\"\n redirect_to items_path\n else\n\n end\n else\n end\n end",
"def training_sessions_remaining_this_month\n end",
"def check_out_date_length\n errors.add(:check_out_at, \"must be less than 12 hours after check in at\") if\n check_out_at > (check_in_at + 12.hours)\n end",
"def is_customer_and_for_over_2yrs?\n (Time.now - created_at) >= (2*365*24*60*60)\n end",
"def available_for?(checking_date, checkout_date)\n Booking.where(island: self.island)\n .where(\"check_in > ? OR check_out < ? \", checkout_date, checking_date)\n .length == Booking.where(island: self.island).length\n end",
"def check_out(user, book)\n# .borrowerd_books refers to the \"getter/setter\" methods defined in the Borrower class which enables\n# us to retrieve the books in the @borrowed_books array and add new ones as well. .length checks the\n# length of the the @borrowered_books array.\n if user.borrowed_books.length >= 2\n#\n puts \"Sorry, the user is only able to check out two books.\"\n return\n end\n# .status refers to the \"getter/setter\" method that retrieves and sets the instance variable @status. \n if book.status == \"available\"\n user.borrowed_books << book\n book.status = \"unavailable\"\n book.borrower = user\n else\n puts \"Sorry, that book is unavailable.\"\n end\n end",
"def choose_dates\n authorize! :choose_dates, :Reservation\n\n if(session[:rental_category_id].nil?)\n redirect_to shopping_path\n end\n\n @start_date = Date.today.next_month.beginning_of_month\n\n # pick_up_dates is the first full week of next month starting from the first weekday\n @pick_up_start_date = @start_date\n @pick_up_start_date += 1.days until @pick_up_start_date.wday == 1 # wday 1 is monday, etc.\n @pick_up_dates = @pick_up_start_date..(@pick_up_start_date + 5.days)\n\n # return_dates is the last full week of next month ending on the last weekday\n @return_end_date = Date.today.next_month.end_of_month\n @return_end_date -= 1.days until @return_end_date.wday == 1 # wday 1 is monday, etc.\n @return_dates = (@return_end_date)..(@return_end_date + 5.days)\n @end_date = @return_dates.last\n end",
"def invalid_dates\n self.listing.reservations.each do |reservation|\n existing_reservations = reservation.checkin..reservation.checkout \n if existing_reservations.include?(self.checkin) || existing_reservations.include?(self.checkout)\n errors.add(:checkin_taken, \"The date is already taken\")\n end\n end \n end",
"def check_out(book, user)\n user.overdue_update\n\n # Check the number of books a user has checked out\n if user.checked_out_books.length >= 2\n puts \"You have too many books checked out. You must return at least one book before you can check out another book.\"\n\n # Check if the user has overdue books\n elsif user.overdue_books.any? \n puts \"You have overdue books! No new books for you! Return your overdue books to be allowed to check out new books.\"\n \n # Check out the book\n elsif book.status == \"available\"\n book.status = \"checked out\"\n user.checked_out_books << book\n book.check_out_date = Time.now\n book.due_date = book.check_out_date + ((60*60*24)*7)\n @checked_out << book\n book.who_checked = user.name\n puts \"#{book.title} has been checked out by #{book.who_checked}. Enjoy!\"\n \n else\n puts \"You have discovered a problem with the check_out method! Sorry!\"\n end\n end",
"def available?(start_date, end_date)\n unless self.reservations.any? { |res| start_date.to_date.between?(res.checkin, res.checkout) || end_date.to_date.between?(res.checkin, res.checkout)} \n true\n end\n end",
"def schedule_future_check_out(user, future_date)\n\n end",
"def new_user?\n self.created_at > 1.month.ago\n end",
"def better_to_confirm\n ! (self.confirmed && (((Time.zone.now - self.confirmed).to_i / 86400) < 365))\n end",
"def invalid_checkin_checkout\n if !self.checkin.nil? && !self.checkout.nil?\n if self.checkin >= self.checkout \n errors.add(:invalid_dates, \"Dates are invalid\")\n end\n end\n end",
"def checkage_restriction_on_book\n @messsage = \"Your age criteria not satisfied to view that book.\"\n render :file => \"shared/message\" if current_user && current_user.age_restriction_on_resource(@book)\n end",
"def checkout_before_checkin\n errors.add(:guest_id, \"Check out date must be before Check In date\") if checkin != nil && checkout != nil && checkout < checkin || checkout == checkin\n end",
"def billing_monthly?\n numbering_period == 'monthly'\n end",
"def eligibleRecu(annee = Date.today().year)\n Date.civil(annee, 1, 1).years_ago(16) <= self.naissance\n end",
"def billing_yearly?\n numbering_period == 'yearly'\n end",
"def check_in_cannot_be_in_the_past\n if check_in.present? && check_in < Date.today\n errors.add(:check_in, \"can't be in the past\")\n end\n end",
"def expiry=(expiry)\n self.expires_on = Date.strptime(expiry, '%m/%y') +1.month\n end",
"def offenses_to_check; end",
"def update_hold_to_checkout(lib_book)\n book = Book.find(self[:book_id])\n\n if book.is_special?\n self.update({ hold: nil, special_approval: true })\n else\n if self.update({ hold: nil, start: Time.now, special_approval: false })\n lib_book.reduce_count\n end\n end\n end",
"def check_in(book,user)\n\n\t\tif book.status == \"available\"\n\t\t\tputs \"This book is not available for check in.\"\n\t\telse \n\t\t\tuser.checked_out_books.delete(book)\n book.status = \"available\"\t\n\t\t\tputs \"Thank you! #{book.title} is now checked in.\"\n\t\tend\n\tend",
"def allowed_to_pay_renewal_member_fee?\n return false if admin?\n\n (current_member? || in_grace_period?) &&\n RequirementsForRenewal.requirements_excluding_payments_met?(self)\n end",
"def is_past_6_months(date)\n monthDifference = (Time.now.year * 12 + Time.now.month) - (date.year * 12 + date.month)\n monthDifference.between?(0, 5)\n end",
"def no_past\n if check_in < Date.now\n errors.add(:check_in, \"You can not book in the past\")\n end\n end",
"def safe_renewal_application_dates(status)\n case status\n when :draft, :enrollment_open\n current_effective_date (TimeKeeper.date_of_record + 2.months).beginning_of_month.prev_year\n when :enrollment_closed, :enrollment_eligible, :enrollment_extended\n current_effective_date (TimeKeeper.date_of_record + 1.months).beginning_of_month.prev_year\n when :active, :terminated, :termination_pending, :expired\n if TimeKeeper.date_of_record.month > 10\n current_effective_date (TimeKeeper.date_of_record - 3.months).beginning_of_month.prev_year\n elsif TimeKeeper.date_of_record.month == 1\n current_effective_date TimeKeeper.date_of_record.beginning_of_month.prev_year\n else\n current_effective_date (TimeKeeper.date_of_record - 1.months).beginning_of_month.prev_year\n end\n end\n end",
"def company_payment_reminders\n check_company_usage_cycle\n company_monthly_payment_reminders\n end",
"def activate\n add_year_to_member_until_until\n ensure_member_role\n end",
"def can_enroll?\n self.self_enrollment_allowed && effective_cutoff_date >= Time.now\n end",
"def in_renewal_span?\n (0..7).include?(end_date.to_date - Time.zone.now.to_date)\n end",
"def check_out_should_be_less_than_check_in\n if check_in.present? && check_out.present? && check_out < check_in\n errors.add(:check_out, \"can't be less than check in date\")\n end\n end",
"def check_out(book, due_date)\n @borrowed_books[book.title.to_sym] = book\n max_borrowed = true if @borrowed_books.length >= 2\n\n time_table[book.title.to_sym] = due_date\n\n end",
"def expired?\n !converted_to_recipient? && months_remaining == 0\n end",
"def check_in(book, user)\n # Check if book is already checked out\n if book.status == \"checked out\" || book.status == \"overdue\"\n book.status = \"available\"\n\n # Remove from user's checked out book array\n user.checked_out_books.delete_if { |e| e == book }\n user.overdue_books.delete_if {|e| e == book }\n \n # Reset the check out and due dates to nothing\n book.check_out_date = nil\n book.due_date = nil\n \n # Remove from the library's checked out and overdue arrays.\n @checked_out.delete_if { |e| e == book }\n @overdue.delete_if { |e| e == book }\n\n # Remove the user who checked out the book\n book.who_checked = nil\n \n # Error message for book that is not checked out.\n elsif book.status == \"available\"\n puts \"This book is not checked out\"\n \n # Allows lost books to be returned.\n elsif book.status == \"lost\"\n book.status = \"available\"\n puts \"Thanks for bringing #{book.title} back!\"\n \n # Malformed input or malfunctioning method error message.\n else\n puts \"There is something wrong with the book you've tried to check out. This is an error message. Sorry.\"\n end\n end",
"def dead_account?\n recipes.count == 0 && (Time.now - created_at) > 3.months\n end",
"def set_expiration_date\n self.expiry_date = Date.today + 365.days\n end",
"def checkoutad\n flag = 0 \n flag2 = 0\n book = Book.find(params[:id])\n @user = User.where(:email => params[:email])\n @books=Book.all\n @books.each do|book|\n if (book.Lastuser == params[:email]) \n flag = 1 \n flash[:notice] = 'User has another book checked out already' \n end\n end\n @users=User.all\n @users.each do|user|\n if (user.email == params[:email]) \n flag2 = 1\n end\n end\n if flag2 == 0 \n flash[:notice] = 'Invalid user email'\n end\n if ((flag == 0) && (flag2 == 1)) \n book = Book.find(params[:id])\n book.Status = !book.Status \n book.Lastuser = params[:email]\n book.save\n History.create(:book_isbn => book.ISBN, :user_email => params[:email], :book_title => book.Title, :book_author => book.Authors, :checkout_time => DateTime.now)\n flash[:notice] = 'Book was sucessfully checked out' \n end \n redirect_to book_path(book) \n end",
"def new?\n if created_at > Time.now - 1.month\n return true\n end\n end",
"def years_needed\n 30\n end",
"def researchers_without_xaccount()\n last_month = Time.now - 1.month\n #People.\n end",
"def renewable?(user)\n course.enrolled?(user) && in_renewal_span?\n end",
"def book_once_aday\n errors.add(:user, 'Guest can book only once a day') if booked_in_same_day?\n end",
"def set_and_authorize_due_date\n @due_date = policy_scope(DueDate).find(params[:id])\n authorize @due_date\n end",
"def checkout\n flag = 0 \n book = Book.find(params[:id])\n @user = User.where(:email => params[:isbn])\n @books=Book.all\n @books.each do|book|\n if (book.Lastuser == current_user.email) \n flag = 1 \n flash[:notice] = 'You have another book checked out already' \n end\n end\n if flag == 0 \n book = Book.find(params[:id])\n book.Status = !book.Status \n book.Lastuser = current_user.email\n book.save\n History.create(:book_isbn => book.ISBN, :user_email => current_user.email, :book_title => book.Title, :book_author => book.Authors, :checkout_time => DateTime.now)\n flash[:notice] = 'Book was sucessfully checked out' \n end \n redirect_to book_path(book) \n end",
"def lost?\n book.status=\"lost\" if Time.now > (book.due_date + (30*24*60*60))\n end",
"def available_for?(reservation)\n return false if staff_only? && !reservation.staff? # TODO handle staff reservations properly\n return false unless ready_for_checkout?\n return false if reservation.start_date.blank? || reservation.end_date.blank?\n if reservation.staff?\n reservation_start_date_with_buffer = reservation.start_date + 1.second\n reservation_end_date = reservation.end_date - 1.second\n else\n reservation_start_date_with_buffer = reservation.start_date - 1.day - (category.buffer_days_between_checkouts.to_i * 1.day)\n reservation_end_date = reservation.end_date\n end\n conditions = [['(start_date <= :start_date AND end_date >= :end_date)'],\n ['(start_date <= :end_date AND end_date >= :end_date)'],\n ['(start_date <= :start_date AND end_date >= :end_date)'],\n ['(start_date >= :start_date AND end_date <= :end_date)'],\n ['(start_date >= :start_date AND start_date <= :end_date)'],\n \t\t['(end_date >= :start_date AND end_date <= :end_date)']]\n reservations.find(:all, :conditions => [\"submitted = true\n AND equipment_reservation_id != #{reservation.id} \n AND (#{conditions.join(\" OR \")})\", \n { :start_date => reservation_start_date_with_buffer, :end_date => reservation_end_date }]).empty?\n end",
"def check_out(user, book)\n if user.borrowed_books_count == 2\n puts \"Sorry, that user already has two books checked out.\"\n elsif book.status == \"checked out\"\n puts \"Sorry, that book in not available.\"\n else\n book.borrower = user\n user.borrowed_books.push(book)\n book.status = \"checked out\"\n puts \"#{user.name} has now checked out #{book.title} by #{book.author}.\"\n end\n end",
"def checkout_book(title)\n # find book instance by title\n searched_book = Book.find_by(title: title)\n # change book.available to false\n searched_book.update_column(:available, false)\n # create Checkout instance with student id, book id, due date, checked_out defaults to true\n Checkout.create(student_id: self.id, book_id: searched_book.id, due_date: ((Date.today)+7))\n end",
"def remember_me\n remember_me_for 3.month\n end",
"def old_enough_to_vote?(yr_born)\n (2016 - yr_born) >= 18 ? \"yes\" : \"no\"\nend",
"def check_out(user, book)\n if user.borrowed_books.length == 2\n puts \"Sorry #{user.name}, you have already checked out two books.\"\n return \n end\n\n if book.status == \"available\"\n book.borrower = user\n user.borrowed_books.push(book)\n book.status = \"checked out\"\n puts \"#{user.name} checked out '#{book.title}' by #{book.author}.\"\n elsif book.status == \"checked out\"\n puts \"Sorry '#{book.title}' is checked out by another library member.\"\n else\n puts \"Sorry, that book is not available\"\n return \n end\n end",
"def invoiced_for(m)\n d = Date.parse(m)\n self.invoices.within_range(d, ((d + 1.month) - 1.day)).sum(:total)\n end",
"def can_rent_truck?\n !license.expired? && age >= 60 && license.to_drive_truck?\n end",
"def check_expiration\n return unless @reservation.booking_request_expired?\n\n flash[:danger] = 'Booking request has expired.'\n redirect_to your_reservations_path\n end",
"def check_in(book)\n book.status = \"available\"\n book.borrower.borrowed_books.delete(book.borrower.borrowed_books[book])\n end",
"def show\n @booking = @boat.bookings.build(user: current_user)\n @booking.start_time = Time.zone.tomorrow + 9.hours\n @booking.end_time = Time.zone.tomorrow + 18.hours\n @booking.people_on_board = 1\n #TODO disable also booked(accepted) days\n end",
"def initialize(room_id, startyear, startmonth, startday, endyear, endmonth, endday)\n unless Availability.all_available_rooms(startyear, startmonth, startday, endyear, endmonth, endday).include?(room_id)\n raise ArgumentError.new(\"That room is not available for the given date range.\")\n end\n\n checkin_date = Date.new(startyear,startmonth,startday)\n checkout_date = Date.new(endyear,endmonth,endday)\n wanteddate = checkin_date\n\n update_status(wanteddate, checkout_date, room_id, :booked)\n\n total_stay = (checkout_date - checkin_date).to_i\n @total_cost = total_stay * 200\n end",
"def date_restricted?\n\n now = Date.today\n\n !((valid_from.nil? or now >= valid_from) and (valid_until.nil? or now <= valid_until))\n\n end",
"def valid_date_in_month(d,m)\n d >= 1 and Time.days_in_month(m,start.year) >= d ? d : raise(ArgumentError, \"invalid day #{d} for #{m}\") \n end",
"def available_rooms(check_in, check_out)\n check_in = Date.parse(check_in)\n check_out = Date.parse(check_out)\n\n if check_in == check_out\n booking_dates = [check_in]\n else\n booking_dates = (check_in..check_out).to_a\n end\n\n # returns a list of all rooms, if no reservations have been made\n return rooms if reservations.empty?\n\n available = []\n availability = \"yes\"\n\n # searches through each room's reservation dates and if they don't include\n # any of the dates being inquired about adds the room to the available\n # list\n rooms.each do |room|\n room.reservations.each do |reservation|\n reservation.all_dates.each do |date|\n availability = \"no\" if booking_dates.include?(date)\n end\n end\n available << room if availability == \"yes\"\n availability = \"yes\"\n end\n\n return available\n end",
"def account_used\n\n\t\tif Booking.where(location_id: Location.where(company_id: self.id).pluck(:id)).where('created_at > ?', DateTime.now - 1.weeks).count > 0\n\t\t\treturn true\n\t\tend\n\n\t\treturn false\n\n\tend",
"def not_renewable?\n return true unless self.class == CartReservation || self.status == \"reserved\"\n reserver.reservations.each do |res|\n if res.equipment_model == self.equipment_model && res.due_date.to_date == self.start_date.to_date && res.is_eligible_for_renew?\n errors.add(:base, res.equipment_model.name + \" should be renewed instead of re-checked out.\\n\")\n return false\n end\n end\n return true\n end",
"def has_overhead_last_5_years\n if current_user.lawfirm.overheads\n ovh = current_user.lawfirm.overheads.collect(&:year)\n if ovh.include?(Date.today.year) and ovh.include?(Date.today.year - 1) and ovh.include?(Date.today.year - 2) and ovh.include?(Date.today.year - 3) and ovh.include?(Date.today.year - 4)\n return true\n else\n redirect_to user_lawfirm_overheads_path(current_user, current_user.lawfirm_id),\n :flash => {:danger => \"You must calculate overhead for each of the past 5 years to view this page.\"}\n end\n else\n redirect_to user_lawfirm_overheads_path(current_user, current_user.lawfirm_id),\n :flash => {:danger => \"You must calculate overhead for each of the past 5 years to view this page.\"}\n end\n end",
"def user_requirements(fname, lname, month, yearofbirth)\n full_name = fname + ' ' + lname\n today_year = 2014\n today_month = 9\n month = 9\n yearofbirth = 1990\n final_age = (today_year - yearofbirth) + final_age_month\n puts full_name \n puts final_age\n end",
"def approve_setup_fee_collection( current_user )\n self.is_setup_fee_collection_approved = true \n self.setup_fee_collection_approver_id = current_user.id \n self.save\n \n # create all those payment payable : loan disbursement \n end",
"def validate_can_assign_auction_date\n if self.ready_for_auction? && \n (self.auction_datum.blank? || (self.auction_datum.present? && self.auction_datum.auction_date.blank? )) &&\n self.service_orders.joins(:service_order_details).where(\"service_order_details.status=? AND service_orders.priority=?\", ServiceOrder::SO_STATUS_APPROVED, ServiceOrder::SO_PRIORITY_HIGH).count > 0\n self.errors.add(:\"auction_datum.auction_date\", I18n.t(\"models.vehicle.errors.service_order_must_be_completed\"))\n end\n end",
"def money_approved?\n true\n end",
"def child_consent_birth_to_6_months?\n @activity_name == \"Child Consent Birth to Six Months\"\n end",
"def too_soon_to_renew?\n due_date_after_renewal <= due_date\n end"
] |
[
"0.65613383",
"0.6254185",
"0.61772865",
"0.58629364",
"0.5851184",
"0.58436793",
"0.581441",
"0.5775874",
"0.5738204",
"0.573172",
"0.571981",
"0.57090956",
"0.5690138",
"0.567225",
"0.56311065",
"0.56303257",
"0.56210506",
"0.56154925",
"0.5610927",
"0.56055796",
"0.5603714",
"0.55979997",
"0.55979997",
"0.55870223",
"0.5560265",
"0.5535701",
"0.5534853",
"0.5499599",
"0.54830277",
"0.5482094",
"0.546239",
"0.5441711",
"0.54405457",
"0.5420454",
"0.5411645",
"0.5394287",
"0.5391349",
"0.5391315",
"0.53853446",
"0.5376921",
"0.536577",
"0.536178",
"0.5360575",
"0.5358572",
"0.53557503",
"0.5349584",
"0.5348773",
"0.53486663",
"0.5345936",
"0.5328133",
"0.5315225",
"0.5311416",
"0.5309743",
"0.5307216",
"0.5300403",
"0.5297392",
"0.52919984",
"0.52901465",
"0.5266964",
"0.5264048",
"0.5255401",
"0.52503306",
"0.5236484",
"0.52310735",
"0.5229617",
"0.52288336",
"0.52189744",
"0.52085733",
"0.52074015",
"0.5205063",
"0.5194804",
"0.51820356",
"0.51814026",
"0.51811385",
"0.5181059",
"0.5178432",
"0.5176703",
"0.5170099",
"0.51647735",
"0.5159726",
"0.51552045",
"0.515215",
"0.5149846",
"0.51478565",
"0.5147558",
"0.5138848",
"0.5137564",
"0.51357263",
"0.5130293",
"0.512555",
"0.51096684",
"0.5094603",
"0.50858206",
"0.5084401",
"0.5083123",
"0.50784075",
"0.50721896",
"0.5071277",
"0.5068462",
"0.5065614"
] |
0.6652991
|
0
|
Checks if the system is properly setup. This method is used by the bootstrapper to see if the system should be initialized. If the system is not properly setup, the bootstrapper will crash. Checks are performed to see if all the tables exists.
|
def check
unless check_tables
puts "CBAC: not properly initialized: one or more tables are missing. Did you install it correctly? (run generate)"
return false
end
return true
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def initialized?\r\n if ENV[\"RAILS_ENV\"] == \"test\" || !User.table_exists? || $setup_disabled \r\n return false\r\n else \r\n $tmp_env = ENV[\"RAILS_ENV\"] || \"development\"\r\n return true\r\n end \r\n end",
"def sanityCheck\n @executor.nil? and raise \"Executor has not been initialized.\"\n @manipulator.nil? and raise \"Manipulator has not been initialized.\"\n @monitor.nil? and raise \"Monitor has not been initialized.\"\n @subject.nil? and raise \"Subject has not been initialized.\"\n end",
"def initial_setup\n CORE.each { |c| c.auto_migrate! }\n end",
"def setup\n begin\n create_campaign_table_if_not_exist\n seed_data\n rescue Exception => e\n raise \"Database setup failed with error #{e}\"\n ensure\n @connection.close\n end\n end",
"def ensure_setup!\n unless @model_class\n raise \"You must call #setup! on this class before calling this method.\"\n end\n end",
"def check_environment\n load_rscribd\n check_config\n check_fields\n end",
"def ensure_physical_databases!\n @ensure_physical_databases ||= create_physical_databases\n end",
"def env_check\n unless Position.count.zero?\n $stderr.puts \"Position table is not empty! (needs to be truncated first)\"\n exit(5)\n end\n end",
"def env_check\n unless Position.count.zero?\n $stderr.puts \"Position table is not empty! (needs to be truncated first)\"\n exit(5)\n end\n end",
"def ensure_infrastructure\n ensure_activity_markers\n ensure_change_logs\n ensure_event_log\n ensure_sync_state\n end",
"def setup?\n @setup\n end",
"def ensure_that_we_have_table_and_column_families! # :nodoc:\n #\n # TODO: Can we skip checking if it exists at all, and instead, rescue it if it does not?\n #\n hbase_create_table! unless klass.table.exists?\n raise ColumnFamiliesMissingError.new(klass, calculate_missing_family_names) if calculate_missing_family_names.any?\n end",
"def ensure_prerequisites\n return false unless command_found('netsh')\n return false unless command_found('net')\n return false unless command_found('reg')\n\n unless wired_autoconfig_service_running?\n info('starting \\'Wired AutoConfig\\' service')\n if admin_mode?\n `net start dot3svc`\n else\n require 'win32ole'\n shell = WIN32OLE.new('Shell.Application')\n shell.ShellExecute('net', 'start dot3svc', nil, 'runas', 1)\n end\n service_has_started = Landrush::Util::Retry.retry(tries: 5, sleep: 1) do\n wired_autoconfig_service_running?\n end\n unless service_has_started\n info('Unable to start \\'Wired AutoConfig\\' service. Unable to configure DNS on host. Try manual configuration.')\n return false\n end\n info('\\'Wired AutoConfig\\' service has started.')\n end\n true\n end",
"def bootstrapped?\n raise \"Invalid Bootstrapper\"\n end",
"def table_or_view_ready?\n Admin::MigrationGenerator.table_or_view_exists?(table_name)\n rescue StandardError => e\n @extra_error = e\n false\n end",
"def init\n if !response_service.admin_view?\n render json: { popup: 'Must be an admin to initialize the database!!' }\n elsif Rails.env.production?\n render json: { popup: 'Can\\'t initialize the production database!!' }\n else\n Answer.delete_all\n Authentication.delete_all\n Expression.delete_all\n Finder.delete_all\n List.delete_all\n Rcpref.delete_all\n Recipe.delete_all\n ImageReference.delete_all\n Referent.delete_all\n Referment.delete_all\n ReferentRelation.delete_all\n ResultsCache.delete_all\n Scraper.clear_all\n Site.delete_all\n TagSelection.delete_all\n Tag.delete_all\n TagOwner.delete_all\n Tagging.delete_all\n TagsCache.delete_all\n Tagset.delete_all\n # User.delete_all\n # UserRelation.delete_all\n Vote.delete_all\n sql = 'DELETE FROM delayed_jobs;'\n ActiveRecord::Base.connection.execute(sql)\n render json: { popup: 'Database is initialized and ready for scraping.' }\n end\n end",
"def ensure_table\n # Check if table exists\n if !@db.tables || !@db.tables.include?(table_name)\n log(\"Creating Table #{table_name}\")\n adaptor_name = @adaptor.adaptor_name\n @db.create_table(table_name) do\n # guid id\n column :id, String, :unique => true, :null => false, :primary_key => true\n\n # When using underscore notation on a field that does not exist, the\n # data will be stored in extra.\n if adaptor_name == 'postgres'\n # Use jsonb\n column :extra, 'json'\n else\n column :extra, String\n end\n end\n # TODO: there's some issue with @db.schema and no clue why, but I\n # have to run this again to get .schema to work later.\n @db.tables\n end\n end",
"def setup\n setup_connection\n\n unless tables.count == 0\n puts \"Aborting! Job already has tables attached. Setup requires a new job.\"\n return\n end\n source_tables = source_connection.tables\n source_tables = source_tables.reject { |table| \n exclude_table_names.include?(table) || table.starts_with?('tmp_') \n }\n\n source_tables.each do |table_name|\n copy_table_schema(table_name)\n end\n\n puts \"Done setup!\"\n puts \"Warning! Table settings have been guessed but you can do extra configuration such as setting the insert_only flag on tables to further increase speed of loading.\"\n end",
"def check_for_initial_install\n #Don't do anything if a user is logged in\n unless user_signed_in?\n #if the flag set in the seeds file still isn't set to true and there are no users, let's do our thing\n if ConcertoConfig[:setup_complete] == \"false\" && User.all.empty?\n redirect_to new_user_registration_path\n end\n end\n end",
"def exist_tables?\n @db.tables.sort == [:mirrors, :users, :user_tokens, :products, :products_users, :versions, :dependencies, :access_keys].sort\n end",
"def setup\n @bigquery = $bigquery\n @prefix = $prefix\n @storage = $storage\n @bucket = $bucket\n @samples_bucket = $samples_bucket\n @samples_public_table = $samples_public_table\n @kms_key = $kms_key\n @kms_key_2 = $kms_key_2\n\n refute_nil @bigquery, \"You do not have an active bigquery to run the tests.\"\n refute_nil @prefix, \"You do not have an bigquery prefix to name the datasets and tables with.\"\n refute_nil @storage, \"You do not have an active storage to run the tests.\"\n refute_nil @bucket, \"You do not have a storage bucket to run the tests.\"\n refute_nil @samples_bucket, \"You do not have a bucket with sample data to run the tests.\"\n refute_nil @samples_public_table, \"You do not have a table with sample data to run the tests.\"\n refute_nil @kms_key, \"You do not have a kms key to run the tests.\"\n refute_nil @kms_key_2, \"You do not have a second kms key to run the tests.\"\n\n super\n end",
"def setup?\n Crocoduck::Store.server_cluster && \n Crocoduck::Store.server_db && \n Crocoduck::Store.server_collection\n end",
"def run_before_migrate_setup\n Chef::Log.info 'No before migrate setup defined.'\n end",
"def db_setup\n path_to_db = File.join(File.dirname(__FILE__), \"temp_humidity.db\")\n SQLite3::Database.open(path_to_db).tap do | db |\n # Do anything here before we begin\n end\nend",
"def check_and_set_environment\n check_env\n set_env\n end",
"def test_DB_initialization\n @fdb = setup\n assert(@fdb.size > 0, \"Database entries not correctly read in\")\n end",
"def system_load_ok?\n true\n end",
"def check_models_presence\n return unless depricated_page?\n return unless signed_in? && !current_user\n\n create_user_if_absent\n create_reader_set_if_absent\n create_mailer_set_if_absent\n end",
"def stem_ready(stem) # :nodoc:\n return unless Thread.exclusive { stems.ready?.all? }\n database { startup_check }\n end",
"def doctor_config_systems\n errors = false\n\n if config_systems.empty?\n errors = true\n logger.error \"systems is empty\"\n end\n\n errors\n end",
"def pre_setup_suite()\n @cfg['pre_setup'] =\"defined\"\n return true\n end",
"def run_checks\n # check that mysql tmpdir is custom setup on all servers\n query = \"show variables like 'tmpdir'\"\n query_command = \"echo -e \\\"#{query}\\\"| mysql\"\n @servers.each do |server|\n server.spot_check(query_command) { |result| raise \"Failure: tmpdir was unset#{result}\" unless result.include?(\"/mnt/mysqltmp\") }\n end\n end",
"def setup\n # Settings, common_codes, entities, menus, terminologies\n return if self.exist_initial_data\n debug_print \"Progressing setup initial data ...\"\n sys_dom = Domain.system_domain\n\n debug_print \"Finding initial data from System Domain ...\"\n ori_codes = CommonCode.where(\"domain_id = #{sys_dom.id} and parent_id is null\")\n ori_entities = Entity.where(\"domain_id = #{sys_dom.id}\")\n ori_settings = Setting.where(\"domain_id = #{sys_dom.id}\")\n\n debug_print \"Copying initial data to Domain (#{self.name})...\"\n self.clone_code_to_domain(ori_codes)\n self.clone_entity_to_domain(ori_entities)\n self.clone_to_domain(ori_settings, Setting)\n\n debug_print \"Completed setup initial data ...\"\n end",
"def first_run?\n not File.exists? '/boot/config/.boxcar'\n end",
"def check_init\n if !@settings.initialized_flag\n if current_user\n # Create the Admin User\n current_user.update_attribute :admin, true \n \n # Set intiatilized flag to true\n @settings.update_attribute :initialized_flag, true\n \n # Put user back on admin area\n redirect_to admin_project_path, :flash => { :success => \"Nice! Your app is now initialized.\" } \n else\n redirect_to new_user_registration_path, :flash => { :error => \"App is not initialized\" }\n end \n end\n end",
"def test_setup\n TestEngine.install_tasks\n Rake::Task['test:engine:setup'].invoke\n assert app_path.join('db/schema.rb').exist?\n assert app_path.join('db/test.sqlite3').exist?\n end",
"def app_init!(rails_env)\n if rails_env.development? || rails_env.demo?\n # If we are running a rake command like `rake db:seed` or\n # `rake db:schema:load`, we do not want to try and seed the fakes\n # because our schema may not be loaded yet and it will fail!\n if running_rake_command?\n load!\n else\n load_fakes_and_seed!\n end\n end\n end",
"def before_setup\n Account.connection.drop_table :accounts, if_exists: true\n Account.connection.exec_query(\"CREATE SEQUENCE accounts_id_seq\")\n Account.connection.exec_query(\"\n CREATE TABLE accounts (\n id BIGINT PRIMARY KEY DEFAULT nextval('accounts_id_seq'),\n firm_id bigint,\n firm_name character varying,\n credit_limit integer\n )\n \")\n\n Company.connection.drop_table :companies, if_exists: true\n Company.connection.exec_query(\"CREATE SEQUENCE companies_nonstd_seq\")\n Company.connection.exec_query(\"\n CREATE TABLE companies (\n id BIGINT PRIMARY KEY DEFAULT nextval('companies_nonstd_seq'),\n type character varying,\n firm_id bigint,\n firm_name character varying,\n name character varying,\n client_of bigint,\n rating bigint,\n account_id integer,\n description character varying\n )\n \")\n\n Course.connection.drop_table :courses, if_exists: true\n Course.connection.exec_query(\"CREATE SEQUENCE courses_id_seq\")\n Course.connection.exec_query(\"\n CREATE TABLE courses (\n id INT PRIMARY KEY DEFAULT nextval('courses_id_seq'),\n name character varying,\n college_id integer\n )\n \")\n\n self.class.fixtures :accounts\n self.class.fixtures :companies\n self.class.fixtures :courses\n end",
"def haveBootstrapped?\n self.class.loadChefLib\n MU.log \"Chef config\", MU::DEBUG, details: ::Chef::Config.inspect\n nodelist = ::Chef::Node.list()\n nodelist.has_key?(@server.mu_name)\n end",
"def probe_tables\n master.probe\n\n @probe_lock.synchronize do\n return unless @tables.nil?\n\n db = standby_slaves.last || active_slaves.last || master\n if db && db.running?\n output \"Probing tables via #{db}\"\n else\n output \"Warning: unable to probe tables\"\n return\n end\n\n @tables = []\n sql = \"SHOW TABLES\"\n db.query_return_array(sql).each do |tbl|\n table_name = tbl.values.first\n @tables << db.detect_table_schema(table_name)\n end\n end\n end",
"def ensure_has_environment_files()\n\n end",
"def just_set_up?\n AppConfig[:just_set_up] == true\n end",
"def init!\n @logger = @config = @database_config = nil\n\n load_application_config\n load_database_config\n note \"Loading #{env} environment (#{Ajaila::VERSION})\"\n load_classes\n note \"Establishing database connection\"\n establish_database_connection\n note \"Running auto-upgrade migrations\"\n run_auto_upgrade_migrations\n note \"Application has been initialized\"\n self\n end",
"def setup\n self.setup! unless self.setup?\n end",
"def startup_config_check\n\t\tfw_connect\n\t\t# they are ALL stale right now...\n\t\tcheck_config_freshness\n\t\tpending = get_pending_commits\n\t\tdo_pending_commits(pending) if pending != 0\n\t\tfw_exit\n\tend",
"def check_config\n unless File.directory?(yolo_dir) and File.exist?(yaml_path)\n @error.run_setup\n load_config\n @formatter.setup_complete\n end\n end",
"def setup\n true\n end",
"def just_set_up!\n AppConfig[:just_set_up] = false\n end",
"def startup()\n check_return_code(PureHailDB.ib_startup(\"BARRACUDA\"))\n end",
"def bootstrap\n sql = 'CREATE TABLE IF NOT EXISTS states(uuid VARCHAR(128) PRIMARY KEY,'\n sql << ' id INTEGER, name VARCHAR(128), deploy_id VARCHAR(128), timestamp INTEGER,'\n sql << ' missing INTEGER, state VARCHAR(128), hyperv VARCHAR(128))'\n\n @db.execute(sql)\n\n sql = 'CREATE TABLE IF NOT EXISTS settings(key VARCHAR(128) PRIMARY KEY,'\n sql << ' value VARCHAR(128))'\n\n @db.execute(sql)\n end",
"def feature_table_exists?\n Feature::FlipperFeature.table_exists?\n rescue StandardError\n false\n end",
"def db_setup\n path_to_db = \"/tmp/temp_humidity.db\"\n SQLite3::Database.open(path_to_db).tap do | db |\n # Do anything here before we begin\n end\nend",
"def prerequisites\n\tKitchenplan::Application.fatal! \"Don't run this as root!\" unless running_as_normaluser?\n\tKitchenplan::Application.fatal! \"#{ENV['USER']} needs to be part of the 'admin' group!\" unless user_is_admin?\n\tKitchenplan::Application.fatal! \"Platform version too low. Your version: #{self.version}\" unless version_supported?\n\tinstall_bundler\n\t# needed for proper librarian usage\n\tinstall_git\n\tkitchenplan_bundle_install\n end",
"def prerequisites\n\tKitchenplan::Application.fatal! \"Don't run this as root!\" unless running_as_normaluser?\n\tKitchenplan::Application.fatal! \"#{ENV['USER']} needs to be part of the 'admin' group!\" unless user_is_admin?\n\tKitchenplan::Application.fatal! \"Platform version too low. Your version: #{self.version}\" unless version_supported?\n\tinstall_bundler\n\t# needed for proper librarian usage\n\tinstall_git\n\tkitchenplan_bundle_install\n end",
"def verify_configuration\n if options.config_check?\n unless File.exists?(\"#{Rails.root}/config/initializers/cambium.rb\")\n help_message('cambium_prereqs')\n exit\n end\n end\n end",
"def db_setup\n log_debug\n db_file = find_db\n db_tmp = '/tmp/plex_missing_tmp.db'\n @db = ''\n \n # cp to tmp as the db is locked if being used\n `cp \"#{db_file}\" #{db_tmp}`\n \n # not too sure why but i was having a problem where a 0 byte file was cp'd\n # def a local issue i assume but the check was needed\n if test ?s, db_tmp\n @db = SQLite3::Database.new db_tmp\n else \n puts \"error-> can not open #{db_tmp} for reasing\"\n exit 2\n end\n end",
"def already_initialized\n response = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query \"SELECT name FROM sqlite_master WHERE type='table'\" }\n response.rows.flatten.member?('code_files')\n rescue ExceptionName\n false\n end",
"def table_exists?\n true\n end",
"def test_can_initialize_with_single_environment\r\n assert_nothing_raised do\r\n DBGeni::Base.installer_for_environment(helper_sqlite_single_environment_file, 'development')\r\n end\r\n end",
"def pre_execute_checks\n validate_terraform_installed\n ensure_output_directory\n Dir.chdir(@opts.get(:input_dir)) do\n puts '=> Fetching modules...'\n tf_get\n end\n end",
"def setup\n @bigtable = $bigtable\n refute_nil @bigtable, \"You do not have an active bigtable to run the tests.\"\n super\n end",
"def setup_db\n return unless File.exist?(\"#{Jets.root}/config/database.yml\")\n\n db_configs = Jets.application.config.database\n # DatabaseTasks.database_configuration for db:create db:migrate tasks\n # Documented in DatabaseTasks that this is the right way to set it when\n # using ActiveRecord rake tasks outside of Rails.\n ActiveRecord::Tasks::DatabaseTasks.database_configuration = db_configs\n\n current_config = db_configs[Jets.env]\n if current_config.blank?\n abort(\"ERROR: config/database.yml exists but no environment section configured for #{Jets.env}\")\n end\n # Using ActiveRecord rake tasks outside of Rails, so we need to set up the\n # db connection ourselves\n ActiveRecord::Base.establish_connection(current_config)\n end",
"def validate_keys\n return if Util::Configuration.is_valid?\n logger.error('==== Please set all environment variables before starting the server ====')\n exit\n end",
"def init_uptime_checks\n keys = @db[:keys].where(key_type: 'uptime').each do |k|\n name = k[:name]\n time, value = last(name)\n bump_uptime(name, get_key(name)) if value == true\n end\n end",
"def try_databases\n db = Database.new(application_root, config, settings)\n db.configure\n end",
"def supports_create_table_if_not_exists?\n server_version >= 90100\n end",
"def check!\n Capistrano::Deploy::Dependencies.new(configuration) do |d|\n d.remote.file(Capistrano::Puppet::Service::Webrick::SERVICE_INIT).or(\"`#{Capistrano::Puppet::Service::Webrick::SERVICE_INIT}' does not exist. Please run `cap deploy:setup'.\")\n end\n end",
"def setup\n\t\t# If there's no test database, we'll use the return statement to stop\n\t\t# executing the rest of this code block.\n\t\treturn unless File.exists?('test.sqlite3')\n\t\t# We'll delete everything in our database so that the results of one\n\t\t# test don't affect other tests.\n\t\tdb = SQLite3::Database.new('test.sqlite3')\n\t\tdb.execute \"DELETE FROM guestbook WHERE 1;\"\n\tend",
"def prepare_for_installation; end",
"def configuration_setup\n dirname = File.expand_path(USER_DIR)\n if !File.exists?(dirname)\n Dir.mkdir(dirname) \n create_storage_dir\n create_staging_dir\n create_user_conf_file\n create_user_email_conf_file\n else \n create_user_conf_file if !File.exists?(USER_CONF_FILE)\n create_storage_dir if !File.exists?(File.expand_path(STORAGE_DIR))\n create_staging_dir if !File.exists?(File.expand_path(STAGING_DIR))\n create_user_email_conf_file if !File.exists?(EMAIL_CONF_FILE)\n end\n end",
"def prepare\n started_at = DateTime.now.to_s\n prepare_deploy\n prepare_common_installation\n puppet_installation\n create_prepare_checkpoint(started_at)\n end",
"def bootstrap\n sql = 'CREATE TABLE IF NOT EXISTS vms(uuid VARCHAR(128) PRIMARY KEY,'\n sql << ' id INTEGER, name VARCHAR(128), deploy_id VARCHAR(128),'\n sql << ' state VARCHAR(128), type VARCHAR(128),'\n sql << ' monitor_info VARCHAR(1024))'\n execute_retry(sql)\n\n sql = 'CREATE TABLE IF NOT EXISTS hosts(id INTEGER PRIMARY KEY,'\n sql << ' name VARCHAR(128), ccr_ref VARCHAR(128), timestamp INTEGER)'\n execute_retry(sql)\n\n sql = 'CREATE TABLE IF NOT EXISTS one_vms(id INTEGER PRIMARY KEY,'\n sql << ' uuid VARCHAR(128))'\n execute_retry(sql)\n\n sql = 'CREATE TABLE IF NOT EXISTS timestamp(ts INTEGER PRIMARY KEY)'\n execute_retry(sql)\n\n sql = 'CREATE TABLE IF NOT EXISTS timestamp_one_vms(ts INTEGER PRIMARY KEY)'\n execute_retry(sql)\n end",
"def setup_database\n Hanami::Model.load!\n end",
"def prerequisites\n\tKitchenplan::Application.fatal! \"Don't run this as root!\" if running_as_superuser?\n\tKitchenplan::Log.warn \"Platform version too low. Your version: #{self.version}\" unless version_supported?\n\tinstall_bundler\n\t# needed for proper librarian usage\n\tinstall_git\n\tkitchenplan_bundle_install\n end",
"def setup_runtimes\n if @runtimes.nil? || @runtimes.empty?\n @logger.fatal(\"Can't determine application runtimes, exiting\")\n exit 1\n end\n @logger.info(\"Checking runtimes:\")\n\n @runtimes.each do |name, runtime|\n # Only enable when we succeed\n runtime['enabled'] = false\n pname = \"#{name}:\".ljust(10)\n\n # Check that we can get a version from the executable\n version_flag = runtime['version_flag'] || '-v'\n\n expanded_exec = `which #{runtime['executable']}`\n unless $? == 0\n @logger.info(\" #{pname} FAILED, executable '#{runtime['executable']}' not found\")\n next\n end\n expanded_exec.strip!\n\n # java prints to stderr, so munch them both..\n version_check = `#{expanded_exec} #{version_flag} 2>&1`.strip!\n unless $? == 0\n @logger.info(\" #{pname} FAILED, executable '#{runtime['executable']}' not found\")\n next\n end\n runtime['executable'] = expanded_exec\n\n next unless runtime['version']\n # Check the version for a match\n if /#{runtime['version']}/ =~ version_check\n # Additional checks should return true\n if runtime['additional_checks']\n additional_check = `#{runtime['executable']} #{runtime['additional_checks']} 2>&1`\n unless additional_check =~ /true/i\n @logger.info(\" #{pname} FAILED, additional checks failed\")\n end\n end\n runtime['enabled'] = true\n @logger.info(\" #{pname} OK\")\n else\n @logger.info(\" #{pname} FAILED, version mismatch (#{version_check})\")\n end\n end\n end",
"def init_database\n\t\tif(!@DB.table_exists?(:events))\n\t\t\t@DB.create_table :events do\n\t\t\t\tprimary_key :id\n\t\t\t\tString :name\n\t\t\t\tString :description\n\t\t\t\tString :date\n\t\t\tend\n\t\tend\n\n\t\tif(!@DB.table_exists?(:timeslots))\n\t\t\t@DB.create_table :timeslots do\n\t\t\t\tString :time\n\t\t\t\tString :parent_table\n\t\t\t\tString :parent_id\n\t\t\tend\n\t\tend\n\n\t\tif(!@DB.table_exists?(:attendees))\n\t\t\t@DB.create_table :attendees do\n\t\t\t\tprimary_key :id\n\t\t\t\tString :name\n\t\t\t\tString :parent_id\n\t\t\tend\n\t\tend\n\tend",
"def setup!\n configuration = RfmAdaptor::Configuration.new(:database)\n database = configuration.__send__(self.database_name)\n raise \"Database: #{self.database_name} configuration file not exists.\" if database.blank?\n raise \"Database: #{self.database_name} environment[#{self.env}] not exists.\" if database[self.env].blank?\n self.attributes = database[self.env]\n self.setup_state = true\n end",
"def setup\n setup_methods.each { |m| self.send(m) }\n start_services\n \n wait_time = cfg('wait-after-startup')\n if not wait_time.nil?\n 1.upto(wait_time) do |i|\n puts \"Waiting #{wait_time-i} seconds before commencing benchmarks\"\n sleep 1\n end\n end\n end",
"def check_environment\n # Also, your VMs require public ssh keys for the root user\n # to exist that match your CLOUD_KEY private key path\n #\n # You must also have the following values set in your environment:\n #\n # ENV[\"API_KEY\"] -- cloudstack api key\n # ENV[\"API_SECRET\"] -- cloudstack api secret\n # ENV[\"API_URL\"] -- cloudstack api endpoint\n # ENV[\"CLOUD_KEY\"] -- local file path to your private SSH key material\n #\n %w{API_KEY API_SECRET API_URL CLOUD_KEY}.each do |var|\n raise \"ERROR: you must set #{var} in you environment\" unless ENV[var]\n end\n end",
"def ensure_present!(create_if_needed)\n return unless @low_card_model.table_exists?\n\n current_name = current_unique_all_columns_index_name\n return true if current_name\n\n if create_if_needed\n create_unique_index!\n true\n else\n message = %{You said that the table '#{low_card_model.table_name}' is a low-card table.\nHowever, it currently does not seem to have a unique index on all its columns. For the\nlow-card system to work properly, this is *required* -- although the low-card system\ntries very hard to lock tables and otherwise ensure that it never will create duplicate\nrows, this is important enough that we really want the database to enforce it.\n\nWe're looking for an index on the following columns:\n\n #{value_column_names.sort.join(\", \")}\n\n...and we have the following unique indexes:\n\n}\n current_unique_indexes.each do |unique_index|\n message << \" '#{unique_index.name}': #{unique_index.columns.sort.join(\", \")}\\n\"\n end\n message << \"\\n\"\n\n raise LowCardTables::Errors::LowCardNoUniqueIndexError, message\n end\n end",
"def correct_setup?\n return required_keys_and_proper_remote_configuration_repo? &&\n local_configuration_repo_exists?\n end",
"def ready?\n File.exist?(desktop_path) && \n File.directory?(libs_path)\n end",
"def boot_up\n celluloid_running = begin\n Celluloid.running?\n rescue StandardError\n false\n end\n Celluloid.boot unless celluloid_running\n end",
"def ready?\n QA::Runtime::Logger.debug 'Checking Smocker readiness'\n get(\"#{admin_url}/version\")\n true\n # rescuing StandardError because RestClient::ExceptionWithResponse isn't propagating\n rescue StandardError => e\n QA::Runtime::Logger.debug \"Smocker not ready yet \\n #{e}\"\n false\n end",
"def precheck\n if !BinarySolo.dir_valid?\n puts \"this is not a binary_solo directoy => better run $ binarysolo init\".colorize(:red)\n false\n elsif !BinarySolo.config_valid?\n puts \"your config is invalid - but I dont have any details for you (yet)\".colorize(:red)\n false\n else\n true\n end\nend",
"def confirm_or_prompt_for_system_requirements\n generate_generatable_options\n validate_root_dns_maps_to_core_ip\n ensure_security_group_prepared\n validate_compute_flavor(core_server_flavor)\n admin_emails\n confirm_or_upload_release\n confirm_or_upload_stemcell\n end",
"def setup\n return if resolved_model_definitions.present?\n @is_rake_task = false\n @is_rake_association_task = false\n @warnings = nil\n @log = false\n @log_clean = false\n check_rake_task\n @resolved_model_definitions = resolve_model_definition_classes_and_values\n end",
"def table_exists?\n @table_exists ||= {}\n @table_exists[current_site] ||= ActiveRecord::Base.connection.table_exists?(@model.table_name)\n end",
"def check_set_up(privileges)\n privileges.keys.each{|action| check_assertion(privileges[action]) }\n end",
"def do_setup \n config = self.config\n host = config['app']['host']\n port = config['app']['port']\n @url_base = \"http://#{host}:#{port}\"\n puts config.inspect\n @pcap_dir = config.fetch 'pcap_dir'\n @index_dir = config.fetch 'index_dir'\n\n # Extract test pcaps and indexes\n FileUtils.rm_rf '/tmp/pcapr_local_test'\n FileUtils.mkdir_p @pcap_dir\n FileUtils.mkdir_p @index_dir\n\n\n # Recreate test database.\n begin\n couch = config['couch']\n RestClient.delete \"#{couch['uri']}/#{couch['database']}\"\n rescue RestClient::ResourceNotFound\n end\n db = @db = PcaprLocal.get_db(config)\n end",
"def setup_done?\n Pillar.exists? pillar: Pillar.all_pillars[:apiserver]\n end",
"def initialized?\n server.present? && username.present? && api_token.present?\n end",
"def verify_systems\n config_systems.each do |system|\n verify system: system\n end\n end",
"def requires_user_existence!\n if not e.user_exists?\n error \"You have to setup your user before you can perform this action.\"\n exit\n end\n end",
"def verify_root\r\n if !User.root\r\n raise ApplicationSetupError, \"\\n\\n**Error: No root user exists! Please run 'rake setup RAILS_ENV=#{$tmp_env}' to create the root user.**\\n\\n\\n\"\r\n end\r\n end",
"def ensure_database\n unless File.exist?(\"./items.csv\")\n puts \"Restoring items database.\"\n update_database\n end\n end",
"def table_exists?\n db.table_exists?(table_name)\n end",
"def check_sanity\n errors = []\n [:site, :uri, :user, :password, :confdir].each do |sym|\n if @config[sym].nil?# or @config[sym].empty?\n errors << \"Option '#{sym}' is required\"\n end\n end\n unless errors.empty?\n $stderr.puts 'ERROR: The following problems were detected:'\n errors.map { |e| $stderr.puts \" * #{e}\" }\n $stderr.puts \"\\nConfiguration options:\\n\"\n ap @config\n exit 1\n end\n end",
"def setup_environment; end",
"def site_setup\n # Get site\n site = Nanoc3::Site.new('.')\n\n # Set up data sources\n site.data_sources.each do |data_source|\n data_source.loading { data_source.setup }\n end\n end"
] |
[
"0.7000241",
"0.639725",
"0.62109065",
"0.61498785",
"0.6081087",
"0.59626234",
"0.59558016",
"0.59019995",
"0.59019995",
"0.5891363",
"0.58892536",
"0.58763915",
"0.586858",
"0.5817226",
"0.5798799",
"0.5797024",
"0.57703197",
"0.5764787",
"0.57598954",
"0.5753579",
"0.5752817",
"0.5718438",
"0.571054",
"0.5695412",
"0.564523",
"0.5633238",
"0.5630595",
"0.5628326",
"0.5615272",
"0.5586627",
"0.55465436",
"0.5545553",
"0.5537958",
"0.55348",
"0.55147314",
"0.54800034",
"0.5479547",
"0.5472681",
"0.5468727",
"0.5449661",
"0.5435633",
"0.54334533",
"0.5420847",
"0.5420134",
"0.5415293",
"0.5413977",
"0.5404133",
"0.5394112",
"0.5388605",
"0.5374597",
"0.5371885",
"0.536531",
"0.5362051",
"0.5362051",
"0.5355138",
"0.53489166",
"0.53276765",
"0.53271884",
"0.53094953",
"0.5300696",
"0.5299848",
"0.5297777",
"0.528942",
"0.527744",
"0.52774334",
"0.5273658",
"0.52660376",
"0.5258746",
"0.5256213",
"0.52553153",
"0.5254186",
"0.5246801",
"0.5244916",
"0.52426684",
"0.5241177",
"0.524085",
"0.5236642",
"0.5236296",
"0.52308357",
"0.52308017",
"0.5230124",
"0.52213484",
"0.521678",
"0.519868",
"0.51907486",
"0.51879185",
"0.51808774",
"0.5178885",
"0.51717466",
"0.51680225",
"0.51591796",
"0.51443845",
"0.51404923",
"0.51319796",
"0.51279086",
"0.5125653",
"0.51244295",
"0.5122547",
"0.51150906",
"0.5114366"
] |
0.7547931
|
0
|
get all repositories TODO: get this somehow in line with using the Searchable module
|
def index
@criteria = {}
@criteria['sort'] = repositories_sort_by
# let's not include any 0-collection repositories unless specified
# include_zero = (!params.blank? && params['include_empty'])
# ok, page sizing is kind of complicated if not including zero counts
page_size = params['page_size'].to_i if !params.blank?
page_size = AppConfig[:pui_search_results_page_size] if page_size == 0
query = 'primary_type:repository'
facets = find_resource_facet
page = params['page'] || 1 if !params.blank?
@criteria['page_size'] = 100
@search_data = archivesspace.search(query, page, @criteria) || {}
@json = []
if !@search_data['results'].blank?
@pager = Pager.new("/repositories?", @search_data['this_page'], @search_data['last_page'])
@search_data['results'].each do |result|
hash = ASUtils.json_parse(result['json']) || {}
id = hash['uri']
if !facets[id].blank?
hash['count'] = facets[id]
@json.push(hash)
end
end
else
raise NoResultsError.new("No repository records found!")
end
@page_title = I18n.t('list', {:type => (@json.length > 1 ? I18n.t('repository._plural') : I18n.t('repository._singular'))})
render
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def get_repositories\n get(\"#{url_base}/repositories?#{dc}\")[\"data\"]\n end",
"def repositories\n response = self.class.get('/repositories').body\n JSON.parse(response)\n end",
"def repositories\n # TODO : merge with current data\n load_repos\n end",
"def repositories\n\t\t\telems = []\n\t\t\tget_resource_link(:datacenterrepositories, \"datacenterRepositories\", \"datacenterRepository\").each do |data|\n\t\t\t\telems << Repository.new(data)\n\t\t\tend\n\t\t\telems\n\t\tend",
"def find_repositories\n @repos = GithubApi.call :repos\n end",
"def get_repos\n @api.list_repositories\n end",
"def repositories\n client.repositories(user_repo, @options)\n end",
"def list_repositories\n JSON.parse(request(:get, ''))\n end",
"def get_repos\n # using oauth token to increase limit of request to github api to 5000\n client = Octokit::Client.new :access_token => self.github_token\n (client.repositories self.github_name, {:type => 'all'}).map do |repo|\n repo.full_name\n end\n end",
"def repos\n client.repos({}, query: { sort: \"asc\" })\n end",
"def all_repos\n\t\tif GitHosting.multi_repos?\n\t\t repositories\n\t\telse\n\t\t [ repository ].compact\n\t\tend\n\t end",
"def list\n @repos\n end",
"def repositories\n @repositories ||= (organization.exists? ? organization.repositories : client.list_repositories)\n end",
"def all\n repos = self.class.load_json(repos_url)\n repos.map! { |repo| self.class.filter_repo_info(repo) }\n self.class.slice_in(repos, 3)\n end",
"def repos(*args)\n params = arguments(args, required: [:q]).params\n params['q'] ||= arguments.q\n\n get_request('/search/repositories', arguments.params)\n end",
"def repositories\n octokit.repositories('zold-io').map { |json| json['full_name'] }\n end",
"def repos\n @repos ||= get(\"/repos/show/#{login}\")['repositories'].map { |r| Repo.new(connection, r) }\n end",
"def get_repos\n\t\t@repos = Repo.all\n\tend",
"def all_repos\n if GitHosting.multi_repos?\n repositories\n else\n [ repository ].compact\n end\n end",
"def list_repos\n repos = []\n end_cursor = nil\n\n data = get_repos(end_cursor)\n repos = repos + data.fetch(\"nodes\")\n next_page = data.dig(\"pageInfo\", \"hasNextPage\")\n end_cursor = data.dig(\"pageInfo\", \"endCursor\")\n\n while next_page do\n data = get_repos(end_cursor)\n repos = repos + data.fetch(\"nodes\")\n next_page = data.dig(\"pageInfo\", \"hasNextPage\")\n end_cursor = data.dig(\"pageInfo\", \"endCursor\")\n end\n\n repos.reject { |r| r.dig(\"isArchived\") || r.dig(\"isDisabled\") }\n end",
"def get_list\n @list_of_repos\n end",
"def repos\n @repos ||= OY.repos\n end",
"def acquire_repo_list\n set_auth\n set_github_repo_name\n repo_list = []\n (@github.repos.list org: GITHUB_ORG).each do |l|\n repo_list << l[:name]\n end\n repo_list\nend",
"def get_all_user_repos\n user = User.find_by(uuid: params[:uuid])\n\n client = Octokit::Client.new(:access_token => user.password)\n repo_list = []\n client.repositories(:user => user.gh_username).each { |repo|\n repo_list.push(repo.name)\n }\n render :json => {:repos => repo_list}\n end",
"def get_my_repos\n repos = []\n\n (1..get_total_repo_pages_count.to_i).each do |index|\n get_json( \"#{ GITHUB_USER_REPOS_URL }?per_page=100&page=#{ index }\" ).each do |item|\n repos << item[ 'full_name' ]\n end\n end\n\n return repos\nend",
"def repositories_to_fetch\n # Find all .git Repositories - Ignore *.wiki.git\n repos = Dir.glob(\"#{@config['git']['repos']}/*/*{[!.wiki]}.git\")\n\n # Build up array of NOT ignored repositories\n delete_path = []\n @config['ignore'].each do |ignored|\n path = File.join(@config['git']['repos'], ignored)\n delete_path += repos.grep /^#{path}/\n repos.delete(delete_path)\n end\n\n return repos - delete_path\n\n end",
"def repos\n api.repos.map(&:to_hash)\n end",
"def repositories\n Repositories.instance\n end",
"def find_repos(user)\n user.repos\n end",
"def repositories\n opts[:repositories]\n end",
"def get_repos\n\t\trepo_list = []\n\t\tparsed_config = begin\n\t\t\tYAML.load(File.open(@path_to_config_yml))\n\t\trescue ArgumentError => e\n \t\t\tputs \"Could not parse YAML: #{e.message}\"\n\t\tend\n\t\tparsed_config['sections'].each do |section|\n\t\t\trepo_list.push(section['repository']['name'].gsub(/\\w*-?\\w*\\//,''))\n\t\tend\n\t\trepo_list.sort\n\tend",
"def repos\n pry(Git::Multi.repositories)\nend",
"def repositories\n [ repository ].to_set + @properties.keys.map { |repository_name| DataMapper.repository(repository_name) }\n end",
"def list_repositories\n return static_list_repositories if false\n super.select do |repo|\n sleep 1\n begin\n github[\"repos/#{repo['full_name']}/contents/.dockstore.yml\"].head\n sleep 1\n rescue RestClient::NotFound\n output.puts \"No .dockstore.yml found in #{repo['full_name']}, skipping\"\n end\n end\n end",
"def repos\n @client.repos.all.collect(&:clone_url)\n end",
"def index\n @repositories = Repository.all\n end",
"def repos\n @repos ||= (user_repos + org_repos).flatten\n end",
"def org_repos\n @org_repos ||= (\n talk 'org repos'\n logins = orgs.map { |org| org[:login] }\n\n logins.map do |login|\n talk \"repos for #{login}\"\n client.organization_repositories login.to_s\n end.flatten\n )\n end",
"def find_all_organizations\n get_url(\"https://api.github.com/users/#{current_user.username}/orgs\")\n end",
"def list\n @connection.get('/user/repos').map do |repo_data|\n Rails.logger.info \"listing repos\"\n GitHubApi::Repo.new(self, repo_data)\n end\n end",
"def repos(opts={ push: false, details: false, orgs: true })\n repos = @client.repositories.map {|repo| parse_repo repo}\n @client.organizations.each do |org|\n repos += @client.organization_repositories(org.login).map {|repo| parse_repo repo}\n end\n repos.reject! {|repo| !repo[:push]} if opts[:push]\n repos.map { |repo| repo[:full_name] } unless opts[:details]\n end",
"def get_repos_by_orga(orga) \n\t\treturn self.fetch(\"repos?owner_name=#{orga}\")\n\tend",
"def filterRepositories\n\tEnumerator.new { |repos|\n\t\twhile (gets)\n\t\t\trepo = Repo.new\n\t\t\t$_.sub!(/\\(via.*?\\)/, '') # Remove 'via' annotation in line.\n\t\t\trepo.name, repo.type, repo.url = $_.split(/\\s+/)\n\t\t\t\n\t\t\trepo.score = 0\n\t\t\t\n\t\t\trepos << repo\n\t\tend\n\t}.group_by{|repo| repo.name}.values.each{|repoList|\n\t\tprintBest repoList\n\t}\nend",
"def all\n return @raw_repos unless @raw_repos.empty?\n return [Template.root.basename.to_s] if Template.project?\n Template.root.join(Meta.new({}).repos_dir).children.map do |path|\n path.basename.to_s\n end\n\n rescue Errno::ENOENT\n then raise(\n Error::RepoNotFound\n )\n end",
"def search_repos\n @current_user ||= User.find(session[:user_id]) if session[:user_id]\n @client = Octokit::Client.new(:access_token => @current_user.token)\n\n # search repos using user query\n repos = @client.search_repositories(\"ember\")\n\n @json = repos.items.map do |repo|\n nhash = repo.to_hash\n nhash\n end\n\n respond_to do |format|\n format.json {\n render json: @json.to_json, status: 200\n }\n end\n end",
"def get_repos\n begin\n @repos ||= github_api_setup.repos.list\n rescue Exception => e\n logger.error \"Github #get_repos error #{e}\"\n end\n end",
"def index\n if (params[:search]) && (params[:search].empty? == false) \n urlformated = URI.encode(params[:search])\n uri = URI.parse(\"https://api.github.com/legacy/repos/search/#{urlformated}\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = (uri.scheme == 'https')\n \n \n request = Net::HTTP::Get.new(uri.request_uri)\n \n res = http.request(request)\n response = JSON.parse(res.body)\n \n\n repository = response['repositories'].map {|rd|\\\n GithubRepository.new( rd['owner'], rd['name'],\\\n rd['description'], rd['language'], rd['url'])} \n \n @github_repositories = repository\n else\n @github_repositories = nil\n end \n end",
"def repos(*args)\n params = args.extract_options!\n normalize! params\n assert_required_keys %w[ keyword ], params\n\n get_request(\"/legacy/repos/search/#{params.delete('keyword')}\", params)\n end",
"def all\n storage.map(&:repository)\n end",
"def get_repo_list(token, user)\n query = %{\n query ($user: String!, $cursor: String) {\n user(login: $user) {\n repositories(first: 100, after: $cursor) {\n edges {\n node {\n name\n owner {\n login\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n\n vars = { user: user, cursor: nil }\n\n repos = []\n\n loop do\n result = Github.query(token, query, vars)\n repos += result.dig(\"data\", \"user\", \"repositories\", \"edges\") || []\n break unless result.dig(\"data\", \"user\", \"repositories\", \"pageInfo\", \"hasNextPage\")\n vars[:cursor] = result.dig(\"data\", \"user\", \"repositories\", \"pageInfo\", \"endCursor\")\n end\n\n repos.map { |e| { owner: e.dig(\"node\", \"owner\", \"login\"), name: e.dig(\"node\", \"name\") } }\nend",
"def static_list_repositories\n %w[https://github.com/iwc-workflows/sars-cov-2-variation-reporting.git\n https://github.com/iwc-workflows/sars-cov-2-pe-illumina-artic-variant-calling.git\n https://github.com/iwc-workflows/sars-cov-2-ont-artic-variant-calling.git\n https://github.com/iwc-workflows/sars-cov-2-se-illumina-wgs-variant-calling.git\n https://github.com/iwc-workflows/sars-cov-2-pe-illumina-wgs-variant-calling.git\n https://github.com/iwc-workflows/parallel-accession-download.git\n https://github.com/iwc-workflows/sars-cov-2-consensus-from-variation.git\n https://github.com/iwc-workflows/sars-cov-2-pe-illumina-artic-ivar-analysis.git\n https://github.com/iwc-workflows/fragment-based-docking-scoring.git\n https://github.com/iwc-workflows/protein-ligand-complex-parameterization.git\n https://github.com/iwc-workflows/gromacs-mmgbsa.git\n https://github.com/iwc-workflows/gromacs-dctmd.git].map { |r| { 'clone_url' => r }}\n end",
"def index\n @repos = Repo.all\n end",
"def index\n @public_repositories = PublicRepository.all\n end",
"def gl_repos\n all_repos.select{|x| x.is_a?(Repository::Git)}\n end",
"def repositories\n Repository.where(user_id: group_ids).or(membered_repositories).order(\"updated_at desc\")\n end",
"def list_all_registered_repos\n data, code = get_json(@all_repos_path)\n return data,code\n end",
"def get_app_repositories\n json_response = @client.list_installation_repos\n\n repository_list = []\n if json_response.count > 0\n json_response[\"repositories\"].each do |repo|\n repository_list.push(repo[\"full_name\"])\n end\n else\n puts json_response\n end\n\n repository_list\nend",
"def get_repos\n\t\tif current_user.nil?\n\t\t\t@repos = Repo.where(:user_id => nil)\n\t\telse\n\t\t\t@repos = current_user.repos\n\t\tend\n\tend",
"def index\n @title = 'Repositories'\n @repositories = Repository.includes(:leaks).all.order(:url).page params[:page]\n end",
"def repositories_for(multi_repo = nil)\n case (owner = superproject = full_names = multi_repo)\n when nil\n repositories # all of them\n when Array\n repositories.find_all { |repository|\n full_names.include?(repository.full_name)\n }\n when *USERS, *ORGANIZATIONS\n repositories.find_all { |repository|\n repository.owner.login == owner\n }\n when *SUPERPROJECTS\n repositories_for(full_names_for(superproject))\n else\n raise ArgumentError, multi_repo\n end\n end",
"def fetch_repositories(repos = nil)\n # Init git settings\n Git.configure do |config|\n config.binary_path = \"#{@config['git']['path']}\"\n end\n @return_repos = []\n # Loop through repos and fetch it\n repos_to_fetch = repos.nil? ? self.repositories_to_fetch : repos\n repos_to_fetch.each do |repo|\n if File.directory?(repo)\n # Get branches\n g = Git.bare(\"#{repo}\", :log => @log)\n g.remotes.each do |remote|\n # Determine which \"remote\" to fetch e.g. \"git fetch github\"\n if @config['provider'].include?(\"#{remote}\")\n @log.info(\"Fetching remote #{remote} in #{repo}\")\n g.remote(remote).fetch\n @return_repos << repo\n end\n end\n end\n end\n @return_repos\n end",
"def getprojects()\n printRepoHeader\n \n loop do\n # Print each of the new returned repositories\n begin\n get.each do |repo|\n printRepo(repo) if (@slugs.add?(repo['slug']))\n\n # Flush to prevent data loss if we crash\n STDOUT.flush\n end\n rescue Exception => msg\n STDERR.puts \"WARNING: Poll failed at #{Time.now}\"\n STDERR.puts msg\n end\n\n # Poll every 5 minutes\n sleep 300\n end\n end",
"def repos\n ReposAPI.new(self)\n end",
"def team_repositories\n team_profiles.map(&:repositories).flatten\n end",
"def find_repositories\n project = find_project\n repositories = git_repositories(project)\n\n # if a specific repository id is passed in url parameter \"repository_id\",\n # then try to find it in the list of current project repositories and use\n # only this and not all to pull changes from (issue #54)\n if params.key?(:repository_id)\n param_repo = repositories.select do |repo|\n repo.identifier == params[:repository_id]\n end\n\n if param_repo.nil? || param_repo.length == 0\n logger.info {\n \"GithubHook: The repository '#{params[:repository_id]}' isn't \" \\\n \"in the list of projects repos. Updating all repos instead.\"\n }\n\n else\n repositories = param_repo\n end\n end\n\n repositories\n end",
"def index\n @repositories = Repository.all\n @path_repos = request.path.starts_with? '/repos'\n end",
"def repositories_with_pull_requests(reponames = [])\n repositories = []\n page = 1\n loop do\n repositories_in_page = load_repos_in_page(page)\n break if repositories_in_page.empty?\n repositories.concat(repositories_in_page)\n page += 1\n end\n repositories.select! { |repo| reponames.include?(repo.name) } unless reponames.empty?\n repositories.select!(&:any_pull_requests?)\n repositories\n end",
"def get_repo_users\n repo_users = Array.new\n github = Github.new :oauth_token => github_token\n\n github.repos.list.body.each do |repo|\n repo_users << repo[\"owner\"][\"login\"]\n end\n\n repo_users\n end",
"def public_repositories\n raw_repos = GitHub::API.json(\"/organizations/#{self.login}/public_repositories\")['repositories']\n repos = []\n\n raw_repos.each do |repo|\n repos << GitHub::Repository.new(repo)\n end\n\n return repos\n end",
"def get_repo_names github_username , git_token\n\n Rails.cache.fetch(\"#{self.id}/repo_names\", expires_in: 6.hours) do\n repo_names = Array.new\n github = Github.new :oauth_token => git_token\n\n github.repos.list.body.each do |repo|\n if github_username == repo[\"owner\"][\"login\"]\n repo_names << { :user=>github_username ,:repo=>repo[\"name\"]}\n end\n end\n\n orgs_names = Array.new\n github.orgs.list.each do |org|\n orgs_names << org[\"login\"]\n end\n\n orgs_names.each do |oname|\n url = \"orgs/\"+oname+\"/repos\"\n \n github.get_request(url,Github::ParamsHash.new({})).each do |orepo|\n if oname == orepo[\"owner\"][\"login\"]\n repo_names << { :user=>oname ,:repo=>orepo[\"name\"]}\n end\n end\n end\n repo_names\n end\n end",
"def get_public_repos(user_name)\n get(\"/users/#{user_name}/repos\")\n end",
"def get_repos project_id\n $logger.info \"Getting repos\"\n\n # from the bitbucket api\n rest_endpoint = \"/rest/api/1.0/projects/#{PROJECT_ID}/repos\"\n\n http = Net::HTTP.new(BASE_GIT_URL, BASE_GIT_PORT)\n repos_request = Net::HTTP::Get.new(\"/rest/api/1.0/projects/#{PROJECT_ID}/repos?limit=1000\")\n repos_request.basic_auth GIT_USER, GIT_PASSWORD\n repos_response = http.request(repos_request)\n repos_response.value\n\n # https://confluence.atlassian.com/bitbucket/what-is-a-slug-224395839.html\n repos_body = JSON.parse(repos_response.body)\n repos = repos_body['values'].map { |v| v['slug'] }\n\n $logger.info \"Found repos #{repos}\"\n\n return repos\nend",
"def index\n @repositories = policy_scope(Repository)\n @team_repositories = Repository\n .joins(namespace: { team: :users })\n .where(\"users.id = :user_id\", user_id: current_user.id)\n @other_repositories = @repositories - @team_repositories\n @team_repositories_serialized = API::Entities::Repositories.represent(\n @team_repositories,\n current_user: current_user,\n type: :internal\n ).to_json\n @other_repositories_serialized = API::Entities::Repositories.represent(\n @other_repositories,\n current_user: current_user,\n type: :internal\n ).to_json\n end",
"def repos\n super.sort\n end",
"def each_repository(&block)\n repositories.values.each(&block)\n end",
"def find_repos\n @current_user ||= User.find(session[:user_id]) if session[:user_id]\n @client = Octokit::Client.new(:access_token => @current_user.token)\n\n # get user input from API\n user_input_string = request.params[:_json]\n input_arr = user_input_string.gsub(/\\s+/, \"\").split(\",\")\n\n # search repos using user input\n repoids = input_arr.map do |input|\n repo = @client.repository(input)\n \"#{repo.to_hash[:id]}\"\n end\n\n # Save user search input and repos to UserPreference\n @current_user.UserPreference.search_input = user_input_string\n @current_user.UserPreference.repos = repoids.join(\",\")\n @current_user.UserPreference.save\n\n respond_to do |format|\n format.json {\n render json: repoids.to_json, status: 200\n }\n end\n end",
"def index\n @git_hub_repos = GitHubRepo.all\n end",
"def fetch_syncables\n gh_client.repos.list.select{|repo| repo.permissions.admin}.map(&:full_name)\n end",
"def repos(config_hash)\n if config_hash[\"organizations\"]\n repos = []\n config_hash[\"organizations\"][\"orgs\"].each do |org|\n # grab all the full repo names in this org. If no type is specified use public and also skip the forks\n # we also skip anything in the blacklist array\n repos << github.org_repos(org, type: config_hash[\"organizations\"][\"type\"] || \"public\")\n .collect { |x| x[\"full_name\"] unless x[\"fork\"] || x[\"archived\"] || (config_hash[\"organizations\"][\"blacklist\"] && config_hash[\"organizations\"][\"blacklist\"].include?(x[\"full_name\"])) }\n end\n repo_list = repos.flatten.compact.sort # return a single sorted array w/o nils\n puts \"Based on the provided org(s) (#{config_hash[\"organizations\"][\"orgs\"].join(',')}) managing the following repos: #{repo_list.join(', ')}\"\n repo_list\n elsif config_hash[\"repositories\"]\n config_hash[\"repositories\"]\n else\n puts \"Config does not include either 'repositories' or 'organizations' sections. Cannot continue!\"\n exit!\n end\nend",
"def index\n @repositories = Repository.all\n\n respond_with(@repositories)\n end",
"def display_org_repos(org)\n repos = Commitchamp::Repo.where(organization: org).order(name: :asc)\n puts \"\\n## Repositories for Organization: #{org}\"\n repos.each do |r|\n puts \"#{r.name}\"\n end\n end",
"def do_your_stuff! organization_name\n get_members_for_org organization_name\n get_repositories_for_all_members\n get_stats_for_repositories\n end",
"def projects_with_repository_enabled\n Project.has_module(:repository).find(:all, :include => :repository, :order => 'identifier')\n end",
"def get_repositories(opts = {})\n data, _status_code, _headers = get_repositories_with_http_info(opts)\n data\n end",
"def search_repo(query)\n repos = load_and_cache_user_repos\n results = repos.select do |repo|\n repo['name'] =~ Regexp.new(query, 'i')\n end\n results += search_all_repos(query) if query =~ %r{\\/}\n results.uniq\n end",
"def display_repository\n return [_('None specified')] unless @research_output.repositories.any?\n\n @research_output.repositories.map(&:name)\n end",
"def get_repos(neo)\n\n\t# return repo's that have more than 1 connection\n\t# TODO: try this; n<-r[follows*2..]-m\n\tcypher_query = ' START n = node:nodes_index(type = \"repo\")'\n\tcypher_query << ' MATCH n<-[r:follows]-m'\n\tcypher_query << ' WITH n, count(m) AS follow_count'\n\tcypher_query << ' WHERE follow_count > 2'\n\tcypher_query << ' RETURN ID(n), n.name, follow_count'\n\tcypher_query << ' ORDER BY ID(n)'\n\tneo.execute_query(cypher_query)['data']\n\nend",
"def index\n @orgs ||= Github::Org.orgs(\n current_user_github_access_token,\n current_github_username\n )\n end",
"def index\n @repositories = @project.repositories.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @repositories }\n end\n end",
"def list_repos(org_login)\n @connection.get(\"/orgs/#{org_login}/repos\").map do |repo_data|\n GitHubApi::Repo.new(@connection.repos, repo_data)\n end\n end",
"def user_repos\n @user_repos ||= (\n talk 'user repos'\n client.repos\n )\n end",
"def get_repo_list(ssh: false)\n CSV.generate do |csv|\n self.groupings.includes(:group).each do |grouping|\n group = grouping.group\n data = [group.group_name, group.repository_external_access_url]\n data << group.repository_ssh_access_url if ssh\n csv << data\n end\n end\n end",
"def packages\n packages = []\n @repositories.each do |repo|\n repo_packages = repo.packages\n repo_packages.map { |p| packages.push(p) } unless repo_packages.empty?\n end\n packages\n end",
"def repos(name=nil, params={})\n params = name if name.is_a?Hash\n prefix = name.is_a?(String) ? \"./repos/#{self[\"login\"]}/#{name}\" : \"#{path_prefix}/repos\" \n Ghee::API::Repos::Proxy.new(connection,prefix, params)\n end",
"def [](name)\n repositories.fetch(name)\n end",
"def all(slug = @curry_with[0])\n response = @connection.get(\"/repos/#{slug}/pulls\", per_page: 100)\n PullRequest.parse(@connection, response.body)\n end",
"def repo\n @repository\n end",
"def get_repo_list\n Chef::Log.debug(\n \"Fetching all versions of #{new_resource.module_name} \" +\n \"from #{new_resource.repository}.\",\n )\n latest = powershell_out!(\n <<-EOH,\n $splat = @{\n Name = \"#{new_resource.module_name}\"\n Repository = \"#{new_resource.repository}\"\n AllVersions = $True\n }\n (Find-Module @splat).Version.ForEach({$_.ToString()})\n EOH\n ).stdout.to_s.chomp.split(\"\\r\\n\")\n Chef::Log.debug(\"Available versions: #{latest.join(', ')}\")\n\n return latest.map { |v| Gem::Version.new(v) }\n end",
"def watched_repos\n @repos ||= get(\"/repos/watched/#{login}\")['repositories'].map { |r| Repo.new(connection, r) }\n end",
"def chunked_repo_sets \n all_repositories = Dir.entries(OBSERVATIONS_DIR).select{|x| x != '.' && x != '..' && x != '.DS_Store'}.map{|x| \"#{OBSERVATIONS_DIR}/\" + x}\n stride = 500\n start_i = 0\n end_i = stride - 1\n repo_count = all_repositories.size\n repo_sets = Array.new\n while start_i < repo_count do\n end_i = repo_count - 1 if end_i >= repo_count\n next_set = all_repositories[start_i..end_i]\n repo_sets << next_set\n start_i = end_i + 1\n end_i += stride\n end\n repo_sets\nend",
"def get_repo (repoName='ComputerScience_test')\n puts \"get_repo\"\n set_repository repoName\n puts \"set_repository #{@repository}\"\n result = @repository.query.perform \"select ?s ?p ?o {?s ?p ?o} order by ?s\"\n #puts \"@repository.query.perform #{result}\"\n \n graph = RDF::Graph.new(\"http://ninjalearning.info:8080/repositories/ComputerScience_test\") # TODO: repo name, host, port, ...\n \n result['values'].each do |triple|\n graph << RDF::Statement.new(\n RDF::URI.new(triple[0]),\n RDF::URI.new(triple[1]),\n RDF::URI.new(triple[2]),\n )\n end\n graph\n end"
] |
[
"0.814363",
"0.8037317",
"0.7947352",
"0.7901802",
"0.7874824",
"0.7850466",
"0.7836493",
"0.78187156",
"0.7746905",
"0.76963997",
"0.76888",
"0.7649038",
"0.7593359",
"0.75741094",
"0.75416505",
"0.7531467",
"0.75255126",
"0.7510282",
"0.74784523",
"0.7455886",
"0.7341373",
"0.73383975",
"0.7329915",
"0.7327602",
"0.72912616",
"0.7283304",
"0.72302586",
"0.72255856",
"0.7211695",
"0.72002697",
"0.718333",
"0.7141668",
"0.71378905",
"0.7120703",
"0.71014714",
"0.70954067",
"0.70848036",
"0.70845294",
"0.7082578",
"0.7078087",
"0.699932",
"0.6993282",
"0.6988594",
"0.6978094",
"0.6950686",
"0.6933172",
"0.69271165",
"0.6925843",
"0.6909382",
"0.690354",
"0.6847444",
"0.6795495",
"0.6767204",
"0.6761657",
"0.6741832",
"0.6698582",
"0.6697739",
"0.66956973",
"0.669171",
"0.6658214",
"0.6646019",
"0.6639566",
"0.6634986",
"0.6632954",
"0.6630214",
"0.6618892",
"0.661802",
"0.65894943",
"0.6589362",
"0.65761876",
"0.6573165",
"0.65271664",
"0.6523752",
"0.6511554",
"0.6501949",
"0.6496077",
"0.6477545",
"0.6465186",
"0.64622957",
"0.64527065",
"0.63866866",
"0.63573533",
"0.634772",
"0.6330849",
"0.6328022",
"0.632062",
"0.6302459",
"0.6291964",
"0.62901926",
"0.62763757",
"0.62729657",
"0.62722087",
"0.626051",
"0.6254441",
"0.62271386",
"0.622502",
"0.62235695",
"0.6219346",
"0.62191653",
"0.62144804",
"0.6212724"
] |
0.0
|
-1
|
get counts of various records belonging to a repository
|
def get_counts(repo_uri)
types = %w(pui_collection pui_archival_object pui_record_group pui_accession pui_digital_object pui_agent pui_subject)
counts = archivesspace.get_types_counts(types, repo_uri)
# 'pui_record' as defined in AppConfig ('record_badge') is intended for archival objects only,
# which in solr is 'pui_archival_object' not 'pui_record' so we need to flip it here
counts['pui_record'] = counts.delete 'pui_archival_object'
final_counts = {}
counts.each do |k, v|
final_counts[k.sub("pui_", '')] = v
end
final_counts['resource'] = final_counts['collection']
final_counts['classification'] = final_counts['record_group']
final_counts
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def count\n size = 0\n core_search.group(\"name.id, #{main_group_by_columns}\").each do |_x|\n size += 1\n end\n size\n end",
"def project_counts\n @project_counts ||= Kithe::Model.joins(:contains_contained_by).\n where(published: true, contains_contained_by: {container_id: project_list.collect(&:id) }).\n group(:container_id).\n count\n end",
"def get_counts_for_all_entities\n @tracker.counts\n end",
"def total_repo_count\n repositories.length\n end",
"def count\n filtered = apply_criteria(@data)\n filtered.count\n end",
"def count_records **args\n logger.progname = 'RestOperations#CountRecords'\n query = OrientSupport::OrientQuery.new args\n \tquery.projection << 'COUNT (*)'\n \tresult = get_records raw: true, query: query\n begin\n result.first['COUNT']\n rescue\n return 0\n end\n end",
"def count **args\n\t\tquery( **( { projection: 'COUNT(*)' }.merge args )).execute(reduce: true){|x| x[:\"COUNT(*)\"]}\n end",
"def count_records(records)\n records.count(:all)\n end",
"def count **args\n logger.progname = 'RestOperations#CountRecords'\n query = OrientSupport::OrientQuery.new args\n query.projection << 'COUNT (*)'\n result = get_records raw: true, query: query\n result.first['COUNT'] rescue 0 # return_value\n end",
"def counts\r\n @counts\r\n end",
"def records_total_count\n fetch_records.unscope(:group, :select).count(:all)\n end",
"def count_records(params)\n scope_data_class(params) do\n params[:scope] = config[:scope]\n data_adapter.count_records(params, final_columns)\n end\n end",
"def count\n all.count\n end",
"def count(constraints = {})\n query(constraints).count\n end",
"def counts(options = {})\n find(:all, options_for_counts(options))\n end",
"def get_entity_count(type)\n @tracker.count(type)\n end",
"def count\n query.count\n end",
"def count\n query.count\n end",
"def count\n return @@all\n end",
"def records_total_count\n Rails.cache.fetch('raw_count') { get_raw_records.count(:all) }\n end",
"def count\n @count ||= @query.count\n end",
"def projects_count\n ProjectDetail.all.count\n end",
"def objects_count\n obj_count = {total_count: Building.count, building_complexes_count: BuildingComplex.count, apartments_count: Apartment.count, penthouses_count: Penthouse.count, apartment_houses_count: ApartmentHouse.count}\n render json: obj_count\n end",
"def company_count\n return 0 unless answer_id\n Card.search left_id: answer_id,\n right: { type_id: WikirateCompanyID },\n return: :count\nend",
"def count\n folder.data_objects.all(parameters).count\n end",
"def count\n Driver.client[coll_name].find.count\n end",
"def count\n @all.size\n end",
"def count\n\n Sizetype.find_all_by_godown_id_and_company_id(1,1).each do |h|\n unless h.quantity.nil?\n @count += h.quantity\n end\n end \n end",
"def find_count(filters, opts = {})\n return super(filters, opts) unless should_query?(filters)\n return 0 if filters.values.any?(&:nil?)\n apply_scopes(filters, opts).total_count\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def set_type_counts\n vars = \"\"\n Repo::REPO_TYPES.each do |t|\n vars << \"@#{t}_count = #{t.camelize.constantize}.count;\"\n end\n eval(vars)\n end",
"def count\n Project.count\n end",
"def count\n @options[:select] = \"COUNT\"\n @options.delete(:attributes_to_get)\n\n response = run\n\n while continue?(response)\n @options[:exclusive_start_key] = response.last_evaluated_key\n response = run(response)\n end\n\n response.count\n end",
"def count\n @count\n end",
"def status_counts\n counts = Array.new\n\n if @db != nil\n is_ok = false\n\n begin\n stm = @db.prepare( 'SELECT qStatus, COUNT( qStatus ) As qCount FROM qryResults GROUP BY qStatus ORDER BY qStatus')\n rs = stm.execute\n\n rs.each do |row|\n result = { 'status' => row['qStatus'], 'count' => row['qCount'] }\n counts.push result\n end\n\n stm.close\n is_ok = true\n rescue ::SQLite3::Exception => e\n Maadi::post_message(:Warn, \"Repository (#{@type}:#{@instance_name}) encountered an SELECT Status Code Counts error (#{e.message}).\")\n end\n end\n\n return counts\n end",
"def count\n @collection.count(Scope.new(@collection, @selector, @opts))\n end",
"def count\n end",
"def count\n end",
"def records_count\n @klass.all.size\n end",
"def count(options = {})\n @owner.ids_for_outbound(@reflection.options[:property]).size\n end",
"def calculate_count _changed_card=nil\n ids = left.related_companies\n update_topic_company_cached_count ids.size\n result = {}\n ids.each do |company_id|\n result[company_id] = true unless result.key?(company_id)\n end\n result.to_json\nend",
"def query_7\n document_ids = Perpetuity[Document].select {|document| document.id}.to_a\n return document_ids.size\nend",
"def count\n resource = @client.send(:head, self.next, **@options)\n resource.get_response.total_records\n end",
"def total_count\n @all.size\n end",
"def count\n @params[:rettype] = 'count'\n self\n end",
"def how_many(klass)\n JSON.parse(@client.raw_read(resource: klass, summary: \"count\").response[:body])[\"total\"].to_i\n end",
"def count; end",
"def count; end",
"def count; end",
"def count\n @collector.count\n end",
"def total_records\n record.records.count\n end",
"def count(opts={})\n all(opts).size\n end",
"def retrieved_records\n results.count\n end",
"def list_pets\n @owner.dogs.count\n @owner.cats.count\n end",
"def count(*vars)\n result = if vars.first.is_a?(Symbol)\n template = vars.shift\n # preserves an eventual wrapper by calling the template method\n self[:context].send(template, params(:size => 0), *vars)\n else\n Query.elastics.count_search(:get, self, *vars)\n end\n result['hits']['total']\n end",
"def count(params = {})\n record_count :dataset, params\n end",
"def determine_count\n if empty?\n @count = 0\n return\n end\n\n result = 0\n\n with_record_stream do |stream|\n mapper = org.codehaus.jackson.map.ObjectMapper.new\n parser = mapper.getJsonFactory.createJsonParser(stream)\n\n while parser.nextToken\n result += 1\n parser.skipChildren\n skip_comma(parser)\n end\n end\n\n @count = result\n end",
"def api_count(args)\n query_str = args[:query]\n object_name = args[:entity].pluralize\n my_response = HTTParty.get(\"https://api.rechargeapps.com/#{object_name}/count?#{query_str}\",\n headers: HEADER)\n my_count = my_response['count'].to_i\n Resque.logger.info \"#{my_count} #{object_name}'s on Recharge API\"\n Resque.logger.info my_response\n my_count\n end",
"def count\n all.size\n end",
"def execute_batch_counting(projects_relation)\n end",
"def count\n self.all.count\n end",
"def count\n ensure_aggregate!\n SQLite::API.aggregate_count( @func )\n end",
"def total_count\n @total_count ||= self.query.count\n end",
"def record_counts(model_query, filtered_query)\n counts = Hash.new\n total = model_query.distinct.count(:id)\n\n # Handle results of joined queries. This feels a little bit hacky.\n total = total.keys.length if total.is_a?(Hash)\n\n counts[:total_rows] = total\n\n if tablesorter_params[:filter]\n # Count again if additional filters were applied (fires a query)\n cnt = filtered_query.count(\"#{model_query.table_name}.id\")\n\n # Handle results of having-queries. This feels a little bit hacky.\n cnt = cnt.keys.length if cnt.is_a?(Hash)\n\n counts[:filtered_rows] = cnt\n else\n counts[:filtered_rows] = total # There wasn't any reduction.\n end\n\n counts\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def count_for(resource)\n\t\tself.find(resource).count\n\tend",
"def count\n # implement in subclasses\n end",
"def scope_count\n count_scope = scope.dup\n count_scope.manager.projections = [Arel.star.count]\n\n count_scope.execute.first&.values&.first || 0\n end",
"def count_records\n count = scoped.count\n\n # If there's nothing in the database and @target has no new records\n # we are certain the current target is an empty array. This is a\n # documented side-effect of the method that may avoid an extra SELECT.\n @target ||= [] && loaded! if count == 0\n\n count\n end",
"def count_people(query={})\n self.simple_client.get(\"/api/v1/people/count?#{query.to_query}\")[\"count\"]\n end",
"def author_count\n revisions = Marginalia.revisions(params[:id])\n authors = []\n revisions.collect {|rev| authors << rev['user']}\n authors.uniq!\n render :text => authors.length\n end",
"def result_count_by_type\n ret = Hash.new {|h, k| h[k] = 0}\n result_ids.group_by(&:first).each do |scope, ids|\n ret[scope] += ids.size\n end\n ret\n end",
"def related_issue_counts\n self.class.related_issue_counts(self.version_key)\n end",
"def count\n load\n @result_count\n end",
"def get_counts(args = {})\r\n Net::Flickr.instance().request('flickr.photos.getCounts', args).at('photocounts')\r\n end",
"def count(scope, attr)\n \"poro_count_#{attr}\"\n end",
"def count(layer_idx=0, options={})\n return nil unless self.metadata[\"capabilities\"] =~ /Query/\n query(layer_idx, options.merge(:returnCountOnly => true))\n end",
"def count\n @store.count\n end",
"def stock_count\n sql = \"SELECT * FROM cars\n WHERE shop_id = $1\"\n value = [@id]\n cars = SqlRunner.run(sql, value)\n result_array = cars.map{|car| Car.new(car)}\n count = result_array.count\n return count\n end",
"def total_records_created\n successful_rows.inject(t = 0) { |t, i| t += processed_rows[i].persisted_objects.size }\n end",
"def count\n load_page(1) if @num_records.nil? # load pagination metadata\n @num_records\n end",
"def count\n @history.objects.find { |o| o.name == \"count\" }.val\n end",
"def resource_count_stats\n klass = klass_from_controller(controller_name)\n full_total = klass.count\n visible_total = if klass.authorization_supported?\n klass.all_authorized_for('view').count\n elsif klass.is_a?(Person) && Seek::Config.is_virtualliver && User.current_user.nil?\n 0\n else\n klass.count\n end\n [visible_total, full_total]\n end",
"def comments_per_recipe\n db_connection do |conn|\n conn.exec(\"SELECT recipe_id, COUNT(*) FROM comments GROUP BY recipe_id\").to_a\n end\nend",
"def display_entity_counts\n @log.info @tracker.display\n end",
"def odb_count\n \"count(#{to_s})\"\n end",
"def count(resource)\n list(resource.to_s,1)[\"meta\"][\"total_count\"]\n end",
"def ri_counts(*args)\n resources, opts = ri_opts(args)\n counts = {}\n threads = []\n resources.each do |res|\n next unless res.populated?\n threads << Thread.new do\n counts[res.acronym] = res.concept_count(self.xxhash, opts)\n end\n end\n threads.each(&:join)\n counts\n end",
"def count(opts = {})\n view = opts[:view] || @opts[:view]\n client.view(view,\n limit: 0,\n include_docs: false,\n stream: true).total_rows\n end",
"def c_count events\n events.map(&:committer).uniq.count\nend",
"def count(params = {})\n @api.get(\"api/count.json\", params)\n end",
"def get_counts(commits)\n commits.reduce([[], []]) do |counts, commit|\n classification = self.classify(commit)\n if classification == 'Good'\n counts[0] << commit\n else\n counts[1] << commit\n end\n counts\n end\n end",
"def collection_object_count_by_classification(scope = nil)\n\n return [] if scope.nil?\n specimen_data = {}\n lot_data = {}\n\n total_index = {}\n\n scope.each do |n|\n a = ::Queries::CollectionObject::Filter.new(project_id: sessions_current_project_id, taxon_name_id: n.id, descendants: true, collection_object_type: 'Specimen').all\n b = ::Queries::CollectionObject::Filter.new(project_id: sessions_current_project_id, taxon_name_id: n.id, descendants: true, collection_object_type: 'Lot').all\n\n ts = CollectionObject.where(id: a).calculate(:sum, :total)\n tl = CollectionObject.where(id: b).calculate(:sum, :total)\n\n if (ts > 0) || (tl > 0)\n lot_data[n.cached] = tl\n specimen_data[n.cached] = ts\n total_index[n.cached] = ts + tl\n end\n\n end\n\n # We only need to sort 1 pile!\n specimen_data = specimen_data.sort{|a,b| total_index[b[0]] <=> total_index[a[0]] }.to_h\n\n return {\n total_index:,\n data: [\n { name: 'Specimen', data: specimen_data},\n { name: 'Lot', data: lot_data}\n ]\n }\n end",
"def lines\n repository.files.map do |file|\n repository.read(file).to_s.lines.count\n end.sum\n end",
"def count_per_period_all\n \tcount = Center.all.inject({}) do |col,center|\n \t\tcol[center.id] = count_sum_per_period(center.id)\n \t\tcol\n \tend\n end",
"def find_counts()\n # Search through given fields for given text\n counts = Array.new\n find_text = @replace['replace']['find']\n @replace['replace']['tables'].each do |table, fields|\n query = find_query(find_text, table, fields.clone)\n @dbconn.query(query).each do |row|\n count_hash = {table: table, fields: fields, count: row['total']}\n counts.push count_hash\n end\n end\n counts\n end"
] |
[
"0.68711966",
"0.6806252",
"0.677834",
"0.6774241",
"0.6767395",
"0.6765067",
"0.67167723",
"0.67054987",
"0.6692752",
"0.665436",
"0.6565099",
"0.6556102",
"0.6518391",
"0.6428198",
"0.640877",
"0.6387814",
"0.63485754",
"0.63485754",
"0.6326861",
"0.6313247",
"0.6310123",
"0.63068354",
"0.6291801",
"0.6284373",
"0.6263812",
"0.62609166",
"0.62462133",
"0.6235516",
"0.62127227",
"0.6192519",
"0.6192519",
"0.6192519",
"0.61916405",
"0.61566436",
"0.6153495",
"0.6147672",
"0.6144692",
"0.61363655",
"0.6117777",
"0.6117777",
"0.61115986",
"0.6103442",
"0.6101024",
"0.60969925",
"0.60939145",
"0.60931563",
"0.6080063",
"0.6074908",
"0.6074868",
"0.6074868",
"0.6074868",
"0.6074506",
"0.6073196",
"0.60508966",
"0.6048561",
"0.6047594",
"0.6047407",
"0.6046232",
"0.60307413",
"0.60269904",
"0.60111576",
"0.6006736",
"0.60054904",
"0.59999865",
"0.59911036",
"0.5990605",
"0.59898293",
"0.59898293",
"0.59898293",
"0.59876096",
"0.59836984",
"0.5978868",
"0.5975477",
"0.5975285",
"0.59588677",
"0.5958412",
"0.59527653",
"0.5938316",
"0.5936481",
"0.5925245",
"0.59182495",
"0.5914698",
"0.5914681",
"0.59084105",
"0.5908312",
"0.59047866",
"0.58967406",
"0.58927923",
"0.58877736",
"0.5886444",
"0.5886398",
"0.5883128",
"0.5881439",
"0.5880429",
"0.5880224",
"0.58785695",
"0.58764607",
"0.58747137",
"0.586851",
"0.58574814"
] |
0.6806599
|
1
|
compose a string of 'OR'd titles for a query
|
def compose_title_list(pairs)
query = ''
pairs.each do |s, ct|
query = query + " title:\"#{s}\""
end
"(#{query})"
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def ar_transform_query_terms terms\n if terms && !terms.empty? && terms !~ /^\\s*[*? ]*\\s*$/\n terms.split(\" \").inject([]) do |query, token| \n query << \"*#{token}*\" \n end.join(\" or \")\n else\n \"\"\n end\n end",
"def build_query(query, options={})\n queries = []\n QUERY_KEYWORDS.each do |kw|\n next unless options[kw]\n if options[kw].is_a? Array\n kw_query = options[kw].map {|s| \"#{kw}:#{s}\".strip }.join(\" OR \")\n queries << \" (#{kw_query})\"\n else\n queries << \" #{kw}:#{options[kw]}\"\n end\n end\n \"#{query} #{queries.join(' ')}\".strip\n end",
"def google_parse_one_clause(str, goods, bads)\n if str.sub!(/^-\"([^\"]+)\"( |$)/, \"\") ||\n str.sub!(/^-(\\S+)( |$)/, \"\")\n bads << Regexp.last_match(1)\n elsif str.sub!(/^((\"[^\"]+\"|\\S+)( OR (\"[^\"]+\"|\\S+))*)( |$)/, \"\")\n str2 = Regexp.last_match(1)\n or_strs = []\n while str2.sub!(/^\"([^\"]+)\"( OR |$)/, \"\") ||\n str2.sub!(/^(\\S+)( OR |$)/, \"\")\n or_strs << Regexp.last_match(1)\n end\n goods << or_strs\n else\n raise(\"Invalid search string syntax at: '#{str}'\") if str != \"\"\n\n return true\n end\n false\n end",
"def or(*exps)\n joined_exps = exps.join(' and ')\n @query[:filters] += \" or #{joined_exps}\"\n self\n end",
"def search_search_text\n query\n .where(\"decidim_opinions_opinions.title ILIKE ?\", \"%#{search_text}%\")\n .or(query.where(\"decidim_opinions_opinions.body ILIKE ?\", \"%#{search_text}%\"))\n end",
"def conditions_for_keywords\n sql = []\n params = []\n\n keywords.each do |kw|\n str = \"lower(tasks.name) like ?\"\n str += \" or lower(tasks.description) like ?\"\n sql << str\n 2.times { params << \"%#{ kw.word.downcase }%\" }\n end\n\n sql = sql.join(\" or \")\n res = TaskFilter.send(:sanitize_sql_array, [ sql ] + params)\n return \"(#{ res })\" if !res.blank?\n end",
"def or( *args ); { $or => args } end",
"def search_terms(*words)\n terms = []\n words.each { |word| terms.push \"'%#{word.gsub(/[^a-z]/i, '').strip}%'\" }\n return nil if terms.empty?\n return 'description ILIKE ' + terms.join(' AND description ILIKE ')\nend",
"def query_for_one_keyword\n return @query_for_one_keyword if @query_for_one_keyword\n\n query = fields.map { |field| \"lower(#{field}) LIKE ?\" }\n .join(' OR ')\n @query_for_one_keyword = \"(#{query})\"\n end",
"def AppendClauseOr(clause,phrase)\n if 0<clause.length then\n clause << \" OR \"\n end\n clause << phrase\n return clause\n end",
"def query_to_terms(query)\n query.scan(/(\\+|or \\-?|and \\-?|\\-)?(\"[^\"]*\"?|[\\w\\-]+)/).collect do |prefix, term|\n term = \"(#{term.scan(/[\\w']+/).join('&')})\" if term[0,1] == '\"'\n term = \"!#{term}\" if prefix =~ /\\-/\n [(prefix =~ /or/) ? '|' : '&', term] \n end\n end",
"def search_search_text\n query\n .where(localized_search_text_in(:title), text: \"%#{search_text}%\")\n .or(query.where(localized_search_text_in(:description), text: \"%#{search_text}%\"))\n end",
"def conditions_for(fields=[])\n predicate = []\n values = []\n fields.each do |field|\n predicate << \"lower(#{field.to_s}) like ?\"\n values << \"'%' + @search_key.downcase + '%'\"\n end\n eval(\"[\\\"#{predicate.join(' OR ')}\\\", #{values.join(',')}]\")\n end",
"def build_meta_search_query(meta_keys)\n keys = meta_keys.join(\"_or_\")\n keys << \"_contains\"\n return keys\n end",
"def join_with_or ar, **options\n\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter ar, 'ar', type: ::Array, allow_nil: true\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter options, 'options', type: ::Hash, allow_nil: false\n\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter options[:or], ':or', type: ::String, option: true, allow_nil: true\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter options[:oxford_comma], ':oxford_comma', types: [ ::FalseClass, ::TrueClass ], option: true, allow_nil: true\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter options[:quote_char], ':quote_char', type: ::String, option: true, allow_nil: true\n\t\t::Xqsr3::Quality::ParameterChecking.check_parameter options[:separator], ':separator', type: ::String, option: true, allow_nil: true\n\n\t\treturn '' if ar.nil?\n\t\treturn '' if ar.empty?\n\n\t\tseparator\t=\toptions[:separator] || ','\n\t\tor_word\t\t=\toptions[:or] || 'or'\n\t\tox_comma\t=\t(options.has_key?(:oxford_comma) && !options[:oxford_comma]) ? '' : separator\n\t\tquote_char\t=\toptions[:quote_char]\n\n\t\tar\t\t\t=\tar.map { |v| \"#{quote_char}#{v}#{quote_char}\" } if quote_char\n\n\t\tcase ar.size\n\t\twhen 1\n\t\t\tar[0]\n\t\twhen 2\n\t\t\t\"#{ar[0]} #{or_word} #{ar[1]}\"\n\t\telse\n\t\t\t\"#{ar[0...-1].join(separator + ' ')}#{ox_comma} #{or_word} #{ar[-1]}\"\n\t\tend\n\tend",
"def construct_tag_search(table, field, values)\n values.map { |v| construct_ilike_search(table, field, v, \"\") }.join(\" OR \")\n end",
"def joinor(ary, delimiter = ', ', final_word = 'or')\n result = ''\n count = 0\n\n case ary.size\n when 0 then ''\n when 1 then ary[0].to_s\n when 2 then \"#{ary[0]} #{final_word} #{ary[1]}\"\n else\n while count <= ary.length - 2\n result += ary[count].to_s + delimiter\n count += 1\n end\n\n result + final_word + ' ' + ary[-1].to_s\n end\nend",
"def query\n ([query_for_one_keyword] * split_query_string.size).join(' AND ')\n end",
"def pummel_query(author, title)\n q1 = form_pummel_query('a', author, title)\n q2 = form_pummel_query('t', title, author)\n combined = \"(#{q1}\\nUNION\\n#{q2}\"\n end",
"def sanitize_relation(relation)\n if 'OR' == relation.upcase\n 'OR'\n else\n 'AND'\n end\n end",
"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 create_queries(keyword)\n sql = \"\"\n self.column_names .each do |col|\n\n sql += col + \" LIKE \" + \"\\'\" + keyword + \"\\'\"\n sql += \" OR \"\n end\n sql[0..-5] #removes the last AND. A temporary dirty fix.\n end",
"def joinor(ary, punc=', ', conj='or')\n if ary.size <= 1\n ary.first.to_s\n elsif ary.size == 2\n ary.join(\" #{conj} \")\n else\n \"#{ary[0..-2].join(punc)}#{punc + conj} #{ary.last}\"\n end\nend",
"def tags_condition(tags)\n condition = tags.map do |t|\n sanitize_sql([\"#{table_name}.name LIKE ?\", t])\n end.join(\" OR \")\n \"(\" + condition + \")\" unless condition.blank?\n end",
"def str_sql_search(str, fields)\n str.gsub!(\"'\", '')\n str.gsub!('\"', '')\n str.gsub!(\"\\\\\", '')\n str.gsub!(\"%\", '')\n \n arr = string_to_arr(str)\n rows = []\n cells = []\n \n for field in fields\n cells = []\n \n for a in arr\n cells.push(\"(#{field} LIKE \\\"%#{a}%\\\")\")\n end\n \n rows.push(\"(\" + cells.join(\" AND \") + \")\")\n end\n \n return rows.join(\" OR \")\n end",
"def search_conditions(query, fields=nil)\n return nil if query.blank?\n fields ||= @search_columns\n\n # split the query by commas as well as spaces, just in case\n words = query.split(\",\").map(&:split).flatten\n\n binds = {} # bind symbols\n or_frags = [] # OR fragments\n count = 1 # to keep count on the symbols and OR fragments\n\n words.each do |word|\n like_frags = [fields].flatten.map { |f| \"LOWER(#{f}) LIKE :word#{count}\" }\n or_frags << \"(#{like_frags.join(\" OR \")})\"\n binds[\"word#{count}\".to_sym] = \"%#{word.to_s.downcase}%\"\n count += 1\n end\n [or_frags.join(\" AND \"), binds]\n end",
"def generate_OR_clauses(rule)\n #First, split rule into positive and negative sets of clauses.\n parts = rule.split(@NOT)\n positive_clauses = parts[0]\n negative_clauses = parts[1]\n\n @or_clauses_pos = positive_clauses.split('OR')\n @or_clauses_neg = negative_clauses.split('OR')\n end",
"def query_terms_string\n raise 'You must supply at least one query term' if query_terms.empty?\n\n \"q=#{query_terms.map(&:to_s).join(\",#{boolean_operator};\")}\"\n end",
"def joinor(arr, delimiter=', ', word='or')\n case arr.size\n when 0 then ''\n when 1 then arr.first\n when 2 then arr.join(\" #{word} \")\n else\n arr[-1] = \"#{word} #{arr.last}\"\n arr.join(delimiter)\n end\nend",
"def search_call_connector(**opt)\n prepend_css!(opt, 'or')\n connector = html_span('OR', opt) # TODO: I18n\n \" #{connector} \".html_safe\n end",
"def either(left, right)\n \"#{quotify left} OR #{quotify right}\"\n end",
"def joinor(array, symbol = ', ', symbol_2 = 'or')\n if array.size == 2\n array.join(' ').insert(-2, 'or ')\n elsif array.size == 1\n array.join\n else\n array.join(\"#{symbol}\").insert(-2, \"#{symbol_2} \")\n end\nend",
"def test_like_two_search_condition\n search_conditions = [[\"Wes\", :like],[\"Hays\", :like]]\n query_fields = {'some_table.first_name' => :string,'some_table.last_name' => :string} \n conditions = build_query(search_conditions, query_fields) \n \n fields = ['first_name','last_name']\n regExs = [build_regex_for_like(fields,'keyword_0'), \n build_regex_for_like(fields,'keyword_1')].join('[ ]AND[ ]')\n \n assert_match /^#{regExs}$/, conditions.first\n assert_equal '%Wes%', conditions.last[:keyword_0]\n assert_equal '%Hays%', conditions.last[:keyword_1]\n end",
"def joinor(ary, delimiter = ', ', last_word = 'or')\n return ary.first if ary.size == 1\n return \"#{ary.first} #{last_word} #{ary.last}\" if ary.size == 2\n\n last_element = ary.pop\n ary << ''\n\n \"#{ary.join(delimiter)}\"\\\n \"#{last_word} \"\\\n \"#{last_element}\"\n end",
"def query_string\n _f = @params.fields.include?(:full_text) ? [:full_text] : fields\n # byebug\n a = query.gsub('/', '').scan( /\"[^\"]+\"|[^ ]+/ ).map do |word|\n if word[0] === '\"'\n m = word.match( /^\"(.*)\"$/ );\n word = m ? m[1] : word;\n end\n Unicode.downcase(word.gsub('\"', ''))\n end\n _q = '(' + a.join('* AND ') + '*)'\n # _q = '/(?=.*?'+a.join( ')(?=.*?' )+').*/';\n #byebug\n index.filter{ ~q(query_string: {fields: _f, query: \"#{_q}\", default_operator: 'or'}) } if _q.present? && _f.present?\n\n #index.query(multi_match: {query: \"#{_q}*\", fields: _f}) if _q.present? && _f.present\n end",
"def search_text(query, text)\n text = pattern(text)\n query.where { title.ilike(text) | description.ilike(text) }\n end",
"def joinor(array, separator = ', ', word = 'or')\n case array.size\n when 0, 1\n array.join\n when 2\n array.join(\" #{word} \")\n else\n last_element = array.pop.to_s\n array.join(separator) << last_element.prepend(\"#{separator}#{word} \")\n end\nend",
"def creating_jql_string arr, str, type\n if !arr.empty? && str.empty?\n array_to_string arr, type\n elsif !arr.empty? && !str.empty?\n \" AND #{array_to_string(arr, type)}\"\n end\n end",
"def joinor(arr, delimiter=', ', word='or')\n arr[-1] = \"#{word} #{arr.last}\" if arr.size > 1\n arr.join(delimiter)\nend",
"def search_query(search_terms)\n resource_handler.searchable_attributes.map do |attribute|\n if relation = attribute[:relation]\n \"LOWER(#{relation[:model_association].klass.table_name}.#{relation[:attr_method]}) LIKE #{search_terms}\"\n else\n \"LOWER(#{resource_handler.model.table_name}.#{attribute[:name]}) LIKE #{search_terms}\"\n end\n end.join(\" OR \")\n end",
"def search_string\n [name, description].join(' ')\n end",
"def joinor(array, delimiter = ', ', word = 'or')\n if array.size == 2\n array.join(\" #{word} \")\n else\n array[-1] = \"#{word} #{array.last}\"\n array.join(delimiter)\n end\nend",
"def joinor(arr, delimiter = ', ', conjunction = 'or')\n return '' if arr.empty?\n arr.map!(&:to_s)\n return arr[0] if arr.size == 1\n str = arr.size > 2 ? arr[0..-2].join(delimiter) + delimiter : arr[0] + ' '\n # str = arr[0..-2].join(delimiter)\n # str << (arr.size > 2 ? delimiter : ' ')\n str << conjunction + ' ' + arr[-1]\nend",
"def joinor(arr, str1 = ', ', str2 = 'or')\n case arr.size\n when 0 then ''\n when 1 then arr.first\n when 2 then arr.join(\" #{str2} \")\n else\n arr[-1] = \"#{str2} #{arr.last}\"\n arr.join(str1)\n end\nend",
"def where_and(str)\n str.include?('WHERE') ? 'AND' : 'WHERE'\nend",
"def all_or(*args)\n Term.get OrTerm, *args\n end",
"def solr_filter_concepts(prefix = '', join = ' || ')\n result = Item::ITYPE_CONCEPT.map{|e|\"#{prefix}itype_text:#{e}\"}.join(\"#{join}\")\n \"(#{result})\"\n end",
"def google_conditions(search, field)\n goods = search.goods\n bads = search.bads\n ands = []\n ands += goods.map do |good|\n or_clause(*good.map { |str| \"#{field} LIKE '%#{clean_pattern(str)}%'\" })\n end\n ands += bads.map { |bad| \"#{field} NOT LIKE '%#{clean_pattern(bad)}%'\" }\n [ands.join(\" AND \")]\n end",
"def join_conditions op, *conditions\n conditions = conditions.compact\n if conditions.empty?\n conditions\n elsif conditions.count == 1\n conditions.first\n else\n strings = conditions.map(&:first)\n args = conditions.flat_map{|c| c[1..-1]}\n [\n strings.map{|s| \"(#{s})\"}.join(\" #{op} \"),\n *args\n ]\n end\n end",
"def or(arg)\n if condition_specifier?(arg)\n SQL::BooleanExpression.from_value_pairs(arg, :OR, false)\n else\n raise Error, 'must pass a conditions specifier to Sequel.or'\n end\n end",
"def initialize(string_or_hash)\n if string_or_hash.class == String\n self.search_string = string_or_hash.strip\n self.operator = \"OR\"\n elsif string_or_hash.class == Hash\n self.terms = string_or_hash.keys.inject({}) {|hash,key| hash[key] = string_or_hash[key].strip; hash }\n self.operator = \"AND\"\n end\n end",
"def build_query(winners, iteration)\n\tq = []\n\t(0..iteration).each do |i|\n\t\t((i+1)..(winners.length - 1)).each do |j|\n\t\t\tq << \"(\" + winners[i][0] + \"^#{winners.length-i} AND \" + winners[j][0] + \"^#{(winners.length-j)/2})\"\n\t\tend\n\tend\n\treturn CGI::escape(q.join(\" OR \"))\nend",
"def handle_AND(clause)\n \"#{clause.gsub!(' AND ', ' ').strip!}\"\n clause.gsub!('( ', '(')\n clause.gsub!(' )', ')')\n clause\n end",
"def calc_where_clause(our_where = where)\n ands = our_where.uniq.map do |x|\n # Make half-assed attempt to cut down on proliferating parens...\n if x.match(/^\\(.*\\)$/) || !x.match(/ or /i)\n x\n else\n \"(#{x})\"\n end\n end\n ands.join(\" AND \")\n end",
"def process_or(exp)\n lhs = process exp.shift\n rhs = process exp.shift\n\n return \"#{lhs} || #{rhs}\"\n end",
"def joinor(arr, sep = \", \", art = \"or \")\n case arr.size\n when 0 then \"\"\n when 1 then arr.first\n when 2 then arr.join(\" #{art} \")\n else\n arr[-1] = \"#{art} #{arr.last}\"\n arr.join(sep)\n end\nend",
"def build_filter filter, fields\n where = [fields.map { |f| \"#{f} like ?\" }.join(\" || \")]\n fields.count.times { |n| where << \"%#{filter}%\" }\n where\n end",
"def build_search_query(terms)\n # givenName, sn, or sAMAccountName start with each term\n query = '(&'\n query << QUERY_BASE\n \n terms.gsub(/[()]/, '').split.each do |term|\n query << '(|'\n query << \"(sAMAccountName=#{term}*)\"\n query << \"(givenName=#{term}*)\"\n query << \"(sn=#{term}*)\"\n query << \"(mail=#{term}*)\"\n query << \"(proxyaddresses=smtp:#{term}*)\"\n query << ')'\n end\n\n query << ')'\n @logger.debug(\"LDAP query = #{query}\")\n\n query\n end",
"def joinor(elements, separator = ', ', conjunction = 'or')\n temp = []\n elements.each.with_index do |element, index|\n if index == elements.size - 1\n if elements.size > 1\n temp << \" #{conjunction} #{element}\"\n else\n temp << \"#{element}\"\n end\n else\n if elements.size > 2\n temp << \"#{element}#{separator}\"\n else\n temp << \"#{element}\"\n end\n end\n end\n temp.join.gsub(' ', ' ')\nend",
"def operation_as_join\n @operation == :all && ' && ' || ' || '\n end",
"def search_process\n @search_text =params[:q].to_s\n all =params[:all].to_s\n exact =params[:exact].to_s\n any =params[:any].to_s\n none =params[:none].to_s\n advanced_query=\"\"\n\n if all != \"\"\n all =all.split(' ')\n all_like =all.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n all_like =all_like.join(' and ')\n advanced_query=all_like\n end\n\n if exact != \"\" && all != \"\"\n exact =\"'%\"+exact+\"%'\"\n advanced_query = advanced_query + \" and keyword like \" + exact\n end\n\n if exact != \"\" && all == \"\"\n exact =\"'%\"+exact+\"%'\"\n advanced_query = \"keyword like \" + exact\n end\n\n if any != \"\" and (all != \"\" or exact != \"\")\n any =any.split(' ')\n any_like =any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n any_like =any_like.join(' or ')\n advanced_query = advanced_query + \" and (\" + any_like + \")\"\n end\n\n if any != \"\" and all == \"\" and exact == \"\"\n any =any.split(' ')\n any_like =any.map { |x| \"keyword like \" + \"'%\" + x + \"%'\" }\n any_like =any_like.join(' or ')\n advanced_query = \"(\" + any_like + \")\"\n end\n\n if none != \"\" and (all != \"\" or exact != \"\" or any != \"\")\n none =none.split(' ')\n none_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\n\n none_not_like=none_not_like.join(' and ')\n\n advanced_query=advanced_query + \" and \" + none_not_like\n\n end\n\n if none != \"\" and all == \"\" and exact == \"\" and any == \"\"\n none =none.split(' ')\n none_not_like=none.map { |x| \"keyword not like \" + \"'%\" + x + \"%'\" }\n\n none_not_like=none_not_like.join(' and ')\n\n advanced_query= none_not_like\n end\n\n\n advanced_query = \"SELECT Model_ID FROM keyword_symbol_tables WHERE \"+advanced_query\n\n parameter_search_text=@search_text.split.join(\" \")\n keyword_array =parameter_search_text.split(' ')\n keyword_count =keyword_array.size\n\n connection = ActiveRecord::Base.connection\n\n if all != \"\" or exact != \"\" or any != \"\" or none != \"\"\n @resultset = connection.execute(\"#{advanced_query}\");\n else\n @resultset = connection.execute(\"call keyword_search('#{parameter_search_text}',#{keyword_count})\");\n end\n\n ActiveRecord::Base.clear_active_connections!\n\n @resultset_strings = @resultset.map { |result| result.to_s.gsub(/[^0-9A-Za-z]/, '') }\n\n @model_ids =Array.new\n @model_names =Array.new\n @model_types =Array.new\n\n @resultset_strings.each do |result|\n\n substring=result[0..4]\n\n if substring == \"NMLCL\"\n cell=Cell.find_by_Cell_ID(result.to_s)\n name=cell.Cell_Name\n type=\"Cell\"\n end\n\n if substring == \"NMLCH\"\n channel=Channel.find_by_Channel_ID(result.to_s)\n name =channel.Channel_Name\n type =\"Channel\"\n end\n\n\n if substring == \"NMLNT\"\n network=Network.find_by_Network_ID(result.to_s)\n name =network.Network_Name\n type =\"Network\"\n end\n\n if substring == \"NMLSY\"\n synapse=Synapse.find_by_Synapse_ID(result.to_s)\n name =synapse.Synapse_Name\n type =\"Synapse\"\n end\n\n @model_ids.push(result)\n @model_names.push(name)\n @model_types.push(type)\n\n end\n\n if @model_ids.count != 0\n\n render :partial => 'keyword_results_list',\n :locals => {\n :model_ids => @model_ids,\n :model_names => @model_names,\n :model_types => @model_types\n }\n\n else\n\n render :partial => 'no_results'\n\n end\n\n end",
"def grouping_query(field, phrase, op = 'AND')\n raise 'op must be AND or OR' unless ['AND', 'OR'].include? op\n\n \"_query_:\\\"{!lucene q.op=#{op}}#{field}:(#{phrase})\\\"\"\n end",
"def process_filters(search_opts = {})\n filter_str = ''\n if search_opts['filter']\n search_opts['filter'].each do |f|\n filter_str = \"#{filter_str} AND #{f}\"\n end\n search_opts.delete('filter')\n end\n filter_str\n end",
"def search_conditions_as_options\n [\n [I18n.t(\"advanced_searches.text_search_field.all_words\"), \"all_words\"],\n [I18n.t(\"advanced_searches.text_search_field.one_word\"), \"one_word\"],\n [I18n.t(\"advanced_searches.text_search_field.exact\"), \"exact\"]\n ]\n end",
"def compose_or(first_condition, second_condition)\n validate_condition(first_condition)\n validate_condition(second_condition)\n first_condition.or(second_condition)\n end",
"def programs_query_str(program_duration_ids)\n program_duration_ids = program_duration_ids.split(',')\n program_durations = Constants::PROGRAM_DURATIONS\n\n program_q = ['(']\n\n program_duration_ids.each_with_index do |id, index|\n if index.zero?\n program_q.push \"duration like '%#{program_durations[id.to_i]}%'\"\n else\n program_q.push \"OR duration like '%#{program_durations[id.to_i]}%'\"\n end\n end\n program_q.push ')'\n\n program_q.join('')\n end",
"def valid_find_operator\n\t\toperator = ' OR '\n\t\tif params[:operator] and !params[:operator].blank? and \n\t\t\t\t['AND','OR'].include?(params[:operator])\n\t\t\toperator = \" #{params[:operator]} \"\n\t\tend\n\t\toperator\n\tend",
"def title_for_search\n (title || \"\").strip.sub(/\\Athe\\s+/i, \"\").sub(/\\Aan?\\s+/i, \"\")\n end",
"def search!(collection, query_str)\n res = collection\n if query_str.present?\n\n query_str.split(Regex::FIELD).each do |term|\n next if term.blank?\n\n parts = []\n terms = []\n fields.each do |f|\n field = get_field(f, collection)\n part = [\"#{field} #{Regex::LIKE} \",\n \"#{query_base} ESCAPE '#{Regex::ESCAPECHAR}'\"].join('')\n terms << get_term(term)\n parts << part\n end\n\n if parts.any?\n query = parts.join(\" #{Regex::OR} \")\n res = res.where(query, *terms)\n end\n end\n end\n res\n end",
"def industries_query_str(industry_ids)\n industry_ids = industry_ids.split(',')\n list_of_clusters = convert_industries_to_hash\n industries_q = ['(']\n\n industry_ids.each_with_index do |id, index|\n if index.zero?\n industries_q.push \"industries like '%#{list_of_clusters[id.to_i]}%'\"\n else\n industries_q.push \" OR industries like '%#{list_of_clusters[id.to_i]}%'\"\n end\n end\n industries_q.push ')'\n\n industries_q.join('')\n end",
"def rewrite_or(expression)\n first = expression[1]\n second = expression[2]\n\n VirtualKeywords.call_operator_replacement(:call_or, first, second)\n end",
"def query\n\t\t\t[@search_term,@filter].compact.join(\" \")\n\t\tend",
"def search_string\n [self.title].join(' ')\n end",
"def bulk_oclc_query(oclc_nos)\n string = \"srw.no any \\\"#{oclc_nos.first}\\\"\"\n oclc_nos[1..-1].each do |num|\n string << \" or srw.no any \\\"#{num}\\\"\"\n end\n string\nend",
"def generate_search (options)\n conditions_stmt = ''\n\n if options[:id].to_s.strip != '' then\n options[:id] = CGI::unescape(options[:id])\n conditions_stmt += ' AND ' unless conditions_stmt == ''\n conditions_stmt += 'code = \"' + options[:id].to_s.strip + '\"'\n end\n\n if options[:visited].to_s.strip != '' then\n options[:visited] = CGI::unescape(options[:visited])\n conditions_stmt += ' AND ' unless conditions_stmt == ''\n conditions_stmt += 'visited = \"' + (options[:visited] == 'true' ? 't' : 'f') + '\"'\n end\n \n if options[:name].to_s.strip != '' then\n options[:name] = CGI::unescape(options[:name])\n conditions_stmt += ' AND ' unless conditions_stmt == ''\n if options[:name] =~ /\\*|\\%/\n options[:name] = options[:name].gsub('*', '%')\n conditions_stmt += 'name LIKE \"' + options[:name].to_s.strip + '\"'\n else\n if options[:name] =~ /!/\n conditions_stmt += 'name != \"' + options[:name].gsub('!', '').to_s.strip + '\"'\n else\n conditions_stmt += 'name = \"' + options[:name].to_s.strip + '\"'\n end\n end\n end\n \n Rails.logger.debug {\"Search conditions: #{conditions_stmt}\"}\n conditions_stmt\n end",
"def educations_query_str(education_ids)\n education_ids = education_ids.split(',')\n list_of_educations = convert_educations_to_hash\n edu_query = ['(']\n\n education_ids.each_with_index do |id, index|\n if index.zero?\n edu_query.push \"education like '%#{list_of_educations[id.to_i]}%'\"\n else\n edu_query.push \" OR education like '%#{list_of_educations[id.to_i]}%'\"\n end\n end\n edu_query.push ')'\n\n edu_query.join('')\n end",
"def group_operators(term_pairs)\n # create \"x OR y\" string\n term = join_terms 'OR', *term_pairs[0]\n rest = term_pairs.from(1)\n if rest.present?\n # nest the remaining pairs recursively, appending them with \" AND \"\n rest_grouped = group_operators rest\n rest_grouped[0] = \"(#{rest_grouped[0]})\" unless rest.length == 1\n join_terms 'AND', term, rest_grouped\n else\n term\n end\n end",
"def sql_where_w_optional_conditions(where_prefix, cond1, cond2=nil, cond3=nil)\n return '' unless cond1.present? || cond2.present? || cond3.present?\n\n if where_prefix\n sql_where = ' WHERE '\n else\n sql_where = ' AND '\n end\n\n sql_where += cond1 if cond1.present?\n\n if cond2.present?\n sql_where += ' AND ' if cond1.present?\n sql_where += cond2\n end\n\n if cond3.present?\n sql_where += ' AND ' if cond1.present? || cond2.present?\n sql_where += cond3\n end\n\n sql_where\n end",
"def search_by_strings(options)\n if options[:categorie].present?\n if options[:tag].present?\n # Search by Categorie AND Tag\n return Course.select(\"courses.title, courses.slug, courses.date, courses.id\")\n .distinct\n .joins(:taggings)\n .joins(:tags)\n .joins(:categorie)\n .where(\"tags.name = ? AND categories.name = ?\", options[:tag].to_s, options[:categorie].to_s)\n else\n # Search by Categorie\n return Course.select(\"*\")\n .joins(:categorie)\n .where(\"categories.name = ?\", options[:categorie].to_s)\n end\n end\n if options[:tag].present?\n # Search by Tag\n return Course.select(\"courses.title, courses.slug, courses.date, courses.id\")\n .distinct\n .joins(:taggings)\n .joins(:tags)\n .where(\"tags.name = ?\", options[:tag].to_s)\n end\n nil\n end",
"def joinor(arr, grammar = \", \" , or_str = \"or\")\n return puts \"#{arr[0]} #{or_str} #{arr[1]}\" if arr.size < 3\n\n output_str = \"\"\n\n arr.each do |num|\n if num == arr.last\n output_str << \"#{or_str} #{num}\"\n else\n output_str << \"#{num}#{grammar}\"\n end\n end\n\n\n puts output_str\nend",
"def construct_all_tags_search(table, field)\n sql_array = [subjects, media_types, durations].map { |a| a if a.any? }.compact\n sql_strings = sql_array.map do |values|\n \"(#{construct_tag_search(table, field, values)})\"\n end\n \"AND \" + sql_strings.join(\" AND \") unless sql_strings.empty?\n end",
"def name_conditions\n [\"(lower(users.first_name) LIKE ? AND lower(users.last_name) LIKE ?) OR (lower(users.first_name) LIKE ? AND lower(users.last_name) LIKE ?)\", \"%#{first_name}%\", \"%#{last_name}%\", \"%#{last_name}%\", \"%#{first_name}%\"] unless name.blank?\n end",
"def conditions\n [conditions_clauses.join(' AND '), *conditions_options]\nend",
"def joinor(arr, separator = \", \", ending = \"or\")\n final_string = \"\"\n n = 0\n\n case arr.length()\n when 1\n final_string = arr[0].to_s\n when 2\n final_string = arr[0].to_s + \" \" + ending + \" \" + arr[1].to_s\n when 3..\n while n < (arr.length()-1)\n final_string += (arr[n].to_s) + separator\n n += 1\n end\n final_string += ending + \" \" + (arr[-1].to_s)\n end\nend",
"def by_ingredients(query)\n # \"OR\" behavior by default\n apply_filter_list \"ingredients\", query\n\n self\n end",
"def humanize_list terms, separator: ', ', conjunction: ' and '\n *all_but_last, last = terms\n return last if all_but_last.empty?\n\n [ all_but_last.join(separator), last ].join conjunction\n end",
"def search\n terms = params[:query].split\n query = terms.map { |term| \"title like '%#{term}%' OR body like '%#{term}%' OR tags like '%#{term}%'\" }.join(\" OR \")\n \n @posts = Post.where(query).order(\"created_at DESC\").first(10)\n end",
"def or(query = nil, *args)\n merge_query(query, :or, *args) do |left, right|\n NSCompoundPredicate.orPredicateWithSubpredicates([left, right])\n end\n end",
"def common_component_titles_like(*titles)\r\n records = Array.new\r\n titles.each do |title|\r\n records += common_component_class.where(\"title LIKE '%#{title}%'\")\r\n end\r\n records\r\n end",
"def search_title_builder\n\t\tif search_params_present?\n\t\t\ttitle = \"Searching Flights\"\n\t\t\ttitle += \" Departing #{ @airport_options[params[:origin].to_i - 1][0] }\" if params[:origin].present?\n\t\t\tif params[:destination].present?\n\t\t\t\tif params[:origin].present?\n\t\t\t\t\ttitle += \" for \"\n\t\t\t\telse\n\t\t\t\t\ttitle += \" to \"\n\t\t\t\tend\n\t\t\t\ttitle += \"#{ @airport_options[params[:destination].to_i - 1][0] }\"\n\t\t\tend\n\t\t\ttitle += \" on #{ params[:departure] }\" if params[:departure].present?\n\t\t\ttitle += \" for #{ params[:passengers] }\" if params[:passengers].present?\n\t\t\treturn title\n\t\telse\n\t\t\ttitle = \"Search Flights\"\n\t\tend\n\tend",
"def to_s\n [left, right].uniq.join(\" #{messages[:or]} \")\n end",
"def grep(cols, terms)\n filter(SQL::BooleanExpression.new(:OR, *Array(cols).collect{|c| SQL::StringExpression.like(c, *terms)}))\n end",
"def where_sql\n named.or(taxon_name_named).to_sql\n end",
"def query( query )\n query.downcase!\n case query\n when /^:r:/ then query_regexp query.gsub(/^:r:/, '')\n when /^:f:/ then query_fulltext_regexp query.gsub(/^:f:/, '')\n else query_simple query\n end\n end",
"def define_match_any_of\n klass.send(:define_method, :match_any_of) do |tags|\n if tags.empty?\n str(\"\")\n else\n tags.map { |tag| str(tag) }.inject do |tag_chain, tag|\n tag_chain.send :|, tag\n end\n end\n end\n end",
"def or(*array_matchers, **keyword_matchers)\n create_matcher('or', array_matchers, keyword_matchers)\n end",
"def or(*array_matchers, **keyword_matchers)\n create_matcher('or', array_matchers, keyword_matchers)\n end",
"def build_conditions_for_datatable\n criteria = search_for.inject([]) do |crit, atom|\n search = AjaxDatatablesRails::Datatable::SimpleSearch.new(value: atom, regex: datatable.search.regexp?)\n disjunction = searchable_columns.map do |simple_column|\n simple_column.search = search\n simple_column.search_query\n end.reduce(:or)\n bag_of_text_class = get_bag_of_text_class\n if bag_of_text_class\n bag_of_text_query = bag_of_text_class.arel_table[:bag_of_text].matches(\"%#{atom}%\")\n if disjunction\n disjunction = disjunction.or(bag_of_text_query)\n else\n disjunction = bag_of_text_query\n end\n end\n crit << disjunction\n end.compact.reduce(:and)\n criteria\n end",
"def get_search_terms(array_of_terms)\n\t\treturn \"q=\"+array_of_terms.join(\"+\")\n\tend",
"def complex_expression_sql_append(sql, op, args)\n case op\n when :^\n j = ' # '\n c = false\n args.each do |a|\n sql << j if c\n literal_append(sql, a)\n c ||= true\n end\n when :ILIKE, :'NOT ILIKE'\n sql << '('\n literal_append(sql, args[0])\n sql << ' ' << op.to_s << ' '\n literal_append(sql, args[1])\n sql << ')'\n else\n super\n end\n end"
] |
[
"0.66017383",
"0.6592401",
"0.6447617",
"0.63557243",
"0.63136",
"0.62717295",
"0.61357176",
"0.6098254",
"0.6058769",
"0.6050013",
"0.6035338",
"0.60258174",
"0.59983474",
"0.59329987",
"0.5874354",
"0.58663225",
"0.5860598",
"0.58542967",
"0.5850351",
"0.58428484",
"0.58413994",
"0.5824611",
"0.5819142",
"0.5811976",
"0.57587546",
"0.56822026",
"0.56737727",
"0.567025",
"0.5648814",
"0.56417763",
"0.56392163",
"0.5632812",
"0.56310314",
"0.56118053",
"0.56070155",
"0.55946875",
"0.5583625",
"0.5583221",
"0.55821055",
"0.55795246",
"0.55581266",
"0.5555508",
"0.5522996",
"0.5512967",
"0.55072004",
"0.547262",
"0.5458845",
"0.5456372",
"0.54509753",
"0.54501444",
"0.5442834",
"0.5427902",
"0.5414187",
"0.5400942",
"0.5395283",
"0.5395259",
"0.5388634",
"0.5382385",
"0.53691417",
"0.53687495",
"0.5359707",
"0.5342125",
"0.5337164",
"0.53363436",
"0.5323863",
"0.53172004",
"0.5308447",
"0.53060514",
"0.5297342",
"0.52818674",
"0.5278511",
"0.5272775",
"0.5253509",
"0.52516925",
"0.5249609",
"0.5235003",
"0.5233499",
"0.52272165",
"0.5215646",
"0.5198206",
"0.5197928",
"0.51956904",
"0.5194646",
"0.51896834",
"0.5187487",
"0.5178403",
"0.5170761",
"0.51679534",
"0.5164791",
"0.5162157",
"0.5153192",
"0.51526046",
"0.51505566",
"0.51474106",
"0.5142217",
"0.51349944",
"0.51349944",
"0.513241",
"0.5122307",
"0.51100034"
] |
0.63271016
|
4
|
USED called from trigger service Send event reminder to user
|
def scheduled_event_reminder_triggered(user_id, event_ids)
return if user_id.nil? || event_ids.nil? || event_ids.empty?
user = User.find(user_id)
return unless user.should_send_email?
events = event_ids.map { |id| Event.find(id) }
if(events.size==1)
tse = events.first.teamsheet_entry_for_user(user)
if user.junior?
JuniorMailerService.scheduled_event_reminder_single(user, tse)
else
UserMailer.delay.scheduled_event_reminder_single(tse)
end
else
teamsheet_entries = events.map { |e| e.teamsheet_entry_for_user(user)}
if user.junior?
JuniorMailerService.scheduled_event_reminder_multiple(user, teamsheet_entries)
else
UserMailer.delay.scheduled_event_reminder_multiple(user, teamsheet_entries)
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def reminder_sent\n end",
"def reminder_received(event)\n @event = event\n\n mail :to => event.email, :subject => 'Reminder alert'\n end",
"def acknowledged_event(user,event)\n @greeting = \"Hi\"\n @event = event\n mail to: user.email\n end",
"def reminder\n DateEventApplicationsMailer.reminder\n end",
"def resolved_event(user,event)\n @greeting = \"Hi\"\n @event = event\n\n mail to: user.email\n end",
"def reminder\n\n end",
"def reminder\n RequestMailer.reminder\n end",
"def new_event(user,event)\n @greeting = \"Hi\"\n @event = event\n\n mail to: user.email\n end",
"def reminder\n UsersMailer.reminder\n end",
"def send_reminders\n User.send_reminders\n redirect_to :back, notice: \"Email reminders sent.\"\n end",
"def reminder(user)\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\"\n end",
"def event_reminder_to_chef(evt)\n @evt = evt\n @chef = User.find_by_id(@evt.user_id)\n @guests = @evt.signups.where('confirmation_status in (?)', 'Attending')\n @comments = @evt.messages.where(\"public_flag = ?\", 1).group(\"messagechain_id\", \"order_id\", \"message_content\", \"sender_id\").sort{|a,b| b[:messagechain_id] <=> a[:messagechain_id]}\n if @guests.sum(:guest_count) > 0\n @paid_communal = @guests.where(\"own_group_flag = 0\")\n @own_table = @guests.where(\"own_group_flag = 1\")\n mail(:to => @chef.email, :subject => \"Your upcoming event on Local Yum\", :from => \"\\\"Local Yum\\\" <alert@localyum.me>\")\n end\n end",
"def send_reminder\r\n\t\tif Date.today == expiration_date - 1\r\n\t\t\tReminderMailer.food_reminder_msg(@user).deliver\r\n \t\tflash[:notice] = \"#{@user.username} has been notified by email.\" \r\n \tend\r\n end",
"def send_email!\n UserMailer.event_ticket_notification(user, self).deliver_now\n end",
"def event_reminder(reminder)\n @event_start = reminder.event.event_start.to_s(:long)\n mail subject: reminder.event.title,\n bcc: reminder.event.subscribers.collect(&:email)\n end",
"def send_email_changed_notification; end",
"def event_mail\n NoticePlannerMailer.delay.notice_planner_email('lumi.xperia@gmail.com', 'test', 'cron-test', 'https://yahoo.co.jp')\n end",
"def notify\n return if @user.email.blank?\n\n Notifier.user_event_analisys(@user, @user.events.future.analisys.first).deliver_now if @user.events.future.analisys.present?\n Notifier.user_event_visit(@user, @user.events.future.visits.first).deliver_now if @user.events.future.visits.present?\n end",
"def add_reminder; end",
"def calendly_invitee_created\n puts \"Webhook call received for event created by #{calendly_invitee_email}\"\n if Profile.email_exist?(calendly_invitee_email)\n # do nothing\n else\n send_mail_to_invitee\n send_mail_for_event_deletion\n\n\n # Send mail to user, to created profile on our site.\n # Delete Event from calendly, (No documentation for the same)\n end\n end",
"def send_events; end",
"def send_notification\n\n\n end",
"def trigger_event_for_user user, event, data=nil\n Pusher[user.private_channel].trigger!(event,data)\n end",
"def new_event(event)\n @greeting = \"Hello!\"\n @id = event.id\n @desc = event.desc\n @title = event.calendar.title\n mail to: event.calendar.user.email\n end",
"def event_rsvp_created(event, attendee)\n @event = event\n @attendee = attendee\n @message = @event.rsvp_text\n\n return nil if attendee.user.email.blank?\n mail(:to => attendee.user.email, :subject => \"You have RSVP'd to #{event.title}\")\n end",
"def pre_lesson_reminder(user)\n @day = day_of_week_string(Date.tomorrow)\n @user = user\n mail to: user.email, subject: \"Reminder: Complete Pre-Lesson Information\"\n end",
"def moved_up_event_waiting_user\n @user = @receiver\n @notification = @user.notifications.find_by(path: \"/events/#{@event.id}\")\n subject = \"[bootcamp] #{@event.title}で、補欠から参加に繰り上がりました。\"\n mail to: @user.email, subject: subject\n end",
"def reminder(attendance_id, type)\n sendgrid_category \"Tea Time Reminder\"\n\n @attendance = Attendance.includes(:tea_time, :user).find(attendance_id)\n @user = @attendance.user\n @type = type\n @tea_time = @attendance.tea_time\n\n mail.attachments['event.ics'] = {\n mime_type: \"text/calendar\",\n content: IcalCreator.new(@tea_time).call.to_ical\n }\n\n cancel_delivery unless @attendance.pending?\n\n mail(to: @user.email,\n from: @tea_time.host.friendly_email(at_tws: true),\n subject: \"Your tea time is coming up!\") do |format|\n format.text\n format.html\n end\n end",
"def event_admin_message_notice(action, user, event)\n @action = action\n @user = user\n @event = event\n \n mail(:to => @user.email, :subject => \"#{@action.user.name} posted on your StreetMeet - #{event.title}\") unless @user.email.blank?\n end",
"def reminder\n ENV['TWILIO_NUMBER'] = '+19803656325'\n ENV['TWILIO_ACCOUNT_SID']= 'AC42b26049da2a7e3556c17a940b75d163'\n ENV['TWILIO_AUTH_TOKEN'] = 'e099f1d5f14b1ddcfcf9376bafb5e3c5'\n \n @twilio_number = ENV['TWILIO_NUMBER']\n @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']\n \n #time_str = ((self.interviewdate).localtime).strftime(\"%I:%M%p on %b. %d, %Y\")\n reminder = \"Hi. Just FUCK OFF\"\n \n message = @client.account.messages.create(\n :from => @twilio_number,\n :to => '+17043450672',\n :body => reminder,\n )\n puts message.to\n end",
"def send_email_changed_notification?; end",
"def fatigue(user, event)\n @greeting = \"Hi #{user.first_name}\"\n\n @event = event\n\n @link = \"toto\"\n\n mail to: user.email\n end",
"def send_one_week_reservation_reminder(email)\n @email = email\n mail(to: email, subject: 'Your Pet Boarding Reservation Reminder [RCN]')\n end",
"def show_reminder\n mail to: @guest.email, subject: \"Reminder: \"+@user.name+\" house show\"\n end",
"def send_reminder(guid)\n post \"/api/documents/#{guid}/send_reminders.xml\", {}\n end",
"def notify_admin_about_newbie(user)\n @user = user\n mail \n end",
"def reminder(user)\n @reminder = \"Hallo #{user.name}, je hebt nog niet aangegeven of je aanwezig bent voor de aankomende wedstrijd of training. Doe dit vandaag nog anders wordt je automisch afwezig gemeld. Dit is een automatisch bericht, niet op reageren aub.\"\n\n mail to: user.email, subject: \"Parkstad, doorgeven van je aanwezigheid\", bcc: \"peter_vd_berg@hotmail.com\"\n end",
"def reminding_exec\n return nil unless @timelog_active\n @log.debug(\"Sending reminder through notify.\")\n Knj::Notify.send(\"time\" => 5, \"msg\" => sprintf(_(\"Tracking task: %s\"), @timelog_active[:descr]))\n end",
"def control_reminder\n UserMailer.control_reminder(User.control.first)\n end",
"def schedule_appointment(appointment, which)\n # sendgrid_category \"Sell Request\"\n @appointment = appointment\n if which == 1\n mail to: @appointment.user.email, subject: \"Appointment schedule confirmation\"\n else\n email = \"tripalink.dev@gmail.com\" if !@appointment.expert\n mail to: email, subject: \"Appointment schedule confirmation\"\n end\n end",
"def event_info_email(user)\n mail( to: user.email,\n subject: \"Your Event info\",\n @body['contract'] => contract\n )\n end",
"def appointment_notification(event, client)\n @intake_form = ENV[\"INTAKE_FORM\"]\n @office_location = ENV[\"OFFICE_LOC\"]\n @event = event\n @counselors = return_counselor_lists(@event.users)\n @name = client.name\n email_with_name = %(\"#{client.name}\" <#{client.email}>)\n mail(to: email_with_name, subject: 'Appointment reminder and intake form for ITPH')\n end",
"def send_reminder_email \n UserMailer.reminder_email(self).deliver\n end",
"def new_game\n @greeting = \"Hi\"\n# @all_rsvps = Rsvp.where(\"event_id = ?\", event.id)\n #@all_rsvps.each do |rsvp|\n # @user = User.where(\"id = ?\", rsvp.user_id).first\n #mail(:to => @user.email, :from => \"sibnerian@gmail.com\", :subject => \"Event Change\")\n #end\n\n mail to: \"to@example.org\"\n end",
"def deliver\n if session[:user_id] then\n EVENT_LOG.tagged(DateTime.now, 'ADMIN') { EVENT_LOG.info('Test-firing message push to devices') }\n User.all.each do |user|\n if rand > 0.5\n user.send_notification('test broadcast', :message)\n else\n user.send_notification(\"Please create a weekly entry\", :reminder)\n end\n end\n Rpush.push\n render nothing: true, status: :ok\n else\n redirect_to admin_login_url\n end\n end",
"def reminder\n @twilio_number = ENV['TWILIO_NUMBER']\n @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']\n time_str = (self.time).strftime(\"%I:%M%p\") #on %b. %d, %Y\n app_id = self.id\n reminder = \"Hi #{self.name}. You shold be waking up soon. If you don't want to be disturbed eliminate the alarm whithin the next 7 minutes. Otherwise I'll really make sure you wake up, trust me.\"\n message = @client.account.messages.create(\n :from => @twilio_number,\n :to => self.phone_number,\n :body => reminder,\n )\n puts message.to\n end",
"def invited_notification(user, data_template, company)\n setup_email(user, company.id)\n @subject += 'Event Invitiation'\n @body[:url] = \"#{SITE}/#{company.name}\"\n @support_email = \"#{SUPPORT_EMAIL}\"\n @invited_to_event = \"#{data_template.event.name}\"\n @invited_to_template = \"#{data_template.name}\"\n end",
"def notify_via_service\n u = User.first\n u.update(last_notification_mail_sent: 30.days.ago)\n service = NotificationDigest.new(type: :notifications)\n service.notify_user(u, deliver: false)\n end",
"def notify\n ReminderMailer.notify\n end",
"def reminder\n @rest_name = self.restaurant.name\n @rest_phone = self.restaurant.phone\n @twilio_number = ENV['TWILIO_NUMBER']\n @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN']\n time_str = ((self.datetime).localtime).strftime(\"%I:%M%p on %b. %d, %Y\")\n reminder = \"Hi #{self.diner_name}. Don't forget your reservation for #{@rest_name} coming up at #{time_str}! Call to cancel: #{@rest_phone}.\"\n message = @client.account.messages.create(\n :from => @twilio_number,\n :to => self.diner_phone,\n :body => reminder\n )\n end",
"def new_event(event)\n # @greeting = \"Hi\"\n\n\n @greeting = \"Hello \" + ((event.who != \"\") ? (event.who + \",\") : \"there!\")\n @event = event\n\n mail( to: event.email, subject: event.name)\n end",
"def sendEventInvite(e, u)\n if !isSignedIn\n redirect_to root_url, notice: \"You must be signed in to send invites.\"\n else\n @e = current_user.events.find_by(id: e)\n @u = User.find_by(id: u)\n\n if @e == nil\n redirect_to '/users/' + u, notice: \"You do not own this event.\"\n elsif @u == nil\n redirect_to root_url, notice: \"This user does not exist.\"\n elsif isAttending(e, u)\n redirect_to '/users/' + u, notice: \"This user is already attending this event.\"\n elsif isInvited(e, u)\n redirect_to '/users/' + u, notice: \"This user is already invited to this event.\"\n else\n @n = @u.notifications.build(:user_id => u, :title => 'New Event Invite', :desc => getName(u, current_user.id) + \" has invited you to attend their event \" + @e.name + \".\", :sender_id => e, :notification_type => 3)\n @n.save\n respond_to do |format|\n format.html { redirect_to '/users/' + u, notice: 'Invitation Sent.' }\n format.json { head :no_content }\n end\n end\n end\n end",
"def account_setup_reminder(user)\n setup_email(user)\n \n @subject = subject_from_sym :account_setup_reminder\n @body[:name] = user.full_name\n @body[:setup_url] = account_setup_url(:id => user.perishable_token, :ref => 'asr1')\n \n add_category_header \"Account Setup Reminder\"\n end",
"def invited_and_create_notification(user, data_template, company)\n setup_email(user, company.id)\n @subject += 'Event Invitiation'\n @body[:url] = \"#{SITE}/activate/#{user.activation_code}\"\n @body[:loginurl] = \"#{SITE}/#{company.name}\"\n @support_email = \"#{SUPPORT_EMAIL}\"\n @invited_to_event = \"#{data_template.event.name}\"\n @invited_to_template = \"#{data_template.name}\"\n end",
"def send_reminder_email(user, expiringtasks)\n @user = user\n @expiringtasks = expiringtasks\n mail( :to => @user.email ,\n :subject => '[Todo Manager] Task Reminder')\n end",
"def processEvent( client, user, t_event )\n#\t\tclient.room.say(\"Processing Event #{t_event}\")\n if user.id != client.user.id\n $botData['events'].each { |event|\n if event['event'] == t_event\n if event['delivery_method'].to_i == 1\n if event['include_name'].to_i == 0\n client.room.say(event['pre_text'] + event['post_text'])\n else\n client.room.say(event['pre_text'] + user.name + event['post_text'])\n end\n else\n if event['include_name'].to_i == 0\n user.say(event['pre_text'] + event['post_text'])\n else\n user.say(event['pre_text'] + user.name + event['post_text'])\n end\n end\n end\n }\n end\nend",
"def to_chef_recipe_evt_req(req)\n @req = req\n @chef = User.find(req.chef_id)\n @mi = Menuitem.find(req.menuitem_id)\n mail(:to => @chef.email, :subject => \"Event Request for Local Yum Item\", :from => \"\\\"Local Yum\\\" <contact@localyum.me>\")\n end",
"def notify_admin_about_newbie(user)\n @user = user\n mail\n end",
"def update_schedule\n role_id = current_user.role_id\n schedule = Schedule.get_schedule_array\n create_schedule = Schedule.get_create_schedule_array\n delete_schedule = Schedule.get_delete_schedule_array\n if Schedule.send_email(role_id,schedule,create_schedule,delete_schedule)\n flash[:success] = \"Users Notified!\"\n redirect_to root_path\n else\n flash[:error] = \"Some error occured! Please try again!\"\n redirect_to (:back)\n end\n end",
"def send_notifications\n end",
"def send_user_reminder_notice(user)\n return if user.email.nil?\n return if user.last_reminder.sent_at < one_week_ago\n EmailSender.send_notice_to(user.email)\nend",
"def event_edit_notice(user, event)\n @user = user\n @event = event\n mail(:to => @user.email, :subject => \"StreetMeet - #{event.title}' has been edited\") unless @user.email.blank?\n end",
"def send_reminder\n @reminder = Reminder.find(params[:id])\n @order = @reminder.order\n \n @reminder.send_email(params)\n \n flash[:notice] = \"Your email was successfully sent at #{current_time}\"\n redirect_to :action => :reminders, :id => @order\n end",
"def send_reminder\n superuser = authorized? @reservation\n \n if @reservation.user != current_user && !superuser\n flash[ :alert ] = \"Reminders can only be sent by their owner, an admin, or an instructor.\"\n elsif @reservation.session.in_past? && !superuser\n flash[ :alert ] = \"Reminders cannot be sent once the session has ended.\" \n else\n @reservation.send_reminder\n flash[ :notice ] = \"A reminder has been sent to #{@reservation.user.name}.\"\n end\n \n if @reservation.user == current_user\n redirect_to reservations_path\n elsif superuser\n redirect_to sessions_reservations_path( @reservation.session )\n else\n redirect_to root_url\n end\n end",
"def user_event_confirmed(user, event)\n @user = user\n @event = event\n meeting = user.meetings.find_by(event: event)\n attachments.inline['prenotazione.ics'] = meeting.ical.to_ical if meeting.confirmed?\n mail(to: @user.email, subject: t('user_event_modified', scope: 'message.email.subjects') + ' ' + (l event.date_on)) if user.email.present?\n end",
"def user_event_analisys(user, event)\n @user = user\n @event = event\n @meeting = user.meetings.find_by(event: event)\n\n mail(to: @user.email, subject: t('user_event_analisys', scope: 'message.email.subjects')) if @user.email.present?\n end",
"def new_schedule_notification(schedule)\n @schedule = schedule\n mail to: schedule.person.email, subject: \"Your new schedule : #{schedule.service.name} - #{schedule.role.name}\"\n end",
"def send_day_before_reservation_reminder(email)\n @email = email\n mail(to: email, subject: 'Your Pet Boarding Reservation Reminder [RCN]')\n end",
"def signed_up_alert(evt)\n @evt = evt\n host = User.find_by_id(@evt.user_id)\n mail(:to => host.email, :subject => \"There is a seat request for your Local Yum event\", :from => \"\\\"Local Yum\\\" <notification@localyum.me>\")\n end",
"def make_reminder(minutes_before = 510)\n Google::Apis::CalendarV3::EventReminder.new({\n minutes: minutes_before,\n reminder_method: 'popup'\n })\nend",
"def send_email\n AlertNotifier.delay.email_back_office_announcement(self)\n end",
"def send_event(type, name, id, info)\n message = create_message(:cmdtype => type, :target => @@myName, \n :value => name, :appID => id, :message => info) \n send_message(@@myECAddress, message)\n end",
"def reminder\n twilio_number = ENV['TWILIO_NUMBER']\n account_sid = ENV['TWILIO_ACCOUNT_SID']\n client = Twilio::REST::Client.new account_sid, ENV['TWILIO_AUTH_TOKEN']\n time_str = ((self.exact_time).localtime(\"+00:00\")).strftime(\"%I:%M%p on %b. %d, %Y\")\n reminder = \"Hi #{self.name}. TASK ALERT: This is your #{task_category} reminder: #{task_title}. You set your reminder for #{time_str}. To see details, check your profile for more information. \\n -Own Up Grown Up\"\n message = client.api.account.messages.create(\n :from => twilio_number,\n :to => phone_number,\n :body => reminder,\n )\n end",
"def new_participant_notification(participant)\n @participant = participant\n @pid = @participant.id\n @name = @participant.name\n @greeting = \"Hi\"\n @event_name = @participant.event.name\n @start_time = @participant.event.start_time.to_formatted_s(:long)\n\n mail to: \"#{@name} <#{@participant.email}>\", subject: \"Confirmation Needed: #{@event_name}\"\n end",
"def send_reminder()\n return MicrosoftGraph::IdentityGovernance::AccessReviews::Definitions::Item::Instances::Item::SendReminder::SendReminderRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def user_welcome_reminder(user,subject,message)\n @from = \"REIMatcher <no-reply@reimatcher.com>\"\n @recipients = user.email\n @subject = \"#{subject}\"\n @sent_on = Time.now\n user_activation_link = \"#{REIMATCHER_URL}user_activate/#{user.activation_code}\"\n unless message.blank?\n @body = message.to_s.gsub(\"[User Email]\",user.email.to_s).gsub(\"[User First Name]\",user.first_name.to_s).gsub(\"[User Last Name]\",user.last_name.to_s).gsub(\"[User Login]\",\"<a href='#{user.login.to_s}'>#{user.login.to_s}</a>\").gsub(\"[User Full Name]\",user.first_name.to_s + \" \" + user.last_name.to_s).gsub(\"[User Activation Link]\",\"<a href='#{user_activation_link}'>#{user_activation_link}</a>\")\n else\n @body = \"\"\n end\n @content_type = \"text/html\"\n reminder_welcome_email_header = {:category => EMAIL_CATEGORIES[:ar]}\n @headers[\"X-SMTPAPI\"] = reminder_welcome_email_header.to_json unless reminder_welcome_email_header.blank?\n# @headers[\"X-SMTPAPI\"] = header\n end",
"def after_update_challenge\n send_email_after_canceled_reactive\n send_email_after_change_start_date\n end",
"def send_lesson_reminder_email\n UserMailer.lesson_reminder(mentor).deliver_now\n end",
"def new_event(player, event)\n @player=player\n @event = event\n emails = \"#{player.email},#{player.parent_email},#{player.parent_email2}\"\n mail(to: emails, subject: \"#{event.eventtype.name} scheduled #{event.the_date}\")\n end",
"def send_event(event)\n each { |actor| actor.mailbox.system_event event }\n end",
"def send_final_exam_invitation!\n update_attribute(:final_exam_invitation_sent_at, Time.now)\n end",
"def notify_custom_event(facebook_user_id, event_name, value, level_id, st1=nil, st2=nil, st3=nil )\n path = \"/api/v1/#{Kontagent.configuration.api_key}/#{MESSAGES_TYPES[:custom_event]}/?s=#{facebook_user_id}\"\n path += \"&n=#{event_name}\" unless event_name.nil?\n path += \"&v=#{value}\" unless value.nil? \n path += \"&l=#{level_id}\" unless level_id.nil? \n\n path += \"&s1=#{st1}\" unless st1.nil? \n path += \"&s2=#{st2}\" unless st2.nil? \n path += \"&s3=#{st3}\" unless st3.nil? \n call_api(path)\n end",
"def send_publish_event_notification(event, user, status)\n success = true\n if user.use_email? && user.confirmed? && event.use_email?\n success = handle_send_publish_event_notification(event, user, status, \"email\")\n end\n if user.use_text? && user.confirmed_text? && event.use_text?\n success = handle_send_publish_event_notification(event, user, status, \"text\")\n end\n if user.use_call? && user.confirmed_call? && event.use_call?\n success = handle_send_publish_event_notification(event, user, status, \"call\")\n end\n unless success\n status.not_delivered!\n end\n set_new_state_after_notify(success, event, status)\n end",
"def perform(user)\n # Do something later\n ActiveSupport::Notifications.instrument \"event\" , { foo: \"event firing in welcome user\" }\n WelcomeMailer.with(user: user).welcome_email.deliver_now\n end",
"def send_invoice_reminder(project)\n MemberMailer.invoice_reminder_for_project_admin(self, project).deliver_now\n end",
"def reminder\n @headhunter = Headhunter.first.id\n HeadhunterMailer.reminder(@headhunter)\n end",
"def send_ticket_to_user(user_id, event_id)\n UserMailer.send_ticket(user_id, event_id).deliver_later\n end",
"def invitee_action\n begin\n if check_magic_token\n\n event_type = params[:event]\n calendar_email = params[:payload][:event][:extended_assigned_to][0][:email] # This is the email of the account used to create the calendar\n email = params[:payload][:invitee][:email]\n first_name = params[:payload][:invitee][:first_name]\n last_name = params[:payload][:invitee][:last_name]\n event_name = params[:payload][:event_type][:name]\n start_time = params[:payload][:event][:invitee_start_time_pretty]\n\n\n contact = {}\n contact['FirstName'] = first_name\n contact['LastName'] = last_name unless last_name.blank?\n contact['Email'] = email\n\n applicant_type = 'event_volunteer'\n selected_timeslot = \"#{event_name}: #{start_time}\"\n\n bz_region = User.get_bz_region(applicant_type, calendar_email)\n if bz_region.nil?\n raise NoRegionMappingException \"No bz_region set b/c we haven't mapped the calendar #{calendar_email} to a region for #{applicant_type}\"\n end\n\n if event_type == 'invitee.created'\n calendly_url = User.get_calendar_url(bz_region)\n phone = nil\n company = nil\n title_industry = nil\n city_state = nil\n career = nil\n params[:payload][:questions_and_answers].each do |qa|\n if qa[:question].downcase.include?('phone')\n phone = qa[:answer]\n elsif qa[:question].downcase.include?('employer')\n company = qa[:answer]\n elsif qa[:question].downcase.include?('title')\n title_industry = qa[:answer]\n elsif qa[:question].downcase.include?('career')\n career = qa[:answer]\n elsif qa[:question].downcase.include?('city, state')\n city_state = qa[:answer]\n end\n end\n\n # Note: city_state is supposed to be in the format: City, State. E.g. Brooklyn, NY\n # If it's not, just set the city to the whole string\n city = city_state.split(',')[0]\n state = city_state.split(',')[1]\n\n # Create a BZ User in this platform\n current_user = User.find_by_email(email)\n if current_user.nil?\n current_user = User.new(:first_name => first_name, :last_name => last_name, :email => email, :phone => phone, :applicant_type => applicant_type, :city => city, :state => state, :external_referral_url => calendly_url, :bz_region => bz_region)\n else\n current_user.bz_region = bz_region\n current_user.applicant_type = applicant_type\n end\n current_user.skip_confirmation!\n current_user.save!\n\n # Create the user in salesforce\n contact['Phone'] = phone\n contact['Signup_Date__c'] = DateTime.now\n contact['MailingCity'] = city\n contact['MailingState'] = state unless state.nil?\n contact['Company__c'] = company\n contact['Title'] = title_industry # Both their title and industry could have commans, so can't split reliable. Just stuff it all in Title field.\n contact['Career__c'] = career\n contact['BZ_Region__c'] = bz_region\n contact['User_Type__c'] = 'Event Volunteer'\n contact['BZ_User_Id__c'] = current_user.id\n contact['Came_From_to_Visit_Site__c'] = calendly_url\n\n salesforce = BeyondZ::Salesforce.new\n existing_salesforce_id = salesforce.exists_in_salesforce(email)\n client = salesforce.get_client\n if !existing_salesforce_id.nil?\n client.update('Contact', existing_salesforce_id, contact)\n else\n # There is a bug in calendly where Last Name is not actually a required field.\n # This is meant to put something in that field so at least a Salesforce record is created.\n contact['LastName'] = '<Missing>' if last_name.blank?\n\n # Note: for new users that volunteer, we don't create BZ Users. We just populate a new Salesforce\n # contact as though it was done manually. Only Fellows and LCs get BZ Users after this calendly integration goes live.\n contact['LeadSource'] = 'Volunteer Signup'\n contact['OwnerId'] = current_user.salesforce_lead_owner_id # Note that if they are already in Salesforce, we assume they have an Owner already.\n contact = client.create('Contact', contact)\n existing_salesforce_id = contact.Id\n end\n\n current_user.salesforce_id = existing_salesforce_id\n current_user.skip_confirmation!\n current_user.save!\n \n cm = current_user.auto_add_to_salesforce_campaign('Confirmed', selected_timeslot)\n if cm.nil?\n logger.debug \"######## Failed to create Campaign Member for #{current_user.inspect}. Dunno why though.\"\n end\n\n current_user.create_mailchimp\n\n elsif event_type == 'invitee.canceled'\n current_user = User.find_by_email(email)\n if !current_user.nil?\n current_user.bz_region = bz_region\n current_user.applicant_type = applicant_type\n cancellation_reason = params[:payload][:invitee][:cancel_reason]\n current_user.cancel_volunteer_signup(selected_timeslot, cancellation_reason)\n else\n logger.warn \"No user with email = #{email} found -- NOOP\"\n end\n\n else\n logger.warn \"Unrecognized event type found: #{event_type} -- NOOP\"\n end\n end\n # Need to catch all exceptions and always report that it was OK b/c Calendly will put the webhook\n # in a failed state and stop calling our endpoint until we delete and re-register the hook.\n rescue Exception => e\n logger.warn \"###### Caught #{e.inspect} -- may have failed to add the Volunteer signup information into Salesforce.\"\n end\n\n render plain: 'OK'\n end",
"def new_notification\n mail(to: \"rhammett@ycp.edu\", subject: 'New Notification', sent_on: Time.now)\n end",
"def new_date_event_application(notification_id)\n @notification = Notification.find(notification_id)\n @date_event_application = @notification.notifiable\n @user = @notification.user\n\n return if !@notification.should_send_email?\n\n @gender_name = him_her_them(@date_event_application.sex)\n @url = Api::V1::ApplicationController.build_frontend_uri(\n \"/dates/#{@date_event_application.date_event_id}/pick-someone/#{@date_event_application.id}\",\n {}\n )\n\n @emoji = emoji_label(@date_event_application)\n @label = category_label(@date_event_application)\n @formatted_time = format_date_event_time(@date_event_application)\n subject_line = [\n \"#{@date_event_application.name} wants to #{@emoji} #{@label} with you\",\n \"#{@emoji} with #{@date_event_application.name} #{@formatted_time}?\",\n ].sample\n\n @notification.update!(email_sent_at: DateTime.now)\n\n mail to: @user.email, subject: subject_line\n end",
"def schedule_reminder_email\n \tstart_time = Time.at(available_slot.start_time).strftime(' %H:%M')\n \tdate = appointment_date.to_s\n \tschedule_time = (Date.parse(date + start_time) - 30.minutes)\n \tReminderMailer.send_reminder(patient).deliver_later(wait_until: schedule_time)\n end",
"def after_create_sendgrid_event(event_data)\n end",
"def shift_notify(shift, employee)\n @shift_name = shift.employee.full_name\n @employee_name = employee.full_name\n @shift_time = shift.shift_day.strftime(\"%a-%d-%b\")\n @employee = employee.id\n @email = shift.employee.email\n\n mail(to: @email, subject:'Interested in your Shift')\n end",
"def email_reminder(week_id,day)\n # can we use a template?\n puts \"checking #{self.name}\"\n my_result = self.weekly_results.find_by(week_id: week_id) ||\n self.weekly_results.create(week_id: week_id)\n if my_result.send(\"#{day}_drinks\").nil? && !self.unsubscribed\n # generate a token and save to Redis\n puts \"No data for #{self.name} - #{Date.today}. Sending email\"\n my_token = SecureRandom.urlsafe_base64\n packet = {\n user: self.id,\n result: my_result.id,\n parameter: day\n }\n $redis.set(my_token,packet.to_json,{ex: 604800})\n # TODO: fix this bad workaround\n u = self\n # send email\n message = Mail.new do\n from ENV['EMAIL_FROM']\n to \"#{u.name} <#{u.email}>\"\n subject 'BoozeTracker Reminder'\n content_type 'text/html; charset=UTF-8'\n body \"<p>Did you have a drink yesterday?</p><p><a href='#{BASEURL}/token/#{my_token}?result=yes'>Yes</a> | <a href='#{BASEURL}/token/#{my_token}?result=no'>No</a></p><p>--</p><p>Brought to you by <a href='#{BASEURL}'>BoozeTracker</a> | <a href='#{BASEURL}/user/toggle-subscription?token=#{my_token}'>Unsubscribe</a></p>\"\n delivery_method Mail::Postmark, api_token: ENV['POSTMARK_API_TOKEN']\n end\n message.deliver\n\n else\n end\n\n\n end",
"def newly_created_opportunity\n # users = User.on_new_opportunity_subscriber\n user = User.find(97)\n opportunity = Opportunity.find(@opportunity_id)\n #NotificationMailer.newly_created_opportunities(user, opportunity).deliver_now\n opportunity.opportunity_email_notification.update_recently_added\n puts \"Notificação oportunidade criada recentemente\"\n end",
"def email_reminder(day)\n return if result(day) || unsubscribed\n send_email_reminder(day)\n end",
"def send_email_reminder(day)\n recipient = \"#{name} <#{email}>\"\n body = email_body(day)\n message = Mail.new do\n from ENV['EMAIL_FROM']\n to recipient\n subject 'BoozeTracker Reminder'\n content_type 'text/html; charset=UTF-8'\n body body\n delivery_method Mail::Postmark, api_token: ENV['POSTMARK_API_TOKEN']\n end\n message.deliver\n end",
"def survey_reminder(user)\n @user = user\n mail to: user.email, subject: \"Reminder: Complete Post-Lesson Survey\"\n end",
"def prebooking_reminder(service)\n notification = Notification.find_by_name(\"Pre booking reminder\")\n vehicle = service.fleet\n setting = vehicle.truck_fleet.setting.email_notifications.find_by_notification_id(notification.id)\n emails = self.find_emails(vehicle, setting)\n if emails.present?\n mail :to => emails,\n :subject => \"Prebooking reminder. For #{vehicle.fleet_number}\"\n end\n end",
"def trigger_email(data)\n data.dig(:options, :mailer).send(\"#{data[:trigger]}_email\", data[:instance]).deliver_now\n end"
] |
[
"0.7809899",
"0.7316274",
"0.71923053",
"0.71556234",
"0.7012851",
"0.6966477",
"0.6963192",
"0.6955951",
"0.6951478",
"0.6891523",
"0.6850651",
"0.6811893",
"0.67579454",
"0.6750615",
"0.66504407",
"0.66271234",
"0.66061294",
"0.6562785",
"0.65620184",
"0.6515868",
"0.6514672",
"0.64642894",
"0.64554286",
"0.6426536",
"0.6412803",
"0.6409708",
"0.6401283",
"0.63867104",
"0.63714147",
"0.6371104",
"0.63511646",
"0.63221234",
"0.63216734",
"0.63203347",
"0.6318303",
"0.63110757",
"0.63086975",
"0.6305199",
"0.63022774",
"0.6301382",
"0.6297596",
"0.6280643",
"0.62796384",
"0.62255526",
"0.6220875",
"0.62194276",
"0.6216213",
"0.62088937",
"0.6205531",
"0.6202879",
"0.6199716",
"0.6184133",
"0.61833555",
"0.6173276",
"0.6169914",
"0.6169846",
"0.61694413",
"0.6163338",
"0.6161628",
"0.615764",
"0.61562943",
"0.6155975",
"0.61503017",
"0.6149253",
"0.6149093",
"0.61488825",
"0.6143868",
"0.61318254",
"0.61303324",
"0.61088216",
"0.6096473",
"0.60864586",
"0.60863274",
"0.6085217",
"0.6081918",
"0.6081887",
"0.6070075",
"0.6069056",
"0.60681725",
"0.60650754",
"0.6028372",
"0.6018159",
"0.60070395",
"0.59963804",
"0.5995752",
"0.5992794",
"0.5992603",
"0.59797513",
"0.59770864",
"0.5976364",
"0.59738386",
"0.59730303",
"0.5969854",
"0.5968393",
"0.5957834",
"0.59557045",
"0.5954903",
"0.5952651",
"0.5950467",
"0.594754"
] |
0.61183244
|
69
|
USED called from user registrations service send confirmation email to user
|
def invited_user_registered(user)
UserMailer.delay.user_registered_confirmation(user)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def send_confirmation_to(user)\n token_link = \"http://localhost:9292/validate/\" + user.validation_token\n template_locals = { :user => user, :token_url => token_link}\n send_email_to_user(user,\"Frank requests that you verify your email address.\" ,:'mail/new_registration', template_locals)\n end",
"def registration_confirmation(user)\n @user = user\n\n mail to: \"yisheng90@gmail.com\", subject: \"Success! You did it.\"\n end",
"def after_confirmation # Send welcome mail after user is successfully registered\n send_user_mail\n end",
"def request_confirm_email _user\n @confirmation = find_or_create_for_user(_user)\n mail( to: _user.email, subject: \"Please confirm your email address\")\n end",
"def email_confirm\n end",
"def confirmation(user)\n @user = user\n @user.generate_confirmation_code\n mail(to: @user.email, subject: \"Confirmation\") do |f|\n f.html\n end\n\n end",
"def resend_confirmation_email\n WEPAY.call('/user/resend_confirmation', self.wepay_access_token, {\n email_message: 'Thank you for signing up with WeCrowd. In order to process payments, you will need to confirm your email address and set a secure payment password. Click the \"confirm\" button below to begin.'\n })\n end",
"def registration_confirmation(user) \n @user=user\n mail(:to => user.email, :subject => \"[给力百货]注册邮箱验证\")\n end",
"def registration_confirmation(user)\n @account = user\n mail(:to => named_email(user), :subject => \"Outcircle - Welcome\")\n end",
"def confirm_email(user)\n @user = user\n @confirm_url = \"http://www.yscalumni.org/confirm/\" + user.confirmation_code\n mail(:to => user.email, :subject => \"Welcome to yscalumni.org! Please confirm your email!\")\n end",
"def registration_confirmation(user)\n @user = user\n mail(to: \"#{user.name} #{user.last_name} <#{user.email}>\",\n subject: '(IMI-Map) Registered')\n end",
"def signup_confirmation(user)\n @user= user\n debugger\n mail to: @user.email , subject: \"MovieBox Sign Up Confirmation\"\n \n end",
"def registration_confirmation(user)\n \t@user = user\n \tmail(:to => \"#{user.name} #{user.last_name} <#{user.email}>\", :subject => \"(IMI-Map) Registered\")\n end",
"def confirmation_email(user)\n # email header info MUST be added here\n @recipients = user.email\n @from = \"#{Site.current.email}\"\n @subject = \"SIR Information:: Welcome to SIR\"\n\n # email body substitutions go here\n @body[\"name\"] = user.login\n @body[\"hash\"] = user.activation_code\n end",
"def user_registered_confirmation(player)\r\n @user = player\r\n @tenant = LandLord.new(@user).tenant\r\n \r\n from = determine_mail_from_for_general_notifications(@tenant)\r\n to = format_email_to_user(@user)\r\n subject = subject_for_user_registered_confirmation\r\n \r\n mail(:from => from, :to => to, :subject => subject)\r\n end",
"def signup_confirmation(user)\n @user = user\n\n mail to: user.email, subject: \"Sign Up Confirmation\"\n end",
"def registration_confirmation(user)\n @user = user\n mail :to => \"#{user.name} <#{user.email}>\", :subject => \"Thanks for Registering\"\n end",
"def signup_confirmation user\n @user = user\n mail to: user.email, subject: \"Welcome to the Clone\"\n end",
"def registration_confirmation\n\t\tuser = User.new\n\t\tuser.generate_token(:email_confirmation_token)\n\t\tUserMailer.registration_confirmation(user)\n end",
"def send_confirmation_instructions; end",
"def signup_confirmation(user)\n @user = user\n mail to: user.email, subject: \"Sign Up Confirmation\"\n end",
"def signup_confirmation_advisee(user)\n @user = user\n mail to: @user.email, subject: \"Advisee new registration\"\n end",
"def confirmation_instructions(user, token, somethingElse)\n AccountMailer.default_url_options[:host] = \"tep-lending-library.herokuapp.com\"\n @resource = user\n @password = user.password\n @token = token\n @name = user.first_name\n @email = user.email\n mail(to: @resource.email, subject: \"Confirm Email\", :tag => \"Welcome to the TEP Lending Library!\")\n mail.delivery_method.settings.merge! @@smtp_settings\n mail\n end",
"def signup_confirmation(user_id)\n # Will make the newly registered user available to the view that will generate the email content\n @user = User.find(user_id)\n\n mail to: @user.email, subject: \"Sign up confirmation\"\n end",
"def confirm_email(confirmation)\n @confirmation = confirmation\n @account = confirmation.account\n \n mail :to => confirmation.unconfirmed_email\n end",
"def confirm_account(user)\n @name = user.first_name\n @confirm_url = confirm_url(user.token)\n\n mail to: user.email, subject: 'Account confirmation'\n end",
"def resend_confirmation_email\n unless current_user.confirmed?\n current_user.send_confirmation_instructions\n flash[:success] = I18n.t('flash.success.confirmation_sent')\n end\n redirect_to home_path\n end",
"def confirm!\n UserMailer.new_registration(self).deliver_now\n super\n end",
"def confirmation_email(puser)\n @puser = puser # Instance variable passed into the view to be used\n mail(:to => puser.email, :subject => \"Confirm your Account\")\n end",
"def confirmation(user)\n \n @user = user\n\n if Rails.env.production?\n @root_path = \"http://allianz-community.com/\"\n else\n @root_path = \"http://localhost:3000/\"\n end\n\n @confirm_path = @root_path + users_confirm_path + \"?id=\"+@user.id.to_s+\"&hash=\" + @user.confirm_hash\n mail to: @user.mail, subject: 'Email confiramtion'\n end",
"def referral_confirmation_email\n\n end",
"def signup_confirmation(user)\n @user = user\n mail to: user.email, subject: \"Signup confirmation from FreeLance\"\n end",
"def signup_confirmation(user)\n @greeting = \"Hi\"\n @user = user\n\n mail to: user.email, subject: \"Sign up confirmation!\"\n end",
"def signup_confirmation(user)\n @user = user\n mail to: user.email, subject: \"Welcome\"\n end",
"def signup_confirmation(user)\n # create an instance variable so that the view has access\n # to the user.\n @user = user\n\n # send email to the user\n mail to: user.email, subject: \"Sign Up Confirmation\"\n end",
"def signup_confirmation(user)\n @user = user\n @greeting = \"Hi\"\n\n mail to: @user.email, subject: \"Hello new friend!\"\n end",
"def activation_confirmation(user)\n user_login_link(user)\n\n @greeting = \"Thank you for choosing Contractor\"\n @name = user.name\n\n mail to: user.email\n end",
"def activation_confirmation(user)\n @root_url = root_url\n mail(:subject => setup_subject(I18n.t('activation_complete')),\n :to => user.email)\n end",
"def account_confirmed(user)\n @notify_subject = strip_tags( \"USER CONFIRMED ACCOUNT AT #{ENV['APPLICATION_CONFIG_name']}\")\n @user = user\n mail( :to => ENV['APPLICATION_CONFIG_admin_notification_address'], :subject => @notify_subject)\n end",
"def send_confirmation_email\n user = User.find_by_username params[:username]\n raise ActiveRecord::RecordNotFound unless user\n\n command = SendConfirmationEmailCommand.new(user, current_user,\n request.remote_ip)\n begin\n command.execute\n rescue => e\n flash['error'] = \"#{e}\"\n else\n flash['success'] = 'Confirmation email sent.'\n ensure\n redirect_back fallback_location: user_url(user)\n end\n end",
"def deliver_confirmation_email_instructions!\n # TODO\n end",
"def confirm_email\n user = User.find_by_confirm_token(params[:id])\n if user\n user.email_activate\n end\n end",
"def signup_confirmation(new_user)\n # @greeting = \"Hi\"\n @resource = new_user\n \n # mail to: new_user.email\n mail(to: @resource.email, subject: \"Welcome!\", :tag => 'password-reset', :content_type => \"text/html\") do |format|\n format.html { render \"user_mailer/signup_confirmation\" }\n end\n \n end",
"def activation_success_email(user)\n # TODO: Implement actual functionality -- Wed Jun 13 15:26:53 2012\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\"\n end",
"def confirm_email\n user = User.find_by_email_confirm_token(params[:confirm_token])\n if user\n user.email_activate\n flash[:success] = \"La tua email è stata confermata! Benvenuto!\"\n log_in user\n remember(user)\n redirect_to groups_path\n else\n flash[:error] = \"Siamo spiacenti, ma pare che l'utente non esista.\"\n redirect_to login_path\n end\n end",
"def confirmation_email(registrations)\n unless registrations.empty?\n @response_email = ResponseEmail.find_by_purpose('auto_response')\n @body = format_confirmation_email(@response_email.body, registrations)\n mail(:to => registrations.first.user.email, :subject => @response_email.subject, :reply_to => @response_email.reply_to)\n end\n end",
"def activation_needed_email(user)\n @user = user\n @url = users_activate_path(id: user.activation_token)\n mail(to: user.email, subject: \"#{User.model_name.human}登録を完了しましょう!\")\n end",
"def confirmation_instructions(user, token, opts)\n my_mail = Mailjet::Send.create(messages: [{\n 'From'=> {\n 'Email'=> Rails.application.credentials.default_email,\n 'Name'=> 'Alim-Alo'\n },\n 'To'=> [{\n 'Email'=> user.email,\n 'Name'=> \"User <3\"\n }],\n 'Subject'=> 'Merci de votre inscription.',\n 'HTMLPart'=> \"<h1>Merci de votre inscription!</h1>\n <a href= '#{user_confirmation_url(@resource, confirmation_token: token)}'>Confirmer mon compte</a>\"\n }]\n )\n\n end",
"def confirm!\n welcome_email\n super\n end",
"def user_confirm_email(current_user)\n @current_user = current_user\n mail(to: current_user.email, subject: 'Confirm Email', from:\"PawBookings <no_reply@pawbookings.com>\")\n end",
"def send_signup_notification\n deliver_activation_email(:signup, :subject => (MaSA[:activation_subject] || \"Please Activate Your Account\") )\n end",
"def signup_email\n MnoEnterprise::SystemNotificationMailer.registration_instructions(params.require(:user).require(:email)).deliver_later\n\n head :no_content\n end",
"def smb_confirm(user)\n @smb = user\n mail(:to => user.email, :subject => \"Registration Confirmation\")\n end",
"def send_confirmation_request\n send_confirmation_email\n send_confirmation_notification\n end",
"def reservation_confirmation\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\"\n end",
"def signup_confirmation(user_name, user_email)\n @user_name = user_name\n @user_email = user_email\n mail to: user_email, subject: \"Dum dum de dum... get started with Bridled!\"\n end",
"def signup_confirmation(user, root_url)\n @user = user\n @url = root_url + 'login'\n mail(to: user.username, subject: 'Sign Up Confirmation')\n end",
"def triggerConfirmation\n\n user = getUserByAuthToken(request)\n user.resend_confirmation_instructions\n\n if(user.errors.blank?)\n logger.info \"Email confirmation instructions were sent for user #{user.email}\\n\"\n raw_token = user.instance_variable_get(\"@raw_confirmation_token\")\n\n the_response = { :confirmation_sent_at => user.confirmation_sent_at }\n\n enable_test_hooks = Rails.application.config.enable_test_hooks\n if(enable_test_hooks)\n # Assume we're in test environment - add hook in response to enable testing\n logger.info \"Including raw confirmation token in response: #{raw_token}\\n\"\n the_response[:confirmation_token] = raw_token\n end\n\n render :status => 201, :json => the_response\n else\n if(!user.errors.messages[:email].blank?)\n logger.error \"Devise said: \\\"#{user.errors.messages[:email]}\\\". Interpret as no email confirmation pending for #{user.email} (user id: #{user.id}), instructions will not be emailed.\\n\"\n render :status => 412, :json => {:error => \"No email confirmation pending\"}.to_json\n else\n logger.error \"Unexpected error encountered when attempting to send confirmation instructions for #{user.email}. Error: #{user.errors.inspect}.\\n\"\n render :status => 500, :json => {:error => I18n.t(\"500response_internal_server_error\")}.to_json\n end\n end\n end",
"def confirm_request\n @email = params[:email]\n @confirmation_code = params[:confirmation_code]\n mail to: @email\n end",
"def register_confirmation(address)\n \tmail to: address\n # mail to: 'appdente@gmail.com'\n end",
"def confirm_email\n\t user = User.find_by(confirm_token: user_params[:confirm_token])\n\t if user\n\t \t# Reset all the actions\n\t\t\tuser.email_confirmed = true\n\t\t\tuser.confirm_token = \"\"\n\t\t\tuser.save\t\n\t\t\trender json: {\n\t\t\t\tstatus: 'success',\n\t\t\t\tmessage: 'Account successfully confirmed!'\n\t\t\t}, status: 200\n\t\telse\n\t\t\trender json: {\n\t\t\t\tstatus: 'error',\n\t\t\t\tmessage: 'Account could not be confirmed'\n\t\t\t}, status: 422\n\t end\n\tend",
"def resend_confirmation_instructions; end",
"def sendmail_confirm(user)\n @greeting = \"Hi\"\n @username = user.username\n @userid = user.userid\n\n mail to: \"kat_tun_jinkazu_love@yahoo.co.jp\", subject: \"登録完了通知\"\n end",
"def sendmail_confirm(user)\n @user = user\n mail(to: user.email,\n subject: \"会計よりお知らせ\")\n end",
"def confirmation\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\"\n end",
"def activation_needed_email(user)\n # TODO: Implement actual functionality -- Wed Jun 13 15:26:53 2012\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\"\n end",
"def confirm(user)\n @greeting = \"Hi\"\n @user = user\n\n mail to: user.email, subject: 'Welcome to Hikultura!'\n end",
"def send_confirmation_email\n begin\n UserMailer.registration_email(self).deliver\n rescue Exception => e\n logger.error \"Mail delivery failed: #{e}\"\n return false\n end\n return true\n end",
"def signup_confirmation\n FreelanceMailerMailer.signup_confirmation\n end",
"def sign_up_notification\n # @greeting = \"Hi\"\n\n # mail to: \"to@example.org\"\n # @admin = User.where(is_admin: true).last\n @user = params[:user]\n mail(to: @user.email, subject: 'Sign Up successfull')\n end",
"def send_confirmation_email\n return false if /\\w@(example)\\.com/.match(self.email)\n UserMailer.confirmation(self).deliver unless confirmed?\n end",
"def activation_success_email\n UserMailerMailer.activation_success_email\n end",
"def act_signup_confirmation(user, act)\n @user = user\n @act = act\n\n mail to: user.email, subject: 'Act Sign Up Confirmation'\n end",
"def activation_needed_email(user)\n @user = user\n @account_activation_url = activate_user_url(user.activation_token)\n mail to: user.email, subject: \"ACTION NEEDED: Activate your VCDelta.org account\"\n end",
"def confirmation_instructions(record, token, opts={})\n\t\t@user_name = record.full_name\n \t\t@confirmation_link = \"#{ENV['DOMAIN']}/users/confirmation?confirmation_token=#{token}\"\n\t\tp \"-----------------------------------------------------------------------------\"\n\t\tp \"Confirmation mail for new user - #{record.email}\"\n\t\tp \"-----------------------------------------------------------------------------\"\n \t\t# mail(\"user-mail-confirmation\",email: record.email)\n \t\tmail(to: \"to@gmail.com\", from: \"from@gmail.com\", subject: \"Sample Registration\")\n\tend",
"def signup_confirmation(employee)\n @employee = params[:employee]\n @url = \"http://example.com/login\"\n mail to: employee.email , subject: \"Sign Up Confirmation\"\n end",
"def user_new_item_confirmation\n @greeting = \"Hi\"\n\n mail to: \"to@example.org\", subject: \"Item Confirmation\"\n end",
"def registration_confirmation(customer)\n @customer = customer\n @url = 'www.shizencyokuhan.com'\n @greeting = \"おめでとうございます! あなたのアカウントが登録されました!\"\n mail(to: @customer.email, bcc:'info@shizencyokuhan.org', subject: 'アカウント登録完了のお知らせ' )\n \n end",
"def activation_needed_email(user)\n @user = user\n @activation_url = activate_url(token: user.activation_token)\n mail to: user.email\n end",
"def send_confirmation_email\n # Do Nothing\n end",
"def resend_confirmation_email\n current_user.resend_confirmation_instructions\n respond_to do |format|\n format.html {redirect_to purchase_orders_path, notice: \"Confirmation Email has been re-sent\"}\n end\n end",
"def sendmail_confirm(user)\n @greeting = \"Hi\"\n @user = user\n\n mail to: \"to@example.org\"\n subject: \"test mail\"\n end",
"def rental_confirmation(user)\n @user = user\n \n mail to: @user.email_address, subject: \"Rental confirmation\"\n end",
"def confirm\n if @user = UserConfirmsAccount.new(:token => params[:token]).call\n self.establish_session @user\n redirect_to profile_url, :notice => \"Thanks for confirming #{@user.email}\"\n else\n redirect_to profile_url, :notice => \"There was a problem confirming - try re-sending the email?\"\n end\n end",
"def signed_up(user)\n @user = user\n \n mail to: @user.email, subject: 'Sign Up Confirmation.'\n end",
"def send_confirmation_email\n\t\tRentersConfirmationJob.perform_later self\n OwnersConfirmationJob.perform_later self\n\tend",
"def transaction_created(user)\n @user = user\n mail to: user.email, subject: \"Sign Up Confirmation\"\n end",
"def index\n @user = current_user\n UserMailer.confirmation_email(@user).deliver\n end",
"def send_confirmation_email\n UserMailer.confirmation_email(@user).deliver_now\n UserMailer.confirmation_email(@user.find_match).deliver_now\n end",
"def send_account_notification\n @user = User.find_by_id(params[:id]) \n begin \n url = \"http://www.uncharted.net/account/activation/#{@user.activation_code}\" \n Emailer.deliver_admin_accountactivation(@user.email,url)\t\n end\n flash[:notice] = \"Email has been sent to #{@user.email} to active his account.\"\n redirect_to :action => 'index'\n end",
"def email_verification_instructions(user)\n load_settings\n @user = user\n subject_suffix = \"Account Activation Instructions\"\n #@url = \"http://example.com/login\"\n mail(:to => user.email,\n :subject => \"[#{user.company_name}] #{subject_suffix}\",\n :template_path => 'notifications',\n :template_name => 'another',\n :activate_account_url => activate_accounts_url(:code => user.perishable_token,\n :subdomain => user.company.subdomain),\n :username => user.login,\n :token => user.perishable_token, :subdomain => user.company.subdomain)\n end",
"def email_confirmation\n user = current_resource_owner\n user.email = user.unconfirmed_email\n user.unconfirmed_email = nil\n user.confirmed_at = Time.now\n end",
"def applicant_confirmation(applicant)\n @applicant = applicant\n\n mail to: applicant.username + \"@facebook.com\", subject: \"Greenpeace Belgium: Application confirmation\"\n end",
"def send_signup_email(user)\n @user = user\n @appointment = Appointment.where(id: @user.appointment_id).first\n mail(\n :to => @user.email,\n :bcc => \"acecprsd@gmail.com\",\n :subject => \"Ace CPR SD Sign-Up Confirmation ##{@user.id}\"\n )\n end",
"def confirm\n @greeting = \"Hi\"\n\n mail to: \"proales@proales.com\"\n end",
"def signup_notification(user)\n provider = self.provider_account = user.account.provider_account\n\n subject = user.account.provider? ? \"3scale account confirmation\" : \"#{account_name(user)} API account confirmation\"\n\n headers(\n 'Return-Path' => from_address(user),\n 'X-SMTPAPI' => '{\"category\": \"Signup Notification\"}'\n )\n\n if user.activation_code\n activate_url = if user.account.provider?\n provider_activate_url(activation_code: user.activation_code, host: domain(user))\n else\n developer_portal.activate_url(activation_code: user.activation_code, host: domain(user))\n end\n end\n\n assign_drops user: Liquid::Drops::User.new(user),\n domain: Liquid::Drops::Deprecated.wrap(domain(user)),\n account_name: Liquid::Drops::Deprecated.wrap(account_name(user)),\n account: Liquid::Drops::Account.wrap(user.account),\n provider: Liquid::Drops::Provider.wrap(user.account.provider_account),\n url: activate_url,\n admin_url: Liquid::Drops::Deprecated.wrap(admin_url(user))\n\n mail(\n template_name: 'signup_notification_email',\n subject: subject,\n to: user.email,\n from: from_address(user)\n )\n end",
"def user_sign_up_notification(user)\n @user = user\n\n mail(to: \"<#{user.email}>\", subject: \"Success! You did it.\")\n end",
"def resend_confirmation\n return unless request.post?\n if current_user.activated_at\n flash.now[:error] = \"Your account has already been activated.\"\n else\n UserNotifier.deliver_signup_notification(current_user)\n flash.now[:notice] = \"Your confirmation email has been re-sent\"\n render :action => 'index'\n end\n end",
"def resend_activation_email\n create_activation_digest\n save\n send_activation_email\n end",
"def adminConfirmation\n ContactMailer.adminConfirmation\n end",
"def email_activation\n @user = Student.first\n @user.create_email_activation\n @email = 'yan_fuhai@hotmail.com'\n @option = 'student'\n UserMailer.email_activation @user, @email, @option\n end"
] |
[
"0.8240044",
"0.8081391",
"0.8028264",
"0.802101",
"0.79306096",
"0.79186344",
"0.7882507",
"0.78680325",
"0.7867517",
"0.78668797",
"0.7848442",
"0.7838104",
"0.78369564",
"0.78168875",
"0.7813571",
"0.7813351",
"0.78127444",
"0.7792471",
"0.77844536",
"0.77539027",
"0.77521807",
"0.77503747",
"0.77417815",
"0.7741202",
"0.77223957",
"0.7713448",
"0.77108914",
"0.7702158",
"0.7682666",
"0.76798004",
"0.7679711",
"0.7654749",
"0.76546305",
"0.7654095",
"0.76522684",
"0.76301575",
"0.7621715",
"0.7620387",
"0.7596468",
"0.75859255",
"0.75818056",
"0.7577445",
"0.7550713",
"0.75384647",
"0.7520412",
"0.7519459",
"0.74885035",
"0.7486792",
"0.7467128",
"0.7442054",
"0.74289435",
"0.7417722",
"0.7414595",
"0.7413189",
"0.7408825",
"0.7407408",
"0.7401581",
"0.73975307",
"0.7395292",
"0.739192",
"0.7382329",
"0.73775864",
"0.7373313",
"0.7372999",
"0.73722136",
"0.7370391",
"0.7368809",
"0.73649216",
"0.73517936",
"0.73502344",
"0.7349747",
"0.7339449",
"0.732795",
"0.7305624",
"0.7303914",
"0.7303178",
"0.7297769",
"0.7290242",
"0.72752625",
"0.72725916",
"0.7271346",
"0.7264354",
"0.7263677",
"0.7262371",
"0.72576666",
"0.72533727",
"0.72495365",
"0.72445416",
"0.7241158",
"0.7239691",
"0.7238375",
"0.7234198",
"0.722992",
"0.72284395",
"0.7225993",
"0.72174424",
"0.7216392",
"0.72150534",
"0.72110903",
"0.7211023",
"0.7210725"
] |
0.0
|
-1
|
find a team's updated events, for the schedule.
|
def updated_events(team)
return team.future_events if team.schedule_last_sent.nil?
team.future_events.select do |event|
!event.last_edited.nil? && event.last_edited > team.schedule_last_sent
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def schedule_updated(app_event)\n team = app_event.obj\n return [] unless team.schedule_updates? \n event_ids = team.updated_events.map(&:id)\n generate_nis(app_event, \"schedule_updated\", event_ids)\n end",
"def create_or_update_google_calendar_events\n client = Google::Apis::CalendarV3::CalendarService.new\n client.authorization = Google::Auth.get_application_default(Google::Apis::CalendarV3::AUTH_CALENDAR) \n\n if self.home_team.google_calendar_id\n event = self.build_google_calendar_event_for_team(self.home_team)\n if self.home_team_google_calendar_id\n client.update_event(self.home_team.google_calendar_id, self.home_team_google_calendar_id, event)\n else\n result = client.insert_event(self.home_team.google_calendar_id, event)\n self.update_column(:home_team_google_calendar_id, result.id)\n end\n end\n\n if self.away_team.google_calendar_id\n event = self.build_google_calendar_event_for_team(self.away_team)\n if self.away_team_google_calendar_id\n client.update_event(self.away_team.google_calendar_id, self.away_team_google_calendar_id, event)\n else\n result = client.insert_event(self.away_team.google_calendar_id, event)\n self.update_column(:away_team_google_calendar_id, result.id)\n end\n end\n end",
"def update_event_teams\n if event_teams.size == 2\n event_teams[0].update_attributes({:team_id => self.team1.id})\n event_teams[1].update_attributes({:team_id => self.team2.id})\n end\n end",
"def index\n @events = Event.where(team: current_team)\n end",
"def index\n @events = @team.events.upcoming_events\n end",
"def get_team_event_list ( team_key, year )\n get_api_resource \"#{@@api_base_url}team/#{team_key}/#{year}/events\"\n end",
"def intersecting_event_schedules\n room.event_schedules.where(start_time: start_time, schedule: schedule).where.not(id: id)\n end",
"def bulk_edit\n if request.put?\n events = params[:venue][:events]\n events.each do |event_id, attributes|\n e = Event.find(event_id)\n logger.info \"Found: #{e.inspect}\"\n start_date = e.start_time.to_date\n finish_date = e.finish_time.to_date\n\n new_start_time = DateTime.parse(\"#{start_date} #{attributes['start_time(5i)']} #{e.start_time.zone}\")\n new_finish_time = DateTime.parse(\"#{finish_date} #{attributes['finish_time(5i)']} #{e.finish_time.zone}\")\n\n # support for events that end past midnight\n if new_finish_time < new_start_time\n new_finish_time += 1.day\n end\n\n e.title = attributes[:title]\n e.start_time = new_start_time\n e.finish_time = new_finish_time\n e.save\n\n logger.info \"Saved: #{e.inspect}\"\n end\n else\n @festival = Festival.current_mapp\n @events = Event.scoped(:include => :venue).by_festival_id(@festival.id).group_by{|e| e.venue}\n end\n end",
"def get_team_history_events ( team_key )\n get_api_resource \"#{@@api_base_url}team/#{team_key}/history/events\"\n end",
"def upcoming_matches\n matches = Event.upcoming.map do |ev| \n match = ev.wattball_match\n\n # Get non-null matches that the team is playing in\n match if match and (match.team1 == self or match.team2 == self)\n end\n\n matches.compact\n end",
"def update_practice_schedule\n if self.event_type == \"Practice Schedule\"\n update_practice_schedule = PracticeSchedule.find_by(id: self.practice_tag)\n if update_practice_schedule.title != self.title || update_practice_schedule.start_time != self.start_time \n update_practice_schedule.update :title => self.title, :start_time => self.start_time\n end \n end\n end",
"def get_team_event_matches ( team_key, event_key )\n get_api_resource \"#{@@api_base_url}team/#{team_key}/event/#{event_key}/matches\"\n end",
"def events\n results = @cal_service.list_events(\n @calendar_id,\n order_by: 'startTime',\n q: 'LIVE',\n single_events: true,\n time_max: (DateTime.now + 7).to_s,\n time_min: DateTime.now.to_s,\n fields: 'items(start,end,summary)',\n )\n\n results.data.items.map do |event|\n summary = event.summary.gsub(/^LIVE:\\s+/, '')\n CalendarEvent.new(summary, event.start.date_time, event.end.date_time)\n end\n end",
"def user_updated_team _user, team\n data = {\n category: 'Teams',\n action: 'Updated an Team',\n label: team.name,\n value: nil,\n bounce: false,\n }\n\n create_event data\n end",
"def events\n results = @client.execute(\n :api_method => @calendar.events.list,\n :authenticated => false,\n :parameters => {\n 'calendarId' => @config[:calendar_id],\n 'fields' => 'items(start,end,summary)',\n 'singleEvents' => true,\n 'orderBy' => 'startTime',\n 'timeMin' => DateTime.now.to_s,\n 'timeMax' => (DateTime.now + 7).to_s,\n 'q' => 'LIVE'\n }\n )\n\n results.data.items.map do |event|\n summary = event.summary.gsub(/^LIVE:\\s+/, '')\n CalendarEvent.new(summary, event.start.date_time, event.end.date_time)\n end\n end",
"def events_now\n\n # Open empty array\n events = []\n\n # Loop over all the calendars\n CALENDARS.each do |name, id|\n\n # Get the events\n cal_events = calendar(id).find_events_in_range(Time.now, Time.now + 60)\n\n # Loop over each one and add it to the array\n cal_events.each do |e|\n events << {event: e, cal: name} unless e.nil?\n end\n\n end\n\n # Return the final list\n return events\n\nend",
"def found_events\n @mood.events\n end",
"def events_happening_at\n find_related_frbr_objects( :happens_at, :which_events?) \n end",
"def update_events\n # TODO: handle simple \"date\" in \"all day\" events\n google_updated_events = get_updated_events\n current_user.events.destroy_all\n if google_updated_events.length > 0\n google_updated_events.each do |event|\n new_event = current_user.events.find_or_create_by(g_id: event.id)\n new_event.update_attributes!({\n 'g_id' => event.id,\n 'summary' => event.summary,\n 'description' => event.description,\n 'start' => event.start ? event.start[\"dateTime\"] : nil,\n 'end' => event.end ? event.end[\"dateTime\"] : nil,\n 'location' => event.location\n })\n end\n end\n end",
"def search_for_future_calendar_events\n uri = URI.parse(\"https://www.googleapis.com/calendar/v3/calendars/ufbobbo%40gmail.com/events?orderBy=startTime&singleEvents=true&timeMin=#{Time.now.strftime(\"%FT%T%:z\")}&fields=items(id%2Cstart)&key=#{ENV['GOOGLE_API_KEY']}\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(request).body\n end",
"def get_events(trace: false, &block)\n r = dropbox_query(query: '2/team_log/get_events', trace: trace)\n r['events'].each(&block)\n while r['has_more']\n r = dropbox_query(query: '2/team_log/get_events/continue', query_data: \"{\\\"cursor\\\":\\\"#{r['cursor']}\\\"}\", trace: trace)\n r['events'].each(&block)\n end\n end",
"def past_teams\n Team.find_by_sql([\"SELECT t.* FROM teams t INNER JOIN team_assignments ta ON ( t.id = ta.team_id) INNER JOIN users u ON (ta.user_id = u.id) INNER JOIN courses c ON (t.course_id = c.id) WHERE u.id = ? AND (c.semester <> ? OR c.year <> ?)\", self.id, AcademicCalendar.current_semester(), Date.today.year])\n end",
"def show_team_entries\n @meeting_events_list = @meeting.meeting_events\n .joins(:event_type, :stroke_type)\n .includes(:event_type, :stroke_type)\n .order('meeting_events.event_order')\n\n # Get a timestamp for the cache key:\n @max_entry_updated_at = get_timestamp_from_relation_chain(:meeting_entries)\n end",
"def update_from_google\n @calendars.each do |google_event|\n event = Event.find_by(gid: google_event.id)\n # Update existing event with updated Calendar info\n if event.present?\n event.title = google_event.summary\n event.description = google_event.description\n event.hangout_link = google_event.hangout_link\n event.starts = google_event.start.date_time\n event.ends = google_event.end.date_time\n if google_event.organizer.display_name == nil \n event.creator = google_event.organizer.email\n else\n event.creator = google_event.organizer.display_name\n end\n event.location = google_event.location\n google_category = google_event.summary.downcase\n if [\"1:1\", \"1-to-1\", \"one-to-one\"].include? google_category\n event.category = \"1:1\"\n elsif [\"standup\", \"stand-up\", \"stand up\", \"check-in\", \"check in\"].include? google_category \n event.category = \"check-in\"\n else\n event.category = \"general\"\n end\n event.save!\n # Update attendees list\n if google_event.attendees != nil\n google_event.attendees.each do |google_attendee|\n attendee = Attendee.find_by(email: google_attendee.email, event_id: google_event.id)\n if attendee.present?\n attendee.email = google_attendee.email\n attendee.name = google_attendee.display_name\n attendee.response = google_attendee.response_status\n attendee.save!\n else\n new_attendee = Attendee.new\n new_attendee.event_id = google_event.id\n new_attendee.gid = google_attendee.id\n new_attendee.email = google_attendee.email\n new_attendee.name = google_attendee.display_name\n new_attendee.organizer = google_attendee.organizer\n new_attendee.response = google_attendee.response_status\n new_attendee.save!\n end\n end\n end\n # Create a new event in case this doesn't exist yet\n else\n if google_event.start.date_time != nil\n new_event = current_user.events.new\n new_event.gid = google_event.id\n new_event.title = google_event.summary\n new_event.description = google_event.description\n new_event.hangout_link = google_event.hangout_link\n new_event.starts = google_event.start.date_time\n new_event.ends = google_event.end.date_time\n if google_event.organizer.display_name == nil\n new_event.creator = google_event.organizer.email\n else\n new_event.creator = google_event.organizer.display_name\n end\n new_event.location = google_event.location\n google_category = google_event.summary.downcase\n if [\"1:1\", \"1-to-1\", \"one-to-one\"].include? google_category\n new_event.category = \"1:1 meeting\"\n elsif [\"standup\", \"stand-up\", \"stand up\", \"check-in\", \"check in\"].include? google_category\n new_event.category = \"Check-in / Stand-up\"\n else\n new_event.category = \"General\"\n end\n new_event.save!\n end\n # Create attendees list\n if google_event.attendees != nil\n google_event.attendees.each do |google_attendee|\n new_attendee = Attendee.new\n new_attendee.event_id = google_event.id\n new_attendee.gid = google_attendee.id\n new_attendee.email = google_attendee.email\n new_attendee.name = google_attendee.display_name\n new_attendee.organizer = google_attendee.organizer\n new_attendee.response = google_attendee.response_status\n new_attendee.save!\n end\n end\n end\n end\n end",
"def fetch_events(calendar_id)\n response = service.list_events(calendar_id,\n max_results: 5,\n single_events: true,\n order_by: \"startTime\",\n time_min: Time.now.iso8601,\n time_max: Date.today.+(1).to_time.iso8601)\n\n # filter out any declined events – they normally represent a clash or room release\n response.items.reject { |event|\n next if event.attendees.nil?\n event.attendees.all? { |attendee| attendee.response_status == \"declined\" }\n }\n end",
"def updated\n watchers.find_all(&:updated?)\n end",
"def past_teams\n Team.find_by_sql([\"SELECT t.* FROM teams t INNER JOIN teams_people tp ON ( t.id = tp.team_id) INNER JOIN users u ON (tp.person_id = u.id) INNER JOIN courses c ON (t.course_id = c.id) WHERE u.id = ? AND (c.semester <> ? OR c.year <> ?)\", self.id, AcademicCalendar.current_semester(), Date.today.year])\n end",
"def events\n @events ||= event_finder\n end",
"def edit\n @event = Event.find(params[:id])\n @possible_times = (Event::POSSIBLE_TIMES_CONST).map{|time| time.change( :year => @event.date.year,\n :month => @event.date.month,\n :day => @event.date.day)}\n end",
"def set_list_events\n @list_events = case params[:type_update]\n when UPDATE_TYPE_ALL_ITEMS then Event.where(multi_dates_id: @event.multi_dates_id)\n when UPDATE_TYPE_ALL_AFTER then Event.where(multi_dates_id: @event.multi_dates_id).where(\"begin_at >= ?\", @event.begin_at)\n else [@event]\n end\n end",
"def find_event\n @event = @conference.events.is_public.accepted.scheduled.find(params[:event_id])\n end",
"def gcupdate_event\n cal_event = Event.find_by(gamecall_tag: self.id)\n if cal_event.title != self.title || cal_event.start_time != self.start_time || cal_event.end_time != self.end_time\n cal_event.update :title => self.title, :start_time => self.start_time, :end_time => self.end_time \n end \n end",
"def set_event_team\n @event_team = EventTeam.find(params[:id])\n end",
"def check_for_sport_event\n events = SportEvent.where('sport_events.event_date = ? AND sport_events.team_first = ? AND sport_events.team_second = ? AND sport_events.sport = ? AND sport_events.scenario_name = ?', self.event_date, self.team_first, self.team_second, self.sport, self.scenario_name)\n # Second round to found nearly same events\n if events.empty?\n events = SportEvent.where('sport_events.event_date = ? AND sport_events.team_first ILIKE ? AND sport_events.team_second ILIKE ? AND sport_events.sport = ? AND sport_events.scenario_name = ?', self.event_date, \"%#{self.team_first}%\", \"%#{self.team_second}%\", self.sport, self.scenario_name)\n end\n\n if events.empty?\n event = SportEvent.create_from_sport_trade(self)\n else\n event = events.first\n end\n\n # Add the Sport Trade to the Sport Event\n event.sport_trades << self\n end",
"def team_team_members\n if has_team?\n Employee.where(id: team_team_positions.map(&:efective_id))\n else\n Employee.none\n end\n end",
"def events\n @events ||= Schedule.new\n end",
"def update_events\n calendar_changed = @event.is_a?(Googlize) && @event.calendar != params[:event][:calendar]\n if calendar_changed\n ge = @event.fetch_google_event\n ge.destroy! if ge #prevents an error when updating a canceled event\n @event.google_event_id = nil\n end\n success = @event.update_attributes(params[:event])\n @event.save if calendar_changed\n @repeat_events.each{|event| event.save } if success\n success\n end",
"def show\n @events = TeamMember.smash(@team_member.meeting)\n end",
"def merge(team)\n raise(ArgumentError, 'Cannot merge nil team') unless team\n raise(ArgumentError, 'Cannot merge team onto itself') if team == self\n\n Team.transaction do\n events_with_results = team.results.collect do |result|\n event = result.event\n event.disable_notification!\n event\n end || []\n \n team.create_team_for_historical_results!\n \n aliases << team.aliases\n events << team.events\n results << team.results(true)\n people << team.people\n Team.delete(team.id)\n existing_alias = aliases.detect{ |a| a.name.casecmp(team.name) == 0 }\n if existing_alias.nil? && Team.find_all_by_name(team.name).empty?\n aliases.create(:name => team.name) \n end\n events_with_results.each do |event|\n event.enable_notification!\n end\n end\n end",
"def merge(team)\n raise(ArgumentError, 'Cannot merge nil team') unless team\n raise(ArgumentError, 'Cannot merge team onto itself') if team == self\n\n Team.transaction do\n events_with_results = team.results.collect do |result|\n event = result.event\n event.disable_notification!\n event\n end || []\n \n team.create_team_for_historical_results!\n \n aliases << team.aliases\n events << team.events\n results << team.results(true)\n people << team.people\n Team.delete(team.id)\n existing_alias = aliases.detect{ |a| a.name.casecmp(team.name) == 0 }\n if existing_alias.nil? && Team.find_all_by_name(team.name).empty?\n aliases.create(:name => team.name) \n end\n events_with_results.each do |event|\n event.enable_notification!\n end\n end\n end",
"def find_associated_records\n if team&.new_record?\n if team.name.blank? || (team.name == \"N/A\")\n self.team = nil\n else\n existing_team = Team.find_by_name_or_alias(team.name)\n self.team = existing_team if existing_team\n end\n end\n end",
"def get_event_and_team\n event = get_event\n team = get_team\n\n if (!event or !team)\n return nil\n else\n return [event, team]\n end\n end",
"def index\n @event_teams = EventTeam.all\n end",
"def get_team_rebounds_stats(conf)\n doc = getHTML(\"http://espn.go.com/mens-college-basketball/statistics/team/_/stat/rebounds/seasontype/2/group/#{conf.webExt}\")\n table = doc.xpath('//table[@class = \"tablehead\"]')\n rows = table.css('tr[@class != \"colhead\"]')\n rows.each do |row|\n col = row.css('td')\n if(col.count == 9)\n name = col[1].text\n offReb = col[4].text\n defReb = col[6].text\n totalReb = col[8].text\n\n # Updates specific teams entry with newly scraped data\n team = Team.find_by! name: name \n team.update(offReb: offReb, defReb: defReb, totalReb: totalReb)\n end\n end \n end",
"def find_events(query)\n event_lookup(\"?q=#{query}\")\n end",
"def find_events(query)\n event_lookup(\"?q=#{query}\")\n end",
"def awaiting_admin_events\n candidate_events.select(&:awaiting_admin?)\n end",
"def registered_events\n return repository.find(name) if repository.registered?(name)\n\n Vedeu::Events::Aliases.find(name).map do |event_name|\n Vedeu::Events::Trigger.trigger(event_name, *args)\n end\n\n []\n end",
"def registered_events\n return repository.find(name) if repository.registered?(name)\n\n Vedeu::Events::Aliases.find(name).map do |event_name|\n Vedeu::Events::Trigger.trigger(event_name, *args)\n end\n\n []\n end",
"def update_team( params )\n\n raise ArgumentError.new(format('wrong type. \\'params\\' must be an Hash, given \\'%s\\'', params.class.to_s)) unless( params.is_a?(Hash) )\n raise ArgumentError.new('missing \\'params\\'') if( params.size.zero? )\n\n v, mv = version.values\n return { 'status' => 404, 'message' => format( 'team has been supported in Grafana since version 5. you use version %s', v) } if(mv < 5)\n\n team_id = validate( params, required: true , var: 'team_id' )\n name = validate( params, required: false, var: 'name' , type: String )\n email = validate( params, required: true , var: 'email', type: String )\n\n if(team_id.is_a?(String))\n o_team = search_team(name: team_id)\n status = o_team.dig('status')\n total_count = o_team.dig('totalCount')\n\n return { 'status' => 404, 'message' => format( 'No Team \\'%s\\' found', team_id) } unless(status == 200 && total_count > 0)\n\n teams = o_team.dig('teams')\n team = teams.detect { |x| x['name'] == team_id }\n\n team_id = team.dig('id')\n end\n\n payload = {\n email: email,\n name: name\n }\n payload.reject!{ |_, y| y.nil? }\n\n endpoint = format( '/api/teams/%d', team_id )\n @logger.debug(\"Updating team with Id #{team_id} (PUT #{endpoint})\") if @debug\n\n put( endpoint, payload.to_json )\n end",
"def get_events\n response = request(:get, \"/devmgr/v2/events\")\n #status(response, 200, 'Failed to get current events from server')\n #JSON.parse(response.body)\n response\n end",
"def update_event(org_unit_id, event_id, event_data)\n # PUT /d2l/api/le/#{$le_ver}/#{org_unit_id}/calendar/event/#{event_id}\n path = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/calendar/event/#{event_id}\"\n payload = { # Calendar.EventDataInfo\n \"Title\" => \"\",\n \"Description\" => \"\",\n \"StartDateTime\" => nil, # UTCDateTime || nil\n \"EndDateTime\" => nil, # UTCDateTime || nil\n \"StartDay\" => nil, # LocalDateTime || nil\n \"EndDay\" => nil, # LocalDateTime || nil\n \"GroupId\" => nil, # D2LID || nil\n \"RecurrenceInfo\" => # Calendar.RecurrenceInfo\n {\n \"RepeatType\" => 0, # number -- repeat type\n \"RepeatEvery\" => 0, # number\n \"RepeatOnInfo\" => # Calendar.RepeatOnInfo\n {\n \"Monday\" => false, # boolean\n \"Tuesday\" => false, # boolean\n \"Wednesday\" => false, # boolean\n \"Thursday\" => false, # boolean\n \"Friday\" => false, # boolean\n \"Saturday\" => false, # boolean\n \"Sunday\" => false, # boolean\n },\n \"RepeatUntilDate\" => \"\" # UTCDATETIME\n },\n \"HasVisibilityRestrictions\" => false,\n \"VisibilityRestrictions\" => # Calendar.VisibilityInfo\n {\n \"Type\" => 0, # <number:VISIBILITY_T>,\n \"Range\" => nil, # <number>|null,\n \"HiddenRangeUnitType\" => nil, # <number:HIDDENUNIT_T>|null,\n \"StartDate\" => nil, # <string:UTCDateTime>|null,\n \"EndDate\" => nil # <string:UTCDateTime>|null,\n },\n \"CalendarEventViewUrl\" => \"\" # String:URL\n }.merge!(event_data)\n check_calendar_event_data_validity(payload) # NOTE: Test later\n _put(path, payload)\nend",
"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 find_event\n @matches[:event] = @to_match\n @matches[:guessing] = true\n end",
"def merge(team)\n raise(ArgumentError, 'Cannot merge nil team') unless team\n raise(ArgumentError, 'Cannot merge team onto itself') if team == self\n\n Team.transaction do\n events = team.results.collect do |result|\n event = result.race.standings.event\n event.disable_notification!\n event\n end\n begin\n save!\n aliases << team.aliases\n results << team.results\n racers << team.racers\n Team.delete(team.id)\n existing_alias = aliases.detect{|a| a.name.casecmp(team.name) == 0}\n if existing_alias.nil? and Team.find_all_by_name(team.name).empty?\n aliases.create(:name => team.name) \n end\n ensure\n if events\n events.each do |event|\n event.reload\n event.enable_notification!\n end\n end\n end\n end\n end",
"def update_team\n \n end",
"def find_last_updated_mir\n @team.meeting_individual_results.exists? ? @team.meeting_individual_results.sort_by_updated_at('DESC').first.updated_at : 0\n end",
"def unregistered_events\n tournament\n .schedules\n .keep_if { |s| s.is_scheduled_online? && s.division == division } -\n sign_ups.map{|x| x.try(:timeslot).try(:schedule) }\n end",
"def schedule_created(app_event)\n team = app_event.obj\n return [] unless team.schedule_updates? \n event_ids = app_event.obj.future_events.map(&:id)\n generate_nis(app_event, \"schedule_created\", event_ids)\n end",
"def fetch_valid_test_events\n Event::NAME_CONFIG.each do |name, e_data|\n\n @client_webhook_setting.event_sources_array.each do |event_source|\n @client_webhook_setting.event_result_types_array.each do |result_type|\n\n next if result_type != e_data[:result_type] ||\n e_data[:inavlid_source].include?(event_source)\n\n event_data = GlobalConstant::Event.send(\"#{name}_event_data\")\n\n if event_source == GlobalConstant::Event.kyc_system_source\n event_data[:user_kyc_detail][:last_acted_by] = Admin::AUTO_APPROVE_ADMIN_ID\n end\n\n event = {\n client_id: @client_id,\n event_source: event_source,\n event_name: name,\n event_data: event_data,\n event_timestamp: Time.now.to_i,\n\n client_webhook_setting_id: @webhook_id,\n lock_id: lock_id\n }\n\n @valid_events[name] ||= []\n @valid_events[name] << event\n end\n end\n end\n end",
"def events_expressed_at\n find_related_frbr_objects( :presented_at, :which_events?) \n end",
"def events_at_venue(venue)\n venue_events[venue.id]\n end",
"def set_event_team_detail\n @event_team_detail = EventTeamDetail.find(params[:id])\n end",
"def update\n respond_to do |format|\n if @event_team.update(event_team_params)\n format.html { redirect_to @event_team, notice: 'Event team was successfully updated.' }\n format.json { render :show, status: :ok, location: @event_team }\n else\n format.html { render :edit }\n format.json { render json: @event_team.errors, status: :unprocessable_entity }\n end\n end\n end",
"def events\n event_lookup()\n end",
"def events\n event_lookup()\n end",
"def request_events(access_token, my_email, calendar_id, calendar_zone)\n service = build_service(access_token)\n\n # Return each google api calendar as an ActiveRecord Calendar model\n events = get_calendar_events(service, calendar_id).map do |item|\n upsert_service_event_item(my_email, calendar_zone, item)\n end\n\n # upsert_service_event_item sometimes returns nils, when an event doesn't\n # get made\n events.reject(&:nil?)\n end",
"def get_all_attended_events\n events_id = Attendance.where(:user_id => self).map{ |attendence| attendence.event.id}\n Event.where(:id => events_id).where_first_meeting_starts_in_past\n end",
"def get_events()\n\t\tevents = []\n\n\t\t@DB[:events].order(:date).each do |event|\n\t\t\tnewTimeslots = []\n\t\t\t@DB[:timeslots].where(parent_table: 'events', parent_id: event[:'id']).each do |timeslot|\n\t\t\t\tnewTimeslots.push(DateTime.parse(timeslot[:'time']))\n\t\t\tend\n\n\t\t\tnewAttendees = []\n\t\t\t@DB[:attendees].where(parent_id: event[:'id']).each do |attendee|\n\t\t\t\tattendeeTimeslots = []\n\t\t\t\t@DB[:timeslots].where(parent_table: 'attendees', parent_id: attendee[:'id']).each do |timeslot|\n\t\t\t\t\tattendeeTimeslots.push(DateTime.parse(timeslot[:'time']))\n\t\t\t\tend\n\n\t\t\t\tnewAttendee = Attendee.new(attendee[:'name'], attendeeTimeslots)\n\t\t\t\tnewAttendees.push(newAttendee)\n\t\t\tend\n\n\t\t\tnewEvent = Event.new(event[:'name'], event[:'description'], newTimeslots, newAttendees, event[:'id'])\n\t\t\tif newEvent.get_date >= @epoch\n\t\t\t\tevents.push(newEvent)\n\t\t\tend\n\t\tend\n\n\t\treturn events\n\tend",
"def upcoming_calendar_events\n self.calendar_events.joins(:event).where(\"DATEDIFF(`start_time`,?) >= 0\", Time.now.beginning_of_day)\n end",
"def fetch_events\n params = {'calendarId' => CONFIG[:cal_id], \n 'orderBy' => 'startTime',\n #'timeMax' => Time.utc(CONFIG[:year].to_i + 1, 4, 1).iso8601, \n #'timeMin' => Time.utc(CONFIG[:year].to_i, 4, 1).iso8601,\n 'singleEvents' => 'True'}\n \n result = @client.execute(:api_method => @cal.events.list, :parameters => params)\n\n @events_list = []\n result.data.items.each do |item|\n @events_list << item\n end\n end",
"def update_entries_for(time_shift)\n time_shift.each do |ts|\n record = ts[1]\n # Update record.\n #ScheduleEntry.update(record[:entry_id], staff_id: record[:staff])\n schedule.entries.update(record[:entry_id], staff_id: record[:staff])\n end\n end",
"def update_teams\n if (home_team != nil and away_team != nil)\n puts \"Updating teams\"\n #match = Matchup.new(params)\n home_team.updateResults(self)\n away_team.updateResults(self)\n home_team.save\n away_team.save\n else\n return false\n end\n end",
"def get_schedule\n response = @client.full_game_schedule(@options[:season])\n parse_schedule_response(response)\n end",
"def process_latest_schedule\n @schedule[:games].each_with_index do |game, i|\n descr = sprintf(\"%s at %s\", game[\"awayTeamName\"], game[\"homeTeamName\"])\n @game_changer.insert_text(i, descr)\n end\n end",
"def update\n respond_to do |format|\n exiting_attendees = @event.users\n if @event.update(event_params)\n (@event.users - exiting_attendees).each do |u|\n EventsUser.create!([{ user_id: u.to_i, event_id: @event.id }])\n # we can consider sending updated event to all users if there is change in schedule\n # we can consider sending event to added users if there is change only in attendees count\n EventMailer.send_update_event_email(@event, u).deliver\n end\n format.html { redirect_to @event, notice: 'Event was successfully updated.' }\n format.json { render :show, status: :ok, location: @event }\n else\n format.html { render :edit }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_event_teams ( event_key )\n get_api_resource \"#{@@api_base_url}event/#{event_key}/teams\"\n end",
"def events_commissioned_at\n find_related_frbr_objects( :is_commissioned_for, :which_events?) \n end",
"def update\n @week = Week.find(params[:id])\n\n case params[:schedule_week]\n\n when 'practice_round'\n raise 'see!'\n #empty week, adding an automated_schedule.\n when 'round_robin'\n\n @week.season.divisions.each do |division|\n division.round_robin_schedule(nil, @week, params[:round_robin_all_teams].to_s=='on', params[:round_robin_schedule].to_s=='extend',nil ,params[:round_robin_overwrite].to_s=='on')\n break if params[:round_robin_all_teams]=='on'\n end\n\n when 'position_night'\n raise 'see!'\n\n when 'cross_division_matchups'\n raise 'see!'\n\n\n when 'random_divisional_matchups'\n raise 'see!'\n\n\n when 'manual_update'\n raise 'see!'\n #changing tee times or matchups of an existing new week. OR creating new matchups and tee-times!\n params[:week][:matchups_attributes].each_pair do |key, value|\n value.parse_time_select! :tee_time\n end\n when 'rain_out'\n last_week = @week.schedule.weeks.where([\"weeks.date > ? \",@week.date]).order(\"date asc\").select{|wk| wk.matchups.blank?}.first\n last_week ||= @week.schedule.weeks.create(:date=>@week.date)\n case params[:rainout_option]\n when 'move'\n last_week.update_attribute(:matchups, @week.matchups)\n last_week.save!\n when 'slide'\n dte = @week.date\n @week.schedule.weeks.where([\"weeks.date >= ? \",@week.date]).each{|week| week.update_attribute(:date,week.date+7.days)}\n last_week.update_attribute(:date,dte)\n when 'discard'\n @week.matchups.destroy_all\n end\n else\n raise 'see!'\n\n\n end\n respond_to do |format|\n format.html { redirect_to schedule_path(@week.schedule) << \"?week_id=#{@week.id}\", notice: 'Week was successfully updated.' }\n format.json { head :no_content }\n end\n end",
"def org_events\n @org_events ||= orgs.map { |o| o.events }.flatten\n end",
"def after_update(sales_team)\n if sales_team.status_changed?\n if sales_team.status==:approved\n mail = SalesTeamMailer.welcome(sales_team)\n mail.deliver\n elsif sales_team.status==:rejected\n mail = SalesTeamMailer.rejected(sales_team)\n mail.deliver\n end\n end\n end",
"def get_next_calendar_events\n next_events = JSON.parse search_for_future_calendar_events\n next_events[\"items\"]\n end",
"def find_team(team_name)\n teams.find {|team| team_name == team.fetch(:team_name)}\nend",
"def check_for_reminder_updates(params)\n\t\treminder_updates = []\n\t\tparams[\"site\"][\"reminders_attributes\"].each_with_index do |reminder, index|\n\t\t\tremind = reminder[1].to_hash\n\t\t\tremind[\"site_id\"] = self.id\n\t\t\tif self.id == nil\n\t\t\t\treminder_updates << index.to_s unless remind[\"message\"].blank? && remind[\"heading\"].blank? ### When creating a new collection\n\t\t\telse\n\t\t\t\treminder_updates << index.to_s unless Reminder.where(remind).present? ### When updating an exisiting collection\n\t\t\tend\n\t\tend\n\t\treminder_updates\n\tend",
"def find_event(event_name)\n @events.find { |event| event.name.to_s == event_name.to_s }\n # TODO: use a data structure that prevents duplicates\n end",
"def find_or_create!()\n event_order = @last_event_order\n @source_dao.meeting_events.each_with_index do |event, index|\n add_to_log( \"\\r\\nProcessing event #{ event.get_full_name }...\" )\n event_type_id = if event.instance_of?( MeetingEvent )\n add_to_log( \"Previosly detected as event_type_id: #{ event.event_type_id }.\" )\n event.event_type_id\n elsif event.instance_of?( FinCalendarParseResultDAO::EventTypeDAO )\n event_type = create_new_event_type( event )\n add_to_log( \"Created new event_type: #{ event_type.inspect }.\" )\n event_type.id\n end\n # Prepare MeetingEvent requires:\n meeting_session_id = @meeting_session.id\n event_type_id = event_type_id\n event_order += index + 1 # (We'll set the event_order as cumulative among all sessions)\n\n # [Steve, 20170920] We cannot safely detect the begin time from the start time\n # of the session here. (We need the entries, at least.)\n #\n # So this has been removed permanently from the search below:...\n #\n # begin_time = @source_dao.start_time_iso_format\n #\n # ...Together with the check for a change in the begin time, which resulted in\n # continuous event updates:\n #\n # ( begin_time.present? &&\n # Format.a_time( meeting_event.begin_time ) != Format.a_time( begin_time ) )\n\n # --- SEARCH #1: find pre-existing event ---\n meeting = @meeting_session.meeting\n add_to_log( \"Searching meeting Event n.#{ event_order }: #{ event.get_full_name } (type: #{ event_type_id }) among existing events for meeting #{ meeting.id }...\" )\n meeting_event = meeting.meeting_events.where( event_type_id: event_type_id ).first\n # Match found?\n if meeting_event.instance_of?( MeetingEvent )\n add_to_log( \"Meeting Event found! => #{ meeting_event.inspect }\" )\n # --- UPDATE ---\n # Force update of the found instance with the correct values if there are\n # any differences (except user_id):\n # (If the found MeetingEvent belongs to a different session, it will be \"moved\"\n # to the one specified in the constructor)\n if ( meeting_event.heat_type_id.to_i < 1 ) ||\n ( meeting_event.meeting_session_id != meeting_session_id )\n meeting_event = update_existing( meeting_event, meeting_session_id, event_order, nil, event_type_id )\n end\n # --- CREATION ---\n else\n meeting_event = create_new( meeting_session_id, event_order, @source_dao.start_time_iso_format, event_type_id )\n end\n # Add the created/updated event row to the list:\n @result_meeting_events << meeting_event\n end\n\n @last_event_order = event_order\n @result_meeting_events\n end",
"def schedule_managers\n @managers.each do |name, manager|\n # Perform one update immediately so that all information is initialized\n # before the first scheduled update cycle occurs. This avoids issues\n # where updates for routes (usually daily) may not have occurred before\n # updates for vehicles (usually every few seconds) need their\n # information.\n manager.update\n @scheduler.every(manager.update_frequency){ manager.update }\n end\n\n @managers.values.map(&:update)\n end",
"def find_g_event_by_id(events, id)\n events.find { |e| e.id == id }\n end",
"def fetch_events(app_name, env_name, options={})\n @event_fetched_times += 1\n set_env_ready(app_name, env_name, true) # assume env become ready after it spit out all the events\n\n unless @events # unrestricted mode for testing if no explicit events set\n return [generate_event_from_messages(['Successfully deployed new configuration to environment',\n 'terminateEnvironment completed successfully',\n 'Successfully launched environment',\n 'Completed swapping CNAMEs for environments'\n ], Time.now + @event_fetched_times), nil]\n end\n\n events = @events[env_key(app_name, env_name)][@event_fetched_times - 1]\n\n if options.has_key?(:start_time)\n start_time = Time.parse(options[:start_time])\n events = events.select { |e| e[:event_date] >= start_time }\n end\n\n if limit = options[:max_records]\n events = events[0..limit]\n end\n\n [events, nil]\n end",
"def team_event\n @team = Team.find(params[:team_id])\n @event = Event.find(params[:event_id])\n @result = Result.first(\n :include => { :scores => [ :source_result, :competition_result ] },\n :conditions => ['results.event_id = ? and team_id = ? and race_id = ?', params[:event_id], params[:team_id], params[:race_id]]\n )\n raise ActiveRecord::RecordNotFound unless @result\n end",
"def team_event\n @team = Team.find(params[:team_id])\n @event = Event.find(params[:event_id])\n @result = Result.first(\n :include => { :scores => [ :source_result, :competition_result ] },\n :conditions => ['results.event_id = ? and team_id = ? and race_id = ?', params[:event_id], params[:team_id], params[:race_id]]\n )\n raise ActiveRecord::RecordNotFound unless @result\n end",
"def find_events(site,location,options_hash,hash_to_manipulate)\n creds = $sites[site]\n id = creds['id']\n key = creds['key']\n\n connection = AWS::EC2.new(\n :access_key_id => id,\n :secret_access_key => key,\n :region => location\n )\n AWS.memoize do\n # Trying to get the responses for just systems that have Events that are not null\n # In theory the \"anything with an event.code\" wildcard value above seems to work.\n instance_details = connection.instances.filter('instance-state-name', 'running')\n response = connection.client.describe_instance_status(options_hash)\n response[:instance_status_set].each do |instances_with_events|\n my_instance = instances_with_events[:instance_id]\n my_events = instances_with_events[:events_set].first\n my_name = instance_details[my_instance].tags['Name']\n hash_to_manipulate[my_instance.to_sym] = { :name => my_name, :code => my_events[:code], :description => my_events[:description], :not_before=> my_events[:not_before], :region => location, :site => site }\n end\n end\nend",
"def update\n\n respond_to do |format|\n ap @team.name\n ap @categorys = Category.where(:team => @team.name)\n ap @admin_tasks = AdminTask.where(:team => @team.name)\n ap @eadmin_tasks = EadminTask.where(:team => @team.name)\n ap @users = User.where(:user_info => @team.name)\n\n if @team.update(team_params)\n ap @team.name\n @admin_tasks.update_all(:team => @team.name )\n @eadmin_tasks.update_all(:team => @team.name )\n @categorys.update_all(:team => @team.name )\n @users.update_all(:user_info => @team.name )\n\n\n format.html { redirect_to team_path, notice: 'Team was successfully updated.' }\n format.json { render :show, status: :ok, location: @team }\n else\n format.html { render :edit }\n format.json { render json: @team.errors, status: :unprocessable_entity }\n end\n end\n end",
"def scan_team_sub_list( team_sublist, updater, logger, filter_by_pool_type_list = nil, filter_by_event_type_list = nil )\n raise ArgumentError.new(\"The updater specified is not valid or nil!\") unless updater.instance_of?( RecordUpdater )\n # Scan the team sub-list:\n team_sublist.each_with_index do |team, team_index|\n logger.info( \"\\r\\nTeam '#{ team.get_full_name }' #{ team.id } (#{ team_index + 1 }/#{ team_sublist.count }):\")\n if team.meeting_individual_results.exists?\n team_best_finder = TeamBestFinder.new( team )\n team_best_finder.set_pools( filter_by_pool_type_list ) if filter_by_pool_type_list\n team_best_finder.set_events( filter_by_event_type_list ) if filter_by_event_type_list\n\n logger.info( \"- Scanning for distinct personal-best timings...\")\n team_bests_4xddao = team_best_finder.scan_for_distinct_bests\n logger.info( \"- Checking for split-categories...\")\n team_bests_4xddao = team_best_finder.split_categories( team_bests_4xddao )\n # Update/create team records based upon returned records-DAO list:\n logger.info( \"- Updating...\")\n updater.add_sql_diff_comment( \"Team '#{ team.get_full_name }' (ID #{ team.id }, #{ team_index + 1 }/#{ team_sublist.count })\" )\n updater.force_update_for_team_records( team_bests_4xddao )\n updater.add_sql_diff_comment( \"( End loop for Team ID #{ team.id } )\\r\\n\\r\\n\" )\n logger.info( \"\\r\\n\")\n end\n end\n end",
"def project_events(project_id, params = {})\n make_get_request(\"/projects/#{project_id}/events\", params)\n end",
"def find_event(role)\n events = find_events(role)\n event = events[0] # if (!events.nil? and events.count == 0)\n end",
"def update_events \n @events.each_value do |event|\n event.update unless event.frozen?\n terminate_event(event) if event.terminated?\n end\n @common_events.each {|event| event.update}\n end",
"def set_event\n @event = Event.find_by(id: params[:id], team: current_team)\n end",
"def fGetAllEvents\n @sports.getAllEvents\n end",
"def get_matches_on_event(event_type)\n if has_matches_on_event?(event_type)\n @matches = @local_swimmer.meeting_programs\n .sort_by_date('DESC')\n .joins(:meeting, :event_type)\n .includes(:meeting, :event_type)\n .where([\n 'meeting_events.event_type_id = ? and exists (select 1 from meeting_individual_results mir join swimmers s on s.id = mir.swimmer_id where s.id = ? and mir.meeting_program_id = meeting_programs.id)',\n event_type.id,\n visitor_swimmer.id\n ])\n end\n end"
] |
[
"0.6999584",
"0.603998",
"0.59195554",
"0.5888743",
"0.58881843",
"0.58482814",
"0.5760947",
"0.56692815",
"0.56352264",
"0.56202865",
"0.5536202",
"0.55358547",
"0.55117476",
"0.5509245",
"0.547375",
"0.5459001",
"0.5457908",
"0.5454145",
"0.54526347",
"0.54355556",
"0.5435393",
"0.5414957",
"0.5402946",
"0.5397318",
"0.53849256",
"0.5362297",
"0.53568316",
"0.534598",
"0.5317897",
"0.5292946",
"0.5288421",
"0.5280105",
"0.5270538",
"0.5265557",
"0.52641404",
"0.5260457",
"0.52525353",
"0.52361333",
"0.5234635",
"0.5234635",
"0.5202059",
"0.51962286",
"0.51868105",
"0.51839167",
"0.51833",
"0.51833",
"0.51768494",
"0.5170562",
"0.5170562",
"0.51615244",
"0.51432264",
"0.51426625",
"0.5140534",
"0.51343656",
"0.51263064",
"0.5124764",
"0.51154584",
"0.5113546",
"0.510792",
"0.51002455",
"0.50989753",
"0.5073966",
"0.50719714",
"0.5070463",
"0.50700116",
"0.50700116",
"0.506912",
"0.5067937",
"0.5066745",
"0.50602466",
"0.50601614",
"0.505937",
"0.5053392",
"0.50488245",
"0.50421125",
"0.5025042",
"0.5010076",
"0.50081384",
"0.5000608",
"0.49863252",
"0.498591",
"0.4983284",
"0.49797222",
"0.4979712",
"0.49764302",
"0.49762994",
"0.4973516",
"0.49668318",
"0.49645633",
"0.49622527",
"0.49622527",
"0.49573964",
"0.49531087",
"0.49497172",
"0.4947339",
"0.4941223",
"0.49390197",
"0.49373728",
"0.49347377",
"0.49345425"
] |
0.8029248
|
0
|
Use callbacks to share common setup or constraints between actions.
|
def set_project
@project = Project.friendly.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
|
Never trust parameters from the scary internet, only allow the white list through.
|
def project_params
params.require(:project).permit(:title, :image, :banner, :date, :description, :summary, :link, :status)
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
|
print documentation ri 'Arraypop' Array.ri Array.ri :pop arr.ri :pop
|
def ri(method = nil)
unless method && method =~ /^[A-Z]/ # if class isn't specified
klass = self.kind_of?(Class) ? name : self.class.name
method = [klass, method].compact.join('#')
end
puts `ri '#{method}'`
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def using_pop(array)\n array.pop()\nend",
"def \n \n using_pop(array)\n \n\n array.pop()\n \nend",
"def pop\r\n @arr.shift\r\n end",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(arr)\n arr.pop\nend",
"def using_pop(array)\n element = array.pop\n element\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop(array)\n array.pop\nend",
"def using_pop (array)\n return array.pop\nend",
"def using_pop(array)\n array = array.pop(1)\n array.pop\n\n\nend",
"def pop_with_args(array)\n array.pop(2)\n end",
"def pop_with_args(array)\narray = array.pop(2)\narray.pop(2)\nend",
"def pop\r\n # What does array.pop do? It takes the last \r\n # item of a list. We want this method to return\r\n # the last item. So maybe we can do something like:\r\n # return @data.last\r\n end",
"def pop_with_args(array)\n array.pop(2);\nend",
"def pop_from_array(arr)\n arr.size.times do\n puts arr.pop\n end\nend",
"def pop()\n v, _ = @array.pop\n v\n end",
"def \n \n pop_with_args(array)\n # {...}(pop_x_times)\n\n\n array.pop(2)\n \n \n #-X-\n # array.pop()\n # array.pop()\n \nend",
"def pop; end",
"def pop; end",
"def pop; end",
"def pop; end",
"def pop; end",
"def pop_from_array(arr)\n l=arr.length\n l.each do\n num=arr.pop\n puts \"#{num} is removed!\"\n end\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array.pop(2)\nend",
"def pop_with_args(array)\n array = array.pop(2)\n array.pop(2)\n \nend",
"def pop_with_args (array)\n return array.pop(2)\nend",
"def pop_with_args(arr)\n arr.pop(2)\nend",
"def pop_with_args(array,numb = 2)\n array.pop(2)\nend",
"def pop\n @a.pop\n end",
"def mutate(arr)\n arr.pop\n end",
"def pop\n @mut.synchronize{@array.sort!.pop}\n end",
"def pop()\n (@arr1.size-1).times { @arr2.push(@arr1.shift) }\n result = @arr1.shift\n @arr1, @arr2 = @arr2, @arr1\n result\n end",
"def pop() end",
"def pop\n end",
"def mutate(array)\n array.pop \nend",
"def pop\r\n # IMPLEMENT ME\r\n end",
"def remove_item(elective_array)\n elective_array.pop\n puts elective_array\nend",
"def pop\n @ivar.pop \n end",
"def eliminar_ult_elem_arr(arreglo)\n arreglo.pop\n arreglo\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def mutate(array)\n array.pop\nend",
"def pop\n raise 'No such element' if @elements.length == 0\n @elements.slice!(-1)\n end",
"def pop \r\n @data.pop\r\n end",
"def stack_as_array\n puts \"Stack as array: \"\n arr = [1,3,4,5,6,7]\n print arr\n puts\n\n puts \"Pop top element (7):\"\n puts arr.pop\n print arr\n puts\n\n puts \"Push element (8):\"\n arr.push(8)\n print arr\n puts\n puts\nend",
"def brpop(*args)\n _bpop(:brpop, args)\n end",
"def pop()\n \n end",
"def pop()\n \n end",
"def pop()\n \n end",
"def brpop(*args)\n _bpop(:brpop, args)\n end",
"def pop\n # IMPLEMENT ME\n end",
"def uncons\n\t\t\tarray = pop\n\t\t\traise ArgumentError, \"UNCONS: first element is not an Array.\" unless array.is_a? Array\n\t\t\tpush array.first\n\t\t\tpush array.drop 1\n\t\tend",
"def pop_stack\n raise ArgumentError if @array_list.empty?\n\n @array_list.pop\n end",
"def remove_element_from_end_of_array(array)\n array.pop\nend",
"def remove_element_from_end_of_array(array)\n array.pop\nend",
"def test_pushing_and_popping_arrays\n array = [1,2]\n array.push(:last)\n\n assert_equal [1, 2, :last], array\n\n popped_value = array.pop\n assert_equal :last, popped_value\n assert_equal [1, 2], array\n end",
"def pop()\n @data.pop\n end",
"def pop\n raise IndexError.new if @data.size == 0\n ret = @data[0]\n @data[0] = @data[@data.size - 1]\n @data = @data.take(@data.size - 1)\n percolate_down\n return ret\n end",
"def remove_element_from_end_of_array(array)\n return array.pop\nend",
"def brpop(*args); end",
"def brpop(*args); end",
"def pop()\n # O(1) time\n @arr.pop\n @min.pop\n end",
"def op_pop(n = nil)\n pop(n)\n end",
"def remove_retrieve_last\n # @array.pop\n @array.slice!(0)\n end",
"def mutate(arr)\n arr.pop # => 6\nend",
"def pop\n delete_at(0)\n end",
"def pop\n raise NotImplementedError\n end",
"def pop\n @data.delete_at @data.length - 1 if @data.length > 0\n end",
"def blpop(*args)\n _bpop(:blpop, args)\n end",
"def blpop(*args)\n _bpop(:blpop, args)\n end",
"def rotate_array(arr, num)\n \n removed = arr.pop(num)\n \n new_arr = removed += arr\n \n print new_arr\nend",
"def pop\n\t\tremove(@length - 1)\n\tend",
"def pop\n\n outlen_op(:tclistpop)\n end",
"def remove_from_end(arr)\n arr.pop\nend",
"def delete\n @array_roses.pop\nend",
"def pop\n if @count > 0\n last_item_index = @count - 1\n\n # stores last element\n last_item = @items[last_item_index]\n\n # remove last item from array\n @items[last_item_index] = nil\n\n # reduces size by 1\n @count -= 1\n\n last_item\n else\n raise \"There are no items in the stack\"\n end\n end",
"def pop\n return nil if self.curr == 0\n val = self.arr[self.curr - 1]\n self.curr -= 1\n val\n end",
"def mutate(arr)\n arr.pop # (no bang! here) mutates\nend"
] |
[
"0.7991969",
"0.7976135",
"0.7928831",
"0.7905559",
"0.7868258",
"0.78483194",
"0.7819838",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.779345",
"0.7650248",
"0.7580603",
"0.747871",
"0.7279898",
"0.72511715",
"0.72024983",
"0.71967643",
"0.71907943",
"0.71211326",
"0.7118125",
"0.7118125",
"0.7118125",
"0.7118125",
"0.7118125",
"0.71027195",
"0.7089207",
"0.7089207",
"0.7070865",
"0.7070865",
"0.7070865",
"0.7070865",
"0.7070865",
"0.7070865",
"0.7070865",
"0.70704055",
"0.7056225",
"0.7037023",
"0.70229",
"0.70214176",
"0.6980927",
"0.698082",
"0.6938514",
"0.6864897",
"0.67318183",
"0.66962534",
"0.6679467",
"0.6650982",
"0.663321",
"0.657464",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.65616536",
"0.654895",
"0.65328836",
"0.6516444",
"0.64983445",
"0.648594",
"0.648594",
"0.648594",
"0.64799976",
"0.6475958",
"0.64493704",
"0.6440505",
"0.64400893",
"0.64400893",
"0.6424699",
"0.64240444",
"0.64093894",
"0.64055336",
"0.6397236",
"0.6397236",
"0.6392293",
"0.6372353",
"0.63684046",
"0.6349941",
"0.63141227",
"0.6285814",
"0.6268567",
"0.6263037",
"0.6253925",
"0.6244194",
"0.62372494",
"0.6204819",
"0.61950004",
"0.6172645",
"0.61619854",
"0.61131275",
"0.60720253"
] |
0.0
|
-1
|
description: serialize the current instance into a question object params: retval: the question object
|
def serialize
super(ATTR_NAME_ARY)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def serialize\n end",
"def serialize; end",
"def serialize; end",
"def serialize!\n end",
"def to_str( )\n @question\n end",
"def serialize\n raise NotImplementedError\n end",
"def serialize\n raise NotImplementedError\n end",
"def serialize\n YAML::dump(self)\n end",
"def serialize\n \n end",
"def serialize(object) end",
"def questionnaire\n QuestionnaireShortSerializer.new(object.measurement.questionnaire)\n end",
"def serialized\n serializer_class.new(self).serializable_hash\n end",
"def serializable_hash(options = nil)\n\t options ||= {}\n\t question = {id: id, content: content}\n\t question[:user] = self.owner\n\t question[:question_image] = self.question_image\n\t question[:responses] = self.responses\n\t question\n\tend",
"def serialize(options={})\n raise NotImplementedError, \"Please implement this in your concrete class\"\n end",
"def serialize(io)\n Encoder.encode(io, self)\n io\n end",
"def serializer; end",
"def question\n answer.question\n end",
"def question\n self.question\n end",
"def marshal\n Marshal.dump self\n end",
"def marshal\n Marshal.dump self\n end",
"def marshal\n Marshal.dump self\n end",
"def questions\n object.questions.map do |question|\n QuestionSerializer.new(question)\n end\n end",
"def serialize\n @raw_data\n end",
"def serialize\n self.to_hash.to_json\n end",
"def to_s()\n serialize.to_s()\n end",
"def to_s()\n serialize.to_s()\n end",
"def create_question\n question_hash = Adapter.quiz_api(difficulty) #use adapter method, with difficulty passes into the url as a variable, to gnerate a new list of questions.\n new_question = Question.new #make a new question instance\n new_question.save #save now so we can store the question's id in the answer by calling self.id\n new_question.content = question_hash['question'] #adding all necessary column data to this question object/row\n new_question.create_answers(question_hash)\n new_question.quiz_id = self.id\n new_question.save #send the newly created question to the database\n end",
"def create\n workout = Workout.find params[:workout_id]\n result = Question.create(workout, { \n :body => params[:body], \n :answer_type => params[:answer_type] }, \n params[:answers].values\n )\n\n @question = result[:question]\n\n respond_to do |format|\n unless @question.persisted?\n format.json { render :json => @question.errors.full_messages, :status => :unprocessable_entity }\n else\n format.json { render :json => @question.as_json({:include => :answers}) }\n end\n \n end\n\n end",
"def serialize\n @serializer.serialize(self.output)\n end",
"def to_s\n values = @params.map{|k, v| \"#{k}: #{v}\"}.join(\" \")\n \"<Twilio.FlexApi.V1.InsightsQuestionnairesInstance #{values}>\"\n end",
"def serialize\n BaseOperator.serialize(self)\n end",
"def info() quiz_question.info end",
"def question\n puts \"#{@question}\"\n end",
"def quiz_detail\r\n result ={}\r\n qzps = self.bank_qizpoint_qzps\r\n node = BankNodestructure.where(:uid => self.node_uid).first\r\n result[:subject] = node.subject\r\n result[:grade]= node.grade\r\n result[:version] = node.version + \"(\"+ node.volume + \")\"\r\n result[:text] = self.text\r\n result[:node_uid] = node.uid\r\n result[:answer] = self.answer\r\n result[:desc] =self.desc\r\n result[:levelword2]=self.levelword2\r\n result[:bank_qizpoint_qzps] = qzps.map{|qzp|\r\n { \r\n \"type\" => qzp.type,\r\n \"type_label\" => Common::Locale::i18n(\"dict.#{qzp.type}\"),\r\n \"answer\" => qzp.answer,\r\n \"desc\" => qzp.desc,\r\n \"score\" => qzp.score,\r\n \"bank_checkpoint_ckps\" => qzp.bank_checkpoint_ckps.map{|bcc|\r\n {\r\n \"dimesion\" => bcc.dimesion,\r\n \"rid\" => bcc.rid,\r\n \"uid\" => bcc.uid,\r\n \"checkpoint\" => bcc.checkpoint,\r\n \"desc\" => bcc.desc\r\n }\r\n }\r\n }\r\n } \r\n result\r\n end",
"def questions\r\n return @questions \r\nend",
"def inspect\n serialize.to_s\n end",
"def inspect\n serialize.to_s\n end",
"def inspect\n serialize.to_s\n end",
"def serialize_test\n all = Hash.new\n all[:id] = id\n all[:title] = title\n all[:description] = description\n all[:tags] = tags\n all[:active] = active\n all[:shared] = shared\n all[:questions] = []\n questions.select(:id, :question, :hint, :explanation, :tags, :qtype, :active, :lang, :worth, :status).each do |q|\n all[:questions] << q\n end\n all\n end",
"def serialize\n h= {\n id: solution.id,\n title: solution.title,\n team_name: solution.team_name,\n representative_email: solution.representative_email,\n representative_first_name: solution.representative_first_name, \n representative_last_name: solution.representative_last_name,\n representative_phone_num: solution.representative_phone_num,\n description: solution.description,\n explanation: solution.explanation,\n youtube_link: \"https://www.youtube.com/watch?v=#{solution.youtube_link}\",\n github_link: solution.github_link,\n web_link: solution.web_url,\n android_market_link: solution.android_mkt_url,\n ios_market_link: solution.ios_mkt_url,\n firebase_shared: solution.firebase_shared?,\n firebase_url: solution.firebase_url,\n market_probe: solution.file_file_name,\n ods: solution.sd_goal_id,\n ods_name: solution&.sd_goal.name,\n decidim_user_id: solution.decidim_user_id,\n decidim_user_email: solution&.user&.email,\n decidim_user_name: solution&.user&.name,\n created_at: solution.created_at,\n updated_at: solution.updated_at,\n }\n h[:categories]= solution.decidim_proposals_proposals.map do |p|\n \"<#{translated_attribute(p.category.try(:name))}>\"\n end.uniq\n h[:necessitats]= solution.decidim_proposals_proposals.map do |p|\n \"<#{Decidim::Proposals::ProposalPresenter.new(p).title}>\"\n end\n h\n end",
"def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_object_value(\"subject\", @subject)\n writer.write_object_value(\"task\", @task)\n writer.write_object_value(\"taskProcessingresult\", @task_processingresult)\n writer.write_object_value(\"workflow\", @workflow)\n end",
"def to_s\n serialize.to_s\n end",
"def to_s\n serialize.to_s\n end",
"def to_s\n serialize.to_s\n end",
"def serialize\n ArtistMessage.encode(self.to_message)\n end",
"def question(player, question) \n output({\n :event => \"question\",\n :id => Events.generate_uuid,\n :timestamp => Events.timestamp,\n :playerid => player.uuid,\n :question => question.to_s,\n :answer => question.answer,\n :result => question.result,\n :duration => question.duration\n })\n end",
"def to_s\n Forme.transform(:serializer, @opts, @form.opts, self)\n end",
"def serialize(object, data); end",
"def serialize(model)\n end",
"def show\n render_json @question\n end",
"def inspect()\n serialize.to_s()\n end",
"def inspect()\n serialize.to_s()\n end",
"def inspect\n serialize.to_s\n end",
"def serialize\n File.open( FILENAME, 'wb' ){ |f| f << Marshal.dump( @all_answers ) }\n end",
"def to_obj; end",
"def serialize(arg)\n raise NotImplementedError\n end",
"def serialized\n @value\n end",
"def as_json(options={})\n {\n :correct => correct,\n :created_at => created_at,\n :id => id, \n :question_id => question_id,\n :response => response ,\n :updated_at => updated_at,\n :user_id => user_id,\n :question => self.question\n }\n end",
"def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_object_value(\"accessPackage\", @access_package)\n writer.write_collection_of_object_values(\"answers\", @answers)\n writer.write_object_value(\"assignment\", @assignment)\n writer.write_date_time_value(\"completedDateTime\", @completed_date_time)\n writer.write_date_time_value(\"createdDateTime\", @created_date_time)\n writer.write_collection_of_object_values(\"customExtensionCalloutInstances\", @custom_extension_callout_instances)\n writer.write_enum_value(\"requestType\", @request_type)\n writer.write_object_value(\"requestor\", @requestor)\n writer.write_object_value(\"schedule\", @schedule)\n writer.write_enum_value(\"state\", @state)\n writer.write_string_value(\"status\", @status)\n end",
"def construct_feedback_object # rubocop:disable Metrics/AbcSize\n return unless @question.codaveri_id\n\n @answer_object[:problem_id] = @question.codaveri_id\n\n @answer_object[:language_version][:language] = @question.polyglot_language_name\n @answer_object[:language_version][:version] = @question.polyglot_language_version\n\n @answer_object[:is_only_itsp] = true if @course.codaveri_itsp_enabled?\n\n @answer_files.each do |file|\n file_template = default_codaveri_student_file_template\n file_template[:path] = file.filename\n file_template[:content] = file.content\n\n @answer_object[:files_student].append(file_template)\n end\n\n # For debugging purpose\n # File.write('codaveri_feedback_test.json', @answer_object.to_json)\n\n @answer_object\n end",
"def show\n @qa = Qa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :xml => @qa.to_json(:include => [:answer, :question]) }\n end\n end",
"def new\n @question = Question.new \n end",
"def serialize(_object, data); end",
"def serialize(_object, data); end",
"def to_s\n return serialize.to_s\n end",
"def render\n @question = Question.find(self.question_id)\n end",
"def instance_to_json\n { \n id: self.id,\n title: self.title,\n content: self.content,\n likes: self.likes,\n author: {\n id: self.author.id,\n name: self.author.name\n }\n }\n end",
"def encode\n raise Errors::SerializerNotConfigured if serializer_missing?\n\n serializer.encode(self)\n end",
"def serialize\n {\n id: @participation.id,\n category: {\n id: @participation.category.try(:id),\n name: @participation.category.try(:name)\n },\n scope: {\n id: @participation.scope.try(:id),\n name: @participation.scope.try(:name)\n },\n title: @participation.title,\n body: @participation.body,\n votes: @participation.participation_votes_count,\n comments: @participation.comments.count,\n created_at: @participation.created_at,\n url: url,\n feature: { id: feature.id },\n meeting_urls: meetings\n }\n end",
"def answer(params={})\n matching_answer_class.new(params.merge(question: self))\n end",
"def inspect\n values = @properties.map{|k, v| \"#{k}: #{v}\"}.join(\" \")\n \"<Twilio.FlexApi.V1.InsightsQuestionnairesInstance #{values}>\"\n end",
"def serialize(buffer = ReDNS::Buffer.new)\n buffer.pack(\n 'nnnnnn',\n self.id,\n (\n (self.query? ? 0 : 0x8000) |\n (ReDNS::OPCODE[self.opcode] || ReDNS::OPCODE[:unknown]) << 12 |\n (self.authorative? ? 0x0400 : 0) |\n (self.truncated? ? 0x0200 : 0) |\n (self.recursion_desired? ? 0x0100 : 0) |\n (self.recursion_available? ? 0x0080 : 0) |\n (ReDNS::RCODE[self.response_code] || ReDNS::RCODE[:noerror])\n ),\n self.questions.length,\n self.answers.length,\n self.nameservers.length,\n self.additional_records.length\n )\n\n [ :questions, :answers, :nameservers, :additional_records ].each do |section|\n @attributes[section] and @attributes[section].each do |part|\n part.serialize(buffer)\n end\n end\n \n buffer\n end",
"def instance_to_json\n { \n id: self.id,\n title: self.title,\n description: self.description,\n creator: self.creator.name\n \n }\n end",
"def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_collection_of_object_values(\"outcomes\", @outcomes)\n writer.write_object_value(\"recipient\", @recipient)\n writer.write_collection_of_object_values(\"resources\", @resources)\n writer.write_collection_of_object_values(\"submittedResources\", @submitted_resources)\n end",
"def to_s\n '<Twilio.FlexApi.V1.InsightsQuestionnairesPage>'\n end",
"def store_datas\n question = Question.find(self.question_id)\n self.exercise = question.exercise.as_json(include: {questions: {include: :test_cases }})\n self.lo = question.exercise.lo.as_json\n self.question = question.as_json(include: :test_cases)\n self.team = Team.find(self.team_id).as_json if self.team_id\n\ttrue\n end",
"def serialize\n JSON.generate(to_h)\n end",
"def to_yaml_s\n _value = @value\n @value = highline_question_type.call @value\n x = super\n @value = _value\n x\n end",
"def new_quiz\n @questionnaire = Object.const_get(params[:model]).new\n @questionnaire.private = params[:private]\n @questionnaire.min_question_score = 0\n @questionnaire.max_question_score = 1\n @participant_id = params[:pid] #creating an instance variable to hold the participant id\n @assignment_id = params[:aid] #creating an instance variable to hold the assignment id\n render :new\n end",
"def new\n @question_id = (@exam_session.exam.questions.find :first,\n :offset => (@exam_session.current_question - 1)).id\n \n @exam_session.update_attribute(:updated_at, Time.now)\n \n @question = Question.find_by_id_and_return_xml_table(@question_id)\n \n @choices = { 'choiceA' => @question.choice_a,\n 'choiceB' => @question.choice_b,\n 'choiceC' => @question.choice_c,\n 'choiceD' => @question.choice_d,\n 'choiceE' => @question.choice_e,\n }\n end",
"def adapt(quiz_question)\n Speed.of('game_question.adapt(quiz_question)') do\n self.quiz_question = quiz_question\n self.level = quiz_question.level\n save\n end\n self\n end",
"def getQuestionObjName\r\n\t\t\treturn \"mfiforce__Question__c\"\r\n\t\tend",
"def encode(obj); end",
"def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_string_value(\"description\", @description)\n writer.write_object_value(\"details\", @details)\n writer.write_string_value(\"name\", @name)\n writer.write_enum_value(\"scenarios\", @scenarios)\n end",
"def serialiser\n return @pile\n end",
"def question(name, text, attrs={}, &instance_block)\n q = Question.new(name, text, self, attrs, &instance_block)\n (@_questions||=[]) << q\n \n postprocess_question(q)\n return q\n end",
"def save_questionnaire \n begin\n @questionnaire.save!\n\n save_questions @questionnaire.id if @questionnaire.id != nil and @questionnaire.id > 0\n\n if @questionnaire.type != \"QuizQuestionnaire\"\n pFolder = TreeFolder.find_by_name(@questionnaire.display_type)\n parent = FolderNode.find_by_node_object_id(pFolder.id)\n if QuestionnaireNode.find_by_parent_id_and_node_object_id(parent.id,@questionnaire.id) == nil\n QuestionnaireNode.create(:parent_id => parent.id, :node_object_id => @questionnaire.id)\n end\n end\n rescue\n flash[:error] = $!\n end\n end",
"def add_question(name, type, klass)\n self.payload += add_record(name, type, klass).encode\n self.question_rr += 1\n end",
"def show\n @questions = @exam.questions\n @question = Question.new\n end",
"def to_s\n self.to_json\n end",
"def serialize_for_session\n @serialized_data ||= serialize_object_for_session\n end",
"def answer_to question\n session_data(:answered)[question.id.to_s]\n end",
"def serialize(object)\n object.to_s\n end",
"def show\n @_question = Question.find(params[:id])\n @question = QuestionPresenter.new(@_question)\n end",
"def new\n @question = Question.new\n end",
"def new\n @question = Question.new\n end",
"def new\n @question = Question.new\n end",
"def new\n @question = Question.new\n end",
"def serialize\n {\n participant_id: participant_id,\n reference_id: reference_id,\n decision_text: decision_text,\n promulgation_date: promulgation_date,\n profile_date: profile_date,\n contention_reference_id: contention_reference_id,\n ramp_claim_id: ramp_claim_id,\n title_of_active_review: title_of_active_review,\n rba_contentions_data: rba_contentions_data,\n associated_end_products: associated_end_products.map(&:serialize)\n }\n end",
"def serialize(serializer = nil, options = {})\n serializer ||= self.class::DEFAULT_SERIALIZER\n serializer.new(self, options: options).attributes\n end",
"def question(q, a)\n qu = Question.new(q,a)\n questions << qu\n @counter = 0 #Se inicializa el contador\n end"
] |
[
"0.641145",
"0.6276993",
"0.6276993",
"0.62692004",
"0.6193972",
"0.6187958",
"0.6187958",
"0.6151299",
"0.61481744",
"0.6139823",
"0.6042619",
"0.5874564",
"0.58579063",
"0.58282727",
"0.58166385",
"0.56716084",
"0.5668924",
"0.5660885",
"0.56190443",
"0.56190443",
"0.56190443",
"0.56001997",
"0.5581674",
"0.556108",
"0.5559999",
"0.5559999",
"0.55484784",
"0.55452543",
"0.55320996",
"0.552678",
"0.5515014",
"0.5496451",
"0.54960084",
"0.54946727",
"0.54945344",
"0.5482796",
"0.5482796",
"0.5482796",
"0.5477684",
"0.5472396",
"0.54666156",
"0.54653955",
"0.54653955",
"0.54653955",
"0.54598165",
"0.54524016",
"0.5451593",
"0.54463696",
"0.5436208",
"0.5432096",
"0.5431949",
"0.5431949",
"0.54253125",
"0.54185545",
"0.540299",
"0.5397729",
"0.5377134",
"0.53476334",
"0.5318617",
"0.5315545",
"0.52974313",
"0.52944905",
"0.52915585",
"0.52915585",
"0.5282592",
"0.5269877",
"0.52661717",
"0.5261245",
"0.525613",
"0.5254701",
"0.525016",
"0.52495235",
"0.5220321",
"0.5217497",
"0.5197342",
"0.5188374",
"0.5188075",
"0.5185868",
"0.5177037",
"0.51728946",
"0.5166075",
"0.51621854",
"0.5158198",
"0.5157959",
"0.5153013",
"0.51479685",
"0.5147663",
"0.51383895",
"0.51359975",
"0.51344836",
"0.513003",
"0.5125715",
"0.5120589",
"0.5120546",
"0.5115693",
"0.5115693",
"0.5115693",
"0.5115693",
"0.5115655",
"0.5101619",
"0.5098957"
] |
0.0
|
-1
|
stringifies and sorts hashes by key at all levels.
|
def params_sorted_by_key(params)
case params
when Hash
params.map { |k, v| [k.to_s, params_sorted_by_key(v)] }
.sort_by { |k, v| k }
.to_h
when Array
params.map { |val| params_sorted_by_key(val) }
else
params.to_s
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def fixed_keys_sort(hash)\n hash.keys.sort_by(&:to_s)\n end",
"def deep_stringify_and_sort(&sort_by)\n result = ActiveSupport::OrderedHash.new\n hash = self.stringify_keys\n hash.stringify_keys.keys.sort(&sort_by).each do |key|\n case value = hash[key]\n when Hash then result[key] = value.deep_stringify_and_sort(&sort_by)\n when Array then result[key] = value.collect {|v| (v.is_a?(Hash) ? v.deep_stringify_and_sort(&sort_by) : v) }\n else result[key] = value\n end\n end\n return result\n end",
"def sort_hash(hash)\n puts hash.keys.map(&:to_s).sort_by(&:length)\n end",
"def sort_hash(hash)\n hash.to_a.sort_by { |a, b| a.to_s }\n end",
"def recsort(hash)\n hash = hash.sort_by(&:first).to_h\n hash.each do |k, v|\n if v.is_a? Hash\n hash[k] = recsort(v)\n end\n end\nend",
"def sort_hash(hash)\n value_sorted_hash = hash.transform_values do |value|\n case value\n when Hash\n sort_hash(value)\n when Array\n value.compact.sort\n else\n value\n end\n end\n\n value_sorted_hash.sort\n end",
"def prepare_hash(h)\n result = {}\n\n h.each do |k, v|\n result[k.to_s] = v\n end\n\n result.sort\n end",
"def stringify_hash_keys(hash); end",
"def hash_hash(h)\n require 'digest/md5'\n\n ordered = h.sort.map { |i| i.class==Hash ? i.sort : i }\n return ordered.to_s\n Digest::MD5.hexdigest(Marshal::dump(ordered))\n end",
"def key_sorter(hash)\n hash.keys.map(&:to_s).sort_by do |item|\n item.length\n end\nend",
"def puppetsort(hash)\n # TODO(sissel): Implement sorting that follows the puppet style guide\n # Such as, 'ensure' goes first, etc.\n return hash.to_a\n end",
"def stringify_keys(hash)\n hash.keys.each do |key|\n hash[key.to_s] = hash.delete(key)\n end\n\n hash.values.select{ |v| v.is_a?(Hash) }.each do |h| \n stringify_keys(h)\n end\n hash\n end",
"def deep_stringify_keys!(hash)\n deep_transform_keys!(hash){ |key| key.to_s }\n end",
"def hkey(h)\n h.sort_by{|x| x[0].to_s}\n end",
"def my_hash_sorting_method(source)\n p source.sort_by { |key, value| value }\nend",
"def sort_deep\n new = {}\n keys = self.keys.sort\n keys.each do |main_key|\n self.each_pair do |k, v|\n next unless k == main_key\n if v.class == Hash\n new[k] = v.sort_deep\n else\n new[k] = v\n end\n end\n end\n new\n end",
"def sort_and_print(hash)\n hash.sort_by {|k, v| v}.reverse.each{|item| p item}\nend",
"def sort_hash(orig)\n return unless orig\n {}.tap do |sorted|\n orig.sort.each do |k, v|\n if v.is_a?(Hash)\n sorted[k] = sort_hash(v)\n elsif v.is_a?(Array) && v.length > 0 && v[0].is_a?(Hash)\n sorted[k] = v.map {|a| sort_hash(a)}\n else\n sorted[k] = v\n end\n end\n end\nend",
"def deep_stringify_keys(hash)\n hash.inject({}) { |result, (key, value)|\n value = deep_stringify_keys(value) if value.is_a?(Hash)\n result[key.to_s] = value\n result\n }\n end",
"def symbolize_all_keys!\n self.keys.map do |key|\n if self[key].is_a? Hash\n self[key].symbolize_all_keys!\n elsif self[key].is_a? Array\n # Find hashes to sort in the array.\n self[key].each do |v|\n v.symbolize_all_keys! if v.is_a? Hash\n end\n end\n self[key.to_sym] = self.delete(key)\n end\n self\n end",
"def sorted_keys; end",
"def deep_stringify_keys(hash)\n transform_hash(hash, :deep => true) {|hash, key, value|\n hash[key.to_s] = value\n }\n end",
"def humanize_keys(hash)\n Hash[hash.map { |k, v| [k.humanize, v] }]\n end",
"def print_sorted_hash(hsh)\n pp Hash[hsh.sort_by{|k, v| v}.reverse]\n end",
"def deep_stringify_keys(hash)\n hash.each_with_object({}) do |(key, value), new_hash|\n new_hash[key.to_s] = (value.respond_to?(:to_hash) ? deep_stringify_keys(value) : value)\n end\n end",
"def recursively_stringify_key\n recursively_transform_keys { |key| key.to_s rescue key }\n end",
"def deep_stringify_keys!\n deep_transform_keys!(&:to_s)\n end",
"def deep_stringify_keys!\n deep_transform_keys!(&:to_s)\n end",
"def deep_stringify_keys!\n deep_transform_keys!(&:to_s)\n end",
"def stringify_keys_recursively!(object); end",
"def stringify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ key.to_s ] = stringify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ key.to_s ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def stringify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ key.to_s ] = stringify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ key.to_s ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def stringify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ key.to_s ] = stringify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ key.to_s ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def stringify_keys( hash )\n\t\t\tnewhash = {}\n\n\t\t\thash.each do |key,val|\n\t\t\t\tif val.is_a?( Hash )\n\t\t\t\t\tnewhash[ key.to_s ] = stringify_keys( val )\n\t\t\t\telse\n\t\t\t\t\tnewhash[ key.to_s ] = val\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn newhash\n\t\tend",
"def deep_stringify_keys!\n deep_transform_keys!{ |key| key.to_s }\n end",
"def deep_stringify_keys\n deep_transform_keys { |key| key.to_s }\n end",
"def deep_stringify_keys!\n deep_transform_keys! { |key| key.to_s }\n end",
"def sort_json unsorted_hash\n sorted_hash = Hash.new\n\n unsorted_hash.keys.sort.reverse.each do |k| \n v = unsorted_hash[k]\n v = sort_json(v) if v.class == Hash\n \n if v.class == Array\n v.each_with_index do |o, i| \n if o.class == Hash\n v[i] = sort_json o\n end\n end\n \n # crude assumption about sorting arrays if an object_id is present in a nested object\n v = v.sort { |o1,o2| o1['object_id'] <=> o2['object_id'] } if v[0].present? && v[0]['object_id'].present?\n end\n \n sorted_hash[k] = v\n end\n \n sorted_hash\n end",
"def deeply_stringify_keys(obj)\n deep_key_stringifier.call( obj )\n end",
"def stringify_keys!(hash)\n map_keys!(hash, Transproc(:to_string).fn)\n end",
"def sort!(hash)\n hash.replace(sort(hash))\n end",
"def sort(hash)\n sorted = {}\n hash.keys.sort.reverse.each do |key|\n sorted[key] = hash[key]\n end\n sorted\nend",
"def my_hash_sorting_method(source)\n source.sort {|k,v| k[1]<=>v[1]}\nend",
"def order_hash(h)\n keys = h.keys.sort { | k1,k2 |\n if k1 == 'count'\n ret = -1\n elsif k2 == 'count'\n ret = 1\n else\n # Cities level is slightly different form, if hash at this level then compare\n # count value within hash, otherwise just compare values. mult by -1 to reverse\n # ordering\n if h[k1].class == Hash\n ret = ( h[k1]['count'] <=> h[k2]['count'] ) * -1\n ret = k1 <=> k2 if ret == 0 && k1!=nil && k2!=nil\n else\n ret = ( h[k1] <=> h[k2] ) * -1\n ret = k1 <=> k2 if ret == 0 && k1!=nil && k2!=nil\n end\n end\n ret\n }\n\n # build up return hash\n ret_hash = {}\n keys.each do | key |\n ret_hash[key] = h[key]\n end\n\n ret_hash\n end",
"def sort\n @key_users.values.sort { |a, b| a.qnkeys <=> b.qnkeys }\n end",
"def join_keys(hash, parent_keys = [])\n hash.inject([]) do |keys, (key, value)|\n full_key = parent_keys + [key]\n if value.is_a?(Hash)\n keys += join_keys(value, full_key)\n elsif !value.nil?\n keys << [full_key.join('.'), parse_value(value)]\n end\n keys\n end\n end",
"def sort_keys\n sort_definitions.keys\n end",
"def deep_transform_keys(&block); end",
"def key_order\n # order(key: :asc)\n all.to_a.sort_by {|n| n.key }\n end",
"def stringify_keys!(hash)\n transform_keys!(hash){ |key| key.to_s }\n end",
"def revive_hash hash, o\n o.children.each_slice(2) { |k,v|\n key = accept(k)\n val = accept(v)\n\n if key == SHOVEL && k.tag != \"tag:yaml.org,2002:str\"\n case v\n when Nodes::Alias, Nodes::Mapping\n begin\n hash.merge! val\n rescue TypeError\n hash[key] = val\n end\n when Nodes::Sequence\n begin\n h = {}\n val.reverse_each do |value|\n h.merge! value\n end\n hash.merge! h\n rescue TypeError\n hash[key] = val\n end\n else\n hash[key] = val\n end\n else\n # This is where we handle the translated key\n if v.is_a?(Psych::Nodes::Scalar) && !WcaI18n::PLURALIZATION_KEYS.include?(key)\n # For scalar value, the start line registered is the correct line\n # We assume that the '#original_hash: ' comment comes on the line before.\n original_hash = @original_hashes_by_line.delete(v.start_line - 1)\n val = WcaI18n::TranslatedLeaf.new(val, original_hash)\n end\n if pluralization_map?(v)\n # For mappings, the start line registered is the line of the first key/value!\n original_hash = @original_hashes_by_line.delete(v.start_line - 2)\n val = WcaI18n::TranslatedLeaf.new(val, original_hash)\n end\n hash[key] = val\n end\n }\n hash\n end",
"def make_smart_dictionary\n\t\t@smart_dictionary = {}\n\t\t@dictionary.each do |el|\n\t\t\tel.chomp.split(\"\").each do |key|\n\t\t\t\tif @smart_dictionary.keys.include?(key)\n\t\t\t\t @smart_dictionary[key] += 1\n\t\t\t\telse\n\t\t\t\t\t@smart_dictionary[key] = 1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t@hash_to_sort = @smart_dictionary.sort_by { |k,v| v }.map { |k,v| k }\n\tend",
"def to_flat include_key=true\n if include_key.is_a? Proc\n sort_key = include_key.call(self)\n elsif include_key && respond_to?(:key)\n sort_key = [self.class.resource_name, key].flatten.join(\"-\")\n else\n sort_key = self.class.resource_name\n end\n [sort_key, *to_a.map(&:to_flat)]\n end",
"def recursive_hash_normalize_keys val\n if val.is_a? Hash\n deep_hash_normalize val\n else\n val\n end\n end",
"def flatten_keys(hash)\n hash.transform_keys(&:downcase).transform_keys(&:to_sym)\n end",
"def proc_ordered_hash(ordered_hash)\n updated_els = Hash.new\n ordered_hash.each do |k,v|\n unless is_scalar_type?(v)\n updated_els[k] = convert_to_string_form(v)\n end\n end\n \n ordered_hash.merge(updated_els)\n end",
"def convert(hash)\n if encoded?(hash)\n hash.sort{ |a, b| a[0].to_i <=> b[0].to_i }.map { |key, value| value }\n else\n hash\n end\n end",
"def to_ordered_hash(opts={})\n force = opts.fetch(:force, false)\n sort_json_ld_keys = opts.fetch(:sort_json_ld_keys, true)\n\n unless force\n self.validate\n end\n\n export_hash = IIIF::OrderedHash.new\n\n if sort_json_ld_keys\n self.keys.select { |k| k.start_with?('@') }.sort!.each do |k|\n export_hash[k] = self.data[k]\n end\n end\n\n sub_opts = {\n include_context: false,\n sort_json_ld_keys: sort_json_ld_keys,\n force: force\n }\n self.keys.each do |k|\n unless sort_json_ld_keys && k.start_with?('@')\n if self.data[k].respond_to?(:to_ordered_hash) #.respond_to?(:to_ordered_hash)\n export_hash[k] = self.data[k].to_ordered_hash(sub_opts)\n\n elsif self.data[k].kind_of?(Hash)\n export_hash[k] = IIIF::OrderedHash.new\n self.data[k].each do |sub_k, v|\n\n if v.respond_to?(:to_ordered_hash)\n export_hash[k][sub_k] = v.to_ordered_hash(sub_opts)\n\n elsif v.kind_of?(Array)\n export_hash[k][sub_k] = []\n v.each do |member|\n if member.respond_to?(:to_ordered_hash)\n export_hash[k][sub_k] << member.to_ordered_hash(sub_opts)\n else\n export_hash[k][sub_k] << member\n end\n end\n else\n export_hash[k][sub_k] = v\n end\n end\n\n elsif self.data[k].kind_of?(Array)\n export_hash[k] = []\n\n self.data[k].each do |member|\n if member.respond_to?(:to_ordered_hash)\n export_hash[k] << member.to_ordered_hash(sub_opts)\n\n elsif member.kind_of?(Hash)\n hsh = IIIF::OrderedHash.new\n export_hash[k] << hsh\n member.each do |sub_k,v|\n\n if v.respond_to?(:to_ordered_hash)\n hsh[sub_k] = v.to_ordered_hash(sub_opts)\n\n elsif v.kind_of?(Array)\n hsh[sub_k] = []\n\n v.each do |sub_member|\n if sub_member.respond_to?(:to_ordered_hash)\n hsh[sub_k] << sub_member.to_ordered_hash(sub_opts)\n else\n hsh[sub_k] << sub_member\n end\n end\n else\n hsh[sub_k] = v\n end\n end\n\n else\n export_hash[k] << member\n # there are no nested arrays, right?\n end\n end\n else\n export_hash[k] = self.data[k]\n end\n\n end\n end\n export_hash.remove_empties\n export_hash.camelize_keys\n export_hash\n end",
"def stringify_keys(hash)\n transform_hash(hash) {|hash, key, value| \n hash[key.to_s] = value\n }\n end",
"def sorted_contents\r\n @contents.keys.sort\r\n end",
"def deep_transform_keys!(&block); end",
"def sort_genes\n @chromhash.each_value do |chrom|\n chrom.sort_genes\n end\n end",
"def sort_keys\n success, output = fetch_collection_of_keys\n if success && output.count > 0\n note = ''\n output.sort! { |key1, key2| key1.num_of_days_left <=> key2.num_of_days_left }\n output.each do |key|\n note += key.to_s + \"\\n\"\n end\n return note, output[0].level\n elsif success && output.count == 0\n return 'There are no keys.', 0\n elsif output.nil?\n return 'There are no keys.', 0\n else\n return output, 3\n end\n end",
"def to_s\n str = ''\n longest_key = length_of_longest_key\n unless @hash.empty?\n @hash.keys.sort.each do |key|\n str += format_key_val_string(key, @hash[key], longest_key) + \"\\n\"\n end\n end\n str\n end",
"def stringified_keys; end",
"def stringify_keys\n each_with_object({}) { |(k, v), hsh| hsh[k.to_s] = v.is_a?(Hash) ? v.stringify_keys : v }\n end",
"def new_dictionary(sorted_hash)\n weighted_tree = Array.new\n stop = sorted_hash.values.reduce(:+)\n results = Hash.new\n\n sorted_hash.each do |let, val|\n results[let] = \"\"\n weighted_tree.push [val, [let]]\n end\n weighted_tree = weighted_tree.sort_by{|x| x[0]}\n\n loop do\n node_value = weighted_tree[0].shift + weighted_tree[1].shift\n left, right = weighted_tree.shift[0], weighted_tree.shift[0]\n new_node = [node_value, left + right]\n\n left.each do |path|\n results[path] = \"0\" + results[path]\n end\n right.each do |path|\n results[path] = \"1\" + results[path]\n end\n if node_value >= stop\n break\n end\n weighted_tree.each_with_index do |node, index|\n if node_value <= node[0]\n weighted_tree.insert(index, new_node)\n break\n else\n weighted_tree.push new_node\n break\n end\n end\n end\n return results\nend",
"def generate_hash\n @groups.flatten.inject([]) {|hash, stone| hash << stone.to_s}.sort.hash\n end",
"def stringify_keys\n reduce({}) { |hsh,(k,v)| hsh.merge(k.to_s => v) }\n end",
"def stringify_keys(hash)\n transform_hash(hash) {|hash, key, value|\n hash[key.to_s] = value\n }\n end",
"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 key2str(hash)\n return hash unless hash.is_a? Hash\n hash.each_value.select { |h| h.is_a? Hash }.each do |subh|\n sv = {}\n subh.each { |k, v| sv[k.to_s] = v }\n subh.replace sv\n end\n hash\n end",
"def recursively_normalize_keys\n recursively_transform_keys { |key| key.downcase.to_sym rescue key }\n end",
"def sort_all\n\t\t\t\tr=::Hash[self.sort]\n\t\t\t\tr.each do |k,v|\n\t\t\t\t\tr[k]=v.sort\n\t\t\t\tend\n\t\t\t\treturn r\n\t\t\tend",
"def stringify_keys!(hash)\n hash.keys.each {|key| hash[key.to_s] = hash.delete(key)}\n end",
"def sort_vals_high_to_low(hash)\n result = hash.sort_by {|key, value| value}.reverse.to_h\n end",
"def stringify_keys\n reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }\n end",
"def stringify_keys\n reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }\n end",
"def stringify_keys\n reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }\n end",
"def reconstruct flat_hash\n flat_hash.inject({}) do |result, (key, value)|\n # Build the nested hash for a single key/value pair\n hash = key.split(\".\").reverse.inject(value) do |r, e|\n { e => r }\n end\n\n result.deep_merge(hash)\n end\nend",
"def dictionary_sort(arr)\n rec_dict_sort arr, []\nend",
"def coerce_symbolized_hash(hash, recursive = false)\n hash = not_nil_hash!(hash)\n symbolized = {}\n hash.each_pair{|k,v| \n if recursive and v.kind_of?(Hash)\n v = coerce_symbolized_hash(v)\n end\n symbolized[coerce_name(k)] = v\n }\n symbolized\n end",
"def dictionary_sort arr\n recursive_sort arr, []\nend",
"def keys_to_s!(recursive: true)\n replace(keys_to_s(recursive: recursive))\n end",
"def underscorize_keys(hash)\n return unless hash.is_a?(Hash)\n hash.keys.each do |k|\n key = k.to_s.underscore.to_sym\n hash[key] = hash[k]\n hash.delete(k) if key != k\n end\n hash\n end",
"def sorted_keys\n SORTED_KEYS\n end",
"def keys_flat(body)\n if body.class == Hash\n arr = []\n body.each do |key, value|\n arr << \"#{keys_flat key}=>#{keys_flat value}\"\n end\n body = arr\n end\n if body.class == Array\n str = ''\n body.map! do |value|\n keys_flat value\n end.sort!.each do |value|\n str << value\n end\n end\n if body.class != String\n body = body.to_s << body.class.to_s\n end\n body\n end",
"def dasherize_keys(hash)\n hash.deep_transform_keys do |key|\n key.to_s.dasherize\n end\n end",
"def symbolize_hash_keys(hash); end",
"def order_tree\n @tree.each do | country, country_hash|\n if country != 'count'\n country_hash.each do | region, region_hash |\n @tree[country][region] = order_hash(@tree[country][region]) if region != 'count'\n end\n @tree[country] = order_hash(@tree[country])\n end\n end\n @tree = order_hash(@tree)\n end",
"def sort_and_print(hash, type=\"visits\")\n new_hash = hash.sort_by { |page, visits| -visits}.to_h\n # Print into console to check\n new_hash.each do |page, number_of_visits|\n print page + \" \" + number_of_visits.to_s + \" \" + type + \" \"\n end\n # Return sorted hash\n return new_hash\nend",
"def recursive_symbolize_keys hash\n if !hash.is_a?(Hash)\n return hash\n end\n \n new_hash = {}\n hash.each_pair do |key, value|\n new_hash[key.to_sym] = recursive_symbolize_keys(value)\n end\n new_hash\n end",
"def to_dotted_hash(hash, recursive_key = \"\")\n hash.each_with_object({}) do |(k , v), ret|\n key = recursive_key + k.to_s\n if v.is_a? Hash\n ret.merge!(to_dotted_hash(v, key + \".\"))\n else\n ret[key] = v\n end\n end\n end",
"def sort_pairs(hash)\n nested_pairs = []\n simple_pairs = []\n table_array_pairs = []\n\n # NOTE: our fix (original code: `hash.keys.sort`) (for details see notes above)\n fixed_keys_sort(hash).each do |key|\n val = hash[key]\n element = [key, val]\n\n if val.is_a? Hash\n nested_pairs << element\n elsif val.is_a?(Array) && val.first.is_a?(Hash)\n table_array_pairs << element\n else\n simple_pairs << element\n end\n end\n\n [simple_pairs, nested_pairs, table_array_pairs]\n end",
"def dehash(hash, depth); end",
"def sorted_rolls\n tsort_hash = {}\n @rolls.each do |file_name, roll|\n tsort_hash[file_name.to_s] = roll.dependencies.map(&:to_s)\n end\n\n tsort_hash.tsort.map(&:to_sym)\n end",
"def render_hash(hsh)\n str = \"\"\n indiff_hsh = hsh.with_indifferent_access\n indiff_hsh.keys.sort.each do |key|\n str << \"#{key}: \"\n value = indiff_hsh[key]\n PP::pp(value, str)\n end\n str\n end",
"def sort_pubkeys(pubkeys)\n pubkeys.map{|p| hex_string?(p) ? p : p.unpack1('H*')}.sort\n end",
"def my_hash_sorting_method(source)\n source.sort_by { |pet, age| age }\nend",
"def stringify_keys; end"
] |
[
"0.72697985",
"0.7064936",
"0.6816567",
"0.678557",
"0.64280444",
"0.6369996",
"0.63179386",
"0.6286139",
"0.62857866",
"0.6284841",
"0.6240203",
"0.62281466",
"0.6168877",
"0.6166443",
"0.6144299",
"0.60586685",
"0.6055375",
"0.605347",
"0.6000603",
"0.5945983",
"0.59232247",
"0.5916717",
"0.5904516",
"0.5901529",
"0.5879219",
"0.58710647",
"0.5859736",
"0.5859736",
"0.5848693",
"0.5848218",
"0.5831324",
"0.5831324",
"0.5831324",
"0.5831324",
"0.5829051",
"0.5826857",
"0.58110416",
"0.58022505",
"0.5800762",
"0.57880694",
"0.5761545",
"0.57180715",
"0.5717887",
"0.57068604",
"0.56875557",
"0.56848663",
"0.56706804",
"0.56661266",
"0.5652131",
"0.5650973",
"0.5633353",
"0.5633152",
"0.5619515",
"0.5610177",
"0.56013286",
"0.55986106",
"0.5594485",
"0.55668074",
"0.555543",
"0.55338126",
"0.5526904",
"0.5514968",
"0.5508708",
"0.5505903",
"0.55011725",
"0.54863745",
"0.5479429",
"0.5464513",
"0.544571",
"0.54424846",
"0.54405385",
"0.542723",
"0.5426336",
"0.54251015",
"0.5417785",
"0.5414125",
"0.540274",
"0.540274",
"0.540274",
"0.5389379",
"0.5378391",
"0.5372852",
"0.5370131",
"0.53698605",
"0.53588885",
"0.53568864",
"0.5356521",
"0.53499246",
"0.53477806",
"0.5345873",
"0.53416556",
"0.5337562",
"0.53368145",
"0.5319471",
"0.53154147",
"0.531531",
"0.5311193",
"0.53083044",
"0.5303492",
"0.530327"
] |
0.6136199
|
15
|
Render straight markdown templates. As no ruby will be evaluated the view handler, locals and content block will be ignored.
|
def render(template_name, view_handler, locals, &content)
self.kramdown_source.render(template_name)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def render_markdown\n return @render if @render\n @render = Markdown.new(:content => content, :indent => self.indent, :path => self.commit ? \"/commits/#{self.commit.id}#{self.web_path}\" : self.web_path)\n @render\n end",
"def render_md page, content\n markdown(content || self.body) # HACK\n end",
"def render_md page, content\n markdown(content || self.body) # HACK\n end",
"def render(context)\n site = context.registers[:site]\n converter = site.find_converter_instance(::Jekyll::Converters::Markdown)\n converter.convert(render_block(context))\n end",
"def render_markdown\n return if self.markdown.nil?\n\n render_as = Redcarpet::Render::HTML\n engine = Redcarpet::Markdown.new(render_as, :autolink => true,\n :space_after_headers => true)\n self.content = engine.render(self.markdown)\n end",
"def render_markdown(text)\n html_renderer.render(text).html_safe if text.present?\n end",
"def render_markdown(markdown)\n settings.markdown_renderer.render(markdown)\n end",
"def liquidize_markdown(content, arguments)\n # doc = BlueCloth.new(Liquid::Template.parse(content).render(arguments, :filters => [LiquidFilters], \n # :registers => {:controller => controller, :view => self, :account_site_assets => account_site_assets, :current_user => current_user}))\n doc = ::Kramdown::Document.new(Liquid::Template.parse(content).render(arguments, :filters => [LiquidFilters], \n :registers => {:controller => controller, :view => self, :account_site_assets => account_site_assets, :current_user => current_user}),\n :parse_block_html => true)\n return doc.to_html.html_safe\n end",
"def content\n MarkdownService.new.render(body).html_safe \n end",
"def markdown(content)\n @markdown_renderer ||= CodeRayify.new(:filter_html => true, :hard_wrap => true)\n \n @markdown_options ||= {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n :lax_html_blocks => true,\n }\n \n @markdown ||= Redcarpet::Markdown.new(@markdown_renderer, @markdown_options)\n @markdown.render(content).html_safe\n end",
"def mdrender\n \t@markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)\n end",
"def recursive_render(markdown)\n Redcarpet::Markdown.new(self.class, @options).render(markdown)\n end",
"def markdown(content)\n renderer = CodeRayify.new(hard_wrap: true, filter_html: true)\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_block: true,\n strikethrough: true,\n superscript: true,\n underline: true,\n disable_indented_code_blocks: true,\n }\n\n Redcarpet::Markdown.new(renderer, options).render(content).html_safe\n end",
"def content!\n if File.exist?(file)\n markdown_to_html\n else\n @type = :empty\n \"\"\n end\n end",
"def render_markdown(text)\n Redcarpet::Markdown.new(\n SupermarketRenderer,\n autolink: true,\n fenced_code_blocks: true,\n tables: true,\n no_intra_emphasis: true,\n strikethrough: true,\n superscript: true\n ).render(\n text\n ).html_safe # rubocop:todo Rails/OutputSafety\n end",
"def markdown content\n require \"kramdown\"\n\n content = content.\n gsub(/^``` *(\\w+)/) { \"{:lang=\\\"#$1\\\"}\\n~~~\" }.\n gsub(/^```/, '~~~')\n\n Kramdown::Document.new(content, KRAMDOWN_CONFIG).to_html\n end",
"def markdown content\n require \"kramdown\"\n\n content = content.\n gsub(/^``` *(\\w+)/) { \"{:lang=\\\"#$1\\\"}\\n~~~\" }.\n gsub(/^```/, '~~~')\n\n Kramdown::Document.new(content, KRAMDOWN_CONFIG).to_html\n end",
"def markdown\n markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)\n end",
"def render\n return @markdown unless $yart_installed\n\n lines = @markdown.split(\"\\n\")\n return @markdown unless yart_snippet?(lines)\n\n yart_lines = extract_yart_lines(lines)\n yart_snippet = yart_lines[1..-2].join(\"\\n\")\n raise YART_PARSE_ERROR if yart_snippet.include?(\"YART.parse\")\n\n html = YART.parse { eval(yart_snippet) }\n @markdown.sub!(yart_lines.join(\"\\n\"), html)\n\n render\n end",
"def markdown(text)\n renderer = Redcarpet::Render::SmartyHTML\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_blocks: true,\n strikethrough: true,\n superscript: true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def call\n # mode = (context[:gfm] != false) ? :gfm : :markdown\n # html = GitHub::Markdown.to_html(@text, mode)\n # html.rstrip!\n # html\n\n options = context[:redcarpet_options] || {}\n renderer = HtmlWithRouge.new(\n filter_html: options.fetch(:filter_html, false),\n hard_wrap: options.fetch(:hard_wrap, true)\n )\n options.reject! { |k, v| [:filter_html, :hard_wrap].include?(k) }\n markdown = Redcarpet::Markdown.new(renderer, options)\n html = markdown.render(@text)\n html.rstrip!\n html\n end",
"def recursive_render(markdown)\n Redcarpet::Markdown.new(self.class, REDCARPET_OPTIONS).render(markdown)\n end",
"def markdown(text)\n render_options = {\n filter_html: true,\n hard_wrap: true,\n link_attributes: { rel: 'nofollow' }\n # no_images: true\n }\n renderer = Redcarpet::Render::HTML.new(render_options)\n\n extensions = {\n autolink: true,\n fenced_code_blocks: true,\n lax_spacing: true,\n no_intra_emphasis: true,\n }\n Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe\n end",
"def markdown(text)\n return if text.blank?\n\n extensions = {\n superscript: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true\n }\n render_options = {\n filter_html: true,\n no_images: true,\n no_styles: true,\n safe_links_only: true,\n space_after_headers: true\n }\n\n renderer = Redcarpet::Render::HTML.new(render_options)\n m = Redcarpet::Markdown.new(renderer, extensions)\n sanitize(m.render(text))\n end",
"def render_plain\n template_content\n end",
"def markdown(text)\n return \"\" unless text\n\n CommonMarker.render_doc(text, :SMART).to_html([:NOBREAKS]).html_safe\n end",
"def render(path)\n\t\t\tredcarpet = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true)\n\t\t\tredcarpet.render(File.read(path))\n\t\tend",
"def markdown(text)\n renderer = HTMLwithPygments.new(:hard_wrap => true)\n options = {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n :strikethrough => true,\n :lax_html_blocks => true,\n :superscript => true,\n :space_after_headers => true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def render\n erb_page = ERB.new(content).result(binding)\n Kramdown::Document.new(erb_page).to_html.html_safe\n end",
"def markdown(text)\n options = {\n filter_html: true,\n hard_wrap: true, \n link_attributes: { rel: 'nofollow', target: \"_blank\" },\n space_after_headers: true, \n fenced_code_blocks: true\n }\n\n extensions = {\n autolink: true,\n superscript: true,\n disable_indented_code_blocks: true\n }\n\n renderer = Redcarpet::Render::HTML.new(options)\n markdown = Redcarpet::Markdown.new(renderer, extensions)\n\n markdown.render(text).html_safe\n end",
"def markdown(text)\n renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_blocks: true,\n tables: true,\n strikethrough: true,\n superscript: true,\n xhtml: true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def render\n markdown = ReadmeTemplate.new(\n metadata: @metadata, tasks: @tasks, credit: @credit\n )\n template_path = File.join(\n File.dirname(File.expand_path(__FILE__)),\n '../../templates/readme.md.erb'\n )\n readme = markdown.render(File.read(template_path))\n File.open(\"#{@cookbook}/README.md\", 'w') { |file| file.write(readme) }\n end",
"def render_markdown(file)\n renderer = PygmentizeHTML\n extensions = {:autolink => true, :hard_wrap => true, :space_after_headers => true, :highlight => true, :tables => true, :fenced_code_blocks => true, :gh_blockcode => true}\n redcarpet = Redcarpet::Markdown.new(renderer, extensions)\n @file = redcarpet.render file\n end",
"def render_md(site, readme)\n begin\n mkconverter = site.getConverterImpl(Jekyll::Converters::Markdown)\n readme.gsub! \"```\",\"\\n```\"\n readme.gsub! '```shell','```bash'\n return mkconverter.convert(readme)\n rescue\n return 'Could not convert readme.'\n end\nend",
"def html\n Markdown.render(self.content)\n end",
"def html\n Markdown.render(self.content)\n end",
"def markdown(text)\n# coderayified = CodeRayify.new(:filter_html => true,:hard_wrap => true)\n coderayified = PygmentsHTML.new(\n with_toc_data: true,\n hard_wrap: true\n )\n# coderayified = Redcarpet::Render::HTML.new(:filter_html => true,:hard_wrap => true)\n options = {\n :no_intra_emphasis => true,\n :tables => true,\n :fenced_code_blocks => true,\n :autolink => true,\n :strikethrough => true,\n :lax_spacing => true,\n :superscript => true\n }\n markdown_to_html = Redcarpet::Markdown.new(coderayified, options)\n markdown_to_html.render(text).html_safe\n end",
"def content \n \trenderer = SyntaxRenderer.new(optionize [\n \t:with_toc_data,\n \t#{:hard_wrap,\n \t:xhtml,\n \t:prettify\n \t])\n \n \tmarkdown = Redcarpet::Markdown.new(renderer, optionize([\n \t:fenced_code_blocks,\n \t:no_intra_emphasis,\n \t:tables,\n \t:superscript,\n \t:autolink,\n \t:strikethrough,\n \t:space_after_headers,\n \t:with_toc_data,\n \t:quote,\n \t:lax_spacing\n \t]))\n \n \treturn markdown.render(parse_links(@content)) \n\tend",
"def convert_markdown\n # self.content_html = Kramdown::Document.new(content).to_html\n self.content_html = markdown(content)\n end",
"def markdown(text)\n coderayified = CodeRayify.new(filter_html: true, hard_wrap: true)\n options = {\n link_attributes: { rel: 'nofollow', target: '_blank' },\n space_after_headers: true,\n fenced_code_blocks: true,\n no_intra_emphasis: true,\n autolink: true,\n strikethrough: true,\n lax_html_blocks: true,\n superscript: true\n }\n markdown = Redcarpet::Markdown.new(coderayified, options)\n markdown.render(text).html_safe\n end",
"def markdown(text)\n htmlcoderay = HTMLWithCoderay.new(filter_html: true,\n hard_wrap: true)\n options = {\n fenced_code_blocks: true,\n no_intra_emphasis: true,\n autolink: true,\n lax_html_blocks: true,\n tables: true,\n strikethrough: true,\n superscript: true,\n underline: true,\n highlight: true,\n footnotes: true,\n with_toc_data: true\n }\n\n markdown_to_html = Redcarpet::Markdown.new(htmlcoderay, options)\n begin\n markdown_to_html.render(text).html_safe\n rescue ArgumentError => e\n \"<h1>Error in Markdown: #{e.message}</h1><p>#{@blog.body}</p>\".html_safe\n end\n end",
"def print_markdown(txt)\n Markdown::Processor.instance.render(txt)\n end",
"def call\n result = self.class.markdown_renderer.result(schema: schema)\n if @html\n result = self.class.html_renderer.result(body: self.class.redcarpet.render(result))\n result.gsub(/id=\"(.+)\"/) {|text| text.tr(\"/:\", \"\") }\n else\n result\n end\n end",
"def convert_markdown\n self.html_content = Raptor::Markdown.render(self.content)\n end",
"def call\n markdown = markdown_renderer.result(schema: schema)\n if @html\n html = markdown_parser.render(markdown)\n html = html_renderer.result(body: html)\n html.gsub(/id=\"(.+)\"/) {|text| text.tr(\"/:\", \"\") }\n else\n markdown\n end\n rescue Jdoc::Link::ExampleNotFound => exception\n abort(\"Error: #{exception.to_s}\")\n end",
"def markdown\n @markdown ||= Redcarpet::Markdown.new(\n Blogelator::HTMLRenderer,\n autolink: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true,\n space_after_headers: true\n )\n end",
"def markdown\n @markdown ||= Redcarpet::Markdown.new(\n Blogelator::HTMLRenderer,\n autolink: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true,\n space_after_headers: true\n )\n end",
"def show\n @markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)\n end",
"def embed_md_erb(filename) # => markdown string\n ERB.new(File.read(filename)).result(binding)\n end",
"def markdown(text) # Define method markdown with redcarpet gem\n\t\tRedcarpet::Markdown.new(Redcarpet::Render::HTML).render(text)\n end",
"def markdown\n @markdown ||= process_markdown!\n end",
"def markdown(text)\n coderayified = CodeRayify.new(:filter_html => true, \n :hard_wrap => true,\n :coderay_default_lang => 'ruby'\n )\n options = {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n }\n markdown_to_html = Redcarpet::Markdown.new(coderayified, options)\n markdown_to_html.render(text).html_safe\n end",
"def configure_markdown\n Tilt.register Spirit::Tilt::Template, *%w(markdown mkd md)\n set :markdown, layout: :layout, layout_engine: :haml\n set :haml, escape_html: true, format: :html5\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 markdown(text)\n raw sanitize Markdown.new(text).to_html\n end",
"def html_markup_markdown(text); end",
"def md(text)\n renderer = Redcarpet::Render::HTML.new\n extensions = {filter_html: true}\n redcarpet = Redcarpet::Markdown.new(renderer, extensions)\n redcarpet.render(text).html_safe\n end",
"def partial(template_name, locals, &content)\n self.kramdown_source.render(template_name)\n end",
"def content_for_preview( layout_options )\r\n content = self.body.dup\r\n content.gsub!( /<%=\\s?(@[^%]+)\\s?%>/, '<code>\\1</code>' )\r\n mail = Mail.new( :token => \"\" )\r\n mail.content = Render::Base.new( content ).mail_content\r\n template = IO.read(\"#{RAILS_ROOT}/app/views/mail_tasks/mailer/this_mail.text.html.rhtml\")\r\n \r\n render = Render::Base.new( template, layout_options.merge( :mail => mail ) )\r\n render.mail_content\r\n end",
"def markdown(text)\n return '' if text.nil? || text.empty?\n Wink::Markdown.new(text, :smart).to_html\n end",
"def markdown(text)\n return '' if text.nil? || text.empty?\n Wink::Markdown.new(text, :smart).to_html\n end",
"def cache_markdown_content\n self.markdown_content = GitHub::Markdown.render(content)\n end",
"def markdown(text)\n Redcarpet::Markdown.new(\n Redcarpet::Render::HTML,\n autolink: true,\n tables: true\n ).render(text).html_safe # rubocop:disable Rails/OutputSafety\n end",
"def default_render_proc\n lambda do |template, options|\n HamlWrapper.view( template, options )\n end\n end",
"def process_markdown\n self.explanation_html = Kramdown::Document.new(explanation_md || '').to_html.gsub(/[\\r\\n]+/, '')\n end",
"def render_document(content, extension)\n if %w{md mdown markdown}.include?(extension.downcase)\n render_markdown(content)\n else\n content\n end\n end",
"def prepare_render\n @content = '## Página no encontrada'\n event = Event.find(params[:event_id])\n if (event)\n pages = event.pages.select{ |page| page.path == params[:page_path]}\n unless(pages.empty?)\n @content = MarkdownEventParser.add_event_details(event, pages[0].content)\n end\n end\n @content = MARKDOWN.render(@content)\n render\n end",
"def markdown( text )\n Kramdown::Document.new( text ).to_html\n end",
"def body\n HTML.render render_md, options\n end",
"def to_html\n determine_markdown_renderer\n @markdown.to_html\n end",
"def create\n @post = Post.new(post_params)\n @post.html = render_to_string template: false, partial: 'root/markdown', locals: { markdown: mark.render(@post.markdown) }\n @post.user = current_user\n\n respond_to do |format|\n if @post.save\n format.html {}\n else\n format.html { render :new }\n end\n end\n end",
"def assemble_markup\n\n design_renderer = liquid_for(@design.markup)\n view_renderer = liquid_for(@view_template.markup)\n params = node_template_data.merge(global_template_data)\n\n # Render the view template.\n rendered_view = view_renderer.render(params, :filters => liquid_filters)\n\n # Render the design and merge in the view.\n design_renderer.render(params.merge('content' => rendered_view), :filters => liquid_filters)\n\n end",
"def markdown(text)\n coderay_options = {\n filter_html: true,\n hard_wrap: true,\n safe_links_only: true,\n with_toc_data: true,\n prettify: true\n }\n\n redcarpet_options = {\n autolink: true,\n disable_indented_code_blocks: false,\n fenced_code_blocks: true,\n highlight: true,\n lax_html_blocks: true,\n lax_spacing: true,\n no_intra_emphasis: true,\n strikethrough: true,\n superscript: true,\n tables: true\n }\n\n coderayified = CodeRayify.new(coderay_options)\n markdown_to_html = Redcarpet::Markdown.new(coderayified, redcarpet_options)\n markdown_to_html.render(text).html_safe\n end",
"def block_html(html)\n html.gsub(/<markdown>([\\d\\D]+?)<\\/markdown>/) {|_|\n extensions = {fenced_code_blocks: true}\n renderer = Redcarpet::Markdown.new(WithHighlights, extensions)\n renderer.render(Regexp.last_match[1])\n }\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 markdown_output_html\n \n if self.markdown_output\n self.markdown_output\n else\n self.markdown_output = MARKDOWN_RENDERER.render(self.output)\n end\n end",
"def render(options = {}, locals = {}, &block)\n if options.is_a?(Hash) && path = options.delete(:cms_page)\n site = CmsSite.find_by_hostname(request.host.downcase)\n page = CmsPage.load_from_file(site, path) if site && ComfortableMexicanSofa.configuration.seed_data_path\n page ||= site && site.cms_pages.find_by_full_path(path)\n if page\n cms_app_layout = page.cms_layout.try(:app_layout)\n options[:layout] ||= cms_app_layout.blank?? nil : cms_app_layout\n options[:inline] = page.content\n @cms_page = page\n super(options, locals, &block)\n else\n raise ActionView::MissingTemplate.new([path], path, \"CMS page not found\", nil)\n end\n else\n super(options, locals, &block)\n end\n end",
"def render_localized_markdown(file)\n path = Rails.root.join('config', 'locales', file.to_s,\n \"#{file}.#{I18n.locale}.md\")\n\n # Fall back to English if we have to\n unless File.exist?(path)\n if I18n.locale != :en\n path = Rails.root.join('config', 'locales', file.to_s,\n \"#{file}.en.md\")\n end\n end\n\n # Give up if we can't find it\n unless File.exist?(path)\n fail I18n::MissingTranslationData.new(I18n.locale,\n \"localized_markdown.#{file}\",\n {})\n end\n\n render_to_string(file: path, layout: false).html_safe\n end",
"def formatter(content)\n #render_options = {hard_wrap: true, filter_html: true, safe_links_only: true}\n #markdown_options = {no_intraemphasis: true, autolink: true, superscript: true}\n #markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(render_options),markdown_options)\n #return markdown.render(content).html_safe\n return markdown_to_html(content) unless content.nil?\n end",
"def simple_markdown(text)\n simple_format markdown text\n end",
"def to_html(locals={}, tilt_options={}, &blk)\n html = content(locals, tilt_options, &blk)\n html = layout.to_html(locals, tilt_options) { html } if layout?\n html\n end",
"def render_markdown(str)\n renderer = Redcarpet::Markdown.new(\n Redcarpet::Render::HTML.new(hard_wrap: true),\n autolink: true, tables: true)\n renderer.render(str)\n end",
"def content_for(*args,&block)\n if block\n helpers.content_for(*args,&block)\n else\n rawtext(helpers.content_for(*args))\n ''\n end\n end",
"def default_render\n render(html: \"\", layout: true)\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 markdown(txt)\n options = %i[\n hard_wrap filter_styles autolink\n no_intraemphasis fenced_code gh_blockcode\n ]\n doc = Nokogiri::HTML(Redcarpet.new(txt, *options).to_html)\n doc.search('//pre[@lang]').each do |pre|\n pre.replace Albino.colorize(pre.text.rstrip, pre[:lang])\n end\n doc.xpath('//body').to_s.gsub(%r{</?body>}, '').html_safe\n end",
"def render_template(view, template, layout_name, locals); end",
"def markdown(text)\n sanitize BlueCloth::new(text).to_html\n end",
"def markdown(text)\n options = [:filter_html, :hard_wrap, :autolink, :no_intraemphasis, :gh_blockcode, :fenced_code]\n syntax_highlighter(Redcarpet.new(text, *options).to_html).html_safe\n end",
"def process_default_render exp\n process_layout\n process_template template_name, nil\n end",
"def initialize_markdown_renderer\n @markdown = Redcarpet::Markdown.new Redcarpet::Render::HTML,\n autolink: true,\n fenced_code_blocks: true\n end",
"def markdown_title\n render_as_markdown title\n end",
"def designer_markdown text, options = {}\n return if text.blank?\n Kramdown::Document.new(text, {\n syntax_highlighter_opts: {\n line_numbers: nil\n }\n }.merge(options)).to_html\n end",
"def render(no_follow = false)\n sanitize = no_follow ?\n @wiki.history_sanitizer :\n @wiki.sanitizer\n\n data = extract_tex(@data.dup)\n data = extract_code(data)\n data = extract_tags(data)\n begin\n data = GitHub::Markup.render(@name, data)\n if data.nil?\n raise \"There was an error converting #{@name} to HTML.\"\n end\n rescue Object => e\n data = %{<p class=\"gollum-error\">#{e.message}</p>}\n end\n data = process_tags(data)\n data = process_code(data)\n if sanitize || block_given?\n doc = Nokogiri::HTML::DocumentFragment.parse(data)\n doc = sanitize.clean_node!(doc) if sanitize\n yield doc if block_given?\n data = doc_to_html(doc)\n end\n data = process_tex(data)\n data.gsub!(/<p><\\/p>/, '')\n data\n end",
"def parse_markdown\n self.body_html = markdown.render(body_markdown.to_s)\n self.summary_html = markdown.render(summary_markdown.to_s)\n end",
"def single_content_for(name, content = nil, &block)\n @view_flow.set(name, ActiveSupport::SafeBuffer.new)\n content_for(name, content, &block)\n end",
"def markdown_to_html(content)\n render_options = {hard_wrap: true, filter_html: true, safe_links_only: true}\n markdown_options = {no_intraemphasis: true, autolink: true, superscript: true, fenced_code_blocks: true }\n markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(render_options),markdown_options)\n return markdown.render(content).html_safe\n end",
"def render(options={})\n format = (options[:format] || detect_format(@path)).to_sym\n use_html = options.key?(:html) ? options[:html] == true : true\n use_css = options.key?(:css) ? options[:css] == true : true\n \n unless valid_format?(format)\n raise ArgumentError, \"Invalid format: #{format}\"\n end\n \n @content = Docify::Markup.send(format, File.read(@path))\n if use_html == true\n params = {\n :title => File.basename(@path),\n :content => @content,\n }\n params[:css] = Docify::CSS if use_css == true\n @content = Docify::Template.new(Docify::TEMPLATE).render(params)\n end\n @content\n end",
"def substitute_markdown_inside_raw_html\n each_element(:raw_html) do |e|\n html = e.parsed_html\n next unless html\n\n html.process_markdown_inside_elements(self)\n end\n end",
"def kss_markdown(text)\n require 'redcarpet'\n Redcarpet::Markdown.new(\n Redcarpet::Render::HTML,\n autolink: true,\n tables: true,\n fenced_code_blocks: true,\n strikethrough: true,\n hard_wrap: true,\n space_after_headers: true,\n underline: true\n ).render(text).html_safe\n end"
] |
[
"0.72609544",
"0.72320473",
"0.72320473",
"0.72225416",
"0.70029414",
"0.6962477",
"0.6707446",
"0.65958196",
"0.6485835",
"0.6475052",
"0.6405583",
"0.6397387",
"0.63704205",
"0.6340168",
"0.63400334",
"0.63383126",
"0.63383126",
"0.6332613",
"0.6328182",
"0.6327208",
"0.6305479",
"0.6298106",
"0.62887156",
"0.6266899",
"0.6261845",
"0.6249363",
"0.62445146",
"0.6213039",
"0.6179907",
"0.61793655",
"0.61745507",
"0.61743265",
"0.615669",
"0.61477786",
"0.6144635",
"0.6144635",
"0.6143616",
"0.6132972",
"0.61173755",
"0.6106877",
"0.61048865",
"0.6104699",
"0.6098038",
"0.6087015",
"0.607758",
"0.6077119",
"0.6077119",
"0.6075272",
"0.6071055",
"0.60700846",
"0.60663694",
"0.60578436",
"0.6033174",
"0.60094494",
"0.600384",
"0.5969497",
"0.59544283",
"0.5953483",
"0.59499556",
"0.59344363",
"0.59344363",
"0.5932374",
"0.59068453",
"0.590387",
"0.5902626",
"0.59019434",
"0.5883966",
"0.587855",
"0.5850357",
"0.5850137",
"0.5836123",
"0.5831257",
"0.5814668",
"0.5812908",
"0.58118474",
"0.57917976",
"0.5786963",
"0.5778747",
"0.5777487",
"0.5770996",
"0.5770451",
"0.5767287",
"0.5744297",
"0.57411724",
"0.5738546",
"0.5735796",
"0.5724053",
"0.5715982",
"0.5715103",
"0.5712835",
"0.5708773",
"0.5705692",
"0.5698003",
"0.5682282",
"0.5667641",
"0.5666233",
"0.565501",
"0.56533176",
"0.5641704",
"0.5630384"
] |
0.62538296
|
25
|
Render straight markdown partial templates. As no ruby will be evaluated the locals and content block will be ignored.
|
def partial(template_name, locals, &content)
self.kramdown_source.render(template_name)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def partial(page, locals={})\n haml page, {:layout => false}, locals\n end",
"def render_md page, content\n markdown(content || self.body) # HACK\n end",
"def render_md page, content\n markdown(content || self.body) # HACK\n end",
"def partial(template, locals = {})\n haml(template, { layout: false }, locals)\n end",
"def partial(template, locals = {})\n haml(template, {:layout => false}, locals)\n end",
"def partial(template, locals = {})\n haml(template, {:layout => false}, locals)\n end",
"def render(context)\n site = context.registers[:site]\n converter = site.find_converter_instance(::Jekyll::Converters::Markdown)\n converter.convert(render_block(context))\n end",
"def partial(template, locals = {})\n haml(template, :layout => false, :locals => locals)\n end",
"def partial(template, locals = {})\n erb(template, :layout => false, :locals => locals)\n end",
"def partial(template, locals = {})\n erb(template, :layout => false, :locals => locals)\n end",
"def partial(template, locals = {})\n erb(template, layout: false, locals: locals)\n end",
"def render_markdown\n return @render if @render\n @render = Markdown.new(:content => content, :indent => self.indent, :path => self.commit ? \"/commits/#{self.commit.id}#{self.web_path}\" : self.web_path)\n @render\n end",
"def partial(page, options={})\n erb page, options.merge!(:layout => false)\n end",
"def partial(page, options={})\n erb page, options.merge!(:layout => false)\n end",
"def render_markdown(text)\n html_renderer.render(text).html_safe if text.present?\n end",
"def partial (template, options = {})\n options = { :layout => false }.merge options\n if template.is_a? Hash\n options[:locals] = template[:locals] || {}\n template.delete(:locals) if template[:locals] \n options[:locals].merge! template\n template = template.reject{ |key, value| [:locals].include? key }.keys.first.to_s\n end \n haml(\"_#{template}\".to_sym, options)\n end",
"def render(*args)\n if args.first.is_a?(Hash) && args.first.keys.include?(:partial)\n return haml \"layouts/_#{args.first[:partial]}.html\".to_sym, :layout => false\n else\n super\n end\n end",
"def render_markdown\n return if self.markdown.nil?\n\n render_as = Redcarpet::Render::HTML\n engine = Redcarpet::Markdown.new(render_as, :autolink => true,\n :space_after_headers => true)\n self.content = engine.render(self.markdown)\n end",
"def render_partial(context, options, &block); end",
"def partial (filename,locals={})\n source = File.read(find(filename))\n engine = Haml::Engine.new(source)\n engine.render(binding,locals)\nend",
"def recursive_render(markdown)\n Redcarpet::Markdown.new(self.class, @options).render(markdown)\n end",
"def partial(file_name)\n erb file_name, :layout => false\n end",
"def render(*args)\n options = {}\n if args.length == 1 && args[0].class == String\n # render partial\n options[:partial] = args[0]\n elsif args.length == 1 && args[0].class == Hash\n # render :partial => 'partial', :locals => {:var1 => value1, :var2 => value2}\n options = args[0]\n elsif args.length == 2 && args[0].class == String && args[1].class == Hash\n # render 'partial', :var1 => value1, :var2 => value2\n options[:locals] = args[1]\n options[:partial] = args[0]\n elsif args.length == 1 && args[0].class == Array\n # render ['xpartials','ypartials']\n raise PartialError, \"render array not yet implemented\"\n else\n raise PartialError, \"unsupported arguments\"\n end\n partial = options[:partial] || nil\n raise PartialError, \"partial not specified\" unless partial\n prawn = options[:prawn] || pdf\n @locals_stack ||= []\n @locals_stack.push @locals\n @locals = options[:locals]\n @pdf_stack ||= []\n @pdf_stack.push @pdf\n @pdf = prawn\n instance_eval(partial_source(partial), __FILE__, __LINE__)\n @pdf = @pdf_stack.pop\n @locals = @locals_stack.pop\n end",
"def recursive_render(markdown)\n Redcarpet::Markdown.new(self.class, REDCARPET_OPTIONS).render(markdown)\n end",
"def liquidize_markdown(content, arguments)\n # doc = BlueCloth.new(Liquid::Template.parse(content).render(arguments, :filters => [LiquidFilters], \n # :registers => {:controller => controller, :view => self, :account_site_assets => account_site_assets, :current_user => current_user}))\n doc = ::Kramdown::Document.new(Liquid::Template.parse(content).render(arguments, :filters => [LiquidFilters], \n :registers => {:controller => controller, :view => self, :account_site_assets => account_site_assets, :current_user => current_user}),\n :parse_block_html => true)\n return doc.to_html.html_safe\n end",
"def partial(partial)\n partial_view = \"partials/_#{partial}\".to_sym\n erb partial_view, :layout => false\nend",
"def template_content(folder = 'content', partial = 'dummy')\n render_to_string(:partial => \"shared/#{ folder }/#{ partial }\")\n end",
"def partial(template, *args)\n template_array = template.to_s.split('/')\n template = template_array[0..-2].join('/') + \"/_#{template_array[-1]}\"\n options = args.last.is_a?(Hash) ? args.pop : {}\n options.merge!(:layout => false)\n locals = options[:locals] || {}\n\n if (collection = options.delete(:collection))\n collection.inject([]) do |buffer, member|\n buffer << haml(:\"#{template}\",\n options.merge(:layout => false,\n :locals => {template_array[-1].to_sym => member}.merge(locals)))\n end.join(\"\\n\")\n else\n haml(:\"#{template}\", options)\n end\n end",
"def render_markdown(markdown)\n settings.markdown_renderer.render(markdown)\n end",
"def render_plain\n template_content\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 mdrender\n \t@markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)\n end",
"def markdown(text)\n renderer = Redcarpet::Render::SmartyHTML\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_blocks: true,\n strikethrough: true,\n superscript: true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def render_partial(*ignore_args); end",
"def render_partial(path, locals = {})\n raw theme_view.render(partial: path, locals: locals)\n end",
"def render_partial(partial, content)\n template = ERB.new(File.read partial)\n content_binding = binding_from_hash(content)\n template.result(content_binding).html_safe\n end",
"def content_formatted\n\t\t\t\t\tresult = self.content\n\t\t\t\t\tif config(:partials)\n\t\t\t\t\t\tconfig(:partials).each do |key, partial|\n\t\t\t\t\t\t\tresult = result.gsub(\"%{\" + key.to_s + \"}\", render_partial(partial))\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\treturn result\n\t\t\t\tend",
"def embed_md_erb(filename) # => markdown string\n ERB.new(File.read(filename)).result(binding)\n end",
"def render_markdown(text)\n Redcarpet::Markdown.new(\n SupermarketRenderer,\n autolink: true,\n fenced_code_blocks: true,\n tables: true,\n no_intra_emphasis: true,\n strikethrough: true,\n superscript: true\n ).render(\n text\n ).html_safe # rubocop:todo Rails/OutputSafety\n end",
"def markdown(content)\n @markdown_renderer ||= CodeRayify.new(:filter_html => true, :hard_wrap => true)\n \n @markdown_options ||= {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n :lax_html_blocks => true,\n }\n \n @markdown ||= Redcarpet::Markdown.new(@markdown_renderer, @markdown_options)\n @markdown.render(content).html_safe\n end",
"def markdown(text)\n render_options = {\n filter_html: true,\n hard_wrap: true,\n link_attributes: { rel: 'nofollow' }\n # no_images: true\n }\n renderer = Redcarpet::Render::HTML.new(render_options)\n\n extensions = {\n autolink: true,\n fenced_code_blocks: true,\n lax_spacing: true,\n no_intra_emphasis: true,\n }\n Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe\n end",
"def markdown(content)\n renderer = CodeRayify.new(hard_wrap: true, filter_html: true)\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_block: true,\n strikethrough: true,\n superscript: true,\n underline: true,\n disable_indented_code_blocks: true,\n }\n\n Redcarpet::Markdown.new(renderer, options).render(content).html_safe\n end",
"def markdown(text)\n renderer = HTMLwithPygments.new(:hard_wrap => true)\n options = {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n :strikethrough => true,\n :lax_html_blocks => true,\n :superscript => true,\n :space_after_headers => true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def markdown\n markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)\n end",
"def content!\n if File.exist?(file)\n markdown_to_html\n else\n @type = :empty\n \"\"\n end\n end",
"def render(path)\n\t\t\tredcarpet = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true)\n\t\t\tredcarpet.render(File.read(path))\n\t\tend",
"def render_markdown(file)\n renderer = PygmentizeHTML\n extensions = {:autolink => true, :hard_wrap => true, :space_after_headers => true, :highlight => true, :tables => true, :fenced_code_blocks => true, :gh_blockcode => true}\n redcarpet = Redcarpet::Markdown.new(renderer, extensions)\n @file = redcarpet.render file\n end",
"def partial(template, *args)\n template_array = template.to_s.split('/')\n template = template_array[0..-2].join('/') + \"/_#{template_array[-1]}\"\n options = args.last.is_a?(Hash) ? args.pop : {}\n options.merge!(:layout => false)\n locals = options[:locals] || {}\n if collection = options.delete(:collection) then\n collection.inject([]) do |buffer, member|\n buffer << erb(:\"#{template}\", options.merge(:layout =>\n false, :locals => {template_array[-1].to_sym => member}.merge(locals)))\n end.join(\"\\n\")\n else\n erb(:\"#{template}\", options)\n end\n end",
"def markdown(text)\n return \"\" unless text\n\n CommonMarker.render_doc(text, :SMART).to_html([:NOBREAKS]).html_safe\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 partial(name, options={})\n path = \"com/\"+(params[:path].empty? ? ['index'] : params[:path]).join(\"/\") + \"/\"\n path = 'com' if name.starts_with?('/')\n \n render options.merge(:partial => \"#{RIGHTJS_SRC_DOCS}/#{path}#{name}.html.erb\")\n end",
"def content\n MarkdownService.new.render(body).html_safe \n end",
"def markdown content\n require \"kramdown\"\n\n content = content.\n gsub(/^``` *(\\w+)/) { \"{:lang=\\\"#$1\\\"}\\n~~~\" }.\n gsub(/^```/, '~~~')\n\n Kramdown::Document.new(content, KRAMDOWN_CONFIG).to_html\n end",
"def markdown content\n require \"kramdown\"\n\n content = content.\n gsub(/^``` *(\\w+)/) { \"{:lang=\\\"#$1\\\"}\\n~~~\" }.\n gsub(/^```/, '~~~')\n\n Kramdown::Document.new(content, KRAMDOWN_CONFIG).to_html\n end",
"def partial(template, *args)\n template_array = template.to_s.split('/')\n template = template_array[0..-2].join('/') + \"/_#{template_array[-1]}\"\n options = args.last.is_a?(Hash) ? args.pop : {}\n options.merge!(:layout => false)\n if collection = options.delete(:collection) then\n collection.inject([]) do |buffer, member|\n buffer << erb(:\"#{template}\", options.merge(:layout =>\n false, :locals => {template_array[-1].to_sym => member}))\n end.join(\"\\n\")\n else\n erb(:\"#{template}\", options)\n end\n end",
"def partial(template, *args)\n template_array = template.to_s.split('/')\n template = template_array[0..-2].join('/') + \"/_#{template_array[-1]}\"\n options = args.last.is_a?(Hash) ? args.pop : {}\n options.merge!(:layout => false)\n locals = options[:locals] || {}\n if collection = options.delete(:collection) then\n collection.inject([]) do |buffer, member|\n buffer << erb(:\"#{template}\", options.merge(:layout =>\n false, :locals => {template_array[-1].to_sym => member}.merge(locals)))\n end.join(\"\\n\")\n else\n erb(:\"#{template}\", options)\n end\n end",
"def markdown(text)\n return if text.blank?\n\n extensions = {\n superscript: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true\n }\n render_options = {\n filter_html: true,\n no_images: true,\n no_styles: true,\n safe_links_only: true,\n space_after_headers: true\n }\n\n renderer = Redcarpet::Render::HTML.new(render_options)\n m = Redcarpet::Markdown.new(renderer, extensions)\n sanitize(m.render(text))\n end",
"def block_html(html)\n html.gsub(/<markdown>([\\d\\D]+?)<\\/markdown>/) {|_|\n extensions = {fenced_code_blocks: true}\n renderer = Redcarpet::Markdown.new(WithHighlights, extensions)\n renderer.render(Regexp.last_match[1])\n }\n end",
"def render_ground( ground, opts={} )\r\n tmpl = File.read_utf8( 'templates/shared/_ground.md' )\r\n render_erb_template( tmpl, binding )\r\nend",
"def partial(*args)\n partial_name = args.shift.to_s\n partial_name = PARTIAL_PREFIX + partial_name\n render_partial(partial_name, *args)\n end",
"def markdown(text)\n options = {\n filter_html: true,\n hard_wrap: true, \n link_attributes: { rel: 'nofollow', target: \"_blank\" },\n space_after_headers: true, \n fenced_code_blocks: true\n }\n\n extensions = {\n autolink: true,\n superscript: true,\n disable_indented_code_blocks: true\n }\n\n renderer = Redcarpet::Render::HTML.new(options)\n markdown = Redcarpet::Markdown.new(renderer, extensions)\n\n markdown.render(text).html_safe\n end",
"def render_partial(template, types, context)\n templates.get(template, types).render(context)\n end",
"def markdown(text)\n renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)\n options = {\n autolink: true,\n no_intra_emphasis: true,\n fenced_code_blocks: true,\n lax_html_blocks: true,\n tables: true,\n strikethrough: true,\n superscript: true,\n xhtml: true\n }\n Redcarpet::Markdown.new(renderer, options).render(text).html_safe\n end",
"def markdown(text) # Define method markdown with redcarpet gem\n\t\tRedcarpet::Markdown.new(Redcarpet::Render::HTML).render(text)\n end",
"def build_html\n ApplicationController.render(partial: partial, locals: locals)\n end",
"def prepare_render\n @content = '## Página no encontrada'\n event = Event.find(params[:event_id])\n if (event)\n pages = event.pages.select{ |page| page.path == params[:page_path]}\n unless(pages.empty?)\n @content = MarkdownEventParser.add_event_details(event, pages[0].content)\n end\n end\n @content = MARKDOWN.render(@content)\n render\n end",
"def call\n # mode = (context[:gfm] != false) ? :gfm : :markdown\n # html = GitHub::Markdown.to_html(@text, mode)\n # html.rstrip!\n # html\n\n options = context[:redcarpet_options] || {}\n renderer = HtmlWithRouge.new(\n filter_html: options.fetch(:filter_html, false),\n hard_wrap: options.fetch(:hard_wrap, true)\n )\n options.reject! { |k, v| [:filter_html, :hard_wrap].include?(k) }\n markdown = Redcarpet::Markdown.new(renderer, options)\n html = markdown.render(@text)\n html.rstrip!\n html\n end",
"def markdown(text)\n# coderayified = CodeRayify.new(:filter_html => true,:hard_wrap => true)\n coderayified = PygmentsHTML.new(\n with_toc_data: true,\n hard_wrap: true\n )\n# coderayified = Redcarpet::Render::HTML.new(:filter_html => true,:hard_wrap => true)\n options = {\n :no_intra_emphasis => true,\n :tables => true,\n :fenced_code_blocks => true,\n :autolink => true,\n :strikethrough => true,\n :lax_spacing => true,\n :superscript => true\n }\n markdown_to_html = Redcarpet::Markdown.new(coderayified, options)\n markdown_to_html.render(text).html_safe\n end",
"def partial_description(*args)\n c = \" \"\n if SemiStatic::Engine.config.open_partials[args.first]\n path = File.dirname Rails.root.join('app', 'views') + SemiStatic::Engine.config.open_partials[args.first]\n filename = \"_#{SemiStatic::Engine.config.open_partials[args.first].split('/').last}.html.haml\"\n if File.exist? path + '/' + filename\n File.open(path + '/' + filename) do |file|\n while (line = file.gets)\n if (line.split('-#').count == 2) && line.split('-#').first.empty?\n content = line.split.last\n if conter\n c += line.split('-#').last.to_s.gsub!(/\\n/, \" \")\n else\n\n end\n end\n end\n end\n end\n end\n c\n end",
"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 render\n return @markdown unless $yart_installed\n\n lines = @markdown.split(\"\\n\")\n return @markdown unless yart_snippet?(lines)\n\n yart_lines = extract_yart_lines(lines)\n yart_snippet = yart_lines[1..-2].join(\"\\n\")\n raise YART_PARSE_ERROR if yart_snippet.include?(\"YART.parse\")\n\n html = YART.parse { eval(yart_snippet) }\n @markdown.sub!(yart_lines.join(\"\\n\"), html)\n\n render\n end",
"def markdown\n @markdown ||= Redcarpet::Markdown.new(\n Blogelator::HTMLRenderer,\n autolink: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true,\n space_after_headers: true\n )\n end",
"def markdown\n @markdown ||= Redcarpet::Markdown.new(\n Blogelator::HTMLRenderer,\n autolink: true,\n disable_indented_code_blocks: true,\n fenced_code_blocks: true,\n space_after_headers: true\n )\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 block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n concat(render(:partial => partial_name, :locals => options))\n end",
"def render_partial(name, options={})\n name = name.to_s\n if File.exists?(Rails.root.join(\"app\", \"views\", \"#{website.folder}/#{name.gsub(/\\/(?!.*\\/)/, \"/_\")}.html.erb\"))\n name = \"#{website.folder}/#{name}\"\n end\n eval(\"render '#{name}', options\")\n end",
"def to_html(locals={}, tilt_options={}, &blk)\n html = content(locals, tilt_options, &blk)\n html = layout.to_html(locals, tilt_options) { html } if layout?\n html\n end",
"def render_partial(name, options={})\n if File.exists?(Rails.root.join(\"app\", \"views\", \"layouts\", \"#{name.gsub(/\\/(?!.*\\/)/, \"/_\")}.html.erb\"))\n name = \"#{website.folder}/#{name}\"\n end\n eval(\"render '#{name}', options\")\n end",
"def streamlined_render(options = nil, deprecated_status = nil, &block)\n begin\n render(options, deprecated_status, &block)\n rescue ActionView::TemplateError => ex \n raise ex\n rescue Exception => ex\n if options\n if options[:partial] && @managed_partials.include?(options[:partial])\n options[:partial] = controller.generic_view(options[:partial])\n render(options, deprecated_status, &block)\n else\n raise ex\n end\n else\n view_name = default_template_name.split(\"/\")[-1]\n render(:template => StreamlinedController.generic_view(view_name))\n end\n end\n end",
"def partial(file, locales)\n template = config.get(:template)\n options = template[:options]\n path = \"#{template[:root]}/#{file}.slim\"\n Slim::Template.new(\n # delegate file read to slim\n path,\n # declare default options\n options\n ).render(\n # ensure helpers are scoped\n self,\n # pass locales via parameters\n locales\n )\n end",
"def render_template(options={})\n # puts \"ActionController#render_template(start), options = #{options}\"\n #`var d = new Date(); console.log(\"time= \" + d.getSeconds() + \":\" + d.getMilliseconds());`\n #Timer.time_stamp(\"render_template (begin)\")\n content_fors = options.delete(:content_for) || {}\n partial = options[:partial]\n\n # renderer = ActionView::Renderer.new(self, path: render_path)\n # puts \"renderer = #{@renderer.inspect}\"\n if partial\n # puts \"ActionController#render_template (partial)\"\n top_view_html = @renderer.render(options)\n else\n # puts \"ActionController#render_template (file)\"\n top_view_html = @renderer.render(file: render_path, options: {locals: @__locals})\n end\n\n content_for_htmls = {}\n content_fors.each do |key, selector|\n content_for_html = @renderer.content_fors[key]\n #puts \"content for #{key} = #{content_for_html}\"\n content_for_htmls[selector] = content_for_html\n end\n #`var d = new Date(); console.log(\"time= \" + d.getSeconds() + \":\" + d.getMilliseconds());`\n [top_view_html, content_for_htmls]\n end",
"def markdown(text)\n coderayified = CodeRayify.new(:filter_html => true, \n :hard_wrap => true,\n :coderay_default_lang => 'ruby'\n )\n options = {\n :fenced_code_blocks => true,\n :no_intra_emphasis => true,\n :autolink => true,\n }\n markdown_to_html = Redcarpet::Markdown.new(coderayified, options)\n markdown_to_html.render(text).html_safe\n end",
"def substitute_markdown_inside_raw_html\n each_element(:raw_html) do |e|\n html = e.parsed_html\n next unless html\n\n html.process_markdown_inside_elements(self)\n end\n end",
"def render_template(view, template, layout_name, locals); end",
"def markdown(text)\n coderayified = CodeRayify.new(filter_html: true, hard_wrap: true)\n options = {\n link_attributes: { rel: 'nofollow', target: '_blank' },\n space_after_headers: true,\n fenced_code_blocks: true,\n no_intra_emphasis: true,\n autolink: true,\n strikethrough: true,\n lax_html_blocks: true,\n superscript: true\n }\n markdown = Redcarpet::Markdown.new(coderayified, options)\n markdown.render(text).html_safe\n end",
"def render(options = T.unsafe(nil), locals = T.unsafe(nil), &block); end",
"def markdown_title\n render_as_markdown title\n end",
"def render_partial(context, options, &block) # :nodoc:\n render_partial_to_object(context, options, &block).body\n end",
"def call\n result = self.class.markdown_renderer.result(schema: schema)\n if @html\n result = self.class.html_renderer.result(body: self.class.redcarpet.render(result))\n result.gsub(/id=\"(.+)\"/) {|text| text.tr(\"/:\", \"\") }\n else\n result\n end\n end",
"def markdown\n @markdown ||= process_markdown!\n end",
"def render(options = {}, locals = {}, &block)\n if options.is_a?(Hash) && path = options.delete(:cms_page)\n site = CmsSite.find_by_hostname(request.host.downcase)\n page = CmsPage.load_from_file(site, path) if site && ComfortableMexicanSofa.configuration.seed_data_path\n page ||= site && site.cms_pages.find_by_full_path(path)\n if page\n cms_app_layout = page.cms_layout.try(:app_layout)\n options[:layout] ||= cms_app_layout.blank?? nil : cms_app_layout\n options[:inline] = page.content\n @cms_page = page\n super(options, locals, &block)\n else\n raise ActionView::MissingTemplate.new([path], path, \"CMS page not found\", nil)\n end\n else\n super(options, locals, &block)\n end\n end",
"def render_document(content, extension)\n if %w{md mdown markdown}.include?(extension.downcase)\n render_markdown(content)\n else\n content\n end\n end",
"def render\n markdown = ReadmeTemplate.new(\n metadata: @metadata, tasks: @tasks, credit: @credit\n )\n template_path = File.join(\n File.dirname(File.expand_path(__FILE__)),\n '../../templates/readme.md.erb'\n )\n readme = markdown.render(File.read(template_path))\n File.open(\"#{@cookbook}/README.md\", 'w') { |file| file.write(readme) }\n end",
"def partial; end",
"def partial; end",
"def partial; end",
"def partial; end",
"def assemble_markup\n\n design_renderer = liquid_for(@design.markup)\n view_renderer = liquid_for(@view_template.markup)\n params = node_template_data.merge(global_template_data)\n\n # Render the view template.\n rendered_view = view_renderer.render(params, :filters => liquid_filters)\n\n # Render the design and merge in the view.\n design_renderer.render(params.merge('content' => rendered_view), :filters => liquid_filters)\n\n end",
"def content_for(*args,&block)\n if block\n helpers.content_for(*args,&block)\n else\n rawtext(helpers.content_for(*args))\n ''\n end\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"
] |
[
"0.7001233",
"0.6778516",
"0.6778516",
"0.67237145",
"0.6688345",
"0.6688345",
"0.6649767",
"0.66445214",
"0.6524422",
"0.6524422",
"0.6514172",
"0.6492352",
"0.642148",
"0.642148",
"0.6387135",
"0.6384678",
"0.6332803",
"0.63063526",
"0.6269621",
"0.6229147",
"0.61983186",
"0.6192554",
"0.61714137",
"0.61234915",
"0.6107759",
"0.6100167",
"0.60976714",
"0.6061037",
"0.6050991",
"0.6029496",
"0.60276914",
"0.6004939",
"0.59727633",
"0.59559655",
"0.5948612",
"0.5943019",
"0.58909476",
"0.5886897",
"0.5885206",
"0.58837324",
"0.58678174",
"0.5866875",
"0.586265",
"0.5847039",
"0.5831316",
"0.581002",
"0.5808175",
"0.58037585",
"0.57975984",
"0.57935",
"0.5766069",
"0.5756141",
"0.5746528",
"0.5746528",
"0.57443786",
"0.57440895",
"0.57417417",
"0.5735627",
"0.5719343",
"0.5718787",
"0.57111865",
"0.57021827",
"0.5699759",
"0.56950444",
"0.5686905",
"0.56804156",
"0.5676983",
"0.5665927",
"0.56480616",
"0.5647135",
"0.56463003",
"0.5645757",
"0.5645757",
"0.56412095",
"0.56412095",
"0.5631915",
"0.5627114",
"0.56260943",
"0.56198406",
"0.56193423",
"0.5617953",
"0.5606147",
"0.5598135",
"0.55911046",
"0.55882174",
"0.55816406",
"0.55773556",
"0.55759144",
"0.557476",
"0.5570048",
"0.55685526",
"0.55576575",
"0.55547965",
"0.5552887",
"0.5552887",
"0.5552887",
"0.5552887",
"0.55506754",
"0.5550404",
"0.55410427"
] |
0.7253534
|
0
|
this is used when chaining engines where another engine initially loads the template file
|
def compile(template_name, compiled_content)
self.kramdown_source.compile(template_name, compiled_content)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def template_engine\n @template_engine ||= :erb\n end",
"def initialize()\n @template = \"call load_file() or load_url() to load a template\"\n @loadOK = false \n end",
"def template\n raise \"Template was not loaded: #{@template}\" if !@loadOK\n @template\n end",
"def loadTemplate\n\t\t@template = File.read(@templateFile)\n\tend",
"def loadTemplate\n\t\t@template = File.read(@templateFile)\n\tend",
"def load_template\n\t\traw = IO.read( __FILE__ ).split( /^__END__$/m, 2 ).last\n\t\treturn ERB.new( raw, nil, '<%>' )\n\tend",
"def process_default_render exp\n process_layout\n process_template template_name, nil\n end",
"def render_with_engine_additions(opts)\n template_path_for_method = Dir[\"#{template_path}/#{opts[:file]}*\"].first\n body = opts.delete(:body)\n i = initialize_template_class(body)\n i.base_path = File.dirname(template_path_for_method)\n i.render(opts)\n end",
"def apply_template_before?; end",
"def template_for(file); end",
"def initialize(template_text,options={})\n @renderer_extension_modules=[]\n\n @name=options[:template_name]\n @templates_root_dir= options[:templates_directory]# || \"#{::Rails.root.to_s}/app/views\"\n\n @output_buffer=\"\"\n #unique tag for escaping post and pre processing tags\n @ltag=\"!@@@##$$1212\"\n @rtag=\"!723465hjf3!@#\"\n\n @default_language=options[:default_language] || \"en\"\n\n\n @escape_tags= options[:tags_to_escape] || []\n @runtime_tags= options[:runtime_tags] || []\n\n\n #escape blocks that will be run at view time\n @template_text=template_text.clone\n @escape_tags.each do |etag|\n escape_tag_content( etag,@template_text)\n\n \n end\n\n# raise \"need templates directory\" unless options[:templates_directory]\n\n #escape all normal dynamic blocks for preprocessing\n @template_text=@template_text.gsub(\"<%\",@ltag).gsub(\"%>\",@rtag).gsub(\"<$\",\"<%\").gsub(\"$>\",\"%>\")\n \n #turn the setup block into a proc <## ##> into executable blocks\n @template_text=@template_text.gsub(\"<##\",\"<% set_setup_proc{ \").gsub(\"##>\",\"} %>\")\n\n #turn the key block into a proc <## ##> into executable blocks\n @template_text=@template_text.gsub(\"<!!KEY\",\"<% set_key_proc{ \").gsub(\"!!KEY>\",\"} %>\")\n\n\n @raw_template=compile(@template_text)\n #this hold variations of the template after it has been localized\n #into different languages, but before rendering\n @localized_templates={}\n @setup_proc=nil\n @key_proc=nil\n @render_base=options[:render_base]\n @template_name=options[:template_name]\n #this tag will be used to create non cachable dynamic blocks\n\n\n if options.has_key?(:helpers) && options[:helpers]!=nil\n options[:helpers].each do |helper|\n include helper\n end\n end\n \n end",
"def initialize_engine\n require_template_library 'eco'\n end",
"def set_template\n end",
"def __in_erb_template;\n end",
"def __in_erb_template;\n end",
"def load_template!\n feed = self\n eval(File.read(@file))\n end",
"def apply_template_after?; end",
"def rendered_templates; end",
"def perform_template_load\n memoize(:template) do\n self.data[:template] = api.stack_template_load(self)\n true\n end\n end",
"def initialize( * )\n\t\tsuper\n\t\t@template = self.load_template\n\tend",
"def templates; end",
"def main_content\n do_include(@template)\n end",
"def templates_for(file); end",
"def template_load_path\n @template_load_path ||= File.expand_path(File.dirname(self.filename))\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 determine_template(options); end",
"def render!\n render :file => template_path\n end",
"def template\n @template ||= File.read(template_full_path)\n end",
"def render\n case File.extname(@template_file)\n when '.erb'\n render_erb\n else\n render_plain\n end\n end",
"def eval_file\n @file || '(__TEMPLATE__)'\n end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def initialize_template_class_with_engine_additions(assigns)\n # I'd like to just return this, but I get problems finding methods in helper\n # modules if the method implemention from the regular class is not called\n # \n # ActionView::Base.new(ActionController::Base.view_paths.dup, assigns, self)\n renderer = initialize_template_class_without_engine_additions(assigns)\n renderer.finder.view_paths = ActionController::Base.view_paths.dup\n renderer\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\n @template ||= Template.new name: script_name, out_file: root_ruby_file, type: type\n end",
"def template\n @template ||= self.class.template\n end",
"def prepare_template(name)\n if @loader.needs_compile?(name)\n lua = @compiler.compile(name, @loader.load_template(name))\n @loader.save_compiled(name, lua)\n end\n end",
"def _render_template(options); end",
"def _render_template(options); end",
"def template_source\n raise NotImplementedError\n end",
"def load_erb(erb)\n # @tmpl = ERB.new(erb)\n @tmpl = ERB.new(erb,0,\"<>\")\n end",
"def find_template(views, name, engine, &block)\n I18n.fallbacks[I18n.locale].each { |locale|\n super(views, \"#{name}.#{locale}\", engine, &block) }\n super(views, name, engine, &block)\n end",
"def initialize_template(record)\n source = record.body || \"\"\n virtual_path = \"pages/#{I18n.locale}_#{record.name}_#{record.permalink}\"\n handler = ActionView::Template.registered_template_handler('erb')\n details = {\n :format => Mime['html'],\n :updated_at => record.updated_at,\n :virtual_path => virtual_path\n }\n ActionView::Template.new(source, \"DbPageTemplate - #{virtual_path}\", handler, details)\n end",
"def prepare\n loader = Twig::Loader::Array.new({ file => data })\n\n if options['paths']\n loader = Twig::Loader::Chain.new([\n loader,\n Twig::Loader::Filesystem.new(options['paths'])\n ])\n elsif !@@loader.nil?\n loader = Twig::Loader::Chain.new([\n loader,\n @@loader\n ])\n end\n @engine = Twig::Environment.new(loader, {\n 'debug' => !!@@debug,\n 'auto_reload' => !!@@auto_reload,\n 'charset' => 'UTF-8',\n 'strict_variables' => false,\n 'autoescape' => 'html', #'filename',\n 'cache' => false,\n 'optimizations' => -1\n })\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 get_template(template); end",
"def initialize_engine\n require_template_library 'haml_coffee_assets/compiler'\n end",
"def initialize_engine\n require_template_library 'ejs'\n end",
"def evaluate_template(template_name,bind)\n template_dir = File.expand_path('./scripts',File.dirname(__FILE__))\n template = File.read(File.expand_path(\"./#{template_name}\",template_dir))\n ERB.new(template, nil, '-').result(bind)\nend",
"def evaluate_template(template_name,bind)\n template_dir = File.expand_path('./scripts',File.dirname(__FILE__))\n template = File.read(File.expand_path(\"./#{template_name}\",template_dir))\n ERB.new(template, nil, '-').result(bind)\nend",
"def template_for path, engine=nil\n templates.cache([path, engine]) do\n if file = template_files(path).first\n ext = File.extname(file)\n ext = ext.empty? ? nil : ext[1..-1]\n engine ||= template_engines[ext].first\n engine.new(file) if engine\n end\n end\n end",
"def template() false end",
"def reset\n\t\t\t#@index = 0\n\t\t\tload_template @filename\n\t\tend",
"def _template_cache\n @cache ||= {}\n end",
"def render(template)\n template = File.read(\"./views/#{template}\")\n engine = Haml::Engine.new(template)\n @response = engine.render\nend",
"def template engine, file, action = nil, context = nil\n\n scope = @node_instance || @node || Object.new\n proc = compile(action)\n return engine.new(file) unless proc &&\n instruction = scope.instance_exec(action, &proc)\n\n pool = compiler_pool\n locals = context.is_a?(Hash) ? context.keys : []\n key = '%s:%s:%s:%s' % [file, @node, action, ::Digest::MD5.hexdigest(locals.to_s)]\n\n pool[key] = engine.new(file).precompile(*locals) if instruction == :update\n \n template, offset = pool.get key do\n engine.new(file).precompile(*locals)\n end\n engine.new { [template, offset] }\n end",
"def initialize_engine\n require_template_library 'opal'\n end",
"def template_source\n @template_source ||= @options[:template_content] || read_file(template_file)\n end",
"def render_template(context, options); end",
"def assemble_template body_file\n if body_file.basename.to_s =~ /\\.hh(k|c|p)/\n body = body_file.read\n return body if body\n else\n super\n end\n end",
"def template_page(site); end",
"def render_template(full_path)\n @current_template = TemplateRenderer.new(@volt_app, @target, @controller, @binding_name, full_path)\n\n call_ready\n end",
"def prep_template(language,frame_binding)\n\n template=@localized_templates[language]\n @language=language\n eval(\"@language='#{language}'\",frame_binding)\n \n unless template\n local_template_text=@raw_template.result(frame_binding)\n local_template_text=local_template_text.gsub(@ltag,\"<%\")\n local_template_text=local_template_text.gsub(@rtag,\"%>\")\n\n template=compile(local_template_text)\n @localized_templates[language]=template unless is_development?\n end\n template\n \n end",
"def load_template(templates, obj, sym)\n owner, st_path = *resource_owner(obj.class, sym)\n if st_path\n ct_path = compiled_template_path(owner, sym)\n ct_file_exists = File.file?(ct_path)\n ct_file_mtime = ct_file_exists ? File.mtime(ct_path) : nil\n st_file = File.new(st_path, 'r:UTF-8')\n\n # Find out if template refresh is required\n if !ct_file_exists \\\n || st_file.mtime > ct_file_mtime \\\n || File.mtime(COMPILER_PATH) > ct_file_mtime\n no_refresh = compile_template(\n st_file, ct_path, ct_file_mtime, owner, sym\n )\n else\n no_refresh = true\n end\n\n # Load template\n method_name = (sym == 'view' ? sym : \"#{sym}_view\").to_sym\n owner.instance_eval do\n method_exists = instance_methods(false).include?(method_name)\n unless method_exists && no_refresh\n remove_method method_name if method_exists\n load ct_path\n end\n end\n\n # Register template in cache\n templates[\"#{owner}##{sym}\"] = nil\n templates[\"#{obj.class}##{sym}\"] = nil\n\n method_name\n else\n raise \"undefined template `#{sym}' for #{obj.class}\"\n end\n end",
"def render(*args)\n tpls_file = (@__caller_info__ || __caller_info__).first.first\n self._template_parser.load(tpls_file).parse.each do |template_name, raw_content|\n # no controller name if absolute view path\n ctrl_name = template_name.match(/^\\//) ? nil : self.controller_name\n path = Merb.dir_for(:view) / self._template_location(template_name.gsub(/^\\//,''), nil, ctrl_name)\n file = VirtualFile.new(raw_content, path)\n TEMPLATES[path.to_s] = file\n end\n super\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 init\n File.open(TEMPLATABLE_FILE, 'w') { |f|f.puts TEMPLATABLE_TEMPLATE }\n end",
"def tpl_ext; return @@tpl_ext; end",
"def use_template(klass)\n define_singleton_method(:source_location) { klass.source_location }\n end",
"def uncached_render\n before_process\n\n content = engine.transform(self)\n\n if path and tlayout = layout\n [instance, tlayout.instance].each do |i|\n i.instance_variable_set(\"@content\", content)\n end\n\n content = tlayout.render\n end\n\n content\n\n ensure\n after_process unless $!\n end",
"def precompiled_template(locals)\n @engine.precompiled\n end",
"def precompiled_template(locals)\n @engine.precompiled\n end",
"def initialize_engine\n require_template_library 'haml_coffee'\n end",
"def template_file\n @template_file || \"#{path}/#{template_name}.#{template_extension}\"\n end",
"def render(template_name)\n #Use controller and template names to construct paths to template files.\n\n\n #Use File.read to read the template file.\n\n #Create a new ERB template from the contents.\n \n #Evaluate the ERB template, using binding to capture the controller's instance variables.\n\n #Pass the result to #render_content with a content_type of text/html.\n\n \n end",
"def load_full_container_template(use_disk_cache = false)\n puts \"\\tCaching container template ...\"\n container_class.template(true)\n end",
"def find_template(views, name, engine, &block)\n\t\t \t#normal\n\t\t super(views, name, engine, &block)\n\t\t #_layout folder\n\t\t super(Paths.layout_path, name.to_s, engine, &block)\n\t\t end",
"def use_template(template)\n @template = template\n end",
"def initialize_template_class(response)\n super\n klass = self.class\n while klass && klass != Target::BaseController\n if klass.to_s.underscore =~ /\\/(\\w+)_controller$/\n response.template.aux_paths ||= []\n response.template.aux_paths << \"#{RESTORE_ROOT}/modules/#{$1}/views\"\n end\n klass = klass.superclass\n end\n end",
"def template\n templater.template\n end",
"def init\n File.open(WASHER_FILE, 'w') { |f|f.puts WASHER_TEMPLATE }\n end",
"def templateForComponent(name)\n template = nil\n pfn = pathForName(name)\n if @templateCache.has_key? pfn\n if @templateCache[pfn].respond_to? :weakref_alive?\n rtc = 0\n begin\n template = @templateCache[pfn].self\n rescue Exception => e\n Logger[Ciowa_log].info \"Error: #{e}\\n#{e.backtrace.join(\"\\n\")}\"\n #reload(File.new(pathForName(name)))\n reload(File.new(pfn))\n rtc += 1\n if rtc < 3\n retry\n else\n raise e\n end\n end\n else\n template = @templateCache[pfn]\n end\n else\n \n #reload(File.new(pathForName(name)))\n reload(File.new(pfn)) if pfn\n template = @templateCache[pfn]\n end\n template\n end",
"def template(name); end",
"def _run_tpl(ctx, obj, sym, args={}, &block)\n Tanuki::Loader.run_template(ctx.templates, obj, sym, args, &block)\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 render_template(view, template, layout_name, locals); end",
"def build_script(hook_type)\n ERB.new(DEFAULT_TEMPLATE).result(binding)\n end",
"def renderOutput(request, response, session, propertyLoader, xmlFileToRender, theme)\n @mySession = session\n @myPropertyLoader = propertyLoader\n @myTheme = theme\n rendererConfig = YAML.load_file( \"#{GlobalSettings.getGlobal(\"Server-ConfigPath\")}OutputRenderers/JSON_XMLRenderer.yaml\")\n cWorkArea = GlobalSettings.getCurrentWorkArea(session)\n docDataDir = GlobalSettings.getDocumentDataDirectory\n @FS = File::SEPARATOR\n xmlFileToRender = xmlFileToRender[0..xmlFileToRender.rindex(\".\")]+\"xml\" if xmlFileToRender.end_with? \".admin\"\n #puts \"\\n\\n----------------------------FileToRender: #{xmlFileToRender}--------------------\\n\\n\"\n file = \"#{cWorkArea}#{xmlFileToRender}\"\n file = GlobalSettings.changeFilePathToMatchSystem(file)\n fcms = nil\n myPage = nil\n if File.exists? file\n fcms = FileCMS.new(session, file, false)\n myPage = Page.new(fcms, -1, session, file)\n #puts \"\\n\\n-------------\\n\\nLoaded Page: #{myPage.title}\\n\\n---------------------------------------\"\n else\n fcms = FileCMS.new(session, file, true)\n end\n #puts \"Theme is: #{theme}\"\n themeTmp = request[\"template\"]\n templateDir = \"#{cWorkArea}#{@FS}system#{@FS}templates#{@FS}#{theme}\"\n\n puts \"TemplateDir exists? #{templateDir} -- #{File.exist?(templateDir)}\"\n if(!File.exist?(templateDir) && request[\"template\"] == nil)\n theme = \"default\"\n templateDir = \"#{cWorkArea}#{@FS}system#{@FS}templates#{@FS}#{theme}\"\n end\n\n version = -1\n if(request[\"version\"] != nil)\n version = request[\"version\"].to_i\n end\n\n # TO-DO: Implement Template system then this....\n\n myTemplate = JSONTemplate.new(templateDir, request[\"file_contents\"], myPage)\n myTemplate.setRenderer(self)\n #myTemplate.setHTMLRenderer(self)\n pageContent = myTemplate.getParsedTemplate\n pageModuleContent = \"\"\n if myTemplate.hasModuleTemplates\n\n\n file_contents = request[\"file_contents\"][:blocks]\n #puts \"HELLOOOOOO :::::: #{file_contents}\"\n file_contents.each{ |key|\n #puts \"Request :::::: #{key}\"\n if key.is_a? Array\n #modType = key[:type]\n at = 0\n modId = nil\n key.each{ |nkey|\n\n if at == 0\n modId = nkey\n at = at.next\n #puts \"Module ID::::: #{modId}\"\n elsif nkey.is_a? Hash\n\n modType = nkey[\"type\"]\n #puts \"\\n\\nNext module type: #{modType}\\n\\n\"\n if myTemplate.containsModuleTemplate(modType)\n\n #TO-DO: process needs to be implemented to support templates in modules....\n modTemplate = myTemplate.getModuleTemplate(modType)\n puts \"#{modType} :::: Data:::: #{nkey[\"data\"]}\"\n modParameters = nkey[\"data\"]\n modParameters[\"id\"] = \"#{modId}\"\n modParameters[\"visible\"] = \"true\"\n modParameters[\"descriptive_name\"] = \"#{modType.capitalize} module\"\n puts \"\\n\\nModule Parameters: #{modParameters}\\n\\n\"\n modTemplate.setModuleData(modParameters)\n #puts \"------------------>Processing module template: #{modType} :: #{modTemplate}\"\n #modTemplate.setModuleToRender(mod)\n pageModuleContent.concat(\"<module>\")\n pageModuleContent.concat(modTemplate.parseTemplate)\n pageModuleContent.concat(\"</module>\")\n #puts \"\\n\\n\\n#{pageModuleContent}\\n\\n\\n\"\n else\n pageModuleContent.concat(\"\\\"unsupported\\\": \\\"Module not supported:#{modType}\\\"\")\n end\n end\n }\n end\n }\n end\n #puts \"Test....\"\n pageContent = Parser.replaceAll(pageContent, \"*CONTENT*\", pageModuleContent)\n pageContent = Hub.applyFilters(request, response, session, pageContent)\n\n myFile = fcms.getFileForWrite# { |file|\n myFile.write( pageContent )\n myFile.close\n return \"{\\\"success\\\": \\\"Writing to #{fcms.getFileURL} success\\\"}\"\n\n end",
"def load_template(template)\n begin\n template = File.join(File.dirname(__FILE__), \"/recipes/#{template}\")\n code = open(template).read\n in_root { self.instance_eval(code) }\n rescue LoadError, Errno::ENOENT => e\n raise \"The template [#{template}] could not be loaded. Error: #{e}\"\n end\nend",
"def render_template(template_name, locals={})\n parse_file_as_erb(\"#{Rails.root}/lib/tasks/templates/#{template_name}.erb\", locals)\nend",
"def render_template(path)\n render(path)\n exit\n end",
"def _template\n @template\n end",
"def load_template_innerds(name)\n body = @loader.load_compiled(name)\n body.split(\"\\n\")[1..-2].join(\"\\n\")\n end",
"def resolve_template_engine(template_path)\n resolved_template_path = File.join(self.options.views, template_path.to_s + \".*\")\n template_file = Dir[resolved_template_path].first\n raise \"Template path '#{template_path}' could not be located in views!\" unless template_file\n template_engine = File.extname(template_file)[1..-1].to_sym\n end",
"def render file_name\n template_file = @template_dir + file_name\n\n template = template_for template_file, false, RDoc::ERBPartial\n\n template.filename = template_file.to_s\n\n template.result @context\n end",
"def tpl_dir; return @@tpl_dir; end"
] |
[
"0.6663644",
"0.65755",
"0.6564395",
"0.65490884",
"0.65490884",
"0.64438295",
"0.64160377",
"0.6399417",
"0.6397451",
"0.6397347",
"0.63802975",
"0.63603044",
"0.6356546",
"0.63317317",
"0.63317317",
"0.6326819",
"0.6326625",
"0.6274839",
"0.6269271",
"0.62640345",
"0.6259108",
"0.62465185",
"0.6229961",
"0.6224547",
"0.62101966",
"0.6209502",
"0.6173024",
"0.61629254",
"0.614606",
"0.6131755",
"0.6075856",
"0.6075856",
"0.6075856",
"0.6075856",
"0.6075856",
"0.6075856",
"0.6075856",
"0.60726315",
"0.6059515",
"0.6047589",
"0.60469663",
"0.6027547",
"0.60227454",
"0.60227454",
"0.60049355",
"0.598557",
"0.5977536",
"0.59672797",
"0.596265",
"0.59604794",
"0.5959505",
"0.5934442",
"0.5924298",
"0.5923079",
"0.5923079",
"0.5922947",
"0.5922504",
"0.5910811",
"0.58992046",
"0.5898012",
"0.58898956",
"0.58884954",
"0.58863723",
"0.58789366",
"0.58786464",
"0.5875176",
"0.58681685",
"0.58655953",
"0.5856676",
"0.58559626",
"0.5846143",
"0.58417785",
"0.58219105",
"0.58183104",
"0.5807512",
"0.58069843",
"0.58069843",
"0.5804906",
"0.5798498",
"0.5795162",
"0.57920086",
"0.57918185",
"0.5790603",
"0.57905847",
"0.5790258",
"0.57882684",
"0.5782331",
"0.57767534",
"0.5776753",
"0.5776732",
"0.5773079",
"0.5755327",
"0.574646",
"0.57454056",
"0.57410145",
"0.57403976",
"0.57375365",
"0.5736276",
"0.5733533",
"0.5732235",
"0.5729938"
] |
0.0
|
-1
|
check if chapter is completed
|
def completed?(chapter)
chapters_completed.include? chapter
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def is_chapter?()\n end",
"def whole_chapter?\n starting_bibleverse.verse.zero?\n end",
"def whole_book?\n starting_bibleverse.chapter.zero?\n end",
"def chapter_valid?(chapter)\n chapter.positive? && chapter <= nr_of_chapters\n end",
"def chapters?\n !chapters.empty?\n end",
"def completed?\n completed == '1'\n end",
"def manuscript_chapter_contradicts?(chapter)\n chapter_in_mampf(chapter)&.title != chapter['description']\n end",
"def test_transition_open_to_writing?\n if self.chapters > self.writers.length then\n return false\n else\n return true\n end\n end",
"def complete?\n end",
"def completed?\n completed\n end",
"def crawling_complete?\n @completed\n end",
"def completed_lesson?(lesson)\n chapters_completed.where(lesson: lesson).count == lesson.chapters.count \n end",
"def incomplete?\n !completed\n end",
"def end_of_chapter\n end",
"def completed?\n !!completed\n end",
"def has_single_chapter?(reference)\n fail NotImplementedError, \"You must override #has_single_chapter? in your language class.\"\n end",
"def complete?\n true\n end",
"def complete?\n true\n end",
"def incomplete?\r\n !complete?\r\n end",
"def complete?\n complete == true\n end",
"def complete?\n return state == \"complete\"\n end",
"def chapter_available?(chapter)\n return false if licensed?\n @chapters.key?(chapter)\n end",
"def complete?\n true\n end",
"def complete?\n true\n end",
"def completed?\n\t\t@completed\n\tend",
"def became_completed?\n completed_changed? && completed\n end",
"def completed?\n @completed\n end",
"def complete?\n\tstatus == \"Completed\"\n end",
"def complete?\r\n @is_complete\r\n end",
"def complete?\n @complete\n end",
"def pedia_complete?\n return status == COMPLETE\n end",
"def complete?\n !incomplete?\n end",
"def complete?\n !incomplete?\n end",
"def complete?\n status == \"Completed\"\n end",
"def completed?\n @completed\n end",
"def completed?\n @completed\n end",
"def complete?\n @complete\n end",
"def completed?\n @completed\n end",
"def complete?\n false\n end",
"def incomplete?\n !@complete\n end",
"def check_completed\n\t\tend",
"def one_verse?\n same_chapter? && same_verse?\n end",
"def complete?\n self.complete\n end",
"def incomplete?\n not complete?\n end",
"def complete? c\n c.complete?\n end",
"def completed?\n return @completed\n end",
"def test_more_chapters\n Republic::DirBinder.write(Republic::Book.new { |b|\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 1</p>\"\n }\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 2</p>\"\n }\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 3</p>\"\n }\n }, TEST_DIR + \"/book2\")\n\n assert File.file?(TEST_DIR + \"/book2/chap0000.xhtml\"), \"First chapter present\"\n assert File.file?(TEST_DIR + \"/book2/chap0001.xhtml\"), \"Second chapter present\"\n assert File.file?(TEST_DIR + \"/book2/chap0002.xhtml\"), \"Third chapter present\"\n\n assert_match /.*This is chapter 1.*/, IO.read(TEST_DIR + \"/book2/chap0000.xhtml\")\n assert_match /.*This is chapter 2.*/, IO.read(TEST_DIR + \"/book2/chap0001.xhtml\")\n assert_match /.*This is chapter 3.*/, IO.read(TEST_DIR + \"/book2/chap0002.xhtml\")\n end",
"def complete?\n self.state == 'complete'\n end",
"def completed?\n header_found, footer_found = false, false\n @lines.each do |line| \n line_def = file_format.line_definitions[line[:line_type]]\n header_found = true if line_def.header\n footer_found = true if line_def.footer \n end\n header_found && footer_found \n end",
"def is_section_complete(type)\n total = data.pages.select { |p| p.type == type }.count\n complete = data.pages.select { |p| p.type == type && p.status == 'success' }.count\n\n total == complete ? true : false\n end",
"def completed?\n @step == @total_steps\n end",
"def completed?\n raise \"completed? should be implemented by the extending class\"\n end",
"def will_course_be_completed(course, term)\n taking_course = taking_courses.where(:course_id => course).first\n if taking_course.nil?\n false\n else\n taking_course.year < term.year or (taking_course.year <= term.year and taking_course.semester.order < term.semester.order)\n end\n end",
"def done?\n if @complete == \"Item complete\"\n return \"Item complete\"\n else\n return \"Item incomplete\"\n end\n end",
"def completed?\n self.state == :completed\n end",
"def completed?(step_name)\n status_flag = self.published || false\n\n unless self.published\n current_index = HYDRANT_STEPS.index(step_name)\n last_index = HYDRANT_STEPS.index(current_step)\n \n unless (current_index.nil? or last_index.nil?)\n status_flag = (last_index >= current_index)\n end\n end\n \n status_flag\n end",
"def completed?\n return @complete\n end",
"def completed?\n return @complete\n end",
"def completed?\n self.is_completed\n end",
"def completed?\n !completed_at.blank?\n end",
"def completed?\n attributes['percentDone'] >= 1\n end",
"def completed?\n @progress != 'PENDING'\n end",
"def became_incompleted?\n completed_changed? && !completed\n end",
"def completed_text_extraction\n @found_completed_text_extraction = true\n end",
"def load_chapter\n end",
"def complete?\n\t\t@cards >= COMPLETE_COLLECTION\n\tend",
"def completed\n end",
"def complete?\n checkbox_text =~ COMPLETE\n end",
"def completed?\n self.status == STATUS_COMPLETED\n end",
"def finished?\n\n end",
"def complete?\n return nil unless ivsat_table\n line = ivsat_table.split(\"\\n\").find{|l| l.include? 'INFO: Sequence completeness:' }\n line && !line.include?('partial')\n end",
"def completed?\n status.completed?\n end",
"def complete?\n self.status == STATUS[:complete] \n #self.status == 1\n end",
"def draft_check\n draft_tutorial = self.draft\n draft_chapters = self.chapters.where({draft: true}).empty?\n draft_steps = self.steps.where({draft: true}).empty?\n\n if draft_tutorial == true || draft_chapters == false || draft_steps == false\n return true\n else\n return false\n end\n end",
"def is_finished\n\t\tif self.completed_at \n\t\t\ttrue\n\t\telse\n\t\t\tfalse\n\t\tend\n\tend",
"def completed?\n if self.completed == true\n true\n end\n\n if( self.user_quiz_answers.count == self.quiz.quiz_phases.collect{ |p| p.quiz_questions }.size )\n self.completed = true\n true\n else\n false\n end\n end",
"def is_complete?\n # puts @xml.root.attributes['complete']\n xml = Document.new(File.open(@xmlfile))\n return 'yes' == xml.root.attributes['complete']\n end",
"def is_open?\n bookings.completed.empty?\n end",
"def finished?\n\tfinished_on.present? \n\tend",
"def complete?\n return true unless skipped_at.nil? # a skipped action item is considered complete. Lazy fucks.\n performed?\n end",
"def on_completed?\n @kind == :on_completed\n end",
"def finished?\n\t\tfinished_on.present?\n\tend",
"def finished?\n\t\tfinished_on.present?\n\tend",
"def completed?(step_name)\n status_flag = published? || false\n unless published?\n step_index = HYDRANT_STEPS.index(step_name)\n current_index = HYDRANT_STEPS.index(step_name)\n last_index = HYDRANT_STEPS.index(last_completed_step.first)\n unless (current_index.nil? or last_index.nil?)\n status_flag = (last_index >= current_index)\n end\n end\n status_flag\n end",
"def done?\n # Fill this in\n end",
"def iscompleted?\n status == \"completed\"\n end",
"def done?\n @done \n end",
"def completed_se?(se)\n Helpers::log(\"Checks if .slide_done.txt is created for #{se}..\")\n done_se = completed_run\n done_se.each do |s|\n if /#{s}/.match(se)\n return TRUE\n end\n end\n return FALSE\n end",
"def step_completed?\n !object.waiting_on.include?(scope)\n end",
"def completed?\n @state.to_s =~ /finished|aborted|failed/\n end",
"def possible_chapter(toks, toksnp, tokslcnp, idx)\n if @possible_chapter\n @possible_chapter\n else\n @possible_chapter =\n ((possible_editor(toks, toksnp, tokslcnp, idx) and\n (toks.join(\" \") =~ /[\\.,;]\\s*in[:\\s]/i)) ?\n \"possibleChapter\" : \"noChapter\")\n end\n end",
"def incomplete?\n !complete? && status != 'unknown'\n end",
"def complete?; end",
"def unlocked_chapter\n if !current_user.sk.admin?\n @chapter.prerequisites.each do |p|\n if (!p.section.fondation && !current_user.sk.chapters.exists?(p))\n redirect_to root_path and return\n end\n end\n end\n end",
"def completed?\n \t!completed_at.blank?\n end",
"def incomplete?\n @completed_at.nil?\n end",
"def incomplete?\n @completed_at.nil?\n end",
"def is_word_complete()\n !@current_state.include? \"_\"\n end",
"def completed?\n !completed_at.blank?\n end",
"def completed?\n self.status_sym == :completed\n end"
] |
[
"0.7454416",
"0.7354883",
"0.7082739",
"0.6996206",
"0.69689006",
"0.6820225",
"0.67828554",
"0.6707823",
"0.6693948",
"0.66886413",
"0.66775817",
"0.66647863",
"0.6630133",
"0.6594676",
"0.65755224",
"0.6534223",
"0.65311223",
"0.64830786",
"0.644937",
"0.6446057",
"0.64407283",
"0.644049",
"0.6418988",
"0.6418988",
"0.64077795",
"0.64013386",
"0.6364489",
"0.6360502",
"0.63522357",
"0.6348518",
"0.63389474",
"0.6321762",
"0.6321762",
"0.63212115",
"0.6315003",
"0.6315003",
"0.6294153",
"0.62938344",
"0.6291169",
"0.62831855",
"0.6250533",
"0.62344575",
"0.62232274",
"0.62211365",
"0.62158585",
"0.6214928",
"0.6186678",
"0.61861783",
"0.6183254",
"0.61747116",
"0.6173821",
"0.617328",
"0.61577034",
"0.61525744",
"0.61438334",
"0.61251175",
"0.60704476",
"0.60704476",
"0.6070431",
"0.6065852",
"0.6064759",
"0.6063326",
"0.6038958",
"0.60358953",
"0.603566",
"0.60323745",
"0.60156685",
"0.60026646",
"0.59998596",
"0.59965587",
"0.5974291",
"0.597266",
"0.59666693",
"0.5955798",
"0.5952451",
"0.5949789",
"0.59490925",
"0.594776",
"0.5942079",
"0.5938449",
"0.59346956",
"0.5933634",
"0.5933634",
"0.5929779",
"0.5929739",
"0.5928878",
"0.5907481",
"0.5902836",
"0.58989316",
"0.589391",
"0.58924127",
"0.5891424",
"0.5888327",
"0.58845246",
"0.588349",
"0.58829826",
"0.58829826",
"0.5876152",
"0.58756185",
"0.5870422"
] |
0.82123095
|
0
|
calculate progress of lesson
|
def progress(lesson)
"%0.2f%" % (chapters_completed.where(lesson: lesson).count / lesson.chapters.count.to_f * 100)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def progress\n total_steps_count = self.steps.count\n\n if total_steps_count.zero?\n 0.0\n else\n approved_steps_count = self.steps.where(state: 'approved').count\n (approved_steps_count * 100.0 / total_steps_count).round(2)\n end\n end",
"def calc_progress\n p = 0.25\n unless self.compile_errors.nil?\n p = 0.5\n end\n\n if self.correct\n p = 1.0\n else\n unless self.results.nil?\n p_tc = 0.0\n self.results.each do |id,result|\n unless result['error']\n p_tc = p_tc + 1\n end\n end\n p = p + ((p_tc/self.results.size) * 0.5)\n end\n end\n\n p\n end",
"def progress()\n return 1.0 * @done_time_units / @total_time_units\n end",
"def tasks_progress\n total_done = 0\n total_tasks = 0\n self.stories.each do |story|\n story.issues.each do |issue|\n total_tasks += 1\n total_done += issue.done\n end\n end\n total_tasks > 0 ? total_done / total_tasks : 100\n end",
"def progress_to_lesson(lesson:, lesson_part:)\n current_lesson_number = highest_lesson_progress.fetch(:lesson_number, 0)\n current_lesson_part_number = highest_lesson_progress.fetch(:lesson_part_number, 0)\n success = false\n error = ''\n\n if (current_lesson_number + 1) == lesson.progression_order\n # if student is progressing to next lesson, or progressing to part in current lesson\n if (current_lesson_part_number == 3)\n # and their current lesson part is the 3rd\n if (lesson_part.progression_order == 1)\n # let them progress\n success = true\n self.student_lesson_progresses.create(lesson: lesson, lesson_part: lesson_part)\n else\n # otherwise fail, prevent progression and return error\n success = false\n error = :cannot_skip_lesson_parts\n end\n elsif (current_lesson_part_number < 2) && (lesson_part.progression_order == 3)\n # if attempting to go from part 0 or 1 to part 3, always fail, prevent progression, and return error\n success = false\n error = :cannot_skip_lesson_parts\n elsif (current_lesson_part_number + 1) == lesson_part.progression_order\n # if next lesson step is current lesson step plus 1, we're all good\n # let them progress\n success = true\n self.student_lesson_progresses.create(lesson: lesson, lesson_part: lesson_part)\n end\n elsif (lesson.progression_order == current_lesson_number)\n if (current_lesson_part_number + 1) == lesson_part.progression_order\n # if next lesson step is current lesson step plus 1, we're all good\n # let them progress\n success = true\n self.student_lesson_progresses.create(lesson: lesson, lesson_part: lesson_part)\n elsif (current_lesson_part_number < 2) && (lesson_part.progression_order == 3)\n # if attempting to go from part 0 or 1 to part 3, always fail, prevent progression, and return error\n success = false\n error = :cannot_skip_lesson_parts\n end\n elsif (lesson.progression_order < current_lesson_number)\n # if student is repeating previous lesson, let them\n success = true\n # no-op\n else\n success = false\n error = :cannot_skip_lessons\n end\n\n OpenStruct.new(\n success: success,\n result: highest_lesson_progress,\n error: error,\n )\n end",
"def progress_stats\n word_count = Float(Word.all.length)\n quizzed_count = Float(Quiz.all.uniq { |noun| noun.word_id }.length)\n rate = quizzed_count / word_count\n rate.round(2) * 100\n end",
"def progress()\n percent = (($ops / $total_ops) * 100).floor\n if (percent <= 99)\n $progress.progress = percent\n $ops += 1\n else\n $progress.finish\n end\nend",
"def calculate_progress\n result = self.progress_status\n (100 * result.values.count(true) / result.values.compact.count).to_s\n end",
"def relative_progress\n if stages.any?\n from_stages = stages.collect{ |pr| pr.relative_progress }.sum\n end\n sum=(relative_milestone.to_f / milestones) * relative_expected_percentage\n sum + from_stages.to_f\n end",
"def calculate\n # Percentage of understanding is calculated by following\n self.progress_rate = ((sum_of_point.to_f / total_count.to_f) * 100.00).round(2)\n end",
"def progress\n l = length\n l.zero? ? 0 : 100 * time / l\n end",
"def progress\n l = length\n l.zero? ? 0 : 100 * time / l\n end",
"def progress\n l = length\n l.zero? ? 0 : 100 * time / l\n end",
"def show\n @user = current_user\n @lessons = Lesson.where(chapter_id: @chapter.id)\n @lessons.all.each do |lesson|\n LessonProgression.find_or_create_by(user_id: @user.id, lesson_id: lesson.id, chapter_id: @chapter.id )\n end\n if LessonProgression.where(user_id: @user.id, chapter_id: @chapter.id, completion: true).any?\n @completedlessons = LessonProgression.where(user_id: @user.id, chapter_id: @chapter.id, completion: true).count\n @totallessons = Lesson.where(chapter_id: @chapter.id).count\n @chapterprogress = (@completedlessons.to_f / @totallessons.to_f)*100\n @chapterprogress = @chapterprogress.to_i\n end\n end",
"def progress(run_id)\r\n @result_count = self.get_results(run_id)[:result].length - 1\r\n run = Run.find(run_id)\r\n @result = ((@result_count.to_f / run.units.count.to_f) * 100).round(2)\r\n end",
"def story_progress; $game_variables[72]; end",
"def progress; end",
"def progress; end",
"def progress; end",
"def progress; end",
"def progress; end",
"def progress\n total = asset.pieces.count\n downloaded = total - piece_downloads.incomplete.count\n [downloaded, total]\n end",
"def progress\n return 100 unless @history.first\n completed_size = @history.first.jobs.select(&:completed?).size\n completed_size * 100 / @history.first.jobs.size\n end",
"def score\n return self.progress - self.budget_ratio\n end",
"def get_sentence_progresses\n if @all_sentence_count > 0\n @progress_sentence_ch = 100 * @memorized_sentence_count_ch / @all_sentence_count\n @progress_sentence_ja = 100 * @memorized_sentence_count_ja / @all_sentence_count\n else\n @progress_sentence_ch = 0\n @progress_sentence_ja = 0\n end\n end",
"def progress\n return @progress\n end",
"def progress\n summary = exec_summary\n summary.progress.num_completed_scan_ranges.to_f / summary.progress.total_scan_ranges.to_f\n end",
"def progress_ratio\n return [0, 7] if self.status_id < RegistrationNotStarted::ID\n voting_absentee? ? statuses = Status.voting_absentee_statuses : statuses = Status.voting_in_person_statuses\n progress = statuses.index(self.status) + 1 # otherwise they start at 0\n total = statuses.length\n [progress, total]\n end",
"def progress_rate\n 1\n end",
"def progression counter,opts = {}\n (@steps = nil; return) if opts[:reset]\n @steps ||= (1..10).map{ |n| [(@num_rows.to_f / 10.to_f) * n,n*10] }\n return if @steps.empty?\n c,perc = @steps[0] \n if counter > c\n Logger.<<(__FILE__,\"INFO\",\"Having processed #{perc}% now ...\",inline: true)\n @steps.shift\n end\n end",
"def update\n @current_lesson = @progress.lesson\n next_lesson = @current_lesson.next(@current_lesson)\n @progress.lesson = next_lesson\n respond_to do |format|\n if @progress.update(progress_params)\n format.html { redirect_to \"/students/#{@progress.student.id}\", notice: 'Progress was successfully updated.' }\n format.json { render :show, status: :ok, location: @progress }\n else\n format.html { render :edit }\n format.json { render json: @progress.errors, status: :unprocessable_entity }\n end\n end\n end",
"def education_selection_status\n percent = 0\n step = 25\n percent += step unless university.nil?\n percent += step unless faculty.nil?\n percent += step if main_course_scenario.programs.size > 0\n percent += step if completed_courses.size > 0 or main_course_scenario.taking_courses.size > 0\n percent\n end",
"def progress_percentage\n total_amount = 0\n # proceed_amount = 0\n total_amount = card_sub_tasks.map(&:service_card_count).reduce(:+)\n # card_sub_tasks.each do |card_sub_task|\n # if card_sub_task.proceed == CardSubTask::PROCEED_FINISHED || card_sub_task.proceed == CardSubTask::PROCEED_ERROR\n # proceed_amount += card_sub_task.service_card_count\n # elsif card_sub_task.proceed == CardSubTask::PROCEED_PROCESSING\n # proceed_amount += card_sub_task.service_cards.count\n # end\n # end\n return percentagere = \"#{sprintf(\"%.1f\", proceed_amount.to_i / total_amount.to_f * 100)}%\"\n end",
"def percent_progress\n data[:percent_progress]\n end",
"def percent_progress\n data[:percent_progress]\n end",
"def index\n @completed_count = Lesson.where(completed: true).count\n @total_count = Lesson.count\n @completed_precent = @completed_count.to_f / @total_count\n \n @lessons = Lesson.order(completed: :asc, id: :desc).paginate(page: params[:page], per_page: 30)\n end",
"def show\n calculate_progress\n ##complete_goal\n end",
"def update_percentage_for_parent_progresses user\n\t\tif model_type == \"lesson\" # find or create progress for track and recursively call on track\n\t\t\tProgress.where(model_type: \"track\", model_id: lesson.track.id, user_id: user.id).first_or_create.update_percentage_for_parent_progresses user\n\t\telsif model_type == \"track\" #update the percentage, find or create progress for topic, and recursively call on topic\n\t\t\tlessons = track.lessons.where('lesson_type != (?)', \"tools\")\n\t\t\tlesson_progresses = lessons.map {|l| l.progress(user) }.compact\n\t\t\tupdate_attributes percent_complete: (lesson_progresses.count / lessons.count.to_f ) * 100\n\t\t\tProgress.where(model_type: \"topic\", model_id: track.topic.id, user_id: user.id).first_or_create.update_percentage_for_parent_progresses user\n\t\telse model_type == \"topic\" #update topic percentage and return\n\t\t\ttracks = topic.tracks\n\t\t\ttrack_progresses = tracks.map {|t| t.progress_percentage(user) }.inject(:+)\n\t\t\tupdate_attributes percent_complete: (track_progresses / tracks.count.to_f ).floor \n\t\tend\n\tend",
"def progress\n data.progress\n end",
"def current_step\n @current_step = wizard_steps.index(step) + 1\n @current_steps = wizard_steps.count\n @current_percentage = @current_step * 100 / @current_steps\n end",
"def progress; state == 'running' ? @doc['progress'] : nil; end",
"def percentage; end",
"def update_progress\n p = Progress.find_or_initialize_by(team_id:self.team_id,user_id:self.user_id,question_id:self.question_id)\n x = self.calc_progress\n if x > p.value\n p.value = x\n end\n p.save!\n end",
"def percent_passes; end",
"def percent_passes; end",
"def percent_complete\n xml = @client.get_request(\"/services/search/jobs/#{@sid}\")\n doc = Nokogiri::XML(xml)\n progress = doc.xpath(\"//s:key[@name='doneProgress']\").text\n return \"#{progress}/1.0\"\n end",
"def get_progress(board)\n counter = 0\n total = $board_width * $board_height\n board.each do |row|\n row.each do |cell| \n if cell == board[0][0]\n counter+=1\n end\n end\n end\n return (counter/total.to_f * 100).to_i\nend",
"def update_progress\n progress = 0\n self.weight_histories.each do |w|\n progress += w.weight_recording\n end\n self.update(progress: progress)\n end",
"def power_play_goal_percentage(seasonasstring) # power_play info in game team stat\n #find list of all games in season given by arg\n #sum all power play goals\n #sum all power play oppertunities\n #divide line 146 and line 147\n #return total of above\n end",
"def self_percent_complete\n if !self.self_check_count.blank?\n if self.designer_completed_checks <= self.self_check_count\n self.designer_completed_checks * 100.0 / self.self_check_count\n else\n 100.0\n end\n else\n 0\n end\n end",
"def update_progress(total, done)\n percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i\n progress(percentage)\n end",
"def progress\n\t@donations = Donation.find_all_by_fundraiser_id(id)\n\t@progress = 0\n\tif @donations.nil?\n\t return @progress\n\telse\n\t @donations.each do |d|\n\t\tif !d.amount.nil?\n\t\t @progress += d.amount\n\t\tend\n\t end\n\tend\n\treturn @progress\n end",
"def get_progresses\n if @all_count > 0\n @progress_ch = 100 * @memorized_count_ch / @all_count\n @progress_ja = 100 * @memorized_count_ja / @all_count\n else\n @progress_ch = 0\n @progress_ja = 0\n end\n end",
"def pri_goal_percentage\n shots_on_goal > 0 ? goals.to_f / shots_on_goal : 1.0\n end",
"def next_percent_complete\n (self.completeness_score.to_f + self.failed_checks.first[:weighting]) / self.class.max_completeness_score.to_f * 100\n end",
"def grade_percentage\n # get the number of passing tests as a float\n passing_tests = tests.select { |test| test.test_status == \"passed\" }.length.to_f\n # get total number of all that students tests\n all_tests = tests.length.to_f\n # calculate their passing_tests as a % of their total tests\n passing_tests / all_tests * 100\n end",
"def progressValue\n return @progressValue\n end",
"def percent_complete\n # return 0 if there is no tasks\n return 0 if tasks.none?\n ((total_complete.to_f / total_tasks) * 100).round\n end",
"def images_conversion_progress\n return (\"%.2f\" % (number_of_completed_images * 1.0 / self.number_of_images_entry)).to_f if self.is_pdf_convertible? \n return 1\n end",
"def complete_percent\n if learner\n # check if this is a reportable thing, if not then base the percent on the existance of the learner\n if offering_reportable?\n learner.report_learner.complete_percent || 0\n else\n # Offering is not reportable, but it has been started. Return 100%.\n 100\n end\n else\n 0\n end\n end",
"def get_build_progress\n total = get_total_pages\n complete = get_page_count('success')\n progress = (complete.to_f / total.to_f) * 100\n\n progress.ceil\n end",
"def import_progress\n import_done.to_f / ( import_total || 999999999 )\n end",
"def progress(status)\n #For each SUT\n $sut.each do |ip, sut|\n #We check the status that we determined earlier,\n #depending on it we call the progress functions\n if status[ip]['status'] == 'Autotest'\n autotestprogress(status, sut, ip)\n elsif status[ip]['status'] == 'Stability'\n stabilityprogress(status, sut, ip)\n elsif status[ip]['status'] == 'CanWakeupTest'\n status[ip]['progress'] == 'Not implemented'\n elsif status[ip]['status'] == 'Manual'\n #If the test is manual, we just say it is not implemented yet. Do not know if it ever will,\n #because it is kind of impossible to know where manual test results will be saved.\n status[ip]['progress'] = 'Not implemented'\n elsif status[ip]['status'] == \"Idle\"\n latest = `ls -td #{$autotestpath}#{sut[:name]}*/ | head -n 1`[0...-1]\n latest = `ls -td #{latest}2017*/ | head -n 1`[0...-1]\n failed = `find #{latest} -name *TestRun.txt`[0...-1]\n if failed == '' && latest != ''\n status[ip]['progress'] = \"Last test failed to proceed\"\n status[ip]['progresscolor'] = \"color:red;\"\n else\n #Idle will be shown as empty in progress tab\n status[ip]['progress'] = ' '\n status[ip]['progresscolor'] = \"color:white;\"\n end\n end\n end\nend",
"def progress_as_percentage\n\t\t\"#{real_days_progress_today.round}%\"\n\tend",
"def get_progress()\n @result_tfile.rewind\n progress = @result_tfile.each_line.collect do |line|\n group = line.scan(/Completed (\\d+) requests/)\n group = group.empty? ? 0 : group[0][0]\n end\n progress.reject{|x| x == 0}.length * 10\n end",
"def inc_progress(activity_rank)\n #diff = (@rank - activity_rank).abs\n ranks = [-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8]\n true_diff = ranks.index(activity_rank) - ranks.index(@rank)\n if true_diff < 0\n if true_diff <= -2\n nil\n else\n @progress += 1\n end\n elsif true_diff == 0\n @progress += 3\n else\n @progress += (10*true_diff*true_diff)\n end\n while @progress >= 100\n self.increase_rank\n @progress -= 100\n end\n end",
"def percent_complete\n @percent_complete ||= calculate_percent_complete\n end",
"def progress_line; end",
"def inc number=0.0\n\t\t@progress_bar.fraction = (@prog += number)\n\tend",
"def index\n @goals = current_user.goals\n \n @goals.each do |g|\n completed_milestone=0\n @milestones=g.milestones \n if(@milestones.count>0)\n @milestones.each do |m|\n if(m.completed)\n completed_milestone=completed_milestone+1\n end\n \n\n end\n g.percentage=(completed_milestone/@milestones.count)*100\n else\n g.percentage=0\n end\n \n end\n\n end",
"def achievements_percentage\n achievements_done.to_f / @achievements.size\n end",
"def progress_params\n params.require(:progress).permit(:lesson_id, :student_id)\n end",
"def percentage_of_passives\n calculator.percentage_of_passives\n end",
"def percent_complete(user)\n\t\tcompletedWorth = 0.0\n\t\ttotalWorth = 0.0\n\t\t\n\t\tself.assignments.each do |assignment|\n\t\t\ttotalWorth += assignment.worth\n\t\t\t\n\t\t\tif assignment.user_grade(user)\n\t\t\t\tcompletedWorth += assignment.worth\n\t\t\tend\n\t\tend\n\t\t\n\t\tif totalWorth != 0\n\t\t\treturn completedWorth / totalWorth\n\t\tend\n\tend",
"def document_progress(new_weight, old_weight)\n if self.goal == \"Lose Weight\"\n self.weight_histories.create(weight_recording: (old_weight - new_weight))\n elsif self.goal == \"Gain Weight\"\n self.weight_histories.create(weight_recording: (new_weight - old_weight))\n end\n end",
"def highest_lesson_progress\n self.student_lesson_progresses.select(:lesson_id, :lesson_part_id).limit(1).order(lesson_id: :desc, lesson_part_id: :desc).try(:first).try(:as_hash) ||\n { lesson_number: 0, lesson_part_number: 0 }\n end",
"def total\n count = 0\n self.total_time_exercise_workouts.each do |ex|\n count += ex.duration\n end\n count\n end",
"def normalization_progress(node)\n if node['progress']\n node['progress'] = 100 if node['progress'] > 100\n node['progress'] = 0 if node['progress'] < 0\n else\n node['progress'] = 100 if integrated_status?(node['status'])\n end\n end",
"def grade_percentage\n passed_tests.count / my_tests.count\n end",
"def masterwork_prob_bonus; 0; end",
"def pdf_total_time\n runs.sum(:finish)\n end",
"def update_progress(steps)\n return unless progress_printer\n unless @progress_printer_instance\n total_records =\n session.left.select_one(\"select count(*) as n from #{session.left.quote_table_name(left_table)}\")['n'].to_i +\n session.right.select_one(\"select count(*) as n from #{session.right.quote_table_name(right_table)}\")['n'].to_i\n @progress_printer_instance = progress_printer.new(total_records, session, left_table, right_table)\n end\n @progress_printer_instance.step(steps)\n end",
"def score\n total = 0\n achievements.each do |a|\n total += a.task.score\n end\n total\n end",
"def grade_percentage\n # This is the total number of tests a student (self) has taken.\n student_tests = BoatingTest.all.select do |test|\n test.student == self\n end\n\n # From the total number of tests taken by that student (self), we just want\n # the one's that have passed.\n passed_test = student_tests.select do |test|\n test.status == \"passed\"\n end\n # From the total number of tests taken by that student (self), we just want\n # the one's that have failed.\n failed_test = student_tests.select do |test|\n test.status == \"failed\"\n end\n\n # Now we need to find the percent of tests that this student (self) has\n # passed compared to the total number of tests they have taken.\n # Multiply by 100 to get a % value instead of decimal.\n # ratio = (passed_test.length.to_f)/(student_tests.length)\n # ratio * 100 SAME AS BELOW\n ratio = \"%.2f\" % (passed_test.length.fdiv(student_tests.length)*100).to_s + \"%\"\n # The \"%.2f\"\n end",
"def update_status\n inds = self.indicators\n if inds.size == 0\n self.status=0.0\n else\n status = 0.0\n inds.each do |indicator|\n status += indicator.contributing_projects_status\n end\n self.status = status / inds.size\n end\n end",
"def info_progress_as_percentaje\n\t\tif self.resources\n\t\t\treal = resources_progress_as_percentage\n\t\t\texpected = resources_estimated_progress_as_percentage\n\t\telse\n\t\t\treal = progress_as_percentage\n\t\t\texpected = estimated_progress_as_percentage\n\t\tend\n\n\t\treturn [real, expected]\n\tend",
"def indicate_progress\n end",
"def grade_percentage\n studentTests= BoatingTest.all.find_all{|test| test.student.first_name == self.first_name}\n totalTests= studentTests.length.to_f\n totalPassed= studentTests.find_all{|test| test.status == \"passed\"}\n numPassed= totalPassed.length.to_f\n percent= (numPassed/totalTests)*100\n end",
"def calculate_duration_of(task) ; 5 ; end",
"def grade_percentage\n all_tests = BoatingTest.all.select do |test|\n test.student == self\n end\n passed_tests = all_tests.select do |test|\n test.status == \"passed\"\n end\n passed_tests.length.to_f/all_tests.length.to_f\n end",
"def progress=(_arg0); end",
"def progress=(_arg0); end",
"def progress=(_arg0); end",
"def progress=(_arg0); end",
"def next_step_number\n progress = current_progress\n progress ? current_progress.step.number + 1 : 0\n end",
"def grade_percentage\n (self.passed_tests.length.to_f / self.tests.length * 100).round(2)\n end",
"def progress=(value)\n @progress = value\n end",
"def show\n @progress = @lesson.progressions.find_by(:user => current_user)\n end",
"def progress_today\n today = Date.today\n run.on(today).size.to_f / on(today).size\n end",
"def input_completed_percentage\n total_input_days = 0\n total_pending_input = 0\n self.users.each do |user|\n pending_input, input_days = user.pending_input\n total_pending_input += pending_input\n total_input_days += input_days\n end\n # If no users, then input is OK\n return 1 if total_input_days == 0\n ((total_input_days - total_pending_input) / total_input_days.to_f).round(2)\n end"
] |
[
"0.771072",
"0.7305538",
"0.726116",
"0.71067166",
"0.70205104",
"0.6955883",
"0.69348335",
"0.6862262",
"0.6855532",
"0.6753974",
"0.6659185",
"0.6659185",
"0.6659185",
"0.6652969",
"0.6642433",
"0.66372055",
"0.6595403",
"0.6595403",
"0.6595403",
"0.6595403",
"0.6595403",
"0.6579258",
"0.65744483",
"0.65102977",
"0.6408839",
"0.6393332",
"0.63720655",
"0.6370624",
"0.63425034",
"0.6341009",
"0.6329648",
"0.63288516",
"0.6328784",
"0.63052785",
"0.63052785",
"0.6299541",
"0.62755126",
"0.6264428",
"0.6254602",
"0.6239605",
"0.6230157",
"0.6205974",
"0.6199949",
"0.619618",
"0.619618",
"0.61760956",
"0.6162758",
"0.61323535",
"0.61283433",
"0.61247426",
"0.6119923",
"0.60702837",
"0.60694987",
"0.6047511",
"0.6043525",
"0.6023961",
"0.6010326",
"0.60090536",
"0.60073036",
"0.60067254",
"0.6001119",
"0.59985495",
"0.59835666",
"0.59720975",
"0.59693754",
"0.59616655",
"0.5953414",
"0.5948918",
"0.59221846",
"0.59213525",
"0.58610034",
"0.58607954",
"0.58249027",
"0.58232987",
"0.5822561",
"0.58169013",
"0.5806717",
"0.58045316",
"0.5803814",
"0.5802298",
"0.57901317",
"0.5782665",
"0.5782064",
"0.57745075",
"0.5769348",
"0.5761223",
"0.5733818",
"0.5727225",
"0.5707638",
"0.57044494",
"0.5703569",
"0.5703569",
"0.5703569",
"0.5703569",
"0.56915647",
"0.5685356",
"0.56849307",
"0.5681816",
"0.5681376",
"0.56762797"
] |
0.8135817
|
0
|
calculate if the lesson is completed
|
def completed_lesson?(lesson)
chapters_completed.where(lesson: lesson).count == lesson.chapters.count
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def completed?\n attributes['percentDone'] >= 1\n end",
"def completed?\n completed\n end",
"def completed?\n @completed\n end",
"def completed?\n @completed\n end",
"def completed?\n\t\t@completed\n\tend",
"def completed?\n completed == '1'\n end",
"def completed?\n @step == @total_steps\n end",
"def completed?\n @completed\n end",
"def completed?\n return @completed\n end",
"def completed?\n !!completed\n end",
"def crawling_complete?\n @completed\n end",
"def became_completed?\n completed_changed? && completed\n end",
"def completed?\n @completed\n end",
"def completed?(idea_id)\n idea = Idea.find idea_id\n questions_count = self.questions.count\n responses = Response.where(:survey_section_id => self.id, :response_set_id => idea.response_set.id)\n responses_count = responses.count\n if responses_count == 0\n 0\n else\n finished_percentage = ((responses_count)*100/(questions_count))\n finished_percentage = 100 if finished_percentage > 100\n finished_percentage = 27 if finished_percentage < 27 && finished_percentage > 0\n finished_percentage\n end\n end",
"def completed?\n !completed_at.blank?\n end",
"def completed?\n if self.completed == true\n true\n end\n\n if( self.user_quiz_answers.count == self.quiz.quiz_phases.collect{ |p| p.quiz_questions }.size )\n self.completed = true\n true\n else\n false\n end\n end",
"def completed?\n !@time_started.nil? && !@time_completed.nil?\n end",
"def completed?\n self.is_completed\n end",
"def completed\n @completed ||= count('completed')\n end",
"def will_course_be_completed(course, term)\n taking_course = taking_courses.where(:course_id => course).first\n if taking_course.nil?\n false\n else\n taking_course.year < term.year or (taking_course.year <= term.year and taking_course.semester.order < term.semester.order)\n end\n end",
"def completed?\n \t!completed_at.blank?\n end",
"def completed?\n min_moves == moves_count.value\n end",
"def completed?\n !completed_at.blank?\n end",
"def completed?\n status.completed?\n end",
"def completed_training?(training)\n return false if training.nil?\n c = training_completions.find(:first, :conditions => { :training_id => training.id })\n c.nil? ? false : c.completed?\n end",
"def is_done\n return @stand\n end",
"def isCompleted\r\n\t\t\t\t\treturn @completed\r\n\t\t\t\tend",
"def isCompleted\r\n\t\t\t\t\treturn @completed\r\n\t\t\t\tend",
"def check_completed\n\t\tend",
"def check_progress\n if self.can_check_progress\n on_db :adage do\n self.completed = !AdaData.with_game(self.name).where(user_id: self.user_id).last.nil?\n self.save\n end\n end\n return self.completed\n end",
"def completed?\n \tcompleted_at?\n end",
"def update_completed? ; false ; end",
"def get_completed_too?\n session.fetch(:completed, params.fetch(:completed, \"0\")) == \"1\"\n end",
"def completed?\n (@start + 10 * DAY) < Time.now\n # p (@start + 10 * DAY)\n end",
"def became_incompleted?\n completed_changed? && !completed\n end",
"def completed?\n completed_at ? true : false\n end",
"def completed?\n completed_at ? true : false\n end",
"def complete?\n total = 0\n @element_list.each do |element|\n total += element[1]\n end\n total >= @target\n end",
"def completed?\n !!completed_at\n end",
"def completed\n candidate_events.select(&:completed?)\n end",
"def completed?\n team_winner\n end",
"def is_finished\n\t\tif self.completed_at \n\t\t\ttrue\n\t\telse\n\t\t\tfalse\n\t\tend\n\tend",
"def iscompleted?\n status == \"completed\"\n end",
"def completion_aspect\n true_value = \"Completed\"\n false_value = \"Incomplete\"\n self.complete ? true_value : false_value\n end",
"def incomplete?\n !completed\n end",
"def completed?\n return @complete\n end",
"def completed?\n return @complete\n end",
"def complete?\n status == \"Completed\"\n end",
"def completed?\n self.state == :completed\n end",
"def finished?\n @round_counter >= @croupier.rules[:rounds]\n end",
"def completed?\n contact_completed? && company_completed? && finance_completed?\n end",
"def finished? participate\n duration = Challenge.find(participate.challenge_id).duration\n return participate.continuous_check_in == duration\nend",
"def completed?\n self.status_sym == :completed\n end",
"def complete?\n\tstatus == \"Completed\"\n end",
"def completed?\n self.completed_at.present?\n end",
"def complete?\n !! completed_at\n end",
"def complete?\r\n @is_complete\r\n end",
"def tally\n\t\t\treturn if completed?\n\t\t\tcomplete if consensus?\n\t\tend",
"def completed?(chapter)\n chapters_completed.include? chapter\n end",
"def finished?\n self.round_count > 0\n end",
"def isFinished\n progressValue.isEqualToNumber(numberOfSteps)\n end",
"def completed?\n @progress != 'PENDING'\n end",
"def education_selection_status\n percent = 0\n step = 25\n percent += step unless university.nil?\n percent += step unless faculty.nil?\n percent += step if main_course_scenario.programs.size > 0\n percent += step if completed_courses.size > 0 or main_course_scenario.taking_courses.size > 0\n percent\n end",
"def is_experiment_completed?(experiment) # rubocop:todo Naming/PredicateName\n !!VanityExperiment.retrieve(experiment).completed_at\n end",
"def check_if_completed(user)\n\n \tlogger.info(\"Checking completion for workout \" + id.to_s + \" by user \" + user.name.to_s)\n\n \tif complete?(user) # If a CompletedWorkout exists already, no further action\n \t\tlogger.info(\"Already completed\")\n \t\treturn false\n elsif self.workout_exercises.map {|we| we.complete?(user)}.reduce {|x,y| x && y} # Check if all exercises are complete (e.g. all return true)\n \t\tlogger.info(\"Completed! Creating new CompletedWorkout\")\n \t\tCompletedWorkout.create!(:user => user, :workout => self, :complete_time => Time.current)\n \t\treturn true\n else\n\t \tlogger.info(\"Not yet completed\")\n\t \treturn false\n \tend\n end",
"def pedia_complete?\n return status == COMPLETE\n end",
"def completed?\n !self.finished_at.nil?\n end",
"def finished?\n self.completed? || self.failed?\n end",
"def completed?\n job_completed?\n end",
"def completed?\n \t\tlatest_transaction.completed? unless transactions.empty?\n \tend",
"def completed?(step_name)\n status_flag = published? || false\n unless published?\n step_index = HYDRANT_STEPS.index(step_name)\n current_index = HYDRANT_STEPS.index(step_name)\n last_index = HYDRANT_STEPS.index(last_completed_step.first)\n unless (current_index.nil? or last_index.nil?)\n status_flag = (last_index >= current_index)\n end\n end\n status_flag\n end",
"def completed?\n\t\t\treturn request_status == REQUEST_STATUS['completed']\n\t\tend",
"def finished?\n\tfinished_on.present? \n\tend",
"def complete?\n self.status == STATUS[:complete] \n #self.status == 1\n end",
"def completed?\n !self.shift_jobs.empty?\n end",
"def completed()\n @completed=true\n @tCompleted=Time.now\n end",
"def incomplete?\n attributes['percentDone'] < 1\n end",
"def completed\n proptime 'COMPLETED'\n end",
"def completed? # Is task completed? method\n completed_status # True or false\n end",
"def finished?\n @step == @total_steps + 1\n end",
"def completed?\n num_recommendations = recommendations.size\n num_users = users.size\n num_confirmed_recommendations = recommendation_statuses.size\n\n num_users * num_recommendations == num_confirmed_recommendations\n end",
"def new_expert?\n project_tasks.where(status: 'finished').count <= 1\n end",
"def profile_completed?\n return true if self.for_testing?\n !self.skills.blank? and !self.bio.blank?\n end",
"def step_completed?\n !object.waiting_on.include?(scope)\n end",
"def complete?\n @complete\n end",
"def completed\n\t\t\t\tif read_attribute(:completed) && read_attribute(:completed) > 0\n\t\t\t\tTime.at(read_attribute(:completed)).to_date\n\t\t\t\telse\n\t\t\t\tnil\n\t\t\t\tend\n\t\t\tend",
"def complete?\n complete == true\n end",
"def completed?\n self.status == STATUS_COMPLETED\n end",
"def completed?(step)\n case step\n when :begin\n true\n when :waiver\n @player.signed_waiver?\n when :squad\n @player.joined_squad?\n when :off_campus\n !@player.off_campus.nil?\n when :confirm\n true\n when :done\n @player.registered == true\n end\n end",
"def completed?(step_name)\n status_flag = self.published || false\n\n unless self.published\n current_index = HYDRANT_STEPS.index(step_name)\n last_index = HYDRANT_STEPS.index(current_step)\n \n unless (current_index.nil? or last_index.nil?)\n status_flag = (last_index >= current_index)\n end\n end\n \n status_flag\n end",
"def complete!\n self.update_attribute(:is_completed, true)\n # TODO: send an email to teacher about taks completion\n end",
"def finished?\n\t\tfinished_on.present?\n\tend",
"def finished?\n\t\tfinished_on.present?\n\tend",
"def any_requested_booking_completed?\n count = 0\n index\n @requested_bookings.each { |booking| count += 1 if booking.completed }\n true if count.positive?\n end",
"def complete?\n @complete\n end",
"def continues?\n year > specialization.study_length\n end",
"def completed?\n user.likes_count >= self.class.config.likes_needed_for_completion\n end",
"def complete?\n end",
"def complete?\n self.complete\n end",
"def finished?\n game && game.count { |h| h[:finished] == true && h[:final] } == 6\n end"
] |
[
"0.7369519",
"0.73497653",
"0.72654337",
"0.72654337",
"0.7237391",
"0.7233562",
"0.7189574",
"0.71696645",
"0.71528494",
"0.71528375",
"0.7105793",
"0.7067047",
"0.7036601",
"0.69687784",
"0.69624245",
"0.69539607",
"0.69492173",
"0.6939414",
"0.6907739",
"0.6864672",
"0.6863269",
"0.68528056",
"0.6832862",
"0.6824893",
"0.6824253",
"0.68118817",
"0.68107367",
"0.68107367",
"0.6803759",
"0.6764566",
"0.676254",
"0.67598593",
"0.6745819",
"0.67432797",
"0.6727094",
"0.6708506",
"0.6708506",
"0.67036366",
"0.6701105",
"0.66656315",
"0.6664263",
"0.66374165",
"0.66259944",
"0.66182",
"0.66097337",
"0.6606356",
"0.6606356",
"0.6597932",
"0.6590599",
"0.65851015",
"0.6564541",
"0.6560765",
"0.6547058",
"0.65348345",
"0.65236944",
"0.65218556",
"0.651364",
"0.6510989",
"0.6509297",
"0.650231",
"0.6493787",
"0.64789224",
"0.6470857",
"0.6434425",
"0.6432998",
"0.6427719",
"0.6426748",
"0.64213276",
"0.6420561",
"0.64146084",
"0.6406603",
"0.64011365",
"0.6399738",
"0.6398498",
"0.6392007",
"0.63914573",
"0.63843435",
"0.63701",
"0.63698554",
"0.63334656",
"0.6332834",
"0.63273984",
"0.6317869",
"0.6315841",
"0.63142616",
"0.6311398",
"0.630959",
"0.63041395",
"0.63029313",
"0.6296165",
"0.62918365",
"0.628727",
"0.628727",
"0.6281462",
"0.62798786",
"0.6277941",
"0.6273962",
"0.62729037",
"0.6266035",
"0.6259012"
] |
0.7348603
|
2
|
set role to student prior to initial registration
|
def ensure_there_is_a_role
if role.blank?
self.role = "student"
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def set_default_role\n self.role ||= :student\n end",
"def set_default_role\n self.role ||= :student\n end",
"def set_role\n return if role?\n\n self.role = 'regular'\n end",
"def assign_role\n self.role = Role.find_by name: \"Regular\" if self.role.nil?\n end",
"def set_initial_role\n self.role ||= :standard # defining the initial / default role \n end",
"def set_role\n @role = role\n end",
"def set_role\n self.role ||= 'standard'\n end",
"def assign_role\n self.role = Role.find_by name: \"Aanvrager\" if self.role.nil?\n end",
"def setup_role\n if self.role_ids.empty?\n self.role_ids = [2]\n end\n end",
"def assign_role\n #self.role = Role.find_by name: '訪客' if self.role.nil?\n self.role = Role.find_by name: 'Guest' if self.role.nil?\n end",
"def setup_role\n if self.role_ids.empty?\n self.role_ids = [2]\n end\n end",
"def set_role\n self.role = 'developer'\n end",
"def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end",
"def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end",
"def setup_role \n if self.role_ids.empty? \n self.role_ids = [2] \n end\n end",
"def set_valid_role\n\t\treturn unless self.role.nil?\n\t\tguest_role = Role.find_by(name: 'Guest')\n\t\tif guest_role.nil?\n\t\t\tRole.create!(name: 'Guest')\n\t\t\tguest_role = Role.find_by(name: 'Guest')\n\t\tend\n\t\tself.role = guest_role\n end",
"def check_for_role\n\t\tself.role = ROLES[:user] if !self.role.present?\n\tend",
"def setup_role\n \tif self.role_ids.empty?\n \t self.role_ids = [3]\n \tend\n end",
"def set_student\n @student = current_user\n end",
"def setup_role\n #get_statuses(@role)\n #set_default_status(@role)\n end",
"def set_default_role\n \tself.role ||= :normal\n end",
"def must_be_student\n unless current_user.role.name.eql?('Student')\n flash[:error] = \"Access denied.\"\n redirect_to root_url\n end\n end",
"def assign_role\n \tdefault_role = Role.where(name: 'LeadGenerator').last\n \t self.role_id = default_role.id if self.role_id.blank? && default_role.present?\t\t\t\n end",
"def assign_role\n self.role = Role.find_by name: \"Survivor\" if self.role.nil?\n end",
"def setup_role\n if self.role_ids.empty?\n self.role_ids = self.roles.find_by_name(:registered).id\n end\n end",
"def setup_role \n if self.role_ids.empty? \n self.role_ids = [Role.find_by_name(\"User\").id] \n end\n end",
"def assign_role\n self.add_role!(\"user\")\n end",
"def check_for_role\n\t\tself.role = ROLES[:user] if self.role.nil?\n\tend",
"def set_role(role, user)\n\t\tprivs = privileges(user)\n\t\tunless privs[:edit]\n\t\t\traise TinyException, TinyException::MESSAGES[TinyException::NOPRIVILEGES]\n\t\tend\n\t\t\n\t\tcase role\n\t\twhen \"student\"\n\t update_attribute(:role, Enrollment::ROLE_STUDENT)\n\t when \"instructor\"\n\t update_attribute(:role, Enrollment::ROLE_INSTRUCTOR)\n\t end\n\tend",
"def assign_default_role\n self.add_role(:newuser) if self.roles.blank?\n end",
"def assign_default_role\n self.add_role(:newuser) if self.roles.blank?\n end",
"def check_for_role\n self.role = ROLES[:user] if self.role.nil?\n end",
"def assign_role\n if self.organization\n self.add_role :organization if self.roles.blank?\n else\n self.add_role :standard if self.roles.blank?\n end\n end",
"def assign_role\n\t\tself.role = Role.find_by role_name: \"PIC Pengadaan\" if self.role.nil?\n\tend",
"def set_default_role\n if self.admin?\n self.admin!\n else\n self.writer!\n end\n end",
"def update_user\n @user = @user || student.user || student.build_user\n @user.update_attribute(:login, loginname)\n @user.roles << Role.find_by_name('student') unless @user.has_role?(\"student\")\n self.update_attribute(:status, 'S')\n end",
"def set_default_role\n update_attribute :roles, [UserRoles::CUSTOMER] if roles.empty?\n end",
"def set_default_role\n self.roles = [Role.find_by_name('user')]\n end",
"def set_urole\n begin\n #@client.sobject_module = Salesforce #Using Salesforce Name, to avoid collision with my 'Order' Object in MongoDB.\n if self.user_role.nil?\n #self.user_role = UserRole.where(name: \"regular\").first\n self.user_role_id = Urole.where(name: \"regular\").first.id\n logger.info \"Setting this user '#{self.email}' to use 'regular' role @ #{Time.now}.\"\n else\n logger.info \"User '#{self.email}' is using '#{self.user_role.name}' role @ #{Time.now}.\"\n end\n rescue Exception => e\n logger.info 'Your DB has not been seeded. Please seed it first. ' + e.message\n end\n end",
"def validates_role\n self.role = Role.find_by_name \"Technician\" if self.role.nil?\n end",
"def set_default_role\n self.role ||= :user\n end",
"def set_default_role\n self.role ||= :user\n end",
"def set_default_role\n self.role ||= :user\n end",
"def set_default_role\n self.role ||= :user\n end",
"def set_default_role\n self.role ||= :standard\n end",
"def set_required_role\n @required_role = RequiredRole.find(params[:id])\n end",
"def create\n super do\n resource.role_id = 1\n resource.save\n end\n end",
"def set_default_role\n\n\t\tself.role ||= :user\n\n\tend",
"def set_default_role\n self.role ||= :user\n end",
"def set_role\n role = Spree::Role.find_by name:\"user\"\n self.spree_roles << role\n end",
"def set_default_role\n self.role ||= Role.find_by_name('user')\n end",
"def set_role\n @role = Role.find_by_actor_id_and_project_id(current_actor.id, @project.id)\n if @role\n @role_level = (RoleLevel.find(@role.role_level_id)).name\n else\n @role_level = ''\n end\n end",
"def role= new_role\n @role = String new_role\n end",
"def set_student\n @student = Student.find(params[:id])\n authorize @student\n end",
"def set_default_role\n add_role :user\n end",
"def set_role\n @role = Role.find_by_actor_id_and_project_id(current_actor.id, @project.id)\n end",
"def default_role\n self.role_id = Role.user.id\n end",
"def default_role\n\t\t\tself.roles << Role.find_by_name(\"ong\")\n\t\t\tself.save\n\t\tend",
"def new_user\n if self.role_id.nil?\n self.role_id = 3\n end\n end",
"def new_user\n if self.role_id.nil?\n self.role_id = 3\n end\n end",
"def student?\n @student = true if session[:role_name] == 'Student'\n end",
"def add_pending_role\n self.user.add_role :teacher\n self.user.role_pending = true\n self.user.save\n end",
"def is_student?\n self.role==\"student\"\n end",
"def assign_role(user, role_name)\n role = Role.find_by_name role_name\n user.role = role\n user.save!\nend",
"def assign_default_role\n if self.roles.blank?\n self.add_role :Cursist\n end\n end",
"def set_defaults\n\t\tself.email = self.users.first.email if ['student','school_admin','admin'].include? self.role\n\t\tself.uuid = SecureRandom::uuid()\n\t\tself.active = true\n\tend",
"def set_role role\n set_ds_field role.to_s\n end",
"def before_update\n r = Role.find(self.id)\n if r.role_name == 'Administrator' then\n if r.role_name != self.role_name then\n errors.add(:role_name, \"Administrator darf nicht umbenannt werden\")\n self.role_name = r.role_name\n end\n end\n if r.role_name == 'Gast' then\n if r.role_name != self.role_name then\n errors.add(:role_name, \"Gast darf nicht umbenannt werden\")\n self.role_name = r.role_name\n end\n end \n end",
"def role=(value)\n @role = value\n end",
"def set_default_role\n if User.count == 0\n self.global_role = GlobalRole.administrator\n else\n self.global_role = GlobalRole.regular_user\n end\n end",
"def set_default_role\n if User.count == 0\n self.role ||= :admin\n else\n self.role ||= :user\n end\n end",
"def required_student\n require_user_type(:student)\n end",
"def init\n self.role ||= \"standard\" #will set the default value only if it's nil\n end",
"def set_default_role!\n clear!\n end",
"def set_default_role!\n clear!\n end",
"def set_default_role!\n clear!\n end",
"def assign_role\n UserRole.create!(user_id: self.id, role_id: 3)\n end",
"def set_student\n @student = Student.find(current_student.id)\n end",
"def after_create\n super\n check_roles\n end",
"def set_role(role, agency)\n if !agency && !role\n raise \"Expecting values for role and agency\"\n end\n # Add role with an agency if applicable\n if role == \"superuser\"\n self.add_role(role)\n elsif agency == \"\"|| agency.nil?\n self.add_role(role)\n elsif staff_agency.nil?\n self.add_role(role,agency)\n elsif agency\n self.remove_role(self.roles.last.name.to_sym)\n self.add_role(role,agency)\n end\n end",
"def set_as_admin\n self.role = USER_ROLES[:admin]\n end",
"def set_admin_student\n @student = Student.find(params[:id])\n end",
"def set_role\n new_role = params[:role]\n return render(nothing: true, status: :unauthorized) if new_role == 'superuser' && current_user.role != 'superuser'\n\n @user.role = new_role\n @user.save!\n respond_to do |format|\n format.js\n end\n end",
"def require_student\n redirect_to root_path unless @auth_user && @auth_user.type == 'Student'\n end",
"def student?\n self.role == \"student\"\n end",
"def switch_role(student_action, tutor_action)\n case @prop[:role]\n when \"student\"\n student_action\n when \"Tutor\"\n tutor_action\n else\n puts 'You have selected an invalid option'\n end \n end",
"def set_default_role\n if User.count == 0\n self.global_role = GlobalRole.administrator\n elsif self.global_role.nil?\n self.global_role = GlobalRole.regular_user\n end\n end",
"def set_default_role\n self.add_role :merchant\n end",
"def add_role\n person\n end",
"def assignrole(role)\n roles << role unless roles.exists?(role)\n end",
"def set_Role(value)\n set_input(\"Role\", value)\n end",
"def set_Role(value)\n set_input(\"Role\", value)\n end",
"def set_student_user\n @id=params[:id]\n if((session[:register].to_s == @id.to_s || session[:student_current_user].to_s == @id.to_s) || \n session[:admin_current_user] != nil)\n @student_user = StudentUser.find(params[:id])\n else\n redirect_to \"/registration_home/index\"\n end\n end",
"def set_student\n @student = Student.find(session[:student_id])\n end",
"def set_user_role(role)\n role_id = Role.where(role_type: role).first.id\n self.update_attributes(role_id: role_id) \n end",
"def set_ministerial_role\n @ministerial_role = MinisterialRole.find(params[:id])\n end",
"def set_current_user\n @current_user = current_student || current_admin\n end",
"def enroll\n\t\traise \"Invalid role!\" unless current_user.role_student?\n\n\t\t# We *shouldn't* get here if we already have requests, but just in case - DESTROY THEM\n\t\t@seminar.seminar_students.for_student_user(current_user).each{|x| x.destroy} \n\n\t\t@enrollment = @seminar.seminar_students.create!(:student_user => current_user, :student_confirmed => true)\n\t\tflash[:notice] = \"Enrollment requested\"\n\t\tredirect_to @seminar\n\tend",
"def add_default_role \n\t\tempty_role_id = self.company.roles.find_by_designation(\"none\").id\n\t\tif self.employees.any? \n\t\t\tself.employees.each do |x| \n\t\t\t\tx.skip_password_validation = true\n\t\t\t\tx.update(role_id: empty_role_id)\n\t\t\tend\n\t\tend\n\tend",
"def set_roles\n roles << Role.user unless has_role?(\"user\")\n as_seller! if @registration_as_seller.to_i == 1\n end"
] |
[
"0.76837623",
"0.76837623",
"0.7334064",
"0.72828394",
"0.7263591",
"0.7050061",
"0.70451283",
"0.70170414",
"0.694737",
"0.6940768",
"0.6921373",
"0.692065",
"0.691259",
"0.691259",
"0.691259",
"0.6871036",
"0.68561524",
"0.685213",
"0.68275684",
"0.6790663",
"0.6779628",
"0.6770219",
"0.67469096",
"0.6731527",
"0.671937",
"0.6717399",
"0.67169875",
"0.670642",
"0.6692663",
"0.66625357",
"0.66625357",
"0.6657779",
"0.66525465",
"0.6641629",
"0.6618301",
"0.66076124",
"0.65945065",
"0.6587124",
"0.6565708",
"0.6564665",
"0.656434",
"0.656434",
"0.656434",
"0.656434",
"0.6559557",
"0.6547093",
"0.65143937",
"0.6505142",
"0.646925",
"0.64649886",
"0.6442869",
"0.6427265",
"0.6413806",
"0.64085007",
"0.6390186",
"0.63807607",
"0.63756776",
"0.6357844",
"0.6353003",
"0.6353003",
"0.63286877",
"0.6325127",
"0.6319897",
"0.63128364",
"0.6312566",
"0.6311366",
"0.63058704",
"0.62971896",
"0.6294417",
"0.62876034",
"0.62563986",
"0.6248109",
"0.62462497",
"0.6244222",
"0.6244222",
"0.6244222",
"0.6236176",
"0.6225603",
"0.6222746",
"0.6217434",
"0.6213338",
"0.6213051",
"0.62001145",
"0.61910695",
"0.61808294",
"0.61792123",
"0.61789197",
"0.6164501",
"0.6160221",
"0.6158192",
"0.6145913",
"0.6145913",
"0.61456126",
"0.6142584",
"0.61397344",
"0.6135413",
"0.61318326",
"0.61225975",
"0.6116893",
"0.6114721"
] |
0.81538695
|
0
|
Display current user profile
|
def my_profile
render json: { user: current_user}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def profile\n @user = @current_user\n\n render :show\n\n end",
"def profile\n\t\t\n\t\tif !current_user\n\t\t\tredirect_to root_url and return\n\t\tend\n\t\t\n\t\t@user = current_user\n\t\t\n\tend",
"def profile\n\t\t@user = User.find(current_user)\n\tend",
"def profile\n\t@user = current_user\n\t@title = \"This is your profile page\"\n end",
"def profile\n\t\t@user = current_user\n\tend",
"def show\n if current_user.is_normal?\n @user = User.find( params[:id] )\n render :profile\n else\n redirect_to user_profile_path\n end\n end",
"def profile\n @user = current_user\n end",
"def show\n\n\t\t@current_profile = Profile.get_profile params[:id], \"asdf\"\n\n\t\tpretty_render \"api/public_user\"\t\n\n\tend",
"def show\n if current_user\n @user = User.find(params[:id])\n @user = current_user\n render :show\n else\n flash[:error] = \"Must be signed in to see your profile!!\"\n redirect_to \"/\"\n end\n end",
"def show\n @profile = @user.profile\n end",
"def profile\n @profile = current_user\n end",
"def show\n @user = User.find(params[:id])\n if $current_user.nil? or $current_user.id != @user.id\n redirect_to signin_path\n else\n @title = \"#{@user.userName}'s profile\"\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user }\n end\n end\n end",
"def show\n op = present User::Show\n redirect_to edit_user_profile_path(current_user, op.model.profile) && return if op.new_profile?\n redirect_to user_profile_path(current_user, op.model.profile)\n end",
"def profile\n if(current_user)\n render 'layouts/loggedin'\n else\n render \"layouts/guest\"\n end\n end",
"def show\n @profile = Profile.find(params[:id]) || current_user.profile\n end",
"def profile_edit\n @user = User.find(current_user.id)\n end",
"def show\n @profile = current_user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def show\n @profile = Profile.find(:first, :conditions => {:user_id => params[:user_id]})\n end",
"def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end",
"def show_current\n user = current_user\n profile = Profile.find_by user_id: user.id\n\n render json: profile\n end",
"def show_current_user_profile\n @user = User.find(params[:id])\n render json: @user\n end",
"def user_profile\n @current_user = current_user\n\n if params[:id] == 'me'\n @user = @current_user\n else\n @user = User.find_by_id(params[:id])\n end\n end",
"def show\n @user = User.find(current_user.id)\n end",
"def show\n\t\t@user = current_user\n\tend",
"def user_information\n @current_user = current_user\n\n render :partial => 'home/user_info'\n end",
"def profile\n if !GraderConfiguration['system.user_setting_enabled']\n redirect_to :controller => 'main', :action => 'list'\n else\n @user = current_user;\n end\n end",
"def index\n @profiles = current_user\n end",
"def show\n\n if @user.id == current_user.id\n add_breadcrumb \"My Profile\"\n else\n add_breadcrumb @user.name\n end\n\n # get the @prev_record_path and @next_record_path view vars\n get_next_and_prev_object_keys(@user, INDEX_KEY_LIST_VAR)\n @prev_record_path = @prev_record_key.nil? ? \"#\" : user_path(@prev_record_key)\n @next_record_path = @next_record_key.nil? ? \"#\" : user_path(@next_record_key)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @user }\n end\n end",
"def profile\r\n if params[:id] && User.exists?(params[:id])\r\n @prof = User.find(params[:id])\r\n else\r\n redirect_to_info_page t(:redir)\r\n return\r\n end\r\n end",
"def show_current_user\n return \"\" unless logged_in?\n \"User: #{current_user.display_name} - (#{current_user.role.display_name})\"\n end",
"def show\n @user = User.find(params[:id]) \n @user_me = retrieve_authenticated_user\n end",
"def show\n user = load_user\n expose user, serializer: UserProfileSerializer\n end",
"def show\n @user_picture = @user.profile_image.expiring_url(3600, :square)\n @bookmarks = @user.bookmarks\n @enrollments = @user.courses\n @enrollments_visible = @user.course_enrollments_visible_for_user(current_user)\n @completions_visible = @user.course_results_visible_for_user(current_user)\n end",
"def profile\n @user = User.find(params[:id])\n end",
"def show\n unless params[:id].blank?\n @user = User.find_by_id(params[:id])\n else\n if logged_in?\n @user = current_user\n else\n require_login and return\n end\n end\n \n if @user.blank?\n flash[:error] = \"User not found\"\n redirect_to root_path and return\n end\n\n @own_profile = (logged_in? && (@user.id == current_user.id))\n\n @page_title = @own_profile ? \"My profile\" : \"View profile\"\n\n @memberships = @user.liga_users.approved.map(&:league)\n end",
"def profile\n \t@user = UsersService.findUserById(params[:id])\n end",
"def profile\n\t\t# determine which user's profile page\n\t\t@user = User.find_by_login(params[:username])\n\t\t# retrieve all bids by this user\n\t @bids = Bid.find_all_by_bidder_id(@user.id, :group => 'item_id')\n\t\t# get all comments for this user\n\t @comments = @user.user_comments\n\t\t# get all user_items by this user\n\t @user_items = @user.posted_items\n\n\t\t# code for facebox\n\t respond_to do |format|\n\t\t\tformat.html\n format.js { render_to_facebox }\n end\n\tend",
"def show\r\n jump_to(\"/profiles/#{session[:account_id]}/basic\")\r\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @user = current_user\n end",
"def show\n @profile = current_user.profile\n\n # ToDo: error message if no profile is found for user\n\n puts 'Got profile='\n pp @profile\n \n\n puts 'got other_names='\n pp @profile.other_names\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @profile }\n format.json { render :json => @profile }\n end\n \n end",
"def show\n if user_signed_in?\n @user = User.find(current_user.id)\n end\n end",
"def show\n @me = current_user\n end",
"def show\n # @profile = Profile.find(params[:id])\n redirect_to user_page_url(@profile.user)\n end",
"def show\n @user=current_user\n end",
"def show\n unless @user==User.find(params[:id])\n flash[:notice]= \"You can only see your own profile.\"\n redirect_to root_path\n end\n @user=User.find(params[:id])\n end",
"def show()\n @authentication = Authentication.find(params[:id])\n\n if @authentication.provider == \"facebook\"\n me = FbGraph::User.me(@authentication.token).fetch\n current_user.fname = me.name.split.first\n current_user.lname = me.name.split.last\n current_user.email = me.email\n current_user.gender = me.gender\n birthday = me.birthday\n current_user.birthday = Chronic.parse(birthday) if birthday\n\n location = me.location\n current_user.location = location if location and location.is_a? String\n current_user.location = location.try(:[], :name) if location and location.is_a? Hash\n pictureurl = me.picture+'?type=large'\n begin\n tempfile = Tempfile.new(['', '.jpg'])\n open(tempfile.path, 'wb') do |file|\n file << open(URI.parse(pictureurl)).read\n end\n current_user.avatar = tempfile\n rescue\n end\n end\n\n current_user.save\n redirect_to edit_user_path\n end",
"def profile\n @user = current_user_with_auths\n @connected = @user.authorizations.collect{|a| a.provider}\n @to_connect = providers - @connected\n unless @user\n redirect_to root_path, :notice => \"Sorry, try logging back in\"\n end\n end",
"def show\n user = User.find(current_user.username)\n redirect_to user_path(user)\n end",
"def profile\n @user = UserService.getUserById(params[:id])\n end",
"def profile\n @presenter = Users::ProfilePresenter.new(current_user.id)\n @message = Message.new\n end",
"def show\n if params[:id]\n @user = User.find(params[:id])\n else\n @user = current_user\n end\n \n if @user == current_user\n render :show_full\n else\n render :show\n end\n end",
"def profile\n render json: @current_user\n end",
"def show\n @users = User.all\n @user = current_user\n end",
"def show\n @flag = @profile.country_code + \" flag\" unless @profile.country_code.nil?\n\n if @profile.user_id == current_user.id\n @title = \"My Profile Card\"\n else\n @title = \"#{@profile.nickname}'s Profile Card\"\n end\n end",
"def show\n # @u = current_user\n end",
"def edit_profile\n \t@user = current_user\n end",
"def show\n @profile = current_user\n @projects = Project.all \n @user = current_user\n end",
"def show\n #@user=current_user\n end",
"def show\n\n @user = User.get(params[:id])\n \n if signed_in? && @user.id == current_user.id\n @menu = \"home\"\n @board = \"user\"\n @section = \"show\"\n \n render 'user'\n else\n redirect_to '/'\n end\n end",
"def go_to_profile\n\t\tif login?\n\t\t\t#Queries the database for the handle and id of all users that are followed by the session user by \n\t\t\t#performing a join between the relationships and users tables.\n\t\t\t@followees = Relationship.find_followees(userid)\n\t\t\terb :profile\n\t\telse\n\t\t\terb :login\n\t\tend\n\tend",
"def show\n redirect_to(default_url) unless logged_in? || User.count > 0\n @user = current_user\n end",
"def show\n set_user\n end",
"def display_name\n self.display_name = self.profile.nickname? ? self.profile.nickname : self.username\n end",
"def profile\n @shop = Shop.find(1)\n render :template => 'facebook/profile.erb', :layout => false\n return\n end",
"def small_profile\n\t\t# determine which user's profile page\n \t@user = User.find_by_login(params[:username])\n\t\t# get all comments for this user\n\t @comments = @user.user_comments\n\t\t# get all user_items by this user\n\t @user_items = current_user.user_items\n\t\trespond_to do |format|\n\t\t\tformat.html\n format.js { render_to_facebox }\n end\n\tend",
"def show\n @page_title = 'Profile for ' + @person.full_name\n end",
"def show\n @profile = @user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def show\n @user = get_user\n end",
"def show\n \tif(params[:id])\n \t\t @profile = Profile.find(params[:id])\n \telse\n \t\t@profile = Profile.find_by_user_id(current_user.id)\n \tend\n # authorize! :show, @profile\n\n add_breadcrumb @profile.first_name + \" \" + @profile.last_name, \"\"\n \n @recentposts = Post.where('user_id = ?', @profile.user.id).order('id desc')\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def profile\n \n end",
"def show\n @title = \"#{@profile.forenames} #{@profile.surnames}\"\n end",
"def show\n {\n id: @current_user.id,\n first_name: @current_user.first_name,\n last_name: @current_user.last_name,\n email: @current_user.email,\n role_name: @current_user.super_admin ? 'Super Admin' : @current_user.role.try(:name),\n permissions: Permissions::Builder.user_permissions(@current_user)\n }\n end",
"def show\n @user = User.find(params[:id])\n\n if @user.state != 'active' or @user.login == 'admin'\n return redirect_to users_path\n end\n \n @page_ancestors = [{:name=>'Community', :url=> users_path}]\n @bc_title = 'User Profile'\n \n respond_to do |format|\n format.html # show.html.erb\n format.iphone\n format.xml { render :xml => @user }\n end\n end",
"def set_users_profile\n @user = User.find(current_user)\n end",
"def show_user\n \tuser = User.where({:id => self.user_id}).first\n \tuser.name\n end",
"def show\n # @user = User.find(params[:id])\n @user = current_user\n end",
"def show\n @title = \"Perfil del Candidato: #{@profile.forenames} #{@profile.surnames}\"\n end",
"def show\n @my_accounts=@current_user\n\tend",
"def set_user\n @profile = User.find(current_user.id)\n end",
"def profile\n\n end",
"def set_profile\n if current_user.nil?\n redirect_to :home, notice: t( 'profiles.notice.pls_signon') \n else\n @person = Person.find( current_user.person_id )\n @user_id = current_user.id\n set_final_breadcrumb( action_name )\n end\n self.feature_help_file = :profile\n end",
"def display_name\n display_name = @current_profile.display_name\n end",
"def set_profile\n @profile = Profile.where(user_id: current_user).first\n end",
"def profile\n render_json 0,\"ok\",current_member.as_profile\n end",
"def show\n @user = User.find(params[:id])\n @links = Link.where(user_id: @user.id)\n @link = Link.new\n render :full_profile\n end"
] |
[
"0.8318606",
"0.8191088",
"0.81457615",
"0.8071622",
"0.79949397",
"0.79619086",
"0.7926748",
"0.7895707",
"0.7849802",
"0.7718731",
"0.7714287",
"0.7606168",
"0.75425965",
"0.75332993",
"0.7532596",
"0.7421233",
"0.7374534",
"0.7367124",
"0.73658246",
"0.7352173",
"0.73259485",
"0.73193496",
"0.7304348",
"0.7275446",
"0.7271447",
"0.7239708",
"0.72276926",
"0.7218275",
"0.7215238",
"0.72022396",
"0.71804935",
"0.7165475",
"0.7128297",
"0.71154106",
"0.7108081",
"0.7103256",
"0.7083577",
"0.7077783",
"0.7069321",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.706918",
"0.70682377",
"0.70646214",
"0.7064562",
"0.7057176",
"0.70564693",
"0.7052007",
"0.7043226",
"0.7026826",
"0.7021555",
"0.7019788",
"0.7009334",
"0.6999994",
"0.6986543",
"0.69690233",
"0.69583493",
"0.6953282",
"0.6939629",
"0.69293946",
"0.69269854",
"0.69079864",
"0.6898207",
"0.68954426",
"0.6888708",
"0.6883681",
"0.6882497",
"0.6879802",
"0.6878479",
"0.68739444",
"0.6871186",
"0.6866982",
"0.68657976",
"0.68638784",
"0.6860845",
"0.68499786",
"0.6846832",
"0.6834898",
"0.6834791",
"0.68281525",
"0.6827874",
"0.68242514",
"0.6818759",
"0.6811706",
"0.68058705",
"0.680398",
"0.67957485",
"0.6792033",
"0.6781225",
"0.6780559"
] |
0.0
|
-1
|
Display the users profile
|
def show
user = User.find_by(id: params[:id])
if user
render json: {status: 200, user: user}
else
render json: {status: 500, message: user.errors.full_messages}
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def profile\n @user = @current_user\n\n render :show\n\n end",
"def show\n\n\t\t@current_profile = Profile.get_profile params[:id], \"asdf\"\n\n\t\tpretty_render \"api/public_user\"\t\n\n\tend",
"def profile\n\t@user = current_user\n\t@title = \"This is your profile page\"\n end",
"def show\n if current_user.is_normal?\n @user = User.find( params[:id] )\n render :profile\n else\n redirect_to user_profile_path\n end\n end",
"def show\n @profile = @user.profile\n end",
"def profile\n\t\t\n\t\tif !current_user\n\t\t\tredirect_to root_url and return\n\t\tend\n\t\t\n\t\t@user = current_user\n\t\t\n\tend",
"def profile\n\t\t@user = User.find(current_user)\n\tend",
"def show\n op = present User::Show\n redirect_to edit_user_profile_path(current_user, op.model.profile) && return if op.new_profile?\n redirect_to user_profile_path(current_user, op.model.profile)\n end",
"def show\n if current_user\n @user = User.find(params[:id])\n @user = current_user\n render :show\n else\n flash[:error] = \"Must be signed in to see your profile!!\"\n redirect_to \"/\"\n end\n end",
"def show\n @profile = Profile.find(:first, :conditions => {:user_id => params[:user_id]})\n end",
"def profile\n\t\t# determine which user's profile page\n\t\t@user = User.find_by_login(params[:username])\n\t\t# retrieve all bids by this user\n\t @bids = Bid.find_all_by_bidder_id(@user.id, :group => 'item_id')\n\t\t# get all comments for this user\n\t @comments = @user.user_comments\n\t\t# get all user_items by this user\n\t @user_items = @user.posted_items\n\n\t\t# code for facebox\n\t respond_to do |format|\n\t\t\tformat.html\n format.js { render_to_facebox }\n end\n\tend",
"def profile\r\n if params[:id] && User.exists?(params[:id])\r\n @prof = User.find(params[:id])\r\n else\r\n redirect_to_info_page t(:redir)\r\n return\r\n end\r\n end",
"def profile\n \t@user = UsersService.findUserById(params[:id])\n end",
"def show\n unless params[:id].blank?\n @user = User.find_by_id(params[:id])\n else\n if logged_in?\n @user = current_user\n else\n require_login and return\n end\n end\n \n if @user.blank?\n flash[:error] = \"User not found\"\n redirect_to root_path and return\n end\n\n @own_profile = (logged_in? && (@user.id == current_user.id))\n\n @page_title = @own_profile ? \"My profile\" : \"View profile\"\n\n @memberships = @user.liga_users.approved.map(&:league)\n end",
"def show\n @title = \"#{@profile.forenames} #{@profile.surnames}\"\n end",
"def show\n @user = User.find(params[:id])\n if $current_user.nil? or $current_user.id != @user.id\n redirect_to signin_path\n else\n @title = \"#{@user.userName}'s profile\"\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user }\n end\n end\n end",
"def profile\n\t\t@user = current_user\n\tend",
"def profile\n check_auth :profile\n \n response = connection.post do |req|\n req.url '/user/profile'\n req.body = { :format => @format }\n end\n response.body[0]\n end",
"def show\n @user = User.find(params[:id])\n @links = Link.where(user_id: @user.id)\n @link = Link.new\n render :full_profile\n end",
"def profile\n @user = current_user\n end",
"def index\n @profiles = current_user\n end",
"def show\n @profile = current_user.profile\n\n # ToDo: error message if no profile is found for user\n\n puts 'Got profile='\n pp @profile\n \n\n puts 'got other_names='\n pp @profile.other_names\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @profile }\n format.json { render :json => @profile }\n end\n \n end",
"def small_profile\n\t\t# determine which user's profile page\n \t@user = User.find_by_login(params[:username])\n\t\t# get all comments for this user\n\t @comments = @user.user_comments\n\t\t# get all user_items by this user\n\t @user_items = current_user.user_items\n\t\trespond_to do |format|\n\t\t\tformat.html\n format.js { render_to_facebox }\n end\n\tend",
"def show\n @user_picture = @user.profile_image.expiring_url(3600, :square)\n @bookmarks = @user.bookmarks\n @enrollments = @user.courses\n @enrollments_visible = @user.course_enrollments_visible_for_user(current_user)\n @completions_visible = @user.course_results_visible_for_user(current_user)\n end",
"def show\n # @profile = Profile.find(params[:id])\n redirect_to user_page_url(@profile.user)\n end",
"def show\n @title = \"Perfil del Candidato: #{@profile.forenames} #{@profile.surnames}\"\n end",
"def show\n @profile = Profile.find(params[:id]) || current_user.profile\n end",
"def profile\n\t\t@user = User.where(username: params[:username])[0]\n\t\t@pics = Picture.where(user_id: @user.id).reverse\n\n\tend",
"def profile\n @user = User.find(params[:id])\n end",
"def profile\n @shop = Shop.find(1)\n render :template => 'facebook/profile.erb', :layout => false\n return\n end",
"def profile\n if(current_user)\n render 'layouts/loggedin'\n else\n render \"layouts/guest\"\n end\n end",
"def show\n @users = @business_profile.users\n end",
"def profile\n if !GraderConfiguration['system.user_setting_enabled']\n redirect_to :controller => 'main', :action => 'list'\n else\n @user = current_user;\n end\n end",
"def profile\n @profile = current_user\n end",
"def profile\n \n end",
"def show\n\n if @user.id == current_user.id\n add_breadcrumb \"My Profile\"\n else\n add_breadcrumb @user.name\n end\n\n # get the @prev_record_path and @next_record_path view vars\n get_next_and_prev_object_keys(@user, INDEX_KEY_LIST_VAR)\n @prev_record_path = @prev_record_key.nil? ? \"#\" : user_path(@prev_record_key)\n @next_record_path = @next_record_key.nil? ? \"#\" : user_path(@next_record_key)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @user }\n end\n end",
"def show\n @profile = current_user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def show\n user = load_user\n expose user, serializer: UserProfileSerializer\n end",
"def profile\n\n end",
"def profile\n @user = UserService.getUserById(params[:id])\n end",
"def show\n @user = User.find(params[:id])\n\n if @user.state != 'active' or @user.login == 'admin'\n return redirect_to users_path\n end\n \n @page_ancestors = [{:name=>'Community', :url=> users_path}]\n @bc_title = 'User Profile'\n \n respond_to do |format|\n format.html # show.html.erb\n format.iphone\n format.xml { render :xml => @user }\n end\n end",
"def show\n @page_title = 'Profile for ' + @person.full_name\n end",
"def show()\n @authentication = Authentication.find(params[:id])\n\n if @authentication.provider == \"facebook\"\n me = FbGraph::User.me(@authentication.token).fetch\n current_user.fname = me.name.split.first\n current_user.lname = me.name.split.last\n current_user.email = me.email\n current_user.gender = me.gender\n birthday = me.birthday\n current_user.birthday = Chronic.parse(birthday) if birthday\n\n location = me.location\n current_user.location = location if location and location.is_a? String\n current_user.location = location.try(:[], :name) if location and location.is_a? Hash\n pictureurl = me.picture+'?type=large'\n begin\n tempfile = Tempfile.new(['', '.jpg'])\n open(tempfile.path, 'wb') do |file|\n file << open(URI.parse(pictureurl)).read\n end\n current_user.avatar = tempfile\n rescue\n end\n end\n\n current_user.save\n redirect_to edit_user_path\n end",
"def manage_profile\n begin\n @has_link_access = true\n if @actor.is_fan? # in case of fan profile login\n @user = @actor\n @additional_info = current_user.additional_info\n get_user_associated_objects\n render :template =>\"/fan/manage_profile\" and return\n elsif @actor.is_artist? # in case of artist profile login\n @user = current_user\n @artist = @actor\n @artist_user = ArtistUser.for_user_and_artist(current_user, @artist).first || ArtistUser.new\n get_artist_objects_for_right_column(@artist)\n render :template =>\"/artist/edit\" and return\n elsif @actor.is_venue? # in case of venue profile login\n @user = current_user\n @venue = @actor\n @venue_user = VenueUser.for_user_and_venue(current_user, @venue).first || VenueUser.new\n get_venue_objects_for_right_column(@venue)\n render :template =>\"/venue/edit\" and return\n end\n rescue =>exp\n logger.error \"Error in User#ManageProfile :=> #{exp.message}\"\n render :nothing => true and return\n end\n respond_to do |format|\n format.js\n format.html\n end\n end",
"def index\n\n\t\t@user=current_user\n\n\t\t# We need to tell the view what to do with the profile\n\t\t# If a profile exists then display some profile information\n\t\t# If a profile doesn't exist then display a message saying to click the edit button to add a new profile\n\n\t\t# Does a valid profile exist on the user?\n\t\t@valid_profile = Profile.exists?(user_id: @user.id)\n\n\t\t# Valid profile exists\n\t\tif @valid_profile\n\n\t\t\t@user_profile = Profile.find_by(user_id: @user.id)\n\n\t\telse\n\n\t\t\t# No valid profile exists\n\t\t\t# The user can either create a new profile or request an existing one\n\t\t\t#@user_profile_requests = @user.profile_requests\n\n\t\t\t# if !current_user.profile_requests.approved(false).empty? %>\n\n\t\t\t# Create a list of user profile requests that are not set yet\n\t\t\t@user_profile_requests_not_set = @user.profile_requests.status_not_set\n\n\t\t\tif @user_profile_requests_not_set.blank?\n\n\t\t\t\t@available_profiles_collection = Profile.where(user_id: nil).order(:lastname)\n\n\t\t\tend\n\n\t\t\t# Create a list of user profile requests that are denied\n\t\t\t@user_profile_requests_denied = @user.profile_requests.status_denied\n\n\t\tend\n\n\n\n\n\tend",
"def show\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user_profile }\n end\n end",
"def show\n unless @user==User.find(params[:id])\n flash[:notice]= \"You can only see your own profile.\"\n redirect_to root_path\n end\n @user=User.find(params[:id])\n end",
"def show\n @profile = @user.profile\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def index\n @profiles = current_user.profiles\n end",
"def index\n @profiles = current_user.profiles\n end",
"def show\n \tif(params[:id])\n \t\t @profile = Profile.find(params[:id])\n \telse\n \t\t@profile = Profile.find_by_user_id(current_user.id)\n \tend\n # authorize! :show, @profile\n\n add_breadcrumb @profile.first_name + \" \" + @profile.last_name, \"\"\n \n @recentposts = Post.where('user_id = ?', @profile.user.id).order('id desc')\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @profile }\n end\n end",
"def profile_edit\n @user = User.find(current_user.id)\n end",
"def show\n \tif !logged_in?\n \t\tredirect_to :controller => :sessions, :action => :new, :return_to => request.request_uri\n \telse\n\t \tlogin = params[:login]\n\t \t@user = User.find_by_login(login)\n\t \t@user_stream = @user.profile_stream_short\n\t \t@user.images.highest_ranked.each do |i|\n\t \t\t@image = i.photo.url(:profile)\n\t\t\tend\t\t\t \t\n\t \t@cats = @user.cats.paginate :page => params[:page], :order => \"created_at desc\", :per_page => 30\n\t \t@user.profile ||= Profile.new\n\t \t@profile = @user.profile\n \tend\n end",
"def show\n totalPicture=Timeline.where(\"user_id=#{@user.id}\").count\n @user_info ={profileImage:\"#{@user.profileImage}\", totalPicture:\"#{totalPicture}\"}\n end",
"def go_to_profile\n\t\tif login?\n\t\t\t#Queries the database for the handle and id of all users that are followed by the session user by \n\t\t\t#performing a join between the relationships and users tables.\n\t\t\t@followees = Relationship.find_followees(userid)\n\t\t\terb :profile\n\t\telse\n\t\t\terb :login\n\t\tend\n\tend",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def profile\n end",
"def show\n render json: get_full_user_details(user), status: :ok\n rescue => e\n log_and_render_users_controller_error(e, \"get user details failed\")\n end",
"def get_user_profile_description\n get_profile_description(\"Users\")\n end",
"def show\n @users = User.all\n @user = current_user\n end",
"def profile(usernames)\n get(\"/1/users/show.json\", :users => [usernames].flatten).users\n end",
"def show\n @user = User.find_by_username(params[:username])\n if !@user.nil?\n @profile = @user.profile\n else\n redirect_to vendor_root_path\n end\n\n # byebug\n end",
"def show\n @user = User.find(params[:id])\n can_edit_hash = Permissions.currentLoggedInOrHasMorePermissions(@current_user,@user)\n @can_edit = can_edit_hash[:has_permission]\n\n #max needs\n @can_see_pref= Permissions.is_at_least_manager(@current_user)\n\n profile_attrs = [:first_name,:last_name, :email,:phone_number]\n @first_name = @user.first_name\n @last_name = @user.last_name\n @email = @user.email\n @phone_number = @user.phone_number\n @role = @user.role\n end",
"def show_user\n \tuser = User.where({:id => self.user_id}).first\n \tuser.name\n end",
"def show\n\t\trequire_login\n\t\t@user = User.find(params[:id])\n\t\t@socials = Social::Social_type\n\tend",
"def user_profile(id)\n users(request(\"users/profile/#{id}.xml\", :auth => true))\n end",
"def show\n drop_breadcrumb(\"用户管理\",users_path)\n drop_page_title(\"用户详情\")\n drop_breadcrumb\n end",
"def show\n @profile = current_user.profile\n @hash = Gmaps4rails.build_markers(@profile) do |profile, marker|\n marker.lat profile.latitude\n marker.lng profile.longitude\n marker.infowindow profile.first_name\n end\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def show\n @profile = Profile.find(params[:id])\n end",
"def profile\n @user = current_user_with_auths\n @connected = @user.authorizations.collect{|a| a.provider}\n @to_connect = providers - @connected\n unless @user\n redirect_to root_path, :notice => \"Sorry, try logging back in\"\n end\n end",
"def public\n @seeker = Seeker.find_by_id(params[:id])\n unless @seeker.nil?\n @title = @seeker.user.name.pluralize + \" Profile\"\n end\n end",
"def show\n\n @user = User.get(params[:id])\n \n if signed_in? && @user.id == current_user.id\n @menu = \"home\"\n @board = \"user\"\n @section = \"show\"\n \n render 'user'\n else\n redirect_to '/'\n end\n end",
"def show\r\n jump_to(\"/profiles/#{session[:account_id]}/basic\")\r\n end",
"def show\n\t\tif not user_signed_in? # if user is not signed in, they should not be allowed to view this page or be redirected\n\t \t\trespond_to do |format|\n\t \t\t\tformat.html { redirect_to root_url }\n\t \t\tend\n\t \t\treturn\n\t \tend\n\t \t\n\t \t@user_profile = Profile.where('id = ?',params[:profile_id]).first\n\t \tif @user_profile.nil? # if the current profile id does not exist, then cannot proceed; if not our profile, TODO: privacy settings\n\t \t\trespond_to do |format|\n\t \t\t\tformat.html { redirect_to root_url }\n\t \t\tend\n\t \t\treturn\n\t \tend\n\t \t\n\t \t@resume = Resume.where('id = ? AND profile_id = ?',params[:id],@user_profile.id).first # must check for nil! \t\n\t \tif @resume.nil?\n\t \tredirect_to profile_path(@user_profile.id) # for now, just go back the profile (eventually, if use index, can go back there like images does)\n\t end\n\tend",
"def show\n @flag = @profile.country_code + \" flag\" unless @profile.country_code.nil?\n\n if @profile.user_id == current_user.id\n @title = \"My Profile Card\"\n else\n @title = \"#{@profile.nickname}'s Profile Card\"\n end\n end",
"def show\n @user = User.find(params[:id])\n @tests = @user.tests.paginate(page: params[:page])\n add_breadcrumb \"Show Profile\", :user_path\n end",
"def show\n p params\n p \"just herer for checking\"\n #@profile = Profile.find(params[:id])\n @user = User.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @user }\n end\n end",
"def user\n\n \n @profile = Profile.find_by_user_id(params[:id])\n\n\nend",
"def profile\n @presenter = Users::ProfilePresenter.new(current_user.id)\n @message = Message.new\n end",
"def user_information\n @current_user = current_user\n\n render :partial => 'home/user_info'\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @user_profile }\n end\n end",
"def profile_show\n @user = User.find(current_user.id)\n\n $admin = User.where(\"admin = ? AND signed_in = ?\", true, true).first\n if $admin.nil?\n $admin = User.where(\"admin = ?\", true).first\n end\n $conversation = Conversation.between(current_user.id,$admin.id).first\n if $conversation.nil?\n $conversation = Conversation.create(sender_id: current_user.id, recipient_id: $admin.id)\n end\n gon.open = $conversation.open\n end",
"def show\n user = User.find(current_user.username)\n redirect_to user_path(user)\n end",
"def show_user_profile\n @user = User.find(username: params[:username])\n render json: @user\n end",
"def display_name\n self.display_name = self.profile.nickname? ? self.profile.nickname : self.username\n end",
"def show\n StatsManager::StatsD.time(Settings::StatsConstants.api['user']['show']) do\n if params[:id]\n unless @user = User.find(params[:id]) or @user = User.find_by_nickname(params[:id])\n return render_error(404, \"could not find that user\")\n end\n else\n return render_error(401, \"current user not authenticated\")\n end\n\n @user_personal_roll_subdomain = (@user.public_roll and @user.public_roll.subdomain)\n @status = 200\n end\n end",
"def profile\n \t\t@patient = Patient.all\n #@current_user = User.find(params[:id])\n end",
"def show\n\t\t@user = User.find(@project.creator)\n\t\t@total = ProjectsUser.where(project_id: @project.id).count\n\t\t@followers = User.select(\"users.id, users.name, users.email\").joins(\"JOIN projects_users ON projects_users.user_id = users.id\").where(\"projects_users.project_id = ?\", @project.id)\n end",
"def profile(username = nil, uid = nil)\n\n end",
"def show\n\t\t# Find all users with id passed by params.\n\t\t@user = User.find(params[:id])\n\t\tCUSTOM_LOGGER.info(\"Start to find users #{@user.to_yaml}\")\n\tend",
"def show\n set_user\n end",
"def index\n @personal_profiles =current_user.personal_profile\n end"
] |
[
"0.7887373",
"0.7818151",
"0.7782933",
"0.7772873",
"0.773372",
"0.7582773",
"0.75272965",
"0.7511028",
"0.7508242",
"0.74860704",
"0.74238795",
"0.7387908",
"0.7346951",
"0.73407084",
"0.7318082",
"0.73044443",
"0.7300331",
"0.72889876",
"0.72794",
"0.72725403",
"0.72640085",
"0.7255135",
"0.72438717",
"0.7243759",
"0.7227217",
"0.72249454",
"0.7218668",
"0.72183806",
"0.7207316",
"0.7205254",
"0.71823084",
"0.7165348",
"0.71597105",
"0.71464616",
"0.7145432",
"0.7137726",
"0.71326894",
"0.70947343",
"0.7082932",
"0.7073329",
"0.70595735",
"0.70384514",
"0.70320326",
"0.70306545",
"0.7016128",
"0.7007897",
"0.6993461",
"0.6985221",
"0.69843596",
"0.69843596",
"0.69840384",
"0.69768375",
"0.69748324",
"0.6974829",
"0.69710875",
"0.6971015",
"0.6971015",
"0.6971015",
"0.6971015",
"0.6971015",
"0.6971015",
"0.6967046",
"0.6960144",
"0.693502",
"0.69179165",
"0.6909114",
"0.68894386",
"0.68848264",
"0.6869567",
"0.6856826",
"0.6856481",
"0.6852044",
"0.6850678",
"0.6850678",
"0.6850678",
"0.6850678",
"0.6850678",
"0.6850678",
"0.68434745",
"0.6842013",
"0.68263054",
"0.68148977",
"0.6803598",
"0.6802836",
"0.6799539",
"0.67925256",
"0.6791855",
"0.67869616",
"0.678448",
"0.6778948",
"0.6778309",
"0.6778164",
"0.67692196",
"0.6768926",
"0.6763891",
"0.6750909",
"0.6749238",
"0.67405236",
"0.67400587",
"0.6739427",
"0.67341536"
] |
0.0
|
-1
|
Returns the current context for this thread, or nil if none exists.
|
def current
all_contexts[Thread.current.object_id]
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def context\n Thread.current[:ctx] ||= {}\n Thread.current[:ctx]\n end",
"def thread_context\n Thread.current[:runshell_context] ||= Context.new(main_context.to_h)\n end",
"def context\n Thread.current[NAME] ||= Hash.new\n end",
"def context\n self.current_custom_context || self.default_context\n end",
"def thread_context(tid)\r\n Ragweed::Wrap32::open_thread(tid) do |h|\r\n Ragweed::Wrap32::get_thread_context(h)\r\n end\r\n end",
"def context\n @context || (parent.context if parent)\n end",
"def context\n Thread.current[NAME] ||= Array.new\n end",
"def context\n @context_stack.last\n end",
"def context\n @_context ||= begin\n ptr = MemoryPointer::new( Context )\n error = OpenCL.clGetKernelInfo(self, CONTEXT, Context.size, ptr, nil)\n error_check(error)\n Context::new( ptr.read_pointer )\n end\n end",
"def context\n @_context ||= begin\n ptr = MemoryPointer::new( Context )\n error = OpenCL.clGetProgramInfo(self, CONTEXT, Context.size, ptr, nil)\n error_check(error)\n Context::new( ptr.read_pointer )\n end\n end",
"def local(thread = Thread.current)\n thread[@key] ||= Datadog::Context.new\n end",
"def context\n @context ||= Context.new(self)\n end",
"def context\n Context.instance\n end",
"def context\n @context ||= Context.new(self)\n end",
"def current_execution_context\n @current_execution_context || self.project.current_execution_cycle.id\n end",
"def context\n nil\n end",
"def get_thread_by_context(username, job_key, application_id, context = 'Interviews')\n $LOG.i \"running \" + __method__.to_s\n @client.get '/mc/v1/contexts/' + username + '/' + context + ':' + job_key + ':' + application_id\n end",
"def get_context\n @context_hash ||= {}\n end",
"def context_scope\n defined?(@_scope) ? @_scope : nil\n end",
"def runshell_context\n Thread.current == Thread.main ?\n main_context :\n thread_context\n end",
"def context(name = current_context)\n named_context(name)&.context\n end",
"def current\n LOOPS[Thread.current]\n end",
"def get_current_object\n if @current_object.nil?\n @parent.get_current_object\n else\n @current_object\n end\n end",
"def context\n unless @instance_context\n @instance_context = TaskContext.new(@version, @params['workspace_sid'], @params['sid'], )\n end\n @instance_context\n end",
"def context\n @parent&.context\n end",
"def context(worker_threads = 1)\n return @context if @context\n @context = ::ZMQ::Context.new(worker_threads)\n end",
"def context\n unless @instance_context\n @instance_context = CurrentCallContext.new(@version, )\n end\n @instance_context\n end",
"def this_context\n self\n end",
"def context\n ptr = FFI::MemoryPointer::new( Context )\n error = OpenCL.clGetKernelInfo(self, CONTEXT, Context.size, ptr, nil)\n error_check(error)\n return Context::new( ptr.read_pointer )\n end",
"def context\n Thread.current[\"#{@name}_dlogger_contexts\"] ||= []\n end",
"def context\n @context ||= {}\n end",
"def context\n @context ||= {}\n end",
"def main_context\n @main_context ||= Context.new\n end",
"def execution_context\n @context\n end",
"def caller\n Thread.current\n end",
"def caller\n Thread.current\n end",
"def mainContext\n # return Context.find( context )\n return context\n end",
"def context(args)\n context = args.delete(:context)\n context || @my\n end",
"def get_current_eoutvar\n Thread.current.instance_variable_get(:@current_eoutvar)\n end",
"def message_context_session\n session\n end",
"def current_context_for(*args)\n ::Fiveruns::Dash.sync { context_finder.call(*args) }\n end",
"def context\n @_context ||= {\n :argv => START_CTX[:argv].map { |arg| arg.dup },\n :cwd => START_CTX[:cwd].dup,\n 0 => START_CTX[0].dup,\n }.tap do |ctx|\n rewrite_context(ctx)\n end\n end",
"def context_or_context_view\n if @context.is_a?(UIViewController)\n @context.view\n else\n @context\n end\n end",
"def current_scope\n Thread.current[:webspicy_scope] || default_scope\n end",
"def current_context\n context = Validation::Context.current\n valid_context?(context) ? context : :default\n end",
"def context\n unless @instance_context\n @instance_context = TaskContext.new(@version , @params['workspace_sid'], @params['sid'])\n end\n @instance_context\n end",
"def context\n Zuul::Context.new context_type, context_id\n end",
"def get_view_context\n if defined?(controller) && controller.present?\n controller.view_context\n else\n ApplicationController.new.view_context\n end\n end",
"def current=(context)\n all_contexts[Thread.current.object_id] = context\n end",
"def current\n Thread.current.thread_variable_get(:reactor)\n end",
"def thread\n @primary_server ? @primary_server.thread : nil\n end",
"def get_current_scope\n get_current_hub&.current_scope\n end",
"def current_contexts\n if @current_contexts.blank?\n @current_contexts = ( self.section_context.present? ? self.section_context.split(',').map(&:to_sym) : inherited_contexts )\n end\n @current_contexts\n end",
"def context\n unless @instance_context\n @instance_context = CpsContext.new(@version, )\n end\n @instance_context\n end",
"def context(key = nil)\n current_context = key.nil? ? @context.local : @context.local(key)\n\n # Rebuild/reset context after a fork\n #\n # We don't want forked processes to copy and retransmit spans\n # that were generated from the parent process. Reset it such\n # that it acts like a distributed trace.\n current_context.after_fork! do\n current_context = self.context = current_context.fork_clone\n end\n\n current_context\n end",
"def incoming_context\n return @incoming_context\n end",
"def current\n Thread.current[:lucene_transaction]\n end",
"def current_show_context\n show = if defined?(parent?).present? && parent? && parent.is_a?(Show)\n parent\n elsif defined?(resource).present? && resource.is_a?(Show)\n resource\n else\n Show.latest\n end\n return show\n rescue\n Show.latest\n end",
"def thread_id\n return @thread_id\n end",
"def find_thread_root\n msg = self\n until (msg.is_root?) do\n msg = msg.parent\n end\n return msg\n end",
"def context\n @_context ||= begin\n ptr = MemoryPointer::new( Context )\n error = OpenCL.clGetSamplerInfo(self, CONTEXT, Context.size, ptr, nil)\n error_check(error)\n Context::new( ptr.read_pointer )\n end\n end",
"def run_context\n nil\n end",
"def execution_context\n raise \"Execution Context is not available in detached frame \\\"#{frame.url}\\\" (are you trying to evaluate?)\" if @_detached\n\n @_context_promise.value\n end",
"def get_context\n Log4r::MDC.get_context\n end",
"def current_user\n @current_user ||= context[:current_user]\n end",
"def context\n init\n @context\n end",
"def context\n unless @instance_context\n @instance_context = InteractionChannelContext.new(\n @version,\n @params['interaction_sid'],\n @params['sid'],\n )\n end\n @instance_context\n end",
"def context\n\n self\n end",
"def context(&block)\n current_context = Thread.current[:lumberjack_context]\n if block\n use_context(Context.new(current_context), &block)\n else\n current_context || Context.new\n end\n end",
"def info\n Thread.current[:info]\n end",
"def ssl_context\n @tls&.ssl_context\n end",
"def context\n @context ||= begin\n require 'ffi-rzmq'\n ZMQ::Context.new\n end\n block_given? ? yield(@context) : @context\n end",
"def context\n unless @instance_context\n @instance_context = NotificationContext.new(@version, @params['chat_service_sid'], )\n end\n @instance_context\n end",
"def context\n Byebug.current_context\n end",
"def fetch(context=nil)\n context.nil? ? global : named_context[context]\n end",
"def current_job\n return @job_current\n end",
"def context\n @context ||= ::ZMQ::Context.new\n end",
"def get(context = Context.current)\n context[self]\n end",
"def user\n Thread.current[\"current_user\"] \n end",
"def request_context\n @requester ? @requester.request : \"(unknown)\"\n end",
"def context\n @context ||= Contexts.context_for(self, embedded)\n end",
"def get_context_class\n c = root.context\n if c.is_a?(Proc)\n c.binding.receiver.class\n else # c is Method or UnboundMethod\n c.owner\n end\n end",
"def context\n @context ||= new_context_mock(context_options, &finalize_proc)\n end",
"def current_environment\n read_environment_from_cache\n end",
"def connection #:nodoc:\n Thread.current['connection'] ||= retrieve_connection\n Thread.current['connection']\n end",
"def current_concurrency\n self.class.current_concurrency self\n end",
"def find_context_node\n if @node.present?\n if @node.content_type == 'Section'\n @context_node = @node\n else\n @context_node = @node.self_and_ancestors.sections.include_content.last\n end\n else\n if controller_model\n parent_resource_type = controller_model.parent_type rescue nil\n\n # Nested controller access\n if parent_resource_type\n name = parent_resource_type.name\n node = current_site.self_and_descendants.accessible.with_content_type(name).include_content.first(:conditions => { :content_id => params[\"#{name.underscore}_id\"].to_i })\n @context_node = node.self_and_ancestors.sections.last if node\n else\n @context_node = current_site\n end\n else\n @context_node = current_site\n end\n end\n\n raise(ActionController::RoutingError, 'No context node found!') unless @context_node\n end",
"def context?\n !!Thread.current[:lumberjack_context]\n end",
"def simple_context\n context_director.simple_context\n end",
"def current\n Thread.current[:CURRENT_CONTROLLER]\n end",
"def context\n\t\t\told_context = @current_context\n\t\t\t@current_context = Context.new(@project, old_context)\n\t\t\tyield\n\t\t\t@current_context = old_context\n\t\tend",
"def conversation_thread_id\n return @conversation_thread_id\n end",
"def context &block\n self.worker.context(&block) \n end",
"def context(status, header, body, request)\n @context = context_retriever(request)&.call(status, header, body)\n @data[:request_context] = @context[:context_id] \\\n if @context && @context[:context_id]\n @context\n end",
"def current\n @env.first\n end",
"def client_context\n return @client_context\n end",
"def context\n {}\n end",
"def context\n {}\n end",
"def me\n context[:current_user]\n end",
"def context\n unless @instance_context\n @instance_context = SettingsContext.new(@version, )\n end\n @instance_context\n end"
] |
[
"0.7655154",
"0.6975651",
"0.6944315",
"0.6748186",
"0.6727816",
"0.65430796",
"0.6531631",
"0.6488136",
"0.6460435",
"0.64238375",
"0.63846403",
"0.63006943",
"0.62653214",
"0.62554944",
"0.62480384",
"0.6219154",
"0.6214809",
"0.62039614",
"0.6193466",
"0.61918724",
"0.6174012",
"0.6173136",
"0.614832",
"0.6137891",
"0.61071277",
"0.6101109",
"0.60799617",
"0.60693234",
"0.6039382",
"0.60207784",
"0.5988533",
"0.5988533",
"0.59684294",
"0.59311366",
"0.5924793",
"0.5924793",
"0.5912688",
"0.5880166",
"0.58777344",
"0.5874807",
"0.5858331",
"0.58553296",
"0.5832244",
"0.5831083",
"0.5819617",
"0.58074385",
"0.57856196",
"0.57796216",
"0.5774839",
"0.5712466",
"0.570675",
"0.5701619",
"0.56854343",
"0.5676952",
"0.56659925",
"0.5665862",
"0.5664572",
"0.5660953",
"0.5637445",
"0.563181",
"0.5625781",
"0.5614064",
"0.56137824",
"0.56106865",
"0.5582434",
"0.5581878",
"0.55508476",
"0.55494356",
"0.5546852",
"0.553432",
"0.5519079",
"0.5516967",
"0.5513992",
"0.5500827",
"0.54986745",
"0.5488948",
"0.54802084",
"0.54621667",
"0.5460584",
"0.5458626",
"0.5454258",
"0.54510784",
"0.54400206",
"0.5433104",
"0.5427315",
"0.54237336",
"0.5417072",
"0.54018086",
"0.53986657",
"0.53957695",
"0.5381234",
"0.5372986",
"0.5369924",
"0.5369271",
"0.5367755",
"0.53641963",
"0.53618747",
"0.53618747",
"0.5359615",
"0.535796"
] |
0.76682615
|
0
|
Assigns a context instance to the current thread.
|
def current=(context)
all_contexts[Thread.current.object_id] = context
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def local=(ctx)\n Thread.current[@key] = ctx\n end",
"def thread_context\n Thread.current[:runshell_context] ||= Context.new(main_context.to_h)\n end",
"def context\n Thread.current[:ctx] ||= {}\n Thread.current[:ctx]\n end",
"def context=(ctx)\n @context.local = ctx\n end",
"def context=(ctx)\n @context = ctx\n end",
"def context\n Thread.current[NAME] ||= Hash.new\n end",
"def set_context\n @context = Monitoring::Context.find(params[:context_id])\n end",
"def context\n unless @instance_context\n @instance_context = TaskContext.new(@version, @params['workspace_sid'], @params['sid'], )\n end\n @instance_context\n end",
"def use_context(context, &block)\n current_context = Thread.current[:lumberjack_context]\n begin\n Thread.current[:lumberjack_context] = (context || Context.new)\n yield\n ensure\n Thread.current[:lumberjack_context] = current_context\n end\n end",
"def thread_context(tid)\r\n Ragweed::Wrap32::open_thread(tid) do |h|\r\n Ragweed::Wrap32::get_thread_context(h)\r\n end\r\n end",
"def context(worker_threads = 1)\n return @context if @context\n @context = ::ZMQ::Context.new(worker_threads)\n end",
"def set_context(spark)\n # store in thread_store for later use\n sent_to spark[:sender]\n previous_sender spark[:sender]\n context_params({ reply_to: spark[:previous_sender], spark_uid: spark[:spark_uid]})\n end",
"def context\n unless @instance_context\n @instance_context = TaskContext.new(@version , @params['workspace_sid'], @params['sid'])\n end\n @instance_context\n end",
"def instance= instance\n\t\t\tthread = Thread.current\n\t\t\tthread.thread_variable_set(self.name, instance)\n\t\tend",
"def context=(context)\n context = Zuul::Context.parse(context)\n self.context_type = context.klass\n self.context_id = context.id\n end",
"def context\n Thread.current[NAME] ||= Array.new\n end",
"def set_context=(value)\n $log.debug(\"Setting context to #{value}\")\n @ssl_context ||= OpenSSL::SSL::SSLContext.new #Create a new context\n @ssl_context &&= OpenSSL::SSL::SSLContext.new(value)\n end",
"def set_context\n @context = Monitoring::Context.find(params[:id])\n end",
"def execution_context\n initialize_context!(Object.new)\n end",
"def context\n init\n @context\n end",
"def set_context\n @context = Context.find(params[:id])\n end",
"def local(thread = Thread.current)\n thread[@key] ||= Datadog::Context.new\n end",
"def as_in_context(context)\n return self if self.context == context\n copy_to(context)\n end",
"def in_context\n old_context = self.context\n self.context = self\n yield\n self.context = old_context\n end",
"def initialize(context, timeout = DEFAULT_TIMEOUT)\n @store = {}\n @mutex = Mutex.new\n\n @timeout = timeout\n @context = context\n\n start_thread\n end",
"def context\n\t\t\told_context = @current_context\n\t\t\t@current_context = Context.new(@project, old_context)\n\t\t\tyield\n\t\t\t@current_context = old_context\n\t\tend",
"def context\n unless @instance_context\n @instance_context = CurrentCallContext.new(@version, )\n end\n @instance_context\n end",
"def context\n @context ||= Context.new(self)\n end",
"def context(&block)\n current_context = Thread.current[:lumberjack_context]\n if block\n use_context(Context.new(current_context), &block)\n else\n current_context || Context.new\n end\n end",
"def set_thread_obj\n @thread_obj = ThreadObj.find(params[:id])\n end",
"def runshell_context\n Thread.current == Thread.main ?\n main_context :\n thread_context\n end",
"def context &block\n self.worker.context(&block) \n end",
"def swap( ctx )\n old = current\n Thread.current[:syncwrap_context] = ctx\n old\n end",
"def context\n @context ||= Context.new(self)\n end",
"def context=(context)\n @context = context\n @source.context = context\n end",
"def call(context: nil)\n synchronize do\n be_prepared!\n if context\n be_unstarted!\n @context = context.for(self)\n end\n if @parallel\n acts = @actions.dup\n @actions = []\n acts.each do |action|\n Thread.new { action.call(context: @context) }\n end\n else\n action = pop\n action.call(context: context) if action\n end\n end\n end",
"def context=(value); end",
"def set_thread_object\n @thread_object = ThreadObject.find(params[:id])\n end",
"def instance\n\t\t\tthread = Thread.current\n\t\t\tname = self.name\n\t\t\t\n\t\t\tunless instance = thread.thread_variable_get(name)\n\t\t\t\tif instance = self.local\n\t\t\t\t\tthread.thread_variable_set(name, instance)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\treturn instance\n\t\tend",
"def context=(context)\n raise(InvalidMixError, \"#@name context already set for this frame\") if context and @context\n @context = context\n end",
"def __bind_to_thread(thread = nil)\n thread ||= Thread.current\n raise ArgumentError, \"Must provide thread\" unless thread.is_a?(Thread)\n raise BindingError, \"Object is already bound\" if __bound?\n __check_bindability\n @bound_thread_id = thread.__id__\n self\n end",
"def with_context(&block)\n Fiber.current.hammer_context = self\n block.call\n Fiber.current.hammer_context = nil\n end",
"def start_thread #does this need to be its own thread?\n @@thread = Thread.new do\n self.run\n end\n end",
"def set_context(key, value)\n @contexts[key] = value\n end",
"def assign_key(key, options = {})\n if @current_context.present?\n @context[key] = @current_context\n @current_context = nil unless options[:keep_context]\n end\n end",
"def contextify\n self.class.monadic_context.new self\n end",
"def context\n unless @instance_context\n @instance_context = CpsContext.new(@version, )\n end\n @instance_context\n end",
"def context=(value)\n if value\n if value.is_a?(UIViewController)\n @context = RubyMotionQuery::RMQ.weak_ref(value)\n elsif value.is_a?(UIView)\n @context = value\n #else\n #debug.log_detailed('Invalid context', objects: {value: value})\n end\n else\n @context = nil\n end\n @context\n end",
"def set!\n\t\t\t# This is actually fiber-local:\n\t\t\tThread.current[:async_task] = self\n\t\tend",
"def initialize\n self.context = Context.new\n end",
"def alter_context(context = T.unsafe(nil)); end",
"def []= key, value\n Thread.current[key] = value\n end",
"def context=(context = null)\n @bridge.set_context(context)\n end",
"def context=(context = null)\n @bridge.set_context(context)\n end",
"def context\n @_context ||= {\n :argv => START_CTX[:argv].map { |arg| arg.dup },\n :cwd => START_CTX[:cwd].dup,\n 0 => START_CTX[0].dup,\n }.tap do |ctx|\n rewrite_context(ctx)\n end\n end",
"def with_context\n self.context_cache = {}\n yield\n ensure\n self.context_cache = nil\n end",
"def thread_init(thread = nil)\n thread = Thread.current if thread == nil\n thread[:knjappserver] = {} if !thread[:knjappserver]\n thread[:knjappserver][:kas] = self\n end",
"def store\n Thread.current\n end",
"def context\n unless @instance_context\n @instance_context = ApplicationContext.new(@version , @params['account_sid'], @params['sid'])\n end\n @instance_context\n end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def context=(_arg0); end",
"def set_thread\n @thread = Threads.find(params[:id])\n end",
"def context\n @context ||= new_context_mock(context_options, &finalize_proc)\n end",
"def with_context(*args, &block)\n adapter.with_context(*args, &block)\n end",
"def context(status, header, body, request)\n @context = context_retriever(request)&.call(status, header, body)\n @data[:request_context] = @context[:context_id] \\\n if @context && @context[:context_id]\n @context\n end",
"def save_context(context)\n message_context_session[:context] = context\n end",
"def context\n unless @instance_context\n @instance_context = CallContext.new(@version, @params['account_sid'], @params['sid'],)\n end\n @instance_context\n end",
"def connect_vm_to_thread\r\n #Check for duplicates.\r\n current = Thread.current\r\n error \"F91: Only one virtual machine allowed per thread\" if current[:vm]\r\n\r\n #This virtual machine is associated with this thread.\r\n current[:vm] = self\r\n @start_time = Time.now\r\n\r\n self\r\n end",
"def context\n unless @instance_context\n @instance_context = TriggerContext.new(@version, @params['account_sid'], @params['sid'],)\n end\n @instance_context\n end",
"def set_app_thread\n @app_thread = @project.app_threads.find(params[:id])\n end",
"def context_missing=(v)\n context.context_missing = v\n end",
"def in_context(context_type, &block)\n context_type.new.instance_eval(&block)\n end",
"def context\n Context.instance\n end",
"def thread\n @thread ||= super\n return @thread unless @thread.nil?\n\n @thread = build_thread\n @thread.save if persisted?\n @thread\n end",
"def context\n @context ||= {}\n end",
"def context\n @context ||= {}\n end",
"def context\n unless @instance_context\n @instance_context = SettingsContext.new(@version, )\n end\n @instance_context\n end",
"def set_server_context server_context\n @server_context = server_context\n end",
"def context\n unless @instance_context\n @instance_context = SecondaryAuthTokenContext.new(@version )\n end\n @instance_context\n end",
"def context\n unless @instance_context\n @instance_context = CallContext.new(@version , @params['sid'])\n end\n @instance_context\n end",
"def initialize(context)\r\n @context = context\r\n end",
"def initialize(context)\n super()\n self.context = context\n end",
"def []=(key, context)\n raise ArgumentError, \"Context must be a VirtFS::Context object\" if context && !context.is_a?(Context)\n raise ArgumentError, \"Cannot change the default context\" if key == :default\n @context_mutex.synchronize do\n if context.nil?\n ctx = @contexts.delete(key)\n ctx.key = nil\n return ctx\n end\n raise \"Context for given key already exists\" if @contexts[key]\n context.key = key\n @contexts[key] = context\n end\n end",
"def initialize(context)\n @context = context\n end",
"def with_subject(*args, &b)\n isolation_context.instance = self.class.superclass.new *args \n b.call self if b\n self\n end",
"def context\n unless @instance_context\n @instance_context = CampaignContext.new(@version, @params['sid'], )\n end\n @instance_context\n end",
"def context(args)\n context = args.delete(:context)\n context || @my\n end",
"def set_debugger_thread(thr)\n raise TypeError, \"Must be another Thread\" unless thr.kind_of?(Thread)\n\n @debugger_thread = thr\n end",
"def set_current_scope(scope)\n Thread.current[:webspicy_scope] = scope\n end",
"def context\n unless @instance_context\n @instance_context = SandboxContext.new(\n @version,\n @params['account_sid'],\n )\n end\n @instance_context\n end",
"def new_context(env)\n\n makara_context, makara_status = makara_values(env)\n\n context = nil\n\n # if the previous request was a redirect, let's keep that context\n if makara_status.to_s =~ /^3/ # 300+ redirect\n context = makara_context\n end\n\n context ||= Makara::Context.get_current if env['rack.test']\n context ||= Makara::Context.generate(env[\"action_dispatch.request_id\"])\n context\n end",
"def set_mail_context\n @mail_context = MailContext.find(params[:id])\n end"
] |
[
"0.68504316",
"0.6741534",
"0.6576933",
"0.6523754",
"0.64893126",
"0.6470508",
"0.63716793",
"0.633284",
"0.62927586",
"0.62610793",
"0.6169457",
"0.61591464",
"0.612363",
"0.6121851",
"0.6097193",
"0.6097007",
"0.6081057",
"0.6069125",
"0.60365206",
"0.6027005",
"0.6010464",
"0.6008602",
"0.5997006",
"0.5932849",
"0.59007186",
"0.588402",
"0.587771",
"0.58509684",
"0.58492815",
"0.5847622",
"0.5847063",
"0.5812808",
"0.57969266",
"0.57652676",
"0.57082844",
"0.5693556",
"0.56913716",
"0.5687439",
"0.5682887",
"0.5680865",
"0.56318146",
"0.5624121",
"0.5618254",
"0.5616644",
"0.5616095",
"0.5609704",
"0.55989945",
"0.559023",
"0.5585265",
"0.55613625",
"0.5550544",
"0.5547507",
"0.5547463",
"0.5547463",
"0.55465084",
"0.5536318",
"0.5534051",
"0.5517886",
"0.5499432",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.54862225",
"0.5482413",
"0.54733723",
"0.5471419",
"0.5468527",
"0.5455281",
"0.5438562",
"0.5435581",
"0.542402",
"0.5418358",
"0.54093915",
"0.54054916",
"0.53940856",
"0.5388699",
"0.5351865",
"0.5351865",
"0.5349289",
"0.5338333",
"0.5333586",
"0.53301454",
"0.5322769",
"0.5322107",
"0.5319355",
"0.5313425",
"0.5310111",
"0.5302113",
"0.5298571",
"0.52972883",
"0.5290413",
"0.5289178",
"0.528916",
"0.5286962"
] |
0.67486894
|
1
|
Clears the assigned context for the current thread.
|
def clear_current
all_contexts.delete(Thread.current.object_id)
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def clear_context\n @current_context = nil\n end",
"def clear\n context.clear if Thread.current[NAME]\n self\n end",
"def clear\n context.clear if Thread.current[NAME]\n self\n end",
"def clear!\n context_manager.clear!\n end",
"def reset_context\n @context = nil\n end",
"def clear!\n contexts.clear\n end",
"def clear!\n contexts.clear\n end",
"def reset\n @context = nil\n end",
"def clear(context = nil)\n with_scope(context) { current_base.clear }\n end",
"def clear(context = nil)\n with_scope(context) { current_base.clear }\n end",
"def clear_view_context!\n @view_context = nil\n end",
"def clear!\n Thread.current[:__honeybadger_context] = nil\n end",
"def clear!\n Thread.current[LOCAL_KEY] = nil\n end",
"def clear_request_data\n Thread.current[THREAD_LOCAL_NAME] = nil\n end",
"def clear\n \n @hook_contexts.clear if @hook_contexts\n @execution_contexts.clear if @execution_contexts\n @cascade_contexts.clear if @cascade_contexts\n \n self\n \n end",
"def reset!\n Thread.current[THREAD_KEY] = {}\n end",
"def reset!\n @context = [context[0]]\n end",
"def reset_ctx(ctx)\n each_value {|x| x.reset_ctx(ctx) }\n end",
"def flush_context_stack\n while (context != TopContext)\n pop_context\n end\n end",
"def clean_thread_context(logger: nil, namespace: nil)\n if store(namespace).present?\n if logger.nil?\n puts \"WARNING: ThreadAccessor variables set outside ThreadAccessor context: #{store(namespace).keys.join(\", \")}\"\n else\n logger.warn(\"ThreadAccessor variables set outside ThreadAccessor context: #{store(namespace).keys.join(\", \")}\")\n end\n end\n\n yield\n ensure\n store(namespace).clear\n end",
"def clean\n Thread.current[:__cms_original_content] = nil\n Thread.current[:__cms_active_page] = nil\n Thread.current[:__cms_stack] = nil\n Thread.current[:__content_node_stack] = nil\n Thread.current[:__content_iterator_stack] = nil\n Thread.current[:__content_iterator_stack_key] = nil\n end",
"def reset\n @thread.kill if @thread.is_a? Thread\n @thread = nil\n\n # Remove all pending events from the queue.\n @event_queue.pop_each { |event| self.cancel( event ) } if @event_queue\n end",
"def clear\n @lock.synchronize do\n @credentials = nil\n end\n end",
"def clear_current_user\n User.current_user = nil\n end",
"def clear_current_cache\n\t\t\t\t\tself.class.clear_current_cache\n\t\t\t\tend",
"def clear!\n context_manager.clear!\n breadcrumbs.clear!\n end",
"def reset_ctx(ctx)\n ctx = Array(ctx || MXNet::Context.current)\n if @_data\n data = _reduce()\n Autograd.pause do\n _init_impl(data, ctx)\n end\n elsif @_deferred_init\n @_deferred_init[1] = ctx\n else\n raise ArgumentError,\n \"Cannot reset context for Parameter '#{@name}' because it \" +\n \"has not been initialized.\"\n end\n end",
"def cancel\n # Context is already cleared in before_action\n end",
"def clean_thread_locals(thread)\n thread.keys.each do |key|\n next if key == :celluloid_queue\n\n # Ruby seems to lack an API for deleting thread locals. WTF, Ruby?\n thread[key] = nil\n end\n end",
"def clear(context: Context.current)\n context.set_value(CORRELATION_CONTEXT_KEY, EMPTY_CORRELATION_CONTEXT)\n end",
"def remove_all_contexts\n previous_size = @contexts.size\n @contexts = []\n previous_size\n end",
"def clear_current!\n @master_state.current_listener_pid = nil\n end",
"def cancel!\n # Context is already cleared in action_for_message\n end",
"def unset_span_context\n OpenCensus::Context.unset SPAN_CONTEXT_KEY\n end",
"def clear\n self.request = nil\n end",
"def clear_request_token\n @request_token = nil\n end",
"def clear()\n @mutex.synchronize {\n each_object &destroy_block\n @idle_list = []\n @active_list = {}\n }\n end",
"def trash_current!\n t = Thread.current\n conn = owned_resource(t)\n return unless conn\n\n @delete_proc.call conn if @delete_proc\n sync { @allocated.delete(t) }\n nil\n end",
"def clear\n\t\tif @active\n\t\t\t@active.cleanup\n\t\t\t@active = nil\n\t\tend\n\tend",
"def clear_current_transaction!\n Thread.current[:appsignal_transaction] = nil\n end",
"def clear_query_caches_for_current_thread\n connection_handler.each_connection_pool do |pool|\n pool.connection.clear_query_cache if pool.active_connection?\n end\n end",
"def clean_thread_locals; end",
"def thread_cleanup\n # do nothing, i think?\n end",
"def flush(ctx)\n ctx.last = nil\n end",
"def clear_current_user; end",
"def clear\n Thread.current[AGGREGATES_KEY] = nil\n end",
"def clear\n Thread.current[AGGREGATES_KEY] = nil\n end",
"def clear\n synchronize do\n @locks.delete(Logging::Logger.thread_name)\n end\n end",
"def pop_context\n context.pop\n end",
"def reset_ctx(connection_initialize = false)\n # set active command sequence info\n Thread.current[:cmd_sequence] = connection_initialize ? :CMD_HELO : :CMD_RSET\n # drop any auth challenge\n Thread.current[:auth_challenge] = {}\n # test existing of :ctx hash\n Thread.current[:ctx] || Thread.current[:ctx] = {}\n # reset server values (only on connection start)\n if connection_initialize\n # create or rebuild :ctx hash\n Thread.current[:ctx][:server] = {\n local_host: '',\n local_ip: '',\n local_port: '',\n remote_host: '',\n remote_ip: '',\n remote_port: '',\n helo: '',\n connected: '',\n authorization_id: '',\n authentication_id: '',\n authenticated: ''\n }\n end\n # reset envelope values\n Thread.current[:ctx][:envelope] = {\n from: '',\n to: []\n }\n # reset message data\n Thread.current[:ctx].merge!(message: {\n delivered: -1,\n bytesize: -1,\n data: ''\n })\n end",
"def with_context(&block)\n Fiber.current.hammer_context = self\n block.call\n Fiber.current.hammer_context = nil\n end",
"def free\n SassC::Lib.sass_free_context(self)\n end",
"def pop_from_active_context\n return @active_context.pop_context\n end",
"def context_renew\n @context&.abort\n @context = org.dspace.core.Context.new\n end",
"def clear\n start\n end",
"def clear_current_user_for_request_and_session\n @current_user = nil\n session[:user_id] = nil\n end",
"def clear_current_user_for_request_and_session\n @current_user = nil\n session[:user_id] = nil\n end",
"def clear_current_user_for_request_and_session\n @current_user = nil\n session[:user_id] = nil\n end",
"def teardown\n evicting_thread.kill\n end",
"def clear_screen\n CLEAR_SCREEN\n end",
"def with_context\n self.context_cache = {}\n yield\n ensure\n self.context_cache = nil\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 @instance = nil\n @local_env = nil\n end",
"def reset\n @instance = nil\n @local_env = nil\n end",
"def testContextDisposal \n assert(Context.method_defined?(:name), \"Method to drop unneeded contexts should exist\")\n _previousDefault = Context.default\n assert(Context.default.isActive)\n assert_raise(RuntimeError) {Context.default.discard} \n Context.default.deactivate\n assert(!Context.default.isActive, \"The default context should be inactive\")\n assert_nothing_raised(RuntimeError){Context.default.discard}\n assert_nothing_raised(RuntimeError){self.testDefaultContext}\n assert(!(Context.default == _previousDefault), \"Fresh default context should not be the default context just discarded\")\n end",
"def clear\n current_state.clear\n end",
"def clear_user_without_logout\n subject.instance_variable_set(:@current_user, nil)\n end",
"def reset_customer_in_thread\n Thread.current['customer'] = nil\n end",
"def switch_to_default_context\n set_context nil\n end",
"def switch_to_default_context\n set_context nil\n end",
"def reset\n @window_size = options.window_size\n contexts.reset\n end",
"def clear\n namespace + '_clear'\n end",
"def clear\n do_clear\n end",
"def clear\n @stack.clear\n end",
"def destroy_previous_contexts\n return unless $js\n\n runtime = $js.instance_variable_get :@runtime\n uuid = $js.instance_variable_get :@uuid\n runtime.vm.delete_context(uuid)\n end",
"def clear_request\n @url = nil\n @options = nil\n end",
"def ensure_clean_context!\n return unless configuration[:tracer].call_context.current_span\n configuration[:tracer].provider.context = Context.new\n end",
"def ensure_clean_context!\n return unless configuration[:tracer].call_context.current_span\n configuration[:tracer].provider.context = Context.new\n end",
"def context\n Thread.current[:ctx] ||= {}\n Thread.current[:ctx]\n end",
"def clear_buffer\n @buffer.clear\n end",
"def clear\n LOCK.synchronize do\n @hooks = nil\n @applied = nil\n @logger = nil\n end\n end",
"def clear_buffer\n buffer.clear\n end",
"def clear!\n @handlers = {}\n @environments = {}\n @requests = []\n end",
"def clear()\n shutdown()\n @tasks = {}\n _clear()\n end",
"def reset_define_context(context=nil)\n ret = @define_context\n @define_context = HashStruct.new(context || {})\n return ret\n end",
"def ti_clear\n\ttictl(\"clear\")\n end",
"def clear\n @mutex.synchronize do\n @tuples.clear\n @objects.clear\n @catdata.clear\n end\n self\n end",
"def reset\n @source_buffer = nil\n\n @lexer.reset\n @static_env.reset\n @context.reset\n @current_arg_stack.reset\n @pattern_variables.reset\n @pattern_hash_keys.reset\n\n self\n end",
"def clear!\n end",
"def clear() end",
"def clear() end",
"def teardown\n Thread.list.each do |thr|\n thr.join if (thr.alive? and thr != @mthread and thr != Thread.current)\n end\n end",
"def clear_buffer_cache!\n @buffers = nil\n end",
"def clear!; end",
"def clear!; end",
"def clear!; end",
"def reset\n self.configuration = ({})\n config_contexts.values.each(&:reset)\n end",
"def clear\n @resource = nil\n end",
"def run_context\n nil\n end",
"def clear!\n @cache.delete(current_store_id)\n end"
] |
[
"0.8428168",
"0.81905293",
"0.81905293",
"0.7738027",
"0.7592086",
"0.7390783",
"0.7390783",
"0.73234934",
"0.7300959",
"0.7300959",
"0.72644985",
"0.72190547",
"0.72048604",
"0.6845888",
"0.67057955",
"0.663552",
"0.65859765",
"0.63439965",
"0.6276657",
"0.621809",
"0.603469",
"0.5961213",
"0.59525466",
"0.59363574",
"0.59355694",
"0.5930034",
"0.59296083",
"0.5922247",
"0.5919463",
"0.591933",
"0.59161305",
"0.59100175",
"0.5909236",
"0.58873713",
"0.585888",
"0.58559895",
"0.58332443",
"0.58003145",
"0.5793054",
"0.574468",
"0.5710534",
"0.5709904",
"0.57019603",
"0.5696137",
"0.56941056",
"0.5691508",
"0.5691508",
"0.56902903",
"0.56870544",
"0.5685637",
"0.5682831",
"0.5682237",
"0.5681578",
"0.5679098",
"0.56440383",
"0.56286776",
"0.56286776",
"0.56286776",
"0.5618086",
"0.5617255",
"0.56046504",
"0.5598043",
"0.55961925",
"0.55961925",
"0.55739623",
"0.5533245",
"0.5521317",
"0.551861",
"0.5514698",
"0.5514698",
"0.5508605",
"0.5494269",
"0.5486052",
"0.54846776",
"0.54635143",
"0.5454062",
"0.5445264",
"0.5445264",
"0.5436471",
"0.5414312",
"0.5410428",
"0.5401126",
"0.54004616",
"0.5386141",
"0.53843427",
"0.5381299",
"0.53740376",
"0.5359005",
"0.5358213",
"0.53570616",
"0.53570616",
"0.5354111",
"0.53508556",
"0.5345496",
"0.5345496",
"0.5345496",
"0.5343558",
"0.53409195",
"0.5338104",
"0.533062"
] |
0.821916
|
1
|
GET /steps GET /steps.json
|
def index
@steps = Step.all
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n \n @steps = @quest.steps\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def index\n @steps = Step.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def index\n @steps = Step.collated.ordered.page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def getsteps\n\t\t@hide_menu = true\n\n puts \"In Steps\"\n recId = params['query'].inspect\n #this is the link to the API\n url = \"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/\" + recId[1..-2] + \"/analyzedInstructions?stepBreakdown=true\"\n stepss = Unirest.get url,\n headers:{\n \"X-Mashape-Key\" => \"UpZLcnOR83mshtXvuIOPFXBkfhn5p1UWi1ejsnsTLWoVXrOppm\",\n \"Accept\" => \"application/json\"\n }\n allSteps = stepss.body\n\n recSteps = Hash.new\n\n counter = 1\n #this is how the recipe information is formatted\n allSteps.each do |key|\n key.each do |key2,steps|\n if(key2.eql? \"steps\")\n steps.each do |step|\n step.each do |key3, lastStep|\n if(key3.eql? \"step\")\n recSteps[counter] = lastStep\n counter += 1\n #this gives each step a number, for ease of use\n end\n end\n end\n end\n end\n end\n puts recSteps\n\n @recipeData = recSteps\n render template: \"recipes/data3\"\n end",
"def index\n @steps = @guide.steps\n end",
"def index\n @steps = Step.all\n end",
"def index\n @goal_steps = GoalStep.all\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def new\n \n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def index\n\n if params[:task_id] \n task = Task.find(params[:task_id])\n if task != nil\n @steps = task.steps\n else\n @steps = []\n end\n else \n @steps = Step.all\n end\n end",
"def show\n @steps_log = StepsLog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @steps_log }\n end\n end",
"def new\n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def steps\n @steps ||= []\n end",
"def index\n redirect_to wizard_path(steps.first, request.query_parameters)\n end",
"def index\n @taken_steps = TakenStep.all\n end",
"def show\n @steps = @tutorial.steps\n @step = @tutorial.steps.build\n end",
"def index\n @next_steps = NextStep.all\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to api_v1_step_url(@step), notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @user_steps = UserStep.all\n end",
"def index\n @roadmap_steps = RoadmapStep.all\n end",
"def show\n @next_step = NextStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @next_step }\n end\n end",
"def show\n @step_activity = StepActivity.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step_activity }\n end\n end",
"def new\n @steps_log = StepsLog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @steps_log }\n end\n end",
"def show\n @step = @guide.steps.find(params[:id])\n end",
"def index\n @project_steps = ProjectStep.all\n end",
"def index\n @step_ms = StepM.all\n end",
"def index\n @step_commands = StepCommand.all\n end",
"def steps=(new_value)\n @steps = new_value\n end",
"def create\n @step = Step.new(step_params) \n\n if @step.save\n render :show, status: :created, location: @step\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def steps\n step_flows.collect(&:current_step)\n end",
"def steps\n @steps ||= parser.parse\n end",
"def steps\n find_solution\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @step = Step.find_by_slug(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @step_type = StepType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step_type }\n end\n end",
"def new\n @step_activity = StepActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_activity }\n end\n end",
"def index \n authorize! :read, @project \n @stepIDs = @project.steps.not_labels.order(\"published_on\").pluck(:id)\n\n # fix step position and ancestry if there's an error\n if @project.steps.where(:position => -1).present?\n Rails.logger.info(\"FIXING STEP POSITIONS AND ANCESTRY\")\n start_position = @project.steps.order(:position).last.position\n @project.steps.where(:position => -1).order(\"created_at\").each do |step|\n last_step = @project.steps.where(:position => start_position).first\n step.update_attributes(:ancestry => last_step.ancestry + \"/\" + last_step.id.to_s)\n step.update_attributes(:position => start_position+1)\n start_position = start_position + 1\n end\n end\n \n respond_to do |format|\n # go directly to the project overview page\n format.html \n format.json\n format.xml \n end\n end",
"def new\n @next_step = NextStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @next_step }\n end\n end",
"def index\n if params[:project_id]\n @steps = Step.joins(:projects).includes(:work_items, :work_items => :users, :work_items => :tasks).where('projects.id = ?', params[:project_id]).order('position ASC')\n steps = @steps.collect do |s|\n s.work_items.sort!{|a, b| a.position <=> b.position}\n s\n end\n @steps = steps\n else\n @steps = Step.all\n end\n\n respond_with @steps\n end",
"def show\n @lead_step = LeadStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lead_step }\n end\n end",
"def set_step\n begin\n @step = Step.find(params[:id])\n rescue => e\n puts e.message\n render json: { message: \"Id do step não encontrado\" }, status: :not_found\n end\n end",
"def steps\n @steps ||= 0\n end",
"def new\n @step = Step.new :phase_template_id => params[:phase_template_id]\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def steps\n %w[first last]\n end",
"def index\n @step_threes = StepThree.all\n end",
"def steps\n %w[name time]\n end",
"def index\n @cooking_steps = CookingStep.all\n end",
"def index\n @steplogs = Steplog.all\n end",
"def show\n @steps = @experiment.steps.all(:order => :step_order)\n\n #NB - in experiment/show view, experiment destroyed at end if temp==true\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @experiment }\n end\n end",
"def create\n @step = Step.new(params[:step])\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step.phase_template, notice: 'Step was successfully added.' }\n format.json { render json: @step, status: :created, location: @step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @step2 = Step2.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step2 }\n end\n end",
"def new\n @step_type = StepType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_type }\n end\n end",
"def get_steps(category)\n steps = []\n params.each do |k,v|\n if (k.starts_with? \"step\") && (cat_number(k) == category[1])\n name = v\n num = step_number(k)\n steps << [cat_number(k),num,name]\n end\n end\n return steps\n end",
"def new\n @step2 = Step2.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step2 }\n end\n end",
"def show\n @step = @script.steps.build\n end",
"def get_word_by_step\n @words = Word.where(step: params[:step]).order(created_at: :desc).page params[:page]\n end",
"def index\n if params[:workflow_id] \n workflow = Workflow.find(params[:workflow_id])\n if workflow != nil\n @step_definitions = workflow.step_definitions\n else\n @step_definitions = []\n end\n else \n @step_definitions = StepDefinition.all\n end\n end",
"def index\n @process_steps = ProcessStep.all\n end",
"def list_tree_steps(flow_step = self, skips = [])\n steps_children = []\n flow_step.my_steps.reject{ |s| skips.include? s.id }.each do |step|\n steps_children << { step: step, flow: step.my_child_flow, steps: (step.step_type == 'flow' ? list_tree_steps(step.my_child_flow, skips) : []) }\n end if flow_step.present? && flow_step.my_steps.present?\n steps_children\n end",
"def create\n \n @step = @quest.steps.new(params[:step])\n\n \n \n if @step.save\n redirect_to (quest_path(@quest)), notice: 'Step was successfully created.'\n\n else\n render action: \"new\" \n end\n end",
"def index\n @category_steps = CategoryStep.all\n end",
"def index\n @steps = Step.where shop_id: session[:shopify]\n end",
"def form_steps\n self.steps\n end",
"def new\n @lead_step = LeadStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lead_step }\n end\n end",
"def new\n @pre_step = PreStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pre_step }\n end\n end",
"def all_steps\n\t#make calls to step here...\nend",
"def steps\n steps_keywords = %w(Given When Then And But)\n nsteps = 0\n @steps = []\n while true\n print \"Add step [Y/n]: \"\n choice = gets\n if choice.downcase.strip != \"n\"\n puts \"Step #{nsteps +1}:\"\n step = gets.capitalize\n init_step_word = step.split(' ').first\n if steps_keywords.include?(init_step_word)\n @steps << step\n nsteps = nsteps ++ 1\n else\n puts \"Error: #{init_step_word} unsupported initial value\"\n puts \"Use only #{steps_keywords} keywords\"\n end\n elsif choice.downcase.strip == \"n\"\n break\n else\n \"please enter a valid choice.\"\n end\n end\n write_feature\n end",
"def index\n @step_scenarios = StepScenario.where(scenario_id: current_scenario.id)\n end",
"def new\n @step = Step.new\n @selection = Selection.find(params[:selection_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @pre_step = PreStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pre_step }\n end\n end",
"def index\n @book_steps = @book.book_steps.all\n @book = @book\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_steps }\n end\n end",
"def run\n if @start.kind_of? String\n client = Restfulie.at(@start)\n client = client.follow if @follow\n client = client.accepts(@accepts) if @accepts\n @start = current = client.get\n else\n # probably configured thru the Rest Process Model class\n @start = current = @goal.class.get_restfulie.get\n end\n \n # load the steps and scenario\n @goal.steps \n @goal.scenario \n \n while(!@goal.completed?(current))\n current = @walker.move(@goal, current, self)\n end\n current\n end",
"def next\n lesson.steps.where(\"id > ?\", id).first\n end",
"def step(steps, force = false)\n #This is a stub, used for indexing\n end",
"def show\n \t@step = Step.find(params[:id])\n \t\n \trespond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @step }\n end\n end",
"def show\n @tc_detail_step = TcDetailStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tc_detail_step }\n end\n end",
"def show\n @recipe = Recipe.find(params[:id])\n @step = @recipe.steps.build #build a new step, this new one does not have sequence_id YET\n @ingredient = @recipe.ingredients.build #build new ingredient\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @recipe }\n end\n end",
"def steps\n %w[\n household_member_demographics_step\n household_member_address_step\n household_member_address_search_results_step\n household_member_citizenship_step\n household_member_education_step\n household_member_employments_step\n household_member_assessment_employment_step\n household_member_incomes_step\n household_member_unearned_incomes_step\n household_member_expenses_step\n household_member_resources_step\n household_member_relations_step\n ]\n end",
"def create\n @step = Step.new(params[:step])\n @step.test_case_id = params[:test_case_id].to_i\n\n respond_to do |format|\n if @step.save\n @step_activity = StepActivity.new(:activity_type => 'edit', :description => @step.description)\n @step_activity.user = current_user\n @step_activity.step = @step\n @step_activity.save!\n format.json { render :json => @step, :status => :created, :location => @step }\n format.html { redirect_to(project_test_case_path(@step.test_case.project, @step.test_case)) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def p_steps_feed\n PStep.all\n end",
"def create\n \t@step = @tutorial.steps.build(params[:step])\n authorize! :create, @step\n respond_to do |format|\n if @step.save\n format.html { redirect_to(@tutorial, :notice => 'Step was successfully created.') }\n format.xml { render :xml => @tutorial, :status => :created, :location => @tutorial }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n\n step_attributes = step_params\n fields_attributes = step_attributes.delete(\"fields\")\n\n @step = Step.new(step_attributes)\n @step.fields = Field.createFields(fields_attributes)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(:step_number, :points, :name, :quest_id, :answer, :body)\n end",
"def index\n @stepones = Stepone.all\n end",
"def new\n @step = @guide.steps.new(params[:step])\n end",
"def steps\n Rails.cache.fetch([self, \"pill_sequence_steps\"]) { pill_sequence_steps }\n end",
"def steps\n @result['tracks'].collect {|track| track.name}\n end",
"def step_params\n params.require(:step).permit(\n :milestone_id, :reached_at, :notes\n )\n end",
"def set_step\n @step = @recipe_item.steps.find(params[:id])\n end",
"def index\n @project_step_ms = ProjectStepM.all\n end",
"def to_json\n # Convert Object to Hash\n hash = self.to_hash\n\n # Grab the Step objects and convert to Hashes\n steps = hash['steps']\n hashified_steps = []\n steps.each {|step| hashified_steps << step.to_hash}\n hash['steps'] = hashified_steps\n\n # Convert Hash to JSON\n hash.to_json\n end",
"def steps\n unless @steps_loaded\n step_file = File.expand_path(\"./steps/#{self.class.name.underscore}.rb\", @@current_dir)\n if File.exists?(step_file)\n self.instance_eval File.read(step_file), __FILE__, __LINE__ + 1\n else\n raise StepsFileNotFoundError.new(\"File #{step_file} not found\")\n end\n @steps_loaded = true\n end\n end",
"def set_step\n @step = @trip.steps.find_by_id params[:id]\n end",
"def index\n @active_workflow_steps = ActiveWorkflowStep.all\n end",
"def steps(steps)\n @step_lengths = steps.map {|keyword, name| (keyword+name).unpack(\"U*\").length}\n @max_step_length = @step_lengths.max\n @step_index = -1\n end"
] |
[
"0.7637826",
"0.71650946",
"0.6820434",
"0.67121947",
"0.6697843",
"0.66859204",
"0.6614578",
"0.6571187",
"0.6571187",
"0.6571187",
"0.6489213",
"0.6478076",
"0.6385908",
"0.63753617",
"0.6344778",
"0.6264669",
"0.62381005",
"0.62057096",
"0.61792237",
"0.61588967",
"0.61372924",
"0.61166376",
"0.6055973",
"0.6044074",
"0.60266876",
"0.60157454",
"0.6003184",
"0.59887326",
"0.5988204",
"0.5983245",
"0.59759283",
"0.5970961",
"0.5963535",
"0.5928957",
"0.5920211",
"0.5900489",
"0.5888895",
"0.5886303",
"0.58858913",
"0.58835393",
"0.58727586",
"0.58081657",
"0.5802995",
"0.58009624",
"0.58002",
"0.5796894",
"0.5779206",
"0.5751844",
"0.57474715",
"0.5742418",
"0.5731351",
"0.5728561",
"0.5713906",
"0.5704631",
"0.56797594",
"0.5667821",
"0.5664656",
"0.5663201",
"0.56514806",
"0.5649133",
"0.564495",
"0.5637676",
"0.5619421",
"0.5602638",
"0.55939716",
"0.5586722",
"0.5582782",
"0.55721897",
"0.5567494",
"0.5566464",
"0.55640906",
"0.55631745",
"0.5559274",
"0.5555995",
"0.5540523",
"0.55343586",
"0.5534257",
"0.5511974",
"0.55112314",
"0.55085605",
"0.5498964",
"0.5487762",
"0.54787225",
"0.54770243",
"0.5469162",
"0.5464744",
"0.5462877",
"0.5460241",
"0.5457021",
"0.5456545",
"0.5453943",
"0.54528433",
"0.54492736",
"0.5446872",
"0.5445863",
"0.5441009",
"0.54409796"
] |
0.68370473
|
5
|
GET /steps/1 GET /steps/1.json
|
def show
render :show
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n \n @steps = @quest.steps\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def index\n @steps = Step.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def new\n \n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def new\n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n @steps_log = StepsLog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @steps_log }\n end\n end",
"def show\n @step2 = Step2.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step2 }\n end\n end",
"def index\n @steps = Step.all\n end",
"def index\n @steps = Step.all\n end",
"def index\n @steps = Step.all\n end",
"def index\n @steps = Step.all\n end",
"def show\n @step = @guide.steps.find(params[:id])\n end",
"def show\n @step_activity = StepActivity.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step_activity }\n end\n end",
"def show\n @next_step = NextStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @next_step }\n end\n end",
"def index\n @steps = @guide.steps\n end",
"def index\n @steps = Step.collated.ordered.page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def show\n @step = Step.find_by_slug(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step }\n end\n end",
"def getsteps\n\t\t@hide_menu = true\n\n puts \"In Steps\"\n recId = params['query'].inspect\n #this is the link to the API\n url = \"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/\" + recId[1..-2] + \"/analyzedInstructions?stepBreakdown=true\"\n stepss = Unirest.get url,\n headers:{\n \"X-Mashape-Key\" => \"UpZLcnOR83mshtXvuIOPFXBkfhn5p1UWi1ejsnsTLWoVXrOppm\",\n \"Accept\" => \"application/json\"\n }\n allSteps = stepss.body\n\n recSteps = Hash.new\n\n counter = 1\n #this is how the recipe information is formatted\n allSteps.each do |key|\n key.each do |key2,steps|\n if(key2.eql? \"steps\")\n steps.each do |step|\n step.each do |key3, lastStep|\n if(key3.eql? \"step\")\n recSteps[counter] = lastStep\n counter += 1\n #this gives each step a number, for ease of use\n end\n end\n end\n end\n end\n end\n puts recSteps\n\n @recipeData = recSteps\n render template: \"recipes/data3\"\n end",
"def show\n @step_type = StepType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @step_type }\n end\n end",
"def show\n @steps = @tutorial.steps\n @step = @tutorial.steps.build\n end",
"def new\n @step2 = Step2.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step2 }\n end\n end",
"def index\n @goal_steps = GoalStep.all\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to api_v1_step_url(@step), notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n\n if params[:task_id] \n task = Task.find(params[:task_id])\n if task != nil\n @steps = task.steps\n else\n @steps = []\n end\n else \n @steps = Step.all\n end\n end",
"def index\n @steps = Step.all\n end",
"def set_step\n begin\n @step = Step.find(params[:id])\n rescue => e\n puts e.message\n render json: { message: \"Id do step não encontrado\" }, status: :not_found\n end\n end",
"def new\n @step = Step.new :phase_template_id => params[:phase_template_id]\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def new\n @next_step = NextStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @next_step }\n end\n end",
"def new\n @step_activity = StepActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_activity }\n end\n end",
"def show\n @pre_step = PreStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pre_step }\n end\n end",
"def create\n @step = Step.new(step_params) \n\n if @step.save\n render :show, status: :created, location: @step\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def show\n @lead_step = LeadStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lead_step }\n end\n end",
"def index\n redirect_to wizard_path(steps.first, request.query_parameters)\n end",
"def new\n @steps_log = StepsLog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @steps_log }\n end\n end",
"def next\n lesson.steps.where(\"id > ?\", id).first\n end",
"def new\n @step = Step.new\n @selection = Selection.find(params[:selection_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def show\n \t@step = Step.find(params[:id])\n \t\n \trespond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @step }\n end\n end",
"def show\n @step = @script.steps.build\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @pre_step = PreStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pre_step }\n end\n end",
"def show\n @recipe = Recipe.find(params[:id])\n @step = @recipe.steps.build #build a new step, this new one does not have sequence_id YET\n @ingredient = @recipe.ingredients.build #build new ingredient\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @recipe }\n end\n end",
"def new\n @step_type = StepType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_type }\n end\n end",
"def index\n @next_steps = NextStep.all\n end",
"def show\n @tc_detail_step = TcDetailStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tc_detail_step }\n end\n end",
"def index\n @taken_steps = TakenStep.all\n end",
"def index \n authorize! :read, @project \n @stepIDs = @project.steps.not_labels.order(\"published_on\").pluck(:id)\n\n # fix step position and ancestry if there's an error\n if @project.steps.where(:position => -1).present?\n Rails.logger.info(\"FIXING STEP POSITIONS AND ANCESTRY\")\n start_position = @project.steps.order(:position).last.position\n @project.steps.where(:position => -1).order(\"created_at\").each do |step|\n last_step = @project.steps.where(:position => start_position).first\n step.update_attributes(:ancestry => last_step.ancestry + \"/\" + last_step.id.to_s)\n step.update_attributes(:position => start_position+1)\n start_position = start_position + 1\n end\n end\n \n respond_to do |format|\n # go directly to the project overview page\n format.html \n format.json\n format.xml \n end\n end",
"def run\n if @start.kind_of? String\n client = Restfulie.at(@start)\n client = client.follow if @follow\n client = client.accepts(@accepts) if @accepts\n @start = current = client.get\n else\n # probably configured thru the Rest Process Model class\n @start = current = @goal.class.get_restfulie.get\n end\n \n # load the steps and scenario\n @goal.steps \n @goal.scenario \n \n while(!@goal.completed?(current))\n current = @walker.move(@goal, current, self)\n end\n current\n end",
"def create\n @step = Step.new(params[:step])\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step.phase_template, notice: 'Step was successfully added.' }\n format.json { render json: @step, status: :created, location: @step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_step\n @step = @recipe_item.steps.find(params[:id])\n end",
"def show\n @goal = Goal.find(params[:id])\n render json: @goal\n end",
"def index\n @project_steps = ProjectStep.all\n end",
"def update\n if @step.update(step_params)\n render :show, status: :ok, location: @step\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def new\n @step = Step.new\n @test_case = TestCase.find(params[:test_case_id])\n respond_with @step\n end",
"def create\n @step = Step.new(params[:step])\n @step.test_case_id = params[:test_case_id].to_i\n\n respond_to do |format|\n if @step.save\n @step_activity = StepActivity.new(:activity_type => 'edit', :description => @step.description)\n @step_activity.user = current_user\n @step_activity.step = @step\n @step_activity.save!\n format.json { render :json => @step, :status => :created, :location => @step }\n format.html { redirect_to(project_test_case_path(@step.test_case.project, @step.test_case)) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def index\n @step_commands = StepCommand.all\n end",
"def index\n @user_steps = UserStep.all\n end",
"def set_step\n @step = @trip.steps.find_by_id params[:id]\n end",
"def step1\n\n end",
"def new\n @lead_step = LeadStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lead_step }\n end\n end",
"def new\n @step = @guide.steps.new(params[:step])\n end",
"def index\n @roadmap_steps = RoadmapStep.all\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.html { redirect_to api_v1_step_url(@step), notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def [](name)\n steps[name]\n end",
"def [](name)\n steps[name]\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def show\n @wizard = Wizard.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @wizard }\n end\n end",
"def update\n @step = @guide.steps.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to [@guide, @step], notice: 'Step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @steps = @experiment.steps.all(:order => :step_order)\n\n #NB - in experiment/show view, experiment destroyed at end if temp==true\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @experiment }\n end\n end",
"def step1\n \n end",
"def new\n @post = Post.new\n session[:step] = @post.step = Post::STEPS.first\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @post }\n end\n end",
"def create\n \n @step = @quest.steps.new(params[:step])\n\n \n \n if @step.save\n redirect_to (quest_path(@quest)), notice: 'Step was successfully created.'\n\n else\n render action: \"new\" \n end\n end",
"def update\n if @step.update(step_params)\n render :show, status: :ok\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def index\n @stepones = Stepone.all\n end",
"def index\n if params[:workflow_id] \n workflow = Workflow.find(params[:workflow_id])\n if workflow != nil\n @step_definitions = workflow.step_definitions\n else\n @step_definitions = []\n end\n else \n @step_definitions = StepDefinition.all\n end\n end",
"def index\n @step_scenarios = StepScenario.where(scenario_id: current_scenario.id)\n end",
"def show\n @book_step = BookStep.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_step }\n end\n end",
"def index\n @step_threes = StepThree.all\n end",
"def index\n @step_ms = StepM.all\n end",
"def show\n unless session[:referrer]\n session[:referrer] = request.referrer\n end\n\n @step = Step.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render xml: @step }\n end\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def current_step \n @current_step || steps.first\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to steps_url }\n format.json { head :no_content }\n end\n end",
"def new\n @goal = Goal.new\n current_uri = request.env['PATH_INFO']\n \n if current_uri == goal_wizard_path\n render :wizard\n else\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @goal }\n end\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def show\n @goal = Goal.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goal }\n end\n end",
"def create\n @recipe = Recipe.find(params[:recipe_id])\n @step = @recipe.steps.new(step_params)\n\n if @step.save\n redirect_to @recipe, notice: 'Step was successfully created.'\n else\n render :new\n end\n end",
"def index\n if params[:project_id]\n @steps = Step.joins(:projects).includes(:work_items, :work_items => :users, :work_items => :tasks).where('projects.id = ?', params[:project_id]).order('position ASC')\n steps = @steps.collect do |s|\n s.work_items.sort!{|a, b| a.position <=> b.position}\n s\n end\n @steps = steps\n else\n @steps = Step.all\n end\n\n respond_with @steps\n end",
"def update\n @step = Step.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n @step_activity = StepActivity.new(:activity_type => 'edit', :description => @step.description)\n @step_activity.user = current_user\n @step_activity.step = @step\n @step_activity.save!\n format.html { redirect_to(project_test_case_path(@step.test_case.project, @step.test_case)) }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def show\n @goal = Goal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goal }\n end\n end",
"def show\n @goal = Goal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goal }\n end\n end",
"def show\n @goal = Goal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goal }\n end\n end"
] |
[
"0.7460156",
"0.7168968",
"0.7168968",
"0.7168968",
"0.7037824",
"0.6926366",
"0.68012416",
"0.6732481",
"0.6719113",
"0.6685765",
"0.6685765",
"0.6685765",
"0.6685765",
"0.6669708",
"0.6632687",
"0.6623837",
"0.65953994",
"0.65694636",
"0.6544564",
"0.6513855",
"0.6479822",
"0.64797056",
"0.6452391",
"0.6446137",
"0.6440331",
"0.6417251",
"0.6358492",
"0.6340917",
"0.6308185",
"0.62872314",
"0.6283348",
"0.62748",
"0.62583727",
"0.6255063",
"0.62546563",
"0.6201376",
"0.618346",
"0.61814576",
"0.61555535",
"0.6155187",
"0.6145225",
"0.612112",
"0.6107107",
"0.6104502",
"0.6064365",
"0.60535765",
"0.602179",
"0.59930885",
"0.598527",
"0.5976091",
"0.5970621",
"0.59607816",
"0.59307384",
"0.5929709",
"0.5907856",
"0.5902595",
"0.590118",
"0.5900156",
"0.5898104",
"0.58977723",
"0.5891257",
"0.5890334",
"0.5888483",
"0.58763933",
"0.58610064",
"0.58610064",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58476466",
"0.58378375",
"0.58249015",
"0.58200574",
"0.58194876",
"0.5811674",
"0.5800567",
"0.57958674",
"0.57924306",
"0.5789379",
"0.5759384",
"0.575808",
"0.5755191",
"0.57512176",
"0.5737421",
"0.5733814",
"0.57299733",
"0.57274497",
"0.5723351",
"0.5694687",
"0.56940514",
"0.5693453",
"0.56933266",
"0.5681886",
"0.5680585",
"0.5680585",
"0.5680585"
] |
0.0
|
-1
|
POST /steps POST /steps.json
|
def create
@testcase = Testcase.find(params[:testcase_id])
@step = @testcase.steps.new(step_params)
byebug
if @step.save
render :show, status: :created
else
render json: @step.errors, status: :unprocessable_entity
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to api_v1_step_url(@step), notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = Step.new(step_params) \n\n if @step.save\n render :show, status: :created, location: @step\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def create\n\n step_attributes = step_params\n fields_attributes = step_attributes.delete(\"fields\")\n\n @step = Step.new(step_attributes)\n @step.fields = Field.createFields(fields_attributes)\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = Step.new(params[:step])\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step.phase_template, notice: 'Step was successfully added.' }\n format.json { render json: @step, status: :created, location: @step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n \n @step = @quest.steps.new(params[:step])\n\n \n \n if @step.save\n redirect_to (quest_path(@quest)), notice: 'Step was successfully created.'\n\n else\n render action: \"new\" \n end\n end",
"def create\n @step = Step.new(params[:step])\n @step.test_case_id = params[:test_case_id].to_i\n\n respond_to do |format|\n if @step.save\n @step_activity = StepActivity.new(:activity_type => 'edit', :description => @step.description)\n @step_activity.user = current_user\n @step_activity.step = @step\n @step_activity.save!\n format.json { render :json => @step, :status => :created, :location => @step }\n format.html { redirect_to(project_test_case_path(@step.test_case.project, @step.test_case)) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @next_step = NextStep.new(params[:next_step])\n\n respond_to do |format|\n if @next_step.save\n format.html { redirect_to :back, notice: 'Next step was successfully created.' }\n format.json { render json: @next_step, status: :created, location: @next_step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @next_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @next_step = NextStep.new(next_step_params)\n\n respond_to do |format|\n if @next_step.save\n format.html { redirect_to @next_step, notice: 'Next step was successfully created.' }\n format.json { render :show, status: :created, location: @next_step }\n else\n format.html { render :new }\n format.json { render json: @next_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = @task.steps.build(params[:step])\n\n if @step.save\n redirect_to [@task,@step]\n else\n render :action => \"new\"\n end\n end",
"def create_steps(stage_steps)\n sequence = 1\n stage_steps.map do |stage_step|\n step = Step.new\n step.sequence = sequence\n\n begin\n action_name = stage_step['action']\n plugin = Cyclid.plugins.find(action_name, Cyclid::API::Plugins::Action)\n\n step_action = plugin.new(stage_step)\n raise if step_action.nil?\n rescue StandardError => ex\n # XXX Rescue an internal exception\n halt_with_json_response(404, INVALID_ACTION, ex.message)\n end\n\n # Serialize the object into the Step and store it in the database.\n step.action = Oj.dump(step_action)\n step.save!\n\n sequence += 1\n\n step\n end\n end",
"def create\n @step = Step.new(step_params)\n\n respond_to do |format|\n if @step.save\n format.js\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @taken_step = TakenStep.new(taken_step_params)\n\n respond_to do |format|\n if @taken_step.save\n format.html { redirect_to @taken_step, notice: 'Steps Taken was successfully created.' }\n format.json { render :show, status: :created, location: @taken_step }\n else\n format.html { render :new }\n format.json { render json: @taken_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = StepsTaken.new(step_params)\n\n if @step.save\n redirect_to @step, notice: 'Step was successfully created.'\n else\n render :new\n end\n end",
"def create\n @step = Step.new(params[:step])\n @test_case = TestCase.find(params[:test_case_id])\n @step.test_case_id = @test_case.id\n\n if @step.save\n flash[:notice] = \"Successfully created step.\"\n end\n respond_with @step\n end",
"def step_params\n params.require(:step).permit(:step_number, :points, :name, :quest_id, :answer, :body)\n end",
"def create\n @questionnaire = @participant.build_questionnaire(params[:questionnaire])\n @questionnaire.step = 1\n \n respond_to do |format|\n if @questionnaire.save\n format.html { redirect_to new_questionnaire_path }\n # format.json { render json: @questionnaire, status: :created, location: @questionnaire }\n else\n format.html { render \"questionnaires/steps/step0\" }\n # format.json { render json: @questionnaire.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @recipe = Recipe.find(params[:recipe_id])\n @step = @recipe.steps.new(step_params)\n\n if @step.save\n redirect_to @recipe, notice: 'Step was successfully created.'\n else\n render :new\n end\n end",
"def create\n \t@step = @tutorial.steps.build(params[:step])\n authorize! :create, @step\n respond_to do |format|\n if @step.save\n format.html { redirect_to(@tutorial, :notice => 'Step was successfully created.') }\n format.xml { render :xml => @tutorial, :status => :created, :location => @tutorial }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n \n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def create\n @step_activity = StepActivity.new(params[:step_activity])\n\n respond_to do |format|\n if @step_activity.save\n format.html { redirect_to @step_activity, notice: 'Step activity was successfully created.' }\n format.json { render json: @step_activity, status: :created, location: @step_activity }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step_activity.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @steps_log = StepsLog.new(params[:steps_log])\n\n respond_to do |format|\n if @steps_log.save\n format.html { redirect_to @steps_log, notice: 'Steps log was successfully created.' }\n format.json { render json: @steps_log, status: :created, location: @steps_log }\n else\n format.html { render action: \"new\" }\n format.json { render json: @steps_log.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @goal_step = GoalStep.new(goal_step_params)\n\n respond_to do |format|\n if @goal_step.save\n format.html { redirect_to @goal_step, notice: \"Goal step was successfully created.\" }\n format.json { render :show, status: :created, location: @goal_step }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @goal_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step_m = StepM.new(step_m_params)\n\n respond_to do |format|\n if @step_m.save\n format.html { redirect_to @step_m, notice: 'Step m was successfully created.' }\n format.json { render :show, status: :created, location: @step_m }\n else\n format.html { render :new }\n format.json { render json: @step_m.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lead_step = LeadStep.new(params[:lead_step])\n\n respond_to do |format|\n if @lead_step.save\n format.html { redirect_to @lead_step, notice: 'Lead step was successfully created.' }\n format.json { render json: @lead_step, status: :created, location: @lead_step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lead_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n \n @steps = @quest.steps\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def create\n @user_step = UserStep.new(user_step_params)\n\n respond_to do |format|\n if @user_step.save\n format.html { redirect_to @user_step, notice: 'User step was successfully created.' }\n format.json { render action: 'show', status: :created, location: @user_step }\n else\n format.html { render action: 'new' }\n format.json { render json: @user_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project = Project.find(params[:project_id])\n position = Step.joins(:projects).where('projects.id = ?', @project.id).maximum('steps.position')\n position = 1 unless position\n @step = @project.steps.create(params[:step])\n @step.position = position - 1\n respond_to do |format|\n if @step.save\n ProjectMailer.notify_step_created(@step, current_user).deliver\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json do\n render json: @step, status: :created\n end\n else\n format.html { render action: \"new\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(\n :milestone_id, :reached_at, :notes\n )\n end",
"def create\n\n # params[:post][:step4] = \"TESTING4\";\n params[:post][:steps] = \"\"\n \n if params[:post][:step]\n params[:post][:step].each do |k, v|\n if params[:post][:step].length == k.to_i\n params[:post][:steps] << v\n else\n params[:post][:steps] << v + '|'\n end\n end\n params[:post].delete(\"step\")\n end\n\n #return render :text => params[:post]\n @post = current_user.posts.create(params[:post])\n\n if @post.save\n flash[:success] = 'Post was successfully created.'\n redirect_to @post\n else\n render :new\n end\n\n end",
"def create\n @step_type = StepType.new(params[:step_type])\n\n respond_to do |format|\n if @step_type.save\n format.html { redirect_to @step_type, notice: 'Step type was successfully created.' }\n format.json { render json: @step_type, status: :created, location: @step_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @roadmap = Roadmap.find(params[:roadmap_id])\n @roadmap_step = @roadmap.roadmap_steps.create(roadmap_step_params)\n #@roadmap_step = RoadmapStep.new(roadmap_step_params)\n\n respond_to do |format|\n if @roadmap_step.save\n format.html { redirect_to @roadmap, notice: 'Roadmap step was successfully created.' }\n format.json { render :show, status: :created, location: @roadmap_step }\n else\n format.html { render :new }\n format.json { render json: @roadmap_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @steplog = Steplog.new(steplog_params)\n\n respond_to do |format|\n if @steplog.save\n format.html { redirect_to @steplog, notice: 'Steplog was successfully created.' }\n format.json { render :show, status: :created, location: @steplog }\n else\n format.html { render :new }\n format.json { render json: @steplog.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @step = Step.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def step_params\n params.require(:step).permit(:recipe_id, :number, :description, :timer)\n end",
"def create\n @step = Step.new(step_params)\n @step.shop_id = session[:shopify]\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to @step, notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n # ensure that the submitted parent_id actually exists\n if !Step.exists?(params[:step][:parent_id].to_i)\n logger.debug \"Step doesn't exist!\"\n if @project.steps.last\n params[:step][:parent_id] = @project.steps.last.id\n else\n params[:step][:parent_id] = nil\n end\n end\n\n if params[:step][:pin] && params[:step][:pin].empty?\n params[:step][:pin] = nil\n end\n\n @step = @project.steps.build(params[:step])\n authorize! :create, @step \n\n if params[:step][:position]\n @step.position = params[:step][:position]\n else\n @step.position = @numSteps\n end\n \n respond_to do |format|\n if @step.save\n\n # update corresponding collections\n @step.project.collections.each do |collection|\n collection.touch\n end\n \n # create an edit entry\n Edit.create(:user_id => current_user.id, :step_id => @step.id, :project_id => @project.id)\n\n # check whether project is published\n if @project.public? || @project.privacy.blank?\n @project.set_published(current_user.id, @project.id, @step.id)\n end\n\n @project.set_built\n\n # update the project updated_at date\n @project.touch\n\n # update the user last_updated_at date\n current_user.touch\n\n @step.update_attributes(:published_on => @step.created_at)\n\n # create a public activity for any added question\n if @step.question\n Rails.logger.debug(\"created new question\")\n @step.question.create_activity :create, owner: current_user, primary: true\n end\n\n # log the creation of a new step\n @project.delay.log\n\n format.html { \n\n # update all images with new step id\n new_step_images = @project.images.where(\"step_id = -1\")\n new_step_images.each do |image|\n image.update_attributes(:saved => true)\n image.update_attributes(:step_id => @step.id)\n end\n\n # update all videos with new step id\n new_step_videos = @project.videos.where(\"step_id = -1\")\n new_step_videos.each do |video|\n video.update_attributes(:saved=>true)\n video.update_attributes(:step_id=> @step.id)\n end\n\n # push project to village if it doesn't already exist\n if @project.village_id.blank? && current_user.from_village? && @project.public? && !access_token.blank?\n create_village_project\n elsif !@project.village_id.blank? && !access_token.blank?\n update_village_project\n end\n \n redirect_to project_steps_path(@project), :flash=>{:createdStep => @step.id}\n \n }\n \n format.json { render :json => @step }\n else\n Rails.logger.debug(@step.errors.inspect)\n format.html { render :action => \"new\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @selection = Selection.find(params[:selection_id])\n @step = @selection.steps.new(params[:step])\n\n respond_to do |format|\n if @step.save\n format.html { redirect_to selection_step_path(@step.selection, @step), notice: 'Step was successfully created.' }\n format.json { render json: @step, status: :created, location: @step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @pre_step = PreStep.new(params[:pre_step])\n\n respond_to do |format|\n if @pre_step.save\n format.html { redirect_to @pre_step, notice: 'Pre step was successfully created.' }\n format.json { render json: @pre_step, status: :created, location: @pre_step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pre_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(:post_id, :name)\n end",
"def step_params\n params.require(:step).permit(:location, :lon, :lat, :arrive_on, :stay, :trip_id)\n end",
"def create\n @step_scenario = StepScenario.new(step_scenario_params)\n @step_scenario.scenario_id = current_scenario.id\n\n respond_to do |format|\n if @step_scenario.save\n format.html { redirect_to scenario_path(current_scenario), notice: \"Passo do cenário cadastrado com sucesso!\" }\n format.json { render :show, status: :created, location: @step_scenario }\n else\n format.html { render :new }\n format.json { render json: @step_scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @process_step = ProcessStep.new(process_step_params)\n\n respond_to do |format|\n if @process_step.save\n format.html { redirect_to @process_step, notice: 'Process step was successfully created.' }\n format.json { render :show, status: :created, location: @process_step }\n else\n format.html { render :new }\n format.json { render json: @process_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step2 = Step2.new(params[:step2])\n\n respond_to do |format|\n if @step2.save\n format.html { redirect_to @step2, notice: 'Step2 was successfully created.' }\n format.json { render json: @step2, status: :created, location: @step2 }\n else\n format.html { render action: \"new\" }\n format.json { render json: @step2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def roadmap_step_params\n params.require(:roadmap_step).permit(:step)\n end",
"def create\n @post = Post.find(params[:post_id])\n @step = Step.new(:post=>@post)\n secureEnter @step\n @step = Step.create(step_params)\n @step.content = \"\"\n respond_to do |format|\n if @step.save\n format.html { redirect_to edit_post_path(@post.id), notice: 'Step was successfully created.' }\n format.json { render :show, status: :created, location: @step }\n else\n format.html { render :new }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @project_step = ProjectStep.new(project_step_params)\n\n respond_to do |format|\n if @project_step.save\n format.html { redirect_to @project_step, notice: 'Project step was successfully created.' }\n format.json { render :show, status: :created, location: @project_step }\n else\n format.html { render :new }\n format.json { render json: @project_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @daily_step = DailyStep.new(daily_step_params)\n\n respond_to do |format|\n if @daily_step.save\n format.html { redirect_to @daily_step, notice: 'Daily step was successfully created.' }\n format.json { render :show, status: :created, location: @daily_step }\n else\n format.html { render :new }\n format.json { render json: @daily_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def steps=(new_value)\n @steps = new_value\n end",
"def step_params\n params.require(:step).permit(:name, :time)\n end",
"def step_params\n params.require(:step).permit(:name, :step_url, :html, :collection_id, :next_step_id, :only_customer, :is_custom)\n end",
"def new\n @next_step = NextStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @next_step }\n end\n end",
"def step_params\n params.require(:step).permit(:number, :description, :locator, :skip, :testcase_id, :actionValue)\n end",
"def create\n @cooking_step = CookingStep.new(cooking_step_params)\n\n respond_to do |format|\n if @cooking_step.save\n format.html { redirect_to @cooking_step, notice: 'Cooking step was successfully created.' }\n format.json { render :show, status: :created, location: @cooking_step }\n else\n format.html { render :new }\n format.json { render json: @cooking_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(:step_number, :pattern_step, :counter_open, :row_count, :rep_count, :pattern_id)\n end",
"def create\n @step = Step.new(step_params)\n @step.screenshot = step_params[:screenshot]\n respond_to do |format|\n if @step.save\n if !params.has_key?(:bookmarklet)\n format.html { redirect_to assignment_path(@step.assignment.id)+\"/\"+@step.user_id.to_s+\"/\"+@step.id.to_s}\n else\n format.html { redirect_to bookmarkletSuccess_url}\n end\n else\n flash[:errors] = @step.errors\n format.html { redirect_to assignment_path(@step.assignment.id)+\"/\"+@step.user_id.to_s }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def next_step_params\n params.require(:next_step).permit(:goal_id, :next_step, :responsible_party, :due_date, :completed)\n end",
"def create\n @step_command = StepCommand.new(step_command_params)\n\n respond_to do |format|\n if @step_command.save\n format.html { redirect_to @step_command, notice: 'Step command was successfully created.' }\n format.json { render :show, status: :created, location: @step_command }\n else\n format.html { render :new }\n format.json { render json: @step_command.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n step_definition_attributes = step_definition_params\n field_definitions_attributes = step_definition_attributes.delete(\"field_definitions\")\n\n @step_definition = StepDefinition.new(step_definition_attributes)\n @step_definition.field_definitions = FieldDefinition.createFieldDefinitions(field_definitions_attributes)\n\n respond_to do |format|\n if @step_definition.save\n format.html { redirect_to @step_definition, notice: 'Step definition was successfully created.' }\n format.json { render :show, status: :created, location: @step_definition }\n else\n format.html { render :new }\n format.json { render json: @step_definition.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step_comment = StepComment.new(step_comment_params)\n\n respond_to do |format|\n if @step_comment.save\n format.html { redirect_to @step_comment, notice: 'Step comment was successfully created.' }\n format.json { render :show, status: :created, location: @step_comment }\n else\n format.html { render :new }\n format.json { render json: @step_comment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @step = @task.steps.build\n end",
"def step_params\n params.require(:step).permit(:instruction)\n end",
"def create\n @step_six = StepSix.new(step_six_params)\n\n respond_to do |format|\n if @step_six.save\n format.html { redirect_to \"/delivery_flows\", notice: 'Step six was successfully created.' }\n format.json { render :show, status: :created, location: @step_six }\n else\n format.html { render :new }\n format.json { render json: @step_six.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @steps_log = StepsLog.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @steps_log }\n end\n end",
"def index\n @steps = Step.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end",
"def create\n @tc_detail_step = TcDetailStep.new(params[:tc_detail_step])\n\n respond_to do |format|\n if @tc_detail_step.save\n format.html { redirect_to @tc_detail_step, notice: 'Tc detail step was successfully created.' }\n format.json { render json: @tc_detail_step, status: :created, location: @tc_detail_step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tc_detail_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n # puts \"---------------------\"\n # puts workflow_params.to_json\n\n # workflow_attributes = workflow_params\n # step_definitions_attributes = workflow_attributes.delete(\"step_definitions\")\n\n # @workflow = Workflow.new(workflow_attributes)\n\n # @workflow.step_definitions = StepDefinition.createStepDefinitions(step_definitions_attributes)\n\n @workflow = Workflow.new(workflow_params)\n respond_to do |format|\n if @workflow.save\n format.html { redirect_to @workflow, notice: 'Workflow was successfully created.' }\n format.json { render :show, status: :created, location: @workflow }\n else\n format.html { render :new }\n format.json { render json: @workflow.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @step_activity = StepActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_activity }\n end\n end",
"def create\n @wizard = Wizard.new(params[:wizard])\n\n respond_to do |format|\n if @wizard.save\n format.html { redirect_to @wizard, notice: 'Wizard was successfully created.' }\n format.json { render json: @wizard, status: :created, location: @wizard }\n else\n format.html { render action: \"new\" }\n format.json { render json: @wizard.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @methodstep = Methodstep.new(params[:methodstep])\n\n respond_to do |format|\n if @methodstep.save\n flash[:notice] = 'Methodstep was successfully created.'\n format.html { redirect_to(@methodstep) }\n format.xml { render :xml => @methodstep, :status => :created, :location => @methodstep }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @methodstep.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @post = Post.find(params[:id])\n\n params[:post][:steps] = \"\"\n if params[:post][:step] \n params[:post][:step].each do |k, v|\n if params[:post][:step].length == k.to_i\n params[:post][:steps] << v\n else\n params[:post][:steps] << v + '|'\n end\n end\n end\n params[:post].delete(\"step\")\n\n if @post.update_attributes(params[:post])\n flash[:success] = 'Post was successfully created.'\n redirect_to @post \n else\n render action: \"edit\"\n end\n end",
"def create\n @category_step = CategoryStep.new(category_step_params)\n\n respond_to do |format|\n if @category_step.save\n format.html { redirect_to @category_step, notice: 'Category step was successfully created.' }\n format.json { render :show, status: :created, location: @category_step }\n else\n format.html { render :new }\n format.json { render json: @category_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @step_type = StepType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step_type }\n end\n end",
"def new\n @step = Step.new :phase_template_id => params[:phase_template_id]\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end",
"def create\n @book_step = BookStep.new(params[:book_step])\n\n respond_to do |format|\n if @book_step.save\n format.html { redirect_to @book_step, notice: 'Book step was successfully created.' }\n format.json { render json: @book_step, status: :created, location: @book_step }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(:title, :position, :board_id)\n end",
"def step(steps, force = false)\n #This is a stub, used for indexing\n end",
"def new\n @step = @guide.steps.new(params[:step])\n end",
"def new\n @trip = Trip.new\n @trip.steps.build\n end",
"def create\n @active_workflow_step = ActiveWorkflowStep.new(active_workflow_step_params)\n\n respond_to do |format|\n if @active_workflow_step.save\n format.html { redirect_to @active_workflow_step, notice: 'Active workflow step was successfully created.' }\n format.json { render :show, status: :created, location: @active_workflow_step }\n else\n format.html { render :new }\n format.json { render json: @active_workflow_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @work_plan = WorkPlan.find(params[:work_plan_id])\n @work_step = WorkStep.new(work_step_params)\n @work_step.work_plan=@work_plan\n\n respond_to do |format|\n if @work_step.save\n format.html { redirect_to @work_plan, notice: 'Work step was successfully created.' }\n format.json { render :show, status: :created, location: @work_plan }\n else\n format.html { render :new }\n format.json { render json: @work_plan.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @post = Post.new\n session[:step] = @post.step = Post::STEPS.first\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @post }\n end\n end",
"def create\n @step_seven = StepSeven.new(step_seven_params)\n\n respond_to do |format|\n if @step_seven.save\n format.html { redirect_to \"/delivery_flows\", notice: 'Step seven was successfully created.' }\n format.json { render :show, status: :created, location: @step_seven }\n else\n format.html { render :new }\n format.json { render json: @step_seven.errors, status: :unprocessable_entity }\n end\n end\n end",
"def step_params\n params.require(:step).permit(:stepDate, :stepAmount)\n end",
"def goal_step_params\n params.require(:goal_step).permit(:name)\n end",
"def new\n @pre_step = PreStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pre_step }\n end\n end",
"def create\n @step_four = StepFour.new(step_four_params)\n\n respond_to do |format|\n if @step_four.save\n format.html { redirect_to \"/delivery_flows\", notice: 'Step four was successfully created.' }\n format.json { render :show, status: :created, location: @step_four }\n else\n format.html { render :new }\n format.json { render json: @step_four.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @step = @trip.steps.new(step_params)\n\n @locations = JSON params['locations']\n\n respond_to do |format|\n if @step.valid?\n if @step.save\n if @step.have_updated_forecast? # return true or false\n format.html { redirect_to @trip, notice: 'Step was successfully created. Updated forecast available.' }\n format.json { render action: 'show', status: :created, location: @step }\n else\n if @step.should_make_forecast?\n if @step.make_forecast == true # return true , false or nil\n format.html { redirect_to @trip, notice: 'Step was successfully created. New forecast requested.' }\n format.json { render action: 'show', status: :created, location: @step }\n else @step.make_forecast == false\n format.html { \n flash.now[:notice] = \"Cannot make forecast for #{@step.location}. City not found!\" \n render action: 'new' }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n else\n format.html { redirect_to @trip, notice: 'Step was successfully created. No forecast available for the arrival.' }\n format.json { render action: 'show', status: :created, location: @step } \n end \n end\n else\n format.html { render action: 'new' }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n else\n format.html { \n flash.now[:notice] = \"Cannot make forecast for #{@step.location}. Arrive on should be in the past!\" \n render action: 'new' }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n \n end\n\n end",
"def step_params\n params.require(:step).permit(:user_id, :assignment_id, :title, :url, :justification, :parent_id, :lft, :rgt, :favorite, :document, :screenshot)\n end",
"def taken_step_params\n params.require(:taken_step).permit(:count, :done_on)\n end",
"def create\n @goal = Goal.new(params[:goal])\n @goal.set_goal_user current_user\n\n # on the wizard path, steps guarantee that this goal preceeds the plan and reward. Create empty objects for next step.\n is_wizard = (params[:user_context] == 'wizard')\n\n respond_to do |format|\n if @goal.save\n if is_wizard \n @reward = @goal.plan.reward\n puts \"reward #{@reward}\"\n format.html { render action: \"wizard_prize\" }\n else\n format.html { redirect_to @goal, notice: 'Goal was successfully created.' }\n end\n format.json { render json: @goal, status: :created, location: @goal }\n else\n format.html { render action: \"new\" }\n format.json { render json: @goal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def steps\n steps_keywords = %w(Given When Then And But)\n nsteps = 0\n @steps = []\n while true\n print \"Add step [Y/n]: \"\n choice = gets\n if choice.downcase.strip != \"n\"\n puts \"Step #{nsteps +1}:\"\n step = gets.capitalize\n init_step_word = step.split(' ').first\n if steps_keywords.include?(init_step_word)\n @steps << step\n nsteps = nsteps ++ 1\n else\n puts \"Error: #{init_step_word} unsupported initial value\"\n puts \"Use only #{steps_keywords} keywords\"\n end\n elsif choice.downcase.strip == \"n\"\n break\n else\n \"please enter a valid choice.\"\n end\n end\n write_feature\n end",
"def create\n @project_step_m = ProjectStepM.new(project_step_m_params)\n\n respond_to do |format|\n if @project_step_m.save\n format.html { redirect_to @project_step_m, notice: 'Project step m was successfully created.' }\n format.json { render :show, status: :created, location: @project_step_m }\n else\n format.html { render :new }\n format.json { render json: @project_step_m.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @stepsix = Stepsix.new(params[:stepsix])\n\n respond_to do |format|\n if @stepsix.save\n format.html { redirect_to(root_path, :notice => 'Stepsix was successfully created.') }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @stepsix.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @step2 = Step2.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step2 }\n end\n end",
"def create\n @project_step = ProjectStep.new(params[:project_step])\n\n respond_to do |format|\n if @project_step.save\n flash[:notice] = 'ProjectStep was successfully created.'\n format.html { redirect_to(@project_step) }\n format.xml { render :xml => @project_step, :status => :created, :location => @project_step }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @project_step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def getsteps\n\t\t@hide_menu = true\n\n puts \"In Steps\"\n recId = params['query'].inspect\n #this is the link to the API\n url = \"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/\" + recId[1..-2] + \"/analyzedInstructions?stepBreakdown=true\"\n stepss = Unirest.get url,\n headers:{\n \"X-Mashape-Key\" => \"UpZLcnOR83mshtXvuIOPFXBkfhn5p1UWi1ejsnsTLWoVXrOppm\",\n \"Accept\" => \"application/json\"\n }\n allSteps = stepss.body\n\n recSteps = Hash.new\n\n counter = 1\n #this is how the recipe information is formatted\n allSteps.each do |key|\n key.each do |key2,steps|\n if(key2.eql? \"steps\")\n steps.each do |step|\n step.each do |key3, lastStep|\n if(key3.eql? \"step\")\n recSteps[counter] = lastStep\n counter += 1\n #this gives each step a number, for ease of use\n end\n end\n end\n end\n end\n end\n puts recSteps\n\n @recipeData = recSteps\n render template: \"recipes/data3\"\n end",
"def create\n @step_three = StepThree.new(step_three_params)\n\n respond_to do |format|\n if @step_three.save\n format.html { redirect_to \"/delivery_flows\", notice: 'Step three was successfully created.' }\n format.json { render :show, status: :created, location: @step_three }\n else\n format.html { render :new }\n format.json { render json: @step_three.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @lead_step = LeadStep.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lead_step }\n end\n end",
"def create\n @step_ingredient = StepIngredient.new(params[:step_ingredient])\n\n respond_to do |format|\n if @step_ingredient.save\n format.html { redirect_to(@step_ingredient, :notice => 'Step ingredient was successfully created.') }\n format.xml { render :xml => @step_ingredient, :status => :created, :location => @step_ingredient }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @step_ingredient.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
[
"0.727691",
"0.71616596",
"0.71529734",
"0.70521736",
"0.6979661",
"0.69371253",
"0.6862949",
"0.6795791",
"0.6771561",
"0.67710626",
"0.67408836",
"0.6711147",
"0.66153246",
"0.6606931",
"0.65982497",
"0.657702",
"0.6566822",
"0.65651876",
"0.65401566",
"0.6530762",
"0.649408",
"0.64927083",
"0.6491112",
"0.6478327",
"0.64471287",
"0.6417116",
"0.63935536",
"0.636563",
"0.6365319",
"0.63594973",
"0.63227475",
"0.6304661",
"0.6301846",
"0.62930876",
"0.62568",
"0.6240614",
"0.6222607",
"0.61880636",
"0.6184948",
"0.6174127",
"0.61741155",
"0.6153926",
"0.61525124",
"0.6107171",
"0.6098244",
"0.60924816",
"0.6087303",
"0.6065637",
"0.60524297",
"0.60450226",
"0.60319155",
"0.6013421",
"0.6007949",
"0.59917873",
"0.59880096",
"0.5983622",
"0.5982921",
"0.5969508",
"0.5967243",
"0.5957204",
"0.59458965",
"0.59259635",
"0.5911674",
"0.59083736",
"0.5902028",
"0.58979064",
"0.58832395",
"0.585192",
"0.5848436",
"0.5835067",
"0.58217067",
"0.58191234",
"0.5804367",
"0.5794485",
"0.57771546",
"0.5777136",
"0.57763344",
"0.5770267",
"0.5758988",
"0.57467693",
"0.5741761",
"0.57361025",
"0.5728702",
"0.5716893",
"0.5704748",
"0.57013357",
"0.570067",
"0.56944174",
"0.56894654",
"0.5687193",
"0.5686485",
"0.56837076",
"0.5675653",
"0.56649107",
"0.5659572",
"0.56503814",
"0.5648317",
"0.5641888",
"0.5634713",
"0.5631234"
] |
0.66162527
|
12
|
PATCH/PUT /steps/1 PATCH/PUT /steps/1.json
|
def update
if @step.update(step_params)
render :show, status: :ok
else
render json: @step.errors, status: :unprocessable_entity
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update\n @step = @guide.steps.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to [@guide, @step], notice: 'Step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = Step.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to @step, notice: 'Step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.html { redirect_to api_v1_step_url(@step), notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = Step.find(params[:id])\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to @step, notice: 'Step was successfully updated.' }\n format.json { render :json => {:message => \"Success\"} }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = Step.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n @step_activity = StepActivity.new(:activity_type => 'edit', :description => @step.description)\n @step_activity.user = current_user\n @step_activity.step = @step\n @step_activity.save!\n format.html { redirect_to(project_test_case_path(@step.test_case.project, @step.test_case)) }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to [@task,@step], notice: 'Step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.html { redirect_to @step, notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.html { redirect_to @step, notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @step.update(step_params)\n render :show, status: :ok, location: @step\n else\n render json: @step.errors, status: :unprocessable_entity\n end\n end",
"def update\n @step = Step.find(params[:id])\n\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to selection_step_path, notice: 'Step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n step_attributes = step_params\n fields_attributes = step_attributes.delete(\"fields\")\n\n Field.updateFields(fields_attributes)\n\n respond_to do |format|\n if @step.update(step_attributes)\n format.html { redirect_to @step, notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n @step = Step.find(params[:id])\n\n if @step.update_attributes(params[:step])\n redirect_to (quest_path(@quest)), notice: 'Step was successfully updated.'\n\n else\n render action: \"edit\" \n end\n \n \n \n end",
"def update\n @next_step = NextStep.find(params[:id])\n\n respond_to do |format|\n if @next_step.update_attributes(params[:next_step])\n format.html { redirect_to :back, notice: 'Next step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @next_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.html { redirect_to assignment_path(@step.assignment.id)+\"/\"+@step.user_id.to_s+\"/\"+@step.id.to_s}\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step_activity = StepActivity.find(params[:id])\n\n respond_to do |format|\n if @step_activity.update_attributes(params[:step_activity])\n format.html { redirect_to @step_activity, notice: 'Step activity was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step_activity.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = Step.find(params[:id])\n @test_case = TestCase.find(params[:test_case_id])\n @step.test_case_id = @test_case.id\n\n if @step.update_attributes(params[:step])\n flash[:notice] = 'Step was successfully updated.'\n end\n respond_with @step\n end",
"def update\n @pre_step = PreStep.find(params[:id])\n\n respond_to do |format|\n if @pre_step.update_attributes(params[:pre_step])\n format.html { redirect_to @pre_step, notice: 'Pre step was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pre_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n # workflow_attributes = workflow_params\n # step_definitions_attributes = workflow_attributes.delete(\"step_definitions\")\n\n # StepDefinition.updateStepDefinitions(step_definitions_attributes)\n\n respond_to do |format|\n if @workflow.update(workflow_params)\n format.html { redirect_to @workflow, notice: 'Workflow was successfully updated.' }\n format.json { render :show, status: :ok, location: @workflow }\n else\n format.html { render :edit }\n format.json { render json: @workflow.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = Step.find(params[:id])\n @tutorial = @step.tutorial\n authorize! :update, @step\n respond_to do |format|\n if @step.update_attributes(params[:step])\n format.html { redirect_to(@tutorial, :notice => 'Step was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @step2 = Step2.find(params[:id])\n\n respond_to do |format|\n if @step2.update_attributes(params[:step2])\n format.html { redirect_to @step2, notice: 'Step2 was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @questionnaire = current_questionnaire\n @questionnaire.step += 1\n\n respond_to do |format|\n if @questionnaire.update_attributes(params[:questionnaire])\n format.html { redirect_to new_questionnaire_path }\n # format.json { head :no_content }\n else\n format.html { render \"questionnaires/steps/step#{@questionnaire.step - 1}\" }\n # format.json { render json: @questionnaire.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @taken_step.update(taken_step_params)\n format.html { redirect_to @taken_step, notice: 'Steps taken was successfully updated.' }\n format.json { render :show, status: :ok, location: @taken_step }\n else\n format.html { render :edit }\n format.json { render json: @taken_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @next_step.update(next_step_params)\n format.html { redirect_to @next_step, notice: 'Next step was successfully updated.' }\n format.json { render :show, status: :ok, location: @next_step }\n else\n format.html { render :edit }\n format.json { render json: @next_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step_type = StepType.find(params[:id])\n\n respond_to do |format|\n if @step_type.update_attributes(params[:step_type])\n format.html { redirect_to @step_type, notice: 'Step type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @step_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_three.update(step_three_params)\n format.html { redirect_to @step_three, notice: 'Step three was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_three }\n else\n format.html { render :edit }\n format.json { render json: @step_three.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @stepone.update(stepone_params)\n format.html { redirect_to mainpage_path(@stepone.mainpage), notice: 'Stepone was successfully updated.' }\n format.json { render :show, status: :ok, location: @stepone }\n else\n format.html { render :edit }\n format.json { render json: @stepone.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @steps_log = StepsLog.find(params[:id])\n\n respond_to do |format|\n if @steps_log.update_attributes(params[:steps_log])\n format.html { redirect_to @steps_log, notice: 'Steps log was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @steps_log.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step.update(step_params)\n format.js\n format.html { redirect_to home_path, notice: 'Step was successfully updated.' }\n format.json { render :show, status: :ok, location: @step }\n else\n format.html { render :edit }\n format.json { render json: @step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_m.update(step_m_params)\n format.html { redirect_to @step_m, notice: 'Step m was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_m }\n else\n format.html { render :edit }\n format.json { render json: @step_m.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @user_step.update(user_step_params)\n format.html { redirect_to @user_step, notice: 'User step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_scenario.update(step_scenario_params)\n format.html { redirect_to scenario_path(current_scenario), notice: \"Passo do cenário atualizado com sucesso!\" }\n format.json { render :show, status: :ok, location: @step_scenario }\n else\n format.html { render :edit }\n format.json { render json: @step_scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @goal_step.update(goal_step_params)\n format.html { redirect_to @goal_step, notice: \"Goal step was successfully updated.\" }\n format.json { render :show, status: :ok, location: @goal_step }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @goal_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @active_workflow_step.update(active_workflow_step_params)\n format.html { redirect_to @active_workflow_step, notice: 'Active workflow step was successfully updated.' }\n format.json { render :show, status: :ok, location: @active_workflow_step }\n else\n format.html { render :edit }\n format.json { render json: @active_workflow_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lead_step = LeadStep.find(params[:id])\n\n respond_to do |format|\n if @lead_step.update_attributes(params[:lead_step])\n format.html { redirect_to @lead_step, notice: 'Lead step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lead_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project_step.update(project_step_params)\n format.html { redirect_to @project_step, notice: 'Project step was successfully updated.' }\n format.json { render :show, status: :ok, location: @project_step }\n else\n format.html { render :edit }\n format.json { render json: @project_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_six.update(step_six_params)\n format.html { redirect_to @step_six, notice: 'Step six was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_six }\n else\n format.html { render :edit }\n format.json { render json: @step_six.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @post = Post.find(params[:id])\n\n params[:post][:steps] = \"\"\n if params[:post][:step] \n params[:post][:step].each do |k, v|\n if params[:post][:step].length == k.to_i\n params[:post][:steps] << v\n else\n params[:post][:steps] << v + '|'\n end\n end\n end\n params[:post].delete(\"step\")\n\n if @post.update_attributes(params[:post])\n flash[:success] = 'Post was successfully created.'\n redirect_to @post \n else\n render action: \"edit\"\n end\n end",
"def update\n respond_to do |format|\n if @cooking_step.update(cooking_step_params)\n format.html { redirect_to @cooking_step, notice: 'Cooking step was successfully updated.' }\n format.json { render :show, status: :ok, location: @cooking_step }\n else\n format.html { render :edit }\n format.json { render json: @cooking_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @book_step = BookStep.find(params[:id])\n\n respond_to do |format|\n if @book_step.update_attributes(params[:book_step])\n format.html { redirect_to @book_step, notice: 'Book step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @book_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @work_step.update(work_step_params)\n format.html { redirect_to @work_plan, notice: 'Work step was successfully updated.' }\n format.json { render :show, status: :ok, location: @work_plan }\n else\n format.html { render :edit }\n format.json { render json: @work_plan.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @process_step.update(process_step_params)\n format.html { redirect_to @process_step, notice: 'Process step was successfully updated.' }\n format.json { render :show, status: :ok, location: @process_step }\n else\n format.html { render :edit }\n format.json { render json: @process_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @use_case = UseCase.find(params[:id])\n @use_case.data = params[:data].to_json\n\n respond_to do |format|\n if @use_case.update_attributes(params[:use_case])\n\n if params[:subaction]==\"step\"\n format.html { redirect_to requirements_project_use_case_path(@use_case.project, @use_case, :type=>\"step\"), notice: 'Use case was successfully updated.' }\n else\n format.html { redirect_to project_use_case_path(@project, @use_case), notice: 'Use case was successfully updated.' }\n end\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @use_case.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = @project.steps.find_by_position(params[:id])\n authorize! :update, @step \n\n # update corresponding collections\n @step.project.collections.each do |collection|\n collection.touch\n end\n \n @step.images.each do |image|\n image.update_attributes(:saved => true)\n end\n\n # remove question if question description is empty\n if params[:step][:question_attributes] && params[:step][:question_attributes][:description].length == 0 && @step.question\n @step.question.destroy\n end\n\n if params[:step][:published_on_date]\n date = params[:step][:published_on_date]\n logger.debug \"date: #{date}\"\n time = params[:step][:published_on_time]\n # retain the same seconds as the original published_on date\n time.insert 5, \":\" + @step.published_on.strftime(\"%S\")\n # logger.debug \"time: #{time}\"\n timeZone = params[:step][:timeZone]\n # logger.debug \"timeZone: #{timeZone}\"\n dateTime = date + \" \" + time + \" \" + timeZone\n # logger.debug \"dateTime: #{dateTime}\"\n dateTime = DateTime.strptime(dateTime, '%m/%d/%Y %I:%M:%S %p %Z')\n # logger.debug \"datetime: #{dateTime}\"\n \n params[:step][:published_on] = dateTime\n params[:step].delete :'published_on_date'\n params[:step].delete :\"published_on_time\"\n params[:step].delete :timeZone\n end\n\n # update the project \n @project.touch\n\n # update the user last updated date\n current_user.touch\n\n # remove any design attributes if they contain an ID that doesn't exist (the file had been removed)\n if params[:step][:design_files_attributes]\n params[:step][:design_files_attributes].values.each do |design_file|\n if DesignFile.exists?(design_file['id']) == false\n design_file.delete :id\n end\n end\n end\n \n respond_to do |format|\n\n if @step.update_attributes(params[:step])\n \n # clear label color if user didn't select color\n if @step.label == false\n @step.update_column(\"label_color\", nil)\n end\n\n # clear edit\n edit = Edit.where(\"user_id = ? AND step_id = ?\", current_user.id, @step.id).first\n edit.update_attributes(:started_editing_at => nil)\n if edit.project_id.blank?\n edit.update_attributes(:project_id => @project.id)\n end\n \n # check whether project is published\n if @project.public? || @project.privacy.blank?\n @project.set_published(current_user.id, @project.id, @step.id)\n end\n\n # check and set built attribute of project\n @project.set_built\n\n # create a public activity for any questions associated with the step if it doesn't already exist\n if @step.question && !PublicActivity::Activity.where(:trackable_type => \"Question\").where(:trackable_id => @step.question.id).exists?\n @step.question.create_activity :create, owner: current_user, primary: true\n end\n\n # create project on the village if the current user is a village user and the project doesn't already exist\n if @project.village_id.blank? && current_user.from_village? && !access_token.blank? && @project.public?\n create_village_project\n elsif !@project.village_id.blank? && !access_token.blank?\n update_village_project\n end\n\n format.html { \n redirect_to project_steps_path(@project), :notice => 'Step was successfully updated.', :flash => {:createdStep => @step.id} \n }\n format.json { head :no_content }\n else\n Rails.logger.info(@step.errors.inspect)\n format.html { render :action => \"edit\" }\n format.json { render :json => @step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_seven.update(step_seven_params)\n format.html { redirect_to @step_seven, notice: 'Step seven was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_seven }\n else\n format.html { render :edit }\n format.json { render json: @step_seven.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_command.update(step_command_params)\n format.html { redirect_to @step_command, notice: 'Step command was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_command }\n else\n format.html { render :edit }\n format.json { render json: @step_command.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @tc_detail_step = TcDetailStep.find(params[:id])\n\n respond_to do |format|\n if @tc_detail_step.update_attributes(params[:tc_detail_step])\n format.html { redirect_to @tc_detail_step, notice: 'Tc detail step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tc_detail_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @stepsix = Stepsix.find(params[:id])\n\n respond_to do |format|\n if @stepsix.update_attributes(params[:stepsix])\n format.html { redirect_to(root_path, :notice => 'Stepsix was successfully updated.') }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @stepsix.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @step_ingredient = StepIngredient.find(params[:id])\n\n respond_to do |format|\n if @step_ingredient.update_attributes(params[:step_ingredient])\n format.html { redirect_to(@step_ingredient, :notice => 'Step ingredient was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @step_ingredient.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @step = params[:step].to_i\n content = FetchContentService.new.(current_student.os, @step)\n current_student.steps << {title: content[:title] }\n current_student.save!\n\n redirect_to edit_students_path\n end",
"def update\n @project_step = ProjectStep.find(params[:id])\n\n respond_to do |format|\n if @project_step.update_attributes(params[:project_step])\n flash[:notice] = 'ProjectStep was successfully updated.'\n format.html { redirect_to(@project_step) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project_step.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @endpoint_info = args[:endpoint_info] if args.key?(:endpoint_info)\n @steps = args[:steps] if args.key?(:steps)\n end",
"def update\n respond_to do |format|\n if @steplog.update(steplog_params)\n format.html { redirect_to @steplog, notice: 'Steplog was successfully updated.' }\n format.json { render :show, status: :ok, location: @steplog }\n else\n format.html { render :edit }\n format.json { render json: @steplog.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_four.update(step_four_params)\n format.html { redirect_to @step_four, notice: 'Step four was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_four }\n else\n format.html { render :edit }\n format.json { render json: @step_four.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @methodstep = Methodstep.find(params[:id])\n\n respond_to do |format|\n if @methodstep.update_attributes(params[:methodstep])\n flash[:notice] = 'Methodstep was successfully updated.'\n format.html { redirect_to(@methodstep) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @methodstep.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n goal = Goal.find params[:id]\n if goal.update(goal_params)\n render json: goal, status: 200\n else\n render json: goal.errors.full_messages, status: 422\n end\n end",
"def update\n @roadmap = Roadmap.find(@roadmap_step.roadmap_id)\n\n respond_to do |format|\n if @roadmap_step.update(roadmap_step_params)\n format.html { redirect_to @roadmap, notice: 'Roadmap step was successfully updated.' }\n format.json { render :show, status: :ok, location: @roadmap_step }\n else\n format.html { render :edit }\n format.json { render json: @roadmap_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @scenario = Scenario.find(params[:id])\n\n respond_to do |format|\n if @scenario.update_attributes(params[:scenario])\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @city = City.find(params[:id])\n if @city.update_attributes(:name=>params[:body][:name],:step=>\"1\")\n render :json=>{:response=>\"success\"}\n else\n render :json=>failure1(@city.errors)\n end\n end",
"def update\n if @scenario.update(scenario_params)\n \trender json: @scenario\n else\n \trender json: {status: 'ERROR', data: @scenario.errors}\n end\n end",
"def set_step\n begin\n @step = Step.find(params[:id])\n rescue => e\n puts e.message\n render json: { message: \"Id do step não encontrado\" }, status: :not_found\n end\n end",
"def update\n @stepnine = Stepnine.find(params[:id])\n\n respond_to do |format|\n if @stepnine.update_attributes(params[:stepnine])\n format.html { redirect_to(root_path, :notice => 'Stepnine was successfully updated.') }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @stepnine.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @scenario = Scenario.find(params[:id])\n\n respond_to do |format|\n if @scenario.update_attributes(scenario_params)\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @wizard = Wizard.find(params[:id])\n\n respond_to do |format|\n if @wizard.update_attributes(params[:wizard])\n format.html { redirect_to @wizard, notice: 'Wizard was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @wizard.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @project_step_m.update(project_step_m_params)\n format.html { redirect_to @project_step_m, notice: 'Project step m was successfully updated.' }\n format.json { render :show, status: :ok, location: @project_step_m }\n else\n format.html { render :edit }\n format.json { render json: @project_step_m.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @step_comment.update(step_comment_params)\n format.html { redirect_to @step_comment, notice: 'Step comment was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_comment }\n else\n format.html { render :edit }\n format.json { render json: @step_comment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category_step.update(category_step_params)\n format.html { redirect_to @category_step, notice: 'Category step was successfully updated.' }\n format.json { render :show, status: :ok, location: @category_step }\n else\n format.html { render :edit }\n format.json { render json: @category_step.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n step_definition_attributes = step_definition_params\n field_definitions_attributes = step_definition_attributes.delete(\"field_definitions\")\n\n FieldDefinition.updateFieldDefinitions(field_definitions_attributes)\n\n respond_to do |format|\n if @step_definition.update(step_definition_attributes)\n format.html { redirect_to @step_definition, notice: 'Step definition was successfully updated.' }\n format.json { render :show, status: :ok, location: @step_definition }\n else\n format.html { render :edit }\n format.json { render json: @step_definition.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_exercise.update(api_v1_exercise_params)\n format.html { redirect_to @api_v1_exercise, notice: 'Exercise was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_exercise }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_exercise.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @step = TaskrequestsStep.find(params[:taskrequests_step_id])\n @absence_request = @step.absence_requests.find(params[:id])\n\n respond_to do |format|\n if @absence_request.update_attributes(params[:absence_request])\n format.html { redirect_to(@absence_request, :notice => 'Absence request was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @absence_request.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_step(step, linear)\n if linear\n self.step_flow = step_flows.find_by(current_step: step)\n self.step_status.mirror_step_flow(self.step_flow)\n self.save\n else\n self.step_status.current_step = step\n end\n self.step_status.save\n self.save\n end",
"def update\n respond_to do |format|\n if @scenario.update(scenario_params)\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { render :show, status: :ok, location: @scenario }\n else\n format.html { render :edit }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @scenario.update(scenario_params)\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { render :show, status: :ok, location: @scenario }\n else\n format.html { render :edit }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @scenario.update(scenario_params)\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { render :show, status: :ok, location: @scenario }\n else\n format.html { render :edit }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @scenario.update(scenario_params)\n format.html { redirect_to @scenario, notice: 'Scenario was successfully updated.' }\n format.json { render :show, status: :ok, location: @scenario }\n else\n format.html { render :edit }\n format.json { render json: @scenario.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @case_sensitive = args[:case_sensitive] if args.key?(:case_sensitive)\n @first_step_required = args[:first_step_required] if args.key?(:first_step_required)\n @match_type = args[:match_type] if args.key?(:match_type)\n @steps = args[:steps] if args.key?(:steps)\n @url = args[:url] if args.key?(:url)\n end",
"def update\n @track = Track.find(params[:id])\n\n unless (current_user?(@track.user) and !current_user.learns(@track))\n current_user.learn!(@track)\n\n @track.steps.each do |step|\n @subm = Submission.new(step_id: step.id, user_id: current_user.id, grade: 'not graded')\n @subm.save\n end\n\n end\n # redirect_to @track\n\n respond_to do |format|\n if @track.update_attributes(params[:track])\n format.html { redirect_to @track, notice: 'Track was successfully.'}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @track.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @solution = @idea.solutions.find(params[:id])\n\n if @solution.update_attributes(params[:solution])\n render json: { text: \"success\" }\n else\n render json: { text: \"fail\"}\n end\n end",
"def edit\n redirect_to wizard_path(steps[0])\n end",
"def update\n @how_to = HowTo.find(params[:id])\n\n respond_to do |format|\n if @how_to.update_attributes(allowed_params)\n @status = admin_how_to_steps_url(@how_to, course_id: @course)\n flash[:notice] = 'HowTo was successfully updated.'\n format.html { redirect_to(admin_how_to_steps_url(@how_to, course_id: @course)) }\n format.xml { head :ok }\n else\n @status = \"failed\"\n format.html { render action: \"edit\" }\n format.xml { render xml: @how_to.errors, status: :unprocessable_entity }\n end\n format.js\n end\n end",
"def update\n @startup = Startup.find(params[:id])\n\n respond_to do |format|\n\n if @startup.update_attributes(params[:startup])\n \tif params[:nextstep] == 'next' \n format.html { render action: \"editcapital\" }\n else\n format.html { render action: \"show\" }\n end\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @startup.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @workflow.update(workflow_params)\n format.json { render json: @workflow, :layout => false }\n else\n #format.json { render json: @workflow.errors, status: :unprocessable_entity, :layout => false }\n end\n end\n end",
"def update_process(job_id:, step:, status:, msg:)\n HTTParty.get(\"#{@host}/api/process/#{job_id}\", query: {\n process_code: @process_code,\n step: step,\n status: status,\n msg: msg,\n api_key: @api_key\n })\n end",
"def update\n respond_to do |format|\n if @lunch.update(lunch_params)\n format.html { redirect_to @lunch, notice: 'Lunch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @lunch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lab_flow = LabFlow.find(params[:id])\n\n respond_to do |format|\n if @lab_flow.update_attributes(params[:lab_flow])\n format.html { redirect_to @lab_flow, notice: 'lab flow was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lab_flow.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @goal = Goal.find(params[:id])\n\n respond_to do |format|\n if @goal.update_attributes(params[:goal])\n format.html { redirect_to @goal, notice: 'Goal was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @goal.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @go_slim_sequence = GoSlimSequence.find(params[:id])\n\n respond_to do |format|\n if @go_slim_sequence.update_attributes(params[:go_slim_sequence])\n format.html { redirect_to @go_slim_sequence, notice: 'Go slim sequence was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @go_slim_sequence.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @exercise = Exercise.find(params[:id])\n\n respond_to do |format|\n if @exercise.update_attributes(params[:exercise])\n format.html { redirect_to @exercise, :notice => 'exercise was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @exercise.errors, :status => :unprocessable_entity }\n end\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 # PATCH\n raise NotImplementedError\n end",
"def update\n\n sub_obj_non_attributes = study_params.select { |key| !key.to_s.match(/_attributes$/) }\n\n @study = Study.find(session[:current_study_id])\n\n \n if ! sub_obj_non_attributes.empty?\n @study.update(sub_obj_non_attributes.to_h.except('_destroy', 'id', 'rec_id', 'updated', 'rec_delete'))\n end\n \n traverse_study_attr(study_params.select { |key| key.to_s.match(/_attributes$/)}, @study)\n \n respond_to do |format|\n format.html { redirect_to study_steps_path}\n format.json { render action: 'show', status: :created, location: @study }\n\n end\n\n end",
"def patch!\n request! :patch\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.status = \"deleted\"\n @step.save!\n\n respond_to do |format|\n format.json { render :json => \"success\" }\n end\n end",
"def update\n @test_run.scenarios.map! do |s|\n s.test_run = @test_run\n s.config_template = @test_run.config\n s\n end\n if @test_run.update(test_run_params)\n redirect_to @test_run, notice: 'Test run was successfully updated.'\n else\n render action: 'edit'\n end\n end",
"def patch(path, opts = {})\n request(:patch, path, opts).body\n end",
"def update!(**args)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n @patch_job_instance_details = args[:patch_job_instance_details] if args.key?(:patch_job_instance_details)\n end",
"def set_step\n @step = @recipe_item.steps.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end",
"def set_step\n @step = Step.find(params[:id])\n end"
] |
[
"0.71927685",
"0.71523595",
"0.7116217",
"0.7104519",
"0.7026183",
"0.7013438",
"0.6940124",
"0.6940124",
"0.6918359",
"0.682918",
"0.6745699",
"0.67377734",
"0.66899604",
"0.66848296",
"0.66759956",
"0.6626989",
"0.6592262",
"0.65648484",
"0.651355",
"0.651099",
"0.65043366",
"0.6494928",
"0.64575064",
"0.6445723",
"0.6444548",
"0.64039403",
"0.6399282",
"0.6378605",
"0.637846",
"0.6357813",
"0.63454235",
"0.63451517",
"0.6336439",
"0.6316975",
"0.6307334",
"0.62782806",
"0.62558943",
"0.62122655",
"0.62061054",
"0.6191617",
"0.61614126",
"0.61567706",
"0.6150027",
"0.61273754",
"0.61090505",
"0.6107557",
"0.60907555",
"0.60779023",
"0.60290813",
"0.6017654",
"0.59929353",
"0.5991733",
"0.5954805",
"0.59447986",
"0.59408724",
"0.5929442",
"0.5920122",
"0.59160334",
"0.59141695",
"0.58743054",
"0.5870133",
"0.5853237",
"0.5850798",
"0.5838877",
"0.58267117",
"0.5814395",
"0.57952744",
"0.5792958",
"0.57810014",
"0.5707802",
"0.5701624",
"0.5701624",
"0.5701624",
"0.5701624",
"0.56997585",
"0.56988436",
"0.569589",
"0.56797343",
"0.5670319",
"0.5661907",
"0.5651941",
"0.5646661",
"0.56422937",
"0.56205267",
"0.5619674",
"0.56037104",
"0.55891985",
"0.55834264",
"0.5581474",
"0.5576181",
"0.55677384",
"0.55591625",
"0.5557098",
"0.5537956",
"0.5531729",
"0.553097",
"0.5528197",
"0.5528197",
"0.5528197",
"0.5528197"
] |
0.6908252
|
9
|
DELETE /steps/1 DELETE /steps/1.json
|
def destroy
@step.destroy
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @step = Step.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.status = \"deleted\"\n @step.save!\n\n respond_to do |format|\n format.json { render :json => \"success\" }\n end\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to quest_steps_url(@quest) }\n format.json { head :ok }\n end\n end",
"def destroy\n @step = @guide.steps.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to guide_steps_path(@guide) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_activity = StepActivity.find(params[:id])\n @step_activity.destroy\n\n respond_to do |format|\n format.html { redirect_to step_activities_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @next_step = NextStep.find(params[:id])\n @next_step.destroy\n\n respond_to do |format|\n format.html { redirect_to next_steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @step.destroy\r\n respond_to do |format|\r\n format.html { redirect_to @tutorial, notice: 'Step was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to @task }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step2 = Step2.find(params[:id])\n @step2.destroy\n\n respond_to do |format|\n format.html { redirect_to step2s_url }\n format.json { head :ok }\n end\n end",
"def delete_workflow_step(id)\n @client.raw('delete', \"/crm/steps/#{id}\")\n end",
"def destroy\n @step_three.destroy\n respond_to do |format|\n format.html { redirect_to step_threes_url, notice: 'Step three was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step.destroy\n respond_to do |format|\n format.html { redirect_to @trip }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lead_step = LeadStep.find(params[:id])\n @lead_step.destroy\n\n respond_to do |format|\n format.html { redirect_to lead_steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @steps_log = StepsLog.find(params[:id])\n @steps_log.destroy\n\n respond_to do |format|\n format.html { redirect_to steps_logs_url }\n format.json { head :no_content }\n end\n end",
"def destroy \n @step = Step.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to selection_path(params[:selection_id]) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_scenario.destroy\n respond_to do |format|\n format.html { redirect_to step_scenarios_url, notice: 'Step scenario was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_definition.destroy\n respond_to do |format|\n format.html { redirect_to step_definitions_url, notice: 'Step definition was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_type = StepType.find(params[:id])\n @step_type.destroy\n\n respond_to do |format|\n format.html { redirect_to step_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @taken_step.destroy\n respond_to do |format|\n format.html { redirect_to taken_steps_url, notice: 'steps taken was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pre_step = PreStep.find(params[:id])\n @pre_step.destroy\n\n respond_to do |format|\n format.html { redirect_to pre_steps_url }\n format.json { head :ok }\n end\n end",
"def delete_workflow_step(id)\n return @client.raw(\"delete\", \"/crm/steps/#{id}\")\n end",
"def destroy\n @goal_step.destroy\n respond_to do |format|\n format.html { redirect_to goal_steps_url, notice: \"Goal step was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tc_detail_step = TcDetailStep.find(params[:id])\n @tc_detail_step.destroy\n\n respond_to do |format|\n format.html { redirect_to tc_detail_steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n secureEnter @step\n @step.destroy\n respond_to do |format|\n format.html { redirect_to edit_post_path(@step.post.id) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_six.destroy\n respond_to do |format|\n format.html { redirect_to step_sixes_url, notice: 'Step six was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user_step.destroy\n respond_to do |format|\n format.html { redirect_to user_steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @next_step.destroy\n respond_to do |format|\n format.html { redirect_to next_steps_url, notice: 'Next step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @id = @step.board_id\n @step.destroy\n respond_to do |format|\n format.html { redirect_to board_url(@id), notice: 'Step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stepone.destroy\n respond_to do |format|\n format.html { redirect_to mainpage_path(@stepone.mainpage), notice: 'Stepone was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.destroy\n authorize! :destroy, @step\n respond_to do |format|\n format.html { redirect_to(@tutorial) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @step_m.destroy\n respond_to do |format|\n format.html { redirect_to step_ms_url, notice: 'Step m was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @steplog.destroy\n respond_to do |format|\n format.html { redirect_to steplogs_url, notice: 'Steplog was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_four.destroy\n respond_to do |format|\n format.html { redirect_to step_fours_url, notice: 'Step four was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step = Step.find(params[:id])\n @step.destroy\n flash[:notice] = \"Successfully destroyed step.\"\n\n if(params[:test_case_id])\n @test_case = TestCase.find(params[:test_case_id])\n end\n @step = Step.new\n respond_with @step\n end",
"def destroy\n @step_command.destroy\n respond_to do |format|\n format.html { redirect_to step_commands_url, notice: 'Step command was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project_step = ProjectStep.find(params[:id])\n @project_step.destroy\n\n respond_to do |format|\n format.html { redirect_to(project_steps_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @roadmap_step.destroy\n respond_to do |format|\n format.html { redirect_to roadmap_steps_url, notice: 'Roadmap step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_seven.destroy\n respond_to do |format|\n format.html { redirect_to step_sevens_url, notice: 'Step seven was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cooking_step.destroy\n respond_to do |format|\n format.html { redirect_to cooking_steps_url, notice: 'Cooking step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @project_step.destroy\n respond_to do |format|\n format.html { redirect_to project_steps_url, notice: 'Project step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stepsix = Stepsix.find(params[:id])\n @stepsix.destroy\n\n respond_to do |format|\n format.html { redirect_to(stepsixes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @scenario = Scenario.find(params[:id])\n @scenario.destroy\n\n respond_to do |format|\n format.html { redirect_to scenarios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @scenario = Scenario.find(params[:id])\n @scenario.destroy\n\n respond_to do |format|\n format.html { redirect_to scenarios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step2 = Proce.find(params[:id])\n @step2.destroy\n\n respond_to do |format|\n format.html { redirect_to(step2s_url) }\n format.xml { head :ok }\n format.json { render :text => '{status: \"success\"}'}\n end\n end",
"def destroy\n @book_step = BookStep.find(params[:id])\n @book_step.destroy\n\n respond_to do |format|\n format.html { redirect_to book_steps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step_ingredient = StepIngredient.find(params[:id])\n @step_ingredient.destroy\n\n respond_to do |format|\n format.html { redirect_to(step_ingredients_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @process_step.destroy\n respond_to do |format|\n format.html { redirect_to process_steps_url, notice: 'Process step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @methodstep = Methodstep.find(params[:id])\n @methodstep.destroy\n\n respond_to do |format|\n format.html { redirect_to(methodsteps_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @daily_step.destroy\n respond_to do |format|\n format.html { redirect_to daily_steps_url, notice: 'Daily step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stepnine = Stepnine.find(params[:id])\n @stepnine.destroy\n\n respond_to do |format|\n format.html { redirect_to(stepnines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @active_workflow_step.destroy\n respond_to do |format|\n format.html { redirect_to active_workflow_steps_url, notice: 'Active workflow step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step = Step.find(params[:id])\n if @step.removable\n step_name = @step.name\n project = @step.projects.first\n @step.destroy\n\n ProjectMailer.notify_step_deleted(step_name, project, current_user).deliver\n respond_to do |format|\n format.html { redirect_to steps_url }\n format.json { render :json => {:message => \"Success\"} }\n end\n else\n respond_to do |format|\n format.html { redirect_to steps_url }\n format.json { render :json => \"Step #{@step.name} is not removable\", :status => :unprocessable_entity}\n end\n end\n end",
"def destroy\n @category_step.destroy\n respond_to do |format|\n format.html { redirect_to category_steps_url, notice: 'Category step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @goal = Goal.find(params[:id])\n @goal.destroy\n render json: @goal\n end",
"def destroy\n @project_step_m.destroy\n respond_to do |format|\n format.html { redirect_to project_step_ms_url, notice: 'Project step m was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tutorial_quest = Tutorial::Quest.find(params[:id])\n @tutorial_quest.destroy\n\n respond_to do |format|\n format.html { redirect_to tutorial_quests_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @scenario.destroy\n respond_to do |format|\n format.html { redirect_to scenarios_url, notice: 'Scenario was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @step = Step.find(params[:step_id])\n authorize! :destroy, @step\n\n if @step.ancestry==\"0\" && @project.steps.where(:ancestry => @step.id.to_s).length > 1\n # can't delete root!\n respond_to do |format|\n format.html {\n flash[:error] = \"Can't delete the root of your project!\"\n redirect_to project_steps_url\n }\n end \n else\n if @step.ancestry == \"0\"\n @project.steps.where(\"id !=?\", @step.id.to_s).each do |step|\n if step.ancestry == @step.id.to_s\n step.update_attributes(:ancestry => \"0\")\n else\n step.update_attributes(:ancestry => step.ancestry.gsub(@step.id.to_s+\"/\", \"\"))\n end\n end\n end\n\n PublicActivity::Activity.where(:trackable_id => @step.id).destroy_all\n if @step.question\n PublicActivity::Activity.where(:trackable_id => @step.question.id).destroy_all\n end \n\n # destroy any news items associated with it\n News.where(:step_id => @step.id).each do |news_item|\n news_item.destroy\n end\n\n @step.destroy\n \n # update positions of subsequent steps\n if @step.position < @steps.count\n for step in @step.position+1..@steps.count\n if @steps.where(\"position\" => step).exists?\n @steps.where(\"position\" => step)[0].update_attribute(:position, step-1)\n end\n end\n end\n\n # check whether project is published\n if @project.public?\n @project.set_published(current_user.id, @project.id, nil)\n end\n\n # check and set built attribute of project\n @project.set_built\n\n @project.delay.log\n\n respond_to do |format|\n format.html { redirect_to project_steps_url }\n format.json { head :no_content }\n end\n end\n end",
"def destroy\n @exercise_execution.destroy\n respond_to do |format|\n format.html { redirect_to exercise_executions_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @wizard = Wizard.find(params[:id])\n @wizard.destroy\n\n respond_to do |format|\n format.html { redirect_to wizards_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @fourth_scenario.destroy\n respond_to do |format|\n format.html { redirect_to fourth_scenarios_url, notice: 'Fourth scenario was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @goal = Goal.find(params[:id])\n @goal.destroy\n\n respond_to do |format|\n format.html { redirect_to goals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @goal = Goal.find(params[:id])\n @goal.destroy\n\n respond_to do |format|\n format.html { redirect_to goals_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @goal = Goal.find(params[:id])\n @goal.destroy\n\n respond_to do |format|\n format.html { redirect_to goals_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @step_comment.destroy\n respond_to do |format|\n format.html { redirect_to step_comments_url, notice: 'Step comment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @scenario.destroy\n respond_to do |format|\n format.html { redirect_to scenarios_url, notice: 'Cenário deletado com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_exercise.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_exercises_url, notice: 'Exercise was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @wizard.destroy\n respond_to do |format|\n format.html { redirect_to wizards_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @storyline = Storyline.find(params[:id])\n @storyline.destroy\n\n respond_to do |format|\n format.html { redirect_to storylines_url }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def delete_story_version(id)\n @client.raw('delete', \"/content/story-versions/#{id}\")\n end",
"def destroy\n @exercise.destroy\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @exercise.destroy\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item1 = LineItem1.find(params[:id])\n @line_item1.destroy\n\n respond_to do |format|\n format.html { redirect_to line_item1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rating_scale_step = RatingScaleStep.find(params[:id])\n @rating_scale_step.destroy\n\n respond_to do |format|\n format.html { redirect_to rating_scale_steps_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @level_goal = LevelGoal.find(params[:id])\n @level_goal.destroy\n\n respond_to do |format|\n format.html { redirect_to level_goals_url }\n format.json { head :no_content }\n end\n end",
"def delete path\n make_request(path, \"delete\", {})\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 @completed_quest = CompletedQuest.find(params[:id])\n @completed_quest.destroy\n\n respond_to do |format|\n format.html { redirect_to completed_quests_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @go_slim_sequence = GoSlimSequence.find(params[:id])\n @go_slim_sequence.destroy\n\n respond_to do |format|\n format.html { redirect_to go_slim_sequences_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tutorial_state = Tutorial::State.find(params[:id])\n @tutorial_state.destroy\n\n respond_to do |format|\n format.html { redirect_to tutorial_states_url }\n format.json { head :ok }\n end\n end",
"def destroy\n story_part_id = @story_part.id\n @story_part.destroy\n render :json => story_part_id\n end",
"def destroy\n @goal_state = GoalState.find(params[:id])\n @goal_state.destroy\n\n respond_to do |format|\n format.html { redirect_to goal_states_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 @exercise_instruction = ExerciseInstruction.find(params[:id])\n @exercise_instruction.destroy\n\n respond_to do |format|\n format.html { redirect_to @exercise_instruction.exercise }\n format.json { head :no_content }\n end\n end",
"def destroy\n @oncourse_exercise.destroy\n respond_to do |format|\n format.html { redirect_to oncourse_exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @sample_line = SampleLine.find(params[:id])\n @sample_line.destroy\n\n respond_to do |format|\n format.html { redirect_to sample_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @second_scenario.destroy\n respond_to do |format|\n format.html { redirect_to second_scenarios_url, notice: 'Second scenario was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @wizard.destroy\n respond_to do |format|\n format.html { redirect_to house_wizards_path(@house), notice: 'Wizard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lab_flow = LabFlow.find(params[:id])\n @lab_flow.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_flows_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @exercise = Exercise.find(params[:id])\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end"
] |
[
"0.7910436",
"0.78295755",
"0.78116536",
"0.7774464",
"0.75964475",
"0.7572063",
"0.7572063",
"0.7572063",
"0.7572063",
"0.742347",
"0.74095196",
"0.7402601",
"0.7400754",
"0.73675877",
"0.7339873",
"0.73136175",
"0.73052126",
"0.73025376",
"0.7301966",
"0.73009235",
"0.728252",
"0.7275749",
"0.7233685",
"0.7226625",
"0.7225262",
"0.7223025",
"0.7219995",
"0.7210809",
"0.72035235",
"0.7190595",
"0.71644974",
"0.71640867",
"0.7136336",
"0.7120084",
"0.7094142",
"0.7090143",
"0.7070875",
"0.7067714",
"0.70634335",
"0.706019",
"0.70294553",
"0.70199656",
"0.6980445",
"0.69582397",
"0.69565696",
"0.6947879",
"0.6895283",
"0.6895283",
"0.68924934",
"0.6884262",
"0.6882513",
"0.68593353",
"0.6837853",
"0.6830447",
"0.6820749",
"0.6735121",
"0.6692822",
"0.66741455",
"0.6643105",
"0.6642436",
"0.6600221",
"0.65661687",
"0.6564071",
"0.65408486",
"0.65299827",
"0.65261614",
"0.6516947",
"0.6516947",
"0.6516086",
"0.65081567",
"0.6500645",
"0.6490229",
"0.64862233",
"0.64662933",
"0.6462921",
"0.644408",
"0.6443559",
"0.6443559",
"0.6441871",
"0.643724",
"0.6437167",
"0.64296806",
"0.6423108",
"0.6404059",
"0.63907415",
"0.63833666",
"0.6364786",
"0.6354129",
"0.6351718",
"0.63494366",
"0.63452953",
"0.63422525",
"0.63417",
"0.63380677",
"0.63360554",
"0.6334881",
"0.6334881",
"0.6334881",
"0.6334881"
] |
0.71376354
|
33
|
Use callbacks to share common setup or constraints between actions.
|
def set_step
@step = Step.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
|
Never trust parameters from the scary internet, only allow the white list through.
|
def step_params
params.require(:step).permit(:number, :description, :locator, :skip, :testcase_id, :actionValue)
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
|
Part 0 cmd[0] : ip of currNode cmd[1] : ip of destNode cmd[2] : name of destNode
|
def edgeb_stdin(cmd)
$record_ip[$hostname] = cmd[0]
$record_ip[cmd[2]] = cmd[1]
node = $node_info.new
time = nil
$lock.synchronize{
node.src = $hostname
node.dst = cmd[2]
node.cost = 1
node.nexthop = cmd[2]
time = $clock.to_i
$rt[cmd[2]] = node
if $local_ip == nil then $local_ip = cmd[0] end
$network.undir_connection($hostname, cmd[2], time, 1)
}
client = TCPSocket.open(cmd[1], $nodesFile[cmd[2]]["PORT"])
client.puts("EDGEB2 #{cmd[2]} #{$hostname} #{cmd[1]} #{time}")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def dest\n self[:ip_dest]\n end",
"def dest_ip\n self[:dest_ip]\n end",
"def edgeb_network(cmd)\n node = $node_info.new \n $lock.synchronize{\n \n node.src = $hostname\n node.dst = cmd[1]\n node.cost = 1\n node.nexthop = cmd[1]\n $rt[cmd[1]] = node\n if $local_ip == nil then $local_ip = cmd[2] end\n\n $network.undir_connection($hostname, cmd[1], cmd[3].to_i, 1) \n }\n #puts \"THIS IS THE ROUTING TABLE: #{$rt}\"\nend",
"def getDestination()\r\n\t\treturn @dnode\r\n\tend",
"def transfer(node, ins) ; ins ; end",
"def ip_cmd_from_file\n\n ip_cmd = ''\n ip_cmd += 'to ' + self.to + ' ' if ! self.to.nil? && ! self.to.empty?\n ip_cmd += 'via ' + self.via + ' ' if ! self.via.nil? && ! self.via.empty?\n ip_cmd += 'dev ' + self.device + ' ' if ! self.device.nil? && ! self.device.empty?\n ip_cmd += 'table ' + self.table + ' ' if ! self.table.nil? && ! self.table.empty?\n return ip_cmd\n\n end",
"def dest\n param(0)\n end",
"def dest\n if (@currentCommand.include?'=')\n result = \"\"\n if (@currentCommand.slice(0) == \"0\")\n result = \"null\"\n else\n endmarks = Array['=', ';']\n i = 0\n\n while (endmarks.include?(@currentCommand.slice(i)) != true)\n result += @currentCommand.slice(i)\n i += 1\n end\n end\n else\n result = 'null'\n end\n return result\n end",
"def ip_to_node ip\n #Get the lines from nta where node is with that IP\n node_ip_lines = $nodes_to_addrs.select{ |line| line =~ /#{ip}/ }\n\n if (node_ip_lines[0] == nil)\n puts \"ERROR: Could not find the IP = #{ip} in the nodes_to_addrs.txt file\"\n return nil\n end\n\n #Remove the IP and whitespace from string\n node_ip_lines[0].split[0...1].join(' ')\nend",
"def destination(dest); end",
"def destination(dest); end",
"def dest_get\n db_select 'destination'\n end",
"def dest_mac\n self[:dest_mac]\n end",
"def edgeu(cmd)\n $dist[cmd[0]] = cmd[1].to_i\n $neighbors[cmd[0]] = cmd[1].to_i\n client = $clients[cmd[0]]\n msg = Msg.new\n msg.setConfig(\"type\", 2)\n msg.setMessage($hostname + \" \" + cmd[1].to_i.to_s)\n sendMessage(client, msg)\n fillInNodes()\nend",
"def active_remote_destinations; end",
"def constructSendCmd(ipport, ipaddr, cmd, nodeType)\n nmsg = MsgPacket.new\n cmstr = nmsg.constructMsg(cmd, nodeType)\n sendCommand(ipport, ipaddr, cmstr)\n insertPool(cmstr, ipaddr)\n end",
"def conn_ip(n_s, n_d)\n nodes_to_addrs2 = File.readlines(ARGV[0])\n #puts \"\\nn_s = \" + n_s + \" n_d = \" + n_d\n \n n_s_ip_lines = nodes_to_addrs2.select{ |line| line =~ /#{n_s}\\s/ }\n #puts \"\\nPRINT N_S LINES\"\n #puts n_s_ip_lines\n\n\n n_s_ip = []\n n_s_ip_lines.each {|line|\n n_s_ip.push line.split[1..2].join('\\t')\n }\n\n #puts \"\\nPRINTING N_S IPs\"\n #puts n_s_ip\n \n\n n_d_ip_lines = nodes_to_addrs2.select { |line| line =~ /#{n_d}\\s/ }\n #puts \"\\nPRINTING N_D LINES\"\n #puts n_d_ip_lines\n\n\n n_d_ip = []\n n_d_ip_lines.each {|line|\n n_d_ip.push line.split[1..2].join('\\t')\n }\n #puts \"\\nPRINTING N_D IPs\"\n #puts n_d_ip\n\n n_s_ip.each{ |s_ip| \n n_d_ip.each{ |d_ip|\n if ((destination_of_addr s_ip) == d_ip)\n #puts \"CONNECTION WITH \" + d_ip\n return d_ip\n end\n }\n }\nend",
"def edgebReflex(msg, client)\n msg = msg.split(',')\n dstip = msg[0]\n srcip = msg[1]\n dst = msg[2]\n $ips[$hostname] = srcip\n $ips[dst] = dstip\n $dist[dst] = 1\n $neighbors[dst] = 1\n $next[dst] = dst\n $clients[dst] = client\n fillInNodes()\nend",
"def receive_name socket \n data = socket.read_packet_2 'n'\n dist = data[0,2] # 5,5\n flags = data[2,4] # flags\n node_name = data[6, data.length]\n [dist, flags, node_name]\n end",
"def dest(str)\n @@DEST_TABLE[str]\n end",
"def arp_dest_ip; self[:arp_dest_ip].to_s; end",
"def resolve_addresses packet # :nodoc:\n source = packet.source @resolver\n source = \"\\\"druby://#{source.sub(/\\.(\\d+)$/, ':\\1')}\\\"\"\n\n destination = packet.destination @resolver\n destination = \"\\\"druby://#{destination.sub(/\\.(\\d+)$/, ':\\1')}\\\"\"\n\n return source, destination\n end",
"def arp_dest_ip= i; typecast \"arp_dest_ip\", i; end",
"def path src, dest\n path = _path srcPaths: [[@nodes[src]]], dest: @nodes[dest]\n if !path.nil?\n path.map(&:value)\n end\n end",
"def _all_gp_dest_src\n (0..7).each do |dest_reg|\n (0..7).each do |src_reg|\n if src_reg != dest_reg\n yield \"r#{dest_reg}\", \"r#{src_reg}\"\n end\n end\n end\n end",
"def command(str)\n ar=str.split(/ /)\n case ar[0]\n when \"++addr\"\n if ar.size<2\n return @addr.to_s\n else \n @addr=ar[1].to_i\n end\n\n end\n return nil\n end",
"def neigh_command_builder(name, cmd, opts)\n command_builder(\"neighbor #{name} #{cmd}\", opts)\n end",
"def uid\n tail_node_uid = tail_node ? tail_node.uid : ''\n head_nade_uid = head_node ? head_node.uid : ''\n tail_node_vpcid = tail_node && tail_node.vpc_id&+'-' || ''\n head_nade_vpcid = head_node && head_node.vpc_id&+'-' || ''\n \"tail-#{tail_node_vpcid}#{tail_node_uid}_head-#{head_nade_vpcid}#{head_nade_uid}_ports-#{port_start}-to-#{port_end}_proto-#{protocol || 'none'}\"\n end",
"def transfer(item)\n base = File.basename(item.to_s.chomp)\n cmd = \"#{@rsync_cmd} #{@origin}/#{base} #{@dst}\"\n SingleLogger.instance.info cmd\n `#{cmd}`\n end",
"def taskDestination _args\n \"taskDestination _args;\" \n end",
"def dest; end",
"def destination; frame[:destination]; end",
"def dest(mnemonic)\n if Code::DEST.has_key?(mnemonic)\n return Code::DEST[mnemonic]\n else\n return \"000\"\n end\n end",
"def source_dest_check\n data[:source_dest_check]\n end",
"def parse_dest(dest)\n case dest\n when Array\n dest.map { |address| parse_address(address) }\n else\n parse_address(dest)\n end\n end",
"def ip_output_from_file\n\n ip_output = '^'\n ip_output += self.to + ' ' if ! self.to.nil? && ! self.to.empty?\n ip_output += 'via ' + self.via + ' ' if ! self.via.nil? && ! self.via.empty?\n ip_output += 'dev ' + self.device + '\\s+' if ! self.device.nil? && ! self.device.empty?\n ip_output += 'table ' + self.table + ' ' if ! self.table.nil? && ! self.table.empty?\n return ip_output\n\n end",
"def isdst() end",
"def destination\r\n @destination\r\n end",
"def send_neighbour(host, port)\n\t\thost = Socket.ip_address_list.detect { |intf| intf.ipv4_private? }.ip_address if host == \"localhost\"\n\t\tnode = NodeInfo.new(host, port)\n\t\t@neighbour_nodes << node\n\t\tsend_message [\"NEW_NODE\", @info], 0, host, port\t\n\tend",
"def task_2(str)\n r = []\n str.each_line do |x|\n ip = x[/^.* - -/]\n d = x[/[\\[].*[\\]]/]\n a = x[/T .* H/]\n if ip && d && a\n r << d[1..-2] + ' FROM: ' + ip[0..-4] + 'TO:' + a[1..-3].upcase\n end\n end\n r\nend",
"def get_path(dest,path)\n if @prev[dest] != -1\n path += get_path(@prev[dest],\"\")\n end\n path += \">#{dest}\"\n end",
"def peerip=(_arg0); end",
"def edged(cmd)\n $lock.synchronize{ \n $network.remove_edge($hostname,cmd[0])\n\n if $rt.has_key? cmd[0]\n $rt.delete cmd[0] \n end\n\n }\nend",
"def destination\n @attributes[:destination]\n end",
"def tellNode(cmd, topo, domain)\n puts \"---------------------------------------------------\"\n d = (domain == nil) ? OConfig.domain : domain\n command = nil\n if (cmd == \"on\" || cmd == \"-on\" || cmd == \"--turn-on\")\n command = \"on\"\n elsif (cmd == \"offs\" || cmd == \"-offs\" || cmd == \"--turn-off-soft\")\n command = \"offSoft\"\n elsif (cmd == \"offh\" || cmd == \"-offh\" || cmd == \"--turn-off-hard\")\n command = \"offHard\"\n end\n if command == nil\n puts \"ERROR - Unknown command : '#{cmd}'\" \n puts \"Use 'help' to see usage information\" \n puts \"\"\n exit 1\n end\n puts \" Testbed : #{d} - Command: #{command}\"\n topo.eachNode { |n|\n url = \"#{OConfig[:tb_config][:default][:cmc_url]}/#{command}?x=#{n[0]}&y=#{n[1]}&domain=#{d}\"\n response = NodeHandler.service_call(url, \"Can't send command to CMC\")\n if (response.kind_of? Net::HTTPOK)\n puts \" Node n_#{n[0]}_#{n[1]} - Ok\"\n else\n puts \" Node n_#{n[0]}_#{n[1]} - Error (node state: 'Not Available')\"\n end\n }\n puts \"---------------------------------------------------\"\nend",
"def print_path(dest)\n\t\tif @predecessor_node[dest] != -1\n\t\t\tprint_path @predecessor_node[dest]\n\t\tend\n\t\tprint \">#{dest}\"\n\tend",
"def dest_prompt\n db_prompt 'destination'\n end",
"def getDestinationDescription ( node_id )\n value = @descriptions[node_id.value]\n return value ? value : \"\"\n end",
"def on_getaddr\n #addrs = @node.addrs.select{|a| a.time > Time.now.to_i - 10800 }.shuffle[0..250]\n #p \"<< addr (#{addrs.size})\"\n #send_data P::Addr.pkt(*addrs)\n end",
"def ip_cmd_from_should\n\n ip_cmd = ''\n ip_cmd += 'to ' + @resource.should(:to) + ' ' if @resource.should(:to)\n ip_cmd += 'via ' + @resource.should(:via) + ' ' if @resource.should(:via)\n ip_cmd += 'dev ' + @resource.should(:device) + ' ' if @resource.should(:device)\n ip_cmd += 'table ' + @resource.should(:table) + ' ' if @resource.should(:table)\n return ip_cmd\n\n end",
"def pacemaker_node_name(n)\n if n[:pacemaker][:is_remote]\n \"remote-#{n[:hostname]}\"\n else\n n[:hostname]\n end\nend",
"def scp(src_file, path_of_servers, dst_file, option = \"\")\n _path_of_servers = path_of_servers.dup\n remove_first_localhost!(_path_of_servers)\n\n #generate session uuid and make temp dir string\n sid = SecureRandom.uuid\n temp_file = \"#{temp_dir(sid)}#{File.basename(src_file)}\"\n\n #first, local src file to edge server's temp dir\n #(/tmp/onion_ssh/<session uuid>/<files>)\n first = _path_of_servers.shift\n ssh([first], \"mkdir -p #{temp_dir(sid)} >& /dev/null\")\n `#{one_scp_str(src_file, first, temp_file)}`\n \n #second to last - 1 , scp temp dir to temp dir\n last = _path_of_servers.pop\n temp_path = [first]\n _second_to_last_minus_one = _path_of_servers\n _second_to_last_minus_one.each do |sv|\n temp_path << sv\n ssh(temp_path,\"mkdir -p #{temp_dir(sid)} >& /dev/null\")\n end\n\n temp_path = [first]\n _second_to_last_minus_one.each do |sv|\n ssh(temp_path, \"#{one_scp_str(temp_file, sv, temp_dir(sid))}\")\n temp_path << sv\n end\n\n #last minus one's path=(temp_path above) and last\n ssh(temp_path, \"#{one_scp_str(temp_file, last, dst_file)}\")\n #delete garbage\n clear_temp([first] + _second_to_last_minus_one, sid)\n end",
"def ip2f(src, dst)\n \"/home/bender/swork/sidecar/data/#{src}/data-#{src},0-#{dst},33434\"\nend",
"def reply!\n self[:src], self[:dst] = self[:dst], self[:src]\n self\n end",
"def reply!\n self[:src], self[:dst] = self[:dst], self[:src]\n self\n end",
"def reply!\n self[:src], self[:dst] = self[:dst], self[:src]\n self\n end",
"def ssh_cmd(destination_host, cmd)\n\n if strict_host_checking\n [\n 'ssh', '-t',\n '-p', OodCore::Job::Adapters::Helper.ssh_port,\n '-o', 'BatchMode=yes',\n \"#{username}@#{destination_host}\"\n ].concat(cmd)\n else\n [\n 'ssh', '-t',\n '-p', OodCore::Job::Adapters::Helper.ssh_port,\n '-o', 'BatchMode=yes',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-o', 'StrictHostKeyChecking=no',\n \"#{username}@#{destination_host}\"\n ].concat(cmd)\n end\n end",
"def edgeuUpdate(msg)\n msg = msg.split(' ')\n dst = msg[0]\n cost = msg[1].to_i\n $dist[dst] = cost\n $neighbors[dst] = cost\nend",
"def travel_command( node )\n\t\t\t\tTravelCommand.new @interface, node\n\t\t\tend",
"def dest_path\n @dest_path ||= remote_path.sub(/^~\\//, '').sub(/\\/$/, '')\n end",
"def to_loc\n nodes = @nodes.collect(&:to_loc)\n @connections.each do |n0, n1|\n nodes.find { |n| n.id == n0.id }.add_link n1.id\n end\n exits = @nodes.select(&:exit?)\n # Verify that @exits is a subset of @nodes\n exits = exits.map { |e| nodes.find { |n| n.id == e.id } }\n StructureResult.new nodes, exits\n end",
"def remote_addr=(_arg0); end",
"def op\n sequence[ip]\n end",
"def src\n self[:ip_src]\n end",
"def remove_node_from_local_and_zookeeper(ip)\n # First, remove our local copy\n index_to_remove = nil\n @nodes.each_index { |i|\n if @nodes[i].public_ip == ip\n index_to_remove = i\n break\n end\n }\n @nodes.delete(@nodes[index_to_remove])\n\n # Then remove the remote copy\n ZKInterface.remove_node_information(ip)\n @last_updated = ZKInterface.remove_ip_from_ip_list(ip)\n end",
"def copy_name_fields\n self.host_name = self.host.host_name rescue nil\n self.hostgroup_name = self.hostgroup.hostgroup_name rescue nil\n end",
"def rsync_from(source, target, dest, port = 22, extra_flags = [])\n rsync = find_program_on_path('rsync')\n flags = \"-rHlv -O --no-perms --no-owner --no-group\"\n unless extra_flags.empty?\n flags << \" \" << extra_flags.join(\" \")\n end\n ex(\"#{rsync} -e '#{ssh_command(port)}' #{flags} #{target}:#{source} #{dest}\")\n end",
"def distance_between_two_nodes(src_name, dest_name)\n\t\tpath = nil\n\n\t\tsrc_node = @graph.get_node(src_name)\n\t\tif src_node.nil?\n\t\t\tsrc_node = create_node_and_populate_graph(src_name)\n\t\tend\n\n\t\tdest_node = @graph.get_node(dest_name)\n\t\tif dest_node.nil?\n\t\t\tdest_node = create_node_and_populate_graph(dest_name)\n\t\telse\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\n\t\tif path.empty?\n\t\t\tpopulate_graph(src_node) if !src_node.populated\n\t\t\tpopulate_graph(dest_node) if !dest_node.populated\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\t\t\n\t\t# after check on first (separation of 2) level we do another two level of check\n\t\tif path.empty?\n\t\t\t(1..2).each do |level|\n\t\t\t\tsrc_connections = get_persons_based_on_level(src_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(src_connections)\n\t\t\t\tdst_connections = get_persons_based_on_level(dest_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(dst_connections)\n\t\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\t\t\tbreak if path.any?\n\t\t\tend\n\t\tend\n\n\t\twrite_to_yaml\n\n\t\tputs \"Path:\"\n\t\tputs path\n\t\tputs \"Degree of separation :\" + (path.nil? ? \"None\" : (path.size - 1).to_s)\n\tend",
"def to_source; \"* = $#{@addr.to_s(16)}\"; end",
"def resolve_node(result)\n begin\n return Resolv.getname(result[:ip])\n rescue => detail\n Puppet.err _(\"Could not resolve %{ip}: %{detail}\") % { ip: result[:ip], detail: detail }\n end\n result[:ip]\n end",
"def arp_dest_mac; self[:arp_dest_mac].to_s; end",
"def peeraddr(*) end",
"def peeraddr(*) end",
"def sent_info(cli,data)\n net = Packet.encode_net(data)\n peer = \"#{cli.ip_daddr}:\" << (cli.is_udp? ? \"#{cli.udp_dst}\" : \"#{cli.tcp_dst}\")\n asked = net.question.map(&:qname).join(', ')\n vprint_good(\"Sent packet with header:\\n#{cli.inspect}\")\n vprint_good(\"Spoofed records for #{asked} to #{peer}\")\n end",
"def create(destination, nexthop, opts = {})\n cmd = \"ip route #{destination} #{nexthop}\"\n cmd << \" #{opts[:router_ip]}\" if opts[:router_ip]\n cmd << \" #{opts[:distance]}\" if opts[:distance]\n cmd << \" tag #{opts[:tag]}\" if opts[:tag]\n cmd << \" name #{opts[:name]}\" if opts[:name]\n configure cmd\n end",
"def ip_string\n\t\t\"#{settings.subnet}.#{settings.nodes_ip_offset + @ip}\"\n\tend",
"def resolve_node(result)\n begin\n return Resolv.getname(result[:ip])\n rescue => detail\n Puppet.err \"Could not resolve #{result[:ip]}: #{detail}\"\n end\n result[:ip]\n end",
"def droby_dump(dest)\n\t DRoby.new(remote_siblings.droby_dump(dest), owners.droby_dump(dest),\n\t\t Distributed.format(model, dest), Distributed.format(plan, dest), \n\t\t Distributed.format(meaningful_arguments, dest), Distributed.format(data, dest),\n\t\t mission: mission?, started: started?,\n\t\t finished: finished?, success: success?)\n\tend",
"def edgeu(cmd)\n time = nil\n $lock.synchronize{\n time = $clock.to_i\n $network.update_cost($hostname, cmd[0], cmd[1].to_i, time)\n\n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n } \n\n client = TCPSocket.open($local_ip, $nodesFile[cmd[0]][\"PORT\"])\n client.puts(\"EDGEU2 #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def valid_dest?(to, board)\n diff = path_diff(to)\n if board[to[0]][to[1]] != nil\n return false unless @moves[:kill].include?(diff)\n elsif @pos[0] == @start_row\n return false unless @moves[:first].include?(diff)\n else\n return false unless @moves[:else] == diff\n end\n [[@pos]] \n end",
"def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end",
"def forwarded_ssh_port(vm, host, i)\n if host.has_key?('forwarded_ssh_port')\n ssh_port = host['forwarded_ssh_port']\n vm.network \"forwarded_port\", guest: ssh_port.has_key?('guest') ? ssh_port['guest'] : 22, host: ssh_port['host'], id: \"ssh\"\n else\n if host.has_key?('private_networks') && host['private_networks'][0]['ip'] != 'dhcp'\n last_part = /^(\\d{1,3}).(\\d{1,3}).(\\d{1,3}).(\\d{1,3})$/.match(host['private_networks'][0]['ip'])[4].to_i\n else\n last_part = i\n end\n vm.network \"forwarded_port\", guest: 22, host: 11000 + last_part , id: \"ssh\"\n end\nend",
"def destination\n @destination\n end",
"def destination\n @destination\n end",
"def smove(source, destination, member); end",
"def smove(source, destination, member); end",
"def initialize(source_instance,transition) \n @number=0 \n @nodecost=0\n @passby=false\n @instance=source_instance\n @transition=transition\n @neighbours=[]\n \n @name = \"NODE \" +source_instance + \" - \" + transition.to_s \n \n end",
"def copy(command)\n src = clean_up(command[1])\n dest = clean_up(command[2])\n pp @client.files.copy(src, dest)\n end",
"def edged(cmd)\n $ips.delete(cmd[0])\n $dist[cmd[0]] = \"INF\"\n $neighbors.delete(cmd[0])\n $next[cmd[0]] = \"NA\"\n client = $clients[cmd[0]]\n client.close()\n $clients.delete(cmd[0])\nend",
"def pull\n zt=Dnsruby::ZoneTransfer.new\n zt.transfer_type=Dnsruby::Types.AXFR\n zt.server=self.server\n zone=zt.transfer(self.zone.domain)\n zone.tsig=self.zone.domain+\".\", self.key\n soa=zone[0]\n recl=zone[1]\n for record in zone\n src,type,target=record.to_s.match(/([A-z\\.0-9]*)[0-9\\t ]*(IN\\t[A-z]*)\\t([A-z0-9\\. ]*)/).captures\n if type=='IN\\tMX' or type=='IN\\tA' or type=='IN\\tCNAME'\n\tcreateRecord(record)\n elsif type=='IN\\tSOA'\n updateSerial(record)\n end\n end\nend",
"def parse_tcpdump(line)\n data = line.split(\" \")\n\n # Check input data validation, null -> skip\n if (line == nil) then\n return (nil)\n end\n if (data == []) then\n return (nil)\n end\n\n src = data[2]\n dst = data[4]\n size = data[-1] \n\n tmp1 = src.split(\".\")\n tmp2 = dst.split(\".\")\n if (tmp1.length == 5) then\n # IPv4\n src_ip = tmp1[0,4].join(\".\")\n src_port = tmp1[4]\n dst_ip = tmp2[0,4].join(\".\")\n dst_port = tmp2[4]\n else\n # IPv6\n src_ip = tmp1[0]\n src_port = tmp1[1]\n dst_ip = tmp2[0]\n dst_port = tmp2[1]\n end\n\n return ([src_ip, src_port, dst_ip, dst_port, size])\nend",
"def move(*args)\n \t# Sending destination path\n \tputs \"MOVING\"\n \tmove_entity(*args[0].public_path)\n \tsuper\n end",
"def copy_and_move_info(request)\n # Collecting the relevant HTTP headers\n unless request.header('Destination')\n fail Exception::BadRequest, 'The destination header was not supplied'\n end\n\n destination = calculate_uri(request.header('Destination'))\n overwrite = request.header('Overwrite')\n\n overwrite = 'T' unless overwrite\n if overwrite.upcase == 'T'\n overwrite = true\n elsif overwrite.upcase == 'F'\n overwrite = false\n else\n # We need to throw a bad request exception, if the header was invalid\n fail Exception::BadRequest, 'The HTTP Overwrite header should be either T or F'\n end\n\n (destination_dir,) = Http::UrlUtil.split_path(destination)\n\n begin\n destination_parent = @tree.node_for_path(destination_dir)\n\n unless destination_parent.is_a?(ICollection)\n fail Exception::UnsupportedMediaType, 'The destination node is not a collection'\n end\n rescue Exception::NotFound => e\n # If the destination parent node is not found, we throw a 409\n raise Exception::Conflict, 'The destination node is not found'\n end\n\n begin\n destination_node = @tree.node_for_path(destination)\n\n # If this succeeded, it means the destination already exists\n # we'll need to throw precondition failed in case overwrite is false\n unless overwrite\n fail Exception::PreconditionFailed, 'The destination node already exists, and the overwrite header is set to false', 'Overwrite'\n end\n rescue Exception::NotFound => e\n # Destination didn't exist, we're all good\n destination_node = false\n end\n\n request_path = request.path\n if destination == request_path\n fail Exception::Forbidden, 'Source and destination uri are identical.'\n end\n if destination[0..request_path.length] == request_path + '/'\n fail Exception::Conflict, 'The destination may not be part of the same subtree as the source path.'\n end\n\n # These are the three relevant properties we need to return\n {\n 'destination' => destination,\n 'destinationExists' => !!destination_node,\n 'destinationNode' => destination_node\n }\n end",
"def move\n @node = Node.find(params[:id])\n case params[:to]\n when 'left_of'\n @node.move_to_left_of(params[:dest_id])\n when 'right_of'\n @node.move_to_right_of(params[:dest_id])\n when 'child_of'\n @node.move_to_child_of(params[:dest_id])\n end\n @node.save\n redirect_to(nodes_url)\n end",
"def set_dest\n @dest = Dest.find(params[:id])\n end",
"def parse_src_to(src, dest)\n pt = Ktutils::ParseTemplate.new(@start_delim, @stop_delim)\n\n @data.each do |t, v|\n pt.add_token( t, v )\n end\n pt.parse( src, dest )\n end",
"def arp_daddr_ip\n\t\tself[:arp_dest_ip].to_x\n\tend",
"def send_to(ip, files)\n begin\n puts \"[*] copying #{files} to ip : #{ip}\"\n sock = TCPSocket::new ip, RNCP::PORT\n sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1\n\n data = tar files\n \n sock.send data.string, 0\n sock.flush\n\n rescue Exception => e\n puts \"[!] cannot create connection to host, bailing out\"\n puts e\n ensure\n sock.close if sock.nil? == false\n puts \"[#] finished\"\n end\n end",
"def jump(src_cell, dest_cell)\n \n temp = cells[src_cell[0]][src_cell[1]].removePiece()\n cells[dest_cell[0]][dest_cell[1]].removePiece()\n cells[dest_cell[0]][dest_cell[1]].addPiece(temp)\n \n end",
"def defNodeHostname(jobid, nodeList)\n hosts = %x(uniq /var/lib/oar/#{jobid} && echo $?)\n hostList = hosts.split(\"\\n\") \n if(hostList.delete_at(hostList.size-1).to_i != 0)\n STDERR.puts hosts\n exit 1\n end\n if hostList.size < nodeList.size\n STDERR.puts \"Not enough nodes in the reservation\"\n STDERR.puts \"You must have #{nodeList.size} nodes\"\n exit 1\n end\n i=0\n nodeList.each do |v|\n v.setNodeRealName(hostList[i])\n i+=1 \n end\n end"
] |
[
"0.6213358",
"0.5807358",
"0.55782133",
"0.5537308",
"0.54837286",
"0.5476828",
"0.5357043",
"0.53223133",
"0.52930564",
"0.528568",
"0.528568",
"0.52326375",
"0.51781124",
"0.51679504",
"0.51147133",
"0.51019484",
"0.50953513",
"0.50868034",
"0.5041119",
"0.50144404",
"0.5001954",
"0.5000562",
"0.49843615",
"0.49712393",
"0.4914696",
"0.4908846",
"0.489688",
"0.4885842",
"0.48849994",
"0.48623356",
"0.48541763",
"0.48222622",
"0.48086774",
"0.4801286",
"0.4797313",
"0.4782509",
"0.47760302",
"0.47729343",
"0.47627562",
"0.47603932",
"0.47586042",
"0.47513857",
"0.47392517",
"0.4735789",
"0.47255895",
"0.47250888",
"0.4714159",
"0.4702871",
"0.46767882",
"0.46730813",
"0.46609032",
"0.46586472",
"0.46497476",
"0.46433043",
"0.46433043",
"0.46433043",
"0.46428525",
"0.46339393",
"0.46320614",
"0.46313164",
"0.46288317",
"0.46245363",
"0.46204966",
"0.46092987",
"0.4596795",
"0.45910877",
"0.45892245",
"0.4588813",
"0.45858878",
"0.45702416",
"0.4567365",
"0.456629",
"0.456629",
"0.4563877",
"0.4562748",
"0.4561281",
"0.45584527",
"0.45531443",
"0.4552081",
"0.4550402",
"0.45499843",
"0.45493987",
"0.4544144",
"0.4544144",
"0.4532346",
"0.4532346",
"0.45293525",
"0.45188195",
"0.45108113",
"0.44983175",
"0.4488236",
"0.4476173",
"0.44694677",
"0.44680226",
"0.4465002",
"0.4460495",
"0.44574752",
"0.44569004",
"0.44535598",
"0.445352"
] |
0.5129832
|
14
|
cmd[0] : name of currNode cmd[1] : name of destNode cmd[2] : ip of currNode cmd[3] : time edge was made
|
def edgeb_network(cmd)
node = $node_info.new
$lock.synchronize{
node.src = $hostname
node.dst = cmd[1]
node.cost = 1
node.nexthop = cmd[1]
$rt[cmd[1]] = node
if $local_ip == nil then $local_ip = cmd[2] end
$network.undir_connection($hostname, cmd[1], cmd[3].to_i, 1)
}
#puts "THIS IS THE ROUTING TABLE: #{$rt}"
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edgeu(cmd)\n $dist[cmd[0]] = cmd[1].to_i\n $neighbors[cmd[0]] = cmd[1].to_i\n client = $clients[cmd[0]]\n msg = Msg.new\n msg.setConfig(\"type\", 2)\n msg.setMessage($hostname + \" \" + cmd[1].to_i.to_s)\n sendMessage(client, msg)\n fillInNodes()\nend",
"def edgeu(cmd)\n time = nil\n $lock.synchronize{\n time = $clock.to_i\n $network.update_cost($hostname, cmd[0], cmd[1].to_i, time)\n\n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n } \n\n client = TCPSocket.open($local_ip, $nodesFile[cmd[0]][\"PORT\"])\n client.puts(\"EDGEU2 #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def edgeb_stdin(cmd)\n $record_ip[$hostname] = cmd[0]\n $record_ip[cmd[2]] = cmd[1]\n node = $node_info.new \n time = nil\n $lock.synchronize{ \n node.src = $hostname\n node.dst = cmd[2]\n node.cost = 1\n node.nexthop = cmd[2]\n time = $clock.to_i\n $rt[cmd[2]] = node\n if $local_ip == nil then $local_ip = cmd[0] end\n\n $network.undir_connection($hostname, cmd[2], time, 1)\n }\n\n client = TCPSocket.open(cmd[1], $nodesFile[cmd[2]][\"PORT\"])\n client.puts(\"EDGEB2 #{cmd[2]} #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def edgebReflex(msg, client)\n msg = msg.split(',')\n dstip = msg[0]\n srcip = msg[1]\n dst = msg[2]\n $ips[$hostname] = srcip\n $ips[dst] = dstip\n $dist[dst] = 1\n $neighbors[dst] = 1\n $next[dst] = dst\n $clients[dst] = client\n fillInNodes()\nend",
"def edgeuUpdate(msg)\n msg = msg.split(' ')\n dst = msg[0]\n cost = msg[1].to_i\n $dist[dst] = cost\n $neighbors[dst] = cost\nend",
"def edgeu_network(cmd)\n $lock.synchronize{\n $network.update_cost($hostname, cmd[0], cmd[1].to_i,cmd[2].to_i)\n \n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n }\nend",
"def transfer(node, ins) ; ins ; end",
"def edged(cmd)\n $lock.synchronize{ \n $network.remove_edge($hostname,cmd[0])\n\n if $rt.has_key? cmd[0]\n $rt.delete cmd[0] \n end\n\n }\nend",
"def move_node!(tg,tga,i)\n #first just add node i in\n tga[0].each_index do |ii|\n if (i == tga[0][ii][0])\n tg[0].push(tga[0][ii])\n tga[0][ii] = nil\n break\n end\n end\n #then add the edges, only add edges for which both nodes exist in tg \n tga[1].each_index do |ii|\n if tg[0].index{|item| item[0] == tga[1][ii][0]} && tg[0].index{|item| item[0] == tga[1][ii][1]}\n tg[1].push(tga[1][ii])\n tga[1][ii] = nil\n end\n end\n tga[0].compact!\n tga[1].compact!\nend",
"def getDestination()\r\n\t\treturn @dnode\r\n\tend",
"def initialize(source_instance,transition) \n @number=0 \n @nodecost=0\n @passby=false\n @instance=source_instance\n @transition=transition\n @neighbours=[]\n \n @name = \"NODE \" +source_instance + \" - \" + transition.to_s \n \n end",
"def updateTable(cmd)\n # puts \"TRYING TO UPDATE TABLE\"\n sentFrom = cmd.shift\n curr_edge_time = nil\n new_edge_time = nil\n new_edge_cost = nil\n node = $node_info.new\n arr = nil\n hops = nil\n lis = nil\n loop{\n new_edge_time = cmd[3].to_i\n new_edge_cost = cmd[2].to_i\n\n $lock.synchronize{\n curr_edge_time = $network.get_time(cmd[0],cmd[1])\n }\n\n if curr_edge_time == 0\n #name of srcNode,name of destNode,cost of edge,time of Edge\n $lock.synchronize{\n $network.undir_connection(cmd[0], cmd[1], new_edge_time, new_edge_cost)\n }\n if ($rt.has_key?(cmd[0]) != true)\n node.src = $hostname\n node.dst = cmd[0]\n node.cost = nil #do dijsktras\n node.nexthop = nil #do dijsktras\n $lock.synchronize{\n $rt[cmd[0]] = node\n }\n end \n if($rt.has_key?(cmd[1]) != true)\n node.src = $hostname\n node.dst = cmd[1]\n node.cost = nil #do dijsktras\n node.nexthop = nil #do dijsktras\n $lock.synchronize{\n $rt[cmd[1]] = node\n }\n \n end\n\n elsif curr_edge_time < new_edge_time\n $lock.synchronize{\n $network.update_cost(cmd[0], cmd[1], new_edge_time, new_edge_cost)\n }\n end \n \n cmd.shift(4)\n break if cmd.length < 4\n \n # puts \"ABOUT TO RUN DIJKSTRAS\"\n $lock.synchronize{\n arr = $network.dijkstra($hostname) \n }\n $full_path = arr[0]\n #puts \"THIS IS THE RETURN OF DIJKSTRAS #{arr}\" \n $lock.synchronize{\n $rt.each_key {|key|\n update = $node_info.new \n # puts \"Key IS #{key}\"\n hops = arr[0]\n lis = arr[1]\n prevs = hops[key]\n update.src = $hostname\n update.dst = key\n update.cost = lis[key]\n update.nexthop = prevs[1]\n $rt[key] = update\n # puts \"ROUTING TABLE #{$rt}\"\n }\n }\n }\nend",
"def tellNode(cmd, topo, domain)\n puts \"---------------------------------------------------\"\n d = (domain == nil) ? OConfig.domain : domain\n command = nil\n if (cmd == \"on\" || cmd == \"-on\" || cmd == \"--turn-on\")\n command = \"on\"\n elsif (cmd == \"offs\" || cmd == \"-offs\" || cmd == \"--turn-off-soft\")\n command = \"offSoft\"\n elsif (cmd == \"offh\" || cmd == \"-offh\" || cmd == \"--turn-off-hard\")\n command = \"offHard\"\n end\n if command == nil\n puts \"ERROR - Unknown command : '#{cmd}'\" \n puts \"Use 'help' to see usage information\" \n puts \"\"\n exit 1\n end\n puts \" Testbed : #{d} - Command: #{command}\"\n topo.eachNode { |n|\n url = \"#{OConfig[:tb_config][:default][:cmc_url]}/#{command}?x=#{n[0]}&y=#{n[1]}&domain=#{d}\"\n response = NodeHandler.service_call(url, \"Can't send command to CMC\")\n if (response.kind_of? Net::HTTPOK)\n puts \" Node n_#{n[0]}_#{n[1]} - Ok\"\n else\n puts \" Node n_#{n[0]}_#{n[1]} - Error (node state: 'Not Available')\"\n end\n }\n puts \"---------------------------------------------------\"\nend",
"def connect edge\n self.add edge.src\n self.add edge.dst\n @nodes[edge.src] << edge\n edge\n end",
"def hyperball_on_edge(edge)\n update_node = @counters.get_counter(edge[1])\n neighbor_node = @counters.get_counter(edge[0])\n\n update_node.merge(neighbor_node)\n end",
"def receive_name socket \n data = socket.read_packet_2 'n'\n dist = data[0,2] # 5,5\n flags = data[2,4] # flags\n node_name = data[6, data.length]\n [dist, flags, node_name]\n end",
"def test_add_destination\n assert_equal(@vertex.edges.length, 0)\n @vertex.add_destination(Edge.new('', 4000))\n @vertex.add_destination(Edge.new('', 4000))\n @vertex.add_destination(Edge.new('', 4000))\n assert_equal(@vertex.edges.length, 3)\n end",
"def nodes(direction, *)\n direction == :to ? @to : @from\n end",
"def travel_command( node )\n\t\t\t\tTravelCommand.new @interface, node\n\t\t\tend",
"def dag_longpath(source, sink, weight_edge_graph, graph)\n <<-DOC\n The backtracking method can be generalized to construct a longest path in any DAG. Whenever we compute S(b) as\n S(b) = max (all predecessors a of node b) {S(a) + weight_of_edge_from_a_to_b }\n we simply need to store a predecessor of b that was used in the computation of sb so that we can backtrack later on. \n You are now ready to use backtracking to find the longest path in an arbitrary DAG.\n DOC\n topo_graph = Marshal.load(Marshal.dump(graph))\n topo_nodes = topological_ordering(topo_graph)\n # puts topo_nodes.join(\" \")\n\n puts graph\n keys = graph.keys\n values = graph.values.flatten.uniq\n # puts keys.join(\" \")\n # puts values.join(\" \")\n nodes_with_indegree_zero = keys - values\n puts nodes_with_indegree_zero.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n nodes_with_indegree_zero.each do |node|\n unless node == source\n topo_nodes.delete(node) \n weight_edge_graph.delete_if {|entry| /^#{node}->/.match(entry)}\n end\n end\n\n # nodes_to_consider = [source]\n # next_node = source\n # index = 1\n # loop do\n # break if next_node == sink\n # if graph[next_node]\n # graph[next_node].each do |node|\n # # puts node\n # nodes_to_consider << node unless nodes_to_consider.include?(node)\n # end\n # end\n # next_node = nodes_to_consider[index]\n # index += 1\n # end\n # puts \"nodes_to_consider: \" + nodes_to_consider.join(\" \")\n # topo_nodes.keep_if {|node| nodes_to_consider.include?(node)}\n puts \"topo nodes: \" + topo_nodes.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n incoming_nodes = {}\n incoming_nodes[topo_nodes[0]] = [{\"pred_node\" => nil, \"weight\" => 0}]\n\n\n best_pred = {}\n topo_nodes.each do |node|\n # incoming_nodes[node] = [{\"pred_node\" => nil, \"weight\" => 0}]\n best_pred[node] = {\"pred_node\" => nil, \"weight\" => 0}\n end\n\n # puts weight_edge_graph.join(\" \")\n (1..(topo_nodes.length-1)).each do |i|\n node = topo_nodes[i]\n puts \"Node: \" + node\n all_weights = []\n weight_edge_graph.each do |entry| \n # puts \"Entry: \" + entry\n # puts best_pred\n if /(\\d+)->#{node}:(\\d+)/.match(entry) \n incoming_nodes[node] = [] unless incoming_nodes[node]\n pred_node_matched = /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n pred_node_weight = /(\\d+)->#{node}:(\\d+)/.match(entry)[2].to_i\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[2]\n incoming_nodes[node] << {\"pred_node\" => pred_node_matched, \"weight\" => pred_node_weight}\n all_weights << (pred_node_weight + best_pred[pred_node_matched][\"weight\"])\n end\n end\n # puts all_weights.join(\" \")\n if incoming_nodes[node] \n # puts incoming_nodes[node]\n incoming_nodes[node].each do |pred_node_entry|\n # puts all_weights.join(\" \")\n if ((best_pred[pred_node_entry[\"pred_node\"]][\"weight\"] + pred_node_entry[\"weight\"]) == all_weights.max)\n best_pred[node][\"weight\"] = all_weights.max\n best_pred[node][\"pred_node\"] = pred_node_entry[\"pred_node\"]\n end\n end\n end\n end\n # puts incoming_nodes\n # puts best_pred\n length = best_pred[sink][\"weight\"]\n path = [sink]\n node = sink\n loop do\n puts node\n break if node == source\n node = best_pred[node][\"pred_node\"]\n path << node\n end\n return length, path.reverse\n end",
"def addOtherEdge (node, dist)\n\t\t@edges.push([node, dist])\n\tend",
"def distance_between_two_nodes(src_name, dest_name)\n\t\tpath = nil\n\n\t\tsrc_node = @graph.get_node(src_name)\n\t\tif src_node.nil?\n\t\t\tsrc_node = create_node_and_populate_graph(src_name)\n\t\tend\n\n\t\tdest_node = @graph.get_node(dest_name)\n\t\tif dest_node.nil?\n\t\t\tdest_node = create_node_and_populate_graph(dest_name)\n\t\telse\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\n\t\tif path.empty?\n\t\t\tpopulate_graph(src_node) if !src_node.populated\n\t\t\tpopulate_graph(dest_node) if !dest_node.populated\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\t\t\n\t\t# after check on first (separation of 2) level we do another two level of check\n\t\tif path.empty?\n\t\t\t(1..2).each do |level|\n\t\t\t\tsrc_connections = get_persons_based_on_level(src_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(src_connections)\n\t\t\t\tdst_connections = get_persons_based_on_level(dest_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(dst_connections)\n\t\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\t\t\tbreak if path.any?\n\t\t\tend\n\t\tend\n\n\t\twrite_to_yaml\n\n\t\tputs \"Path:\"\n\t\tputs path\n\t\tputs \"Degree of separation :\" + (path.nil? ? \"None\" : (path.size - 1).to_s)\n\tend",
"def lsp()\n\t$sequencenum += 1\n\tmsg = \"LSP \"\n\tmsg<<\"#{$hostname} \"\n\t#puts (\"neighbor in lsp = #{$neighbors}\")\n\t$neighbors.each do |key, value|\n\t\tmsg<<\"#{value.name}\"\n\t\tmsg<<\":\"\n\t\tmsg<<\"#{value.cost}\"\n\t\tmsg<<\"|\"\t\t\n\tend\n\t#puts (\"before chomp #{msg}\")\n\tmsg = msg.chomp(\"|\")\n\tmsg<<\" #{$sequencenum}\"\n\t#puts (\"sending msg #{msg}\")\n\t# flooding each neighbor node with lsp\n\t#puts (\"flooding msg = #{msg}\")\n\tflood(msg)\nend\n\n#pass whatever message you receive to each of the connecting negihbors of the node\ndef flood(msg)\n\t#$semaphore.synchronize{\n\t$neighbors.each do |key, value|\n\t#puts (\"writing to #{value.name} : #{msg} through socket #{value.sock}\")\n\t#value.sock.puts(\"#{msg}\")\\\n\t\twriteTo(value.sock, msg)\n\t\t#$pq.insert(Time.new, Event.new(\"WRITE\", [value.sock, msg]))\n\tend\n\t#}\nend",
"def on_getaddr\n #addrs = @node.addrs.select{|a| a.time > Time.now.to_i - 10800 }.shuffle[0..250]\n #p \"<< addr (#{addrs.size})\"\n #send_data P::Addr.pkt(*addrs)\n end",
"def nextHop( target_id )\n m = 0\n n = -1\n while @guid[m] == target_id[m] && m < @m_max\n m += 1\n end\n n = target_id[m]\n n = n.to_s\n n = n.hex\n # Once we have M and N we check the routing table at that location to see if we have an entry\n # This entry will be once digit closer than the current nodes GUID\n if @routing_table[[0,m,n]] != nil\n return InetAddr.new( @routing_table[[0,m,n]][:ip_address], @routing_table[[0,m,n]][:port] ), m, n\n # If not we search the entire routing table for the entry with the GUID closest to the target_id\n else\n shortestDistance = dist( target_id, @guid ) # distance between ourself and target\n # we will only send message on if there is a closer address\n nh = InetAddr.new()\n @routing_table.each do |key, array| # Access each element of routing table\n # IF it is less than out distance to target set it as shortest\n if dist( target_id, array[:node_id] ) < shortestDistance && dist( target_id, array[:node_id] ) != 0\n shortestDistance = dist( target_id, array[:node_id] )\n nh.ip = array[:ip_address]\n nh.port = array[:port]\n end\n end\n return nh, m, n\n # Function returns an InetAddr struct as well as M and N\n end\n end",
"def save_message_from(n, delta)\n incoming[neighbors.index(n)] = delta\n end",
"def conn_ip(n_s, n_d)\n nodes_to_addrs2 = File.readlines(ARGV[0])\n #puts \"\\nn_s = \" + n_s + \" n_d = \" + n_d\n \n n_s_ip_lines = nodes_to_addrs2.select{ |line| line =~ /#{n_s}\\s/ }\n #puts \"\\nPRINT N_S LINES\"\n #puts n_s_ip_lines\n\n\n n_s_ip = []\n n_s_ip_lines.each {|line|\n n_s_ip.push line.split[1..2].join('\\t')\n }\n\n #puts \"\\nPRINTING N_S IPs\"\n #puts n_s_ip\n \n\n n_d_ip_lines = nodes_to_addrs2.select { |line| line =~ /#{n_d}\\s/ }\n #puts \"\\nPRINTING N_D LINES\"\n #puts n_d_ip_lines\n\n\n n_d_ip = []\n n_d_ip_lines.each {|line|\n n_d_ip.push line.split[1..2].join('\\t')\n }\n #puts \"\\nPRINTING N_D IPs\"\n #puts n_d_ip\n\n n_s_ip.each{ |s_ip| \n n_d_ip.each{ |d_ip|\n if ((destination_of_addr s_ip) == d_ip)\n #puts \"CONNECTION WITH \" + d_ip\n return d_ip\n end\n }\n }\nend",
"def output_route( node )\n if @visited[node].previous\n return output_route( @visited[node].previous ) + \" -> \" + node.to_s\n else\n return node.to_s\n end\n end",
"def add_edge(from_node, to_node)\n add_node(from_node)\n add_node(to_node)\n @nodes[from_node] << to_node\n @node_dir_ancestors[to_node] << from_node\n\n if self.has_cycle\n puts \"No longer DAG\"\n end\n end",
"def nodes\n [@from, @to]\n end",
"def neighbours(e)\n\t\tneighbours = []\n\t\t@e.each do |edge|\n\t\t\tneighbours << edge.dest if edge.src == e\n\t\tend\n\t\tneighbours\n\tend",
"def add_edge(id1, id2)\n # YOUR WORK HERE\n end",
"def reachable\n @vertices.each do |vk, is_up|\n if is_up\n print \"#{vk}\\n\"\n if @edges_up[vk]\n @edges_up[vk].each do |ek, up_too|\n if up_too\n print \" #{ek}\\n\"\n end\n end\n end\n end\n end\n end",
"def push_edge(edge)\n if @leader.nil?\n @leader = edge.node1.leader\n edge.node2.leader = @leader\n else\n edge.node1.leader = @leader\n edge.node2.leader = @leader\n end\n \n adj_edge1_index = $vertices[edge.node1.node].first # we could select here first edge since \n adj_edge2_index = $vertices[edge.node2.node].first # they all are adjacent\n\n if adj_edge2_index && adj_edge1_index\n puts \"adj_edge1_index - #{adj_edge1_index}, adj_edge2_index - #{adj_edge2_index}\"\n end\n\n adj_edge1 = $edges[adj_edge1_index]\n adj_edge2 = $edges[adj_edge2_index]\n\n # 3 branches should be considered\n # 1st - edge is merged to only scc with adj edge1 o--o--o o----o \n # 2nd - edge is merged to only scc with adj edge2 o--o o--o----o\n # 3rd - edge is merged to scc1 or scc2 and these sccs are merges as well o--o---o--o\n\n if adj_edge1 && adj_edge2\n if adj_edge1.scc && adj_edge2.scc # merging 2 SCCs\n puts \"merging sccs\"\n if adj_edge1.scc.count > adj_edge2.scc.count\n @vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n # change leaders of SCC of adjacent edge 2\n adj_edge2.scc.vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n adj_edge2.scc.edges.each{|e| e.scc = adj_edge1.scc}\n @mst.delete_scc(adj_edge2.scc) # remove SCC from the list\n else\n @vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n # change leaders of SCC of adjacent edge 1\n adj_edge1.scc.vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n adj_edge1.scc.edges.each{|e| e.scc = adj_edge2.scc}\n @mst.delete_scc(adj_edge1.scc) # remove SCC from the list\n end\n elsif adj_edge1.scc || adj_edge2.scc\n scc = adj_edge1.scc || adj_edge2.scc # only one should be available\n @vertices.each{ |v| v.node.leader = scc.leader }\n puts 'adding edge ' + edge.inspect + ' to scc ' + scc.inspect\n end\n else\n @vertices << edge.node1\n @vertices << edge.node2\n @edges << edge\n end\n\n edge.scc = self # save link to the SCC in the edge itself\n end",
"def expand_graph_adj(vertex, pass = nil)\n m = $game_map\n add_vertex(vertex)\n \n tp = vertex.x == 21 && vertex.y == 5\n \n t = Time.now\n vx,vy = vertex.x, vertex.y\n return if !MoveUtils.ev_passable?(vx,vy, @source)\n \n ([Vertex.new(vx-1,vy, m.terrain_tag(vx-1,vy)),Vertex.new(vx,vy-1, m.terrain_tag(vx,vy-1))]).each_with_index do |v,i|\n next if !@verticies[v]\n x,y = v.x,v.y\n dir = (i+1)*4\n ev_pass = MoveUtils.ev_passable?(x,y,@source)\n next if !ev_pass\n add_edge(vertex, v, {} , opp_dir(dir), dir)\n end\n end",
"def get_adjacent_nodes(node) #[[6,1]]\n\tadj = []\n\tnode = [node]\n\tnode.each do |node|\n\t\tx, y = node[0], node[1]\n\t\tadj = [[(x+1),y], [(x-1), y], [x, (y+1)], [x, (y-1)]]\n\tend\n\tadj\nend",
"def shortest_paths(source, dest)\n @graph_paths=[]\n @source = source\n dijkstra source\n @path=[]\n find_path dest\n actual_distance=if @distance[dest] != INFINITY\n @distance[dest]\n else\n \"no path\"\n end\n \"Shortest route and distance : #{@path.join(\"-->\")}, #{actual_distance} km\"\n end",
"def path_to(node)\n return unless has_path_to?(node)\n path = []\n current_node = node\n\n while(current_node != @source_node) do\n path.unshift(current_node)\n current_node = @edge_to[current_node]\n end\n\n path.unshift(@source_node)\n end",
"def path_to(node)\n return unless has_path_to?(node)\n path = []\n current_node = node\n\n while(current_node != @source_node) do\n path.unshift(current_node)\n current_node = @edge_to[current_node]\n end\n\n path.unshift(@source_node)\n end",
"def other_vertex(direction, edge)\n case direction\n when :in; edge.source\n else\n edge.target\n end\n end",
"def traceroute(cmd)\n\tdst = cmd[0]\n\n # Check to see if there is a next hop\n next_hop = $next[dst]\n if next_hop == \"NA\"\n STDOUT.puts \"TRACEROUTE ERROR: HOST UNREACHABLE\"\n return\n end\n\n # This will print out itself with hop 0 and time 0.00\n\tSTDOUT.puts(\"0 \" + $hostname + \" 0.00\")\n \n if next_hop == $hostname\n return\n end\n\n # Sets up the message for tracerouteCallBack\n client = $clients[next_hop]\n msg = Msg.new\n msg.setConfig(\"type\", 4)\n msg.setConfig(\"code\", 0)\n msg.setMessage($hostname + \" \" + dst + \" \" + dst + \" 0 \" + $currtime.to_f.round(4).to_s)\n $traceroute_finish = false\n $hop_counter = \"1\"\n sendMessage(client, msg)\n\n start_time = $currtime\n while $currtime - start_time < $ping_timeout\n if $traceroute_finish\n return\n end\n sleep(0.1)\n end\n\tSTDOUT.puts(\"TIMEOUT ON HOPCOUNT \" + $hop_counter)\nend",
"def distance_between(node, visited = [], queue = [node])\n shifted = queue.shift\n output = [shifted]\n visited.push(node)\n\n node.connections.each do |connection|\n if !visited.include?(connection) && !queue.include?(connection)\n connection.level = node.level + 1\n queue.push(connection)\n end\n end\n queue.empty? ? output : output + distance_between(queue[0], visited, queue)\nend",
"def push(source_loc, current_loc, next_loc, dir, goal_loc, depth)\n \n extra_cost = depth\n node_cost = predict_movement_cost(source_loc,current_loc,goal_loc) + extra_cost\n node = Map_Address.new(next_loc.x,next_loc.y,node_cost)\n \n @nodes.push(node)\n @nodes.sort!{ |a,b| a.cost <=> b.cost}\n \n # save source direction\n @move_dir[ hash_address(next_loc.x,next_loc.y) ] = dir\n # save source address\n @nodes_parent_id[ hash_address(next_loc.x, next_loc.y) ] = hash_address(current_loc.x,current_loc.y)\n end",
"def nextHop(target_id)\n m = 0\n n = -1\n while @guid[m] == target_id[m] && m < @m_max\n m += 1\n end\n n = target_id[m]\n n = n.to_s\n n = n.hex\n\n # Checking routing table at that location to see if has an entry\n # If has,the entry will be a digit closer than the current nodes GUID\n if @routing_table[[0, m, n]] != nil\n return InetAddr.new(@routing_table[[0, m, n]][:ip_address], @routing_table[[0, m, n]][:port]), m, n\n\n # If not,searching the entire routing table for the entry with the GUID closest to the target_id\n else\n shortestDistance = distancing(target_id, @guid)\n # Sending message on if there is a closer address\n nh = InetAddr.new()\n @routing_table.each do |key, array| # Accessing each element of routing table\n if distancing(target_id, array[:node_id]) < shortestDistance && distancing(target_id, array[:node_id]) != 0\n shortestDistance = distancing(target_id, array[:node_id])\n nh.ip = array[:ip_address]\n nh.port = array[:port]\n end\n end\n return nh, m, n\n end\n end",
"def handle_connections\n @node.connections.sort{|x,y| y.uptime <=> x.uptime}.map{|c|\n \"#{c.host.rjust(15)}:#{c.port} [#{c.direction}, state: #{c.state}, \" +\n \"version: #{c.version.version rescue '?'}, \" +\n \"block: #{c.version.block rescue '?'}, \" +\n \"uptime: #{format_uptime(c.uptime) rescue 0}, \" +\n \"client: #{c.version.user_agent rescue '?'}]\" }\n end",
"def nodes\n @from | @to\n end",
"def dest\n self[:ip_dest]\n end",
"def edged(cmd)\n $ips.delete(cmd[0])\n $dist[cmd[0]] = \"INF\"\n $neighbors.delete(cmd[0])\n $next[cmd[0]] = \"NA\"\n client = $clients[cmd[0]]\n client.close()\n $clients.delete(cmd[0])\nend",
"def draw_node(dx, dy, x, y, connections, type, scale)\n draw_x = dx + x*$node_size + $node_size / 2.0\n draw_y = dy + y*$node_size + $node_size / 2.0\n Node.create({:x => draw_x, :y => draw_y, :factor_x => scale, :factor_y => scale}, type)\n n, s, e, w = connections.values\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 0, :factor_x => scale, :factor_y => scale) if n == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 180, :factor_x => scale, :factor_y => scale) if s == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 90, :factor_x => scale, :factor_y => scale) if e == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 270, :factor_x => scale, :factor_y => scale) if w == 1\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 0, :factor_x => scale, :factor_y => scale) if n == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 180, :factor_x => scale, :factor_y => scale) if s == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 90, :factor_x => scale, :factor_y => scale) if e == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 270, :factor_x => scale, :factor_y => scale) if w == 2\n end",
"def to_loc\n nodes = @nodes.collect(&:to_loc)\n @connections.each do |n0, n1|\n nodes.find { |n| n.id == n0.id }.add_link n1.id\n end\n exits = @nodes.select(&:exit?)\n # Verify that @exits is a subset of @nodes\n exits = exits.map { |e| nodes.find { |n| n.id == e.id } }\n StructureResult.new nodes, exits\n end",
"def next_nodes\n transitions.map(&:target)\n end",
"def neigh_command_builder(name, cmd, opts)\n command_builder(\"neighbor #{name} #{cmd}\", opts)\n end",
"def send_neighbour(host, port)\n\t\thost = Socket.ip_address_list.detect { |intf| intf.ipv4_private? }.ip_address if host == \"localhost\"\n\t\tnode = NodeInfo.new(host, port)\n\t\t@neighbour_nodes << node\n\t\tsend_message [\"NEW_NODE\", @info], 0, host, port\t\n\tend",
"def path_to(node)\n return unless @visited.include?(node)\n path = []\n while(node != @node) do\n path.unshift(node) \n node = @edge_to[node]\n end\n path.unshift(@node)\n end",
"def handle_addrs count = 32\n @node.addrs.weighted_sample(count.to_i) do |addr|\n Time.now.tv_sec + 7200 - addr.time\n end.map do |addr|\n [addr.ip, addr.port, Time.now.tv_sec - addr.time] rescue nil\n end.compact\n end",
"def out_neighbors(vertex)\n\tend",
"def all_paths_source_target(graph, results=[], current_node=0, current_path=[])\n if current_node == graph.length - 1\n return results << (current_path + [current_node])\n end\n\n graph[current_node].each do |node|\n all_paths_source_target(graph, results, node, (current_path + [current_node]))\n end\n\n return results\nend",
"def build_path(start, end_pos)\n node = Node.new(start[0], start[1])\n target = Node.new(end_pos[0], end_pos[1])\n visited_nodes = []\n next_moves = [node]\n until next_moves.empty? do\n node = next_moves.shift\n puts \"Current node: #{node.x}, #{node.y}\"\n if node.x == target.x && node.y == target.y \n return node\n end\n visited_nodes.push(node)\n node.moves = get_moves(node)\n node.moves.reject do |square|\n visited_nodes.include?(square)\n end\n node.moves.each do |move| \n next_moves.push(move)\n end\n end\n return node\nend",
"def to_s\n \"#{@name}::#{@num_nodes}::#{Base64.encode64(@start_time._dump).chomp}::#{Base64.encode64(@end_time._dump).chomp}::#{total_time}::#{cost}\"\n end",
"def path_from_src_to_dest(graph, src=0, dest=0)\n\t\t# Update source and destination\n\t\t@source, @destination = src, dest\n\n\t\t# Check if source is undefined, if so return empty path\n\t\tif @source == 0\n\t\t\treturn []\n\t\tend\n\n\t\t# Generate a connections hash based on graph edges\n\t\toutgoing = Hash.new()\n\t\tnodes = graph.nodes.keys\n\t\tresult = Array.new()\n\n\t\tgraph.nodes.keys.each {|key| outgoing[key] = Hash.new() }\n\t\tgraph.edges.values.each do |edge|\n\t\t\t# Is it possible for any two issues to have multiple links\n\t\t\t# between them?\n\t\t\toutgoing[edge.a.id][edge.b.id] = edge\t\t\n\t\tend\n\n\t\t# If an edge already exists in the graph from source to destination\n\t\tif outgoing[@source].has_key?(@destination)\n\t\t\tresult.push(outgoing[@source][@destination].id)\n\t\t\treturn result\n\t\tend\n\t\t\t\n\t\t# Compute all paths from source\n\t\tpaths_tracer, paths_distances, relationships_on_paths = compute_paths_from_source(outgoing, nodes)\n\t\t\n\t\t# Find the shortest path through the graph between source and destination\n\t\tif destination != 0\n\t\t\treturn trace_path_src_to_dest(outgoing, paths_tracer)\n\t\tend\n\n\t\t# This happens only if the destination is 0, as it would have returned otherwise.\n\t\t# Return available relationships, distances, \n\t\treturn important_relationships_from_source(paths_tracer, paths_distances, relationships_on_paths)\n\tend",
"def path(source, target, meta)\n # retrieve the path to the target node, using the meta hash\n # that was constructed at each iteration of the `each` iteration\n predecessor = target\n result_path = []\n\n # follow the leads from the back\n until predecessor == source\n result_path << predecessor.number\n predecessor = meta[predecessor]\n end\n\n # add the source, since now `predecessor == source` is true\n result_path << source.number\n result_path.reverse.join(\", \")\nend",
"def checkNode()\n source_set = []\n neighbor_set = []\n $networks.each do |s, nb|\n source_set << s\n nb[\"neighbors\"].each do |s_, dist|\n neighbor_set << s_\n end\n end\n source_set.sort!\n source_set.uniq!\n neighbor_set.sort!\n neighbor_set.uniq!\n return source_set == neighbor_set\nend",
"def children\n out_edges.each{|e| e.dest}\n end",
"def add_edge(src, dest, weight)\n @v << src if !@v.include?(src)\n @v << dest if !@v.include?(dest)\n new_edge = Edge.new(src,dest, weight)\n src.out_edges << new_edge\n dest.in_edges << new_edge\n @e << new_edge\n end",
"def getHubCity()\n vertex = 0\n city = \"\"\n @parse.map{ |airport|\n if(airport[\"destinations\"].length > vertex)#if target has more vertex swap\n city = airport[\"name\"]\n vertex =airport[\"destinations\"].length\n end\n }\n \n puts \"The city with more connections is \" + city + \" with #{vertex}\"\n end",
"def internal_connections\n stroke(200, 0, 0, 80)\n nodes[0..nodes.size - 1].each_with_index do |pi, i|\n nodes[i + 1..nodes.size - 1].each do |pj|\n line(pi.x, pi.y, pj.x, pj.y)\n end\n end\n end",
"def edge(resource,node1,node2) \n label = fetch_fragment(resource) if(@options.showedges)\n color = colour_map(resource) if (@options.colour_code)\n @root.add_edge(node1,node2,:label=>label,:color=>color)\n end",
"def shortest_paths(dest)\n position = dest\n final = {}\n analisados = {}\n route = []\n route << dest\n @previous['a'] = -1\n\n @nodes.each do |n|\n analisados[n] = false\n end\n analisados[position] = true\n\n while analisados(analisados)\n adyacentes(position, analisados).each do |n|\n if @distance[n] == (@distance[position] - graph[n][position])\n @previous[position] = n\n position = n\n route << n\n end\n analisados[n] = true\n end\n\n end\n route << 'a'\n route\n end",
"def follow(edge)\n if edge.nodes.first == self\n edge.nodes.last\n else\n edge.nodes.first\n end\n end",
"def detect_cycle_in_graph(edges)\nend",
"def edges_to(node)\n edges.select { |edge| edge.last == node }\n end",
"def flat_edgelist\n ni = Hash.new\n @nodes.each_with_index { |n,i| ni[n]=i+1 }\n sa = []\n da = []\n @links.each_value do |l| \n sa << ni[l.src]\n da << ni[l.dest]\n end\n sa + da\n end",
"def destination; frame[:destination]; end",
"def dfs_topological_sort\n # sorted by finished time reversely and collect node names only\n timestamp, = self.depth_first_search\n timestamp.sort {|a,b| b[1][1] <=> a[1][1]}.collect {|x| x.first }\n end",
"def findShortest(graph_nodes, graph_from, graph_to, ids, val)\n return -1 if ids.count(val)<=1 # no two nodes with color val\n dmin = graph_nodes\n num_edges = graph_from.length\n neighbors = {}\n 0.upto(num_edges-1) do |i|\n if neighbors[graph_from[i]]\n neighbors[graph_from[i]] << graph_to[i]\n else\n neighbors[graph_from[i]] = [graph_to[i]]\n end\n if neighbors[graph_to[i]]\n neighbors[graph_to[i]] << graph_from[i]\n else\n neighbors[graph_to[i]] = [graph_from[i]]\n end\n end\n p neighbors\n ids.each_with_index do |v,i|\n if v == val\n # zero-base index to one-base index \n source_node = i+1\n # look for others using bfs (stop looking if distance > dmin)\n queue = []\n visited = []\n backtrace = {}\n queue << source_node\n while !(queue.empty?)\n current_node = queue.shift\n visited << current_node\n if (current_node!=source_node) && (ids[current_node-1]==val)\n puts \"we are here!\"\n # how did I get here? backtrace\n hops = 0\n trace_node = current_node\n while (trace_node!=source_node)\n trace_node = backtrace[trace_node]\n hops +=1\n end\n if hops < dmin\n dmin = hops\n end\n break\n end\n neighbors[current_node].each do |xnode|\n if !(visited.include?(xnode))\n queue << xnode\n backtrace[xnode] = current_node\n end\n end\n end\n p visited\n end\n end\n if dmin == graph_nodes\n return -1\n else\n return dmin\n end\nend",
"def status()\n\tneighbors = []\n $neighbors.each do |node, distance|\n neighbors << node\n end\n neighbors.sort\n msg = \"Name: \" + $hostname + \"\\n\"\n msg += \"Port: \" + $port + \"\\n\"\n msg += \"Neighbors: \" \n neighbors.each do |node|\n msg += node + \",\"\n end\n if msg[-1] == \",\"\n msg = msg.chop\n end\n STDOUT.puts msg\nend",
"def compute(source, num_nodes)\n x = [source]\n source.length = 0\n until x.length == num_nodes\n min_edge = nil\n min_distance = Float::INFINITY\n x.each do |xnode|\n xnode.outgoing_edges.each do |xedge|\n next if xedge.visited?\n curr_distance = xnode.length + xedge.distance\n if curr_distance <= min_distance\n min_distance = curr_distance\n min_edge = xedge\n end\n end\n end\n min_edge.head.length = min_distance\n x << min_edge.head\n end\n x\nend",
"def shortest_path_to(dest_node)\n return unless has_path_to?(dest_node)\n path = []\n while (dest_node != @node) do\n path.unshift(dest_node)\n dest_node = @edge_to[dest_node]\n end\n path.unshift(@node)\n end",
"def travel_cost( dest )\n sp = shortest_path( dest )\n path_cost( sp )\n end",
"def dest_ip\n self[:dest_ip]\n end",
"def rearrange(node)\n idx = @path.index(node) + 1\n # cost = @cost - distance(x, y) - distance(x, e)\n cost = @cost - @@graph.distance(node, @path[idx]) + @@graph.distance(node, path.last)\n new_path = @path[0, idx] + @path[idx, @path.length].reverse\n LKPath.new(new_path, cost)\n end",
"def getNode(name)#name is the int for the vertice\n\t\t@graph.select {|nodes| nodes.node == name }[0] \n\tend",
"def add_edge(src, dest)\n # add a edge to the head\n @adjList[src] << dest\n # since this graph is not directed we need to do the oposite also\n # @adjList[dest] << src\n @edges += 1\n end",
"def update\n @edge = Edge.find_by_src_id_and_dest_id(params[:edge][:src_id] , params[:edge][:dest_id])\n\n if @edge.update(edge_params)\n flash[:notice] = t('edge_updated_success')\n\t\t\t\tredirect_to :controller => \"nodes\" , :action => \"listByCourse\" , :course_id => @edge.src.course_id\t\t\n else\n render :action => \"edit\" \n end\n end",
"def op\n sequence[ip]\n end",
"def find_neighbors(node)\n nbrs = []\n self.edges.each do |e|\n nbrs.push(e.target) if e.source == node\n nbrs.push(e.source) if e.target == node\n end\n nbrs\n end",
"def insert(node,path)\n if path[:edge_list].empty?\n path[:edge_list] << [node,node]\n else\n deleted_edge = path[:edge_list].min_by{|edge| distance(edge.first,node) + distance(node,edge.last) - distance(edge.first,edge.last)}\n deleted_distance = distance(deleted_edge.first,deleted_edge.last)\n path[:edge_list].delete(deleted_edge)\n path[:edge_list] << [deleted_edge.first,node]\n path[:edge_list] << [node, deleted_edge.last]\n path[:length] += (distance(deleted_edge.first,node) + distance(node,deleted_edge.last) - distance(deleted_edge.first,deleted_edge.last))\n end\n end",
"def directed?() false; end",
"def edge_name\n @edge_name\n end",
"def seek_from_node(starting_node)\n puts \"seek started from node #{starting_node.inspect}...\"\n \n # -- PART I -- (starting from one node for now...) \n visited_nodes = grow_basic_path([ starting_node ])\n \n puts \"got basic path of length #{visited_nodes.length}, moving on to IIa)...\"\n \n # -- PART II a) --\n if visited_nodes.length < nodes.length\n target_nodes = extract_target_nodes_from_path(visited_nodes)\n \n while target_nodes.length > 0\n puts \"TNL: #{target_nodes.length}\"\n visited_nodes = restructure_path(visited_nodes, target_nodes)\n target_nodes = extract_target_nodes_from_path(visited_nodes)\n end\n end\n \n puts \"...done, moving on to IIb)...\"\n \n # -- PART II b) --\n if visited_nodes.length < nodes.length\n visited_nodes = trim_and_extend_path(visited_nodes)\n end\n \n puts \"...done, moving on to IIc)...\"\n \n # -- PART II c) --\n if visited_nodes.length < nodes.length\n visited_nodes = trim_and_extend_path(visited_nodes.reverse)\n end\n \n # -- PART III --\n results = {}\n \n if visited_nodes.length < nodes.length \n results[:path] = visited_nodes\n else\n results[:tour] = visited_nodes\n \n cycle_starts = connected_to(visited_nodes.first).map do |node|\n visited_nodes[visited_nodes.index(node) - 1]\n end\n cycle_ends = connected_to(visited_nodes.last)\n \n (cycle_starts & cycle_ends).each do |node|\n index = visited_nodes.index(node)\n \n circuit = visited_nodes[0..index] + [ visited_nodes.last ]\n circuit += visited_nodes[(index + 1 - visited_nodes.length)..-2].reverse\n \n results[:cycles] ||= []\n results[:cycles] << circuit\n end\n end\n \n results\n end",
"def fillInNodes()\n msg = Msg.new\n msg.setConfig(\"type\", 1)\n msg.setConfig(\"ttl\", $ports.length)\n msg.setConfig(\"seq\", nextSeqNum())\n msg_str = $hostname + \"\\t\"\n if $neighbors.length > 0\n $neighbors.each do |dst, distance|\n msg_str += dst + \",\" + distance.to_s + \"\\t\"\n end\n msg.setMessage(msg_str)\n $clients.each do |dst, client| \n sendMessage(client, msg)\n end\n end\nend",
"def test_add_edge_with_cycles\n @graph.add_edge('a', 'b');\n @graph.add_edge('b', 'c');\n @graph.add_edge('c', 'a');\n\n # 0 and 2 are indexes of vertex a and vertex c respectively\n assert(@graph.vertices[0].neighbours[2] == true && @graph.vertices[2].neighbours[0] == true)\n end",
"def shortest_paths(source, dest)\n\t\t\t@source = source\n\t\t\tdijkstra source\n\t\t\tprint_path dest\n\t\t\treturn @distance[dest]\n\t\tend",
"def path_to(v)\n return nil unless @visited.include?(v)\n\n path = []\n cur_node = v\n while (cur_node != source_node)\n path << cur_node\n cur_node = @edge_to[cur_node]\n end\n path << source_node\n path.reverse\n end",
"def add_connections(start_cell, end_cell)\n start_cell.connected_cells.each do |cell|\n (@cells_to_visit << cell).sort_by! { |cell| cell.distance_to(end_cell) } unless cell_array_visited.include?(cell)\n end\n end",
"def plan(s1, s2)\r\n if s1 == s2\r\n return []\r\n end\r\n\r\n condensed_path = Array.new\r\n full_path = Array.new\r\n temp = BFS.new(graph, find_node(s1)).shortest_path_to(find_node(s2))\r\n\r\n temp.each {|x| full_path.push(x.to_s)}\r\n condensed_path.push(full_path.first)\r\n condensed_path = condensed_path + transfer_stations(full_path)\r\n \r\n if condensed_path.last != full_path.last #need to test this more\r\n condensed_path << full_path.last\r\n end\r\n\r\n return condensed_path\r\n end",
"def timelink(src, dest, time, w=1, add=true)\n l = link(src, dest, w, add)\n l << time\n end",
"def connect(src, tar, distance = 1)\n unless @nodes.include?(src)\n raise ArgumentError, \"No such node: #{src}\"\n end\n unless @nodes.include?(tar)\n raise ArgumentError, \"No such node: #{tar}\"\n end\n @edges.push Edge.new(src, tar, distance)\n end",
"def node; changeset.node; end",
"def Close_ALL_pending_links(graph,current_job,destination_node)\r\n \r\n node_to_delete = Array.new\r\n \r\n # chiudo i link aperti, ciclando sull'array dei nodi pendenti\r\n @OpenLink.each_with_index do |source_node,i|\r\n \r\n unless source_node.nil?\r\n if source_node.split('.')[0].nil? # allora ho passato un output\r\n # aggiungo il link\r\n graph.add_link(source_node, current_job + \".\" + destination_node, \"\") \r\n puts \"aggiunto link #{i}:\" + source_node + \"->\" + current_job + \".\" + destination_node\r\n end\r\n \r\n if source_node.split('.')[0] == current_job\r\n # aggiungo il link\r\n graph.add_link(source_node, destination_node, \"\") \r\n puts \"aggiunto link:\" + source_node + \"->\" + destination_node\r\n end \r\n end\r\n end\r\n \r\n #dopo aver collegato tutti i link aperti di quel job, creo la lista degli elementi da cancellare \r\n @OpenLink.each do |source_node|\r\n unless source_node.nil?\r\n if source_node.split('.')[0] == current_job\r\n node_to_delete << source_node\r\n end\r\n end\r\n end\r\n # elimino dall'array gli elementi selezionati\r\n node_to_delete.each do|delete_node|\r\n @OpenLink.delete(delete_node);\r\n end\r\n\r\n end"
] |
[
"0.6386743",
"0.6305659",
"0.6026351",
"0.60089004",
"0.5930569",
"0.57697797",
"0.56592053",
"0.5602687",
"0.5590002",
"0.55648386",
"0.55371714",
"0.5525014",
"0.545143",
"0.5281572",
"0.5271316",
"0.5220897",
"0.5171023",
"0.516839",
"0.5148021",
"0.5145073",
"0.5144903",
"0.5134455",
"0.51176727",
"0.51120186",
"0.5074209",
"0.5074037",
"0.50319165",
"0.5011453",
"0.49995965",
"0.4982607",
"0.49730214",
"0.49701828",
"0.49602628",
"0.49595153",
"0.49451888",
"0.4945114",
"0.49305928",
"0.4928439",
"0.4928439",
"0.49200612",
"0.49181822",
"0.49162376",
"0.49101245",
"0.49030906",
"0.4891048",
"0.4889859",
"0.48885614",
"0.48833916",
"0.4875678",
"0.48600507",
"0.48566204",
"0.48490342",
"0.48439747",
"0.48238286",
"0.48129034",
"0.48115212",
"0.48101622",
"0.48083082",
"0.48016647",
"0.47966745",
"0.47937804",
"0.4793479",
"0.4793222",
"0.47869185",
"0.4784209",
"0.47759333",
"0.47741413",
"0.47683316",
"0.47669685",
"0.4749639",
"0.47398192",
"0.47390962",
"0.47342736",
"0.4734253",
"0.47319883",
"0.47107804",
"0.47099966",
"0.4709025",
"0.4705084",
"0.46873564",
"0.46866083",
"0.46824992",
"0.46818325",
"0.46809265",
"0.4678919",
"0.46789068",
"0.46759874",
"0.46714103",
"0.46704045",
"0.46645138",
"0.46600634",
"0.46592093",
"0.46589935",
"0.46583375",
"0.46545818",
"0.46540946",
"0.46502644",
"0.46464327",
"0.46442443",
"0.46438128"
] |
0.6612269
|
0
|
Part 1 Dest of node to remove edge from
|
def edged(cmd)
$lock.synchronize{
$network.remove_edge($hostname,cmd[0])
if $rt.has_key? cmd[0]
$rt.delete cmd[0]
end
}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def remove_edge(id1, id2)\n # YOUR WORK HERE\n end",
"def delete_edge!(from, to)\n protected_delete_edge!(from, to)\n protected_delete_edge!(to, from)\n @edge_number -= 1\n end",
"def remove_edge(from, to)\n\t\t\t@size -= 1 if disconnect(from, to)\n\t\t\tself\n\t\tend",
"def delete_edge!(from, to)\n protected_delete_edge!(from, to)\n @edge_number -= 1\n end",
"def remove(node)\n node.inputs.each do |producer_edge|\n producer_edge.from.outputs.reject! { |edge| edge.to == node }\n end\n\n node.outputs.each do |consumer_edge|\n consumer_edge.to.inputs.reject! { |edge| edge.from == node }\n end\n\n nodes.delete(node)\n end",
"def delete_edge(from, to)\n @edges_cost[from].delete to\n @edges_up[from].delete to\n end",
"def disconnect_via(edge)\n @in_edges.delete(edge)\n @out_edges.delete(edge)\n\n nil\n end",
"def remove_edge(eid)\n p1, p2 = @points_of_edge[eid]\n @points_of_edge[eid] = nil\n @length_of_edge[eid] = nil\n\n @edges_of_point[p1] -= [eid]\n @edges_of_point[p2] -= [eid]\n end",
"def disconnect(edge)\n #adj_v.delete(vertex)\n in_edges.delete(edge)\n end",
"def remove_edge(e)\n\t\t# Delete an edge\n\t\tfor i in 0..num_edges-1\n\t\t\tif @Edges[i].points[0] == e.points[0] and @Edges[i].points[1] == e.points[1]\n\t\t\t\t@Edges.delete_at(i)\n\t\t\t\tbreak\n\t\t\telsif @Edges[i].points[1] == e.points[0] and @Edges[i].points[0] == e.points[1]\n\t\t\t\t@Edges.delete_at(i)\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n#\t\trehash\n\tend",
"def remove_edge(x, y)\n raise\n end",
"def remove_edge_if #:yields: source, target, edge\n _clear_cache\n removed_rel = []\n @pathway.relations.delete_if do |rel|\n if yield rel.node[0], rel.node[1], rel.edge then\n removed_rel << rel\n true\n end\n end\n removed_rel.each do |rel|\n source = rel.node[0]\n target = rel.node[1]\n h = @pathway.graph[source]\n h.delete(target) if h\n h = @pathway.graph[target]\n h.delete(source) if h\n end\n self\n end",
"def remove_lonely_nodes\n @nodes.delete_if { |n| (@sourcelinks[n].empty? && @destlinks[n].empty?) }\n self\n end",
"def pull_edges_of(node)\n\t\t\teach_node do |other|\n\t\t\t\tremove_edge(node, other)\n\t\t\t\tremove_edge(other, node)\n\t\t\tend\n\t\tend",
"def remove_node(node)\n @nodes_being_worked_on.delete(node)\n @nodes.delete(node)\n # the last edge keeps getting ignored when you remove this, so handling the final case\n assign_node(@edges[0][1]) if @edges.size == 1\n @edges.reject! { |edge| edge.include?(node) }\n end",
"def delete_edge(from_vertex, to_vertex)\n begin\n self[from_vertex].out_edges.delete(to_vertex)\n self[to_vertex].in_edges.delete(from_vertex)\n rescue NoMethodError => e\n err_suffix = \"in delete_edge(#{from_vertex}, #{to_vertex}).\"\n if self[from_vertex].nil?\n puts(\"No vertex with id #{from_vertex} \" << err_suffix)\n else\n puts(\"No vertex with id #{to_vertex} \" << err_suffix)\n end \n end\n end",
"def test_remove_edge\n @dgraph.add_edge('a', 'b');\n @dgraph.remove_edge('a','b')\n\n # 0 and 1 are indexes of vertex a and vertex b respectively\n assert(@dgraph.vertices[0].neighbours[1] == nil)\n end",
"def remove_edge(col, row)\n @deleted << [col, row]\n end",
"def omit_degree_2_nodes\r\n # add all nodes into a queue\r\n # queue = put all nodes from @nodes into the queue\r\n # puts \"#{@vertices}\"\r\n queue = Queue.new\r\n @vertices.each do |node|\r\n queue << node\r\n end\r\n\r\n # iterate through all nodes until queue is not empty\r\n while ! queue.empty?\r\n # take the first node number from the queue\r\n # i = queue.deque()\r\n # take the first node itself\r\n node=queue.pop\r\n\r\n # puts \"osm_id=#{node.osm_id} degree=#{node.degree}\"\r\n # puts \"node neighbours #{node.neighbours}\"\r\n # do anything only iff this node's degree == 2\r\n if node.degree == 2\r\n # take the node's neighbours and the two edges going from the node\r\n # we would like to shrink these two edges into only one while isolating\r\n # the _node_\r\n v1_nr = node.neighbours[0]\r\n e1_nr = node.edges[0]\r\n v2_nr = node.neighbours[1]\r\n e2_nr = node.edges[1]\r\n\r\n #puts \"actual node: #{node.osm_id} , actual neighbours #{v1_nr} , #{v1_nr}\"\r\n #puts \"neigbours of #{node.osm_id}: #{v1_nr.osm_id} #{v2_nr.osm_id}\" if (node.neighbours.length==2)\r\n next if node.neighbours.length!=2\r\n\r\n # IMPORTANT!\r\n # however, if there was a cycle, which means that the node's neighbours\r\n # ARE already connected, do nothing and leave this degree-2-node _i_ as\r\n # it is!\r\n\r\n #puts \"are connected #{v1_nr}, #{v2_nr} of #{node.osm_id}?\"\r\n next if are_connected(v1_nr, v2_nr, node.osm_id)\r\n\r\n #puts \"handling #{node.osm_id} - has 2 and is not cyclic, going to delete neighbours!\"\r\n #puts \"cur_node is: #{node.osm_id}\"\r\n\r\n #puts \"# this is not needed, but just for sure: record the neighbours' degrees before the shrinkage\"\r\n #v1_deg = v1_nr.degree ; v2_deg = v2_nr.degree\r\n #puts \" -> neighbours degree: v1:#{v1_deg} v2:#{v2_deg}\"\r\n\r\n #puts \"# record the neighbours' OSM/id, for future use\"\r\n #v1_osm = v1_nr.osm_id ; v2_osm = v2_nr.osm_id\r\n #puts \" -> v1_osm: #{v1_osm} deg: #{v1_deg} :: v2_osm #{v2_osm} deg: #{v2_deg}\"\r\n\r\n #puts \"# invalidate the two edges -- particularly, do not output them into Graphviz output\"\r\n e1_nr.invalidate\r\n e2_nr.invalidate\r\n e_distance=e1_nr.time_distance+e2_nr.time_distance\r\n\r\n #puts \" -> invalidated edges - #{e1_nr} #{e1_nr.osm_from}-#{e1_nr.osm_to}(#{e1_nr.is_valid}) #{e2_nr} #{e2_nr.osm_from}-#{e2_nr.osm_to}(#{e2_nr.is_valid})\"\r\n #puts \"# disconnect the triple v1--i--v2, i.e. leave out the neighbours from\r\n # the nodes' own neighbours' lists\"\r\n #ns=[] ; v1_nr.neighbours.each do |n| ns << \"#{n.osm_id}\" end; puts \"old v1 neighbours : #{ns}\"\r\n #ns=[] ; v2_nr.neighbours.each do |n| ns << \"#{n.osm_id}\" end; puts \"old v2 neighbours : #{ns}\"\r\n #ns=[] ; node.neighbours.each do |n| ns << \"#{n.osm_id}\" end; puts \"old v neighbours : #{ns}\"\r\n\r\n node.disconnect_neighbour(v1_nr)\r\n node.disconnect_neighbour(v2_nr)\r\n v2_nr.disconnect_neighbour(node)\r\n v1_nr.disconnect_neighbour(node)\r\n node.invalidate\r\n\r\n #puts \"Disconnect edges from nodes\"\r\n #ns=[] ; v1_nr.edges.each do |n| ns << \"#{n.osm_from}-#{n.osm_to}(#{n.is_valid})\" end; puts \" -> old v1 neighbours : #{ns}\"\r\n #ns=[] ; v2_nr.edges.each do |n| ns << \"#{n.osm_from}-#{n.osm_to}(#{n.is_valid})\" end; puts \" -> old v2 neighbours : #{ns}\"\r\n v1_nr.disconnect_edge(e1_nr)\r\n v2_nr.disconnect_edge(e2_nr)\r\n\r\n #puts \" # create a new edge going from v1 into v2 (it does not matter in which direction, it is anyway an artificial/virtual edge\"\r\n # save this Edge into the array @edges\r\n v_nr = @vertices.length\r\n e = Edge.new(v1_nr.osm_id, v2_nr.osm_id, 0, v_nr, e1_nr.name, e1_nr.maxspeed, e1_nr.is_oneway, e_distance)\r\n\r\n #puts (\"new edge from #{v1_nr.osm_id} to #{v2_nr.osm_id}\")\r\n @edges.push(e)\r\n\r\n #puts \"#add edge to vertex\"\r\n #ns=[] ; v1_nr.edges.each do |n| ns << \"#{n.osm_from}-#{n.osm_to}(#{n.is_valid})\" end; puts \"old v1 edges : #{ns}\"\r\n #ns=[] ; v2_nr.edges.each do |n| ns << \"#{n.osm_from}-#{n.osm_to}(#{n.is_valid})\" end; puts \"old v2 edges : #{ns}\"\r\n v1_nr.add_edge(e)\r\n v2_nr.add_edge(e)\r\n\r\n #add linkeds to vetexes\r\n v1_nr.connect_neighbour(v2_nr)\r\n v2_nr.connect_neighbour(v1_nr)\r\n end\r\n end\r\n end",
"def delete_edge(src, label, dest)\r\n return self if @graph_hash[src].nil?\r\n return self if @graph_hash[src][label].nil?\r\n @graph_hash[src][label].reject! {|node| node==dest}\r\n if @graph_hash[src][label].empty?\r\n @graph_hash[src].delete(label)\r\n end\r\n # !!! TODO: Add code to handle (delete) orphaned nodes.\r\n self\r\n end",
"def remove_edge_by_indexes(start_vertex_index, end_vertex_index)\n\n @vertices[start_vertex_index].neighbours[end_vertex_index] = nil\n @vertices[end_vertex_index].neighbours[start_vertex_index] = nil\n\n self\n end",
"def destroy\n @edge = Edge.find_by_src_id_and_dest_id(params[:src_id] , params[:dest_id])\n @edge.destroy\n\t\tredirect_to :controller => \"nodes\" , :action => \"listByCourse\" , :course_id => @edge.src.course_id\t\t\n\n end",
"def protected_delete_edge!(from, to)\n if has_edge?(from, to)\n @vertices[from].delete(to)\n @edge_labels.delete(Pair.new(from, to))\n end\n end",
"def remove_edge(node_1, node_2)\n raise KeyError, \"#{node_1} is not a valid node.\" unless @nodes.key?(node_1)\n raise KeyError, \"#{node_2} is not a valid node\" unless @nodes.key?(node_2)\n raise KeyError, 'The given edge is not a valid one.' unless @adj[node_1].key?(node_2)\n\n @adj[node_1].delete(node_2)\n @pred[node_2].delete(node_1)\n end",
"def remove_edge(start_vertex_name, end_vertex_name)\n\n first_vertex_index = find_index_for_vertex(start_vertex_name)\n second_vertex_index = find_index_for_vertex(end_vertex_name)\n\n if (first_vertex_index == nil)\n raise GraphError.new('Edge removal error. First vertex could not be found', GraphError::ERROR_REMOVE_EDGE_FAILURE)\n end\n\n if (second_vertex_index == nil)\n raise GraphError.new('Edge removal error. Second vertex could not be found', GraphError::ERROR_REMOVE_EDGE_FAILURE)\n end\n\n remove_edge_by_indexes(first_vertex_index, second_vertex_index)\n end",
"def delete!\n graph.remove_edge element\n end",
"def delete!\n graph.remove_edge element\n end",
"def test_remove_edge\n @graph.remove_edge('a','b')\n\n # 0 and 1 are indexes of vertex a and vertex b respectively\n assert(@graph.vertices[0].neighbours[1] == nil && @graph.vertices[1].neighbours[0] == nil)\n end",
"def remove_edge(u, v)\n super\n @weights.delete([u,v])\n end",
"def delete_node(node)\n ## just copy the information of the next node and then cut it out\n node.id = node.next.id\n node.next = node.next.next\nend",
"def remove_relationship(destiny, label)\n return if destiny.nil? or destiny == self\n edge_class = ModelFabric.get_class(SocialFramework.edge_class)\n\n edge = edge_class.where([\"(origin_id = :origin_id AND destiny_id = :destiny_id OR \n destiny_id = :origin_id AND origin_id = :destiny_id) AND label = :label\",\n { origin_id: self.id, destiny_id: destiny.id, label: label }]).first\n\n self.edges.destroy(edge.id) unless edge.nil?\n end",
"def remove_edge(u, v)\n raise NotImplementedError\n end",
"def remove_edge!(edge)\n @vertices[edge.source].remove_edge(:out, edge)\n @vertices[edge.target].remove_edge(:in, edge)\n\n @edges.delete(edge)\n nil\n end",
"def inline\n @out.delete(self)\n @in.each do |n|\n i = 0\n while(i < n.out.length)\n n.out[i,1] = @out if n.out[i] == self\n i += 1\n end\n end\n @graph.remove(self)\n end",
"def reverse_delete(result)\n edges = result[0]\n hitList = result[1]\n\n hitList.each do |k, dist|\n edges[k[0]].delete(k[-1])\n edges[k[-1]].delete(k[0])\n\n unless path_exists?(edges, k[0], k[-1]) #check if connection still path\n p \"path does not exist, reconnecting #{k[0]} to #{k[-1]} \"\n edges[k[0]][k[-1]] = dist\n edges[k[-1]][k[0]] = dist\n end\n end\n\n edges\n end",
"def delete!\n graph.removeEdge element\n end",
"def delete_edge(v)\n count = 0\n @edges.each do |e|\n @edges.delete_at(count)if e.vertex.eql?(v)\n count+=1\n end\n end",
"def remove(p)\n @first = counterclockwise(@first) if @first.equal?(p)\n @first = nil if @first.equal?(p)\n @neighbors.delete(p)\n end",
"def remove_edge(direction, edge)\n opposite_adjacencies(direction, edge).delete(edge)\n end",
"def remove_preceding(node_or_range, size); end",
"def move_node!(tg,tga,i)\n #first just add node i in\n tga[0].each_index do |ii|\n if (i == tga[0][ii][0])\n tg[0].push(tga[0][ii])\n tga[0][ii] = nil\n break\n end\n end\n #then add the edges, only add edges for which both nodes exist in tg \n tga[1].each_index do |ii|\n if tg[0].index{|item| item[0] == tga[1][ii][0]} && tg[0].index{|item| item[0] == tga[1][ii][1]}\n tg[1].push(tga[1][ii])\n tga[1][ii] = nil\n end\n end\n tga[0].compact!\n tga[1].compact!\nend",
"def remove_nodes!(tg,tiles)\n result = [Array.new,Array.new]\n\n tg[0].each_index {|n| # remove nodes\n tiles.each do |i|\n if i == tg[0][n][0]\n result[0].push(tg[0][n])\n tg[0][n] = nil\n break\n end \n end\n }\n tg[1].each_index {|e| # remove edges\n tiles.each do |i|\n if(tg[1][e][0] == i || tg[1][e][1] == i) \n result[1].push(tg[1][e])\n tg[1][e] = nil\n break # don't add edge twice\n end\n end\n }\n tg[0].compact!\n tg[1].compact!\n return result\nend",
"def remove_from_graph\n # Ignores trying to delete nonexistent records\n connection.execute <<-EOS\n DELETE IGNORE FROM #{oqgraph_table_name} WHERE origid = #{self.send(self.class.from_key)} AND destid = #{self.send(self.class.to_key)};\n EOS\n end",
"def unlink(other)\n self.class.graph.disjoin(vertex, other.vertex)\n end",
"def removed(node)\n\t\t\t@size -= 1\n\t\t\treturn node\n\t\tend",
"def edge_down(from, to)\n @edges_up[from].store(to, false)\n end",
"def remove(node)\n end",
"def contract edge\n vertex_1 = edge[0]\n vertex_2 = edge[1]\n #puts \"contracting edge \" + vertex_1.id.to_s + \", \" + vertex_2.id.to_s\n remove_vertex vertex_2\n\n vertex_2.adjacent_vertices.each{ |adjacent_vertex|\n vertex = find(adjacent_vertex)\n vertex_2_index = vertex.adjacent_vertices.index(vertex_2.id)\n vertex.adjacent_vertices[vertex_2_index] = vertex_1.id\n }\n vertex_1.adjacent_vertices.concat(vertex_2.adjacent_vertices)\n vertex_1.adjacent_vertices.delete_if {|adjacent_vertex| adjacent_vertex == vertex_1.id }\n end",
"def test_drop_edges_aliases\n s0, s1, e01, e10, e11 = nil\n fa = Automaton.new do |fa|\n s0 = fa.add_state(:initial => true)\n s1 = fa.add_state\n e10 = fa.connect(s1, s0, 'b')\n e01 = fa.connect(s0, s1, 'a')\n e11 = fa.connect(s1, s1, 'a')\n end\n\n fa.delete_edges(e10,e11)\n assert_equal(2, fa.state_count)\n assert_equal(1, fa.edge_count)\n assert_equal(0, e01.index)\n end",
"def remove node\n # if the node is at beginning or end of list\n # handle this separately\n return remove_first if node.prev_node == nil\n return remove_last if node.next_node == nil\n\n # tell adjacent nodes to 'skip' over this node\n node.next_node.prev_node = node.prev_node\n node.prev_node.next_node = node.next_node\n\n # store the data, so we can return it\n data = node.data\n\n # send to garbage collector\n node.data = nil\n node = node.prev_node = node.next_node = nil\n\n @size -= 1\n\n return data\n end",
"def remove_leading(node_or_range, size); end",
"def remove node\n # if the node is at beginning or end of list\n # handle this separately\n return remove_first if node == @head\n return remove_last if node == @tail\n\n # store the data, so we can return it\n data = node.data\n\n # iterate through nodes, two at a time\n each_cons(2) do |search_node, next_node|\n # if our second item in a pair is the node we are looking for\n if next_node == node\n # then make the previous node's (i.e the search_node) next node equal to the FOLLOWING\n search_node.next_node = next_node.next_node\n next_node = nil\n break\n end\n end\n\n @size -= 1\n\n return data\n end",
"def disconnect node1, node2\n if !nodes.include?(node1) || !nodes.include?(node2)\n raise NodeContainsException, 'The graph does not contain either ' + node1 + ' or ' + node2\n end\n @connections[node1].delete node2\n @connections[node2].delete node1\n end",
"def test_drop_edge_aliases\n s0, s1, e01, e10 = nil\n fa = Automaton.new do |fa|\n s0 = fa.add_state(:initial => true)\n s1 = fa.add_state\n e01 = fa.connect(s0, s1, 'a')\n e10 = fa.connect(s1, s0, 'b')\n end\n\n # we drop second edge\n fa.delete_edge(e10)\n assert_equal(2, fa.state_count)\n assert_equal(1, fa.edge_count)\n assert_equal(0, e01.index, 'First edge index has not changed')\n end",
"def isolates\n edges.inject(Set.new(vertices)) { |iso, e| iso -= [e.source, e.target] }\n end",
"def remove(node)\n # Traverse looking for the node\n sets = []\n prev_link = nil\n each_link do |link|\n if link[:ref_id] == node.id\n sets << [prev_link, link]\n next # in case adjacent removal node links\n end\n prev_link = link\n end\n # Now we can just do the join and we're out\n sets.each do |prev_link, the_link|\n if prev_link\n prev_link[:next_id] = the_link[:next_id]\n else\n self[:head_id] = the_link[:next_id]\n end\n # Mark removal\n element_removed!\n end\n # Return the node if any were removed\n node unless sets.empty?\n end",
"def remove_redundant_edges(in_vtx, out_vtx, index)\n @edges.each do |edge|\n if edge && edge.index == index\n # when in-vertices are eq and out-vertices are substrings or vice versa\n if in_vtx.name.casecmp(edge.in_vertex.name) == 0 && out_vtx.name.casecmp(edge.out_vertex.name) != 0 && out_vtx.name.downcase.include?(edge.out_vertex.name.downcase)\n edge = nil\n # when in-vertices are only substrings and out-verts are equal\n elsif in_vtx.name.casecmp(edge.in_vertex.name) != 0 && in_vtx.name.downcase.include?(edge.in_vertex.name.downcase) && out_vtx.name.casecmp(edge.out_vertex.name) == 0\n edge = nil\n end\n end\n end\n\n # recreating the edges array without the nil values\n @edges.compact!\n @num_edges = @edges.size + 1\n end",
"def remove_node(node)\n\t\t\tif has_node?(node)\n\t\t\t\tpull_edges_of(node)\n\t\t\t\t@nodes.delete(node)\n\t\t\t\t@order -= 1\n\t\t\tend\n\t\t\tself\n\t\tend",
"def add_undirected_edge(id1,id2)\n @g[id1] ||= Set.new\n @g[id2] ||= Set.new\n @g[id1] << id2\n @g[id2] << id1\n end",
"def remove_redundant_dsts()\n while @hops.size > 1 and @hops[-1].ip == @dst and @hops[-2].ip == @dst\n @hops = @hops[0..-2]\n end\n end",
"def delete\n @prev_node.next_node = @next_node\n @next_node.prev_node = @prev_node\n @prev_node = @next_node = nil\n @value\n end",
"def node_delete_after!(x, prev, level)\n netx = node_next(x, level) # 'next' is a reserved word in ruby\n \n # forward links\n prev[0][level] = netx\n \n # backward links\n netx[3][level] = prev\n end",
"def remove(x, y)\n @store[x].remove(y)\n @store[y].remove(x) if undirected?\n end",
"def anti_parallel_edge(edge)\n edge.to.out_edges.to_a.detect { |o| o.to == edge.from }\n end",
"def delete_vertex(vertex)\n out_e = self[vertex].out_edges.to_a\n out_e.each { |e| delete_edge(vertex, e) }\n in_e = self[vertex].in_edges.to_a\n in_e.each { |e| delete_edge(e, vertex) }\n self.delete(vertex)\n end",
"def remove_vertex(x)\n raise\n end",
"def delete(rel)\n @relations.delete_if do |x|\n x === rel\n end\n @graph[rel.from].delete(rel.to)\n @graph[rel.to].delete(rel.from) if @undirected\n end",
"def del_start\n @head = @head.node_sig\n if @head != nil\n @head.edi_ant(nil)\n end\n end",
"def remove_vertex(v)\n\t\t@Vertices.delete_at(@Hash[v.label])\n\t\tnum=num_edges-1\n\t\ti=0\n\t\twhile i != num do\n\t\t\tif @Edges[i].points[0] == v.label or @Edges[i].points[1] == v.label\n\t\t\t\t@Edges.delete_at(i)\n\t\t\t\ti=-1\n\t\t\t\tnum=num-1\n\t\t\tend\n\t\t\ti+=1\n\t\tend\n\t\trehash\n\tend",
"def destroy\n super do\n graph.delete [source.to_term, nil, nil]\n parent.delete [parent, nil, source.to_term]\n end\n end",
"def destroy\n Segment.find_by_guid(source.guid).destroy if source && Segment.find_by_guid(source.guid)\n Segment.find_by_guid(target.guid).destroy if target && Segment.find_by_guid(target.guid)\n successors.each {|successor| NetworkConnection.find_by_guid(successor.guid).destroy if successor}\n super\n end",
"def subtract(edge_list)\r\n @inbound -= edge_list.inbound\r\n @outbound -= edge_list.outbound\r\n self\r\n end",
"def source_edge\n return unless edge\n return unless local_position.on_line?(edge.line)\n\n edge\n end",
"def delete_edge(vertex1, vertex2)\n if !contains_vertex?(vertex1) || !contains_vertex?(vertex2)\n raise InvalidVertexException, \"The graph does not contain that vertex\"\n elsif !(@graph[vertex1].include?(vertex2))\n raise InvalidEdgeException, \"The graph does not contain that edge\" \n end\n @graph[vertex1].delete(vertex2)\n @graph[vertex2].delete(vertex1)\n self\n end",
"def karger(g)\n if g.nodes.size <= 2\n return g.edges.size\n end\n # pp \"-------------------------\"\n e = g.edges.to_a.at(rand(g.edges.size))\n # pp \"picked edge: \"\n # print_edge e\n # pp \"left edges size: #{g.edges.size}\"\n n1 = e.nodes.to_a[0]\n n2 = e.nodes.to_a[1]\n # print_edge e\n # print_node n1\n # print_node n2\n n1.edges.merge(n2.edges)\n # print_node n1\n n1.edges.delete(e)\n g.edges.delete(e)\n edges_to_be_deleted = []\n n1.edges.to_a.each do |e|\n if e.nodes.include?(n2)\n e.nodes.delete(n2)\n e.nodes.add(n1)\n end\n if e.nodes.size < 2\n edges_to_be_deleted << e\n end\n end\n # puts \"before purge:\"\n # print_node n1\n edges_to_be_deleted.each do |e|\n n1.edges.delete e\n g.edges.delete e\n end\n # puts \"after adjust node: \"\n # print_node n1\n g.nodes.delete(n2.index)\n karger(g)\nend",
"def test_delete_if\n graph = Rgraphum::Graph.new\n (0..9).each do |i|\n graph.vertices << { label: \"v#{i}\" }\n end\n (0..9).each do |i|\n graph.edges << {\n source: graph.vertices[i],\n target: graph.vertices[(i+1) % 10],\n weight: i,\n }\n end\n\n # v0 -> v1 -> v2 -> v3 -> v4 -> v5 -> v6 -> v7 -> v8 -> v9\n # ^ |\n # +-----------------------------------------------------+\n assert_equal 10, graph.vertices.size\n assert_equal 10, graph.edges.size\n graph.vertices do |vertex|\n assert_equal 2, vertex.edges.size\n end\n\n graph.edges.delete_if { |edge| edge.weight.odd? }\n # graph.edges.reject! { |edge| edge.weight.odd? }\n\n # v0 -> v1 v2 -> v3 v4 -> v5 v6 -> v7 v8 -> v9\n assert_equal 10, graph.vertices.size\n assert_equal 5, graph.edges.size, \"edges.size was 10 but deleted 5 edges\"\n\n assert_equal 0, graph.edges[0].weight\n assert_equal 2, graph.edges[1].weight\n assert_equal 4, graph.edges[2].weight\n assert_equal 6, graph.edges[3].weight\n assert_equal 8, graph.edges[4].weight\n\n graph.vertices do |vertex|\n assert_equal 1, vertex.edges.size\n end\n end",
"def delete_middle_node(node)\n temp = node.prev\n temp.next = node.next\n node.next.prev = temp\nend",
"def delete\n\t\tdb.execute{ \"delete edge #{ref_name} #{rrid}\" }\n\tend",
"def delete_node_improved(node)\n node.val = node.next.val\n node.next = node.next.next\nend",
"def cut(vert)\n\t\treturn unless self.has_vertex? vert\n\t\t\n\t\tnew_name = \"#{vert}_\"\n\t\t\n\t\t# create the new target node\n\t\t# (the old one should still also exist in the graph)\n\t\tself.add_vertex(new_name)\n\t\t\n\t\t# get the children of the specified node, and rename their parents to the new target\n\t\tself.children(vert).each do |child|\n\t\t\tself.each_edge.select{ |dep, course|\n\t\t\t\tdep == vert && course == child\n\t\t\t}.each{ |dep, course|\n\t\t\t\tself.remove_edge dep, course\n\t\t\t\t# self.add_edge new_name, course\n\t\t\t}\n\t\tend\n\t\t\n\tend",
"def pop\n @nodes.shift\n end",
"def cleanup_phi_nodes\n nodes.dup.each do |node| # dup because we're mutating\n next unless node.is_a?(PhiNode)\n\n if node.inputs.size == 1\n # Remove phi nodes with a single input.\n connect_over(node)\n remove(node)\n elsif node.inputs.map(&:from).uniq.size == 1\n # Remove phi nodes where all inputs are the same.\n producer_edge = node.inputs.first\n consumer_edge = node.outputs.find { |e| !e.to.is_a?(MergeNode) }\n connect(\n producer_edge.from,\n consumer_edge.to,\n :data,\n consumer_edge.label\n )\n remove(node)\n end\n end\n end",
"def remove_trailing(node_or_range, size); end",
"def shift\n node = self.double_link_linked_list.delete_head\n node ? node.value : nil\n end",
"def delete!\n graph.remove_vertex element\n end",
"def edges_to(node)\n edges.select { |edge| edge.last == node }\n end",
"def remove\n node = @head\n\n if node\n @head = node.next_node\n @tail = nil unless @head\n\n node.data\n end\n end",
"def remove_node_if\n #_clear_cache #done in clear_node(node)\n all = self.nodes\n all.each do |node|\n if yield node then\n self.clear_node(node)\n @pathway.graph.delete(node)\n end\n end\n self\n end",
"def remove_node(node)\n raise KeyError, \"Error in deleting node #{node} from Graph.\" unless @nodes.key?(node)\n\n neighbours = @adj[node]\n neighbours.each_key { |k| @pred[k].delete(node) }\n @pred[node].each_key do |k|\n @adj[k].delete(node)\n end\n\n @pred.delete(node)\n @adj.delete(node)\n @nodes.delete(node)\n end",
"def edges\n\t\t\tself.node_maps.select { |i| !i.marked_for_destruction? }.select { |i|\n\t\t\t\ti.node && i.parent\n\t\t\t}.collect { |i|\n\t\t\t\t{\n\t\t\t\t\t:source => i.parent.node.id,\n\t\t\t\t\t:target => i.node.id,\n\t\t\t\t}\n\t\t\t}.uniq\n\t\tend",
"def remove\n @nxt.prv = @prv if @nxt\n @prv.nxt = @nxt if @prv\n end",
"def test_drop_edges_recognizes_sub_transaction\n s0, ea, eb, ec = nil\n fa = Automaton.new do |fa|\n s0 = fa.add_state(:initial => true)\n ea = fa.connect(s0, s0, 'a')\n eb = fa.connect(s0, s0, 'b')\n ec = fa.connect(s0, s0, 'c')\n end\n fa.drop_edges(ea, eb, ec)\n assert_equal(0, fa.edge_count)\n assert_equal(0, s0.in_edges.size)\n assert_equal(0, s0.out_edges.size)\n end",
"def pop_sync(rc)\n point1 = rc.prev_link.point\n point2 = rc.point\n point3 = rc.next_link.point\n\n # This works because all of the nodes share the same\n # \"parent_polygon\" i.e., they aren't copies, they're the same ruby\n # object. This makes triangulation destructive, which is why\n # we copy the polygon first\n rc.parent_polygon.delete(point2)\n\n return Triangle.new(point1, point2, point3)\n end",
"def erase\n @nodes.erase\n end",
"def remove_vertex(id)\n # YOUR WORK HERE\n end",
"def del_final\n @tail = @tail.node_ant\n if @tail != nil\n @tail.edi_sig(nil)\n else\n @head = @tail\n end\n end",
"def remove_at(index)\n removed_node = at_no_data(index)\n prev_node = at_no_data(index - 1)\n next_node = at_no_data(index + 1)\n prev_node.next_node = next_node\n puts \"#{removed_node.data} has left the group\"\n removed_node\n end",
"def out_neighbors(vertex)\n\tend",
"def out_edges(source)\n h = @pathway.graph[source]\n if h\n h.collect { |key, val| [ source, key, val ] }\n else\n []\n end\n end",
"def edges\n @structure.reduce([]) do |acc, node|\n acc + node[1].map { |dest| [node[0], dest] }\n end\n end"
] |
[
"0.71168524",
"0.7091838",
"0.70847076",
"0.7054624",
"0.70041543",
"0.6983194",
"0.69370836",
"0.6833785",
"0.669455",
"0.64881223",
"0.6478261",
"0.64762974",
"0.64500105",
"0.640798",
"0.63919973",
"0.63730836",
"0.6360826",
"0.6359386",
"0.6342667",
"0.6341068",
"0.6322373",
"0.631432",
"0.62978476",
"0.62864786",
"0.62795526",
"0.62795",
"0.62795",
"0.624678",
"0.6225059",
"0.61517006",
"0.6131461",
"0.61295456",
"0.6087701",
"0.60824275",
"0.6068021",
"0.6034622",
"0.60230875",
"0.6022828",
"0.60041195",
"0.59552413",
"0.5877872",
"0.5836212",
"0.5825501",
"0.5815361",
"0.5813628",
"0.5785717",
"0.577545",
"0.5733999",
"0.57295334",
"0.5721457",
"0.57210296",
"0.5720985",
"0.57200634",
"0.5679863",
"0.56741405",
"0.5658785",
"0.562747",
"0.56261367",
"0.5619456",
"0.56062394",
"0.5599105",
"0.55914634",
"0.5588706",
"0.5562638",
"0.5555873",
"0.55464816",
"0.55449575",
"0.5523335",
"0.5497493",
"0.5496402",
"0.5486667",
"0.5482375",
"0.54686564",
"0.5466381",
"0.54607046",
"0.54534155",
"0.5449448",
"0.5446437",
"0.54352933",
"0.5434747",
"0.5419534",
"0.5416976",
"0.5414023",
"0.5405213",
"0.5397621",
"0.53942233",
"0.53915",
"0.5390934",
"0.5385652",
"0.5382829",
"0.53825766",
"0.53767395",
"0.5373472",
"0.53693616",
"0.5363463",
"0.53621095",
"0.5360737",
"0.53547305",
"0.53537697",
"0.53440934"
] |
0.54720014
|
72
|
cmd[0] : DEST cmd[1] : COST
|
def edgeu(cmd)
time = nil
$lock.synchronize{
time = $clock.to_i
$network.update_cost($hostname, cmd[0], cmd[1].to_i, time)
if $rt.has_key? cmd[0]
$rt[cmd[0]][:cost] = cmd[1].to_i
end
}
client = TCPSocket.open($local_ip, $nodesFile[cmd[0]]["PORT"])
client.puts("EDGEU2 #{$hostname} #{cmd[1]} #{time}")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edgeu_network(cmd)\n $lock.synchronize{\n $network.update_cost($hostname, cmd[0], cmd[1].to_i,cmd[2].to_i)\n \n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n }\nend",
"def command(cmd, arg = 2)\n return if @sp == nil\n #<SOT><CMD_BYTE><CHECK_SUM><EOT>\n case cmd\n=begin\n Request DCF Time\n <SOH><0x30><Chksum><EOT>\n=end\n when 0 #Poll DCF Time\n exchange(\"\\x01\\x30\\xcf\\x04\", 7)\n puts DCF77.new(@response).to_s\n=begin\n Request Dataset\n \t<SOH><0x31><Chksum><EOT>\n \t\tResponse from weather station: (34/60 Bytes) Mine has additional 0 byte, so 35/61 bytes are received.\n \t\t1. Data available\n \t\t\tBlock no.: 2 bytes Number of the block in the memory\n \t\t\t (no relation to time. Serves to control dataset registered twice).)\n \t\t\tTime: 2 bytes Age of the dataset in minutes up to the current time.\n \t\t\t\t\t\t\t\t age = ( data[2] & 0xff ) + ( data[3] << 8 & 0xff00 );\n \t\t\tData: 30 (9 sensors) or 56 (16 sensors) bytes\n \t\t2. No data available: <DLE>\n=end\n when 1 #Request dataset\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n #@response.each { |r| print \"%02X \" % r }\n s = Sensors.new(@response)\n if s.data?\n puts s.to_data_row\n puts Sensors.new(@response).to_s\n end\n=begin\n \tSelect Next Dataset\n \t\t<SOH><0x32><Chksum><EOT>\n \t\t\tResponse from weather station: (1 Byte)\n \t\t\t\t1. Next dataset available : <ACK> 0x06\n \t\t\t\t2. No dataset available: <DLE> 0x10\n=end\n when 2 #select next dataset\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tSet 8 Sensors\n \t\t<SOH><0x33><Chksum><EOT>\n \t\tResponse from weather station: (1 Byte)\n \t\t<ACK>\n=end\n when 3 #activate 8 sensors\n exchange(\"\\x01\\x33\\xcc\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n set 16 Sensors\n \t<SOH><0x34><Chksum><EOT>\n \tResponse from weather station: (1 Byte)\n \t<ACK>\n=end\n when 4 #activate 16 sensors\n exchange(\"\\x01\\x34\\xcb\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tStatus\n \t <SOH><0x35><Chksum><EOT>\n \tResponse from weather station: (21 Byte)\n \tBytes 1 - 18\n \t\t\tS:1-8 Temp/Hum\n \t\t\t9 Rain,\n \t\t\t10 Wind\n \t\t\t11 Indoor Temp/Hum/Pres\n \t\t\t12 S9:Temp/Hum\n \t\t\t13-15 S10-15:Temp/Hum/Pres\n \t\tByte >= 0x10 if sensor present\n \t\tvalue > 0x10 number of error\n \tByte 19 Sample Interval in minutes\n \tByte 20\n \t bit 0 DFC77 time receiver active\n \t\tbit 1 HF if set\n \t\tbit 2 8/16 Sensors\n \t\tbit 3 DFC Synchronized (Not likely in NZ)\n \tByte 21 Version Number\n=end\n when 5 #Request Status\n exchange(\"\\x01\\x35\\xca\\x04\", 21)\n @response.each { |r| print \"%02X \" % r }\n puts\n=begin\n Set Interval time\n \t <SOH><0x36><minutes><Chksum><EOT>\n \t\tminutes range 1..60\n \t Response from weather station: (1 Byte)\n \t<ACK> if in range\n \t<DLE> if out of range\n=end\n when 6 #set interval time\n #<SOT><CMD_BYTE><ARGUMENT><CHECK_SUM><EOT>\n raise Weather_exception, \"Interval Range 2..60\" if arg > 60 || arg < 2\n exchange(\"\\x01\\x36#{arg.chr}#{(0xc9-arg).chr}\\x04\", 1)\n exit @response[0] == ACK ? 0 : 1\n\n when 12 #Loop through 1 and 2\n begin\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n s = Sensors.new(@response)\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n if s.data?\n\t puts s.to_data_row\n else\n break\n end\n end while( @response[0] == ACK )\n end\n end",
"def cost \n return @extra_cost + @basic_transfer.cost\n end",
"def curatorWaypointCost _args\n \"curatorWaypointCost _args;\" \n end",
"def args(count)\n resp = sequence[ip+1, count]\n puts ([opcode] + resp).inspect\n resp\n end",
"def execute_command(cmd, opts)\r\n\r\n\t\tsoapenv = 'http://schemas.xmlsoap.org/soap/envelope/'\r\n\t\txsi = 'http://www.w3.org/2001/XMLSchema-instance'\r\n\t\txs = 'http://www.w3.org/2001/XMLSchema'\r\n\t\tsapsess = 'http://www.sap.com/webas/630/soap/features/session/'\r\n\t\tns1 = 'ns1:OSExecute'\r\n\r\n\t\tcmd_s = cmd.split(\"&\") #Correct issue with multiple commands on a single line\r\n\t\tif cmd_s.length > 1\r\n\t\t\tprint_status(\"Command Stager progress - Split final payload for delivery (#{cmd_s.length} sections)\")\r\n\t\tend\r\n\r\n\t\tcmd_s = cmd_s.collect(&:strip)\r\n\t\tcmd_s.each do |payload|\r\n\r\n\t\t\tdata = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' + \"\\r\\n\"\r\n\t\t\tdata << '<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"' + soapenv + '\" xmlns:xsi=\"' + xsi + '\" xmlns:xs=\"' + xs + '\">' + \"\\r\\n\"\r\n\t\t\tdata << '<SOAP-ENV:Header>' + \"\\r\\n\"\r\n\t\t\tdata << '<sapsess:Session xlmns:sapsess=\"' + sapsess + '\">' + \"\\r\\n\"\r\n\t\t\tdata << '<enableSession>true</enableSession>' + \"\\r\\n\"\r\n\t\t\tdata << '</sapsess:Session>' + \"\\r\\n\"\r\n\t\t\tdata << '</SOAP-ENV:Header>' + \"\\r\\n\"\r\n\t\t\tdata << '<SOAP-ENV:Body>' + \"\\r\\n\"\r\n\t\t\tdata << '<' + ns1 + ' xmlns:ns1=\"urn:SAPControl\"><command>cmd /c ' + payload.strip\r\n\t\t\tdata << '</command><async>0</async></' + ns1 + '>' + \"\\r\\n\"\r\n\t\t\tdata << '</SOAP-ENV:Body>' + \"\\r\\n\"\r\n\t\t\tdata << '</SOAP-ENV:Envelope>' + \"\\r\\n\\r\\n\"\r\n\r\n\t\t\tuser_pass = Rex::Text.encode_base64(datastore['USERNAME'] + \":\" + datastore['PASSWORD'])\r\n\r\n\t\t\tbegin\r\n\t\t\t\tres = send_request_raw({\r\n\t\t\t\t\t'uri' => \"/#{datastore['URI']}\",\r\n\t\t\t\t\t'method' => 'POST',\r\n\t\t\t\t\t'data' => data,\r\n\t\t\t\t\t'headers' =>\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t'Content-Length' => data.length,\r\n\t\t\t\t\t\t\t'SOAPAction' => '\"\"',\r\n\t\t\t\t\t\t\t'Authorization' => 'Basic ' + user_pass,\r\n\t\t\t\t\t\t\t'Content-Type' => 'text/xml; charset=UTF-8',\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}, 60)\r\n\r\n\t\t\tif (res.code != 500 and res.code != 200)\r\n\t\t\t\tprint_error(\"[SAP] An unknown response was received from the server\")\r\n\t\t\t\tabort(\"Invlaid server response\")\r\n\t\t\telsif res.code == 500\r\n\t\t\t\tbody = res.body\r\n\t\t\t\tif body.match(/Invalid Credentials/i)\r\n\t\t\t\t\tprint_error(\"[SAP] The Supplied credentials are incorrect\")\r\n\t\t\t\t\tabort(\"Exploit not complete, check credentials\")\r\n\t\t\t\telsif body.match(/Permission denied/i)\r\n\t\t\t\t\tprint_error(\"[SAP] The Supplied credentials are valid, but lack OSExecute permissions\")\r\n\t\t\t\t\traise RuntimeError.new(\"Exploit not complete, check credentials\")\r\n\t\t\t\tend\r\n\t\t\tend\r\n\r\n\t\t\trescue ::Rex::ConnectionError\r\n\t\t\t\tprint_error(\"[SAP] Unable to attempt authentication\")\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\tend",
"def write_cmd(buf)\n\tend",
"def food_total_cost(*args)\n\titem = args\n\tvalue = args\n\t#item1 + item2 + item3\nend",
"def execute(ints, pos)\n memory = ints.dup\n opcode = ints[pos]\n a = memory[pos + 1]\n b = memory[pos + 2]\n c = memory[pos + 3]\n\n if opcode == 1\n memory[c] = memory[a] + memory[b]\n elsif opcode == 2\n memory[c] = memory[a] * memory[b]\n else\n raise \"dunno what to do\"\n end\n\n return memory\nend",
"def transfer(raccount, amount, purpose = [])\n end",
"def cost(state)\n return fungsi(state[0], state[1])\nend",
"def execute(x1, x2)\r\n # Somatório (NET)\r\n @net = net(x1, x2)\r\n\r\n # Função de Ativação\r\n return 1 if (@net >= 0) \r\n\r\n return 0;\r\n end",
"def compress_commands(cmds, opts)\n\t\t# Initiate the download\n\t\tcmds << \"tftp -i #{opts[:tftphost]} GET #{opts[:transid]} #{@tempdir + @var_payload_out}\"\n\n\t\t# Make it all happen\n\t\tcmds << \"start #{@tempdir + @var_payload_out}\"\n\n\t\t# Clean up after unless requested not to..\n\t\tif (not opts[:nodelete])\n\t\t\t# XXX: We won't be able to delete the payload while it is running..\n\t\tend\n\n\t\tsuper\n\tend",
"def process_command(rep)\n\t \t\taddress = rep[:address]\n\n\t \t\tif address==1\n\t \t\t\tqueue = @cmd_queue_1\n\t \t\telse\n\t \t\t\tqueue = @cmd_queue_0\n\t \t\tend\n\n\t \t\tcase rep[:type]\n\t \t\t\twhen 0\n\t \t\t\t\t@log.info \"Command OK\"\n\t \t\t\twhen 1\n\t \t\t\t\t@log.error \"Invalid Command\"\t\n\t \t\t\twhen 2\n\t \t\t\t\t@log.error \"Busy - command ignored\"\t\t\n\t \t\t\twhen 3\n\t \t\t\t\t@log.error \"Can't Process - input out of range or error\"\n\t \t\t\t\t\n\t \t\tend\n\t \t\twrite_command_status(queue)\n\t end",
"def cost \n\n \ttotal=@costItems.reduce(0) do |sum,hm|\n \t\tsum+=hm \n end\n puts total\n end",
"def transfer; end",
"def transfer; end",
"def send_cmd(cmd, conn)\n out = conn.cmd('String' => cmd, 'Match' => /(SUCCESS:.*\\n|ERROR:.*\\n|END.*\\n)/)\n out.lines\nend",
"def transfer_command( amount, ship )\n\t\t\t\tTransferCommand.new @interface, amount, ship\n\t\t\tend",
"def exec(opcode, arg)\n case opcode\n when 0\n self.acc = self.acc + ram.read(arg)\n when 1\n self.acc = self.acc - ram.read(arg)\n when 2\n self.acc = self.io.ask(\"> \", Integer)\n when 3\n self.io.say(\"--> #{self.acc}\")\n when 4\n ram.store(arg) { self.acc }\n when 5\n self.acc = ram.read(arg)\n when 6\n self.pc = arg\n when 7\n self.pc = arg if self.acc == 0\n when 8\n @running = false\n else\n raise \"Unknown instruction code #{opcode}\"\n end\n end",
"def cost(op)\n { materials: 0.84, labor: 1.24 }\nend",
"def cmd; end",
"def op\n sequence[ip]\n end",
"def write(cmd)\n\t \t @log.debug \"Tx: \"+cmd\n\t\t @sp.write cmd\n\t\t sleep 0.25 \n\t end",
"def _recursor(cmds,session)\n results = []\n passed = true\n @log.debug \"Processing #{cmds.inspect}\"\n cmds.each do |myhash|\n if myhash.size != 1\n @log.error \"Config format problem with #{myhash.inspect}\"\n raise VmthError\n end\n cmd = myhash.keys.first\n values = myhash[cmd]\n @log.debug \"Values is #{values.inspect}\"\n if cmd=='foreach'\n args = values.shift['args']\n args.each do |arg|\n @log.debug \"Arg is #{arg.inspect}\"\n @arg = arg\n res_hash = _recursor(values,session)\n results << res_hash['output']\n passed = res_hash['passed'] and passed\n end\n elsif cmd=='cmd'\n command_string = eb(values)+\" 2>&1\"\n @log.debug \"Running on vm.. '#{command_string}\"\n result = session.exec!(command_string)\n @log.debug \"output is: #{result}\"\n results << result\n elsif %{upload download upload_recurse download_recurse}.include?(cmd)\n first=eb(values[0])\n second=eb(values[1])\n @log.debug \"File transfer with #{first} => #{second}\"\n if cmd=='upload'\n results << session.scp.upload!(first,second)\n elsif cmd=='upload_recurse'\n results << session.scp.upload!(first,second,{:recursive=>true})\n elsif cmd=='download'\n results << session.scp.download!(first,second )\n elsif cmd=='download_recurse'\n results << session.scp.download!(first,second,{:recursive=>true})\n end\n elsif cmd=='cmdtest'\n res_hash = run_on_channel(session,eb(values[0]),values[1])\n results << res_hash['output']\n passed = res_hash['passed'] and passed\n else\n @log.error \"unknown command #{cmd.inspect}\"\n raise VmthError\n end\n end\n return {'output'=>results,'passed'=>passed}\n end",
"def travel_cost( dest )\n sp = shortest_path( dest )\n path_cost( sp )\n end",
"def get_cost_from_ip (ip1,ip2)\n #get the cost betweent the 2 ips reading from the text file produced by gen_weights\n ip_substring = ip1.concat(\",\").concat(ip2)\n cost_lines = $costs.select{ |line| line =~ /^#{ip_substring}/}\n if (cost_lines[0] == nil)\n return 0\n end\n c = cost_lines[0].split(',')\n $sequence_number = c[3].to_i\n return c[2].to_i\nend",
"def cost \n return @extra_cost + @basic_tran.cost\n end",
"def command(str)\n ar=str.split(/ /)\n case ar[0]\n when \"++addr\"\n if ar.size<2\n return @addr.to_s\n else \n @addr=ar[1].to_i\n end\n\n end\n return nil\n end",
"def cost\r\n 0\r\n end",
"def read_command(cmd, synth=SYNTH_A)\n # Make sure cmd is valid\n raise \"unknown command #{cmd}\" unless LENGTH.has_key?(cmd)\n # Make sure synth has no stray bits set\n synth &= (SYNTH_A|SYNTH_B)\n # Get length of data to read\n length = LENGTH[cmd]\n\n serialport do |sp|\n cmd = RD|synth|cmd\n sp.write(cmd.chr)\n data = sp.read(length)\n csum = sp.read(1)\n if @debug\n print\"data\"\n data.each_char {|c| print \" %02x\" % c.ord}\n puts csum ? \"\\ncsum %02x\" % csum.ord : \"\\ncsum --\"\n end\n if !csum || !Valon.checksum_ok?(csum, data)\n #p \"data=#{data.inspect} (len #{data.length})\"\n #p \"csum=#{csum.inspect}\"\n raise 'checksum error'\n end\n return data\n end\n end",
"def oper(n, p)\n @socket << \"OPER #{n} #{p}\"\n end",
"def cost\r\n return @extra_cost + @basic_shifted.cost\r\n end",
"def estimate_cost(sql, *args)\n explanation = ask \"EXPLAIN (FORMAT JSON) #{sql}\", *args\n explanation.first.dig \"Plan\", \"Total Cost\"\n end",
"def command cmd, target=nil, value=nil\r\n @xml.tr do\r\n _tdata cmd\r\n _tdata target\r\n _tdata value\r\n end\r\n end",
"def sh(t, s, c)\n\n end",
"def cost_for_path(path_cpy, amount)\n\tcost = 0\n\tpath = path_cpy\n\t\t\n\twhile(path.length > 1)\n\t\tloc1 = path.shift\n\t\tloc2 = path[0]\n\t\t\t\n\t\tcost += cost_between(loc1, loc2, amount)\n\tend\n\treturn cost\n end",
"def edgeu(cmd)\n $dist[cmd[0]] = cmd[1].to_i\n $neighbors[cmd[0]] = cmd[1].to_i\n client = $clients[cmd[0]]\n msg = Msg.new\n msg.setConfig(\"type\", 2)\n msg.setMessage($hostname + \" \" + cmd[1].to_i.to_s)\n sendMessage(client, msg)\n fillInNodes()\nend",
"def run_prog(prog)\n i = 0\n while prog[i] != 99\n op = prog[i]\n x_addr = prog[i+1]\n y_addr = prog[i+2]\n out_addr = prog[i+3]\n case prog[i]\n when 1\n prog[out_addr] = prog[x_addr] + prog[y_addr]\n when 2\n prog[out_addr] = prog[x_addr] * prog[y_addr]\n when 99\n break\n end\n i += 4\n end\n return prog[0]\nend",
"def process_argv(option, num1, num2)\n port = 9090\n\n transporte = Thrift::Socket.new('localhost', port)\n transporte = Thrift::BufferedTransport.new(transporte)\n protocolo = Thrift::BinaryProtocol.new(transporte)\n\n client = CalculatorService::Client.new(protocolo)\n transporte.open()\n case option\n when \"-h\"\n puts \"This is the help menu.\"\n puts \"Example: [command] num1 num2\"\n puts \" --sum sum two numbers\"\n puts \" --substract substract two numbers\"\n puts \" --division divide two numbers\"\n puts \" --multiply multiply two numbers\"\n exit\n when \"--sum\"\n result = client.Sum(num1.to_f, num2.to_f)\n puts \"Result: \" + result.result.to_s\n \n when \"--substract\"\n result = client.Subtraction(num1.to_f, num2.to_f)\n puts \"Result: \" + result.result.to_s\n when \"--division\"\n result = client.Division(num1.to_f, num2.to_f)\n puts \"Result: \" + result.result.to_s\n when \"--multiply\"\n result = client.Multiplication(num1.to_f, num2.to_f)\n puts \"Result: \" + result.result.to_s\n end\n transporte.close()\nend",
"def cost\n\t\treturn @extra_cost + @real_shake.cost\n\tend",
"def cmdarg; end",
"def cmdarg; end",
"def cmdarg; end",
"def total_cost(distance, mpg, cpg)\n\tprice = (distance / mpg) * cpg \nend",
"def standard_cost_code; end",
"def get_cost_vector\n\t\t\tNMath.sqrt(((@tuneable_data - @goal_vector) ** 2).sum(0))\n\t\tend",
"def args(count)\n resp = count.times.map { |i| read(ip + 1 + i) }\n\n puts(([opcode] + resp).inspect) if debug\n\n resp\n end",
"def edgeuUpdate(msg)\n msg = msg.split(' ')\n dst = msg[0]\n cost = msg[1].to_i\n $dist[dst] = cost\n $neighbors[dst] = cost\nend",
"def cost \n return @extra_cost + @basic_inst.cost\n end",
"def cascad(lcmd) sync_spawn(\"oled-exp\",@opt,\"cascad\",*(lcmd.map {|a|i a.to_s}) ) end",
"def total_cost(text)\n text.split(\"\\n\").inject(0){ |acc, line| acc + line_cost(line) }\n end",
"def total_cost\n [executor_cost, team_lead_cost, account_manager_cost].compact.inject(&:+)\n end",
"def execute(aCommand,aPGW,aUser,aPassword,para1,para2,para3,para4,para5,para6,para7,para8,para9,para10)\n\n\t\tresult = \"\"\n \t\thostname = aPGW\n \t\tuser = aUser\n \t\tpassword = aPassword\n \t\tmsisdn = para1\n\t\tport = 7776\n\t\tcommand = aCommand\n\n\t\tcommandString = buildCommand(aCommand,para1,para2,para3,para4,para5,para6,para7,para8,para9,para10)\n\t\tputs 'about to open tcp connection.....'\n\t\ts = TCPSocket.open(hostname, port)\n\t\tputs 'connection opened'\n\t\ts.write(\"LGI:OPNAME=\\\"#{user}\\\", PWD=\\\"#{password}\\\";\")\n\n\t\tputs 'logged in!'\n\t\tstream = true\n\n\t\twhile stream\n\t \t\tline = s.gets\n \t\t\t puts line.chop \n \t \t\tif (line[/END/])\n \t \t\t\tstream = false\n \t \t \t\t#s.close\n \t\t\tend \n \t\tend\n\n \t\ts.write(commandString)\n \t\ts.write(\"LGO:;\")\n\n\n\n\t\tstream = true\n\n\t\twhile stream\n\t\t\t line = s.gets \n\t \t\tresult = result+line\n \t \t\t#puts line.chop \n \t \t\tif (line[/END/])\n \t \t\t\tstream = false\n \t \t\t\ts.close \n \t \t\t\tputs 'closed connection' \n \t\t\tend \n \t\tend\n\n \t\treturn result\n\n\n\n end",
"def sendop(*args)\n common_call(args) do |filtered|\n handle = task.do_operation_send(name, orocos_arguments_typenames, filtered)\n handle.instance_variable_set :@operation, self\n handle.instance_variable_set :@orocos_return_types, @orocos_return_typenames.dup\n handle.instance_variable_set :@return_values, new_result\n handle\n end\n end",
"def total_cost\n # quantity * unit_cost_price\n unit_cost_price\n end",
"def opcode(op,args) \"#{op} #{args.join ','}\" end",
"def opcode(op,args) \"#{op} #{args.join ','}\" end",
"def opcode(op,args) \"#{op} #{args.join ','}\" end",
"def opcode(op,args) \"#{op} #{args.join ','}\" end",
"def cost\n unless @cost\n @cost = 0\n @nodes_v.each do |v|\n @cost += @nodes_s.map { |s| v.distance_to(s) }.min\n end\n end\n\n @cost\n end",
"def constructSendCmd(ipport, ipaddr, cmd, nodeType)\n nmsg = MsgPacket.new\n cmstr = nmsg.constructMsg(cmd, nodeType)\n sendCommand(ipport, ipaddr, cmstr)\n insertPool(cmstr, ipaddr)\n end",
"def calculate\n @output << @first << (@op.to_s + @second.to_s)\n \n case @op\n when \"+\" then @result = @first + @second\n when \"-\" then @result = @first - @second\n when \"*\" then \n @result = @first * @second\n # Nasobeni pod sebou ma smysl resit jenom pokud ma druhy citatel vic nez jednu cislici\n if @second.to_s.length > 1\n @output << '-'\n # Iterace pozadu pres druhy citatel pro nasobeni pod sebou\n # Idealne by to zde slo zjednodusit na @second.to_s.reverse.each_char.with_index,\n # ale to jak jsem zjistil neni podporovano v 1.8.x\n @second.to_s.reverse.split(\"\").each_with_index do |char, i|\n @output << (@first * char.to_i).to_s + (' ' * i)\n end \n end\n end\n @output << '-'\n @output << @result\n self # pro zjednoduseni chain callu \n end",
"def cost(op)\n {labor: 4.38, materials: 0}\nend",
"def calculate_hcost(p)\n\t\tdistance = (@end_pos[0] - p[0]).abs + (@end_pos[1] - p[1]).abs\n\t\tdistance * COST_ORT\n\tend",
"def latency_of(dist)\n len=(dist == 0) ? OVERHEAD_INNER : OVERHEAD_OUTER + dist\n if len <= 300 # [cm]\n #Copper cable\n len*4.4E-9 #HP BladeSystem c-Class 40G QSFP+ to QSFP+ Direct Attach Copper Cable\n else\n # Optical cable \n len*5.2E-9 #Speed of light in glass= 190000km/sec\n end\nend",
"def total_cost\n @cost + tip\n end",
"def edgeb_stdin(cmd)\n $record_ip[$hostname] = cmd[0]\n $record_ip[cmd[2]] = cmd[1]\n node = $node_info.new \n time = nil\n $lock.synchronize{ \n node.src = $hostname\n node.dst = cmd[2]\n node.cost = 1\n node.nexthop = cmd[2]\n time = $clock.to_i\n $rt[cmd[2]] = node\n if $local_ip == nil then $local_ip = cmd[0] end\n\n $network.undir_connection($hostname, cmd[2], time, 1)\n }\n\n client = TCPSocket.open(cmd[1], $nodesFile[cmd[2]][\"PORT\"])\n client.puts(\"EDGEB2 #{cmd[2]} #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def build_for_send_amount(address, address_dest, path, script, xpubs = [])\n build_inputs([address])\n total, fee = build_fee(:send)\n output_amount = total - (fee.to_i * 2)\n output_amount_to_addr2 = fee.to_i\n send(inputs: @inputs,\n path: path,\n output_amount: output_amount,\n address: address,\n output_amount_to_addr2: output_amount_to_addr2,\n addr2: address_dest,\n script: script,\n xpubs: xpubs)\n end",
"def workload\n [@nodeid,@data.count]\n end",
"def execute(cmd_string, complete_target = true, target = nil, sel = nil)\n #DebugTools.log_outbound_command(self.command, cmd_string, complete_target, target)\n\n sel = @unit.world.selchannel\n if sel\n @unit.print_both(@unit, :reply, \"WEIGHTS: \") \n sel.members.each do |m|\n if m.weight > 0\n out = \"#{m.nick} - sent: #{m.incoming_weight} received: #{m.outgoing_weight} total: #{m.weight}\" \n @unit.print_both(@unit, :reply, out) \n end\n end\n end\n return true\n \n end",
"def command_queue; end",
"def execute_action(action, tem_index)\n case action[:action]\n when :migrate\n in_part = @lock.synchronize { @tem_parts[action[:secpack]][tem_index] }\n target_ecert = @tem_certs[action[:to]]\n \n t0 = Time.now\n out_part = in_part.migrate target_ecert, @tems[tem_index]\n time_delta = Time.now - t0\n \n @lock.synchronize do\n @tem_parts[action[:secpack]][action[:to]] = out_part\n task = action[:secpack] == :mapper ? :migrate_map : :migrate_reduce\n @timings[:tems][tem_index][task] += time_delta\n end\n \n when :map\n mapper, item = nil, nil\n @lock.synchronize do\n mapper = @tem_parts[:mapper][tem_index]\n item = @db.item(action[:item])\n end\n\n t0 = Time.now\n output = mapper.map_object item, @tems[tem_index]\n time_delta = Time.now - t0\n \n @lock.synchronize do\n @outputs[action[:output_id]] = output\n @timings[:tems][tem_index][:map] += time_delta\n end\n \n when :reduce\n reducer, output1, output2 = nil, nil, nil\n @lock.synchronize do\n reducer = @tem_parts[:reducer][tem_index]\n output1 = @outputs[action[:output1_id]]\n output2 = @outputs[action[:output2_id]]\n end\n \n t0 = Time.now\n output = reducer.reduce_outputs output1, output2, @tems[tem_index]\n time_delta = Time.now - t0\n \n @lock.synchronize do\n @outputs[action[:output_id]] = output\n @timings[:tems][tem_index][:reduce] += time_delta\n end\n\n when :finalize\n finalizer = nil\n @lock.synchronize do\n finalizer = @tem_parts[:finalizer][tem_index]\n output = @outputs[action[:output_id]]\n end\n \n t0 = Time.now\n final_output = finalizer.finalize_output output, @tems[tem_index]\n time_delta = Time.now - t0\n \n @lock.synchronize do\n @outputs[action[:final_id]] = final_output\n @timings[:tems][tem_index][:finalize] += time_delta\n end\n end\n end",
"def add_result result\n source = result.source\n destination = result.destination\n\n @drb_results_received += 1\n @drb_exceptions_raised += 1 unless result.status\n\n sent_timestamp = @last_peer_send[destination].delete source\n message, argc, allocations = @last_sent_message[destination].delete source\n\n return unless sent_timestamp\n\n latency = result.timestamp - sent_timestamp\n\n @peer_latencies[destination][source].add latency\n @message_latencies[message][argc].add latency\n @message_allocations[message][argc].add allocations + result.allocations\n end",
"def getcost()\n return @cost\n end",
"def estimate_price(from, dest)\n distance = from.zip(dest).map { |x| x.reduce(:-).abs }.sum\n @total_pay = distance * 300\n \"Distance : #{distance}\\nThe price is #{total_pay}\"\n end",
"def create_receipt\n total_cost = 0\n @basket.each {|item, quantity|\n total_cost += price(item,quantity)\n }\n total_cost\nend",
"def send_and_receive( cmd_str )\n trans_send( cmd_str )\n trans_send( RPC::MSG_END )\n trans_receive()\n end",
"def process\n if command_type == :C_COMMAND\n @c = Code.new([comp, dest, jump])\n \"#{@c.translate_c}\\n\"\n else\n @c = Code.new(@current[1..-1])\n \"#{@c.translate_a}\\n\"\n end\n end",
"def execute_transaction\n#each transfer can only happen once\n if valid? && sender.balance > amount && self.status == \"pending\"\n receiver.balance += amount\n sender.balance -= amount\n self.status = \"complete\"\n else\n#rejects a transfer if the sender doesn't have a valid account\n reject_transfer\n end\n end",
"def send_cmd(cmd)\n full_cmd = '$' + cmd + '#' + checksum(cmd)\n vprint_status('Sending cmd: '+full_cmd)\n sock.put(full_cmd)\n read_ack\n end",
"def command\n consume 1, :command\n end",
"def cost\r\n\t\treturn @extra_cost + @real_need.cost\r\n\tend",
"def cops; end",
"def cops; end",
"def cops; end",
"def process_op\n # validate_op\n (opcode, modes, addrs) = fetch_instruction\n\n\n case opcode\n\n # ADD: 1, *X, *Y, *(X+Y)\n when 1\n catch_fire if modes[2] == 1\n result = @at.lookup(addrs[0], modes[0]) + @at.lookup(addrs[1], modes[1])\n @at.write(addrs[2], modes[2], result)\n @counter += 4\n\n # MULT: 2, *X, *Y, *(X+Y)\n when 2\n catch_fire if modes[2] == 1\n result = @at.lookup(addrs[0], modes[0]) * @at.lookup(addrs[1], modes[1])\n @at.write(addrs[2], modes[2], result)\n @counter += 4\n\n # INPUT: 3, ADDR\n when 3\n catch_fire if modes[0] == 1\n result = read_input\n if result.nil?\n @waiting = true\n return 0\n end\n @at.write(addrs[0], modes[0], result)\n @counter += 2\n\n # OUTPUT: 4, *ADDR\n when 4\n value = @at.lookup(addrs[0], modes[0])\n write_output(value)\n @counter += 2\n\n # JUMP-IF-TRUE: 5, *BOOL, *INST_PTR\n when 5\n if @at.lookup(addrs[0], modes[0]) != 0\n @counter = @at.lookup(addrs[1], modes[1])\n else\n @counter += 3\n end\n\n # JUMP-IF-FALSE: 6, *BOOL, *INST_PTR\n when 6\n if @at.lookup(addrs[0], modes[0]) == 0\n @counter = @at.lookup(addrs[1], modes[1])\n else\n @counter += 3\n end\n\n # LESS-THAN: 7, *X, *Y, *(X<Y?1:0)\n when 7\n catch_fire if modes[2] == 1\n result = @at.lookup(addrs[0], modes[0]) < @at.lookup(addrs[1], modes[1]) ? 1 : 0\n @at.write(addrs[2], modes[2], result)\n @counter += 4\n\n # EQUALS: 8, *X, *Y, *(X=Y?1:0)\n when 8\n catch_fire if modes[2] == 1\n result = @at.lookup(addrs[0], modes[0]) == @at.lookup(addrs[1], modes[1]) ? 1 : 0\n @at.write(addrs[2], modes[2], result)\n @counter += 4\n\n # UPDATE OFFSET: 9 *OFFSET\n when 9\n @at.offset += @at.lookup(addrs[0], modes[0])\n @counter += 2\n\n # HALT: 99\n when 99\n halt\n @counter += 1\n\n else\n catch_fire(\"opcode: #{opcode}\")\n end\n end",
"def cost\n return @cost\n end",
"def cost\n return @cost\n end",
"def send_cmd(cmd)\n # What time is it ?\n # update_access\n\n # Write the command plus a newline to the input\n @pipe.write_input(cmd + \"\\n\")\n end",
"def cost\n start_value\n end",
"def exec_queue(command,data)\n result = @gardener.seed(\"#{command} #{data}\")\n\t\t\t$log_sambala.debug(\"exec_queue result\") {\"#{result.inspect}\"}\n\t\t\tresult.integer? ? [true,result] : [false,result]\n end",
"def run_ef_tx_rx_cmd ts, tx_idx, rx_idx_list, frame\n cmd = \"ef name f1 #{frame}\"\n cmd += \" tx #{ts.pc.p[tx_idx]} name f1\"\n ts.pc.p.each_index do |idx|\n if rx_idx_list.include? idx\n cmd += \" rx #{ts.pc.p[idx]} name f1\"\n else\n cmd += \" rx #{ts.pc.p[idx]}\"\n end\n end\n\n ts.pc.run \"sudo #{cmd}\"\nend",
"def dpExecuteAction(host, cmd)\n mc = rpcclient \"deploop\"\n h = Socket.gethostbyname(host)\n mc.identity_filter \"#{h[1][0]}\"\n mc.progress = false\n\n result = mc.execute(:cmd=> cmd)\n\n mc.disconnect\n\n result[0][:data].each do |a|\n puts a\n end\n\n result[0][:data][:exitcode]\n end",
"def total\n result = 0\n (1..3).each do |n|\n v = eval \"cost_\" + n.to_s\n result += v.to_f\n end\n result\n end",
"def op\n opcode % 100\n end",
"def op\n opcode % 100\n end",
"def total_cost\n @quantity * @price\n end",
"def consume_command! num=1\n @command.shift(num)\n end",
"def execute\n instruction = @emulator.instruction_register\n\n source = instruction.operand(2)\n @emulator.register_write(@destination, @emulator.register_read(@source))\n end"
] |
[
"0.58614534",
"0.56380147",
"0.55545676",
"0.5505499",
"0.5289272",
"0.52743083",
"0.5253263",
"0.52382857",
"0.5230898",
"0.5194175",
"0.5187378",
"0.51801586",
"0.5164179",
"0.51584613",
"0.51559526",
"0.51432997",
"0.51432997",
"0.5137132",
"0.5135012",
"0.512023",
"0.5099516",
"0.50813264",
"0.50802857",
"0.5071976",
"0.50340366",
"0.5029158",
"0.50128204",
"0.49996737",
"0.49901044",
"0.49868056",
"0.4968909",
"0.49687126",
"0.49654967",
"0.4964757",
"0.49623647",
"0.49495625",
"0.49404252",
"0.49402294",
"0.49365386",
"0.49364275",
"0.4934716",
"0.49336493",
"0.49336493",
"0.49336493",
"0.4927055",
"0.49215314",
"0.49169907",
"0.49133193",
"0.49022678",
"0.48978093",
"0.489546",
"0.48890847",
"0.48781595",
"0.486461",
"0.4842923",
"0.48363778",
"0.481727",
"0.481727",
"0.481727",
"0.481727",
"0.48119068",
"0.4804004",
"0.47999597",
"0.4798615",
"0.47973904",
"0.47926828",
"0.47902548",
"0.47869974",
"0.47815704",
"0.47789663",
"0.47645462",
"0.47618866",
"0.4758187",
"0.47547933",
"0.47508076",
"0.47432485",
"0.47356638",
"0.47347394",
"0.47310582",
"0.47260103",
"0.47237724",
"0.47234944",
"0.47200847",
"0.47191527",
"0.47191527",
"0.47191527",
"0.47188827",
"0.4716367",
"0.4716367",
"0.4713342",
"0.47126153",
"0.47114503",
"0.4706755",
"0.4706193",
"0.47051793",
"0.47045374",
"0.47045374",
"0.47042763",
"0.46978584",
"0.46955326"
] |
0.61732787
|
0
|
cmd[0] : DEST cmd[1] : COST cmd[2] : Time of updated edge
|
def edgeu_network(cmd)
$lock.synchronize{
$network.update_cost($hostname, cmd[0], cmd[1].to_i,cmd[2].to_i)
if $rt.has_key? cmd[0]
$rt[cmd[0]][:cost] = cmd[1].to_i
end
}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edgeu(cmd)\n time = nil\n $lock.synchronize{\n time = $clock.to_i\n $network.update_cost($hostname, cmd[0], cmd[1].to_i, time)\n\n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n } \n\n client = TCPSocket.open($local_ip, $nodesFile[cmd[0]][\"PORT\"])\n client.puts(\"EDGEU2 #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def edgeuUpdate(msg)\n msg = msg.split(' ')\n dst = msg[0]\n cost = msg[1].to_i\n $dist[dst] = cost\n $neighbors[dst] = cost\nend",
"def edgeu(cmd)\n $dist[cmd[0]] = cmd[1].to_i\n $neighbors[cmd[0]] = cmd[1].to_i\n client = $clients[cmd[0]]\n msg = Msg.new\n msg.setConfig(\"type\", 2)\n msg.setMessage($hostname + \" \" + cmd[1].to_i.to_s)\n sendMessage(client, msg)\n fillInNodes()\nend",
"def updateTable(cmd)\n # puts \"TRYING TO UPDATE TABLE\"\n sentFrom = cmd.shift\n curr_edge_time = nil\n new_edge_time = nil\n new_edge_cost = nil\n node = $node_info.new\n arr = nil\n hops = nil\n lis = nil\n loop{\n new_edge_time = cmd[3].to_i\n new_edge_cost = cmd[2].to_i\n\n $lock.synchronize{\n curr_edge_time = $network.get_time(cmd[0],cmd[1])\n }\n\n if curr_edge_time == 0\n #name of srcNode,name of destNode,cost of edge,time of Edge\n $lock.synchronize{\n $network.undir_connection(cmd[0], cmd[1], new_edge_time, new_edge_cost)\n }\n if ($rt.has_key?(cmd[0]) != true)\n node.src = $hostname\n node.dst = cmd[0]\n node.cost = nil #do dijsktras\n node.nexthop = nil #do dijsktras\n $lock.synchronize{\n $rt[cmd[0]] = node\n }\n end \n if($rt.has_key?(cmd[1]) != true)\n node.src = $hostname\n node.dst = cmd[1]\n node.cost = nil #do dijsktras\n node.nexthop = nil #do dijsktras\n $lock.synchronize{\n $rt[cmd[1]] = node\n }\n \n end\n\n elsif curr_edge_time < new_edge_time\n $lock.synchronize{\n $network.update_cost(cmd[0], cmd[1], new_edge_time, new_edge_cost)\n }\n end \n \n cmd.shift(4)\n break if cmd.length < 4\n \n # puts \"ABOUT TO RUN DIJKSTRAS\"\n $lock.synchronize{\n arr = $network.dijkstra($hostname) \n }\n $full_path = arr[0]\n #puts \"THIS IS THE RETURN OF DIJKSTRAS #{arr}\" \n $lock.synchronize{\n $rt.each_key {|key|\n update = $node_info.new \n # puts \"Key IS #{key}\"\n hops = arr[0]\n lis = arr[1]\n prevs = hops[key]\n update.src = $hostname\n update.dst = key\n update.cost = lis[key]\n update.nexthop = prevs[1]\n $rt[key] = update\n # puts \"ROUTING TABLE #{$rt}\"\n }\n }\n }\nend",
"def edgeb_network(cmd)\n node = $node_info.new \n $lock.synchronize{\n \n node.src = $hostname\n node.dst = cmd[1]\n node.cost = 1\n node.nexthop = cmd[1]\n $rt[cmd[1]] = node\n if $local_ip == nil then $local_ip = cmd[2] end\n\n $network.undir_connection($hostname, cmd[1], cmd[3].to_i, 1) \n }\n #puts \"THIS IS THE ROUTING TABLE: #{$rt}\"\nend",
"def edged(cmd)\n $lock.synchronize{ \n $network.remove_edge($hostname,cmd[0])\n\n if $rt.has_key? cmd[0]\n $rt.delete cmd[0] \n end\n\n }\nend",
"def edgeb_stdin(cmd)\n $record_ip[$hostname] = cmd[0]\n $record_ip[cmd[2]] = cmd[1]\n node = $node_info.new \n time = nil\n $lock.synchronize{ \n node.src = $hostname\n node.dst = cmd[2]\n node.cost = 1\n node.nexthop = cmd[2]\n time = $clock.to_i\n $rt[cmd[2]] = node\n if $local_ip == nil then $local_ip = cmd[0] end\n\n $network.undir_connection($hostname, cmd[2], time, 1)\n }\n\n client = TCPSocket.open(cmd[1], $nodesFile[cmd[2]][\"PORT\"])\n client.puts(\"EDGEB2 #{cmd[2]} #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def edged(cmd)\n $ips.delete(cmd[0])\n $dist[cmd[0]] = \"INF\"\n $neighbors.delete(cmd[0])\n $next[cmd[0]] = \"NA\"\n client = $clients[cmd[0]]\n client.close()\n $clients.delete(cmd[0])\nend",
"def edgebReflex(msg, client)\n msg = msg.split(',')\n dstip = msg[0]\n srcip = msg[1]\n dst = msg[2]\n $ips[$hostname] = srcip\n $ips[dst] = dstip\n $dist[dst] = 1\n $neighbors[dst] = 1\n $next[dst] = dst\n $clients[dst] = client\n fillInNodes()\nend",
"def travel_time_and_cost\n cost = 0\n travel_time = 0\n (@path.size - 1).times do |i|\n current_vertex = @path[i]\n next_vertex = @path[i+1]\n # travel time = travel distance\n distance = Vertex.euclidean_distance(current_vertex, next_vertex)\n travel_time += distance\n # calculate how early or how late is service\n early_cost = (next_vertex.ready_time - travel_time) > 0 ? (next_vertex.ready_time - travel_time) : 0\n late_cost = (travel_time - next_vertex.due_time) > 0 ? (travel_time - next_vertex.due_time) : 0\n # calculate penalty cost\n cost += early_cost * @penalty_coefficient + late_cost * @penalty_coefficient\n # add service_time and early_cost (wait-for-service time) to travel time\n travel_time += next_vertex.service_time + early_cost\n end\n return cost, travel_time\n end",
"def cost_query_from\n @edge_table\n end",
"def update!(**args)\n @cost_milli_node_hours = args[:cost_milli_node_hours] if args.key?(:cost_milli_node_hours)\n @successful_stop_reason = args[:successful_stop_reason] if args.key?(:successful_stop_reason)\n end",
"def update!(**args)\n @cost_milli_node_hours = args[:cost_milli_node_hours] if args.key?(:cost_milli_node_hours)\n @successful_stop_reason = args[:successful_stop_reason] if args.key?(:successful_stop_reason)\n end",
"def update!(**args)\n @cost_milli_node_hours = args[:cost_milli_node_hours] if args.key?(:cost_milli_node_hours)\n @successful_stop_reason = args[:successful_stop_reason] if args.key?(:successful_stop_reason)\n end",
"def command(cmd, arg = 2)\n return if @sp == nil\n #<SOT><CMD_BYTE><CHECK_SUM><EOT>\n case cmd\n=begin\n Request DCF Time\n <SOH><0x30><Chksum><EOT>\n=end\n when 0 #Poll DCF Time\n exchange(\"\\x01\\x30\\xcf\\x04\", 7)\n puts DCF77.new(@response).to_s\n=begin\n Request Dataset\n \t<SOH><0x31><Chksum><EOT>\n \t\tResponse from weather station: (34/60 Bytes) Mine has additional 0 byte, so 35/61 bytes are received.\n \t\t1. Data available\n \t\t\tBlock no.: 2 bytes Number of the block in the memory\n \t\t\t (no relation to time. Serves to control dataset registered twice).)\n \t\t\tTime: 2 bytes Age of the dataset in minutes up to the current time.\n \t\t\t\t\t\t\t\t age = ( data[2] & 0xff ) + ( data[3] << 8 & 0xff00 );\n \t\t\tData: 30 (9 sensors) or 56 (16 sensors) bytes\n \t\t2. No data available: <DLE>\n=end\n when 1 #Request dataset\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n #@response.each { |r| print \"%02X \" % r }\n s = Sensors.new(@response)\n if s.data?\n puts s.to_data_row\n puts Sensors.new(@response).to_s\n end\n=begin\n \tSelect Next Dataset\n \t\t<SOH><0x32><Chksum><EOT>\n \t\t\tResponse from weather station: (1 Byte)\n \t\t\t\t1. Next dataset available : <ACK> 0x06\n \t\t\t\t2. No dataset available: <DLE> 0x10\n=end\n when 2 #select next dataset\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tSet 8 Sensors\n \t\t<SOH><0x33><Chksum><EOT>\n \t\tResponse from weather station: (1 Byte)\n \t\t<ACK>\n=end\n when 3 #activate 8 sensors\n exchange(\"\\x01\\x33\\xcc\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n set 16 Sensors\n \t<SOH><0x34><Chksum><EOT>\n \tResponse from weather station: (1 Byte)\n \t<ACK>\n=end\n when 4 #activate 16 sensors\n exchange(\"\\x01\\x34\\xcb\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tStatus\n \t <SOH><0x35><Chksum><EOT>\n \tResponse from weather station: (21 Byte)\n \tBytes 1 - 18\n \t\t\tS:1-8 Temp/Hum\n \t\t\t9 Rain,\n \t\t\t10 Wind\n \t\t\t11 Indoor Temp/Hum/Pres\n \t\t\t12 S9:Temp/Hum\n \t\t\t13-15 S10-15:Temp/Hum/Pres\n \t\tByte >= 0x10 if sensor present\n \t\tvalue > 0x10 number of error\n \tByte 19 Sample Interval in minutes\n \tByte 20\n \t bit 0 DFC77 time receiver active\n \t\tbit 1 HF if set\n \t\tbit 2 8/16 Sensors\n \t\tbit 3 DFC Synchronized (Not likely in NZ)\n \tByte 21 Version Number\n=end\n when 5 #Request Status\n exchange(\"\\x01\\x35\\xca\\x04\", 21)\n @response.each { |r| print \"%02X \" % r }\n puts\n=begin\n Set Interval time\n \t <SOH><0x36><minutes><Chksum><EOT>\n \t\tminutes range 1..60\n \t Response from weather station: (1 Byte)\n \t<ACK> if in range\n \t<DLE> if out of range\n=end\n when 6 #set interval time\n #<SOT><CMD_BYTE><ARGUMENT><CHECK_SUM><EOT>\n raise Weather_exception, \"Interval Range 2..60\" if arg > 60 || arg < 2\n exchange(\"\\x01\\x36#{arg.chr}#{(0xc9-arg).chr}\\x04\", 1)\n exit @response[0] == ACK ? 0 : 1\n\n when 12 #Loop through 1 and 2\n begin\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n s = Sensors.new(@response)\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n if s.data?\n\t puts s.to_data_row\n else\n break\n end\n end while( @response[0] == ACK )\n end\n end",
"def latency_of(dist)\n len=(dist == 0) ? OVERHEAD_INNER : OVERHEAD_OUTER + dist\n if len <= 300 # [cm]\n #Copper cable\n len*4.4E-9 #HP BladeSystem c-Class 40G QSFP+ to QSFP+ Direct Attach Copper Cable\n else\n # Optical cable \n len*5.2E-9 #Speed of light in glass= 190000km/sec\n end\nend",
"def hyperball_on_edge(edge)\n update_node = @counters.get_counter(edge[1])\n neighbor_node = @counters.get_counter(edge[0])\n\n update_node.merge(neighbor_node)\n end",
"def add_edge(x, y, cost: 1)\n raise\n end",
"def push_request\n if (project.max_flow source_id, target_id, start_time) < size\n update_attribute :success, false\n else\n request_size = self.size\n\n while request_size > 0\n timer = Timer.where(:time => start_time, :project_id => project.id).first_or_create\n\n if timer.capacities_matrix_text.present?\n capacities_matrix = eval(timer.capacities_matrix_text)\n else\n capacities_matrix = (project.connections_hashes start_time).last\n\n timer.capacities_matrix_text = capacities_matrix.to_s\n end\n\n timer.save\n \n best_path = project.best_path source_id, target_id, start_time\n\n capacities_matrix = eval((timer = project.timers.where(:time => self.start_time).first).capacities_matrix_text)\n\n min_capacity = []\n\n best_path.each_cons(2).to_a.each do |source_id, target_id|\n min_capacity << capacities_matrix[source_id][target_id] \n end\n \n min_capacity = min_capacity.min\n\n min_capacity = min_capacity > request_size ? request_size : min_capacity\n \n (self.start_time..(self.start_time + self.lifetime - 1)).each do |time|\n timer = Timer.where(:time => time, :project_id => project.id).first_or_create\n\n if timer.capacities_matrix_text.present?\n capacities_matrix = eval(timer.capacities_matrix_text)\n else\n capacities_matrix = (project.connections_hashes time).last\n end\n \n best_path.each_cons(2).to_a.each do |source_id, target_id|\n capacities_matrix[source_id][target_id] -= min_capacity \n end\n\n timer.capacities_matrix_text = capacities_matrix.to_s\n\n timer.save\n end\n\n update_attribute :path, path.to_s + best_path.to_s\n\n request_size -= min_capacity\n end\n\n update_attribute :success, true\n end\n end",
"def latency; end",
"def tellNode(cmd, topo, domain)\n puts \"---------------------------------------------------\"\n d = (domain == nil) ? OConfig.domain : domain\n command = nil\n if (cmd == \"on\" || cmd == \"-on\" || cmd == \"--turn-on\")\n command = \"on\"\n elsif (cmd == \"offs\" || cmd == \"-offs\" || cmd == \"--turn-off-soft\")\n command = \"offSoft\"\n elsif (cmd == \"offh\" || cmd == \"-offh\" || cmd == \"--turn-off-hard\")\n command = \"offHard\"\n end\n if command == nil\n puts \"ERROR - Unknown command : '#{cmd}'\" \n puts \"Use 'help' to see usage information\" \n puts \"\"\n exit 1\n end\n puts \" Testbed : #{d} - Command: #{command}\"\n topo.eachNode { |n|\n url = \"#{OConfig[:tb_config][:default][:cmc_url]}/#{command}?x=#{n[0]}&y=#{n[1]}&domain=#{d}\"\n response = NodeHandler.service_call(url, \"Can't send command to CMC\")\n if (response.kind_of? Net::HTTPOK)\n puts \" Node n_#{n[0]}_#{n[1]} - Ok\"\n else\n puts \" Node n_#{n[0]}_#{n[1]} - Error (node state: 'Not Available')\"\n end\n }\n puts \"---------------------------------------------------\"\nend",
"def update_graph\n connection.execute <<-EOS\n UPDATE #{oqgraph_table_name} \n SET origid = #{self.send(self.class.from_key)}, \n destid = #{self.send(self.class.to_key)}, \n weight = #{self.send(self.class.weight_column)} \n WHERE origid = #{self.send(self.class.from_key + '_was')} AND destid = #{self.send(self.class.to_key + '_was')};\n EOS\n end",
"def lsp()\n\t$sequencenum += 1\n\tmsg = \"LSP \"\n\tmsg<<\"#{$hostname} \"\n\t#puts (\"neighbor in lsp = #{$neighbors}\")\n\t$neighbors.each do |key, value|\n\t\tmsg<<\"#{value.name}\"\n\t\tmsg<<\":\"\n\t\tmsg<<\"#{value.cost}\"\n\t\tmsg<<\"|\"\t\t\n\tend\n\t#puts (\"before chomp #{msg}\")\n\tmsg = msg.chomp(\"|\")\n\tmsg<<\" #{$sequencenum}\"\n\t#puts (\"sending msg #{msg}\")\n\t# flooding each neighbor node with lsp\n\t#puts (\"flooding msg = #{msg}\")\n\tflood(msg)\nend\n\n#pass whatever message you receive to each of the connecting negihbors of the node\ndef flood(msg)\n\t#$semaphore.synchronize{\n\t$neighbors.each do |key, value|\n\t#puts (\"writing to #{value.name} : #{msg} through socket #{value.sock}\")\n\t#value.sock.puts(\"#{msg}\")\\\n\t\twriteTo(value.sock, msg)\n\t\t#$pq.insert(Time.new, Event.new(\"WRITE\", [value.sock, msg]))\n\tend\n\t#}\nend",
"def transfer(event)\n connection = event.connection\n src = connection.src\n dst = connection.dst\n queues.each do |q|\n q.register_stat(q.state, event.time - @current_time) # register stat for all queues\n end\n @current_time = event.time\n @current_event = event\n src.register_exit\n if src.state >= src.servers\n connections = @network.get_connections(src) # get all connections for queue\n connection = select_connection(connections) # handle probabilities\n event_type = connection.nil? ? \"exit\" : \"transfer\" # set type for scheduling event\n @scheduler.schedule(event_type, (@current_time + @random.next_in_range(src.min_service, src.max_service)), src, connection) # schedule event\n raise OutOfRandomsError if @random.see_next < 0\n end\n if dst.state < dst.capacity\n dst.register_entry\n if dst.state <= dst.servers\n connections = @network.get_connections(dst) # get all connections for queue\n connection = select_connection(connections) # handle probabilities\n event_type = connection.nil? ? \"exit\" : \"transfer\" # set type for scheduling event\n @scheduler.schedule(event_type, (@current_time + @random.next_in_range(dst.min_service, dst.max_service)), dst, connection) # schedule event\n raise OutOfRandomsError if @random.see_next < 0\n end\n else\n dst.register_loss\n end\n end",
"def to_s\n \"#{@name}::#{@num_nodes}::#{Base64.encode64(@start_time._dump).chomp}::#{Base64.encode64(@end_time._dump).chomp}::#{total_time}::#{cost}\"\n end",
"def cost \n return @extra_cost + @basic_transfer.cost\n end",
"def travel_cost( dest )\n sp = shortest_path( dest )\n path_cost( sp )\n end",
"def update!(**args)\n @end_tracking_time_usec = args[:end_tracking_time_usec] if args.key?(:end_tracking_time_usec)\n @start_tracking_time_usec = args[:start_tracking_time_usec] if args.key?(:start_tracking_time_usec)\n @wait_compress_time_usec = args[:wait_compress_time_usec] if args.key?(:wait_compress_time_usec)\n @wait_content_cache_usec = args[:wait_content_cache_usec] if args.key?(:wait_content_cache_usec)\n @wait_credential_time_usec = args[:wait_credential_time_usec] if args.key?(:wait_credential_time_usec)\n @wait_dns_time_usec = args[:wait_dns_time_usec] if args.key?(:wait_dns_time_usec)\n @wait_fetch_client_usec = args[:wait_fetch_client_usec] if args.key?(:wait_fetch_client_usec)\n @wait_for_cached_content_streaming_usec = args[:wait_for_cached_content_streaming_usec] if args.key?(:wait_for_cached_content_streaming_usec)\n @wait_for_fetch_usec = args[:wait_for_fetch_usec] if args.key?(:wait_for_fetch_usec)\n @wait_host_id_time_usec = args[:wait_host_id_time_usec] if args.key?(:wait_host_id_time_usec)\n @wait_next_flow_usec = args[:wait_next_flow_usec] if args.key?(:wait_next_flow_usec)\n @wait_robots_cache_time_usec = args[:wait_robots_cache_time_usec] if args.key?(:wait_robots_cache_time_usec)\n @wait_robots_fetch_time_usec = args[:wait_robots_fetch_time_usec] if args.key?(:wait_robots_fetch_time_usec)\n @wait_robots_time_usec = args[:wait_robots_time_usec] if args.key?(:wait_robots_time_usec)\n @wait_schedule_time_usec = args[:wait_schedule_time_usec] if args.key?(:wait_schedule_time_usec)\n end",
"def transfer(node, ins) ; ins ; end",
"def execute_best_swap graph\n gain,swap = execute_swap graph\n compute_swap\nend",
"def make_transferred!\n update_column(:transferred_at, Time.current)\n end",
"def save_message_from(n, delta)\n incoming[neighbors.index(n)] = delta\n end",
"def update_edges(edges, l_act_edge)\n prev_edge = Edge.new\n\n prev_edge = edges;\n\n begin\n edges = prev_edge.next\n if (edges.delta_y > 1)\n edges.delta_y -= 1\n edges.x_int = edges.x_int - edges.delta_x\n prev_edge = edges\n else\n prev_edge.next = edges.next\n l_act_edge = prev_edge if (edges == l_act_edge)\n edges = nil # dispose edges\n end\n end while (prev_edge != l_act_edge)\n \n return l_act_edge\n end",
"def get_cost_vector\n\t\t\tNMath.sqrt(((@tuneable_data - @goal_vector) ** 2).sum(0))\n\t\tend",
"def traceroute(cmd)\n\tdst = cmd[0]\n\n # Check to see if there is a next hop\n next_hop = $next[dst]\n if next_hop == \"NA\"\n STDOUT.puts \"TRACEROUTE ERROR: HOST UNREACHABLE\"\n return\n end\n\n # This will print out itself with hop 0 and time 0.00\n\tSTDOUT.puts(\"0 \" + $hostname + \" 0.00\")\n \n if next_hop == $hostname\n return\n end\n\n # Sets up the message for tracerouteCallBack\n client = $clients[next_hop]\n msg = Msg.new\n msg.setConfig(\"type\", 4)\n msg.setConfig(\"code\", 0)\n msg.setMessage($hostname + \" \" + dst + \" \" + dst + \" 0 \" + $currtime.to_f.round(4).to_s)\n $traceroute_finish = false\n $hop_counter = \"1\"\n sendMessage(client, msg)\n\n start_time = $currtime\n while $currtime - start_time < $ping_timeout\n if $traceroute_finish\n return\n end\n sleep(0.1)\n end\n\tSTDOUT.puts(\"TIMEOUT ON HOPCOUNT \" + $hop_counter)\nend",
"def op\n sequence[ip]\n end",
"def test_add_edge_with_cycles\n @graph.add_edge('a', 'b');\n @graph.add_edge('b', 'c');\n @graph.add_edge('c', 'a');\n\n # 0 and 2 are indexes of vertex a and vertex c respectively\n assert(@graph.vertices[0].neighbours[2] == true && @graph.vertices[2].neighbours[0] == true)\n end",
"def cost_to_visit(pos, prev_pos, gem)\n cost = (pos[0] - gem[0]).abs + (pos[1] - gem[1]).abs\n cost += 2 if opposite_direction(pos, prev_pos, gem)\n cost\nend",
"def computeSP\n @graph.nodes.each do |node|\n @dist_to[node]=Float::INFINITY\n end\n @dist_to[@source] = 0\n \n #node and it's distance to source (source -> source = 0)\n @queue.insert(@source, 0)\n \n #while elements exist in the queue\n while @queue.any?\n #check the lowest distance (closest)\n close = @queue.remove_min\n #check each adjacent edge\n close.adjacent_edges.each do |adjacent|\n relax(adjacent)\n end\n end\n end",
"def execute\n @last_speed = @fan.speed\n @fan.high\n end",
"def runOperation(msg, client)\n case msg.getConfig(\"type\")\n when 0; edgebReflex(msg.getMessage(), client)\n when 1; fillBack(msg)\n when 2; edgeuUpdate(msg.getMessage())\n when 3; pingCallBack(msg)\n when 4; tracerouteCallBack(msg)\n when 5; sendMsgCallBack(msg, client)\n else STDERR.puts \"ERROR: INVALID MESSAGE \\\"#{msg}\\\"\"\n end\nend",
"def attract\n @edges.each do |edge|\n delta_x = edge.end.position.x - edge.beginning.position.x\n delta_y = edge.end.position.y - edge.beginning.position.y\n\n norm = normal(delta_x, delta_y)\n\n if 0 < norm && 1.5 * @optimal_distance < norm\n attraction = attractive_force(norm)\n if edge.end.disposition.nil? # wtf?\n edge.end.disposition = Coordinates.new(0, 0)\n else\n edge.end.disposition.x -= (delta_x * norm) / attraction\n edge.end.disposition.y -= (delta_y * norm) / attraction\n end\n edge.beginning.disposition.x += (delta_x * norm) / attraction\n edge.beginning.disposition.y += (delta_y * norm) / attraction\n end\n end\n end",
"def execute_swap graph, swap\n mark {a,b}\n swap a,b\n compute_d {a,b}\n graph.t += swap.gain\n return graph\nend",
"def add_result result\n source = result.source\n destination = result.destination\n\n @drb_results_received += 1\n @drb_exceptions_raised += 1 unless result.status\n\n sent_timestamp = @last_peer_send[destination].delete source\n message, argc, allocations = @last_sent_message[destination].delete source\n\n return unless sent_timestamp\n\n latency = result.timestamp - sent_timestamp\n\n @peer_latencies[destination][source].add latency\n @message_latencies[message][argc].add latency\n @message_allocations[message][argc].add allocations + result.allocations\n end",
"def push_edge(edge)\n if @leader.nil?\n @leader = edge.node1.leader\n edge.node2.leader = @leader\n else\n edge.node1.leader = @leader\n edge.node2.leader = @leader\n end\n \n adj_edge1_index = $vertices[edge.node1.node].first # we could select here first edge since \n adj_edge2_index = $vertices[edge.node2.node].first # they all are adjacent\n\n if adj_edge2_index && adj_edge1_index\n puts \"adj_edge1_index - #{adj_edge1_index}, adj_edge2_index - #{adj_edge2_index}\"\n end\n\n adj_edge1 = $edges[adj_edge1_index]\n adj_edge2 = $edges[adj_edge2_index]\n\n # 3 branches should be considered\n # 1st - edge is merged to only scc with adj edge1 o--o--o o----o \n # 2nd - edge is merged to only scc with adj edge2 o--o o--o----o\n # 3rd - edge is merged to scc1 or scc2 and these sccs are merges as well o--o---o--o\n\n if adj_edge1 && adj_edge2\n if adj_edge1.scc && adj_edge2.scc # merging 2 SCCs\n puts \"merging sccs\"\n if adj_edge1.scc.count > adj_edge2.scc.count\n @vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n # change leaders of SCC of adjacent edge 2\n adj_edge2.scc.vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n adj_edge2.scc.edges.each{|e| e.scc = adj_edge1.scc}\n @mst.delete_scc(adj_edge2.scc) # remove SCC from the list\n else\n @vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n # change leaders of SCC of adjacent edge 1\n adj_edge1.scc.vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n adj_edge1.scc.edges.each{|e| e.scc = adj_edge2.scc}\n @mst.delete_scc(adj_edge1.scc) # remove SCC from the list\n end\n elsif adj_edge1.scc || adj_edge2.scc\n scc = adj_edge1.scc || adj_edge2.scc # only one should be available\n @vertices.each{ |v| v.node.leader = scc.leader }\n puts 'adding edge ' + edge.inspect + ' to scc ' + scc.inspect\n end\n else\n @vertices << edge.node1\n @vertices << edge.node2\n @edges << edge\n end\n\n edge.scc = self # save link to the SCC in the edge itself\n end",
"def update!(**args)\n @bot_overhead_ms = args[:bot_overhead_ms] if args.key?(:bot_overhead_ms)\n @client_controlflow_stats = args[:client_controlflow_stats] if args.key?(:client_controlflow_stats)\n @connect_time_ms = args[:connect_time_ms] if args.key?(:connect_time_ms)\n @controlflow_stats = args[:controlflow_stats] if args.key?(:controlflow_stats)\n @down_load_time = args[:down_load_time] if args.key?(:down_load_time)\n @edge_egress_overhead_ms = args[:edge_egress_overhead_ms] if args.key?(:edge_egress_overhead_ms)\n @ssl_connect_time_ms = args[:ssl_connect_time_ms] if args.key?(:ssl_connect_time_ms)\n @server_response_time_ms = args[:server_response_time_ms] if args.key?(:server_response_time_ms)\n @transfer_time_ms = args[:transfer_time_ms] if args.key?(:transfer_time_ms)\n end",
"def send_cmd(cmd)\n # What time is it ?\n # update_access\n\n # Write the command plus a newline to the input\n @pipe.write_input(cmd + \"\\n\")\n end",
"def cost\r\n return @extra_cost + @basic_shifted.cost\r\n end",
"def update!(**args)\n @conv_id = args[:conv_id] if args.key?(:conv_id)\n @nodes = args[:nodes] if args.key?(:nodes)\n end",
"def calculate_hcost(p)\n\t\tdistance = (@end_pos[0] - p[0]).abs + (@end_pos[1] - p[1]).abs\n\t\tdistance * COST_ORT\n\tend",
"def test_add_destination\n assert_equal(@vertex.edges.length, 0)\n @vertex.add_destination(Edge.new('', 4000))\n @vertex.add_destination(Edge.new('', 4000))\n @vertex.add_destination(Edge.new('', 4000))\n assert_equal(@vertex.edges.length, 3)\n end",
"def fillBack(msg)\n ttl = msg.getConfig(\"ttl\")\n sn = msg.getConfig(\"seq\")\n if ttl == 0\n return\n else\n message = msg.getMessage()\n message_array = message.split(\"\\t\")\n host = message_array[0]\n if (host != $hostname and ($networks[host] == nil or $networks[host][\"sn\"] != sn))\n host_dist_tbl = Hash.new()\n for i in 1..(message_array.length - 1)\n neighbor_dist_pair = message_array[i].split(\",\")\n host_dist_tbl[neighbor_dist_pair[0]] = neighbor_dist_pair[1].to_i\n end\n $networks[host] = {\"sn\" => sn, \"neighbors\" => host_dist_tbl}\n msg.setConfig(\"ttl\", ttl - 1)\n $clients.each do |dst, client|\n sendMessage(client, msg)\n end\n if checkNode()\n runDijkstra()\n end\n end\n end\nend",
"def cost\n unless @cost\n @cost = 0\n @nodes_v.each do |v|\n @cost += @nodes_s.map { |s| v.distance_to(s) }.min\n end\n end\n\n @cost\n end",
"def update\n @time += -1\n if @time == -1\n done = @target\n @target = \"\"\n return done\n end\n return nil\n end",
"def transfer; end",
"def transfer; end",
"def curatorWaypointCost _args\n \"curatorWaypointCost _args;\" \n end",
"def latency\n case @op\n when :call, :trace, :cjmp, :root_nop\n raise \"Rescheduling #{@op} is illegal !\"\n when :nop\n 1\n when :mov, :mov_m, :setx, :sety, :setz, :setxy, :setxz, :setyz, :setx0, :setxy0, :setxz0\n 2\n when :add\n 3\n when :frac, :frac\n 3\n when :mul, :dp3, :mad\n 5\n when :mov_rsq, :mov_rcp, :dp3_rsq\n 6\n # We can safely consider load/texload the slowest instruction\n when :load, :texload\n 20\n else\n raise \"Unknown operation #{@op}\"\n end\n end",
"def plan_trip(origin_line,origin_stop,destination_line,destination_stop)\n if (origin_line === destination_line)\n final_line_stops = get_users_stops_by_line(origin_line,origin_stop,destination_stop)\n puts(\"#{$travel_instruction} #{origin_line} line: #{final_line_stops}\")\n puts(\"#{final_line_stops.length} stops in total.\")\n else\n origin_line_stops = get_users_stops_by_line(origin_line,origin_stop,$intersection_point)\n destination_line_stops = get_users_stops_by_line(destination_line,$intersection_point,destination_stop)\n puts(\"#{$travel_instruction} #{origin_line} line: #{origin_line_stops}.\")\n puts(\"Change at #{$intersection_point}.\")\n puts(\"#{$travel_change_over} #{destination_line_stops}.\")\n puts(\"#{origin_line_stops.concat(destination_line_stops).length} stops in total\")\n end\nend",
"def update\n @edge = Edge.find_by_src_id_and_dest_id(params[:edge][:src_id] , params[:edge][:dest_id])\n\n if @edge.update(edge_params)\n flash[:notice] = t('edge_updated_success')\n\t\t\t\tredirect_to :controller => \"nodes\" , :action => \"listByCourse\" , :course_id => @edge.src.course_id\t\t\n else\n render :action => \"edit\" \n end\n end",
"def onrecv(id, msg)\n\tscore = W1*msg[3]-W2*msg[2]\n\te = $rt[id, msg[0]]\n\treturn if e != nil && score <= e[4]\n\t$rt[id, msg[0]] = msg + [score]\n\tNODES.times do |i|\n\t\tif $matadj[id, i] > 0\n\t\t\tonrecv(i, [msg[0], id, msg[2] + 1, min($bandwidth[id], msg[3])])\n\t\tend\n\tend\nend",
"def write(cmd)\n\t \t @log.debug \"Tx: \"+cmd\n\t\t @sp.write cmd\n\t\t sleep 0.25 \n\t end",
"def update_target_cost\n cost = BigDecimal(0.00, 10)\n self.activities.each do |activity|\n cost += activity.targetCost\n end\n self.target_cost = cost\n end",
"def update!(**args)\n @bounding_marker = args[:bounding_marker] if args.key?(:bounding_marker)\n @connection_token = args[:connection_token] if args.key?(:connection_token)\n @curve = args[:curve] if args.key?(:curve)\n @flow = args[:flow] if args.key?(:flow)\n @lane_number = args[:lane_number] if args.key?(:lane_number)\n @primary_connection = args[:primary_connection] if args.key?(:primary_connection)\n @segment = args[:segment] if args.key?(:segment)\n @yield_to_other_connections = args[:yield_to_other_connections] if args.key?(:yield_to_other_connections)\n end",
"def update!(**args)\n @advisory_maximum_speed = args[:advisory_maximum_speed] if args.key?(:advisory_maximum_speed)\n @altitude = args[:altitude] if args.key?(:altitude)\n @avg_speed_kph = args[:avg_speed_kph] if args.key?(:avg_speed_kph)\n @avg_speed_kph_metadata = args[:avg_speed_kph_metadata] if args.key?(:avg_speed_kph_metadata)\n @barrier = args[:barrier] if args.key?(:barrier)\n @barrier_metadata = args[:barrier_metadata] if args.key?(:barrier_metadata)\n @bicycle_facility = args[:bicycle_facility] if args.key?(:bicycle_facility)\n @bicycle_safety = args[:bicycle_safety] if args.key?(:bicycle_safety)\n @condition = args[:condition] if args.key?(:condition)\n @condition_metadata = args[:condition_metadata] if args.key?(:condition_metadata)\n @construction_begin_date = args[:construction_begin_date] if args.key?(:construction_begin_date)\n @construction_end_date = args[:construction_end_date] if args.key?(:construction_end_date)\n @construction_status = args[:construction_status] if args.key?(:construction_status)\n @construction_status_metadata = args[:construction_status_metadata] if args.key?(:construction_status_metadata)\n @covered = args[:covered] if args.key?(:covered)\n @distance_to_edge = args[:distance_to_edge] if args.key?(:distance_to_edge)\n @distance_to_edge_metadata = args[:distance_to_edge_metadata] if args.key?(:distance_to_edge_metadata)\n @edge_follows_segment_begin_fraction = args[:edge_follows_segment_begin_fraction] if args.key?(:edge_follows_segment_begin_fraction)\n @edge_follows_segment_end_fraction = args[:edge_follows_segment_end_fraction] if args.key?(:edge_follows_segment_end_fraction)\n @elevation = args[:elevation] if args.key?(:elevation)\n @elevation_metadata = args[:elevation_metadata] if args.key?(:elevation_metadata)\n @endpoint = args[:endpoint] if args.key?(:endpoint)\n @endpoint_metadata = args[:endpoint_metadata] if args.key?(:endpoint_metadata)\n @grade_level = args[:grade_level] if args.key?(:grade_level)\n @internal = args[:internal] if args.key?(:internal)\n @interpolation_offset_meters = args[:interpolation_offset_meters] if args.key?(:interpolation_offset_meters)\n @intersection = args[:intersection] if args.key?(:intersection)\n @is_max_permitted_speed_derived = args[:is_max_permitted_speed_derived] if args.key?(:is_max_permitted_speed_derived)\n @lane = args[:lane] if args.key?(:lane)\n @legal_maximum_speed = args[:legal_maximum_speed] if args.key?(:legal_maximum_speed)\n @legal_minimum_speed = args[:legal_minimum_speed] if args.key?(:legal_minimum_speed)\n @max_permitted_speed_kph = args[:max_permitted_speed_kph] if args.key?(:max_permitted_speed_kph)\n @max_permitted_speed_kph_metadata = args[:max_permitted_speed_kph_metadata] if args.key?(:max_permitted_speed_kph_metadata)\n @on_right = args[:on_right] if args.key?(:on_right)\n @pedestrian_crossing = args[:pedestrian_crossing] if args.key?(:pedestrian_crossing)\n @pedestrian_facility = args[:pedestrian_facility] if args.key?(:pedestrian_facility)\n @pedestrian_grade = args[:pedestrian_grade] if args.key?(:pedestrian_grade)\n @priority = args[:priority] if args.key?(:priority)\n @priority_metadata = args[:priority_metadata] if args.key?(:priority_metadata)\n @restriction = args[:restriction] if args.key?(:restriction)\n @road_monitor = args[:road_monitor] if args.key?(:road_monitor)\n @road_sign = args[:road_sign] if args.key?(:road_sign)\n @route = args[:route] if args.key?(:route)\n @route_association = args[:route_association] if args.key?(:route_association)\n @separated_roadways = args[:separated_roadways] if args.key?(:separated_roadways)\n @sibling = args[:sibling] if args.key?(:sibling)\n @slope = args[:slope] if args.key?(:slope)\n @surface = args[:surface] if args.key?(:surface)\n @surface_metadata = args[:surface_metadata] if args.key?(:surface_metadata)\n @sweep = args[:sweep] if args.key?(:sweep)\n @toll_road = args[:toll_road] if args.key?(:toll_road)\n @usage = args[:usage] if args.key?(:usage)\n @visible_landmark = args[:visible_landmark] if args.key?(:visible_landmark)\n end",
"def oper(n, p)\n @socket << \"OPER #{n} #{p}\"\n end",
"def move_node!(tg,tga,i)\n #first just add node i in\n tga[0].each_index do |ii|\n if (i == tga[0][ii][0])\n tg[0].push(tga[0][ii])\n tga[0][ii] = nil\n break\n end\n end\n #then add the edges, only add edges for which both nodes exist in tg \n tga[1].each_index do |ii|\n if tg[0].index{|item| item[0] == tga[1][ii][0]} && tg[0].index{|item| item[0] == tga[1][ii][1]}\n tg[1].push(tga[1][ii])\n tga[1][ii] = nil\n end\n end\n tga[0].compact!\n tga[1].compact!\nend",
"def changed_net_cost\n unless added.nil?\n return added.substract_cost_from(removed)\n else\n return removed.total_cost unless removed.nil?\n end\n end",
"def relax(edge)\n #If the distance currently is lower than the added distance,\n #Don't increase it.\n return if @dist_to[edge.dest] <= @dist_to[edge.source] + edge.weight\n \n #Update the distance and add it back to the queue\n @dist_to[edge.dest] = @dist_to[edge.source] + edge.weight\n @path[edge.dest] = edge.source\n @queue.insert(edge.dest, @dist_to[edge.dest])\n end",
"def update!(**args)\n @abort_cause = args[:abort_cause] if args.key?(:abort_cause)\n @destination_egress_location = args[:destination_egress_location] if args.key?(:destination_egress_location)\n @endpoint_info = args[:endpoint_info] if args.key?(:endpoint_info)\n @error = args[:error] if args.key?(:error)\n @probing_latency = args[:probing_latency] if args.key?(:probing_latency)\n @result = args[:result] if args.key?(:result)\n @sent_probe_count = args[:sent_probe_count] if args.key?(:sent_probe_count)\n @successful_probe_count = args[:successful_probe_count] if args.key?(:successful_probe_count)\n @verify_time = args[:verify_time] if args.key?(:verify_time)\n end",
"def execute\n @last_speed = @fan.speed\n @fan.medium\n end",
"def get_path(double_array, path_cost, path_time)\n double_array.each do |path|\n correct_path = []\n cost = 0\n time = 0\n count = 0\n until count == path.size - 1\n correct_edge = @edge_array.find { |i| \n i.source == path[count] && i.destination == path[count+1] \n }\n cost += correct_edge.cost\n time += correct_edge.time\n count += 1\n end\n if cost == path_cost && time == path_time\n return path\n end\n end\n end",
"def add_edge(edge)\n # pp @access_paths\n # pp edge\n added = false\n return added if @edges.include?(edge)\n visited_path = @access_paths.each_with_index.select{|p,idx| !(p & edge).empty? }\n if visited_path.count == 2\n # if the two vertexes are visited in 2 paths\n # We'll combine the 2 paths\n new_path =[]\n to_del_idx =[]\n visited_path.each do |p|\n idx = p[1]\n v_path = p[0]\n new_path = new_path + v_path\n to_del_idx << idx\n end\n @access_paths.delete_if.with_index{|p,idx| to_del_idx.include?(idx)}\n @access_paths << new_path\n @edges << edge unless @edges.include?(edge)\n added = true\n elsif visited_path.count == 1\n v_path = visited_path[0][0]\n # binding.pry\n if (v_path & edge).count() == 2\n # binding.pry\n # add edge only when it does not create cycle\n puts \"Refuse to add edge #{edge.to_s} as it create cycle\"\n else\n # v_path = visited_path[0][1]\n vertext = edge - v_path\n v_path = v_path + vertext\n idx = visited_path[0][1]\n @access_paths.delete_at(idx)\n @access_paths << v_path\n @edges << edge unless @edges.include?(edge)\n added = true\n end\n elsif visited_path.count == 0\n @access_paths << edge\n @edges << edge unless @edges.include?(edge)\n added = true\n end\n # puts \"added is #{added}\"\n\n return added\n\tend",
"def update_mate(_mate, _edge, _val)\n m = _mate\n\n # add no edge\n return m if _val == 0\n\n # ad an edge\n a = _edge[0]\n b = _edge[1]\n\n if m.mate[a] == nil && m.mate[b] == nil # a, b are new terminal\n m.mate[a] = b\n m.mate[b] = a\n elsif m.mate[a] == nil # a is a new terminal\n t = m.mate[b]\n m.mate[a] = t\n m.mate[t] = a if m.mate[t] != nil\n m.mate[b] = 0\n elsif m.mate[b] == nil # b is a new terminal\n t = m.mate[a]\n m.mate[b] = t\n m.mate[t] = b if m.mate[t] != nil\n m.mate[a] = 0\n else # a, b, are not a new terminal\n t = m.mate[a]\n s = m.mate[b]\n m.mate[a] = 0\n m.mate[b] = 0\n m.mate[s] = t if m.mate[s] != nil\n m.mate[t] = s if m.mate[t] != nil\n end\n\n return m\n end",
"def server_timing=(_arg0); end",
"def initialize(source_instance,transition) \n @number=0 \n @nodecost=0\n @passby=false\n @instance=source_instance\n @transition=transition\n @neighbours=[]\n \n @name = \"NODE \" +source_instance + \" - \" + transition.to_s \n \n end",
"def dag_longpath(source, sink, weight_edge_graph, graph)\n <<-DOC\n The backtracking method can be generalized to construct a longest path in any DAG. Whenever we compute S(b) as\n S(b) = max (all predecessors a of node b) {S(a) + weight_of_edge_from_a_to_b }\n we simply need to store a predecessor of b that was used in the computation of sb so that we can backtrack later on. \n You are now ready to use backtracking to find the longest path in an arbitrary DAG.\n DOC\n topo_graph = Marshal.load(Marshal.dump(graph))\n topo_nodes = topological_ordering(topo_graph)\n # puts topo_nodes.join(\" \")\n\n puts graph\n keys = graph.keys\n values = graph.values.flatten.uniq\n # puts keys.join(\" \")\n # puts values.join(\" \")\n nodes_with_indegree_zero = keys - values\n puts nodes_with_indegree_zero.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n nodes_with_indegree_zero.each do |node|\n unless node == source\n topo_nodes.delete(node) \n weight_edge_graph.delete_if {|entry| /^#{node}->/.match(entry)}\n end\n end\n\n # nodes_to_consider = [source]\n # next_node = source\n # index = 1\n # loop do\n # break if next_node == sink\n # if graph[next_node]\n # graph[next_node].each do |node|\n # # puts node\n # nodes_to_consider << node unless nodes_to_consider.include?(node)\n # end\n # end\n # next_node = nodes_to_consider[index]\n # index += 1\n # end\n # puts \"nodes_to_consider: \" + nodes_to_consider.join(\" \")\n # topo_nodes.keep_if {|node| nodes_to_consider.include?(node)}\n puts \"topo nodes: \" + topo_nodes.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n incoming_nodes = {}\n incoming_nodes[topo_nodes[0]] = [{\"pred_node\" => nil, \"weight\" => 0}]\n\n\n best_pred = {}\n topo_nodes.each do |node|\n # incoming_nodes[node] = [{\"pred_node\" => nil, \"weight\" => 0}]\n best_pred[node] = {\"pred_node\" => nil, \"weight\" => 0}\n end\n\n # puts weight_edge_graph.join(\" \")\n (1..(topo_nodes.length-1)).each do |i|\n node = topo_nodes[i]\n puts \"Node: \" + node\n all_weights = []\n weight_edge_graph.each do |entry| \n # puts \"Entry: \" + entry\n # puts best_pred\n if /(\\d+)->#{node}:(\\d+)/.match(entry) \n incoming_nodes[node] = [] unless incoming_nodes[node]\n pred_node_matched = /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n pred_node_weight = /(\\d+)->#{node}:(\\d+)/.match(entry)[2].to_i\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[2]\n incoming_nodes[node] << {\"pred_node\" => pred_node_matched, \"weight\" => pred_node_weight}\n all_weights << (pred_node_weight + best_pred[pred_node_matched][\"weight\"])\n end\n end\n # puts all_weights.join(\" \")\n if incoming_nodes[node] \n # puts incoming_nodes[node]\n incoming_nodes[node].each do |pred_node_entry|\n # puts all_weights.join(\" \")\n if ((best_pred[pred_node_entry[\"pred_node\"]][\"weight\"] + pred_node_entry[\"weight\"]) == all_weights.max)\n best_pred[node][\"weight\"] = all_weights.max\n best_pred[node][\"pred_node\"] = pred_node_entry[\"pred_node\"]\n end\n end\n end\n end\n # puts incoming_nodes\n # puts best_pred\n length = best_pred[sink][\"weight\"]\n path = [sink]\n node = sink\n loop do\n puts node\n break if node == source\n node = best_pred[node][\"pred_node\"]\n path << node\n end\n return length, path.reverse\n end",
"def build_status_update(curr_lsn, send_time)\n return nil if curr_lsn.nil?\n\n message = ['r']\n # received/flushed/applied\n 3.times { message << curr_lsn }\n # send_time\n message << format_time(send_time)\n # require reply\n message << 0\n message = message.pack('aQ>4C')\n end",
"def update!(**args)\n @relative_cost = args[:relative_cost] if args.key?(:relative_cost)\n @type = args[:type] if args.key?(:type)\n end",
"def cost\n\t\treturn @extra_cost + @real_shake.cost\n\tend",
"def test_shortest_flight\n @vertex.add_destination(Edge.new('', 3000))\n @vertex.add_destination(Edge.new('', 4000))\n @vertex.add_destination(Edge.new('', 1000))\n shortest_flight = @vertex.shortest_flight\n assert_equal(shortest_flight.distance, 1000)\n assert_instance_of(Edge, shortest_flight)\n end",
"def server_timing; end",
"def workload\n [@nodeid,@data.count]\n end",
"def addOtherEdge (node, dist)\n\t\t@edges.push([node, dist])\n\tend",
"def estimate_cost(sql, *args)\n explanation = ask \"EXPLAIN (FORMAT JSON) #{sql}\", *args\n explanation.first.dig \"Plan\", \"Total Cost\"\n end",
"def updateTime\n\n # Cleanup phase\n @timestamps << @activestamps.map {|s| s.to_f}\n\n t1, t2, t3, t4, cfs, cfd = @activestamps\n @log.debug \"t1: #{t1.to_f}, \"\\\n \"t2: #{t2.to_f}, \"\\\n \"t3: #{t3.to_f}, \"\\\n \"t4: #{t4.to_f}, \"\\\n \"cfs: #{cfs.to_f}, \"\\\n \"cfd: #{t4.to_f}\"\n\n # Calculate link delay and average link delay\n delay = ((t2 - t1) + (t4 - t3) - cfs - cfd) / BigDecimal.new(2)\n @delay << (delay.to_f > 0 ? delay : delay * -1)\n delay_avg = @delay[-1]\n if @delay_avg[-1]\n one = BigDecimal.new(1)\n delay_avg = ALPHA * @delay_avg[-1] + (one - ALPHA) * @delay[-1]\n end\n @delay_avg << delay_avg\n\n # Calculate phase error and average phase_error\n @phase_error << ((t2 - t1) - (t4 - t3) - cfs + cfd) / BigDecimal.new(2)\n\n # Calculate average phase error if multiple data points exists\n avg = @phase_error[-1]\n if @phase_err_avg[-1]\n one = BigDecimal.new(1)\n avg = ALPHA * @phase_err_avg[-1] + (one - ALPHA) * @phase_error[-1]\n end\n @phase_err_avg << avg\n\n # Calculate frequency error\n distance = -2\n if @timestamps[distance]\n ot1 = @timestamps[distance][0]\n ot2 = @timestamps[distance][1]\n ode = @delay_avg[distance].to_f\n de = @delay_avg.last.to_f\n ocfs = @timestamps[distance][4].to_f\n error = (t1.to_f - ot1)/((t2.to_f + de + cfs.to_f)-(ot2 + ode + ocfs))\n # Do some hard filtering of data\n if error < 2 && error > 0.5\n @freq_error << error\n else\n puts \"ERROR ERROR ERROR ERROR \" + error.to_s # Why?\n @freq_error << @freq_error[-1] || 1\n end\n end\n\n # Calculate average frequency error if multiple data points exists\n if @freq_error[-1] && @flipflop - 1 < @flipflopeach\n @freq_err_avg << @freq_err_avg.last\n elsif @freq_error[-1]\n avg = @freq_error[-1]\n if @freq_err_avg[-1]\n one = BigDecimal.new(1)\n avg = ALPHA_F * @freq_err_avg[-1] + (one - ALPHA_F) * @freq_error[-1]\n end\n @freq_err_avg << avg\n end\n\n # TODO: Update system\n @log.info \"Delay: #{@delay.last.to_f} \\t\" \\\n \"Delay_avg: #{@delay_avg.last.to_f} \\t\" \\\n \"phase_err: #{@phase_error.last.to_f} \\t\"\\\n \"phase_err_avg: #{@phase_err_avg.last.to_f}, \\t\"\\\n \"freq_err: #{@freq_error.last.to_f} \\t\"\\\n \"freq_err_avg: #{@freq_err_avg.last.to_f}\"\n\n # Adjust phase\n adjOffset(@phase_err_avg.last.to_f) if @flipflop < @flipflopeach\n\n # Adjust frequency when we have some point of measurement and when we can\n # actually make adjustments in the flipflop thing.\n if @freq_err_avg[-10] && @flipflop >= @flipflopeach\n adjFreq(@freq_err_avg.last.to_f)\n end\n\n # Final cleanup\n @activestamps.fill(nil,0,4)\n\n # Adjust flipflop\n @flipflop = (@flipflop + 1) % (2 * @flipflopeach)\n end",
"def last_op\n @connection && @connection.get_operation_result\n end",
"def up_speed(arg)\n @speed += arg\n end",
"def move(currX,currY,nextX,nextY,prev)\n if @mat[currY][currX] == \"0\"\n point = Point.new(nextX,nextY)\n if !(@traceSet.include?(point.to_S))\n point.setPrev(prev)\n @traceArray.push(point)\n @traceSet.add(point.to_S)\n if point.isEqual(@final)\n @tnode = point\n end\n end\n end\n end",
"def update!(**args)\n @create_time = args[:create_time] if args.key?(:create_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @error = args[:error] if args.key?(:error)\n @execution = args[:execution] if args.key?(:execution)\n @executor_detail = args[:executor_detail] if args.key?(:executor_detail)\n @inputs = args[:inputs] if args.key?(:inputs)\n @outputs = args[:outputs] if args.key?(:outputs)\n @parent_task_id = args[:parent_task_id] if args.key?(:parent_task_id)\n @pipeline_task_status = args[:pipeline_task_status] if args.key?(:pipeline_task_status)\n @start_time = args[:start_time] if args.key?(:start_time)\n @state = args[:state] if args.key?(:state)\n @task_id = args[:task_id] if args.key?(:task_id)\n @task_name = args[:task_name] if args.key?(:task_name)\n end",
"def update!(**args)\n @app_id = args[:app_id] if args.key?(:app_id)\n @module_id = args[:module_id] if args.key?(:module_id)\n @version_id = args[:version_id] if args.key?(:version_id)\n @request_id = args[:request_id] if args.key?(:request_id)\n @ip = args[:ip] if args.key?(:ip)\n @start_time = args[:start_time] if args.key?(:start_time)\n @end_time = args[:end_time] if args.key?(:end_time)\n @latency = args[:latency] if args.key?(:latency)\n @mega_cycles = args[:mega_cycles] if args.key?(:mega_cycles)\n @method_prop = args[:method_prop] if args.key?(:method_prop)\n @resource = args[:resource] if args.key?(:resource)\n @http_version = args[:http_version] if args.key?(:http_version)\n @status = args[:status] if args.key?(:status)\n @response_size = args[:response_size] if args.key?(:response_size)\n @referrer = args[:referrer] if args.key?(:referrer)\n @user_agent = args[:user_agent] if args.key?(:user_agent)\n @nickname = args[:nickname] if args.key?(:nickname)\n @url_map_entry = args[:url_map_entry] if args.key?(:url_map_entry)\n @host = args[:host] if args.key?(:host)\n @cost = args[:cost] if args.key?(:cost)\n @task_queue_name = args[:task_queue_name] if args.key?(:task_queue_name)\n @task_name = args[:task_name] if args.key?(:task_name)\n @was_loading_request = args[:was_loading_request] if args.key?(:was_loading_request)\n @pending_time = args[:pending_time] if args.key?(:pending_time)\n @instance_index = args[:instance_index] if args.key?(:instance_index)\n @finished = args[:finished] if args.key?(:finished)\n @instance_id = args[:instance_id] if args.key?(:instance_id)\n @line = args[:line] if args.key?(:line)\n @app_engine_release = args[:app_engine_release] if args.key?(:app_engine_release)\n @trace_id = args[:trace_id] if args.key?(:trace_id)\n @source_reference = args[:source_reference] if args.key?(:source_reference)\n end",
"def doge_control\r\n @next_queue_time = get_queue_time\r\n end",
"def test_node_change_log2\r\n Model.node_changes_to_log([:evidence])\r\n @mymodel = Model.new(1, \"rubylicious\") \r\n node_list = @mymodel.node_list \r\n\r\n node1 = node_list.add_node('autonum', 'node one', NODE);\r\n perfind2 = node_list.add_node('autonum', 'pi two', PERFIND); \r\n process3 = node_list.add_node('autonum', 'process three', PROCESS);\r\n process4 = node_list.add_node('autonum', 'process four', PROCESS); \r\n \r\n perfind2.evidence = 0.12\r\n process3.evidence = 0.34 \r\n process4.evidence = 0.56 \r\n \r\n i = 0\r\n while(ar = @mymodel.consume_next_node_change)\r\n assert_equal([0.12,0.12], ar[0].send(ar[1][0])) if ar[0] == perfind2\r\n assert_equal([0.34,0.34], ar[0].send(ar[1][0])) if ar[0] == process3 \r\n assert_equal([0.56,0.56], ar[0].send(ar[1][0])) if ar[0] == process4\r\n i += 1\r\n end\r\n \r\n assert_equal(3, i, 'Incorrect number of node changes were logged')\r\n \r\n end",
"def test_backward_node\n loss = DNN::Losses::MeanSquaredError.new\n y = Numo::SFloat[[0, 1]]\n t = Numo::SFloat[[2, 4]]\n loss.forward_node(y, t)\n grad = loss.backward_node(Numo::SFloat[1])\n assert_equal Numo::SFloat[[-2, -3]], grad.round(4)\n end",
"def cstime=(*) end",
"def dij(linkPackageMap, native)\nputs \"start dij\"\ndist = Hash.new();\nprevNode = Hash.new();\ntraversed = Array.new;\nallNodes = linkPackageMap.keys;\n#for i in 0..allNodes.length - 1\n#\tdist[allNodes[i]] = -1;\n#\tprevNode[allNodes[i]] = nil;\n#end\ndist[native] = 0;\nprevNode[native] = native;\n#q = PriorityQueue.new\n#q[native] = 0;\n\nq = Pqueue.new();\nq.push(native, 0);\n\n\nuntil q.isEmpty()\n\tu, distance = q.pop();\n\ttraversed.push(u);\n\t#puts u;\n\t#puts distance;\n\tuNeighborMap = linkPackageMap[u].map();\n\t#puts uNeighborMap.keys;\n\tuNeighbors = uNeighborMap.keys\n\tfor i in 0..uNeighbors.length - 1\n\t\t#puts uNeighbors[i]\n\t\tif !traversed.include?(uNeighbors[i]) then\n\t\t\tnewDistance = dist[u].to_i + uNeighborMap[uNeighbors[i]].to_i;\n\t\t\tif dist[uNeighbors[i]] == nil then\n\t\t\t\tdist[uNeighbors[i]] = newDistance\n\t\t\t\tprevNode[uNeighbors[i]] = u;\n\t\t\telse \n\t\t\t\tif newDistance < dist[uNeighbors[i]] then\n\t\t\t\tdist[uNeighbors[i]] = newDistance\n\t\t\t\tprevNode[uNeighbors[i]] = u;\n\t\t\t\tend\n\t\t\tend\n\t\t\tq.push(uNeighbors[i], dist[uNeighbors[i]].to_i);\n\t\t\t#q[uNeighbors[i]] = dist[uNeighbors[i]].to_i;\n\t\tend\n\t\t\t\n\tend\n\nend\n\n\n\nnodes = prevNode.keys;\n#puts nodes;\nnativeNeighbor = linkPackageMap[native].map();\n#nativeNeighbor.each{|key, value| puts \"key : #{key} value : #{value}\"}\nfor i in 0 .. nodes.length - 1\n\tif prevNode[nodes[i]] == native then\n\t\tprevNode[nodes[i]] = nodes[i];\n\telse\n\t\twhile(!nativeNeighbor.include?(prevNode[nodes[i]]) )\n\t\t\tprevNode[nodes[i]] = prevNode[prevNode[nodes[i]]];\n\t\tend\t\n\tend\nend\n\nreturn dist, prevNode;\nend",
"def add_edge(id1, id2)\n # YOUR WORK HERE\n end",
"def get_update\n line = @socket.gets.chop\n\n die \"connection lost\" if !line\n\n update = JSON.parse(line, :create_additions => true)\n\n case update.type.to_sym\n when :update_snakes\n update.msg = JSON.parse(update.msg, :create_additions => true)\n update_snakes update.msg\n when :update_colors \n @renderer.update_colors update.msg\n when :identity\n puts line\n #TODO it's me! do something!\n end\n end",
"def build_client_algorithm_packet; end",
"def sendop(*args)\n common_call(args) do |filtered|\n handle = task.do_operation_send(name, orocos_arguments_typenames, filtered)\n handle.instance_variable_set :@operation, self\n handle.instance_variable_set :@orocos_return_types, @orocos_return_typenames.dup\n handle.instance_variable_set :@return_values, new_result\n handle\n end\n end"
] |
[
"0.75870264",
"0.678527",
"0.6460501",
"0.61730546",
"0.6092415",
"0.58193505",
"0.57349604",
"0.55861866",
"0.55764824",
"0.5494816",
"0.537581",
"0.529418",
"0.529418",
"0.529418",
"0.5195012",
"0.51921046",
"0.5174208",
"0.5133308",
"0.5125066",
"0.5058883",
"0.5056944",
"0.50265163",
"0.50093997",
"0.49774623",
"0.4972271",
"0.49679583",
"0.493912",
"0.49354276",
"0.4905571",
"0.48990148",
"0.489772",
"0.4886315",
"0.48786768",
"0.48715138",
"0.4868499",
"0.4864295",
"0.4860639",
"0.4835525",
"0.4835147",
"0.48305613",
"0.48301274",
"0.4827784",
"0.48266494",
"0.4824414",
"0.48219106",
"0.48066592",
"0.4798698",
"0.47768193",
"0.4773146",
"0.47668952",
"0.47549704",
"0.47404766",
"0.47312856",
"0.47302547",
"0.47210366",
"0.47210366",
"0.4716707",
"0.4689673",
"0.4687302",
"0.46865028",
"0.46839392",
"0.46765056",
"0.46674898",
"0.46624",
"0.46559903",
"0.46341726",
"0.46228474",
"0.4620487",
"0.46190763",
"0.46113586",
"0.46109647",
"0.46085408",
"0.4600834",
"0.4598375",
"0.45928645",
"0.45873865",
"0.45844132",
"0.45811337",
"0.45797026",
"0.45775598",
"0.45774618",
"0.45749664",
"0.45627233",
"0.4560309",
"0.4543343",
"0.4540475",
"0.45381817",
"0.4532121",
"0.45294192",
"0.45187283",
"0.45186868",
"0.4518261",
"0.45171174",
"0.4514524",
"0.45126265",
"0.45111728",
"0.45105174",
"0.45073074",
"0.45064628",
"0.4491217"
] |
0.714894
|
1
|
do main loop here....
|
def main()
while(line = STDIN.gets())
line = line.strip()
arr = line.split(' ')
cmd = arr[0]
args = arr[1..-1]
case cmd
when "EDGEB"; edgeb_stdin(args)
when "EDGED"; edged(args)
when "EDGEU"; edgeu(args)
when "DUMPTABLE"; dumptable(args)
when "SHUTDOWN"; shutdown(args)
when "STATUS"; status()
when "SENDMSG"; sendmsg(arr)
when "PING"; ping(args)
when "TRACEROUTE"; traceroute(arr)
when "FTP"; ftp(arr)
when "CIRCUITB"; circuitb(args)
when "CIRCUITM"; circuitm(arr)
when "CIRCUITD"; circuitd(args)
else STDERR.puts "ERROR: INVALID COMMAND \"#{cmd}\""
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def loop; end",
"def loop\n end",
"def loop\n end",
"def loop\n end",
"def run_loop\n end",
"def post_loop; end",
"def loop_forever; end",
"def pre_loop; end",
"def postloop\n end",
"def preloop\n end",
"def parentloop; end",
"def main_loop\n @main_loop ||= lambda do\n # Smoother, but slower: GC.start if rand > 0.98\n next_step\n SUBSTEPS.times do\n move\n targeting\n handle_input\n remove_marked\n step_physics\n end\n end\n end",
"def kloop\n end",
"def run()\n while(true)\n cycle() ;\n sleep(2) ;\n end\n end",
"def thread; end",
"def thread; end",
"def thread; end",
"def running; end",
"def running; end",
"def run() end",
"def endless_loop?; end",
"def testloop\n \n end",
"def game_loop\n end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run\n while 1\n if step == 1 then break end\n end\n end",
"def start\n main_loop\n end",
"def game_loop\n end",
"def run\n end",
"def infinite_loop?; end",
"def run\n while 1\n sleep(0.2)\n #puts \"bezim \"+@pid.to_s\n end\n end",
"def run\n \n end",
"def run\n \n end",
"def main_loop\r\n Graphics.update # Update game screen\r\n Input.update # Update input information\r\n main_update # Update scene objects\r\n update # Update Processing\r\n end",
"def myloop\n while true\n yield\n end\nend",
"def run\n while @running\n step\n end\n end",
"def start\n loop do\n run\n end\n end",
"def sleepy_run; end",
"def run\n raise NotImplementedError, 'Generic loop has nothing to do'\n end",
"def run\n end",
"def main_process\n while @running\n Graphics.update\n update\n end\n end",
"def run\n end",
"def run\n end",
"def run\n end",
"def run\n end",
"def run\n end",
"def run\n end",
"def run\n end",
"def main_loop\n\t\t\tbegin\n\t\t\t\tloop {\n\t\t\t\t\titerate\n\t\t\t\t\tlog.debug \"Finished iteration; sleeping for #{sleep_time}s.\"\n\t\t\t\t\tsleep sleep_time\n\t\t\t\t}\n\t\t\trescue Exception => e\n\t\t\t\t# We want to avoid crashing if at all possible, so we catch\n\t\t\t\t# everything, log it, sleep (to avoid thrashing or flooding the\n\t\t\t\t# logs completely if the error persists), and go back to the\n\t\t\t\t# main loop.\n\t\t\t\tlog.error(\"#{self.class.inspect}'s main loop crashed \" \\\n\t\t\t\t\t\t \"with #{e.inspect} at #{e.backtrace[0]}!\")\n\t\t\t\tsleep(sleep_time * 10)\n\t\t\t\tretry\n\t\t\tend\n\t\tend",
"def my_loop\n while true\n yield\n end\nend",
"def main_loop\n %w[INT TERM].each { |sig| Signal.trap(sig) { save_state; exit(0) } }\n\n while true\n check_log_file unless File.size(@auth_log.file) == @auth_log.size\n sleep(@cfg['check_interval'])\n end\n end",
"def run\n start_game\n game_loop\n end_game\n end",
"def run()\n end",
"def run_main\n end",
"def start\n #method calls for Create and Print initial boardboard\n createBoard\n printBoard\n \n #loop 10 times \n #process board and print\n 10.times do\n processBoard\n printBoard\n end\n end",
"def go\n while(true)\n process_event(wait_for_event)\n end\n end",
"def run(_); end",
"def run(_); end",
"def main\n\t\tstart\n\t\twhile self == SceneManager.scene\n\t\t\tGraphics.update\n\t\t\tController.keyboard.update\n\t\t\tupdate\n\t\t\tController.wait_next_frame\n\t\tend\n\t\tterminate\n\tend",
"def runs; end",
"def wait; end",
"def wait; end",
"def wait; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def process; end",
"def running?; end",
"def in_loop\n declare_alive\n project.load\n if loop_i == -1\n say '-----------------------------------'\n say 'MiGA:%s launched.' % project.name\n say '-----------------------------------'\n load_status\n @loop_i = 0\n end\n @loop_i += 1\n check_datasets\n check_project\n if shutdown_when_done? and jobs_running.size + jobs_to_run.size == 0\n say 'Nothing else to do, shutting down.'\n return false\n end\n flush!\n if loop_i==4\n say 'Housekeeping for sanity'\n @loop_i = 0\n purge!\n end\n report_status\n sleep(latency)\n true\n end",
"def foreverize\n loop do\n run\n end\n end",
"def while(&block)\n\t\t\t\t\trepeat &block\n\t\t\t\tend",
"def run\n @running = true\n begin\n while running?\n self.ir = decode(ram.read(self.pc))\n self.pc += 1\n exec(ir[0], ir[1])\n end\n end \n end",
"def run_forever\n run\n sleep(10) while true\n end",
"def loop\n puts \"Diet Manager 3000!\"\n puts \"Created by Jesse Jurman\"\n check = 1\n while check != 0\n print \"> \"\n check = step\n end\n end",
"def main_loop()\n setup()\n finished = false\n while !finished\n print \":) \"\n line = gets.chomp\n if line == 'Q'\n finished = true\n else\n parse_command(line)\n end\n end\n exit\nend",
"def main_loop()\n setup()\n finished = false\n while !finished\n print \":) \"\n line = gets.chomp\n if line == 'Q'\n finished = true\n else\n parse_command(line)\n end\n end\n exit\nend",
"def run\n end",
"def run_game\n start_game\n new_board\n while true\n print_grid\n tour_joueur1\n tour_joueur2\n end\nend",
"def thread()\n #This is a stub, used for indexing\n end",
"def load(n,m)\n n.times {\n puts \"*\"\n sleep(m)\n}\n \nend",
"def run\n loop { run_once }\n end",
"def idle\n sleep(5) while running?\n end",
"def run\n loop do\n break unless app_loop\n end\n end",
"def run_input_thread; end",
"def start_run; end",
"def run\n\t stop = false\n\t\n\t while not stop do\n\t frame_time = \"%10.6f\" % ((Time.now).to_f + @send_buffer_delay.to_f)\n\t\tstop = send \"frame start #{frame_time}\"\n\n $items.each do |obj|\n next if obj.ship.dead?\n stop = send obj.output\n end\n\n\t $score.each do |s|\n\t if rand(100) < 1\n\t stop = send s[1].send_score(s[0], s[2], s[3])\n\t end\n\t end\n\n\t\tstop = send \"frame stop\"\n\t\tsleep 0.05\n\t end\n\tend",
"def main_end ; end",
"def run\n run_one_instruction while threads.length > 0\n end",
"def mainloop(screen, ballTracker)\n\t# draws the screen\n\tdisplayBoundaries(screen)\n\t# configures keyboard\n\tstartKbd\n\n\t# initial racquet position in the middle\n\tracquet=SCREEN_X/2.floor\n\t# displayes the ball and racquet\n displayDyn(screen,racquet)\n \n totalVisits = 0;\n \n\tloop do\n # updates the position of the ball\n u=update(racquet,screen,false, ballTracker, totalVisits)\n if u == nil\n # missed the racquet, game over\n displayEndgame\n break\n elsif !u\n # display needs to be updated\n displayDyn(screen,racquet)\n end\n ch = readChar\n if ch == 'q' || ch == \"\\003\" \n # character 'q' or Ctrl-C means 'quit the game'\n displayEndgame\n break\n elsif ch != nil\n if ch == LEFT \n racquet = racquetLeft(racquet)\n elsif ch == RIGHT\n racquet = racquetRight(racquet)\n end\n end\n # 100ms per cycle\n sleep(0.1)\t\n end\n ensure\n\t\t# ensures that when application stops, the keyboard is in a usable state\n\t\tendKbd\nend",
"def start\n \n\tend"
] |
[
"0.8564647",
"0.8516369",
"0.8516369",
"0.84616023",
"0.82521206",
"0.8024656",
"0.7735339",
"0.7631197",
"0.7602355",
"0.7532698",
"0.7404509",
"0.73160857",
"0.7300256",
"0.7291489",
"0.72511065",
"0.72511065",
"0.72511065",
"0.7250268",
"0.7250268",
"0.72476906",
"0.7246597",
"0.72391254",
"0.71711266",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.71498394",
"0.709139",
"0.7090613",
"0.70587236",
"0.70488924",
"0.69289917",
"0.69043946",
"0.6863424",
"0.6863424",
"0.6811438",
"0.68106365",
"0.6737151",
"0.6732404",
"0.6683759",
"0.66377294",
"0.66306984",
"0.66254455",
"0.66227156",
"0.66227156",
"0.66227156",
"0.66227156",
"0.66227156",
"0.66227156",
"0.66227156",
"0.66036695",
"0.6600849",
"0.65870196",
"0.65546286",
"0.65502125",
"0.6540317",
"0.65191483",
"0.6516962",
"0.65110195",
"0.65110195",
"0.6501214",
"0.6464676",
"0.6457405",
"0.6457405",
"0.6457405",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64207685",
"0.64086825",
"0.6407304",
"0.64061356",
"0.639873",
"0.6394614",
"0.6392455",
"0.6382951",
"0.638293",
"0.638293",
"0.63717884",
"0.63695854",
"0.6355937",
"0.6337204",
"0.6335141",
"0.6334927",
"0.6332377",
"0.6331752",
"0.6328911",
"0.6320516",
"0.63173294",
"0.6311834",
"0.62953967",
"0.629419"
] |
0.0
|
-1
|
cmd[0] Flood message sent from probably don't need but can be used for debugging cmd[1] name of srcNode cmd[2] name of destNode cmd[3] cost of edge cmd[4] time of Edge Shift or delete cmd[1],cmd[2], cmd[3], cmd[4] to get the next edge src,edge dest and edge time USE $rt to check if we need to change graph. will reduce the runtime These are strings so remember to change to integers to_i Use dijkstras for next hop in $rt
|
def updateTable(cmd)
# puts "TRYING TO UPDATE TABLE"
sentFrom = cmd.shift
curr_edge_time = nil
new_edge_time = nil
new_edge_cost = nil
node = $node_info.new
arr = nil
hops = nil
lis = nil
loop{
new_edge_time = cmd[3].to_i
new_edge_cost = cmd[2].to_i
$lock.synchronize{
curr_edge_time = $network.get_time(cmd[0],cmd[1])
}
if curr_edge_time == 0
#name of srcNode,name of destNode,cost of edge,time of Edge
$lock.synchronize{
$network.undir_connection(cmd[0], cmd[1], new_edge_time, new_edge_cost)
}
if ($rt.has_key?(cmd[0]) != true)
node.src = $hostname
node.dst = cmd[0]
node.cost = nil #do dijsktras
node.nexthop = nil #do dijsktras
$lock.synchronize{
$rt[cmd[0]] = node
}
end
if($rt.has_key?(cmd[1]) != true)
node.src = $hostname
node.dst = cmd[1]
node.cost = nil #do dijsktras
node.nexthop = nil #do dijsktras
$lock.synchronize{
$rt[cmd[1]] = node
}
end
elsif curr_edge_time < new_edge_time
$lock.synchronize{
$network.update_cost(cmd[0], cmd[1], new_edge_time, new_edge_cost)
}
end
cmd.shift(4)
break if cmd.length < 4
# puts "ABOUT TO RUN DIJKSTRAS"
$lock.synchronize{
arr = $network.dijkstra($hostname)
}
$full_path = arr[0]
#puts "THIS IS THE RETURN OF DIJKSTRAS #{arr}"
$lock.synchronize{
$rt.each_key {|key|
update = $node_info.new
# puts "Key IS #{key}"
hops = arr[0]
lis = arr[1]
prevs = hops[key]
update.src = $hostname
update.dst = key
update.cost = lis[key]
update.nexthop = prevs[1]
$rt[key] = update
# puts "ROUTING TABLE #{$rt}"
}
}
}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edgeu(cmd)\n $dist[cmd[0]] = cmd[1].to_i\n $neighbors[cmd[0]] = cmd[1].to_i\n client = $clients[cmd[0]]\n msg = Msg.new\n msg.setConfig(\"type\", 2)\n msg.setMessage($hostname + \" \" + cmd[1].to_i.to_s)\n sendMessage(client, msg)\n fillInNodes()\nend",
"def edgeu(cmd)\n time = nil\n $lock.synchronize{\n time = $clock.to_i\n $network.update_cost($hostname, cmd[0], cmd[1].to_i, time)\n\n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n } \n\n client = TCPSocket.open($local_ip, $nodesFile[cmd[0]][\"PORT\"])\n client.puts(\"EDGEU2 #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def edgeb_network(cmd)\n node = $node_info.new \n $lock.synchronize{\n \n node.src = $hostname\n node.dst = cmd[1]\n node.cost = 1\n node.nexthop = cmd[1]\n $rt[cmd[1]] = node\n if $local_ip == nil then $local_ip = cmd[2] end\n\n $network.undir_connection($hostname, cmd[1], cmd[3].to_i, 1) \n }\n #puts \"THIS IS THE ROUTING TABLE: #{$rt}\"\nend",
"def edgeuUpdate(msg)\n msg = msg.split(' ')\n dst = msg[0]\n cost = msg[1].to_i\n $dist[dst] = cost\n $neighbors[dst] = cost\nend",
"def edged(cmd)\n $lock.synchronize{ \n $network.remove_edge($hostname,cmd[0])\n\n if $rt.has_key? cmd[0]\n $rt.delete cmd[0] \n end\n\n }\nend",
"def edgeu_network(cmd)\n $lock.synchronize{\n $network.update_cost($hostname, cmd[0], cmd[1].to_i,cmd[2].to_i)\n \n if $rt.has_key? cmd[0]\n $rt[cmd[0]][:cost] = cmd[1].to_i\n end\n }\nend",
"def edgebReflex(msg, client)\n msg = msg.split(',')\n dstip = msg[0]\n srcip = msg[1]\n dst = msg[2]\n $ips[$hostname] = srcip\n $ips[dst] = dstip\n $dist[dst] = 1\n $neighbors[dst] = 1\n $next[dst] = dst\n $clients[dst] = client\n fillInNodes()\nend",
"def edgeb_stdin(cmd)\n $record_ip[$hostname] = cmd[0]\n $record_ip[cmd[2]] = cmd[1]\n node = $node_info.new \n time = nil\n $lock.synchronize{ \n node.src = $hostname\n node.dst = cmd[2]\n node.cost = 1\n node.nexthop = cmd[2]\n time = $clock.to_i\n $rt[cmd[2]] = node\n if $local_ip == nil then $local_ip = cmd[0] end\n\n $network.undir_connection($hostname, cmd[2], time, 1)\n }\n\n client = TCPSocket.open(cmd[1], $nodesFile[cmd[2]][\"PORT\"])\n client.puts(\"EDGEB2 #{cmd[2]} #{$hostname} #{cmd[1]} #{time}\") \n \nend",
"def tellNode(cmd, topo, domain)\n puts \"---------------------------------------------------\"\n d = (domain == nil) ? OConfig.domain : domain\n command = nil\n if (cmd == \"on\" || cmd == \"-on\" || cmd == \"--turn-on\")\n command = \"on\"\n elsif (cmd == \"offs\" || cmd == \"-offs\" || cmd == \"--turn-off-soft\")\n command = \"offSoft\"\n elsif (cmd == \"offh\" || cmd == \"-offh\" || cmd == \"--turn-off-hard\")\n command = \"offHard\"\n end\n if command == nil\n puts \"ERROR - Unknown command : '#{cmd}'\" \n puts \"Use 'help' to see usage information\" \n puts \"\"\n exit 1\n end\n puts \" Testbed : #{d} - Command: #{command}\"\n topo.eachNode { |n|\n url = \"#{OConfig[:tb_config][:default][:cmc_url]}/#{command}?x=#{n[0]}&y=#{n[1]}&domain=#{d}\"\n response = NodeHandler.service_call(url, \"Can't send command to CMC\")\n if (response.kind_of? Net::HTTPOK)\n puts \" Node n_#{n[0]}_#{n[1]} - Ok\"\n else\n puts \" Node n_#{n[0]}_#{n[1]} - Error (node state: 'Not Available')\"\n end\n }\n puts \"---------------------------------------------------\"\nend",
"def edged(cmd)\n $ips.delete(cmd[0])\n $dist[cmd[0]] = \"INF\"\n $neighbors.delete(cmd[0])\n $next[cmd[0]] = \"NA\"\n client = $clients[cmd[0]]\n client.close()\n $clients.delete(cmd[0])\nend",
"def dag_longpath(source, sink, weight_edge_graph, graph)\n <<-DOC\n The backtracking method can be generalized to construct a longest path in any DAG. Whenever we compute S(b) as\n S(b) = max (all predecessors a of node b) {S(a) + weight_of_edge_from_a_to_b }\n we simply need to store a predecessor of b that was used in the computation of sb so that we can backtrack later on. \n You are now ready to use backtracking to find the longest path in an arbitrary DAG.\n DOC\n topo_graph = Marshal.load(Marshal.dump(graph))\n topo_nodes = topological_ordering(topo_graph)\n # puts topo_nodes.join(\" \")\n\n puts graph\n keys = graph.keys\n values = graph.values.flatten.uniq\n # puts keys.join(\" \")\n # puts values.join(\" \")\n nodes_with_indegree_zero = keys - values\n puts nodes_with_indegree_zero.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n nodes_with_indegree_zero.each do |node|\n unless node == source\n topo_nodes.delete(node) \n weight_edge_graph.delete_if {|entry| /^#{node}->/.match(entry)}\n end\n end\n\n # nodes_to_consider = [source]\n # next_node = source\n # index = 1\n # loop do\n # break if next_node == sink\n # if graph[next_node]\n # graph[next_node].each do |node|\n # # puts node\n # nodes_to_consider << node unless nodes_to_consider.include?(node)\n # end\n # end\n # next_node = nodes_to_consider[index]\n # index += 1\n # end\n # puts \"nodes_to_consider: \" + nodes_to_consider.join(\" \")\n # topo_nodes.keep_if {|node| nodes_to_consider.include?(node)}\n puts \"topo nodes: \" + topo_nodes.join(\" \")\n\n puts weight_edge_graph.join(\" \")\n incoming_nodes = {}\n incoming_nodes[topo_nodes[0]] = [{\"pred_node\" => nil, \"weight\" => 0}]\n\n\n best_pred = {}\n topo_nodes.each do |node|\n # incoming_nodes[node] = [{\"pred_node\" => nil, \"weight\" => 0}]\n best_pred[node] = {\"pred_node\" => nil, \"weight\" => 0}\n end\n\n # puts weight_edge_graph.join(\" \")\n (1..(topo_nodes.length-1)).each do |i|\n node = topo_nodes[i]\n puts \"Node: \" + node\n all_weights = []\n weight_edge_graph.each do |entry| \n # puts \"Entry: \" + entry\n # puts best_pred\n if /(\\d+)->#{node}:(\\d+)/.match(entry) \n incoming_nodes[node] = [] unless incoming_nodes[node]\n pred_node_matched = /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n pred_node_weight = /(\\d+)->#{node}:(\\d+)/.match(entry)[2].to_i\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[1]\n # puts /(\\d+)->#{node}:(\\d+)/.match(entry)[2]\n incoming_nodes[node] << {\"pred_node\" => pred_node_matched, \"weight\" => pred_node_weight}\n all_weights << (pred_node_weight + best_pred[pred_node_matched][\"weight\"])\n end\n end\n # puts all_weights.join(\" \")\n if incoming_nodes[node] \n # puts incoming_nodes[node]\n incoming_nodes[node].each do |pred_node_entry|\n # puts all_weights.join(\" \")\n if ((best_pred[pred_node_entry[\"pred_node\"]][\"weight\"] + pred_node_entry[\"weight\"]) == all_weights.max)\n best_pred[node][\"weight\"] = all_weights.max\n best_pred[node][\"pred_node\"] = pred_node_entry[\"pred_node\"]\n end\n end\n end\n end\n # puts incoming_nodes\n # puts best_pred\n length = best_pred[sink][\"weight\"]\n path = [sink]\n node = sink\n loop do\n puts node\n break if node == source\n node = best_pred[node][\"pred_node\"]\n path << node\n end\n return length, path.reverse\n end",
"def nextHop( target_id )\n m = 0\n n = -1\n while @guid[m] == target_id[m] && m < @m_max\n m += 1\n end\n n = target_id[m]\n n = n.to_s\n n = n.hex\n # Once we have M and N we check the routing table at that location to see if we have an entry\n # This entry will be once digit closer than the current nodes GUID\n if @routing_table[[0,m,n]] != nil\n return InetAddr.new( @routing_table[[0,m,n]][:ip_address], @routing_table[[0,m,n]][:port] ), m, n\n # If not we search the entire routing table for the entry with the GUID closest to the target_id\n else\n shortestDistance = dist( target_id, @guid ) # distance between ourself and target\n # we will only send message on if there is a closer address\n nh = InetAddr.new()\n @routing_table.each do |key, array| # Access each element of routing table\n # IF it is less than out distance to target set it as shortest\n if dist( target_id, array[:node_id] ) < shortestDistance && dist( target_id, array[:node_id] ) != 0\n shortestDistance = dist( target_id, array[:node_id] )\n nh.ip = array[:ip_address]\n nh.port = array[:port]\n end\n end\n return nh, m, n\n # Function returns an InetAddr struct as well as M and N\n end\n end",
"def fillBack(msg)\n ttl = msg.getConfig(\"ttl\")\n sn = msg.getConfig(\"seq\")\n if ttl == 0\n return\n else\n message = msg.getMessage()\n message_array = message.split(\"\\t\")\n host = message_array[0]\n if (host != $hostname and ($networks[host] == nil or $networks[host][\"sn\"] != sn))\n host_dist_tbl = Hash.new()\n for i in 1..(message_array.length - 1)\n neighbor_dist_pair = message_array[i].split(\",\")\n host_dist_tbl[neighbor_dist_pair[0]] = neighbor_dist_pair[1].to_i\n end\n $networks[host] = {\"sn\" => sn, \"neighbors\" => host_dist_tbl}\n msg.setConfig(\"ttl\", ttl - 1)\n $clients.each do |dst, client|\n sendMessage(client, msg)\n end\n if checkNode()\n runDijkstra()\n end\n end\n end\nend",
"def packet_in datapath_id, message\n match = ExactMatch.from( message )\n action, log = lookup_rules( datapath_id, match )\n info \"action=#{ action }, datapath_id=#{ datapath_id.to_hex }, message={#{ match.to_s }}\" if log\n if action == :allow\n #set rules in the switch\n #please fill up the following blank ****** user input from here ******\n send_flow_mod_add( datapath_id,\n :match => match,\n :idle_timeout => 300,\n :hard_timeout => 300,\n :actions => ActionOutput.new( (match.in_port == 1)? 2 : 1 )\n )\n #set rules in the switch for reverse path\n #please fill up the following blank ****** user input from here ******\n # reverse flow has the same attributes, but with source/destination\n # swapped\n reverse_match = Match.new(\n :in_port => (match.in_port == 1)? 2 : 1,\n :dl_src => match.dl_dst, # swapping source and dest\n :dl_dst => match.dl_src, # MAC addresses\n :dl_type => match.dl_type,\n :dl_vlan => match.dl_vlan,\n :dl_vlan_pcp => match.dl_vlan_pcp,\n :nw_tos => match.nw_tos,\n :nw_proto => match.nw_proto,\n :nw_src => match.nw_dst, # swapping source and dest\n :nw_dst => match.nw_src, # IP addresses\n :tp_src => match.tp_dst, # swapping source and dest\n :tp_dst => match.tp_src # TCP ports\n )\n info \"reverse flow: {#{ reverse_match.to_s }}\"\n send_flow_mod_add( datapath_id,\n :match => reverse_match,\n :idle_timeout => 300,\n :hard_timeout => 300,\n :actions => ActionOutput.new( (reverse_match.in_port == 1)? 2 : 1 )\n )\n else \n #set drop rule in the switch\n #please fill up the following blank ****** user input from here ******\n send_flow_mod_add( datapath_id,\n :match => match,\n :idle_timeout => 300,\n :hard_timeout => 300\n )\n end\n end",
"def parse(msg)\n if(String(msg).empty?)\n return\n end\n \n #\n # If there is no timestam, given them \n #\n if(@timestamp.nil?)\n @timestamp=Time.now\n end\n \n #\n # Socket Event\n #\n if(msg.instance_of?(Fixnum))\n @command=msg\n @to=@selfNick\n @fromNick=@server\n @from=@fromNick\n\n case msg\n when Event::LINK_ESTABLISHING\n @cmndstr=\"LINK_ESTABLISHING\"\n when Event::LINK_ESTABLISHED\n @cmndstr=\"LINK_ESTABLISHED\"\n when Event::LINK_FAILED\n @cmndstr=\"LINK_FAILED\"\n when Event::LINK_CLOSING\n @cmndstr=\"LINK_CLOSING\"\n when Event::LINK_CLOSED\n @cmndstr=\"LINK_CLOSED\"\n end\n return\n end\n \n #\n # Some spetial messages parse\n #\n tmp=msg.split(\" \",2)\n case tmp[0]\n when \"KILL\"\n @cmndstr=\"KILL\"\n @command=Event::RECV_MESSAGE_KILL\n @args=[tmp[1]]\n when \"PING\"\n @cmndstr=\"PING\"\n @command=Event::RECV_MESSAGE_PING\n @args=[tmp[1]]\n when \"PONG\"\n @cmndstr=\"PONG\"\n @command=Event::RECV_MESSAGE_PONG\n @args=[tmp[1]]\n when \"ERROR\"\n @cmndstr=\"ERROR\"\n @command=Event::RECV_MESSAGE_ERROR\n @args=[tmp[1]]\n when \"NOTICE\"\n #\n # for madoka-parsed CTCP message\n #\n # She parse unknown ctcp such as\n # :hoge!~huga@hoe mohe PRIVMSG ^AGOHAN asa^A\n # to\n # NOTICE mohe :GOHAN@hoge: asa\n #\n if(String(tmp[1])=~/([^\\s]+) :([^\\@\\s]+)@([^:]+):(.+)/)\n @ctcpQuery=true\n @cmndstr=\"CTCP_QUERY\"\n \n @to=String($1)\n @channel=@to\n @fromNick=String($3)\n @from=@fromNick\n parseCtcp(Event::RECV_CMND+Event::CMND_CTCP_QUERY,\n String($2)+String($4))\n else\n @cmndstr=\"NOTICE\"\n @command=Event::RECV_MESSAGE_NOTICE\n @args=[tmp[1]]\n end\n else\n parseMessage(msg)\n end\n end",
"def parseCommand(cmnd,arg)\n event=Event::RECV_CMND\n \n case(cmnd)\n when \"PASS\"\n event+=Event::CMND_PASS\n when \"NICK\"\n #\n # for madoka feed-back\n #\n if((@args[0].nil?)&&(!@to.nil?))\n @args=[@to]\n else\n @to=@args[0]\n end\n event+=Event::CMND_NICK\n when \"USER\"\n event+=Event::CMND_USER\n when \"SERVER\"\n event+=Event::CMND_SERVER\n when \"OPER\"\n event+=Event::CMND_OPER\n when \"QUIT\"\n event+=Event::CMND_QUIT\n when \"SQUIT\"\n event+=Event::CMND_SQUIT\n when \"JOIN\"\n #\n # for madoka feed-back\n #\n if((@args[0].nil?)&&(!@to.nil?))\n @args=[@to]\n else\n @to=@args[0]\n end\n event+=Event::CMND_JOIN\n when \"PART\"\n event+=Event::CMND_PART\n when \"MODE\"\n event+=Event::CMND_MODE\n when \"TOPIC\"\n event+=Event::CMND_TOPIC\n when \"NAMES\"\n event+=Event::CMND_NAMES\n when \"LIST\"\n event+=Event::CMND_LIST\n when \"INVITE\"\n event+=Event::CMND_INVITE\n when \"KICK\"\n event+=Event::CMND_KICK\n when \"VERSION\"\n event+=Event::CMND_VERSION\n when \"STATAS\"\n event+=Event::CMND_STATAS\n when \"LINK\"\n event+=Event::CMND_LINK\n when \"TIME\"\n event+=Event::CMND_TIME\n when \"CONNECT\"\n event+=Event::CMND_CONNECT\n when \"TRACE\"\n event+=Event::CMND_TRACE\n when \"ADMIN\"\n event+=Event::CMND_ADMIN\n when \"INFO\"\n event+=Event::CMND_INFO\n when \"PRIVMSG\"\n begin\n if(args[0][0]==1)\n @ctcpQuery=true\n @cmndstr=\"CTCP_QUERY\"\n parseCtcp(event+Event::CMND_CTCP_QUERY,arg.join(\" \"))\n return\n end\n rescue NameError\n end\n event+=Event::CMND_PRIVMSG\n when \"NOTICE\"\n begin\n if(args[0][0]==1)\n @ctcpAnswer=true\n @cmndstr=\"CTCP_ANSWER\"\n parseCtcp(event+Event::CMND_CTCP_ANSWER,args.join(\" \"))\n return\n end\n rescue NameError\n end\n event+=Event::CMND_NOTICE\n when \"WHO\"\n event+=Event::CMND_WHO\n when \"WHOIS\"\n event+=Event::CMND_WHOIS\n when \"WHOWAS\"\n event+=Event::CMND_WHOWAS\n when \"KILL\"\n event+=Event::CMND_KILL\n when \"PING\"\n event+=Event::CMND_PING\n when \"PONG\"\n event+=Event::CMND_PONG\n when \"ERROR\"\n event+=Event::CMND_ERROR\n when \"AWAY\"\n event+=Event::CMND_AWAY\n when \"REHASH\"\n event+=Event::CMND_REHASH\n when \"RESTART\"\n event+=Event::CMND_RESTART\n when \"SUMMON\"\n event+=Event::CMND_SUMMON\n when \"USERS\"\n event+=Event::CMND_USERS\n when \"WALLOPS\"\n event+=Event::CMND_WALLOPS\n when \"USERHOST\"\n event+=Event::CMND_USERHOST\n when \"ISON\"\n event+=Event::CMND_ISON\n end\n \n @command=event\n end",
"def lsp()\n\t$sequencenum += 1\n\tmsg = \"LSP \"\n\tmsg<<\"#{$hostname} \"\n\t#puts (\"neighbor in lsp = #{$neighbors}\")\n\t$neighbors.each do |key, value|\n\t\tmsg<<\"#{value.name}\"\n\t\tmsg<<\":\"\n\t\tmsg<<\"#{value.cost}\"\n\t\tmsg<<\"|\"\t\t\n\tend\n\t#puts (\"before chomp #{msg}\")\n\tmsg = msg.chomp(\"|\")\n\tmsg<<\" #{$sequencenum}\"\n\t#puts (\"sending msg #{msg}\")\n\t# flooding each neighbor node with lsp\n\t#puts (\"flooding msg = #{msg}\")\n\tflood(msg)\nend\n\n#pass whatever message you receive to each of the connecting negihbors of the node\ndef flood(msg)\n\t#$semaphore.synchronize{\n\t$neighbors.each do |key, value|\n\t#puts (\"writing to #{value.name} : #{msg} through socket #{value.sock}\")\n\t#value.sock.puts(\"#{msg}\")\\\n\t\twriteTo(value.sock, msg)\n\t\t#$pq.insert(Time.new, Event.new(\"WRITE\", [value.sock, msg]))\n\tend\n\t#}\nend",
"def constructMsg(cmd, nodeType)\n msgstr = String.new(@istr)\n @@cmdSeqNo = @@cmdSeqNo + 1\n seqstr = to_s_i(@@cmdSeqNo)\n msgstr[0] = seqstr[0]\n msgstr[1] = seqstr[1]\n msgstr[2] = seqstr[2]\n msgstr[3] = seqstr[3]\n t = Time.now\n timestr = to_s_i(t.to_i)\n msgstr[4] = timestr[0]\n msgstr[5] = timestr[1]\n msgstr[6] = timestr[2]\n msgstr[7] = timestr[3]\n msgstr[8] = CM_PACKET_FORMAT \n msgstr[9] = 0\n if (cmd == CM_CMD_IDENTIFY_NODE)\n msgstr[10] = CM_CMD_IDENTIFY_NODE\n msgstr[11] = 0\n else\n msgstr[10] = cmd\n msgstr[11] = 0\n end\n ipstr = to_s_i(CM_MYIP)\n msgstr = msgstr + ipstr \n msgstr = msgstr + (CMC_SOFTWARE_VERSION).to_s\n msgstr[18] = nodeType\n msgstr[19] = 0\n msgstr = msgstr + CM_CMSTATUS\n msgstr = msgstr + CM_MAC\n msgstr = msgstr + CM_MAC\n msgstr = msgstr + CM_MAC\n msgstr = msgstr + CM_MAC\n \n return msgstr \n end",
"def nextHop(target_id)\n m = 0\n n = -1\n while @guid[m] == target_id[m] && m < @m_max\n m += 1\n end\n n = target_id[m]\n n = n.to_s\n n = n.hex\n\n # Checking routing table at that location to see if has an entry\n # If has,the entry will be a digit closer than the current nodes GUID\n if @routing_table[[0, m, n]] != nil\n return InetAddr.new(@routing_table[[0, m, n]][:ip_address], @routing_table[[0, m, n]][:port]), m, n\n\n # If not,searching the entire routing table for the entry with the GUID closest to the target_id\n else\n shortestDistance = distancing(target_id, @guid)\n # Sending message on if there is a closer address\n nh = InetAddr.new()\n @routing_table.each do |key, array| # Accessing each element of routing table\n if distancing(target_id, array[:node_id]) < shortestDistance && distancing(target_id, array[:node_id]) != 0\n shortestDistance = distancing(target_id, array[:node_id])\n nh.ip = array[:ip_address]\n nh.port = array[:port]\n end\n end\n return nh, m, n\n end\n end",
"def receive_name socket \n data = socket.read_packet_2 'n'\n dist = data[0,2] # 5,5\n flags = data[2,4] # flags\n node_name = data[6, data.length]\n [dist, flags, node_name]\n end",
"def command(cmd, arg = 2)\n return if @sp == nil\n #<SOT><CMD_BYTE><CHECK_SUM><EOT>\n case cmd\n=begin\n Request DCF Time\n <SOH><0x30><Chksum><EOT>\n=end\n when 0 #Poll DCF Time\n exchange(\"\\x01\\x30\\xcf\\x04\", 7)\n puts DCF77.new(@response).to_s\n=begin\n Request Dataset\n \t<SOH><0x31><Chksum><EOT>\n \t\tResponse from weather station: (34/60 Bytes) Mine has additional 0 byte, so 35/61 bytes are received.\n \t\t1. Data available\n \t\t\tBlock no.: 2 bytes Number of the block in the memory\n \t\t\t (no relation to time. Serves to control dataset registered twice).)\n \t\t\tTime: 2 bytes Age of the dataset in minutes up to the current time.\n \t\t\t\t\t\t\t\t age = ( data[2] & 0xff ) + ( data[3] << 8 & 0xff00 );\n \t\t\tData: 30 (9 sensors) or 56 (16 sensors) bytes\n \t\t2. No data available: <DLE>\n=end\n when 1 #Request dataset\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n #@response.each { |r| print \"%02X \" % r }\n s = Sensors.new(@response)\n if s.data?\n puts s.to_data_row\n puts Sensors.new(@response).to_s\n end\n=begin\n \tSelect Next Dataset\n \t\t<SOH><0x32><Chksum><EOT>\n \t\t\tResponse from weather station: (1 Byte)\n \t\t\t\t1. Next dataset available : <ACK> 0x06\n \t\t\t\t2. No dataset available: <DLE> 0x10\n=end\n when 2 #select next dataset\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tSet 8 Sensors\n \t\t<SOH><0x33><Chksum><EOT>\n \t\tResponse from weather station: (1 Byte)\n \t\t<ACK>\n=end\n when 3 #activate 8 sensors\n exchange(\"\\x01\\x33\\xcc\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n set 16 Sensors\n \t<SOH><0x34><Chksum><EOT>\n \tResponse from weather station: (1 Byte)\n \t<ACK>\n=end\n when 4 #activate 16 sensors\n exchange(\"\\x01\\x34\\xcb\\x04\",1)\n exit @response[0] == ACK ? 0 : 1\n=begin\n \tStatus\n \t <SOH><0x35><Chksum><EOT>\n \tResponse from weather station: (21 Byte)\n \tBytes 1 - 18\n \t\t\tS:1-8 Temp/Hum\n \t\t\t9 Rain,\n \t\t\t10 Wind\n \t\t\t11 Indoor Temp/Hum/Pres\n \t\t\t12 S9:Temp/Hum\n \t\t\t13-15 S10-15:Temp/Hum/Pres\n \t\tByte >= 0x10 if sensor present\n \t\tvalue > 0x10 number of error\n \tByte 19 Sample Interval in minutes\n \tByte 20\n \t bit 0 DFC77 time receiver active\n \t\tbit 1 HF if set\n \t\tbit 2 8/16 Sensors\n \t\tbit 3 DFC Synchronized (Not likely in NZ)\n \tByte 21 Version Number\n=end\n when 5 #Request Status\n exchange(\"\\x01\\x35\\xca\\x04\", 21)\n @response.each { |r| print \"%02X \" % r }\n puts\n=begin\n Set Interval time\n \t <SOH><0x36><minutes><Chksum><EOT>\n \t\tminutes range 1..60\n \t Response from weather station: (1 Byte)\n \t<ACK> if in range\n \t<DLE> if out of range\n=end\n when 6 #set interval time\n #<SOT><CMD_BYTE><ARGUMENT><CHECK_SUM><EOT>\n raise Weather_exception, \"Interval Range 2..60\" if arg > 60 || arg < 2\n exchange(\"\\x01\\x36#{arg.chr}#{(0xc9-arg).chr}\\x04\", 1)\n exit @response[0] == ACK ? 0 : 1\n\n when 12 #Loop through 1 and 2\n begin\n exchange(\"\\x01\\x31\\xce\\x04\", 61)\n s = Sensors.new(@response)\n exchange(\"\\x01\\x32\\xcd\\x04\",1)\n if s.data?\n\t puts s.to_data_row\n else\n break\n end\n end while( @response[0] == ACK )\n end\n end",
"def get_move\n #puts \"get_move for #{self}\"\n return [] if goal == nil or goal == []\n while(1)\n rv = []\n g = goal.shift\n return [] if g == nil\n puts g.join('---')\n case g[0]\n when KILL\n e = g[1] # get the ennemy\n if(not $map.exists?(e) or e.life<=0)\n puts 'this ant does not exists anymore or is dead, next goal'\n next \n end\n \n dist = distance(self,e)\n #puts \"I am #{self}\"\n #puts \"goal: kill this enneny: #{e}\"\n i = 0\n if dist > 1 # move\n # by doing this we are finding subgoals\n # TODO: add_sub_goal ?\n\n path = find_best_way(e.x,e.y)# we have to move next to it\n #puts ppath(path)\n if path==nil\n # TODO: no path, find something else to do\n puts 'no path ! , next goal'\n next\n end\n \n # we have a path to it\n # so now we have to move smartly\n # if we are at 3 cases, we can move and attack\n # more than that we have to move at 4 cases and wait the next turn\n # TODO: do not wait at a position where we can be attacked\n if(path.size-2 <= 3) # minus two because the path include our case\n i = path.size-2 # 0 based minus one, so -2 \n #puts 's1'\n elsif(path.size-2 >= 6) # we are far away\n i = 6\n #puts 's2'\n else\n i = (path.size-2)\n #puts 's3'\n end\n #puts i\n #sleep(1)\n if i <= 0\n puts \"i <= 0 (#{i}), #{ppath(path)}\"\n sleep(5)\n else\n a,b = path[i][0]\n #puts \"I am moving to (#{[a,b].join(',')})\"\n self.x,self.y = a,b\n rv << \"Cb#{object_id}~\"+[a,b].pack('cc')\n #puts x\n end\n end\n return rv if i > 3 # return if we can not attack at the same round\n #puts i\n dist = distance(self,e)\n if dist == 1\n puts 'Attack'\n rv << \"Cc#{object_id}~#{e.object_id}\"\n e.life -= 5\n end\n return rv\n else\n puts 'unknown goal, next goal'\n end # case\n end #while\n puts \"no goal ? find something else to do !\"\n rv\n end",
"def to_s\n msg_str = \"Command Packet Hex Str: #{@cmd_str.to_s}\\n\"\n msg_str << \"net_id: #{@net_id}\\n\"\n msg_str << \"pkt_no: #{@pkt_no}\\n\"\n msg_str << \"cmd_id: #{@cmd_id.to_s(16)}\\n\"\n msg_str << \"res_req: #{@res_req}\\n\"\n msg_str << \"ack_req: #{@ack_req}\\n\"\n msg_str << \"ack_bit: #{@ack_bit}\\n\"\n msg_str << \"err_bit: #{@err_bit}\\n\"\n if @data != nil\n data_str = \"\"\n if @data == CmdManager::DONT_CARE\n data_str = CmdManager::DONT_CARE\n else \n @data.each{|x| \n if x == CmdManager::DONT_CARE\n data_str << CmdManager::DONT_CARE\n else\n data_str << \"#{x.to_s(16)} \"\n end\n }\n end\n \n msg_str << \"data: [#{data_str.chop}]\\n\"\n end\n if @error_no != 0\n msg_str << \"error_desc: #{@error_desc}\\n\"\n end\n \n msg_str\n end",
"def move_node!(tg,tga,i)\n #first just add node i in\n tga[0].each_index do |ii|\n if (i == tga[0][ii][0])\n tg[0].push(tga[0][ii])\n tga[0][ii] = nil\n break\n end\n end\n #then add the edges, only add edges for which both nodes exist in tg \n tga[1].each_index do |ii|\n if tg[0].index{|item| item[0] == tga[1][ii][0]} && tg[0].index{|item| item[0] == tga[1][ii][1]}\n tg[1].push(tga[1][ii])\n tga[1][ii] = nil\n end\n end\n tga[0].compact!\n tga[1].compact!\nend",
"def traceroute(cmd)\n\tdst = cmd[0]\n\n # Check to see if there is a next hop\n next_hop = $next[dst]\n if next_hop == \"NA\"\n STDOUT.puts \"TRACEROUTE ERROR: HOST UNREACHABLE\"\n return\n end\n\n # This will print out itself with hop 0 and time 0.00\n\tSTDOUT.puts(\"0 \" + $hostname + \" 0.00\")\n \n if next_hop == $hostname\n return\n end\n\n # Sets up the message for tracerouteCallBack\n client = $clients[next_hop]\n msg = Msg.new\n msg.setConfig(\"type\", 4)\n msg.setConfig(\"code\", 0)\n msg.setMessage($hostname + \" \" + dst + \" \" + dst + \" 0 \" + $currtime.to_f.round(4).to_s)\n $traceroute_finish = false\n $hop_counter = \"1\"\n sendMessage(client, msg)\n\n start_time = $currtime\n while $currtime - start_time < $ping_timeout\n if $traceroute_finish\n return\n end\n sleep(0.1)\n end\n\tSTDOUT.puts(\"TIMEOUT ON HOPCOUNT \" + $hop_counter)\nend",
"def command(str)\n ar=str.split(/ /)\n case ar[0]\n when \"++addr\"\n if ar.size<2\n return @addr.to_s\n else \n @addr=ar[1].to_i\n end\n\n end\n return nil\n end",
"def sendmsg(cmd)\n\tdst = cmd[0]\n msg = $hostname + \" \" + dst + \" \" + cmd[1..-1].join(\" \")\n error_msg = \"SNDMSG ERROR: HOST UNREACHABLE\"\n\n # Make sure dst is reachable by checking it's next table, making sure it's not NA\n # and that the client table can find the right client\n if ($next.include?(dst) && $next[dst] != \"NA\" &&\n $clients.has_key?($next[dst]))\n next_hop = $next[dst]\n else\n STDOUT.puts(error_msg)\n return\n end\n\n client = $clients[next_hop]\n \n # Construct the packet\n packet = Msg.new()\n packet.setConfig(\"type\", 5)\n packet.setConfig(\"code\", 0)\n packet.setMessage(msg)\n\n success = sendMessage(client, packet)\n if !success\n STDOUT.puts(error_msg)\n end\nend",
"def ip_cmd_from_file\n\n ip_cmd = ''\n ip_cmd += 'to ' + self.to + ' ' if ! self.to.nil? && ! self.to.empty?\n ip_cmd += 'via ' + self.via + ' ' if ! self.via.nil? && ! self.via.empty?\n ip_cmd += 'dev ' + self.device + ' ' if ! self.device.nil? && ! self.device.empty?\n ip_cmd += 'table ' + self.table + ' ' if ! self.table.nil? && ! self.table.empty?\n return ip_cmd\n\n end",
"def shortest_paths(source, dest)\n @graph_paths=[]\n @source = source\n dijkstra source\n @path=[]\n find_path dest\n actual_distance=if @distance[dest] != INFINITY\n @distance[dest]\n else\n \"no path\"\n end\n \"Shortest route and distance : #{@path.join(\"-->\")}, #{actual_distance} km\"\n end",
"def findShortest(graph_nodes, graph_from, graph_to, ids, val)\n return -1 if ids.count(val)<=1 # no two nodes with color val\n dmin = graph_nodes\n num_edges = graph_from.length\n neighbors = {}\n 0.upto(num_edges-1) do |i|\n if neighbors[graph_from[i]]\n neighbors[graph_from[i]] << graph_to[i]\n else\n neighbors[graph_from[i]] = [graph_to[i]]\n end\n if neighbors[graph_to[i]]\n neighbors[graph_to[i]] << graph_from[i]\n else\n neighbors[graph_to[i]] = [graph_from[i]]\n end\n end\n p neighbors\n ids.each_with_index do |v,i|\n if v == val\n # zero-base index to one-base index \n source_node = i+1\n # look for others using bfs (stop looking if distance > dmin)\n queue = []\n visited = []\n backtrace = {}\n queue << source_node\n while !(queue.empty?)\n current_node = queue.shift\n visited << current_node\n if (current_node!=source_node) && (ids[current_node-1]==val)\n puts \"we are here!\"\n # how did I get here? backtrace\n hops = 0\n trace_node = current_node\n while (trace_node!=source_node)\n trace_node = backtrace[trace_node]\n hops +=1\n end\n if hops < dmin\n dmin = hops\n end\n break\n end\n neighbors[current_node].each do |xnode|\n if !(visited.include?(xnode))\n queue << xnode\n backtrace[xnode] = current_node\n end\n end\n end\n p visited\n end\n end\n if dmin == graph_nodes\n return -1\n else\n return dmin\n end\nend",
"def two_break_distance(p, q)\n p_nodes = colored_edges(p)\n q_nodes = colored_edges(q)\n\n all_nodes = p_nodes + q_nodes\n\n puts all_nodes.length\n # puts all_nodes.sort.join(\" \")\n\n cycle_count = 0\n\n loop do \n\n break if all_nodes.empty?\n cycle = {}\n # cycle = all_nodes[0]\n cycle[all_nodes[0][0]] = 1\n cycle[all_nodes[0][1]] = 1\n\n found_a_node = 1\n\n loop do\n\n break if found_a_node == 0\n\n found_a_node = 0\n # all_nodes.dup.each do |node|\n index = 0\n loop do\n break if all_nodes.length == index\n node = all_nodes[index]\n # if (cycle.include?(node[0]) || cycle.include?(node[1]))\n if (cycle.has_key?(node[0]) || cycle.has_key?(node[1]))\n # puts all_nodes.length\n # print node.join(\" \") + \" \"\n # cycle += node\n cycle[node[0]] = 1\n cycle[node[1]] = 1\n # cycle.uniq!\n all_nodes.delete(node)\n found_a_node = 1\n else\n index += 1\n end\n end\n\n end\n \n # puts cycle.join(\" \")\n # puts cycle.keys.length\n cycle_count += 1 unless cycle.empty?\n # puts all_nodes.join(\" \")\n # break\n end\n\n # puts cycle_count\n no_of_blocks = p_nodes.length\n\n return (no_of_blocks - cycle_count)\n\n end",
"def get_route_command(path_address,moving_direction)\n cmd_list = []\n \n for i in 0...path_address.size\n curx = path_address[i].x\n cury = path_address[i].y\n \n command_id = 0\n debug_info = \"\"\n case moving_direction[i]\n when 2\n debug_info = \"↓\"\n command_id = 2\n when 4\n debug_info = \"←\"\n command_id = 4\n when 6\n debug_info = \"→\"\n command_id = 6\n when 8\n debug_info = \"↑\"\n command_id = 8\n else\n debug_info = \"O\"\n end #case\n \n puts \"#{debug_info} (#{curx},#{cury})\" if $pathfinding_debug\n if command_id > 0\n #Pixel_Core::Pixel.times{ }\n cmd_list << [command_id, true]\n end # if command_id > 0\n end # for i in path_address.size\n \n return cmd_list\n end",
"def problem_107\n if false\n net = [ \"-,16,12,21,-,-,-\", \"16,-,-,17,20,-,-\", \"12,-,-,28,-,31,-\",\n \"21,17,28,-,18,19,23\", \"-,20,-,18,-,-,11\", \"-,-,31,19,-,-,27\",\n \"-,-,-,23,11,27,-\" ]\n net.map! {|line| line.split(/,/).map {|i| i == '-' ? nil : i.to_i}}\n else\n net = []\n open(\"network.txt\").each do |line|\n net << line.chomp.split(/,/).map {|i| i == '-' ? nil : i.to_i}\n end\n end\n\n # Reformat into an array of nodes, with the their connections\n nodes = Hash.new {|h,k| h[k] = Hash.new }\n net.each_with_index do |row,i| # Each nodes is connected to...\n row.each_index do |col| # For each possible connection....\n # Add the node we are connected to and the cost\n nodes[i][col] = row[col] if row[col]\n end\n end\n\n initial = nodes.reduce(0) do |a,row|\n row[1].reduce(a) {|aa,p| aa + p[1] }\n end / 2\n # add to the 'borg' that is node0\n node0,node0_links = nodes.shift\n ans = []\n node0_contains = Hash.new\n node0_contains[node0] = true\n\n # What we do select the lowest link, the 'merge' it into node0, repeat\n while nodes.length > 0\n n,v = node0_links.min {|a,b| a[1] <=> b[1]}\n ans << [n,v] # Save the link for the answer\n node0_contains[n] = true # add to the 'borg' that is node0\n nodes[n].each_pair do |k,a| # Now merge in new poin, update vertexs\n next if node0_contains[k]\n node0_links[k] = [a, node0_links[k] || 1_000_000].min\n end\n nodes.delete(n) # Remove from free nodes\n node0_links.delete(n) # Remove from vertexes to resolve\n end\n\n now = ans.reduce(0) {|a,v| a + v[1]}\n puts \"initial = #{initial}\"\n puts \"now = #{now}\"\n initial - now\nend",
"def build_assignment_graph(layer)\n\t\th = @via_positions.length\n\t\tfail if (h == 0) || h.odd?\n\t\tfail if @start_node.pads.min < 0 || @start_node.pads.max >= @layer_count\n\t\tfail if @end_node.pads.min < 0 || @end_node.pads.max >= @layer_count\n\t\tvia_count = h / 2\n\t\tputs via_count\n\t\tlayers = 0..(@layer_count - 1) \n\t\tcolums = 0..(via_count * 2) # F O F O F for via_count == 2 \n\t\t#vp = @via_positions.dup # x,y pairs\n\t\t#vp.unshift(@start_node.y)\n\t\t#vp.unshift(@start_node.x)\n\t\tvp = [@start_node.x, @start_node.y] + @via_positions\n\t\tm = Array.new(@layer_count){Array.new(via_count * 2 + 1)}\n\t\tfor i in colums # from T back to S\n\t\t\tif i.even?\n\t\t\t\ty = vp.pop\n\t\t\t\tx = vp.pop\n\t\t\tend\n\t\t\tfor j in layers\n\t\t\t\tl = Array.new\n\t\t\t\tif i.even? # forward\n\t\t\t\t\tk = i + 1\n\t\t\t\t\twhile k > 0\n\t\t\t\t\t\tk -= 2\n\t\t\t\t\t\tif k == -1 # link forward node to T node\n\t\t\t\t\t\t\tl << @end_node if @end_node.pads.include?(j)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (h = m[j][k])\n\t\t\t\t\t\t\t\tl << h # link to up/down node \n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = F_node.new(x, y, j, l)\n\t\t\t\t\t\tl.each{|el|\n\t\t\t\t\t\t#unless @segment_list.index{|m| m.x1 == && m.y1 == el.y1 & m.x2 == el.x2 && m.y2 == el.y2}\n\t\t\t\t\t\t\t@segment_list << Segment.new(x, y, el.x, el.y)\n\t\t\t\t\t\t}\n\t\t\t\t\tend\n\t\t\t\telse #up/down\n\t\t\t\t\tfor k in layers do\n\t\t\t\t\t\tif (k != j) && (h = m[k][i - 1])\n\t\t\t\t\t\t\tl << h\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tunless l.empty?\n\t\t\t\t\t\tm[j][i] = V_node.new(x, y, j, l)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#puts @segment_list.length\n\t\t@segment_list.uniq!{|el| [el.x1, el.y1, el.x2, el.y2]}\n\t\tputs @segment_list.length\n\t\t@all_intersecting_segments = Array.new\n\t\t@segment_list.each{|el|\n\t\t\t@all_intersecting_segments += el.intersecting_segments\n\t\t}\n\t\t@all_intersecting_segments.uniq!\n\n\t\tfor j in layers\n\t\t\tif (h = m[j][-1]) && @start_node.pads.include?(j)\n\t\t\t\t@start_node.next << h\n\t\t\tend\n\t\tend\n\tend",
"def process(dfstr)\n tracelog {\"process(commands, input).\"}\n #\"\"\"Filesystem Size Used Avail Use%\n # /dev/grid/node-x0-y0 92T 73T 19T 79%\"\"\"\n linect = 0\n nodes = {}\n dfstr.each_line do |line|\n linect += 1\n line = line.chomp.chomp\n tracelog { \"read-line #{linect}: #{line}\" }\n if md = (/^\\/dev\\/grid\\/node\\-x(\\d+)\\-y(\\d+) +(\\d+)T +(\\d+)T +(\\d+)T +(\\d+)%$/.match line) #md = (/^\\/dev\\/grid\\/node\\-x(\\d+)\\-y(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)%$/.match line)\n x = md[1].to_i\n y = md[2].to_i\n siz = md[3].to_i\n usd = md[4].to_i\n ava = md[5].to_i\n prc = md[6].to_i\n key = \"#{x},#{y}\"\n nodes[key] = {:size=>siz, :used=>usd, :avail=>ava, :useperc=>prc}\n tracelog {\"node[#{key}]=#{nodes[key]}\"}\n else\n deblog {\" skipped line ##{linect} #{line}.\"}\n end\n end\n deblog {\"#nodes=#{nodes.size} of #lines=#{linect}\"}\n \n viabpairnum = 0\n nodes.each do |a_key, a_vals|\n nodes.each do |b_key, b_vals|\n #next if a_key == b_key\n if a_vals[:used] > 0 && a_key != b_key && a_vals[:used] <= b_vals[:avail]\n tracelog {\"viable pair: A=#{a_key}, used=#{a_vals[:used]}; B=#{b_key}, avail=#{b_vals[:avail]}\"}\n viabpairnum += 1\n end\n end\n end\n viabpairnum\nend",
"def travel_command( node )\n\t\t\t\tTravelCommand.new @interface, node\n\t\t\tend",
"def constructSendCmd(ipport, ipaddr, cmd, nodeType)\n nmsg = MsgPacket.new\n cmstr = nmsg.constructMsg(cmd, nodeType)\n sendCommand(ipport, ipaddr, cmstr)\n insertPool(cmstr, ipaddr)\n end",
"def aStar(tx = @player.x/@TILESIZE, ty = @player.y/@TILESIZE, x = @x/@TILESIZE, y = @y/@TILESIZE)\n #exit conditions\n if tx > @map.WIDTH or ty > @map.HEIGHT or tx < 0 or ty < 0\n return Node.new(x, y, nil, 0)\n end\n start = Time.now\n evald = Array.new #nodes that have already been evaluated\n queue = [Node.new(x, y, 0)]#the last element is the g value\n until queue.empty?\n #queue.each{ |q| print q.toArray, \"...\"}\n #print \"\\n\" #for debugging\n current = queue[0]#finds the node in queue with the lowest f value\n queue.each do |q|\n current = q if q.f(tx, ty) < current.f(tx, ty)\n end\n evald.push(current)#move current from 'queue' to 'evald'\n queue.delete(current)\n #direction from the second node aka the one after the one the ghost is at\n if current.x == tx and current.y == ty\n current.trim\n return current\n #print \"the ghost is confused\\n\" # for debugging\n end\n @map.getSurrounding(current.x, current.y, false).each{ |n|\n node = Node.toNode(n)\n node.g= current.g + 1\n node.parent= current\n nodeInEvald = false\n evald.each{ |evNode|\n if(evNode.coords == node.coords)\n if(evNode.g > node.g)\n evNode.g = node.g\n evvNode.dir = node.dir\n end\n nodeInEvald = true\n break\n end\n }\n if !nodeInEvald\n queue.push(node) \n end\n }\n #just gives up if it's been trying to find a path for more than 5 seconds\n if Time.now - start > 5\n current.trim\n current.timeOut = true;\n return current\n end\n end\n nil\n end",
"def shortest_paths(s)\n @source = s\n dijkstra s\n puts \"Source: #{@source}\"\n @nodes.each do |dest|\n puts \"\\nTarget: #{dest}\"\n print_path dest\n if @d[dest] != @INFINITY\n puts \"\\nDistance: #{@d[dest]}\"\n else\n puts \"\\nNO PATH\"\n end\n end\n end",
"def task_2(str)\n r = []\n str.each_line do |x|\n ip = x[/^.* - -/]\n d = x[/[\\[].*[\\]]/]\n a = x[/T .* H/]\n if ip && d && a\n r << d[1..-2] + ' FROM: ' + ip[0..-4] + 'TO:' + a[1..-3].upcase\n end\n end\n r\nend",
"def edgesymbol\n directed ? '->' : '--'\n end",
"def dij(linkPackageMap, native)\nputs \"start dij\"\ndist = Hash.new();\nprevNode = Hash.new();\ntraversed = Array.new;\nallNodes = linkPackageMap.keys;\n#for i in 0..allNodes.length - 1\n#\tdist[allNodes[i]] = -1;\n#\tprevNode[allNodes[i]] = nil;\n#end\ndist[native] = 0;\nprevNode[native] = native;\n#q = PriorityQueue.new\n#q[native] = 0;\n\nq = Pqueue.new();\nq.push(native, 0);\n\n\nuntil q.isEmpty()\n\tu, distance = q.pop();\n\ttraversed.push(u);\n\t#puts u;\n\t#puts distance;\n\tuNeighborMap = linkPackageMap[u].map();\n\t#puts uNeighborMap.keys;\n\tuNeighbors = uNeighborMap.keys\n\tfor i in 0..uNeighbors.length - 1\n\t\t#puts uNeighbors[i]\n\t\tif !traversed.include?(uNeighbors[i]) then\n\t\t\tnewDistance = dist[u].to_i + uNeighborMap[uNeighbors[i]].to_i;\n\t\t\tif dist[uNeighbors[i]] == nil then\n\t\t\t\tdist[uNeighbors[i]] = newDistance\n\t\t\t\tprevNode[uNeighbors[i]] = u;\n\t\t\telse \n\t\t\t\tif newDistance < dist[uNeighbors[i]] then\n\t\t\t\tdist[uNeighbors[i]] = newDistance\n\t\t\t\tprevNode[uNeighbors[i]] = u;\n\t\t\t\tend\n\t\t\tend\n\t\t\tq.push(uNeighbors[i], dist[uNeighbors[i]].to_i);\n\t\t\t#q[uNeighbors[i]] = dist[uNeighbors[i]].to_i;\n\t\tend\n\t\t\t\n\tend\n\nend\n\n\n\nnodes = prevNode.keys;\n#puts nodes;\nnativeNeighbor = linkPackageMap[native].map();\n#nativeNeighbor.each{|key, value| puts \"key : #{key} value : #{value}\"}\nfor i in 0 .. nodes.length - 1\n\tif prevNode[nodes[i]] == native then\n\t\tprevNode[nodes[i]] = nodes[i];\n\telse\n\t\twhile(!nativeNeighbor.include?(prevNode[nodes[i]]) )\n\t\t\tprevNode[nodes[i]] = prevNode[prevNode[nodes[i]]];\n\t\tend\t\n\tend\nend\n\nreturn dist, prevNode;\nend",
"def shortest_paths(s)\n\t\t@source = s\n\t\tdijkstra s\n\t\tputs \"Source: #{@source}\"\n\t\t@nodes.each do |dest|\n\t\t\tputs \"\\nTarget: #{dest}\"\n\t\t\tprint_path dest\n\t\t\tif @d[dest] != @INFINITY\n\t\t\t\tputs \"\\nDistance: #{@d[dest]}\"\n\t\t\telse\n\t\t\t\tputs \"\\nNO PATH\"\n\t\t\tend\n\t\tend\n\tend",
"def to_s\n \"#{@name}::#{@num_nodes}::#{Base64.encode64(@start_time._dump).chomp}::#{Base64.encode64(@end_time._dump).chomp}::#{total_time}::#{cost}\"\n end",
"def on_getaddr\n #addrs = @node.addrs.select{|a| a.time > Time.now.to_i - 10800 }.shuffle[0..250]\n #p \"<< addr (#{addrs.size})\"\n #send_data P::Addr.pkt(*addrs)\n end",
"def ping(cmd)\n\tdst = cmd[0]\n next_hop = $next[dst]\n if next_hop == \"NA\" || next_hop == $hostname\n STDOUT.puts \"PING ERROR: HOST UNREACHABLE\"\n return\n end\n n = cmd[1].to_i\n delay = cmd[2].to_i\n client = $clients[next_hop]\n\n # This will iterate through the number of pings given on the command line. It will setup the \n # proper message for pingCallBack and adds the current time to the ping table with the key\n # of the sequence number. It will then check if ping_table has that key still (should be removed\n # by pingCallBack) so if it still exists, then the host was not reached.\n for seq_id in (0..(n - 1))\n msg = Msg.new\n msg.setConfig(\"type\", 3)\n msg.setConfig(\"code\", 0)\n msg.setMessage($hostname + \" \" + dst + \" \" + seq_id.to_s)\n $ping_table[seq_id.to_s] = $currtime\n sendMessage(client, msg)\n Thread.new {\n seq_id_ = seq_id\n sleep($ping_timeout)\n if $ping_table.has_key?(seq_id_.to_s)\n STDOUT.puts \"PING ERROR: HOST UNREACHABLE\"\n end\n $ping_table.delete(seq_id_.to_s)\n }\n sleep(delay)\n end\nend",
"def expand_graph_adj(vertex, pass = nil)\n m = $game_map\n add_vertex(vertex)\n \n tp = vertex.x == 21 && vertex.y == 5\n \n t = Time.now\n vx,vy = vertex.x, vertex.y\n return if !MoveUtils.ev_passable?(vx,vy, @source)\n \n ([Vertex.new(vx-1,vy, m.terrain_tag(vx-1,vy)),Vertex.new(vx,vy-1, m.terrain_tag(vx,vy-1))]).each_with_index do |v,i|\n next if !@verticies[v]\n x,y = v.x,v.y\n dir = (i+1)*4\n ev_pass = MoveUtils.ev_passable?(x,y,@source)\n next if !ev_pass\n add_edge(vertex, v, {} , opp_dir(dir), dir)\n end\n end",
"def shortest_paths(dest)\n position = dest\n final = {}\n analisados = {}\n route = []\n route << dest\n @previous['a'] = -1\n\n @nodes.each do |n|\n analisados[n] = false\n end\n analisados[position] = true\n\n while analisados(analisados)\n adyacentes(position, analisados).each do |n|\n if @distance[n] == (@distance[position] - graph[n][position])\n @previous[position] = n\n position = n\n route << n\n end\n analisados[n] = true\n end\n\n end\n route << 'a'\n route\n end",
"def get_command\n\t\ttext = read.chomp\n\t\tcommand = {}\n\t\tif text =~ /PASS/i\n\t\t\tcommand[:pass] = true\n\t\telsif text =~ /ADD\\W+(\\d+)\\W+\\((.*?)\\),?\\W+\\((.*?)\\)/i\n\t\t\tcommand[:action] = :add\n\t\t\tcommand[:id] = $1.to_i # FUTURE spec says it is 4 digits max\n\t\t\tcommand[:points] = [$2,$3].collect do |p|\n\t\t\t\tx,y = p.split(\",\")\n\t\t\t\t{:x => x.to_i, :y => y.to_i}\n\t\t\tend\n\t\telsif text =~ /REMOVE\\W+(\\d+)/\n\t\t\tcommand[:action] = :remove\n\t\t\tcommand[:id] = $1.to_i # FUTURE spec says it is 4 digits max\n\t\tend\n\t\tcommand\n\tend",
"def latency_of(dist)\n len=(dist == 0) ? OVERHEAD_INNER : OVERHEAD_OUTER + dist\n if len <= 300 # [cm]\n #Copper cable\n len*4.4E-9 #HP BladeSystem c-Class 40G QSFP+ to QSFP+ Direct Attach Copper Cable\n else\n # Optical cable \n len*5.2E-9 #Speed of light in glass= 190000km/sec\n end\nend",
"def load_graph(load_cmd)\n\t\tProcessLogger.log(\"Loading graph from GraphViz file #{@filename}.\")\n\n\t\t# Load OSM from XML\n\t\tosm = File.open(@filename) { |f| Nokogiri::XML(f) }\n\n\t\t# aux data structures\n\t\thash_of_vertices = {}\n\t\tlist_of_edges = []\n\t\thash_of_visual_vertices = {}\n\t\tlist_of_visual_edges = []\t\n\n\t\tosm.at_xpath(\"//osm\")\n\n\t\tways = osm.xpath(\"//way\")\t\t\n\t\tways.each do |way| \n\t\t\tway_tags = way.xpath(\"tag\")\n\n\t\t\t# Check whether current way is according to @highway_attributes\t\n\t\t\ttag_highway = way_tags.at_css(\"[@k='highway']\")\n\t\t\thighway_type = tag_highway.nil? ? nil : tag_highway[\"v\"] \n\t\t\tunless (@highway_attributes.include?(highway_type))\n\t\t\t\tnext\n\t\t\tend\n\t\t\t\n\t\t\t# gets speed whether is set or assign 50 as default\n\t\t\ttag_maxspeed = way_tags.at_css(\"[@k='maxspeed']\")\n\t\t\tspeed = tag_maxspeed.nil? ? 50 : tag_maxspeed[\"v\"].to_i\n\n\t\t\t# gets value whether is oneway\n\t\t\ttag_oneway = way_tags.at_css(\"[@k='oneway']\")\n\t\t\tis_one_way = load_cmd.start_with?('--load-dir') && !tag_oneway.nil? && tag_oneway[\"v\"] == \"yes\" ? true : false\t\t\t\t\n\t\t\t\n\t\t\tway_nds = way.xpath(\"nd\")\n\t\t\tway_nds.count.times do |nd_index| \n\t\t\t\t\n\t\t\t\tvid_from = way_nds[nd_index][\"ref\"]\n\t\t\t\tvid_to = way_nds[nd_index + 1].nil? ? nil : way_nds[nd_index + 1][\"ref\"]\n\t\t\t\n\t\t\t\tif vid_from && vid_to\n\t\t\t\t\tv1 = hash_of_vertices.has_key?(vid_from) ? hash_of_vertices[vid_from] : Vertex.new(vid_from) \n\t\t\t\t\tunless hash_of_vertices.has_key?(vid_from)\n\t\t\t\t\t\thash_of_vertices[vid_from] = v1 \n\t\t\t\t\t\tProcessLogger.log(\"\\t Vertex #{vid_from} loaded\")\n\t\t\t\t\tend\n\n\t\t\t\t\tv2 = hash_of_vertices.has_key?(vid_to) ? hash_of_vertices[vid_to] : Vertex.new(vid_to) \n\t\t\t\t\tunless hash_of_vertices.has_key?(vid_to)\n\t\t\t\t\t\thash_of_vertices[vid_to] = v2 \n\t\t\t\t\t\tProcessLogger.log(\"\\t Vertex #{vid_to} loaded\")\n\t\t\t\t\tend\n\n\t\t\t\t\tedge = Edge.new(v1, v2, speed, is_one_way)\n\t\t\t\t\tlist_of_edges << edge\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\tif load_cmd.end_with?(\"-comp\")\n\t\t\tlist_of_edges, hash_of_vertices = _process_comp(list_of_edges, hash_of_vertices)\n\t\tend\n\n\t\t# process visual vertices\t\n\t\tProcessLogger.log(\"Processing vertices\")\n\t\tnodes = osm.xpath(\"//node\")\n\t\tnodes.each do |node|\n\t\t\tvid = node[\"id\"]\n\t\t\tunless hash_of_vertices.has_key?(vid)\n\t\t\t\tnext\n\t\t\tend\n\n\t\t\tvertex = hash_of_vertices[vid]\n\t\t\tlat = node[\"lat\"]\n\t\t\tlon = node[\"lon\"]\n\t\t\tx = lon.to_f * 100\n\t\t\ty = lat.to_f * 100\n\t\t\t\t\t\n\t\t\thash_of_visual_vertices[vid] = VisualVertex.new(vid, vertex, lat, lon, y, x)\n\t\t\tProcessLogger.log(\"\\t Visual vertex #{vid} in \")\t\t\t\n\t\tend\n\t\tedge_map = {}\n\t\t# process visual edges\n\t\tlist_of_edges.each do |edge|\t\t\n\t\t\tv1 = hash_of_visual_vertices[edge.v1.id] if hash_of_visual_vertices.has_key?(edge.v1.id)\n\t\t\tv2 = hash_of_visual_vertices[edge.v2.id] if hash_of_visual_vertices.has_key?(edge.v2.id)\n\t\t\tedge.length = _calc_geo_distance(v1.lon.to_f, v1.lat.to_f, v2.lon.to_f, v2.lat.to_f)\n\t\t\tv_edge = VisualEdge.new(edge, v1, v2) if v1 && v2\n\t\t\tlist_of_visual_edges << v_edge\n\n\t\t\t# process to edge_map\n\t\t\tif edge_map.has_key?(edge.v1.id)\n\t\t\t\tedge_map[edge.v1.id][edge.v2.id] = v_edge\n\t\t\telse\n\t\t\t\tedge_map[edge.v1.id] = { edge.v2.id => v_edge }\n\t\t\tend\t\n\t\t\t\n\t\t\tif edge.one_way == false \n\t\t\t\tif edge_map.has_key?(edge.v2.id)\n\t\t\t\t\tedge_map[edge.v2.id][edge.v1.id] = v_edge\n\t\t\t\telse\n\t\t\t\t\tedge_map[edge.v2.id] = { edge.v1.id => v_edge }\n\t\t\t\tend\t\n\t\t\tend\n\t\tend\n\t\t\n\t\t# get bounds hash from OSM\n\t\tosm_bounds = osm.at_xpath(\"//bounds\")\n\t\tbounds = {:minlat => osm_bounds[\"minlat\"], :minlon => osm_bounds[\"minlon\"], :maxlat => osm_bounds[\"maxlat\"], :maxlon => osm_bounds[\"maxlon\"]}\n\t\t# multiply each bound by 100\n\t\tbounds.map {|key, val| bounds[key] = val.to_f * 100 }\n\n\t\t# puts \"hash_of_vertices: #{hash_of_vertices.count}, list_of_edges: #{list_of_edges.count}\"\n\t\t# puts \"hash_of_visual_vertices: #{hash_of_visual_vertices.count}, list_of_visual_edges: #{list_of_visual_edges.count}\"\n\t\t\n\t\tg = Graph.new(hash_of_vertices, list_of_edges, edge_map)\n\t\tvg = VisualGraph.new(g, hash_of_visual_vertices, list_of_visual_edges, bounds)\n\t\t\n\t\t\n\t\tprint \"Loaded Graph containing #{hash_of_vertices.length} nodes. \\n\"\n\t\t\n\t\treturn g, vg\t\n\tend",
"def respond(message)\n=begin\n If a joining message adds address to routing table and gateway table before sending a routing info message\n to it and a joining relay message to a node with a GUID closer to the joining node\n=end\n if message[\"type\"] == \"JOINING_NETWORK\"\n tnh, tm, tn = nextHop(message[\"node_id\"])\n @gateway_table[message[\"node_id\"]] = {:ip_address => message[\"ip_address\"], :port => message[\"port\"]}\n if @routing_table.has_key?([0, tm, tn]) == false\n @routing_table[[0, tm, tn]] = {:node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}\n end\n if tnh.ip != nil\n joinMsgRelay = {:type => \"JOINING_NETWORK_RELAY\", :node_id => message[\"node_id\"], \\\n :gateway_id => @guid, :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}.to_json\n @socket.send joinMsgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push(addr)\n }\n routingInfoMsg = {:type => \"ROUTING_INFO\", :gateway_id => @guid, :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable}.to_json\n @socket.send routingInfoMsg, 0, message[\"ip_address\"], message[\"port\"]\n end\n\n if message[\"type\"] == \"JOINING_NETWORK_RELAY\"\n tnh, tm, tn = nextHop(message[\"node_id\"])\n nh, gm, gn = nextHop(message[\"gateway_id\"])\n if @routing_table.has_key?([0, tm, tn]) == false\n #puts \"h6\"\n @routing_table[[0, tm, tn]] = {:node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}\n end\n if tnh.ip != nil\n joinMsgRelay = {:type => \"JOINING_NETWORK_RELAY\", :node_id => message[\"node_id\"], \\\n :gateway_id => message[\"gateway_id\"], \\\n :ip_address => message[\"ip_address\"], :port => message[\"port\"]}.to_json\n @socket.send joinMsgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push(addr)\n }\n routingInfoMsg = {:type => \"ROUTING_INFO\", :gateway_id => message[\"gateway_id\"], :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable}.to_json\n if nh.ip != nil\n @socket.send routingInfoMsg, 0, nh.ip, nh.port\n end\n end\n\n=begin\n when getting a routing info message extract as much useful information out of it as we can and forward it onto the\n intended target node unless it was intended for our node\n=end\n if message[\"type\"] == \"ROUTING_INFO\"\n routeInfo(message[\"route_table\"])\n if message[\"node_id\"] == @guid\n return\n elsif message[\"gateway_id\"] == @guid\n if @gateway_table.has_key?(message[\"node_id\"])\n p @socket.send message.to_json, 0, @gateway_table[message[\"node_id\"]][:ip_address].to_s, @gateway_table[message[\"node_id\"]][:port]\n else\n puts \"Routing_Info message receave error not key in gatewayTable!\"\n end\n else\n nh, gm, gn = nextHop(message[\"node_id\"])\n message = message.to_json\n if nh.ip != nil\n @socket.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n # If get a leaving message, remove the node from the network\n if message[\"type\"] == \"LEAVING_NETWORK\"\n removeAddr(message[\"node_id\"])\n end\n\n # When receive an chat message,check if it is intended for\n # If not, forward to next hop\n if message[\"type\"] == \"CHAT\"\n if message[\"target_id\"] == @guid\n flag = true\n for i in 0..@postHash.length-1\n if @postHash[i][:text] == message[\"post\"]\n flag = false\n end\n end\n if flag\n @postHash << {:text => message[\"post\"]}\n end\n ackChatMsg = {:type => \"ACK_CHAT\", :node_id => message[\"sender_id\"], :Tag => message[\"Tag\"]}.to_json\n if message[\"sender_id\"] == @guid\n puts \" \"\n print @name, \" CHATTING WITH YOURSELF\" # If processes own chatting message, no need to send an ACK\n puts \" \"\n return\n end\n nh, sm, sn = nextHop(message[\"sender_id\"])\n @socket.send ackChatMsg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop(message[\"target_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n # Keep forwarding until this ACK_CHAT message reaches its destination\n if message[\"type\"] == \"ACK_CHAT\"\n if message[\"node_id\"] == @guid\n tagHash = Hash_Func(message[\"Tag\"])\n @chatAckWait[tagHash] = 2\n else\n nh, m, n = nextHop(message[\"node_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n=begin\n Keep forwarding chat_retrieve message until it reaches correct location in which case appending @postHash to a\n chat response message and send it to the sender ID\n=end\n if message[\"type\"] == \"CHAT_RETRIEVE\"\n if message[\"node_id\"] == @guid\n chatresponse_msg = {:type => \"CHAT_RESPONSE\", :tag => message[\"tag\"], :node_id => message[\"sender_id\"],\n :sender_id => @guid, :response => @postHash}.to_json\n nh, sm, sn = nextHop(message[\"sender_id\"])\n @socket.send chatresponse_msg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop(message[\"node_id\"])\n message = message.to_json\n if nh.ip != nil\n @socket.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n=begin\n Keep forwarding response until reach intended recipient and then put results in flag.\n Original chat_retrieve thread can process the results\n=end\n if message[\"type\"] == \"CHAT_RESPONSE\"\n if message[\"node_id\"] == @guid\n @chat_retrieveAckWait[message[\"sender_id\"]] = message[\"response\"]\n else\n nh, tm, tn = nextHop(message[\"node_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Upon receiving a PING, sending to next hop and generating ACK\n if message[\"type\"] == \"PING\"\n ackMsg = {:type => \"ACK\", :node_id => @guid, :ip_address => @localInetAddr.ip, \\\n :port => @localInetAddr.port}.to_json\n @socket.send ackMsg, 0, message[\"ip_address\"], message[\"port\"]\n if message[\"target_id\"] != @guid\n #puts @name, \"PNH\", message[\"target_id\"], Time.now\n nh, m, n = nextHop(message[\"target_id\"])\n if nh.ip != nil\n message[\"ip_address\"] = @localInetAddr.ip\n message[\"port\"] = @localInetAddr.port\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Receiving an ACK message proves the node is still alive\n if message[\"type\"] == \"ACK\"\n @checkAckWait[message[\"node_id\"]] = 2\n end\n end",
"def plan(s1, s2)\r\n if s1 == s2\r\n return []\r\n end\r\n\r\n condensed_path = Array.new\r\n full_path = Array.new\r\n temp = BFS.new(graph, find_node(s1)).shortest_path_to(find_node(s2))\r\n\r\n temp.each {|x| full_path.push(x.to_s)}\r\n condensed_path.push(full_path.first)\r\n condensed_path = condensed_path + transfer_stations(full_path)\r\n \r\n if condensed_path.last != full_path.last #need to test this more\r\n condensed_path << full_path.last\r\n end\r\n\r\n return condensed_path\r\n end",
"def dfs1(graph, start_vertex)\n\tstack = [start_vertex]\n\tvisited = []\n\n\tuntil stack.empty?\n\t\tcurr_vertex = stack[-1]\n\n\t\tif !graph[curr_vertex] || graph[curr_vertex][0] \n\t\t\t$finishing_time += 1\n\t\t\t$magic_order[$finishing_time] = curr_vertex\n\t\t\tstack.pop\n\t\telse\n\t\t\tmore = []\n\t\t\tgraph[curr_vertex][0] = true\n\n\t\t\tif graph[curr_vertex][2..-1]\n\t\t\t\tgraph[curr_vertex][2..-1].each do |edge|\n\t\t\t\t\tif !graph[edge] && !visited.include?(edge)\n\t\t\t\t\t\tmore << edge\n\t\t\t\t\t\tvisited << edge\n\t\t\t\t\telsif !graph[edge]\n\t\t\t\t\t\tnext\n\t\t\t\t\telsif !graph[edge][0]\n\t\t\t\t\t\tmore << edge \n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tif more.empty?\n\t\t\t\t$finishing_time += 1\n\t\t\t\t$magic_order[$finishing_time] = curr_vertex\n\t\t\t\tstack.pop\n\t\t\telse\n\t\t\t\tstack.concat(more)\n\t\t\tend\n\t\tend\n\tend\nend",
"def directcommand(server,msg)\n tmp=nil\n if(msg[0]==\":\")\n tmp=Message.new(msg)\n else\n tmp=Message.new(\":* \"+msg)\n end\n \n case tmp.command\n when Event::RECV_CMND_QUIT,\n Event::RECV_CMND_PRIVMSG,Event::RECV_CMND_NOTICE\n @connector.write(server,msg,true)\n else\n @connector.write(server,msg)\n end\n end",
"def neigh_command_builder(name, cmd, opts)\n command_builder(\"neighbor #{name} #{cmd}\", opts)\n end",
"def draw_node(dx, dy, x, y, connections, type, scale)\n draw_x = dx + x*$node_size + $node_size / 2.0\n draw_y = dy + y*$node_size + $node_size / 2.0\n Node.create({:x => draw_x, :y => draw_y, :factor_x => scale, :factor_y => scale}, type)\n n, s, e, w = connections.values\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 0, :factor_x => scale, :factor_y => scale) if n == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 180, :factor_x => scale, :factor_y => scale) if s == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 90, :factor_x => scale, :factor_y => scale) if e == 1\n OutConnector.create(:x => draw_x, :y => draw_y,:angle => 270, :factor_x => scale, :factor_y => scale) if w == 1\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 0, :factor_x => scale, :factor_y => scale) if n == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 180, :factor_x => scale, :factor_y => scale) if s == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 90, :factor_x => scale, :factor_y => scale) if e == 2\n InConnector.create(:x => draw_x, :y => draw_y,:angle => 270, :factor_x => scale, :factor_y => scale) if w == 2\n end",
"def path_from_src_to_dest(graph, src=0, dest=0)\n\t\t# Update source and destination\n\t\t@source, @destination = src, dest\n\n\t\t# Check if source is undefined, if so return empty path\n\t\tif @source == 0\n\t\t\treturn []\n\t\tend\n\n\t\t# Generate a connections hash based on graph edges\n\t\toutgoing = Hash.new()\n\t\tnodes = graph.nodes.keys\n\t\tresult = Array.new()\n\n\t\tgraph.nodes.keys.each {|key| outgoing[key] = Hash.new() }\n\t\tgraph.edges.values.each do |edge|\n\t\t\t# Is it possible for any two issues to have multiple links\n\t\t\t# between them?\n\t\t\toutgoing[edge.a.id][edge.b.id] = edge\t\t\n\t\tend\n\n\t\t# If an edge already exists in the graph from source to destination\n\t\tif outgoing[@source].has_key?(@destination)\n\t\t\tresult.push(outgoing[@source][@destination].id)\n\t\t\treturn result\n\t\tend\n\t\t\t\n\t\t# Compute all paths from source\n\t\tpaths_tracer, paths_distances, relationships_on_paths = compute_paths_from_source(outgoing, nodes)\n\t\t\n\t\t# Find the shortest path through the graph between source and destination\n\t\tif destination != 0\n\t\t\treturn trace_path_src_to_dest(outgoing, paths_tracer)\n\t\tend\n\n\t\t# This happens only if the destination is 0, as it would have returned otherwise.\n\t\t# Return available relationships, distances, \n\t\treturn important_relationships_from_source(paths_tracer, paths_distances, relationships_on_paths)\n\tend",
"def build_sketch_graph\n\t@temp_hop_record = Hash.new\n\t@processed_list = Hash.new\n\t$node_list.each do |n|\n\t\t#Nodes in sketched graph: queries, user_inputs\n\t\t#if n.getInstr.getFromUserInput or (n.isQuery? and n.isWriteQuery?) or (n.getInstr.instance_of?AttrAssign_instr and n.getInstr.getFuncname.index('!') == nil)\n\t\tif n.isQuery? #or n.getInstr.getFromUserInputor isTableAttrAssign(n) \n\t\t\tn.Tnode = TreeNode.new(n)\n\t\t\t$sketch_node_list.push(n.Tnode)\t\n\t\t\t@temp_hop_record[n] = Array.new\n\t\t\t@processed_list[n] = Array.new\n\t\t\t@temp_hop_record[n].push(n)\n\t\tend \n\tend\n\tfor i in 0...$node_list.length\n\t\tadded_edge = false\n\t\tno_changes = true\n\t\t$node_list.each do |n|\n\t\t\tif n.Tnode != nil\n\t\t\t\t@temp_hop_record[n].push(nil)\n\t\t\t\ttemp_node = @temp_hop_record[n].shift\n\t\t\t\tstep = 0\n\t\t\t\twhile temp_node != nil and step < 10000 do\n\t\t\t\t\tstep += 1\n\t\t\t\t\tno_changes = false\n\t\t\t\t\ttemp_node.getDataflowEdges.each do |e|\n\t\t\t\t\t\tif e.getToNode.Tnode != nil and e.getToNode != n\n\t\t\t\t\t\t\tif n.Tnode.hasChildren(e.getToNode.Tnode) == false and (n.getIndex < e.getToNode.getIndex)\n\t\t\t\t\t\t\t\tn.Tnode.addChildren(e.getToNode.Tnode, i)\n\t\t\t\t\t\t\t\t#puts \"\\tAdd edge: #{n.getIndex}:#{n.getInstr.toString} -> #{e.getToNode.getIndex}:#{e.getToNode.getInstr.toString}\"\n\t\t\t\t\t\t\t\tadded_edge = true\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif e.getToNode != n \n\t\t\t\t\t\t\t\tif @processed_list[n].include?e\n\t\t\t\t\t\t\t\telsif e.getToNode.getIndex < e.getFromNode.getIndex #returnv\n\t\t\t\t\t\t\t\t\te.getToNode.getDataflowEdges.each do |e1|\n\t\t\t\t\t\t\t\t\t\tif e1.getToNode.getIndex > temp_node.getIndex\n\t\t\t\t\t\t\t\t\t\t\t@temp_hop_record[n].push(e1.getToNode)\n\t\t\t\t\t\t\t\t\t\t\t@processed_list[n].push(e1)\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\telse\n\t\t\t\t\t\t\t\t\t@temp_hop_record[n].push(e.getToNode)\n\t\t\t\t\t\t\t\t\t@processed_list[n].push(e)\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\tend\n\t\t\t\t\ttemp_node = @temp_hop_record[n].shift\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tif added_edge\n\t\t\t#puts \"iteration #{i} ||\"\n\t\tend\n\t\tif no_changes\n\t\t\tbreak\n\t\tend\n\tend\n=begin\n\tgraph_write($graph_file, \"digraph sketch {\\n\")\n\t$node_list.each do |n|\n\t\tif n.Tnode != nil\n\t\t\tif n.isQuery?\n\t\t\t\tcolor = \"blue\"\n\t\t\telsif n.getInstr.instance_of?AttrAssign_instr\n\t\t\t\tcolor = \"darkorange\"\n\t\t\telse\n\t\t\t\tcolor = \"crimson\"\n\t\t\tend\n\t\t\tgraph_write($graph_file, \"\\tn#{n.getIndex} [label=<<i>#{n.getIndex}__#{n.getInstr.toString2}</i>> color=#{color}]; \\n\")\n\t\t\tn.Tnode.children.each do |c|\n\t\t\t\tgraph_write($graph_file, \"\\tn#{n.getIndex} -> n#{c.node.node.getIndex} [label=\\\"#{c.dist}\\\"]\\n\")\n\t\t\tend\n\t\tend\n\tend\n\tgraph_write($graph_file, \"}\")\n=end\nend",
"def seek_from_node(starting_node)\n puts \"seek started from node #{starting_node.inspect}...\"\n \n # -- PART I -- (starting from one node for now...) \n visited_nodes = grow_basic_path([ starting_node ])\n \n puts \"got basic path of length #{visited_nodes.length}, moving on to IIa)...\"\n \n # -- PART II a) --\n if visited_nodes.length < nodes.length\n target_nodes = extract_target_nodes_from_path(visited_nodes)\n \n while target_nodes.length > 0\n puts \"TNL: #{target_nodes.length}\"\n visited_nodes = restructure_path(visited_nodes, target_nodes)\n target_nodes = extract_target_nodes_from_path(visited_nodes)\n end\n end\n \n puts \"...done, moving on to IIb)...\"\n \n # -- PART II b) --\n if visited_nodes.length < nodes.length\n visited_nodes = trim_and_extend_path(visited_nodes)\n end\n \n puts \"...done, moving on to IIc)...\"\n \n # -- PART II c) --\n if visited_nodes.length < nodes.length\n visited_nodes = trim_and_extend_path(visited_nodes.reverse)\n end\n \n # -- PART III --\n results = {}\n \n if visited_nodes.length < nodes.length \n results[:path] = visited_nodes\n else\n results[:tour] = visited_nodes\n \n cycle_starts = connected_to(visited_nodes.first).map do |node|\n visited_nodes[visited_nodes.index(node) - 1]\n end\n cycle_ends = connected_to(visited_nodes.last)\n \n (cycle_starts & cycle_ends).each do |node|\n index = visited_nodes.index(node)\n \n circuit = visited_nodes[0..index] + [ visited_nodes.last ]\n circuit += visited_nodes[(index + 1 - visited_nodes.length)..-2].reverse\n \n results[:cycles] ||= []\n results[:cycles] << circuit\n end\n end\n \n results\n end",
"def Graph(str)\n graph = Graph.new\n nodes = {}\n str.lines.each do |line|\n case line\n when /^\\s*(\\w+):(.*)$/\n name,code = $~[1,2]\n graph << (nodes[name] = eval(code))\n when /^\\s*(\\w+)\\s*->\\s*(\\w+)((\\s*->\\s*\\w+)*)\\s*(#.*)?$/\n name1,name2,others = $~[1,3]\n [name1,name2].each do |name|\n raise \"Undefined node: #{name} on line: #{line}\" if not nodes.key? name\n end\n nodes[name1].out << nodes[name2]\n \n if others != \"\"\n # repeat on the part of this line which we have not processed yet\n line = name2+others\n redo\n end\n when /^\\s*(#.*)?$/\n next\n else\n raise \"Couldn't parse this line: #{line}\"\n end\n end\n raise \"No start node defined! There should be a node called START.\" if not nodes.key? 'START'\n graph.start = nodes['START']\n graph\nend",
"def detect_cycle_in_graph(edges)\nend",
"def push_edge(edge)\n if @leader.nil?\n @leader = edge.node1.leader\n edge.node2.leader = @leader\n else\n edge.node1.leader = @leader\n edge.node2.leader = @leader\n end\n \n adj_edge1_index = $vertices[edge.node1.node].first # we could select here first edge since \n adj_edge2_index = $vertices[edge.node2.node].first # they all are adjacent\n\n if adj_edge2_index && adj_edge1_index\n puts \"adj_edge1_index - #{adj_edge1_index}, adj_edge2_index - #{adj_edge2_index}\"\n end\n\n adj_edge1 = $edges[adj_edge1_index]\n adj_edge2 = $edges[adj_edge2_index]\n\n # 3 branches should be considered\n # 1st - edge is merged to only scc with adj edge1 o--o--o o----o \n # 2nd - edge is merged to only scc with adj edge2 o--o o--o----o\n # 3rd - edge is merged to scc1 or scc2 and these sccs are merges as well o--o---o--o\n\n if adj_edge1 && adj_edge2\n if adj_edge1.scc && adj_edge2.scc # merging 2 SCCs\n puts \"merging sccs\"\n if adj_edge1.scc.count > adj_edge2.scc.count\n @vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n # change leaders of SCC of adjacent edge 2\n adj_edge2.scc.vertices.each{|v| v.node.leader = adj_edge1.scc.leader }\n adj_edge2.scc.edges.each{|e| e.scc = adj_edge1.scc}\n @mst.delete_scc(adj_edge2.scc) # remove SCC from the list\n else\n @vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n # change leaders of SCC of adjacent edge 1\n adj_edge1.scc.vertices.each{|v| v.node.leader = adj_edge2.scc.leader }\n adj_edge1.scc.edges.each{|e| e.scc = adj_edge2.scc}\n @mst.delete_scc(adj_edge1.scc) # remove SCC from the list\n end\n elsif adj_edge1.scc || adj_edge2.scc\n scc = adj_edge1.scc || adj_edge2.scc # only one should be available\n @vertices.each{ |v| v.node.leader = scc.leader }\n puts 'adding edge ' + edge.inspect + ' to scc ' + scc.inspect\n end\n else\n @vertices << edge.node1\n @vertices << edge.node2\n @edges << edge\n end\n\n edge.scc = self # save link to the SCC in the edge itself\n end",
"def solve\n graph = Graph.create(words, WordNode)\n graph.connect_nodes(:one_char_diff)\n\n end_node = graph.nodes_hash[end_word]\n start_node = graph.nodes_hash[start_word]\n start_node.cost = 0\n\n heap = Containers::Heap.new { |a, b| (a.cost <=> b.cost) == -1 }\n graph.nodes_hash.each do |k, v|\n heap.push v\n end\n\n puts heap.size\n # puts \"is empty?#{heap.empty?}\"\n until heap.empty? do\n current_node = heap.pop\n puts current_node.value, current_node.cost\n # puts current_node == end_node\n # puts current_node.value, end_node.value\n return graph.path(end_node) if current_node == end_node\n\n current_node.connected_nodes.each do |node|\n\n # puts node.visited\n unless node.visited\n cost = current_node.cost + 1\n if cost < node.cost\n node.cost = cost\n node.parent = current_node\n # puts \"changed parent\"\n # puts node.parent\n end\n end\n end\n\n current_node.visited = true\n end\n end",
"def enum_moves\n @scratch = dup_maze(@maze)\n @locs.each_with_index do |loc, robot|\n @cost = 1\n leading_edge = [loc]\n loop do\n next_edge = []\n leading_edge.each do |x, y|\n next_edge.concat search_from(x, y, robot)\n end\n break if next_edge.empty?\n leading_edge = next_edge\n @cost += 1\n end\n end\n\n @moves\n end",
"def distance *path\n cost, edge_exists = 0, false\n\n # Adds the cost of the next move\n neighbors = @nodes[path.shift]\n neighbors.each do |node|\n if node.dst == path.first\n edge_exists = true\n cost += node.length\n break\n end\n end\n\n # Iterates in depth when neighbor exists\n return -1 unless edge_exists\n if path.length > 1\n sub_cost = distance *path\n return -1 if sub_cost == -1\n cost += sub_cost\n end\n cost\n end",
"def find_path(char)\n # get pixel movement rate\n pix = $BlizzABS.pixel\n # use request\n request = @request[char]\n # if no nodes to test\n if request.open.size == 0\n # abort testing for this character\n @request.delete(char)\n # resets state\n char.ai.state = (char.ai.state == Invalid ? Return : Ready)\n # stop execution\n return []\n end\n # found\n found = false\n # find minimal key\n key = request.open.keys.min {|a, b|\n Math.hypot(a[0] - request.tx, a[1] - request.ty) <=>\n Math.hypot(b[0] - request.tx, b[1] - request.ty)}\n # this node is now logged as checked\n request.closed[key[0], key[1]] = request.open[key]\n # remove this node from the pending array\n request.open.delete(key)\n # iterate through all possible directions with relative offsets\n Cache::PathDirs.each {|dir|\n # coordinates of new position\n kx, ky = key[0] + dir[0], key[1] + dir[1]\n # if new coordinates are destination\n if kx == request.tx && ky == request.ty\n # the new node was checked\n request.closed[kx, ky] = dir[2]\n # path was found\n found = true\n # stop checking\n break\n # if new node not checked yet and coordinates are passable\n elsif request.closed[kx, ky] == 0 &&\n char.passable?(key[0] * pix, key[1] * pix, dir[2])\n # add new node to be checked\n request.open[[kx, ky]] = dir[2]\n end}\n # stop execution except if found path\n return nil unless found\n # backtrack the path\n result = request.backtrack\n # finish testing for this character\n @request.delete(char)\n # resets state\n char.ai.state = (char.ai.state == Invalid ? Return : Ready)\n # return movement command array\n return result\n end",
"def peek(args={})\n\t\t\tpeek_data = [\"6 \"]\n\t\t\tpeek_data << \"%-5d\" % self.to_s.size\n\t\t\tpeek_data << \"%-31s\" % self.ipv6_saddr\n\t\t\tpeek_data << \"-> \"\n\t\t\tpeek_data << \"%-31s\" % self.ipv6_daddr\n\t\t\tpeek_data << \" N:\"\n\t\t\tpeek_data << self.ipv6_next.to_s(16)\n\t\t\tpeek_data.join\n\t\tend",
"def find_shortest_path(initial_node, final_node)\n\t\tunless @nodes.include?(initial_node) && @nodes.include?(final_node)\n\t\t raise(\"Either of the nodes not found in the Graph\") \n\t\tend\n\t\tdistance = {}\n\t previous = {}\n\t\tdistance[initial_node] = 0 # Distance from initial_node to initial_node\n\t previous[initial_node] = nil\n\t\tnodes_counted = @nodes\n\t\t\t\n\t\tnodes_counted.each do |n|\n\t\t if n != initial_node \n\t\t\t distance[n] = Float::INFINITY # Unknown distance function from initial_node to final_node\n\t\t\t previous[n] = nil \t # Previous node in optimal path from initial_node\n\t\t\tend\n\t\tend\n\n\t\tuntil nodes_counted.empty? \n\t\t\n\t\t\tu = distance.select{|k,v| nodes_counted.include?(k)}.min_by{|k,v| v}.first # Source node in first case\n\t\t\tbreak if (distance[u] == Float::INFINITY)\n\t\t\tnodes_counted.delete(u)\n\t\t\t\n\t\t\t@paths[u].keys.each do |v|\n\t\t\t\talt = distance[u] + @paths[u][v]\n\t\t\t\tif alt < distance[v] # A shorter path to v has been found\n\t\t\t\t\tdistance[v] = alt\n\t\t\t\t\tprevious[v] = u\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t \n\t\tpath = []\n\t\tcurrent = final_node\n\t\twhile current\n\t\t\tpath.unshift(current)\n\t\t\tcurrent = previous[current]\n\t\tend\n \n\t\treturn distance[final_node], path\n\n\tend",
"def get_edge(edge)\n return nil unless edge[:from][:name]\n return nil unless edge[:to][:name]\n\n #Get the type of the edge\n type = edge[:type] || Config::DEFAULT_TYPE\n edge[:type] = type\n\n #Check if the edge type exists\n etype = Marshal.load(@db.m_get(\"edge#{type}\") || Marshal.dump({})) \n \n #Integrity check: Check whether the edge direction is not contradictory\n if edge[:directed]\n if etype[:directed] != nil\n if etype[:directed] != edge[:directed]\n return nil\n end\n else\n #If there is no edge of that type then pre-empt the result\n return nil\n end\n else\n if etype[:directed] != nil\n edge[:directed] = etype[:directed]\n else\n #If there is no edge of that type then pre-empt the result\n return 3\n end\n end\n\n #Convert the edge into a Key string and fetch the corresponding data\n key, reverse_key = Keyify.edge(edge)\n value = @db.e_get(key)\n\n if value\n new_edge = Marshal.load(value)\n new_edge[:from] = self.get_node(edge[:from])\n new_edge[:to] = self.get_node(edge[:to])\n new_edge[:type] = edge[:type]\n new_edge[:directed] = etype[:directed] #Pick direction alone from the meta_db for consistency\n new_edge\n end\n end",
"def create_sub_graph(spec_edges, move_dist = nil)\n # declare locals\n time = Time.now\n m = $game_map\n map_width,map_height = m.width, m.height\n MoveUtils.init_ev_passables\n \n if !move_dist\n dist = spec_edges[:move] ||= TactBattleManager::Defaults::Move\n else\n dist = move_dist\n end\n \n x_low = x_high = y_low = y_high = nil\n if @source\n x_low, x_high = [@source.x-dist, 0].max, [@source.x+dist,map_width-1].min\n y_low, y_high = [@source.y-dist, 0].max, [@source.y+dist,map_height-1].min \n else\n x_low, x_high = 0, [dist,map_width-1].min\n y_low, y_high = 0, [dist,map_height-1].min\n end\n \n @jump_time = 0\n @optim_cache = {}\n x_low.upto(x_high).each do |x|\n y_low.upto(y_high).each do |y|\n expand_graph_adj(v=Vertex.new(x,y, m.terrain_tag(x,y)), spec_edges[:pass])\n add_adjacent_jumpables(v.x,v.y,dist,spec_edges)if spec_edges[:jump_length]>0\n end\n end\n self\n end",
"def shortest_route visit_path, dst, condition=nil\n return route(visit_path, dst).first.cost\n end",
"def execute(val)\n @mResult = \"\"\n id = 0\n rid = Hash.new\n commandParser(val)\n\n addressArr = [\"Ave.\",\"St.\",\"Way\",\"Cir\",\"Dr\",\"Rd\",\"Ct\",\"Trl\",\"Blvd\"]\n @mIterations.times { \n @mCommand.split.each{ |option|\n\n nodelim = false\n \n case option\n when \"id\" # TODO\n @mResult += id.to_s\n when \"rid\" # This method might be a bit slow. Recheck in the future. \n tmp = 0\n while rid[tmp] != true do\n tmp = rand(4000000000) # Assuming that rid is a standard int\n rid[tmp] = true\n end\n @mResult += tmp.to_s\n when \"surname\" \n @mResult += @mSurnames.sample\n when \"address\" \n @mResult += @mWords.sample.capitalize + \" \" + @mWords.sample.capitalize + \" \" + addressArr.sample\n when \"name\" \n @mResult += @mNames.sample\n when \"post\"\n @mResult += (65 + rand(26)).chr + rand(9).to_s + (65 + rand(26)).chr + rand(9).to_s + (65 + rand(26)).chr + rand(9).to_s\n when \"age\"\n @mResult += (rand(40) + 14).to_s\n when \"phone\"\n @mResult += (100+rand(899)).to_s + \"-\" + (\"%04d\" % rand(9999))\n when \"alpha\"\n @mResult += (97 + rand(26)).chr\n when \"ALPHA\"\n @mResult += (65 + rand(26)).chr\n when \"num\"\n @mResult += (rand(10)).to_s # 0 -> 9\n when \"date\"\n month = rand(12) + 1\n t = Time.utc(1970+rand(500), month, 1+rand(31), 1+rand(23),rand(60),rand(60)) \n @mResult += t.year.to_s + \"-\" + \"%02d\" % t.mon + \"-\" + \"%02d\" % t.day\n when \"time\"\n t = Time.utc(1970+rand(500), month, 1+rand(31), 1+rand(23),rand(60),rand(60)) \n @mResult += t.hour.to_s + \":\" + t.min.to_s + \":\" + t.sec.to_s\n when \"space\" # TODO\n @mResult += \" \" \n nodelim = true\n when \"null\" # TODO\n @mResult += @mDelim2 \n when /word/\n (option.to_i == 0 ? 1 : option_to_i).times{ @mResult += @mWords.sample }\n when /range/ # TODO \n # We calculate the offset\n exp = option.split(/range/i)\n exp[0] = exp[0].to_i\n exp[1] = exp[1].to_i\n x = [exp[0], exp[1]].max + 1\n y = [exp[0], exp[1]].min - 1\n @mResult += (rand(x-y)+y).to_s\n when /list/\n @mResult += option.gsub(/list/, '').gsub(/=/, '').split(',').sample\n when /man/\n @mResult += option.gsub(/man/, '').gsub(/=/, '')\n when \"back\"\n 2.times { @mResult.chop! }\n when \"nodelim\" \n nodelim = true\n when \"%\"\n nodelim = true\n end # end the big case!\n \n @mResult += @mDelim1 \n \n if nodelim\n # chop the delim1\n (@mDelim1.length + 1).times{ @mResult.chop! }\n end\n } # end per field\n\n # need to chop the extra delim1\n @mDelim1.length.times{ @mResult.chop! }\n @mResult += @mDelim2\n\n } # end per row\n end",
"def parse_command(cmd)\n command = cmd.split(\" \")\n if command[0] == \"Driver\"\n @drivers << Driver.new(command[1])\n elsif command[0] == \"Trip\"\n @drivers.find {|d| d.name == command[1]}.\n trips << Trip.new(command[1], command[2], command[3], command[4])\n end\n end",
"def get_edge_distance_string(edge)\n begin\n dist = edge.distance_string\n rescue NoMethodError\n dist = (edge ? edge.to_s : nil)\n end\n dist\n end",
"def initialize(source_instance,transition) \n @number=0 \n @nodecost=0\n @passby=false\n @instance=source_instance\n @transition=transition\n @neighbours=[]\n \n @name = \"NODE \" +source_instance + \" - \" + transition.to_s \n \n end",
"def shortest_distance()\n min = 1000000\n s = \"\"\n @edges.each do |city, dests|\n dests.each do |dest|\n if min > dest.distance\n min = dest.distance\n s = \"#{city} to #{dest.name}\"\n end\n end\n end\n \"Shortest distance is #{min} from #{s}\"\n end",
"def shortest_paths(source, dest)\n\t\t\t@source = source\n\t\t\tdijkstra source\n\t\t\tprint_path dest\n\t\t\treturn @distance[dest]\n\t\tend",
"def conn_ip(n_s, n_d)\n nodes_to_addrs2 = File.readlines(ARGV[0])\n #puts \"\\nn_s = \" + n_s + \" n_d = \" + n_d\n \n n_s_ip_lines = nodes_to_addrs2.select{ |line| line =~ /#{n_s}\\s/ }\n #puts \"\\nPRINT N_S LINES\"\n #puts n_s_ip_lines\n\n\n n_s_ip = []\n n_s_ip_lines.each {|line|\n n_s_ip.push line.split[1..2].join('\\t')\n }\n\n #puts \"\\nPRINTING N_S IPs\"\n #puts n_s_ip\n \n\n n_d_ip_lines = nodes_to_addrs2.select { |line| line =~ /#{n_d}\\s/ }\n #puts \"\\nPRINTING N_D LINES\"\n #puts n_d_ip_lines\n\n\n n_d_ip = []\n n_d_ip_lines.each {|line|\n n_d_ip.push line.split[1..2].join('\\t')\n }\n #puts \"\\nPRINTING N_D IPs\"\n #puts n_d_ip\n\n n_s_ip.each{ |s_ip| \n n_d_ip.each{ |d_ip|\n if ((destination_of_addr s_ip) == d_ip)\n #puts \"CONNECTION WITH \" + d_ip\n return d_ip\n end\n }\n }\nend",
"def save_message_from(n, delta)\n incoming[neighbors.index(n)] = delta\n end",
"def travel_time_and_cost\n cost = 0\n travel_time = 0\n (@path.size - 1).times do |i|\n current_vertex = @path[i]\n next_vertex = @path[i+1]\n # travel time = travel distance\n distance = Vertex.euclidean_distance(current_vertex, next_vertex)\n travel_time += distance\n # calculate how early or how late is service\n early_cost = (next_vertex.ready_time - travel_time) > 0 ? (next_vertex.ready_time - travel_time) : 0\n late_cost = (travel_time - next_vertex.due_time) > 0 ? (travel_time - next_vertex.due_time) : 0\n # calculate penalty cost\n cost += early_cost * @penalty_coefficient + late_cost * @penalty_coefficient\n # add service_time and early_cost (wait-for-service time) to travel time\n travel_time += next_vertex.service_time + early_cost\n end\n return cost, travel_time\n end",
"def onrecv(id, msg)\n\tscore = W1*msg[3]-W2*msg[2]\n\te = $rt[id, msg[0]]\n\treturn if e != nil && score <= e[4]\n\t$rt[id, msg[0]] = msg + [score]\n\tNODES.times do |i|\n\t\tif $matadj[id, i] > 0\n\t\t\tonrecv(i, [msg[0], id, msg[2] + 1, min($bandwidth[id], msg[3])])\n\t\tend\n\tend\nend",
"def get_message_from(n)\n incoming[neighbors.index(n)]\n end",
"def command(cmd)\n if VNMNetwork::COMMANDS.keys.include?(cmd.to_sym)\n cmd_str = \"#{VNMNetwork::COMMANDS[cmd.to_sym]}\"\n else\n cmd_str = \"#{cmd}\"\n end\n\n return cmd_str\n end",
"def generateplatform(edgefile,platformbase,opts)\n\n #===========================================================\n # Check inputs\n #===========================================================\n \n nodeperswitch=1;\n if opts.has_key?(:nodeperswitch)\n nodeperswitch=opts[:nodeperswitch].to_i;\t\n end\n corepernode=1;\n if opts.has_key?(:corepernode)\n corepernode=opts[:corepernode].to_i;\t\n end\n if !opts.has_key?(:networkmodel)\n opts[:networkmodel]=\"SMPI\"\n end\n if !opts.has_key?(:collselector)\n opts[:collselector]=\"mvapich2\"\n end\n if !opts.has_key?(:machinepower)\n # case Socket.gethostname\n # when /calc[0-9]/\n # opts[:machinepower]=50e9\n # STDOUT.puts \"Detected calcXX computer, hence I will assume host has #{opts[:machinepower]} Flops/sec power.\"\n # else\n # opts[:machinepower]=10e9\n # STDOUT.puts \"Unknown computer, hence using baseline host power #{opts[:machinepower]} Flops/sec\"\n # end\n opts[:machinepower]=NODEPOWER\n end\n if !opts.has_key?(:power)\n opts[:power]=NODEPOWER\n end\n if !opts.has_key?(:cablebw)\n opts[:cablebw]=CABLEBW\n end\n if !opts.has_key?(:switchbw)\n opts[:switchbw]=SWITCHBW\n end\n if !opts.has_key?(:switchlat)\n opts[:switchlat]=SWITCHLAT\n end\n if !opts.has_key?(:defaultdistance)\n opts[:defaultdistance]=DEFAULTDISTANCE\n end\n if !opts.has_key?(:unidirectional) && (edgefile.end_with?(\".unidir.edges\") || edgefile.end_with?(\"bFalse.edges\")) \n opts[:unidirectional]=true;\n end\n\t\n checkfile(edgefile,\"edgefile\")\n conn = MyMatrix.new.load_edgelist(edgefile,!(opts[:unidirectional]));\n\n \n #Not sure that the edge file provides the physical distance between racks.. So we say that if a length is below default distance, we force the default distance \n conn.map{ |d|\n if(d>0 && d< opts[:defaultdistance] )\n d=opts[:defaultdistance]\n end\n }\n STDOUT.puts \"Found #{conn.row_size} nodes in file #{edgefile}\"\n \n #Generate SimGrid platform\n simgridfile = File.new( \"#{platformbase}.xml\", 'w' )\n\n #Generate the platform configuration element string\n\n configString=\n\"<?xml version='1.0'?>\n<!DOCTYPE platform SYSTEM 'http://simgrid.gforge.inria.fr/simgrid.dtd'>\n<platform version='3'>\n <config>\n <prop id='maxmin/precision' value='1e-4'/> \n <prop id='network/model' value='#{opts[:networkmodel]}'/>\n <!-- Negative values enable auto-select... -->\n <prop id='contexts/nthreads' value='1'/>\n <!-- Power of the executing computer in Flop per seconds. Used for extrapolating tasks execution time by SMPI [default is 20000]-->\n <prop id='smpi/running_power' value='#{opts[:machinepower]}'/>\n <!-- Display simulated timing at the end of simulation -->\n <prop id='smpi/display_timing' value='1'/>\n <prop id='cpu/optim' value='Lazy'/>\n <prop id='network/optim' value='Lazy'/>\n <prop id='smpi/coll_selector' value='#{opts[:collselector]}'/>\n <prop id='smpi/cpu_threshold' value='0.00000001'/>\"\n\n if(opts[:addproperties])\n if(opts[:addproperties].class==\"String\")\n props=opts[:addproperties].split(\",\");\n opts[:addproperties]=Array.new\n props.each{ |pair| opts[:addproperties].push(pair.split(\"=\"))}\n end\n opts[:addproperties].each{ |e| e.each{ |propname,propvalue|\n configString+='<prop id='#{propname}' value='#{propvalue}' />\\n'\n } \n }\n end\n\n if opts[:tracing]\n configString+=\"\n <prop id='tracing' value='yes'/> \n <prop id='tracing/smpi' value='yes'/> \n <prop id='tracing/smpi/computing' value='yes'/>\"\n end\n\n configString+=\"\n </config>\n <AS id='AS0' routing='Floyd'>\n </AS>\n</platform>\"\n\n\n\n connectedSwitches=[]\n doc = Document.new(configString)\n\n platformas= doc.root.elements[2];\n\n #STDERR.puts doc.root.elements[1].inspect\n \n #platformas.add_element(Rexml::Comment(\"List of switches and associated hosts\"))\n #Generate one switch and associated nodes/links\n for i in 0...conn.row_size\n #Check whether this node is completely disconnected. If yes, discard it with warning\n\n haslink=false\n conn.each_link{ |li,lj,dist|\n if li == i || lj == i\n haslink=true\n break\n end\n }\n\n if !haslink\n STDERR.puts \"WARNING: Could not find links onward node #{i}, could be your topology does not include all nodes in [0,#{conn.row_size}[ (which is OK), or could be that the input topology is disconnected (which is probably NOT OK)! This node will not be included in platform.\"\n next\n end\n\n connectedSwitches.push(i)\n \n for j in 1..nodeperswitch\n platformas.add_element \"host\", {\n \"id\" => \"n#{i*nodeperswitch+j}\",\n \"power\" => opts[:power],\n \"core\" => corepernode\n }\t\n platformas.add_element \"link\", {\n \"id\" => \"linkn#{i*nodeperswitch+j}s#{i}\",\n \"bandwidth\" => opts[:cablebw],\n \"latency\" => latency_of(0)\n }\t\n end\n\n\n platformas.add_element \"link\", {\n \"id\" => \"ls#{i}\",\n \"bandwidth\" => opts[:switchbw],\n \"latency\" => opts[:switchlat]\n }\t\n\n platformas.add_element \"router\", {\n \"id\" => \"s#{i}\"\n }\n\n\n #Generate routes -Step 1-\n \n \n end\n\n \n \n #Generate inter-switch links\n conn.each_link{ |i,j,dist|\n platformas.add_element \"link\", {\n \"id\" => \"links#{i}s#{j}\",\n \"bandwidth\" => opts[:cablebw],\n \"latency\" => latency_of(dist)\n }\n\n }\n\n\n \n #Generate routes\n #For each physical link, we nee to traverse:\n #-> A Simgrid link representing the physical link with id linksxxsyy or linknxxsyy\n #-> A Simgrid link representing the limitations of the physical router/switch with id lsxxx\n #Since we need to cross the link emulating physical switch only once (we chose on input), we need non symmetrical routes.\n #And naturally, unidirectionnal topoloies are created only by not setting up the reciprocal route (from yy to xx)\n\n connectedSwitches.each{ |i|\n #for switch to node\n for j in 1..nodeperswitch\n route=platformas.add_element \"route\", {\n \"src\" => \"n#{i*nodeperswitch+j}\",\n \"dst\" => \"s#{i}\",\n \"symmetrical\" => \"NO\"\n }\n route.add_element \"link_ctn\", { \"id\" => \"linkn#{i*nodeperswitch+j}s#{i}\"}\n route.add_element \"link_ctn\", { \"id\" => \"ls#{i}\"}\n route2=platformas.add_element \"route\", {\n \"src\" => \"s#{i}\",\n \"dst\" => \"n#{i*nodeperswitch+j}\",\n \"symmetrical\" => \"NO\"\n }\n route2.add_element \"link_ctn\", { \"id\" => \"linkn#{i*nodeperswitch+j}s#{i}\"}\n end\n\n }\n\n\n \n #for inter-switches\t\n conn.each_link{ |i,j,dist|\n route=platformas.add_element \"route\", {\n \"src\" => \"s#{i}\",\n \"dst\" => \"s#{j}\",\n \"symmetrical\" => \"NO\"\n }\n route.add_element \"link_ctn\", { \"id\" => \"links#{i}s#{j}\"}\n route.add_element \"link_ctn\", { \"id\" => \"ls#{j}\"}\n\n if !opts[:unidirectional]\n route2=platformas.add_element \"route\", {\n \"src\" => \"s#{j}\",\n \"dst\" => \"s#{i}\",\n \"symmetrical\" => \"NO\"\n }\n route2.add_element \"link_ctn\", { \"id\" => \"links#{i}s#{j}\"}\n route2.add_element \"link_ctn\", { \"id\" => \"ls#{i}\"}\n end\n\n }\n\n doc.write(simgridfile,1,false);\t\n\n\n\n #Generate dummy (S)MPI platform file\n File.open(\"#{platformbase}.txt\", 'w') { |file| \n connectedSwitches.each{ |i|\n for j in 1..nodeperswitch\n file.write(\"n#{i*nodeperswitch+j}:#{corepernode}\\n\")\n end \n }\n }\n\n\n \n\n end",
"def parse(str)\n\t\tqueue = []\t\t # Queue of DNode-Instances, for the breadth first search in the decision tree\n\t\tstack = [start]\t # Stack of the NPDA\n\t\tindex = 0\t\t # Position in the input string\n#\t\tdebug \"STACK #{stack}\\n\"\n\t \n\t\twhile(!stack.empty? || index != str.length)\n\t\t\tif(!stack.empty? && stack.last.is_a?(String) && (stack.last.length <= str.length-index) && str[index...index+stack.last.length] == stack.last)\n\t\t\t\t# Accept-away the string (advance)\n\t\t\t\ttop = stack.pop\n#\t\t\t\tdebug(\"Akzeptiere String #{top.inspect}\\n\")\n\t\t\t\tindex += top.length\n\t\t\telsif(!stack.empty? && stack.last.is_a?(NonTerminal) && stack.last.rules.size == 1)\n\t\t\t\t# Apply rule directly, no decision neccessary\n\t\t\t\ttop = stack.pop\n#\t\t\t\tdebug \"#{top} : Direkt ersetzen -> #{top.rules[0]}\\n\"\n\t\t\t\tstack.concat(top.rules[0].reverse)\n\t\t\telse\n\t\t\t\tif(!stack.empty? && stack.last.is_a?(NonTerminal))\n\t\t\t\t\t# Queue decision\n\t\t\t\t\ttop = stack.pop\n#\t\t\t\t\tdebug \"#{top} : Einreihen\\n\"\n\t\t\t\t\tqueue.push(DNode.new(top, -1, stack, index, if(queue.empty?) then nil else queue.first end))\n\t\t\t\telse\n\t\t\t\t\t# Dead end - forget stack\n\t\t\t\tend\n\n\n\t\t\t\t# Apply nex dicision in the queue\n\t\t\t\tif(queue.empty? || (queue.first.index == queue.first.nonTerminal.rules.length - 1 && queue.size < 2))\n\t\t\t\t\t# Can't continue in the current path(branch), no other existing paths => Don't accept string\n\t\t\t\t\treturn nil\n\t\t\t\telse\n\t\t\t\t\tdecide = queue.first\n\t\t\t\t\tdecide.index = decide.index+1\n\t\t\t\t\t# Last decision for this DNode-object; take the next from the queue\n\t\t\t\t\tif(decide.index == decide.nonTerminal.rules.length)\n#\t\t\t\t\t\tdebug(\"#{queue.first.nonTerminal} : Dead end go to #{queue[1].nonTerminal}/#{queue[1].index+1}\")\n\t\t\t\t\t\tqueue.delete_at(0)\n\t\t\t\t\t\tdecide = queue.first\n\t\t\t\t\t\tdecide.index = decide.index+1\n\t\t\t\t\t\t\n#\t\t\t\t\t\tdebug(\"#{decide.nonTerminal}: Last Decision\")\n\t\t\t\t\telse\n\t\t\t\t\t\t# Next decision for this branch\n#\t\t\t\t\t\tdebug \"#{decide.nonTerminal}: Decide #{decide.index}\"\n\t\t\t\t\tend\n\t\t\t\t\t# Use the stack of this branch\n\t\t\t\t\tstack = decide.stack.clone\n#\t\t\t\t\tdebug \" ++ #{decide.nonTerminal.rules[decide.index]}\\n\"\n\t\t\t\t\t# Decided -> Apply production rule (Fill stack)\n\t\t\t\t\tstack.concat(decide.nonTerminal.rules[decide.index].reverse)\n\t\t\t\t\t# Jump to the position of this branch in the input string\n\t\t\t\t\tindex = decide.strIndex\n\t\t\t\tend\n\t\t\tend\n#\t\t\tdebug \"STACK #{stack}\\n\"\n\t\tend\n\t\t# Backtrace what decision was applied when, to generate array of indices of decisions (backwards)\n\t\ttrace = []\n\t\tif(!queue.empty?)\n\t\t\td = queue.first\n\t\t\ttrace << d.index\n\t\t\twhile(d.pnode != nil)\n\t\t\t\ttrace << d.pindex\n\t\t\t\td = d.pnode\n\t\t\tend\n\t\tend\n\t \n\t\t# Generate parser tree\n\t\troot = NTermInst.new(start)\n\t\tstack = [root]\n\t\twhile(!stack.empty?)\n\t\t\ttop = stack.pop()\n\t\t\t# What decision was done here\n\t\t\ttop.decision = if(top.nonTerminal.rules.size>1) then trace.pop() else 0 end\n\t\t \n\t\t\ts = top.nonTerminal.rules[top.decision].size\n\t\t\ttop.children = Array.new(s)\n\t\t \n\t\t\t# For all symbols on the right side of this production rule...\n\t\t\t(s-1).downto(0) { |i|\n\t\t\t\tsym = top.nonTerminal.rules[top.decision][i]\n\t\t\t\ttop.children[i] = if(sym.is_a?(String))\n\t\t\t\t\t# String ( = Sequence of terminal symbols) => Put into parser tree\n\t\t\t\t\tsym\n\t\t\t\telse\n\t\t\t\t\t# Non terminal symbols => to stack\n\t\t\t\t\tx = NTermInst.new(sym)\n\t\t\t\t\tstack.push(x)\n\t\t\t\t\tx\n\t\t\t\tend\n\t\t\t}\n\t\tend\n\t \n#\t\tdebug \"Accepting\\n\"\n\t\troot # Parserbaum zurückgeben\n\tend",
"def getDestination()\r\n\t\treturn @dnode\r\n\tend",
"def build_nodes_two(in_str)\n hash = Hash.new\n x,y = [0,0]\n dx, dy = [0,0]\n in_str.each do |str|\n dir = str[0]\n num = str[1..-1].to_i\n case dir \n when \"R\"\n r = (x + 1..(x + num))\n r.each do |i|\n dx += 1\n hash[[i,y]] = (dx + dy)\n x = i\n end \n when \"L\"\n r = ((x - num)...x)\n r.to_a.reverse.each do |i|\n dx += 1\n hash[[i,y]] = (dx + dy)\n x = i\n end \n when \"U\"\n r = (y + 1..y + num)\n r.each do |i|\n dy += 1\n hash[[x,i]] = (dx + dy)\n y = i\n end \n when \"D\"\n r = ((y - num)...y)\n r.to_a.reverse.each do |i|\n dy += 1\n hash[[x,i]] = (dx + dy)\n y = i\n end \n end \n end \n hash\nend",
"def traverse_graph(start_node_name, definitions, file_name)\n json_result = []\n all_paths = find_all_paths_from_node(start_node_name)\n all_paths = remove_subarrays(all_paths)\n\n all_paths.each do |path|\n p \"path: #{path}\"\n next if path.length < 2\n\n (0..path.length - 1).each do |i|\n break if i == path.length - 1\n break if @adj_matrix[path[i]].eql? nil\n break if @adj_matrix[path[i]][path[i + 1]].eql? nil\n\n @adj_matrix.fetch(path[i]).fetch(path[i + 1]).fetch('function')\n begin\n definitions.send(@adj_matrix.fetch(path[i]).fetch(path[i + 1]).fetch('function'))\n @adj_matrix[path[i]][path[i + 1]]['value'] = true\n rescue RuntimeError => e\n puts \"ERROR going from #{path[i]} to #{path[i + 1]}\"\n puts e.message.to_s\n # unless @adj_matrix[path[i]][path[i + 1]]['value'] = false\n # appended_error = @adj_matrix[path[i]][path[i + 1]]['label'].concat(\" \\nError: #{e.message}\")\n # @adj_matrix[path[i]][path[i + 1]]['label'] = appended_error\n # end\n @adj_matrix[path[i]][path[i + 1]]['value'] = false\n end\n\n temp = {}\n temp['source'] = path[i]\n temp['destination'] = path[i + 1]\n temp['label'] = @adj_matrix[path[i]][path[i + 1]]['label']\n temp['value'] = @adj_matrix[path[i]][path[i + 1]]['value']\n json_result.push(temp)\n end\n build_model(json_result, file_name)\n end\n build_model(json_result, file_name)\n end",
"def get_node_launch_command(node_info, mode, offset, nw_name)\n pwd = `pwd`.gsub(/\\n+/,\"\")\n ds = node_info.dir_structure\n if :docker.eql? mode\n docker_rpc_port = 6666\n docker_api_port = 7777\n \"docker run \\\n --name #{node_info.id} \\\n --hostname #{node_info.id} \\\n -e NODE_ID=#{node_info.id} \\\n -e ELECTION_TIMEOUT_MILLIS=3000 \\\n --mount type=bind,source=#{pwd}/#{ds.log},target=/node/cluster-data/log \\\n --mount type=bind,source=#{pwd}/#{ds.state},target=/node/cluster-data/state \\\n --mount type=bind,source=#{pwd}/#{ds.snapshot},target=/node/cluster-data/snapshot \\\n --mount type=bind,source=#{pwd}/#{ds.cluster},target=/node/cluster-data/cluster,readonly \\\n -p #{docker_api_port + offset}:#{docker_api_port} \\\n --network=#{nw_name} \\\n raft:local \\\n \".gsub(/\\s+/, \" \")\n else\n \"./raft \n --id=#{node_info.id} \\\n --api-port=#{node_info.api_port} \\\n --rpc-port=#{node_info.rpc_port} \\\n --log-entry-path=#{ds.log} \\\n --log-metadata-path=#{ds.log}/metadata.json \\\n --raft-state-path=#{ds.state}/state.json \\\n --election-timeout=3000 \\\n --rpc-timeout=2000 \\\n --api-timeout=2000 \\\n --api-fwd-timeout=1500 \\\n --max-conn-retry-attempts=5 \\\n --snapshot-path=#{ds.snapshot} \\\n --cluster-config-path=#{ds.cluster}/config.json \\\n \".gsub(/\\s+/, \" \")\n end\nend",
"def inspect\r\n @rules.each{|r|\r\n r[1].each{|d|\r\n print r[0].to_s + \" => \" + d[0].inspect + \" TXTO \" + d[1].inspect + \"\\n\"\r\n }\r\n }\r\n end",
"def reachable\n @vertices.each do |vk, is_up|\n if is_up\n print \"#{vk}\\n\"\n if @edges_up[vk]\n @edges_up[vk].each do |ek, up_too|\n if up_too\n print \" #{ek}\\n\"\n end\n end\n end\n end\n end\n end",
"def flags_and_opcode\n # 0 \n # 0 1 2 3 4 5 6 7\n # +-+-+-+-+-------\n # |F|R|R|R| opcode\n # |I|S|S|S| (4) \n # |N|V|V|V| \n # | |1|2|3| \n byte = get(@need).bytes.first\n @opcode = byte & 0xF # last 4 bites\n @fin = (byte & 0x80 == 0x80)# first bit\n\n #p :byte => byte, :bits => byte.to_s(2), :opcode => @opcode, :fin => @fin\n # mask_and_payload_length has a minimum length\n # of 1 byte, so start there.\n transition(:mask_and_payload_init, 1)\n\n # This state yields no output.\n return nil\n end",
"def thread_graph(out, t_id, info)\n total_calls = 0\n run_total = 0.0\n\n data = info[:nodes]\n\n methods = info[:methods]\n\n run_total = info[:runtime].to_f\n\n all_callers = Hash.new { |h,k| h[k] = [] }\n\n data.each do |n_id, n_data|\n n_data[4].each do |sub|\n all_callers[sub] << n_id\n end\n end\n\n indexes = data.keys.sort do |a, b|\n data[b][1] <=> data[a][1]\n end\n\n indexes = indexes.first(SHORT_LINES) unless options[:full_report]\n\n shown_indexes = {}\n\n indexes.each_with_index do |id, index|\n shown_indexes[id] = index + 1\n end\n\n out.puts \"===== Thread #{t_id} =====\"\n out.puts \"Total running time: #{sec(info[:runtime])}s\"\n out.puts \"index % time self children called name\"\n out.puts \"----------------------------------------------------------\"\n\n primary = \"%-7s%6s %8.2f %9.2f %8d %s [%d]\\n\"\n secondary = \" %8.2f %9.2f %8d %s%s\\n\"\n\n indexes.each do |id|\n m_id, total, called, tn, sub_nodes = data[id]\n\n # The idea is to report information about caller as a ratio of the\n # time it called method.\n #\n\n callers = all_callers[id].sort_by do |c_id|\n clr = data[c_id]\n\n clr[total]\n end\n\n callers = callers.first(10) unless options[:full_report]\n\n callers.each do |c_id|\n clr_m_id, clr_total, clr_called, clr_tn, clr_sub = data[c_id]\n\n sub_total = clr_sub.inject(0) { |a,s| a + data[s][1] }\n\n self_total = clr_total - sub_total\n out.printf(secondary, sec(self_total),\n sec(sub_total),\n clr_called,\n methods[clr_m_id][:name],\n graph_method_index(shown_indexes[c_id]))\n end\n\n # Now the primary line.\n\n children = sub_nodes.inject(0) { |a,s| a + data[s][1] }\n # children = method[:cumulative] * (method[:edges_total].to_f / method[:total])\n\n self_total = total - children\n out.printf primary, (\"[%d]\" % shown_indexes[id]),\n percentage(total, run_total, 1, nil),\n sec(self_total),\n sec(children),\n called,\n methods[m_id][:name],\n shown_indexes[id]\n\n # Same as caller, the idea is to report information about callee methods\n # as a ratio of the time it was called from method.\n #\n\n edges = sub_nodes.sort_by do |e_id|\n if edge = data[e_id]\n edge[1]\n else\n 0.0\n end\n end\n\n edges = edges.last(10) unless options[:full_report]\n # method[:edges] = method[:edges].first(10) unless options[:full_report]\n\n edges.reverse_each do |e_id|\n c_m_id, c_total, c_called, c_tn, c_sub_nodes = data[e_id]\n\n grandchildren = c_sub_nodes.inject(0) { |a,s| a + data[s][1] }\n grandchildren = 0 if grandchildren < 0\n\n self_total = c_total - grandchildren\n out.printf secondary, sec(self_total),\n sec(grandchildren),\n c_called,\n methods[c_m_id][:name],\n graph_method_index(shown_indexes[e_id])\n end\n\n out.puts \"-------------------------------------------------------\"\n end\n\n epilogue out, data.size, total_calls\n end",
"def distance_between_two_nodes(src_name, dest_name)\n\t\tpath = nil\n\n\t\tsrc_node = @graph.get_node(src_name)\n\t\tif src_node.nil?\n\t\t\tsrc_node = create_node_and_populate_graph(src_name)\n\t\tend\n\n\t\tdest_node = @graph.get_node(dest_name)\n\t\tif dest_node.nil?\n\t\t\tdest_node = create_node_and_populate_graph(dest_name)\n\t\telse\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\n\t\tif path.empty?\n\t\t\tpopulate_graph(src_node) if !src_node.populated\n\t\t\tpopulate_graph(dest_node) if !dest_node.populated\n\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\tend\n\t\t\n\t\t# after check on first (separation of 2) level we do another two level of check\n\t\tif path.empty?\n\t\t\t(1..2).each do |level|\n\t\t\t\tsrc_connections = get_persons_based_on_level(src_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(src_connections)\n\t\t\t\tdst_connections = get_persons_based_on_level(dest_node, level)\n\t\t\t\tpopulate_graph_for_given_collections(dst_connections)\n\t\t\t\tpath = breath_first_search(src_node, dest_node)\n\t\t\t\tbreak if path.any?\n\t\t\tend\n\t\tend\n\n\t\twrite_to_yaml\n\n\t\tputs \"Path:\"\n\t\tputs path\n\t\tputs \"Degree of separation :\" + (path.nil? ? \"None\" : (path.size - 1).to_s)\n\tend",
"def build_path(start, end_pos)\n node = Node.new(start[0], start[1])\n target = Node.new(end_pos[0], end_pos[1])\n visited_nodes = []\n next_moves = [node]\n until next_moves.empty? do\n node = next_moves.shift\n puts \"Current node: #{node.x}, #{node.y}\"\n if node.x == target.x && node.y == target.y \n return node\n end\n visited_nodes.push(node)\n node.moves = get_moves(node)\n node.moves.reject do |square|\n visited_nodes.include?(square)\n end\n node.moves.each do |move| \n next_moves.push(move)\n end\n end\n return node\nend",
"def move(request)\n possible_moves = %w[up down left right]\n my_snake_id = request.dig(:you, :id)\n\n obstacles =\n request.dig(:board, :snakes).each_with_object([]) do |snake, res|\n next if snake[:id] == my_snake_id && request[:turn].zero?\n\n # don't add my own head as an obstacle\n snake[:body].shift if snake[:id] == my_snake_id\n\n res << snake[:body]\n end.flatten.uniq\n\n graph = Graph.new(\n width: request.dig(:board, :width),\n height: request.dig(:board, :height),\n start_x: request.dig(:you, :head, :x),\n start_y: request.dig(:you, :head, :y),\n obstacles: obstacles\n )\n\n h_sorted_foods =\n request\n .dig(:board, :food)\n .sort do |a, b|\n a_node_h_dist = graph.start.distance(Node.new(a[:x], a[:y]))\n b_node_h_dist = graph.start.distance(Node.new(b[:x], b[:y]))\n\n a_node_h_dist <=> b_node_h_dist\n end\n\n food = h_sorted_foods.first\n\n graph.set_end(food[:x], food[:y])\n\n path = ASTAR.new(graph.start, graph.end).search\n\n next_node = path&.first\n\n if next_node.x > graph.start.x\n 'right'\n elsif next_node.x < graph.start.x\n 'left'\n elsif next_node.y > graph.start.y\n 'up'\n elsif next_node.y < graph.start.y\n 'down'\n else\n # TODO: replace this with navigating to biggest open space\n possible_moves.sample\n end\nend",
"def get_path(double_array, path_cost, path_time)\n double_array.each do |path|\n correct_path = []\n cost = 0\n time = 0\n count = 0\n until count == path.size - 1\n correct_edge = @edge_array.find { |i| \n i.source == path[count] && i.destination == path[count+1] \n }\n cost += correct_edge.cost\n time += correct_edge.time\n count += 1\n end\n if cost == path_cost && time == path_time\n return path\n end\n end\n end",
"def apply_kruskal\r\n #sort the edges by its time-distance (sec)\r\n #then go over each edge, check if its borders vertices belong to the same group, if not , connect it,\r\n #groups are the lowest id\r\n\r\n edges_counter=0\r\n\r\n #1. sort edges\r\n @valid_edges.sort! { |a,b| a.time_distance <=> b.time_distance }\r\n\r\n #2. initialize head and inks nodes. each is his own head and points to null. (we maintaint information only for the selected ones (saving))\r\n @valid_vertices.each do |n|\r\n n.set_node_head_mst(n.osm_id)\r\n n.set_node_tail_mst(n.osm_id)\r\n #puts \"#{n.osm_id}, #{n.mst_head} \"\r\n end\r\n\r\n #3. go over valid (filtered)edges, join if possible. lower id will always be n1\r\n @valid_edges.each do |e|\r\n #lower id to be first of the selected two nodes\r\n if e.osm_from<e.osm_to\r\n then\r\n n1osm=e.osm_from\r\n n2osm=e.osm_to\r\n else\r\n n1osm=e.osm_to\r\n n2osm=e.osm_from\r\n end\r\n\r\n #get object, its current head and next\r\n n1=@nodes_hash[n1osm]\r\n n2=@nodes_hash[n2osm]\r\n n1_head_osm=n1.mst_head\r\n n2_head_osm=n2.mst_head\r\n\r\n #4. if the head1 != head2, nodes can be connected and marked bold red\r\n if n1_head_osm != n2_head_osm\r\n #mark the edge as bold\r\n e.set_bold\r\n edges_counter=edges_counter + 1\r\n\r\n #get head object of both lists\r\n n1_tail_osm=n1.mst_tail\r\n n2_tail_osm=n2.mst_tail\r\n n1_head=@nodes_hash[n1_head_osm]\r\n n1_tail=@nodes_hash[n1_tail_osm]\r\n\r\n #join two lists (if they are lists)\r\n #puts \"n1: H1:#{n1_head.mst_head} T1:#{n1_head.mst_tail} H1N:#{n1_head.mst_next} ## n2: H2:#{n2Head.mst_head} T2:#{n2Head.mst_tail} H2N:#{n2Head.mst_next}\"\r\n n1_tail.set_next_node_mst(n2_head_osm)\r\n n1_head.set_node_tail_mst(n2_tail_osm)\r\n\r\n #fix links to head and tail on all their children\r\n child_node_osm=n1_head.mst_next\r\n until child_node_osm==-1 do\r\n child_node=@nodes_hash[child_node_osm]\r\n child_node.set_node_head_mst(n1_head_osm)\r\n child_node.set_node_tail_mst(n2_tail_osm)\r\n child_node_osm=child_node.mst_next\r\n end\r\n\r\n #puts \"n1: H1:#{n1_head.mst_head} T1:#{n1_head.mst_tail} H1N:#{n1_head.mst_next} ## n2: H2:#{n2Head.mst_head} T2:#{n2Head.mst_tail} H2N:#{n2Head.mst_next}\"\r\n end\r\n end\r\n\r\n #validations\r\n\r\n puts \"Validation error. In mst should be less edges then vertices\" if @valid_vertices.length <= edges_counter\r\n puts \"Validation passed. Minimum spanning tree has less edges (#{edges_counter}) than vertices (#{@valid_vertices.length}). Graph has more components. \" if @valid_vertices.length > edges_counter+1\r\n puts \"Validation passed. Minimum spanning tree has one edge less (#{edges_counter}) than vertices (#{@valid_vertices.length}). Graph has one component. \" if @valid_vertices.length == edges_counter+1\r\n end",
"def runOperation(msg, client)\n case msg.getConfig(\"type\")\n when 0; edgebReflex(msg.getMessage(), client)\n when 1; fillBack(msg)\n when 2; edgeuUpdate(msg.getMessage())\n when 3; pingCallBack(msg)\n when 4; tracerouteCallBack(msg)\n when 5; sendMsgCallBack(msg, client)\n else STDERR.puts \"ERROR: INVALID MESSAGE \\\"#{msg}\\\"\"\n end\nend"
] |
[
"0.6579866",
"0.63999313",
"0.62158346",
"0.60665673",
"0.5780086",
"0.5779895",
"0.5770335",
"0.56623864",
"0.555246",
"0.5360149",
"0.529686",
"0.5241645",
"0.5213028",
"0.51927036",
"0.51253843",
"0.51174945",
"0.50856936",
"0.5031403",
"0.5015003",
"0.49930185",
"0.49499106",
"0.49394",
"0.49325374",
"0.49293378",
"0.49076003",
"0.48629022",
"0.48320755",
"0.48109996",
"0.4806059",
"0.48016128",
"0.47960904",
"0.47867712",
"0.477454",
"0.47642756",
"0.476221",
"0.475887",
"0.4750133",
"0.47472787",
"0.4740365",
"0.473145",
"0.4688493",
"0.46833268",
"0.46826956",
"0.46789265",
"0.46784475",
"0.46750498",
"0.4671169",
"0.466163",
"0.46561715",
"0.46555415",
"0.46480915",
"0.46366015",
"0.46354",
"0.4634867",
"0.46153834",
"0.46093655",
"0.46057636",
"0.4601736",
"0.4599729",
"0.4582061",
"0.457625",
"0.45638248",
"0.4563734",
"0.45630598",
"0.45470053",
"0.4536084",
"0.4527456",
"0.45246473",
"0.4519948",
"0.45118004",
"0.45102915",
"0.44970435",
"0.4496243",
"0.4495629",
"0.44933462",
"0.44924605",
"0.44905895",
"0.44883776",
"0.44872326",
"0.44798467",
"0.4470733",
"0.44658118",
"0.4454753",
"0.4454674",
"0.44463927",
"0.4442287",
"0.44405738",
"0.4438691",
"0.44375888",
"0.4436309",
"0.44272012",
"0.44208783",
"0.44170427",
"0.44091758",
"0.44075346",
"0.4402977",
"0.43923768",
"0.4383487",
"0.4376133",
"0.4369784"
] |
0.5981413
|
4
|
A thread that handles all incoming connections
|
def serverHandling()
loop {
#puts "ServerHandling thread: #{Thread.current}"
thread = Thread.start($serv.accept) do |client|
message = client.gets.chomp
arr = message.split(' ')
server_cmd = arr[0]
args = arr[1..-1]
# if server_cmd != "UPDATE" then puts "THIS IS THE MESSAGE: #{message}" end
case server_cmd
when "EDGEB2"; edgeb_network(args)
when "EDGEU2"; edgeu_network(args)
when "UPDATE"; updateTable(args)
when "TOSOURCE"; source_console(args)
when "PING"; ping_network(args)
when "FORWARD"; forward_packet(args)
when "SEND"; packet_forward(args)
when "SEND2"; file_forward(args)
when "SUCCESS"; transfer_success(args)
when "CIRCUITB2"; circuitb_network(args)
else STDERR.puts "ERROR: INVALID COMMAND \"#{server_cmd}\""
end
client.close
end
}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def run\n loop do\n memcached = Memcached.new # each client has its oun cache storage\n new_client = @tcp_Server.accept # when a new client connects to the server\n client_handler_id = rand(999999).to_s\n client_handler = ClientHandler.new(id: client_handler_id, clientSocket: new_client, memcached: memcached)\n @@clients << client_handler\n\n Thread.start(client_handler) do |handler| # open a new thread for each accepted connection\n # Here we inform the client of the connections. It's human made, so can be removed if not needed\n puts \"New connection established! Now #{@@clients.length()} clients :>\"\n puts \"WAITING FOR REQUESTS\"\n handler.send(\"Server: Connection established with Client Handler ID: #{client_handler_id}\")\n handler.send(\"Server: You are the client ##{@@clients.length()}\")\n handler.send(\"Server: You may introduce commands now\")\n listen_requests(handler) # allow communication\n end\n end.join\n end",
"def run!\n start_server!\n @server_thread = Thread.new do\n loop do\n Thread.start(@server.accept) do |socket|\n begin\n handle_request(socket)\n rescue => e\n @logger.error \"#{e.class}: #{e.message}\"\n @logger.debug e.backtrace\n ensure\n closing_client = @client_mutex.synchronize do\n @clients.delete(socket)\n end\n # invoke callbacks for disconnect if there is a client to\n # disconnect\n emit(:client_disconnect, closing_client) if closing_client\n socket.close\n end\n end\n end\n end\n end",
"def main_loop\n Thread.start(@protocol.accept) do |client|\n @grp.add Thread.current\n Thread.current['DRb'] = { 'client' => client ,\n 'server' => self }\n DRb.mutex.synchronize do\n client_uri = client.uri\n @exported_uri << client_uri unless @exported_uri.include?(client_uri)\n end\n loop do\n begin\n succ = false\n invoke_method = InvokeMethod.new(self, client)\n succ, result = invoke_method.perform\n if !succ && verbose\n p result\n result.backtrace.each do |x|\n puts x\n end\n end\n client.send_reply(succ, result) rescue nil\n ensure\n client.close unless succ\n if Thread.current['DRb']['stop_service']\n Thread.new { stop_service }\n end\n break unless succ\n end\n end\n end\n end",
"def listen\n Thread.new do\n while (true)\n socket = @server.accept\n puts \"connection from #{socket.peeraddr[2]} port #{socket.peeraddr[1]}\"\n @connections.add(socket.peeraddr[2], socket.peeraddr[1], socket)\n end\n end\n end",
"def accept_connections\n loop do\n # socket open for clients\n # handle multiple client requests\n Thread.start(listening_socket.accept) do |client|\n yield(client)\n client.close\n end\n end\n end",
"def listen\n connect do\n routes.each do |queue|\n @client.subscribe(queue) do |args|\n run(queue, args)\n end\n end\n end\n while (!Thread.current[:shutdown]) do\n sleep(self.class.sleep_time)\n end\n end",
"def run\n\t\t# Empezamos a escuchar al servidor\n\t\tlisten\n\t\t# Empezamos a enviar al servidor\n\t\tsend\n\t\t# Revisamos el estado de la conexion\n\t\t# check_alvie\n\t\t# Al terminar cerramos los Threads\n\t\t@request.join if @request.alive?\n\t\t@response.join if @response.alive?\n\tend",
"def run\n loop do\n # Wait for a client to connect and then create a thread for it\n Thread.new(@server.accept) do |client_socket|\n logger.info \"Accepted client: #{client_socket.peeraddr.join(':')}\"\n server_socket = TCPSocket.new(@server_host, @server_port)\n begin\n process_packets(client_socket, server_socket)\n rescue Exception => exp\n logger.error exp.to_s\n end\n logger.info \"Disconnected: #{client_socket.peeraddr.join(':')}\"\n server_socket.close\n client_socket.close\n end\n end\n end",
"def socket_loop\n @socket.listen\n loop do\n client_socket, client_addr = @socket.accept\n Thread.new(client_socket) { |client_socket| serve_client client_socket } \n end\n @manager.tem_ports\n end",
"def run\n loop {\n # Thread.start -> takes arguments that it yields to block for creating thread\n # # server#accept -> returns a new Socket object and Addrinfo object\n Thread.start(@server.accept) do |client| # each client thread\n nick_name = client.gets.chomp.to_sym\n # check if client connectiont already exists\n @connections[:clients].each do |other_name, other_client|\n if nick_name == other_name || client == other_client\n puts \"This username already exists\"\n Thread.kill self\n end\n end\n puts \"#{nick_name} #{client}\"\n @connections[:clients][nick_name] = client\n client.puts \"Connection established, Thank you for joining! Happy Chatting\"\n # listen for client messages\n listen_for_user_messages(nick_name, client)\n end\n }\n end",
"def run\n loop do\n #Kernel.exit\n if @workQ.size < (@pool_size-1)\n Thread.start(@fileServer.accept) do | client |\n @workQ.push 1\n message_handler(client)\n @workQ.pop(true)\n end\n else\n # if thread pool is full\n sleep 5 \n client.close\n end\n end\n end",
"def start_acceptor!\n\t\t$threads << @acceptor = Thread.new() do\n\t\t\twhile true\n\t\t\t\tif new_connection = @server.accept\n\t\t\t\t\tputs \"New connection accepted: #{new_connection}\"\n\t\t\t\t\t@connections << new_connection #Save any inbound\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend",
"def start\n Socket.accept_loop(@tcpserver) do |connection|\n SLogger.debug(\"[server] accepted a new connection (#{connection})\")\n\n self.session.connection = connection\n self.handle_connection(connection)\n end\n rescue IOError\n Thread.exit\n end",
"def start(multithreaded)\n if multithreaded\n Thread.abort_on_exception = true\n @log.info \"Accepting concurrent connections with new threads\"\n end\n begin\n loop do\n if multithreaded\n Thread.new(@server.accept) do |client_sock|\n handle_sock(client_sock)\n end\n else\n handle_sock(@server.accept)\n end\n end\n rescue Interrupt, SystemExit => e\n @server.close\n @log.info { \"Shutting down the ChainReactor server\" }\n raise e\n rescue Exception => e\n @server.close\n raise e\n end\n end",
"def start\n loop do\n begin\n socket = tcp_server.accept\n\n handle_request(socket)\n ensure\n socket.close\n end\n end\n end",
"def run\n loop do\n #Kernel.exit\n if @workQ.size < (@pool_size-1)\n Thread.start(@fileServer.accept) do | client |\n @workQ.push 1\n message_handler(client)\n @workQ.pop(true)\n end\n else\n # if thread pool is full\n puts 'Thread pool full wait 5'\n sleep 5 \n client.close\n end\n end\n end",
"def start\n\n # load config files\n @httpd_conf.load \n @mimes.load\n # initialze logger \n logger = Logger.new(@httpd_conf.logfile) \n Thread.abort_on_exception=true\n \n loop do\n puts \"Opening server socket to listen for connections\"\n\n # handle incoming request\n Thread.start(server.accept) do |client|\n worker = Worker.new(client,@httpd_conf,@mimes,logger) \n worker.handle_request\n end\n end\n\n end",
"def start\n connect\n @last_alive = Time.now\n @listener = Thread.new do\n while true\n begin\n @last_alive = Time.now if @hub.fetch_command\n\n if Time.now > @last_alive + @keepalive_timeout\n @logger.error \"connection lost\" if @logger\n @last_alive = Time.now\n reconnect\n end\n\n rescue Exception => e\n exit if e.class == Interrupt\n puts e.message\n puts e.backtrace.join(\"\\n\")\n break\n end\n end\n end\n end",
"def run\n loop do\n if @workQ.size < (@pool_size-1)\n Thread.start(@directoryServer.accept) do | proxy |\n @workQ.push 1\n proxy_handler(proxy)\n @workQ.pop(true)\n end\n else\n # if thread pool is full\n sleep 5 \n proxy.close\n end\n end\n end",
"def start\r\n @thread = Thread.new {\r\n @server.connect\r\n @proto.fire_pseudo(:connect, {address: @server.address?, port: @server.port?})\r\n protos = @server.read\r\n while protos != nil && @halt != true\r\n protos.each do |proto|\r\n Log::write \"<= \" + proto\r\n @proto.parse_proto(proto)\r\n end\r\n protos = @server.read\r\n end\r\n }\r\n end",
"def run\n loop do\n Thread.start(server.accept) do |client|\n begin\n ServerThread.new(client,@job_queue).run\n rescue Exception => e\n STDERR.puts \"A server thread has encountered an exception:\"\n STDERR.puts \"--------------------------------\"\n STDERR.puts e.message\n STDERR.puts e.backtrace\n STDERR.puts \"--------------------------------\"\n end\n end\n end\n end",
"def start_server\n @watchman = Thread.new {\n while !@stopped\n @pool_mutex.synchronize\n socket = @server.accept\n @pool << Thread.new(socket) {|socket|\n serve(socket)\n }\n end \n }\n end",
"def run\n loop{\n @client = @server.accept\n @serverPool.schedule(@client)\n }\n end",
"def run\n loop{\n @client = @server.accept\n @serverPool.schedule(@client)\n }\n end",
"def start\n\t\t@server_thread = Thread.new do\n\t\t\tbegin\n\t\t\tserver = TCPServer.open(23)\n\t\t\tloop {\n\t\t\t\tbegin\n\t\t\t\t\tclient = TelnetClient.new(server.accept)\n\t\t\t\t\t@client_list << client\n\t \t\t\t\tt = Thread.new do\n\t \t\t\t\t\thandleNewClient(client) \n\t \t\t\t\tend\n\t \t\t\trescue Exception => e \n\t\t\t\t\tputs \"Client Error: #{e.message}\"\n\t\t\t\t\tputs e.inspect\n\t\t\t\t\tputs e.backtrace\n\t\t\t\tend\n\t\t\t}\n\t\t\trescue Interrupt => e\n\t\t\t\tputs \"Server is interrupted\"\n\t\t\tensure\n\t\t\t\tclose_all()\n\t\t\t\tserver.close\n\t\t\tend\n\t\tend\n\t\t@server_thread.abort_on_exception = true\n\tend",
"def run\n Thread.start do\n begin\n while true\n main_loop\n end\n ensure\n @protocol.close if @protocol\n end\n end\n end",
"def run\n loop do\n #Kernel.exit\n if @workQ.size < (@pool_size-1)\n Thread.start(@replicaServer.accept) do | client |\n @workQ.push 1\n message_handler(client)\n @workQ.pop(true)\n end\n else\n # if thread pool is full\n sleep 5 \n client.close\n end\n end\n end",
"def _start_updates\n\n t = Thread.new do\n packet_manager = PacketManager.instance\n loop do\n # update pacekts\n list_updated = packet_manager.update_streams\n # send\n @clients.each_index do |i|\n c = @clients[i]\n list_updated.each do |p|\n begin\n send_stream(c, p)\n rescue => e\n @clients[i] = nil # to be removed\n PadoaukLog.info \"terminated connection from #{c.peeraddr.to_s}\", self\n c.close\n break # break list_updated.each\n end\n end\n end\n @clients.delete_if { |e| e == nil }\n\n Thread.stop\n end\n end\n\n add_task(t)\n\n end",
"def run\n @active_connections = 0\n @mutex = Mutex.new\n\n logger.info \"Starting server on #{server_configuration.bind}\"\n\n # Set up each listener and add it to an array ready for the event loop\n @active_descriptors = []\n @active_descriptors << establish_socket_server\n @active_descriptors << establish_file_descriptor_server\n @active_descriptors << setup_signal_traps\n\n write_pidfile\n\n # Enter the main loop\n select_loop\n end",
"def listen\n Thread.new do\n while true\n retrieve_messages\n sleep (0.1)\n end\n end\n end",
"def run\n srv = if self.path\n UNIXServer.new(path)\n else\n TCPServer.new(host, port)\n end\n\n loop do\n io = accept_connection(srv)\n\n begin\n data = receive_data(io)\n send_data(io, handle_data(io, data)) if data\n rescue\n raise 'Connection reset by peer' if config[:debug] && io.closed?\n ensure\n io.close rescue nil\n GC.start if config[:run_gc_per_request]\n end\n end\n end",
"def run\n trap_signals\n loop do\n break if signals_want_shutdown\n begin\n # IO.select returns either a triplet of lists with IO objects that\n # need attention or nil on timeout of 2 seconds.\n if needy = IO.select([server.socket, lifeline], nil, [server.socket, lifeline], 2)\n server.log.debug(\"Detected activity on: #{needy.inspect}\")\n # If the lifeline is active the server went down and we need to go\n # down as well.\n break if needy.flatten.any? { |io| !io.respond_to?(:accept_nonblock) }\n # Otherwise we handle incoming requests\n needy.flatten.each do |io|\n if io.respond_to?(:accept_nonblock)\n begin\n process_incoming_socket(*io.accept_nonblock)\n rescue Errno::EAGAIN, Errno::ECONNABORTED\n end\n end\n end\n end\n rescue EOFError, Errno::EAGAIN, Errno::EINTR, Errno::EBADF, IOError\n end\n end\n cleanup\n end",
"def run_server_thread; end",
"def start_async\n while c = @serv.accept\n Thread.start do\n begin\n @threads << Thread.current\n l = Mutex.new\n loop do\n begin\n x = Dr2.read(c, [Dr2::Types::Message,\n Dr2::Types::Error])\n Thread.start {\n begin\n @threads << Thread.current\n receive x, c, l\n ensure\n l.unlock rescue nil if l.locked?\n @threads.delete Thread.current\n end\n }\n rescue Dr2::Types::EOFException\n break\n rescue Dr2::Types::QuitException\n break\n rescue Exception\n l.synchronize { Dr2.write(c, $!) }\n end\n end\n ensure\n c.close rescue nil\n @threads.delete Thread.current\n end\n end\n end\n end",
"def run\n\t\n\t\twhile true \t\t\t\t\t\t# run forever\n\t\t\n\t\t\tready2read = sockets_ready_for_reading()\n\t\t\t\n\t\t\tnext if not ready2read \t\t\t# if nil, loop again\n\t\n\t\t\tputs \"<Debug> ready2read=#{ready2read.inspect}\" if $DEBUG\n\n\t\t\tready2read.each do |socket|\t\t\n\t\t\t\n\t\t\t\tif socket == @server_socket then\t# we have a new client\n\n\t\t\t\t\taccept_new_connection\n\n\t\t\t\telse \t\t\t\t\t\t\t# a client has a message\n\n\t\t\t\t\tconn = get_connection_by_socket(socket)\n\n\t\t\t\t\tif socket.eof? then \t# the socket was closed\n\n\t\t\t\t\t\tmessage = sprintf(\"190 %s@%s:%s now disconnected\\n\", \n\t\t\t\t\t\t\tconn.username, conn.host, conn.port)\n\t\t\t\t\t\tlog_message(message)\n\t\t\t\t\t\tbroadcast_message(message, conn)\n\t\t\t\t\t\tsocket.close\n\t\t\t\t\t\t@connection_array.delete(conn)\n\t\t\t\t\t\tlog_socket_info\n\n\t\t\t\t\telse\t\t\t\t\t# we have a message to process\n\t\t\t\t\t\n\t\t\t\t\t\tmessage = socket.gets.chomp!\n\t\t\t\t\t\tlog_string = sprintf(\"<log>:Message From: %s@%s:%s %s\", \n\t\t\t\t\t\t conn.username, conn.host, conn.port, message.inspect)\n\t\t\t\t\t\tlog_message(log_string)\n\t\t\t\t\t\tprocess_message(message, conn)\n\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend \n\t\tend\n\tend",
"def start_handler\n queue = ::Queue.new\n\n local_port = bind_port\n\n handler_name = \"ReverseTcpHandlerListener-#{local_port}\"\n self.listener_thread = framework.threads.spawn(handler_name, false, queue) { |lqueue|\n loop do\n # Accept a client connection\n begin\n client = listener_sock.accept\n if client\n self.pending_connections += 1\n lqueue.push(client)\n end\n rescue Errno::ENOTCONN\n nil\n rescue StandardError => e\n wlog [\n \"#{handler_name}: Exception raised during listener accept: #{e.class}\",\n $ERROR_INFO.to_s,\n $ERROR_POSITION.join(\"\\n\")\n ].join(\"\\n\")\n end\n end\n }\n\n worker_name = \"ReverseTcpHandlerWorker-#{local_port}\"\n self.handler_thread = framework.threads.spawn(worker_name, false, queue) { |cqueue|\n loop do\n begin\n client = cqueue.pop\n\n unless client\n elog(\"#{worker_name}: Queue returned an empty result, exiting...\")\n end\n\n # Timeout and datastore options need to be passed through to the client\n opts = {\n datastore: datastore,\n expiration: datastore['SessionExpirationTimeout'].to_i,\n comm_timeout: datastore['SessionCommunicationTimeout'].to_i,\n retry_total: datastore['SessionRetryTotal'].to_i,\n retry_wait: datastore['SessionRetryWait'].to_i\n }\n\n if datastore['ReverseListenerThreaded']\n thread_name = \"#{worker_name}-#{client.peerhost}\"\n conn_threads << framework.threads.spawn(thread_name, false, client) do |client_copy|\n handle_connection(wrap_aes_socket(client_copy), opts)\n end\n else\n handle_connection(wrap_aes_socket(client), opts)\n end\n rescue StandardError => e\n elog('Exception raised from handle_connection', error: e)\n end\n end\n }\n end",
"def loop_forever\n running = true\n\n while wait_for_connection\n @logger.info(\"New client connected\")\n command, *arguments = next_message.split\n @logger.debug \"#{command} received\"\n response = case command\n when /^track$/i then track(arguments.first)\n when /^list$/i then list\n when /^release$/i then release(arguments.first)\n end\n\n write(response) unless response.nil?\n end\n rescue => e\n @logger.error(\"An error occurred when waiting for new connections!\\n\\t#{e.inspect}\\n\\t#{e.backtrace.join(\"\\n\\t\")}\")\n end",
"def run\n\t\tputs \"Server waiting for conncetions\"\n\t\tloop do\n\t\t\tThread.start(@serverSocket.accept) do |conection|\n\t\t\t\t# Agregamos al cliente a la lista de conectados si este no\n\t\t\t\t# esta en la lista\n\t\t\t\t(@clients << conection) unless @clients.include? conection\n\t\t\t\t# Registramos la conexion por consola\n\t\t\t\tputs \"Conexion #{conection}\"\n\t\t\t\t# Avisamos de la conexion exitosa\n\t\t\t\tconection.puts \"i Conexion establecida\"\n\t\t\t\t# Enviamos la lista de servidores\n\t\t\t\tconection.puts \"m \" << Connections::SERVER_IP.join(\" \") if @master\n\t\t\t\tconection.puts \"s \" << @arry_ips.join(\" \") unless @master\n\t\t\t\t# Escuchamos los mensajes de la conexion\n\t\t\t\tlisten_user(conection)\n\t\t\t\t# Quitamos la conexion\n\t\t\t\t@clients.delete(conection)\n\t\t\t\t# Avisamos en consola de la desconeccion\n\t\t\t\tputs \"Desconexion #{conection}\"\n\t\t\t\t# Cerramos el socket\n\t\t\t\tconection.close\n\t\t\tend\n\t\tend.join\n\tend",
"def run_socket_thread\n @thread ||= Thread.new { run_socket_loop }\n end",
"def start_monitoring_connection\n @connection_monitor_thread ||= Thread.new{monitor_connection}\n @connection_monitor_thread.abort_on_exception = true\n end",
"def listen\n connect do\n routes.each do |route|\n @client.subscribe(route) do |args|\n run(route, args)\n end\n end\n \n loop do\n sleep 1\n end\n end\n end",
"def start_listen\n @thr_listen = Thread.new do\n begin\n @io_in.each_line do |line|\n raise \"No line?\" if !line || line.to_s.strip.empty?\n alive_check!\n debug \"Received: #{line}\" if @debug\n\n begin\n obj = Marshal.load(Base64.strict_decode64(line.strip))\n debug \"Object received: #{obj}\\n\" if @debug\n rescue => e\n $stderr.puts \"Base64Str: #{line}\" if @debug\n $stderr.puts e.inspect if @debug\n $stderr.puts e.backtrace if @debug\n\n raise e\n end\n\n id = obj[:id]\n obj_type = obj[:type]\n\n if obj_type == :send\n Thread.new do\n #Hack to be able to do callbacks from same thread when using blocks. This should properly be cleaned a bit up in the future.\n obj[:obj][:send_id] = id\n\n begin\n raise \"Object was not a hash.\" unless obj.is_a?(Hash)\n raise \"No ID was given?\" unless id\n res = self.__send__(\"cmd_#{obj.fetch(:obj).fetch(:cmd)}\", obj.fetch(:obj))\n rescue Exception => e\n raise e if e.is_a?(SystemExit) || e.is_a?(Interrupt)\n res = {type: :error, class: e.class.name, msg: e.message, bt: e.backtrace}\n end\n\n data = Base64.strict_encode64(Marshal.dump(type: :answer, id: id, answer: res))\n @io_out.puts(data)\n end\n elsif obj_type == :answer\n if answer_queue = @answers[id]\n debug \"Answer #{id} saved.\\n\" if @debug\n answer_queue << obj.fetch(:answer)\n elsif @debug\n debug \"No answer-queue could be found for ID #{id}.\"\n end\n else\n raise \"Unknown object: '#{obj}'.\"\n end\n end\n rescue => e\n if @debug\n debug \"Error while listening: #{e.inspect}\"\n debug \"#{e.backtrace.join(\"\\n\")}\\n\"\n end\n\n @listen_err = e\n end\n end\n end",
"def running\n #RubyProf.measure_mode = RubyProf::PROCESS_TIME #<= Measuring process time\n #RubyProf.start #<= Measuring performance of the socket\n puts \"Server Listening...\"\n @start = Time.now\n @server = TCPServer.new @ip, @port\n while (connection = @server.accept)\n @mutex.synchronize do\n @acceptor << Thread.fork(connection) do |client| #<= Blocking Accept\n begin\n puts \"Client #{client} Connected At #{Time.now}\\n\"\n port, host = client.peeraddr[1, 2]\n @sockets << client\n @connection << \"#{client}:#{host}:#{port}\"\n client.puts \"Connection Established!\"\n sleep 5\n listening(client)\n rescue EOFError\n client_list\n client.close\n puts \"Client #{client} Terminated...\\n\"\n end\n end\n end\n end\n end",
"def run\n while true\n begin\n res = select( @descriptors, nil, nil)\n if res != nil \n for sock in res[0]\n if sock == @serverSocket \n accept_new_connection\n elsif sock.eof? \n sock.close\n @user_info.delete(@user_info[@descriptors.index(sock)-1])\n @descriptors.delete(sock)\n else\n msg = sock.gets()\n puts msg\n user_info = @user_info[@descriptors.index(sock)-1]\n if (msg =~ /user_info:|source_info:|admin_info:/) and user_info.nil? \n eval_first_msg(msg,sock) \n elsif (msg =~ /user_info:|source_info:|admin_info:/) and !(user_info.nil?)\n sock.write(\"You are registered #{user_info[:nickname]}, do not try to deceive me\\n\")\n else\n response_request(msg,sock)\n end\n end\n end\n end\n rescue => e\n puts \"Somenthing wrong happened #{e}\"\n end\n end\n end",
"def start\n Thread.new do\n connect = false\n until connect do\n begin\n call do |server| \n @server = server\n Waves::Logger.info \"#{self.class.basename} started on #{host}:#{port}.\"\n end\n rescue RuntimeError => e\n Waves::Logger.error e.to_s\n sleep 1\n end\n connect = true\n end\n end\n end",
"def run\n @active_connections = 0\n @mutex = Mutex.new\n\n logger.info \"Starting server on #{server_configuration.bind}\"\n\n establish_socket_server\n write_pidfile\n setup_signal_traps\n select_loop\n end",
"def each\n @mutex.synchronize do\n # Don't include the ones in a reserved_placeholder state because that object is meaningless\n @connections.each { |connection| yield connection unless connection.kind_of?(Thread) }\n end\n end",
"def run!\n start_server!\n loop do\n Thread.start(@proxy_server.accept) do |socket|\n begin\n handle_request(socket)\n rescue => e\n @logger.error(self.class) { e.message }\n @logger.error(self.class) { e.backtrace }\n ensure\n socket.close\n end\n end\n end\n end",
"def serving_loop\n Thread.new { socket_loop }\n @manager.management_loop\n end",
"def start\n # the above only accepts 1 requiest. it will stop after receiving a request\n # in order to enable the server to accept more than 1 request, you need to create a loop\n loop do\n # this is an infinite loop.. this can now accept multiple vars and it will ahve separate objects per request\n # once the server socket is ready..\n # we need to tell the server socket that we're ready to accept a connection\n # the #accept method accepts the next incoming connection or it will block if there are no incoming connections at teh moment\n # it will #accept once it arrives\n # this is the socket / connetiont at we have to teh remote browser\n socket = @server.accept # THIS IS THE CLIENT SOCKET\n puts \"this is the socket var: \" + @socket.inspect\n # let's start the new conneciton inside a thread\n # NOTE: there's a big performance and memory penalty for creating a new thread => needs to put a bunch of memory\n # to increase the performance, they initialize threads and then store those threads in a $\"thread pool\" => ie. instead of initializign new threads, it leverages existing threads\n # doing what you did below slows down the server significantly\n # apache, nginx, unicorn => prefork model\n # => fork meaning it will fork right afte rthe server socket initialization (see above in TCPServer) => 2 parts: main server socket in the master process and we will make child processes by calling a method called fork. it copies the the main process and it will $share the sockets from the master process\n # to the child proceess\n Thread.new do\n # create a new isntance of the connneciton class\n connection = Connection.new(socket, @app) # now we have access to the rack application instance inside our Connection \n connection.process\n end\n end\n end",
"def listenLoop()\n x = Thread.new{\n i = 0\n while true\n i = i + 1\n puts \" \"\n print @name, \" Listen Loop Round: \", i\n puts \" \"\n jsonIN = @s.recv(65536)\n puts \" \"\n print @name, \" \", Time.now, \" has receaved a Message: \", jsonIN\n puts \" \"\n parsed = JSON.parse(jsonIN)\n if @netWorkMember\n self.respond( parsed )\n else\n puts \"Not a member of a Network hence I will not respond\"\n end\n end\n }\n end",
"def listening\n @start = Time.now\n #RubyProf.measure_mode = RubyProf::PROCESS_TIME #<= Measuring process time\n #RubyProf.start #<= Measuring performance of the socket\n @res = Thread.new do\n count = 0\n while (message = @server.readline)\n count += 1\n puts \"Server: #{message}\"\n puts \"Amount Of Responses #{count}\"\n end\n end\n end",
"def run (queue)\n loop do\n @LOG.debug \"waiting on #{@port_num}\"\n Thread.start(@server.accept) do |client|\n addr = client.addr\n addr.shift # removes \"AF_INET\"\n @LOG.info(\"accept connection addr: #{addr.join(\":\")}\")\n peer_addr = client.peeraddr\n peer_addr.shift # removes \"AF_INET\"\n @LOG.debug(\"connected to peer: #{peer_addr.join(\":\")}\")\n while size = client.recv(4).unpack(\"l\")[0]\n @LOG.debug \"begin receiving data with size #{size}\"\n data = client.recv(size)\n unmarshaled_data = Marshal.load(data)\n @LOG.debug \"data received (#{unmarshaled_data})\"\n queue.push unmarshaled_data\n end\n @LOG.info \"connection #{peer_addr.join(\":\")} is closed by other side\" \n end \n end\n end",
"def start\n @server = TCPServer.open(@hostname, @port)\n loop do\n Thread.new(@server.accept) do |client|\n while message = client.gets\n fmp = ForeignMessageParser.new(message)\n Mailbox.append(fmp.to_event) if fmp.got_valid_message?\n end\n client.close\n end\n end\n end",
"def listener()\n\t$server = TCPServer.open($port)\n\t#puts (\"start listening\")\n\tloop {\n\t\tclient = $server.accept()\n\t\t#puts (\"adding #{client} to reading list\")\n\t\t# synchronize reading list\n\t\t$semaphore.synchronize {\n\t\t\t$reading.push(client)\t\n\t\t}\n\t}\nend",
"def run\n use(@inline_handler)\n @socket = TCPServer.new(@host, @port)\n @handlers = @handlers.uniq.freeze\n @options = @options.freeze\n @acceptor = Thread.new do \n begin\n logger.debug \"Starting leech server on tcp://#{@host}:#{@port}\"\n loop do \n begin\n client = @socket.accept \n worker_list = @workers.list\n \n if worker_list.length >= @max_workers\n logger.error \"Server overloaded with #{worker_list.length} workers (#@max_workers max). Dropping connection.\"\n client.close rescue nil\n reap_dead_workers(\"max processors\")\n else\n thread = Thread.new(client) {|c| process_client(c) }\n thread[:started_on] = Time.now\n @workers.add(thread)\n sleep @throttle if @throttle > 0\n end\n rescue StopServer\n break\n rescue Errno::EMFILE\n reap_dead_workers(\"too many open files\")\n sleep 0.5\n rescue Errno::ECONNABORTED\n client.close rescue nil\n rescue Object => e\n logger.error \"#{Time.now}: Unhandled listen loop exception #{e.inspect}.\"\n logger.error e.backtrace.join(\"\\n\")\n end\n end\n graceful_shutdown\n ensure\n @socket.close \n logger.debug \"Closing leech server on tcp://#{@host}:#{@port}\"\n end\n end\n \n return @acceptor\n end",
"def listenLoop()\n x = Thread.new {\n i = 0\n while true\n i = i + 1\n puts \" \"\n print @name, \" Listen Loop Round: \", i\n puts \" \"\n jsonIN = @socket.recv(65536)\n puts \" \"\n print @name, \" \", Time.now, \" has received a Message: \", jsonIN\n puts \" \"\n parsed = JSON.parse(jsonIN)\n if @netWorkMember\n self.respond(parsed)\n else\n puts \"Not a member of a Network, No Response\"\n end\n end\n }\n end",
"def run\n while true; async.handle_message @socket.read; end\n end",
"def run\n EventMachine::run do\n @tcp = EventMachine::connect(config.server.host, config.server.port, TCPConnection)\n @tcp.client = self\n spectator_join\n end\n end",
"def start\n @thread = Thread.new do\n EM::WebSocket.start(ws_options) do |ws|\n ws.onopen do |handshake|\n log \"onopen: #{handshake.headers}\"\n @clients << ws\n end\n\n ws.onclose do |event|\n log \"closed: #{event}\"\n @clients.delete ws\n end\n\n ws.onmessage do |msg|\n log \"received: #{msg}\"\n end\n end\n end\n end",
"def server_loop(server)\n loop do\n Thread.start(server.accept) do |client|\n _unused, remote_port, _unused, remote_ip = client.peeraddr\n @server.logging \"--> OPEN connection from #{remote_ip}:#{remote_port}\"\n client.puts @entrypoint_routine.call\n client.close\n @server.logging \"<-- CLOSE connection from #{remote_ip}:#{remote_port}\"\n end\n end\n end",
"def listen \n @logger.info \"tcp server is listening...\"\n while @running do # Servers run forever\n while session = @server.accept do \n sockets << session\n Thread.start do\n session.puts(Time.now.ctime) # Send the time to the client\n session.puts(\"Hello hive game viewer\\n\")\n #session.puts \"Hi there\"\n @logger.info \"someone connected\"\n Thread.start do\n while true do\n input = session.gets\n @logger.info input\n session.puts \"you said #{input}\"\n end\n end \n #userinput = gets \n #puts \"sending #{userinput}\"\n #session.puts(\"#{userinput}\\n\")\n end\n end\n end\nend",
"def listen()\n loop { \n Thread.start(@server.accept) do |client|\n client.puts(Time.now.ctime) \n while line = client.recv(200)\n purge()\n puts line\n interprete(client,line)\n end\n end\n }\n end",
"def start_server\n loop do\n socket = @server.accept\n @pool.post do\n request = socket.gets\n unless request.nil?\n response = fetch_data(request)\n socket.print build_response(response)\n socket.print \"\\r\\n\"\n socket.print response[:message]\n end\n socket.close\n end\n end\n end",
"def listen\n @thread = Thread.new do\n while (true)\n header = @socket.read(1)\n length = @socket.read(4).unpack(\"I\")[0]\n data = @socket.read(length)\n\n case header\n when \"0\"\n puts \"chat message from #{@socket.peeraddr[3]}: #{data}\"\n end\n end\n end\n end",
"def listen\n\n puts('listening')\n while true\n begin\n received_data = p @socket.recv(1000) # Receive\n Thread.new do # Start a new thread to handle the incoming message\n respond(JSON.parse(received_data)) # Determine how to respond to received and parsed message\n end\n rescue Errno::ECONNRESET # If there was an issue in replaying in respond function - e.g. remote host no longer up\n puts('Connection to remote host failed')\n end\n end\n end",
"def start\n unless @running\n @connections.each { |conn| conn.start(@start_bytes) }\n @running = true\n end\n end",
"def start_server\t\n\t\tloop{\n\t\t\tThread.new(@server.accept) do |client|\n\t\t\t\t\t\t\n\t\t\t\t#connection and request\n\t\t\t\tsock_domain, remote_port, remote_hostname, remote_ip = client.peeraddr\n\t\t\t\tclient_ip = remote_ip.to_s\t\n\t\t\t\t@@static_id += 1\n\t\t\t\t@connection_no = @@static_id \t\t\t\t\n\t\t\t\tputs \"\\nConnection ##{@connection_no} client #{client_ip} accepted\"\t\n\t\t\t\t\n\t\t\t\t#send client secret key \n\t\t\t\tclient.puts @key\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t#receive data from client\n\t\t\t\tdata = client.gets.chomp\n\t\t\t\tputs \"received encoded: #{data}\"\n\t\t\t\t\n\t\t\t\tdecdata = Base64.decode64(data)\n\t\t\t\tputs \"decoded message #{decdata}\"\n\t\t\t\t\t\n\t\t\t\t#encrypts message with secret key and newly generated\n\t\t\t\t#initialization vector. \n\t\t\t\tiv = @aes_cipher.random_iv\t\n\t\t\t\t@aes_cipher.iv = iv\n\t\t\t\tputs \"generated IV: #{iv}\"\n\t\t\t\tencrypted = @aes_cipher.update(decdata)\n\t\t\t\tencrypted << @aes_cipher.final\t\n\t\t\t\tputs \"Encrypted Msg: #{encrypted}\"\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t#send back IV and encrypted data\n\t\t\t\tenc_encrypted = Base64.encode64(encrypted)\n\t\t\t\tclient.puts enc_encrypted\n\t\t\t\tclient.puts iv\t\t\t\t\n\t\t\t\t\n\t\t\t\t#close connections\n\t\t\t\tclient.close\t\t\n\t\t\t\t\n\t\t\tend\n\t\t}\n\tend",
"def start\n Thread.new do\n loop do\n @connection.wait_for_notify do |channel|\n @actions[channel].call\n end\n end\n end\n end",
"def listen\n loop do\n self.listen_loop\n \n #Break out if something is wrong.\n break if !@out_mutex or (@in and @in.closed?) or (@out and @out.closed?)\n end\n end",
"def start_sync\n lock = Mutex.new\n while c = @serv.accept\n Thread.start do\n begin\n @threads << Thread.current\n loop do\n begin\n x = Dr2::Types.read(c, [Dr2::Types::Message,\n Dr2::Types::Error])\n lock.synchronize { receive x, c }\n rescue Dr2::Types::EOFException\n break\n rescue Exception\n Dr2::Types.writer($!).write_dr2(c)\n end\n end\n ensure\n c.close rescue nil\n @threads.delete Thread.current\n end\n end\n end\n end",
"def start\n begin\n socket = connect()\n rescue NotAuthorized => e\n return nil\n rescue Errno::ECONNREFUSED => e\n puts \"The connection was refused (#{e.to_s}). Goodbye.\"\n return nil\n rescue => e\n puts \"Failed to connect: #{e.to_s}\\n #{$@}\"\n return nil\n end\n\n return nil unless socket\n\n begin\n listen_thread =\n Thread.new do\n print '> '\n STDOUT.flush\n loop do\n scribe( socket )\n end\n end\n\n loop do\n deliver( socket )\n end\n\n rescue => e\n puts \"An error occured: #{e.to_s}\\n #{$@}\"\n ensure\n listen_thread.kill if listen_thread\n disconnect( socket )\n end\n end",
"def run\n connect = false\n until connect do\n begin\n call { |server| @server = server ; start }\n rescue\n Waves::Logger.error e.to_s\n sleep 1\n end\n connect = true\n end\n end",
"def start_handler\n\n\t\t# Maximum number of seconds to run the handler\n\t\tctimeout = 150\n\t\t\n\t\tif (exploit_config and exploit_config['active_timeout'])\n\t\t\tctimeout = exploit_config['active_timeout'].to_i\n\t\tend\n\t\n\t\t# Take a copy of the datastore options\n\t\trhost = datastore['RHOST']\n\t\tlport = datastore['LPORT']\n\t\t\n\t\t# Ignore this if one of the required options is missing\n\t\treturn if not rhost\n\t\treturn if not lport\n\t\n\t\t# Only try the same host/port combination once\n\t\tphash = rhost + ':' + lport.to_s\n\t\treturn if self.listener_pairs[phash]\n\t\tself.listener_pairs[phash] = true\n\n\t\t# Start a new handling thread\n\t\tself.listener_threads << Thread.new {\n\t\t\tclient = nil\n\t\t\t\n\t\t\tprint_status(\"Started bind handler\")\n\n\t\t\tif (rhost == nil)\n\t\t\t\traise ArgumentError, \n\t\t\t\t\t\"RHOST is not defined; bind stager cannot function.\",\n\t\t\t\t\tcaller\n\t\t\tend\n\n\t\t\tstime = Time.now.to_i\n\t\t\t\n\t\t\twhile (stime + ctimeout > Time.now.to_i)\n\t\t\t\tbegin\n\t\t\t\t\tclient = Rex::Socket::Tcp.create(\n\t\t\t\t\t\t'PeerHost' => rhost,\n\t\t\t\t\t\t'PeerPort' => lport.to_i,\n\t\t\t\t\t\t'Proxies' => datastore['Proxies'],\n\t\t\t\t\t\t'Context' =>\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t'Msf' => framework,\n\t\t\t\t\t\t\t\t'MsfPayload' => self,\n\t\t\t\t\t\t\t\t'MsfExploit' => assoc_exploit\n\t\t\t\t\t\t\t})\n\t\t\t\trescue Rex::ConnectionRefused\n\t\t\t\t\t# Connection refused is a-okay\n\t\t\t\trescue ::Exception\n\t\t\t\t\twlog(\"Exception caught in bind handler: #{$!}\")\n\t\t\t\tend\n\n\t\t\t\tbreak if client\n\n\t\t\t\t# Wait a second before trying again\n\t\t\t\tRex::ThreadSafe.sleep(0.5)\n\t\t\tend\n\n\t\t\t# Valid client connection?\n\t\t\tif (client)\n\t\t\t\n\t\t\t\t# Increment the has connection counter\n\t\t\t\tself.pending_connections += 1\n\t\t\t\t\n\t\t\t\t# Start a new thread and pass the client connection\n\t\t\t\t# as the input and output pipe. Client's are expected\n\t\t\t\t# to implement the Stream interface.\n\t\t\t\tconn_threads << Thread.new {\n\t\t\t\t\tbegin\n\t\t\t\t\t\thandle_connection(client)\n\t\t\t\t\trescue\n\t\t\t\t\t\telog(\"Exception raised from BindTcp.handle_connection: #{$!}\")\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\telse\n\t\t\t\twlog(\"No connection received before the handler completed\")\n\t\t\tend\n\t\t}\n\tend",
"def serve\n @serverTransport.listen()\n\n begin\n while (true)\n @thread_q.push(:token)\n Thread.new do\n begin\n while (true)\n client = @serverTransport.accept()\n trans = @transportFactory.getTransport(client)\n prot = @protocolFactory.getProtocol(trans)\n begin\n while (true)\n @processor.process(prot, prot)\n end\n rescue TTransportException, TProtocolException => e\n ensure\n trans.close()\n end\n end\n rescue Exception => e\n @exception_q.push(e)\n ensure\n @thread_q.pop() # thread died!\n end\n end\n end\n ensure\n @serverTransport.close()\n end\n end",
"def tcp_listener(output_queue)\n @logger.info(\"Starting syslog tcp listener\", :address => \"#{@host}:#{@port}\")\n @tcp = TCPServer.new(@host, @port)\n @tcp.do_not_reverse_lookup = true\n\n while !stop?\n socket = @tcp.accept\n @tcp_sockets << socket\n metric.increment(:connections)\n\n Thread.new(output_queue, socket) do |output_queue, socket|\n tcp_receiver(output_queue, socket)\n end\n end\n ensure\n close_tcp\n end",
"def run\n connect\n end",
"def monitor_socket\n\t\tself.waiters = []\n\n\t\t# Spawn a new thread that monitors the socket\n\t\tself.dispatcher_thread = ::Thread.new {\n\t\t\twhile (true)\n\t\t\t\tbegin\n\t\t\t\t\trv = Rex::ThreadSafe.select([ self.sock.fd ], nil, nil, 2)\n\t\t\t\trescue\n\t\t\t\t\tdlog(\"Exception caught in monitor_socket: #{$!}\", 'meterpreter', LEV_1)\n\t\t\t\tend\n\n\t\t\t\tbegin\n\t\t\t\t\tpacket = receive_packet\n\t\t\t\trescue EOFError\n\t\t\t\t\tbreak\n\t\t\t\tend\n\n\t\t\t\tif (packet)\n\t\t\t\t\tdispatch_inbound_packet(packet)\n\t\t\t\tend\n\t\t\tend\n\t\t}\n\tend",
"def handle_monitor_connection request\n @node.connections.select {|c| c.connected?}.each do |conn|\n respond(request, [:connection, [:connected, conn.info]])\n end\n end",
"def start_listening\n\t\t@socket = UDPSocket.new\n\t\t@socket.bind(@info.host, @info.port)\n\t\twhile true\n\t\t\ttext, sender = @socket.recvfrom(1024)\n\n\t\t\t\targuments = Marshal.load(text)\n\t\t\t\tmsg_type = arguments.shift\n\t\t\t\t\n\t\t\t\tputs \"Received msg: #{msg_type}, #{arguments} from remote #{sender}\"\n\n\t\t\t\tif msg_type == \"GET\"\n\t\t\t\t\tkey, port = arguments\n\t\t\t\t\tget(key.to_i, sender[3], port)\n\t\t\t\telsif msg_type == \"PUT\"\n\t\t\t\t\tkey, value = arguments\n\t\t\t\t\tput(key.to_i, value)\n\t\t\t\telsif msg_type == \"PING\"\n\t\t\t\t\tnode = arguments.first\n\t\t\t\t\tsend_message [\"OK\"], 0, node.host, node.port\n\t\t\t\telsif msg_type == \"OK\"\n\t\t\t\t\t@waiting = false\n\t\t\t\telsif msg_type == \"NEW_NODE\"\n\t\t\t\t\tnew_node_info = arguments.first\n\t\t\t\t\tnew_network_node(new_node_info)\n\t\t\t\telsif msg_type == \"ADD_NODE\"\n\t\t\t\t\tinfo = arguments.first\n\t\t\t\t\t@neighbour_nodes << info\n\t\t\t\telsif msg_type == \"DROP_NODE\"\n\t\t\t\t\tinfo = arguments\n\t\t\t\t\tto_delete = @neighbour_nodes.select { |n| n.host == info.host and n.port == info.port}\n\t\t\t\t\t@neighbour_nodes - to_delete\n\t\t\t\telsif msg_type == \"RESOURCE_TABLE\"\n\t\t\t\t\t@resource_table = arguments.first\n\t\t\t\telsif msg_type == \"ADD_RESOURCE\"\n\t\t\t\t\tresource = arguments.first\n\t\t\t\t\t@resource_table.merge!(resource)\n\t\t\t\t\tputs \"#{resource.to_a}\"\n\t\t\t\t\tputs \"#{request_queue}\"\n\t\t\t\t\tresolve_queue(resource.to_a[0][0])\n\t\t\t\tend \n\t\tend\n\tend",
"def listen\n\t\t@response = Thread.new do\n\t\t\tloop do\n\t\t\t\t# Revisamos si se cerro la conexion\n\t\t\t\t# @server.eof?\n\t\t\t\t# @request.kill\n\t\t\t\t# @server.close\n\t\t\t\t# puts \"Reconectando...\"\n\t\t\t\t# reconect\n\t\t\t\t# Optenemos el mensaje del servidor\n\t\t\t\tmessage = @server.gets.chomp\n\t\t\t\t# Optenemos el tipo\n\t\t\t\tmessage_t = message[0]\n\t\t\t\t# Quitamos los dos primeros caracteres\n\t\t\t\tmessage.slice!(0..1)\n\t\t\t\t# Revisamos si es un mensaje o una nota a reproducir\n\t\t\t\tif message_t == \"i\"\n\t\t\t\t\t# Mostramos el mensaje en consola\n\t\t\t\t\tputs message\n\t\t\t\telsif message_t == \"n\"\n\t\t\t\t\t# Tomamos solo la nota y reproducimos su equivalente\n\t\t\t\t\t# Reproducimos la nota musical\n\t\t\t\t\tputs \"Nota no valida [q-p][a-l]!\" unless RMSound::note_play(message[0])\n\t\t\t\telsif message_t == \"s\"\n\t\t\t\t\t# Resivimos una lista de ips de un esclavo\n\t\t\t\t\t# Actualizamos la lista interna si esta por defecto\n\t\t\t\t\tif @ip_integrity == \"d\"\n\t\t\t\t\t\tputs \"Lista de IPs actualizada\"\n\t\t\t\t\t\t@ip_integrity = \"s\"\n\t\t\t\t\t\t@arry_ips = message.split(' ')\n\t\t\t\t\tend\n\t\t\t\telsif message_t == \"m\"\n\t\t\t\t\t# Resivimos una lista de ips de un maestro\n\t\t\t\t\t# Actualizamos la lista interna si esta por defecto\n\t\t\t\t\tif @ip_integrity != \"m\"\n\t\t\t\t\t\tputs \"Lista de IPs actualizada\"\n\t\t\t\t\t\t@ip_integrity = \"m\"\n\t\t\t\t\t\t@arry_ips = message.split(' ')\n\t\t\t\t\tend\n\t\t\t\telsif message_t == \"r\"\n\t\t\t\t\tputs message\n\t\t\t\telse\n\t\t\t\t\t# Mostramos el mensaje en consola\n\t\t\t\t\tputs \"Desconocido: \" << message\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend",
"def cycle\n @initialized = true\n @socket = UDPSocket.new\n @socket.bind(@listen_address, @listen_port)\n \n initial_counters = {}\n \n if @counters_list_file && File.exist?(@counters_list_file)\n counter_keys = IO.read(@counters_list_file).split(\"\\n\")\n counter_keys.each do |key|\n initial_counters[key] = 0\n end\n end\n \n # block will be called when a request comes from the core\n # if exit is received the method will return\n network_loop(pipe, @socket, initial_counters) do |msg, counters, gauges|\n data = {}\n \n values = gauges\n \n counters.each do |k, v|\n values[k] = v / interval_in_seconds()\n end\n \n unless values.empty?\n if @host\n data['host'] = @host\n end\n \n data[@app] = {}\n data[@app][@res] = values\n end\n \n send_metrics(data)\n end\n \n end",
"def start\n _connect\n sleep 1\n end",
"def joinall\n @connections.each do |k,v|\n\tv[:thread].join\n end\n end",
"def all_connections\n hold do |c|\n sync do\n yield c\n @available_connections.each{|conn| yield conn}\n end\n end\n end",
"def all_connections\n hold do |c|\n sync do\n yield c\n @available_connections.each{|conn| yield conn}\n end\n end\n end",
"def start\n # Synchronous (mutual exclusion) message processing is handled by a\n # producer-consumer approach. The socket pushes messages onto this queue,\n # which are processed by a consumer thread one at a time.\n @messages = Queue.new\n @message_consumer = Thread.new do\n loop do\n meths = @messages.pop\n begin\n meths.each { |meth, args| broadcast_sync meth, *args }\n rescue\n options[:logger].error $!\n end\n end\n end\n \n @socket = connect\n username = @options[:user]\n username ||= @nick\n realname = @options[:name]\n realname ||= @nick\n \n pass @options[:server_password] if @options[:server_password]\n user username, @nick, @nick, realname\n nick @nick\n \n while line = @socket.gets\n meths = receive line # parse the line and get a list of methods to call\n @messages.push meths # push the methods on the queue; the consumer thread will execute all the synchronous methods\n # then execute all the other methods in their own thread\n meths.each { |meth, args| broadcast meth, *args }\n end\n end",
"def start\n @quit = nil\n @socket = self.connect()\n self.on_message(/^PING/) { |event|\n self.send_raw_line(\"PING \"+event[:matchdata].post_match)\n }\n self.on_server_message(353) { |event|\n }\n self.on_server_message(376) do |event|\n if @password and !@authenticated then\n self.message 'NickServ', \"IDENTIFY #{@password}\"\n @authenticated = true\n end\n @channels.each { |channel|\n if channel.kind_of? Hash then\n self.send_raw_line(\"JOIN \"+channel.keys.first+\" \"+channel.values.first)\n else\n self.send_raw_line(\"JOIN \"+channel)\n end\n }\n end\n \n self.send_raw_line(\"USER \"+@nickname+\" \"+@nickname+\" \"+@nickname+\" \"+@nickname)\n self.send_raw_line(\"NICK \"+@nickname)\n begin\n while line = @socket.gets\n handle_raw_line(line) \n end\n rescue IOError => ioe\n raise ioe unless @quit\n end\n end",
"def run\n while s = @socket.accept do\n Thread.new do\n begin\n input = s.gets.strip\n result = @backend.process(input)\n if result.ready?\n log \"OK: #{input}\"\n s.puts \"OK\"\n s.puts result.value\n elsif result.error\n log \"ERROR: #{input}: #{result.error}\"\n if result.error.respond_to?(:backtrace)\n result.error.backtrace.each do |line|\n log \"ERROR: #{line}\"\n end\n end\n s.puts \"ERROR\"\n s.puts result.error.to_s\n else\n log \"PENDING: #{input}\"\n s.puts \"PENDING\"\n end\n rescue Errno::EPIPE\n log \"pipe closed\"\n # client closed the socket early\n rescue => e\n puts e\n puts e.backtrace.join(\"\\n\")\n ensure\n s.close\n end\n end\n end\n rescue Errno::EBADF\n # socket got cleaned up, but we're done anyway\n end",
"def listen_requests(handler)\n loop do\n message = handler.listen # expecting array\n command_data = message[0] if message != nil\n\n if command_data != nil && command_data != \"\"\n command = command_data.split(\"\\s\")[0]\n if command == \"close\" || command == \"quit\"\n remove_client(handler) # when client disconnects or closes communication\n elsif command == \"clients\"\n handler.send(\"Server has #{@@clients.length()} clients connected :D\")\n elsif command == \"server -v\"\n handler.send(\"Your SERVER VERSION is #{SERVER_VERSION} ;)\")\n else # if isn't a server request, let the client handler manage it\n handler.manage_requests(message)\n end\n end\n end\n end",
"def run\n @stats[:start_time] = Time.now\n\n BasicSocket.do_not_reverse_lookup = true\n\n @acceptor = Thread.new do\n loop do\n begin\n accept_connection\n rescue StopServer\n @socket.close rescue Object\n break\n rescue Errno::EMFILE\n cull_workers(\"Too many open files or sockets\")\n sleep @timeout / 100\n rescue Errno::ECONNABORTED\n begin\n client.close\n rescue Object => e\n logger.warn \"Got exception closing socket (client aborted connection) #{e}\"\n end\n rescue Object => e\n logger.fatal \"Unhandled exception: #{e}. TELL BLAINE HE'S A MORON.\"\n logger.debug e.backtrace.join(\"\\n\")\n end\n end\n\n graceful_shutdown\n end\n\n return @acceptor\n end",
"def listen\n while true\n data = $BLIX_REQUEST.pop\n response = do_handle(body)\n if response\n puts \"[DummyServer] response: data=#{data}, options=#{options}\" if $DEBUG\n $BLIX_RESPONSE.push(data)\n end\n end\n end",
"def connect\n connection.tap do |c|\n c.start\n end\n end",
"def startHttp(callback_opts) do\n server = TCPServer.new @host, @port\n while session = server.accept\n @implementation(session, callback_opts)\n end\n end",
"def listen\n @response = Thread.new do\n loop {\n msg = JSON.parse(@server.gets.chomp)\n puts sprintf(\"msg in listen: %s\\n\", msg.inpect)\n if msg[0].string?\n puts msg[0]\n elsif msg[0] == 0x00\n if msg[1] == \"CLIST\"\n puts msg[1].to_s.gsub!(/[\"\\[\\]]/,'')\n elsif msg[1] == \"DISCONNECT\"\n puts \"disconnecting\"\n exit(0)\n end\n elsif msg[0] == 0x01\n puts \"Access denied, wrong password or no such client_ID\"\n exit(0)\n elsif msg[0] == 0x02\n puts \"Duplicate client_ID\"\n exit(0)\n end\n }\n end\n end",
"def serve\n Lamp.logger.info 'Starting Lamp service ...'\n @thread = Thread.new { @server.serve }\n sleep SPIN while @thread.alive? and not socket.handle\n @port = socket.handle.addr[1] and Lamp.logger.info status if @thread.alive?\n @thread\n end",
"def listen\n @@em.schedule do\n EventMachine::WebSocket.run(:host => @host, :port => @port) do |ws|\n ws.onopen { }\n ws.onclose { @connection_event_handlers[:closed].each { |h| h.call self } }\n ws.onerror { |e| @connection_event_handlers[:error].each { |h| h.call self } }\n ws.onmessage { |msg| handle_message(msg, ws) }\n end\n end\n self\n end",
"def enqueue_from_server\n @writter = Thread.new do \n while @online\n begin\n if @socket.eof?\n @socket.close\n puts \"Server is down, please press quit\"\n break\n end\n msg = @socket.gets.chop\n if msg =~ /Advice from channel/ \n @advices << msg\n else\n msg = \"=> #{msg}\"\n @response << msg\n end\n rescue => e\n puts \"Error writter Thread #{e}\"\n end\n end\n end\n end",
"def init_messaging\n @read_thread = Thread.new { read_loop }\n end",
"def start\n if @supernode_table.empty?\n # The supernode table is empty, so this node is probably \n # starting and not promoted to supernode mode.\n \n # NOTE The +attempt_fetch_supernodes+ will block if no \n # supernode is found. Since supernodes should still work \n # even there is no other active supernodes, a thread is created\n # here. So it can still accept connections from other ordinary\n # nodes.\n Thread.new do \n # 1. Get supernodes from cache or bootstrap node\n Routing.log {|logger| logger.info(self.class) {'1. Getting SNs ...'}}\n sns = attempt_fetch_supernodes\n # 2. Connect to supernodes\n Routing.log {|logger| logger.info(self.class) {'2. Connecting to SNs ...'}}\n connect_supernodes(sns)\n end\n else\n # It is promoted to supernode mode.\n @supernode_table.supernodes.each do |sn|\n @lock.synchronize { @socks << sn.socket }\n end\n end\n\n # 3. Start the background threads\n @request_supernode_thread = start_request_supernodes_thread\n @compute_hits_thread = start_compute_hits_thread\n\n # 4. Create the server socket and handle incoming messages\n @server = TCPServer.open(@driver.config['listening_port'].to_i)\n @socks << @server\n @running = true\n while @running\n # Wait for messages from other nodes\n ready = select(@socks,nil,nil,@timeout)\n readable = ready[0]\n\n unless readable.nil?\n readable.each do |sock|\n if sock == @server # Accept new client\n client = @server.accept\n accepted = on_handshaking(client)\n if accepted\n @lock.synchronize { @socks << client }\n else\n client.close\n end\n elsif sock.eof? # Socket has disconnected\n Routing.log {|logger| logger.info(self.class) {'Socket has disconnected.'}}\n @lock.synchronize {@socks.delete(sock)}\n # Remove it if it is in supernode table\n @supernode_table.delete(sock.node) if @supernode_table.include?(sn.node)\n sock.close\n else # Message is ready for reading\n msg = @protocol.read_message(sock)\n unless msg.nil?\n @bandwidth_manager.downloaded(msg.bytesize,Time.now-message.ftime.to_time) unless @bandwidth_manager.nil?\n handle_message(msg,sock)\n else\n Routing.log {|logger| logger.error(self.class) {'The message read is nil.'}}\n end\n end\n end\n else # Timeout\n @socks.delete_if do |sock|\n sock.closed? # Discarded by supernode table\n end\n end\n end\n end"
] |
[
"0.74341583",
"0.7157197",
"0.7110875",
"0.70952433",
"0.7015998",
"0.6843977",
"0.6842806",
"0.683896",
"0.682579",
"0.6790225",
"0.6780209",
"0.67702806",
"0.67486066",
"0.67424226",
"0.6728888",
"0.6696061",
"0.6688816",
"0.668869",
"0.66851056",
"0.6674531",
"0.66651124",
"0.66218925",
"0.66041756",
"0.66041756",
"0.6589681",
"0.65729445",
"0.6566549",
"0.65644854",
"0.65635157",
"0.65537655",
"0.6542413",
"0.65389127",
"0.65105236",
"0.6500815",
"0.6497995",
"0.64865744",
"0.6484284",
"0.64816487",
"0.6480158",
"0.6470722",
"0.64639425",
"0.6463096",
"0.64609754",
"0.644244",
"0.6424894",
"0.6424066",
"0.6420757",
"0.6412853",
"0.64128304",
"0.6408472",
"0.64046013",
"0.6396137",
"0.63636893",
"0.6350579",
"0.63473105",
"0.6345316",
"0.6340404",
"0.6313955",
"0.63102096",
"0.63025427",
"0.6294826",
"0.62947",
"0.62881726",
"0.6286754",
"0.62737465",
"0.6254795",
"0.6252095",
"0.6244597",
"0.6235182",
"0.6225082",
"0.6220108",
"0.62163603",
"0.62144685",
"0.6204227",
"0.6202816",
"0.62009865",
"0.6189345",
"0.618639",
"0.618547",
"0.61818343",
"0.61728466",
"0.61647034",
"0.6157838",
"0.61487806",
"0.61404616",
"0.61404616",
"0.6134025",
"0.6112843",
"0.6111387",
"0.60965806",
"0.6090748",
"0.60877943",
"0.60829693",
"0.60804796",
"0.60692173",
"0.60377693",
"0.6030591",
"0.60282534",
"0.60197246",
"0.6018572"
] |
0.618364
|
79
|
GET /liners GET /liners.json
|
def index
@liners = Liner.all
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def show\n @trainer = Trainer.find(params[:id])\n\n render json: @trainer.as_json(only: [:name], include: [:trainees])\n end",
"def index\n @litters = Litter.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @litters }\n end\n end",
"def index\n @liner_items = LinerItem.all\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json {\n render json: @line_items \n }\n end\n end",
"def list_lines\n RailLine.list_lines\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n\n @metro_lines = MetroLine.all\n\n render json: @metro_lines\n\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @line_items }\n end\n end",
"def get_lines_with_http_info(year, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: BettingApi.get_lines ...'\n end\n # verify the required parameter 'year' is set\n if @api_client.config.client_side_validation && year.nil?\n fail ArgumentError, \"Missing the required parameter 'year' when calling BettingApi.get_lines\"\n end\n # resource path\n local_var_path = '/lines'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = year\n query_params[:'week'] = opts[:'week'] if !opts[:'week'].nil?\n query_params[:'seasonType'] = opts[:'season_type'] if !opts[:'season_type'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'home'] = opts[:'home'] if !opts[:'home'].nil?\n query_params[:'away'] = opts[:'away'] if !opts[:'away'].nil?\n query_params[:'conference'] = opts[:'conference'] if !opts[:'conference'].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 = []\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<GameLines>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: BettingApi#get_lines\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n @line = Line.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def show\n @kennel_litter = KennelLitter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kennel_litter }\n end\n end",
"def show\n @trainer = Trainer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trainer }\n end\n end",
"def show\n puts params.inspect.green\n\n @line_item = LineItem.find(params[:id])\n\n puts @line_items.inspect.magenta\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def create\n company_name = params[:liner][:company_name]\n company = Company.find_or_create_by name: company_name\n @liner = company.liners.new(liner_params)\n\n respond_to do |format|\n if @liner.save\n format.html { redirect_to @liner, notice: 'Liner was successfully created.' }\n format.json { render :show, status: :created, location: @liner }\n else\n format.html { render :new }\n format.json { render json: @liner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_liner\n @liner = Liner.find(params[:id])\n end",
"def index\n @line_livers = LineLiver.all\n end",
"def show\n @litter = Litter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @litter }\n end\n end",
"def range\n #@lines = Line.where(:no=> params[:id])\n line_range = params[:id].split(\"-\")\n @lines = Line.where(:no=>line_range[0]..line_range[1])\n line_op = Hash.new\n respond_to do |format|\n format.html #range.html.erb\n #format.json { render json: @lines }\n format.json {render :json => @lines.to_json(:only =>[:line, :stanza_id],:methods=>[:section,:runningno,:share_url])}\n #format.json {render :json => {:lines => @lines, :marker => line_op }}\n end\n end",
"def trainings\n render json: @plan.trainings\n end",
"def get_ruling_lines!\n self.get_rulings\n end",
"def klines(options)\n request :public, :get, :klines, options\n end",
"def index\n @batting_lines = BattingLine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @batting_lines }\n end\n end",
"def index\n @itineraries = Itinerary.all.order(:start_date)\n respond_to do |format|\n format.html do\n @itineraries = @itineraries.map{ |i| ::ItineraryPresenter.new(i) }\n @itineraries = build_pagination(@itineraries)\n end\n format.json do\n render json: {\n itineraries: @itineraries.map do |itinerary|\n {\n properties: {\n id: itinerary.id,\n start_date: itinerary.start_date,\n end_date: itinerary.end_date,\n available_seat: itinerary.available_seat,\n description: itinerary.description,\n user: itinerary.user,\n start_loc: itinerary.locations.where(is_origin: true).first.address,\n end_loc: itinerary.locations.where(is_origin: false).first.address,\n eta: helpers.distance_of_time_in_words(format(itinerary.start_date), format(itinerary.end_date)),\n }\n }\n end\n }\n end\n end\nend",
"def show\n @lineup = Lineup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lineup }\n end\n end",
"def show\n @lineitem = Lineitem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lineitem }\n end\n end",
"def show\n @line = ReportingForms::Tanimoto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def index\n @itineraryList = Itinerary.all\n render json: @itineraryList, status: 200\n end",
"def index\n @linehauls = Linehaul.all\n end",
"def index\n @lifelines = Lifeline.all\n end",
"def index\n @line_items = @order.line_items\n\n render json: @line_items\n end",
"def show\n @lent = Lent.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lent }\n end\n end",
"def ruling_lines\n get_ruling_lines!\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def index\n @minerals = Mineral.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @minerals }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def index\n @line_stations = LineStation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_stations }\n end\n end",
"def full_line\n RetortApi.markov_chain(identity: { medium: 'bible' })\nend",
"def show\n @litra = Litra.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @litra }\n end\n end",
"def index\n @lines = Line.all\n end",
"def index\n @lines = Line.all\n end",
"def new\n @kennel_litter = KennelLitter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @kennel_litter }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @line_item }\n end\n end",
"def show\n @ledger_entry = LedgerEntry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @ledger_entry }\n end\n end",
"def new\n @trainer = Trainer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trainer }\n end\n end",
"def get_lines(year, opts = {})\n data, _status_code, _headers = get_lines_with_http_info(year, opts)\n data\n end",
"def show\n @trail = Trail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trail }\n end\n end",
"def show\n @trail = Trail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trail }\n end\n end",
"def index\n @traces = Trace.all\n url_string = ''\n data = []\n pdist = 0\n plat = @traces.first.latitude\n plon = @traces.first.longitude\n traces = @traces.pluck(:latitude, :longitude).map { |lat, lon| { latitude: lat, longitude: lon } }\n response = HTTParty.post(\n url_string,\n :body => traces.to_json,\n :headers => { 'Content-Type' => 'application/json' }\n )\n @traces.each_with_index do |t,index|\n data << {\n \"latitude\": t.latitude,\n \"longitude\": t.longitude,\n \"distance\": distance([plat,plon],[t.latitude, t.longitude]) + pdist,\n \"elevation\": response[index]\n }\n pdist += distance([plat,plon],[t.latitude, t.longitude])\n plat = t.latitude\n plon = t.longitude\n end\n render json: data\n end",
"def range\n #@lines = Line.where(:no=> params[:id])\n line_range = params[:id].split(\"-\")\n @stanzas = Stanza.where(:section_id=>line_range[0]..line_range[2],:runningno=>line_range[1]..line_range[3]).order('no')\n lines = Array.new\n @stanzas.each {|s| lines << s.cached_lines }\n respond_to do |format|\n format.html #range.html.erb\n format.json {render :json => lines.to_json(:only =>[:line, :stanza_id],:methods=>[:section,:runningno,:share_url,:no])}\n end\n end",
"def index\n @lineitems = Lineitem.all\n end",
"def new\n @line = Line.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line }\n end\n end",
"def show\n @item_line = ItemLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @item_line }\n end\n end",
"def index\n @retailers = Retailer.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @retailers }\n end\n end",
"def index\n @partners = Partner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @partners }\n end\n end",
"def show\n @line_item1 = LineItem1.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @line_item1 }\n end\n end",
"def show\n @traces = Trace.find_by(id: params[:id])\n url_string = ''\n response = HTTParty.get(url_string)\n data = {\n \"latitude\": @traces.latitude,\n \"longitude\": @traces.longitude,\n \"elevation\": response.body.to_i\n }\n render json: data\n end",
"def index\n @trainees = Trainee.all\n\n respond_to do |format|\n format.html\n format.json { render :json => @trainees.to_json(:except => [:created_at, :updated_at], :include => {:skills => { :except => [:created_at, :updated_at]} }) }\n end\n\n end",
"def airlines(params={})\n perform_get('/airlines.xml', params)\n end",
"def index \n respond_to do |format|\n format.html do\n authenticate_user!\n if params[:all] != \"true\"\n @trails = Trail.where(source: current_user.organization)\n else\n @trails = Trail.all\n end\n end\n format.json do\n @trails = Trail.all\n entity_factory = ::RGeo::GeoJSON::EntityFactory.instance\n features = []\n @trails.each do |trail|\n # taking a trip to Null Island, because RGeo::GeoJSON chokes on empty geometry here\n feature = entity_factory.feature(RGeo::Geographic.spherical_factory.point(0,0), trail.id, trail.attributes)\n features.push(feature)\n end\n collection = entity_factory.feature_collection(features)\n my_geojson = RGeo::GeoJSON::encode(collection)\n render json: Oj.dump(my_geojson)\n end\n end\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def index\n @line_items = LineItem.all\n end",
"def getelevators\n puts params\n elid = params[\"columnid\"]\n\n elevators = Elevator.where(:column_id => elid)\n\n puts elevators.inspect\n \n respond_to do |format|\n format.json { render json: elevators }\n end\n end",
"def new\n @labor_cost_line = LaborCostLine.new\n @laborers = Laborer.scoped - @labor_cost.line_items.all.map{|li| li.laborer}\n\n respond_to do |format|\n format.js\n format.html # new.html.erb\n format.xml { render :xml => @labor_cost_line }\n end\n end",
"def show\n @batting_line = BattingLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @batting_line }\n end\n end",
"def index\n @applied_lines = AppliedLine.all\n end",
"def show\n @author = Author.find(params[:id])\n @author_lines = AuthorLine.order('position').includes(:author, :article => :conference).where(:author_id => params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @author }\n end\n end",
"def show\n @sample_line = SampleLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sample_line }\n end\n end",
"def new\n @litter = Litter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @litter }\n end\n end",
"def index\n @litters = Litter.all\n end",
"def show\n @line = Line.find_by_no(params[:id]) || not_found\n authorize! :index, @line\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def index\n @order_line_items = @order.order_line_items\n\n render json: @order_line_items\n end",
"def timeline\n Chirp.timeline(current_user)\n render json: @chirp\n end",
"def show\n @invent_journal_line = InventJournalLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invent_journal_line }\n end\n end",
"def legislators(options = {})\n get('/legislators', options)\n end",
"def index\n\t #@racers = Racer.all\n\t if !request.accept || request.accept == \"*/*\"\n\t\t\trender plain: \"/api/racers/#{params[:racer_id]}/entries\"\n\t\telse\n\t\t\t#real implementation ...\n\t\tend\n\t end",
"def index\n @line_items = LineItem.all\nend",
"def index\n @line_items = LineItem.all\nend",
"def data_headlines(project_id, opts = {})\n get \"projects/#{project_id}/data/headlines\", opts\n end",
"def show\n @event_entry = EventEntry.find(params[:id])\n @runners = @event_entry.runners\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @event_entry }\n end\n end",
"def index\n #since trainers is conncected to gym\n #find the gym where the id of gym is equal to the trainer\n #SO THIS WILL TARGET SPECEFIC PEOPLE WHOS GYM.ID IS EQUAL TO TRAINER gym_id\n @gym=Gym.find(params[:gym_id])\n @trainers=Trainer.where(gym_id: @gym.id)\n render json: @trainers, include: :clients, status: :ok\n end",
"def show\n @training_calendar = TrainingCalendar.find(params[:id])\n @trainees = Trainee.find_all_by_training_calendar_id(@training_calendar.id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @training_calendar }\n end\n end"
] |
[
"0.6039168",
"0.58767325",
"0.58016515",
"0.57443225",
"0.57294405",
"0.5728215",
"0.5728215",
"0.5728215",
"0.5728215",
"0.5711922",
"0.5696984",
"0.5663344",
"0.5617804",
"0.5560731",
"0.5555264",
"0.55024165",
"0.5497077",
"0.5494845",
"0.5459527",
"0.5457283",
"0.5456509",
"0.5455979",
"0.54503393",
"0.54311687",
"0.5409579",
"0.53393286",
"0.52916706",
"0.528419",
"0.52760345",
"0.5266547",
"0.5265742",
"0.5258382",
"0.52558655",
"0.52480704",
"0.5248008",
"0.52466553",
"0.5246533",
"0.5245576",
"0.5245576",
"0.5245576",
"0.5245576",
"0.5245576",
"0.5245576",
"0.5245576",
"0.5244805",
"0.5238486",
"0.5237763",
"0.52205265",
"0.52205265",
"0.5219238",
"0.52125806",
"0.5192094",
"0.5191523",
"0.51863575",
"0.5160809",
"0.5160809",
"0.51574385",
"0.5150661",
"0.5148494",
"0.51473016",
"0.5136725",
"0.5122288",
"0.51036555",
"0.5100094",
"0.50969124",
"0.5093678",
"0.50887626",
"0.5080309",
"0.50577444",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5055053",
"0.5039823",
"0.50270706",
"0.50262386",
"0.50026554",
"0.50015515",
"0.49944502",
"0.4982588",
"0.498145",
"0.49784157",
"0.49772444",
"0.49748453",
"0.49737582",
"0.49714372",
"0.49703962",
"0.49693072",
"0.49693072",
"0.49683496",
"0.49654207",
"0.4963697",
"0.4960791"
] |
0.704166
|
0
|
GET /liners/1 GET /liners/1.json
|
def show
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def index\n @liners = Liner.all\n end",
"def show\n @trainer = Trainer.find(params[:id])\n\n render json: @trainer.as_json(only: [:name], include: [:trainees])\n end",
"def show\n @line = Line.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def index\n @litters = Litter.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @litters }\n end\n end",
"def show\n @trainer = Trainer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trainer }\n end\n end",
"def set_liner\n @liner = Liner.find(params[:id])\n end",
"def index\n\n @metro_lines = MetroLine.all\n\n render json: @metro_lines\n\n end",
"def show\n puts params.inspect.green\n\n @line_item = LineItem.find(params[:id])\n\n puts @line_items.inspect.magenta\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def index\n @liner_items = LinerItem.all\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_items }\n end\n end",
"def show\n @litter = Litter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @litter }\n end\n end",
"def show\n @line_item1 = LineItem1.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @line_item1 }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json {\n render json: @line_items \n }\n end\n end",
"def index\n @line_items = LineItem.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @line_items }\n end\n end",
"def create\n company_name = params[:liner][:company_name]\n company = Company.find_or_create_by name: company_name\n @liner = company.liners.new(liner_params)\n\n respond_to do |format|\n if @liner.save\n format.html { redirect_to @liner, notice: 'Liner was successfully created.' }\n format.json { render :show, status: :created, location: @liner }\n else\n format.html { render :new }\n format.json { render json: @liner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def range\n #@lines = Line.where(:no=> params[:id])\n line_range = params[:id].split(\"-\")\n @lines = Line.where(:no=>line_range[0]..line_range[1])\n line_op = Hash.new\n respond_to do |format|\n format.html #range.html.erb\n #format.json { render json: @lines }\n format.json {render :json => @lines.to_json(:only =>[:line, :stanza_id],:methods=>[:section,:runningno,:share_url])}\n #format.json {render :json => {:lines => @lines, :marker => line_op }}\n end\n end",
"def show\n @kennel_litter = KennelLitter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kennel_litter }\n end\n end",
"def show\n @line = ReportingForms::Tanimoto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def get_lines_with_http_info(year, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: BettingApi.get_lines ...'\n end\n # verify the required parameter 'year' is set\n if @api_client.config.client_side_validation && year.nil?\n fail ArgumentError, \"Missing the required parameter 'year' when calling BettingApi.get_lines\"\n end\n # resource path\n local_var_path = '/lines'\n\n # query parameters\n query_params = {}\n query_params[:'year'] = year\n query_params[:'week'] = opts[:'week'] if !opts[:'week'].nil?\n query_params[:'seasonType'] = opts[:'season_type'] if !opts[:'season_type'].nil?\n query_params[:'team'] = opts[:'team'] if !opts[:'team'].nil?\n query_params[:'home'] = opts[:'home'] if !opts[:'home'].nil?\n query_params[:'away'] = opts[:'away'] if !opts[:'away'].nil?\n query_params[:'conference'] = opts[:'conference'] if !opts[:'conference'].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 = []\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<GameLines>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: BettingApi#get_lines\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n @lineup = Lineup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lineup }\n end\n end",
"def new\n @line = Line.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line }\n end\n end",
"def show\n @trail = Trail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trail }\n end\n end",
"def show\n @trail = Trail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trail }\n end\n end",
"def show\n @lineitem = Lineitem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lineitem }\n end\n end",
"def show\n @litra = Litra.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @litra }\n end\n end",
"def list_lines\n RailLine.list_lines\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_item }\n end\n end",
"def index\n @line_livers = LineLiver.all\n end",
"def trainings\n render json: @plan.trainings\n end",
"def show\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @line_item }\n end\n end",
"def new\n @trainer = Trainer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trainer }\n end\n end",
"def index\n @minerals = Mineral.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @minerals }\n end\n end",
"def show\n @line = Line.find_by_no(params[:id]) || not_found\n authorize! :index, @line\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def show\n @lent = Lent.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lent }\n end\n end",
"def index\n @batting_lines = BattingLine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @batting_lines }\n end\n end",
"def full_line\n RetortApi.markov_chain(identity: { medium: 'bible' })\nend",
"def new\n @line_item1 = LineItem1.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @line_item1 }\n end\n end",
"def show\n @item_line = ItemLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @item_line }\n end\n end",
"def index\n @line_stations = LineStation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @line_stations }\n end\n end",
"def get_subject_by_curricular_line\n @subjects = Subject.get_by_career(params[:career_id],params[:cl_id])\n render :json => @subjects\n end",
"def show\n @runner = Runner.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @runner }\n end\n end",
"def show\n @sample_line = SampleLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sample_line }\n end\n end",
"def show\n @ledger_entry = LedgerEntry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @ledger_entry }\n end\n end",
"def index\n @lines = Line.all\n end",
"def index\n @lines = Line.all\n end",
"def show\n @batting_line = BattingLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @batting_line }\n end\n end",
"def show\n @mineral = Mineral.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @mineral }\n end\n end",
"def range\n #@lines = Line.where(:no=> params[:id])\n line_range = params[:id].split(\"-\")\n @stanzas = Stanza.where(:section_id=>line_range[0]..line_range[2],:runningno=>line_range[1]..line_range[3]).order('no')\n lines = Array.new\n @stanzas.each {|s| lines << s.cached_lines }\n respond_to do |format|\n format.html #range.html.erb\n format.json {render :json => lines.to_json(:only =>[:line, :stanza_id],:methods=>[:section,:runningno,:share_url,:no])}\n end\n end",
"def index\n @itineraries = Itinerary.all.order(:start_date)\n respond_to do |format|\n format.html do\n @itineraries = @itineraries.map{ |i| ::ItineraryPresenter.new(i) }\n @itineraries = build_pagination(@itineraries)\n end\n format.json do\n render json: {\n itineraries: @itineraries.map do |itinerary|\n {\n properties: {\n id: itinerary.id,\n start_date: itinerary.start_date,\n end_date: itinerary.end_date,\n available_seat: itinerary.available_seat,\n description: itinerary.description,\n user: itinerary.user,\n start_loc: itinerary.locations.where(is_origin: true).first.address,\n end_loc: itinerary.locations.where(is_origin: false).first.address,\n eta: helpers.distance_of_time_in_words(format(itinerary.start_date), format(itinerary.end_date)),\n }\n }\n end\n }\n end\n end\nend",
"def show\n @line = Line.includes({:sublines => :transactions}).find(params[:id])\n @budget = @line.budget\n @subtitle = '%s %d' % [@line.category.capitalize, @line.line_number]\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line }\n end\n end",
"def index\n @itineraryList = Itinerary.all\n render json: @itineraryList, status: 200\n end",
"def show\n @invent_journal_line = InventJournalLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invent_journal_line }\n end\n end",
"def show\n @renter = Renter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @renter }\n end\n end",
"def get_ruling_lines!\n self.get_rulings\n end",
"def index\n @line_items = @order.line_items\n\n render json: @line_items\n end",
"def show\n @lei = Lei.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @lei }\n end\n end",
"def new\n @kennel_litter = KennelLitter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @kennel_litter }\n end\n end",
"def index\n #since trainers is conncected to gym\n #find the gym where the id of gym is equal to the trainer\n #SO THIS WILL TARGET SPECEFIC PEOPLE WHOS GYM.ID IS EQUAL TO TRAINER gym_id\n @gym=Gym.find(params[:gym_id])\n @trainers=Trainer.where(gym_id: @gym.id)\n render json: @trainers, include: :clients, status: :ok\n end",
"def show\n @airlin = Airlin.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @airlin }\n end\n end",
"def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end",
"def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end",
"def index\n @lifelines = Lifeline.all\n end",
"def show\n @order_line = OrderLine.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @order_line }\n end\n end",
"def show\n @rayon = Rayon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @rayon }\n end\n end",
"def new\n @litter = Litter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @litter }\n end\n end",
"def show\n @timeline = Timeline.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @timeline }\n end\n end",
"def show\n @weekline = Weekline.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @weekline }\n end\n end",
"def klines(options)\n request :public, :get, :klines, options\n end",
"def show\n @line_station = LineStation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @line_station }\n end\n end",
"def index\n @partners = Partner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @partners }\n end\n end",
"def index\n @linehauls = Linehaul.all\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @lineup = Lineup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lineup }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @line_item }\n end\n end",
"def show\n @event_entry = EventEntry.find(params[:id])\n @runners = @event_entry.runners\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @event_entry }\n end\n end",
"def show\n @author = Author.find(params[:id])\n @author_lines = AuthorLine.order('position').includes(:author, :article => :conference).where(:author_id => params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @author }\n end\n end",
"def new\n @lineitem = Lineitem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lineitem }\n end\n end",
"def new\n @tln = Orbituarysite.find(params[:id]) \n @timeline = @tln.timelines.new\n @orbituarysite = current_user.orbituarysites.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @timeline }\n end\n end",
"def show\n @slitter = Slitter.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @slitter }\n end\n end",
"def new\n @invent_journal_line = InventJournalLine.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invent_journal_line }\n end\n end",
"def index\n @lineitems = Lineitem.all\n end",
"def new\n @labor_cost_line = LaborCostLine.new\n @laborers = Laborer.scoped - @labor_cost.line_items.all.map{|li| li.laborer}\n\n respond_to do |format|\n format.js\n format.html # new.html.erb\n format.xml { render :xml => @labor_cost_line }\n end\n end"
] |
[
"0.6836065",
"0.6083431",
"0.58974695",
"0.57809585",
"0.5733845",
"0.5717326",
"0.56469184",
"0.56080073",
"0.55987537",
"0.5595026",
"0.5595026",
"0.5595026",
"0.5595026",
"0.55837494",
"0.55795395",
"0.5577129",
"0.55625665",
"0.55320835",
"0.55211914",
"0.5517878",
"0.5478583",
"0.54627323",
"0.5447059",
"0.5436065",
"0.5429175",
"0.5429175",
"0.54078573",
"0.5394399",
"0.53929067",
"0.5381092",
"0.53802866",
"0.53802866",
"0.53802866",
"0.53802866",
"0.53802866",
"0.53802866",
"0.53802866",
"0.5376299",
"0.5347144",
"0.53454024",
"0.5345026",
"0.53087354",
"0.5297448",
"0.5293754",
"0.5283316",
"0.5279361",
"0.5272386",
"0.5266407",
"0.5261497",
"0.5247576",
"0.52469015",
"0.5236774",
"0.52292097",
"0.5221115",
"0.5221115",
"0.520682",
"0.5192721",
"0.5191916",
"0.51659745",
"0.51635575",
"0.5155425",
"0.5148874",
"0.514276",
"0.5134944",
"0.51246226",
"0.51244986",
"0.5124056",
"0.5116332",
"0.5116183",
"0.5111039",
"0.5111039",
"0.5096608",
"0.5083464",
"0.50799537",
"0.5079812",
"0.50796896",
"0.50771683",
"0.5073453",
"0.506977",
"0.5052989",
"0.5052589",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.5048075",
"0.50474614",
"0.50435585",
"0.5042775",
"0.5027253",
"0.5024749",
"0.5015949",
"0.5002831",
"0.50013536",
"0.49992976",
"0.4998902"
] |
0.0
|
-1
|
POST /liners POST /liners.json
|
def create
company_name = params[:liner][:company_name]
company = Company.find_or_create_by name: company_name
@liner = company.liners.new(liner_params)
respond_to do |format|
if @liner.save
format.html { redirect_to @liner, notice: 'Liner was successfully created.' }
format.json { render :show, status: :created, location: @liner }
else
format.html { render :new }
format.json { render json: @liner.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create\n p'*'*800\n p params\n\n @trainer = Trainer.new(trainer_params)\n\n p @trainer\n\n if @trainer.save\n render json: @trainer, status: :created, location: @trainer\n else\n render json: @trainer.errors, status: :unprocessable_entity\n end\n end",
"def create\n @line_liver = LineLiver.new(line_liver_params)\n\n respond_to do |format|\n if @line_liver.save\n format.html { redirect_to @line_liver, notice: 'Line liver was successfully created.' }\n format.json { render :show, status: :created, location: @line_liver }\n else\n format.html { render :new }\n format.json { render json: @line_liver.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @liners = Liner.all\n end",
"def create\n @trainer = Trainer.new(params[:trainer])\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to @trainer, :notice => 'Trainer was successfully created.' }\n format.json { render :json => @trainer, :status => :created, :location => @trainer }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @trainer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @trainer = Trainer.new(params[:trainer])\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to @trainer, notice: 'Trainer was successfully created.' }\n format.json { render json: @trainer, status: :created, location: @trainer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def liner_params\n puts(params)\n params.require(:liner).permit(:new_liner_reference, :previous_liner_reference, :liner_reference, :location, :row, :collumn, :structure, :plant, :width, :height, :thickness, :original_thickness, :thickness_loss_per_day, :current_thickness)\n end",
"def create\n @trainer = Trainer.new(trainer_params)\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to @trainer, notice: 'Trainer was successfully created.' }\n format.json { render :show, status: :created, location: @trainer }\n else\n format.html { render :new }\n format.json { render json: @trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @trainer = Trainer.new(trainer_params)\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to @trainer, notice: 'Trainer was successfully created.' }\n format.json { render :show, status: :created, location: @trainer }\n else\n format.html { render :new }\n format.json { render json: @trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @trainees = TraineeBatch.new(params[:participants][:ids], params[:training_calendar_id])\n respond_to do |format|\n if @trainees.save\n format.html { redirect_to training_calendar_path(params[:training_calendar_id]), :notice => 'The participant(s) were successfully added.' }\n format.json { render :json => @trainees, :status => :created, :location => @trainees }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @trainees.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def new\n @trainer = Trainer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trainer }\n end\n end",
"def create\n @linehaul = Linehaul.new(linehaul_params)\n\n respond_to do |format|\n if @linehaul.save\n format.html { redirect_to linehauls_path, notice: 'Linehaul was successfully created.' }\n format.json { render :show, status: :created, location: @linehaul }\n else\n format.html { render :new }\n format.json { render json: @linehaul.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @linhkien = Linhkien.new(linhkien_params)\n\n respond_to do |format|\n if @linhkien.save\n format.html { redirect_to @linhkien, notice: 'Linhkien was successfully created.' }\n format.json { render :show, status: :created, location: @linhkien }\n else\n format.html { render :new }\n format.json { render json: @linhkien.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_liner\n @liner = Liner.find(params[:id])\n end",
"def create\n @workshop = Workshop.new(workshop_params)\n puts \"====================================\"\n puts params['trainers']\n puts \"====================================\"\n trainers = params['trainers'].map do |id|\n Trainer.find(id)\n end\n @workshop.trainers << trainers\n\n\n respond_to do |format|\n if @workshop.save\n format.html { redirect_to @workshop, notice: 'Workshop was successfully created.' }\n format.json { render :show, status: :created, location: @workshop }\n else\n format.html { render :new }\n format.json { render json: @workshop.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lineup = Lineup.new(params[:lineup])\n\n respond_to do |format|\n if @lineup.save\n format.html { redirect_to @lineup, notice: 'Lineup was successfully created.' }\n format.json { render json: @lineup, status: :created, location: @lineup }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lineup.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @line = Line.new(line_params)\n\n respond_to do |format|\n if @line.save\n format.html { redirect_to new_line_path, notice: 'Line was successfully created. 5 points are awarded to your score.' }\n format.json { render json: @line, status: :created, location: @line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @kennel_litter = KennelLitter.new(params[:kennel_litter])\n\n respond_to do |format|\n if @kennel_litter.save\n format.html { redirect_to @kennel_litter, notice: 'Kennel litter was successfully created.' }\n format.json { render json: @kennel_litter, status: :created, location: @kennel_litter }\n else\n format.html { render action: \"new\" }\n format.json { render json: @kennel_litter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @renter = Renter.new(renter_params)\n\n respond_to do |format|\n if @renter.save\n format.html { redirect_to @renter, notice: 'Renter was successfully created.' }\n format.json { render :show, status: :created, location: @renter }\n else\n format.html { render :new }\n format.json { render json: @renter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @item_line = ItemLine.new(params[:item_line])\n\n respond_to do |format|\n if @item_line.save\n format.html { redirect_to @item_line, notice: 'Item line was successfully created.' }\n format.json { render json: @item_line, status: :created, location: @item_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @item_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lifeline = Lifeline.new(lifeline_params)\n\n respond_to do |format|\n if @lifeline.save\n format.html { redirect_to @lifeline, notice: 'Lifeline was successfully created.' }\n format.json { render :show, status: :created, location: @lifeline }\n else\n format.html { render :new }\n format.json { render json: @lifeline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @esseline = Esseline.new(esseline_params)\n\n respond_to do |format|\n if @esseline.save\n format.html { redirect_to @esseline, notice: 'Esseline was successfully created.' }\n format.json { render :show, status: :created, location: @esseline }\n else\n format.html { render :new }\n format.json { render json: @esseline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @applied_line = AppliedLine.new(applied_line_params)\n\n respond_to do |format|\n if @applied_line.save\n format.html { redirect_to @applied_line, notice: 'Applied line was successfully created.' }\n format.json { render :show, status: :created, location: @applied_line }\n else\n format.html { render :new }\n format.json { render json: @applied_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @line = Line.new(line_params)\n\n respond_to do |format|\n if @line.save\n format.html { redirect_to @line, notice: \"Line was successfully created.\" }\n format.json { render :show, status: :created, location: @line }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @line_up = LineUp.new(line_up_params)\n\n respond_to do |format|\n if @line_up.save\n format.html { redirect_to @line_up, notice: 'Line up was successfully created.' }\n format.json { render :show, status: :created, location: @line_up }\n else\n format.html { render :new }\n format.json { render json: @line_up.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @sundry_grn = SundryGrn.new\n\n 3.times do\n line= @sundry_grn.line_items.build\n end\n\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @sundry_grn }\n end\n end",
"def create\n @line_item = LineItem.new(params[:line_item])\n\n respond_to do |format|\n if @line_item.save\n format.html { redirect_to @line_item, notice: 'Line item was successfully created.' }\n format.json { render json: @line_item, status: :created, location: @line_item }\n else\n format.html { render action: \"new\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create \n @line_item = LineItem.new(line_item_params)\n respond_to do |format|\n if @line_item.save\n format.html { redirect_to '/line_items', notice: \"Line item was successfully created.\" }\n format.json { render :show, status: :created, location: @line_item }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @pt_trainer = Pt::Trainer.new(pt_trainer_params)\n\n respond_to do |format|\n if @pt_trainer.save\n format.html { redirect_to @pt_trainer, notice: 'Trainer was successfully created.' }\n format.json { render :show, status: :created, location: @pt_trainer }\n else\n format.html { render :new }\n format.json { render json: @pt_trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @airlin = Airlin.new(params[:airlin])\n\n respond_to do |format|\n if @airlin.save\n format.html { redirect_to @airlin, notice: 'Airlin was successfully created.' }\n format.json { render json: @airlin, status: :created, location: @airlin }\n else\n format.html { render action: \"new\" }\n format.json { render json: @airlin.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @invent_journal_line = InventJournalLine.new(params[:invent_journal_line])\n\n respond_to do |format|\n if @invent_journal_line.save\n format.html { redirect_to @invent_journal_line, notice: 'Invent journal line was successfully created.' }\n format.json { render json: @invent_journal_line, status: :created, location: @invent_journal_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @invent_journal_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @lineup = Lineup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lineup }\n end\n end",
"def new\n @trainees = TraineeBatch.new([], params[:training_calendar_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @trainees }\n end\n end",
"def create\n @rayon = Rayon.new(params[:rayon])\n\n respond_to do |format|\n if @rayon.save\n format.html { redirect_to @rayon, notice: 'Rayon was successfully created.' }\n format.json { render json: @rayon, status: :created, location: @rayon }\n else\n format.html { render action: \"new\" }\n format.json { render json: @rayon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def destroy\n @liner.destroy\n respond_to do |format|\n format.html { redirect_to liners_url, notice: 'Liner was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def create\n @trainer = Trainer.new(trainer_params)\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to @trainer, notice: 'Trener został pomyslnie dodany' }\n else\n format.html { render action: 'new' }\n end\n end\n end",
"def create\n @trail = Trail.new(params[:trail])\n\n respond_to do |format|\n if @trail.save\n format.html { redirect_to @trail, notice: 'Trail was successfully created.' }\n format.json { render json: @trail, status: :created, location: @trail }\n else\n format.html { render action: \"new\" }\n format.json { render json: @trail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @line = Line.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line }\n end\n end",
"def create\n @line_item = @order.line_items.new(line_item_params)\n\n if @line_item.save\n render json: @line_item, status: :created, location: [@order, @line_item]\n else\n render json: @line_item.errors, status: :unprocessable_entity\n end\n end",
"def create\n respond_to do |format|\n @lineitem = Lineitem.create!(lineitem_params)\n @participants = Participant.all\n\t @users = User.all\n if @lineitem.save\n format.html { redirect_to @lineitem, notice: 'Lineitem was successfully created.' }\n format.json { render action: 'show', status: :created, location: @lineitem }\n else\n format.html { render action: 'new' }\n format.json { render json: @lineitem.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @trainer = Trainer.new params[:trainer]\n if @trainer.save\n current_user.trainers << @trainer\n redirect_to :action => 'show', :id => @trainer.id\n else\n flash.now[:error] = 'There was a problem creating your trainer'\n flash.now[:errors] = @trainer.errors\n render :action => 'new'\n end\n end",
"def create\n @weekline = Weekline.new(params[:weekline])\n\n respond_to do |format|\n if @weekline.save\n format.html { redirect_to @weekline, notice: 'Weekline was successfully created.' }\n format.json { render json: @weekline, status: :created, location: @weekline }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weekline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lineaedesal = Lineaedesal.new(params[:lineaedesal])\n\n respond_to do |format|\n if @lineaedesal.save\n format.html { redirect_to(@lineaedesal, :notice => 'Lineaedesal was successfully created.') }\n format.xml { render :xml => @lineaedesal, :status => :created, :location => @lineaedesal }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @lineaedesal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @ledger_entry = LedgerEntry.new(params[:ledger_entry])\n\n respond_to do |format|\n if @ledger_entry.save\n format.html { redirect_to @ledger_entry, :notice => 'Ledger entry was successfully created.' }\n format.json { render :json => @ledger_entry, :status => :created, :location => @ledger_entry }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @ledger_entry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @lyric = Lyric.new(params[:lyric])\n\n respond_to do |format|\n if @lyric.save\n format.html { redirect_to @lyric, notice: 'Lyric was successfully created.' }\n format.json { render json: @lyric, status: :created, location: @lyric }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lyric.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post\n Rentlinx.client.post(self)\n end",
"def trainer_params\n params.require(:trainer).permit(:siren, :sigle, :effectif, :adresse, :nom_dirigeant, :email_dirigeant, :crawled_for_email)\n end",
"def create\n @labor_cost_line = LaborCostLine.new(params[:labor_cost_line])\n @labor_cost_line.labor_set = @labor_cost\n @laborers = Laborer.scoped\n\n respond_to do |format|\n if @labor_cost_line.save\n format.js {\n @labor_cost_lines = @labor_cost.line_items\n }\n format.html { redirect_to(labor_cost_line_item_path(@labor_cost, @labor_cost_line), :notice => 'Labor cost line was successfully created.') }\n format.xml { render :xml => @labor_cost_line, :status => :created, :location => @labor_cost_line }\n else\n format.js\n format.html { render :action => \"new\" }\n format.xml { render :xml => @labor_cost_line.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @lyric = Lyric.new(lyric_params)\n\n respond_to do |format|\n if @lyric.save\n format.html { redirect_to @lyric, notice: 'Lyric was successfully created.' }\n format.json { render json: @lyric, status: :created, location: @lyric }\n else\n format.html { render action: \"new\" }\n format.json { render json: @lyric.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @rower = Rower.new(rower_params)\n\n respond_to do |format|\n if @rower.save\n format.html { redirect_to @rower, notice: 'Rower was successfully created.' }\n format.json { render :show, status: :created, location: @rower }\n else\n format.html { render :new }\n format.json { render json: @rower.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @textline = Textline.new(textline_params)\n\n respond_to do |format|\n if @textline.save\n format.html { redirect_to @textline, notice: 'Textline was successfully created.' }\n format.json { render :show, status: :created, location: @textline }\n else\n format.html { render :new }\n format.json { render json: @textline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @time_line = TimeLine.new(time_line_params)\n\n respond_to do |format|\n if @time_line.save\n format.html { redirect_to @time_line, notice: 'Time line was successfully created.' }\n format.json { render :show, status: :created, location: @time_line }\n else\n format.html { render :new }\n format.json { render json: @time_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @phone_line = PhoneLine.new(phone_line_params)\n\n respond_to do |format|\n if @phone_line.save\n format.html { redirect_to phone_lines_url, notice: 'Phone line was successfully created.' }\n format.json { render :show, status: :created, location: @phone_line }\n else\n format.html { render :new }\n format.json { render json: @phone_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @trail = Trail.new(trail_params)\n\n respond_to do |format|\n if @trail.save\n format.html { redirect_to @trail, notice: 'Trail was successfully created.' }\n format.json { render :show, status: :created, location: @trail }\n else\n format.html { render :new }\n format.json { render json: @trail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def trainer_params\n params.require(:trainer).permit(:name, :email, :phone, :description, :logo)\n end",
"def create\n #New itinerary\n @newItinerary = Itinerary.new itin_params\n @newItinerary.save\n #new event and event_itinerary\n @eventArray = event_array\n @eventArray.each do |event|\n event = Event.new(event) #iterate through, add event itinerary to each one with itinerary ID from first save.\n event.save\n @newEventItin = EventItinerary.new(:event_id => event[:id],:itinerary_id => @newItinerary[:id])\n @newEventItin.save\n end\n \n respond_to do |format|\n format.json { render :json => [{:event => @eventArray},{ :itineraries => @newItinerary},{:event_itineraries => @newEventItin} ]}\n end\n end",
"def create\n @trade_line = TradeLine.new(trade_line_params)\n\n respond_to do |format|\n if @trade_line.save\n format.html { redirect_to @trade_line, notice: 'Trade line was successfully created.' }\n format.json { render action: 'show', status: :created, location: @trade_line }\n else\n format.html { render action: 'new' }\n format.json { render json: @trade_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @trail = Trail.new(trail_params)\n\n respond_to do |format|\n if @trail.save\n format.html { redirect_to @trail, notice: 'Trail was successfully created.' }\n format.json { render action: 'show', status: :created, location: @trail }\n else\n format.html { render action: 'new' }\n format.json { render json: @trail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @itinerary = Itinerary.new(itinerary_params)\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to @itinerary, notice: 'Itinerary was successfully created.' }\n format.json { render :show, status: :created, location: @itinerary }\n else\n format.html { render :new }\n format.json { render json: @itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @line = ReportingForms::Tanimoto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line }\n end\n end",
"def create\n @penyelesaian = Penyelesaian.new(penyelesaian_params)\n\n unless params[:next_line].nil?\n @penyelesaian.status = \"Closed\"\n else\n @penyelesaian.status = \"Open\"\n end\n\n respond_to do |format|\n if @penyelesaian.save\n if params[:next_line]\n format.html { redirect_to \"/internals/\" + params[:penyelesaian][:id_rfc] + \"/new_internal\", notice: \"Penyelesaian was successfully created.\" }\n format.json { render :show, status: :created, location: @penyelesaian }\n else\n format.html { redirect_to rfc_path(params[:penyelesaian][:id_rfc]), notice: \"Penyelesaian was successfully created.\" }\n format.json { render :show, status: :created, location: @penyelesaian }\n end\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @penyelesaian.errors, status: :unprocessable_entity }\n end\n end\n end",
"def linehaul_params\n params.require(:linehaul).permit(:route)\n end",
"def new\n @lineitem = Lineitem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lineitem }\n end\n end",
"def new\n @kennel_litter = KennelLitter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @kennel_litter }\n end\n end",
"def create\n @itinerary = Itinerary.new(itinerary_params)\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to @itinerary, notice: \"Itinerary was successfully created.\" }\n format.json { render :show, status: :created, location: @itinerary }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @line_item }\n end\n end",
"def create\n @runner = Runner.new(runner_params)\n @runner.status = true\n @area = Area.find_by(name: @runner.area)\n @runner.area_id = @area.id\n respond_to do |format|\n if @runner.save\n format.html { redirect_to @runner, notice: 'Runner was successfully created.' }\n format.json { render :show, status: :created, location: @runner }\n else\n format.html { render :new }\n format.json { render json: @runner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @batting_line = BattingLine.new(params[:batting_line])\n\n respond_to do |format|\n if @batting_line.save\n format.html { redirect_to @batting_line, notice: 'Batting line was successfully created.' }\n format.json { render json: @batting_line, status: :created, location: @batting_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @batting_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @line_item = LineItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @line_item }\n end\n end",
"def create\n @sample_line = SampleLine.new(params[:sample_line])\n\n respond_to do |format|\n if @sample_line.save\n format.html { redirect_to @sample_line, notice: 'Sample line was successfully created.' }\n format.json { render json: @sample_line, status: :created, location: @sample_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sample_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def trainings\n render json: @plan.trainings\n end",
"def create\n @admin_itinerary = Itinerary.new(admin_itinerary_params)\n\n respond_to do |format|\n if @admin_itinerary.save\n format.html { redirect_to session['previous_url'] || admin_itineraries_url, notice: 'Itinerari è stato creato con successo.' }\n format.json { render :show, status: :created, location: @admin_itinerary }\n else\n format.html { render :new }\n format.json { render json: @admin_itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @line_station = LineStation.new(params[:line_station])\n\n respond_to do |format|\n if @line_station.save\n format.html { redirect_to @line_station, notice: 'Line station was successfully created.' }\n format.json { render json: @line_station, status: :created, location: @line_station }\n else\n format.html { render action: \"new\" }\n format.json { render json: @line_station.errors, status: :unprocessable_entity }\n end\n end\n end",
"def line_params\r\n params.require(:line).permit(:name)\r\n end",
"def create\n @search_line = SearchLine.new(search_line_params)\n\n respond_to do |format|\n if @search_line.save\n format.html { redirect_to @search_line, notice: 'Search line was successfully created.' }\n format.json { render :show, status: :created, location: @search_line }\n else\n format.html { render :new }\n format.json { render json: @search_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def trainer_params\n params.require(:trainer).permit(:name, :info)\n end",
"def create\n\n @user = User.new(users_params)\n @user.save\n @trainer = Trainer.new(trainer_params)\n @trainer.user_id = @user.id\n @trainer.created_at = @user.created_at\n @trainer.updated_at = @user.updated_at\n\n respond_to do |format|\n if @trainer.save\n format.html { redirect_to '/trainers', notice: 'Trainer was successfully created.' }\n format.json { render :show, status: :created, location: @trainer }\n else\n format.html { render :new }\n format.json { render json: @trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @landmark = current_user.landmarks.build(params[:landmark])\n @landmark.save\n respond_to do |format|\n format.html { }\n if (@landmark)\n format.json { render json: @landmark }\n else\n format.json { render json: @landmark.errors.full_messages, :status => 400 }\n end\n end\n end",
"def new\n @rfq = Rfq.new\n 3.times { @rfq.rfq_lines.build }\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @rfq }\n end\n end",
"def create\n @learner = Learner.new(learner_params)\n\n respond_to do |format|\n if @learner.save\n format.html { head :created, content_type: \"text/html\" }\n format.json { head :created, location: @order }\n else\n format.html { head :bad_request, content_type: \"text/html\" }\n format.json { head :bad_request }\n end\n end\n end",
"def create\n @order_line = OrderLine.new(params[:order_line])\n\n respond_to do |format|\n if @order_line.save\n format.html { redirect_to @order_line, notice: 'Order line was successfully created.' }\n format.json { render json: @order_line, status: :created, location: @order_line }\n else\n format.html { render action: \"new\" }\n format.json { render json: @order_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @plains_walker = PlainsWalker.new(plains_walker_params)\n\n respond_to do |format|\n if @plains_walker.save\n format.html { redirect_to @plains_walker, notice: 'Plains walker was successfully created.' }\n format.json { render :show, status: :created, location: @plains_walker }\n else\n format.html { render :new }\n format.json { render json: @plains_walker.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @line_detail = LineDetail.new(line_detail_params)\n generate_id\n respond_to do |format|\n if @line_detail.save\n format.html { redirect_to @line_detail, notice: 'Line detail was successfully created.' }\n format.json { render action: 'show', status: :created, location: @line_detail }\n else\n format.html { render action: 'new' }\n format.json { render json: @line_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def show\n @trainer = Trainer.find(params[:id])\n\n render json: @trainer.as_json(only: [:name], include: [:trainees])\n end",
"def create\n @trainee = Trainee.new(trainee_params)\n\n respond_to do |format|\n if @trainee.save\n format.html { redirect_to @trainee, notice: 'Trainee was successfully created.' }\n format.json { render :show, status: :created, location: @trainee }\n else\n format.html { render :new }\n format.json { render json: @trainee.errors, status: :unprocessable_entity }\n end\n end\n end",
"def trainer_params\n params.require(:trainer).permit(:name, :lastname, :birth_date, :time_acting, :qualifications, :availability, :price, :uid, :picture)\n end",
"def create_flight_creation(body)\r\n # Prepare query url.\r\n _path_url = '/v1/airline/flights'\r\n _query_builder = Configuration.get_base_uri\r\n _query_builder << _path_url\r\n _query_url = APIHelper.clean_url _query_builder\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json',\r\n 'content-type' => 'application/json; charset=utf-8'\r\n }\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.post(\r\n _query_url,\r\n headers: _headers,\r\n parameters: body.to_json\r\n )\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_context.response.raw_body)\r\n Response.from_hash(decoded)\r\n end",
"def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end",
"def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trail }\n end\n end",
"def create\n @prayer = Prayer.new(params[:prayer])\n\n respond_to do |format|\n if @prayer.save\n format.html { redirect_to @prayer, notice: 'Prayer was successfully created.' }\n format.json { render json: @prayer, status: :created, location: @prayer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @prayer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @diciplina = Diciplina.new(params[:diciplina])\n respond_to do |format|\n if @diciplina.save\n format.html { redirect_to @diciplina, notice: 'Diciplina was successfully created.' }\n format.json { render json: @diciplina, status: :created, location: @diciplina }\n else\n format.html { render action: \"new\" }\n format.json { render json: @diciplina.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @weekline = Weekline.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weekline }\n end\n end"
] |
[
"0.6214964",
"0.5854367",
"0.5851985",
"0.5804397",
"0.57401246",
"0.5656456",
"0.5631725",
"0.5631725",
"0.55973405",
"0.54875636",
"0.54869634",
"0.54577047",
"0.54260683",
"0.5419705",
"0.541122",
"0.54039025",
"0.53778136",
"0.53751636",
"0.5367665",
"0.5345483",
"0.53257036",
"0.53219527",
"0.530908",
"0.53064686",
"0.53047025",
"0.5286399",
"0.5250396",
"0.5244357",
"0.52412313",
"0.5239123",
"0.52244925",
"0.52211833",
"0.51922786",
"0.5192197",
"0.51899564",
"0.51825476",
"0.5178147",
"0.5176832",
"0.51671934",
"0.51663536",
"0.51629806",
"0.5156965",
"0.5155884",
"0.5150269",
"0.51458895",
"0.5122461",
"0.5107903",
"0.5098726",
"0.50957406",
"0.5094394",
"0.5081465",
"0.5074989",
"0.5071109",
"0.50674784",
"0.5066906",
"0.5039023",
"0.5035195",
"0.5034002",
"0.50322604",
"0.50303984",
"0.50235116",
"0.50225514",
"0.5022118",
"0.50187516",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.5018179",
"0.50015926",
"0.49963915",
"0.4993352",
"0.49920222",
"0.499022",
"0.49876392",
"0.49847588",
"0.49846563",
"0.49842864",
"0.4980828",
"0.49781805",
"0.497813",
"0.49719462",
"0.49656516",
"0.49611437",
"0.4957638",
"0.49550858",
"0.49526253",
"0.49521735",
"0.49508697",
"0.49427548",
"0.49426502",
"0.49426502",
"0.49350205",
"0.49295023",
"0.49248436"
] |
0.64722174
|
0
|
PATCH/PUT /liners/1 PATCH/PUT /liners/1.json
|
def update
respond_to do |format|
liner = Liner.find_by(liner_reference: liner_params["liner_reference"])
original_thickness = liner.original_thickness.to_i
current_thickness = liner_params["current_thickness"].to_i
thickness_loss_per_day = original_thickness - current_thickness
liner_params["thickness_loss_per_day"] = thickness_loss_per_day
if @liner.update(liner_params)
format.html { redirect_to @liner, notice: 'Liner was successfully updated.' }
format.json { render :show, status: :ok, location: @liner }
else
format.html { render :edit }
format.json { render json: @liner.errors, status: :unprocessable_entity }
end
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def patch!\n request! :patch\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 @line = Line.find(params[:id])\n\n respond_to do |format|\n if @line.update_attributes(line_params)\n format.html { redirect_to new_line_path, notice: 'Line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render verb: \"edit\" }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, **args); end",
"def update\n respond_to do |format|\n if @liner_item.update(liner_item_params)\n format.html { redirect_to @liner_item, notice: 'Liner item was successfully updated.' }\n format.json { render :show, status: :ok, location: @liner_item }\n else\n format.html { render :edit }\n format.json { render json: @liner_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end",
"def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end",
"def update\n respond_to do |format|\n if @line_liver.update(line_liver_params)\n format.html { redirect_to @line_liver, notice: 'Line liver was successfully updated.' }\n format.json { render :show, status: :ok, location: @line_liver }\n else\n format.html { render :edit }\n format.json { render json: @line_liver.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item1 = LineItem1.find(params[:id])\n\n respond_to do |format|\n if @line_item1.update_attributes(params[:line_item1])\n format.html { redirect_to @line_item1, :notice => 'Line item1 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @line_item1.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @line = Line.find_by_no(params[:id])\n\n respond_to do |format|\n if @line.update_attributes(params[:line])\n format.html { redirect_to @line, notice: 'Line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @trainer = Trainer.find(params[:id])\n\n if @trainer.update(trainer_params)\n head :no_content\n else\n render json: @trainer.errors, status: :unprocessable_entity\n end\n end",
"def update\n @litter = Litter.find(params[:id])\n\n respond_to do |format|\n if @litter.update_attributes(params[:litter])\n format.html { redirect_to @litter, notice: 'Litter was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @litter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @slitter = Slitter.find(params[:id])\n\n respond_to do |format|\n if @slitter.update_attributes(params[:slitter])\n format.html { redirect_to @slitter, notice: 'Slitter was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @slitter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @lifeline.update(lifeline_params)\n format.html { redirect_to @lifeline, notice: 'Lifeline was successfully updated.' }\n format.json { render :show, status: :ok, location: @lifeline }\n else\n format.html { render :edit }\n format.json { render json: @lifeline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end",
"def update\n respond_to do |format|\n if @line_detail.update(line_detail_params)\n format.html { redirect_to @line_detail, notice: 'Line detail was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @line_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @trainer = Trainer.find(params[:id])\n\n respond_to do |format|\n if @trainer.update_attributes(params[:trainer])\n format.html { redirect_to @trainer, :notice => 'Trainer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @trainer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @trainer = Trainer.find(params[:id])\n\n respond_to do |format|\n if @trainer.update_attributes(params[:trainer])\n format.html { redirect_to @trainer, notice: 'Trainer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @trainer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @renter = Renter.find(params[:id])\n\n respond_to do |format|\n if @renter.update_attributes(params[:renter])\n format.html { redirect_to @renter, :notice => 'Renter was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @renter.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @rayon = Rayon.find(params[:id])\n\n respond_to do |format|\n if @rayon.update_attributes(params[:rayon])\n format.html { redirect_to @rayon, notice: 'Rayon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @rayon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def patch(path, params = {})\n request(:patch, path, params)\n end",
"def update\n respond_to do |format|\n if @line_pet.update(line_pet_params)\n format.html { redirect_to @line_pet, notice: 'Line pet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @line_pet.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 @lyric.update(lyric_params)\n format.html { redirect_to @lyric, notice: 'Lyric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lyric.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update # PATCH\n raise NotImplementedError\n end",
"def update\n @renter = Renter.find(params[:id])\n\n respond_to do |format|\n if @renter.update_attributes(params[:renter])\n format.html { redirect_to @renter, notice: 'Renter was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @renter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @kennel_litter = KennelLitter.find(params[:id])\n\n respond_to do |format|\n if @kennel_litter.update_attributes(params[:kennel_litter])\n format.html { redirect_to @kennel_litter, notice: 'Kennel litter was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @kennel_litter.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @lunch.update(lunch_params)\n format.html { redirect_to @lunch, notice: 'Lunch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @lunch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lyric = Lyric.find(params[:id])\n\n respond_to do |format|\n if @lyric.update_attributes(params[:lyric])\n format.html { redirect_to @lyric, notice: 'Lyric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lyric.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params)\n time(\"PATCH #{path}\") { Cloudflarer.new.patch(path, params) }\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 @invent_journal_line = InventJournalLine.find(params[:id])\n\n respond_to do |format|\n if @invent_journal_line.update_attributes(params[:invent_journal_line])\n format.html { redirect_to @invent_journal_line, notice: 'Invent journal line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invent_journal_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @my_prayer_request = PrayerRequest.find(params[:id])\n\n respond_to do |format|\n if @my_prayer_request.update_attributes(params[:my_prayer_request])\n format.html { redirect_to @my_prayer_request, notice: 'My prayer request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @my_prayer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @clientsOffers = ClientsOffers.find(params[:id])\n\n respond_to do |format|\n if @clientsOffers.update_attributes(params[:clientsOffers])\n format.html { redirect_to @clientsOffers, notice: 'ClientsOffers was succesfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @clientsOffers.errors, status: :unprocesable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @esseline.update(esseline_params)\n format.html { redirect_to @esseline, notice: 'Esseline was successfully updated.' }\n format.json { render :show, status: :ok, location: @esseline }\n else\n format.html { render :edit }\n format.json { render json: @esseline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @line_concept = args[:line_concept] if args.key?(:line_concept)\n @stops = args[:stops] if args.key?(:stops)\n end",
"def update\n respond_to do |format|\n if @line.update(line_params)\n format.html { redirect_to @line, notice: \"Line was successfully updated.\" }\n format.json { render :show, status: :ok, location: @line }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, :notice => 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @line_item.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @prayer_request = PrayerRequest.find(params[:id])\n\n respond_to do |format|\n if @prayer_request.update_attributes(params[:prayer_request])\n format.html { redirect_to @prayer_request, notice: 'Prayer request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @prayer_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @item_line = ItemLine.find(params[:id])\n\n respond_to do |format|\n if @item_line.update_attributes(params[:item_line])\n format.html { redirect_to @item_line, notice: 'Item line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @item_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line = Line.find(params[:id])\n\n respond_to do |format|\n if @line.update_attributes(params[:line])\n format.html { redirect_to(@line, :notice => 'Line was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @line.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @linehaul.update(linehaul_params)\n format.html { redirect_to linehauls_path, notice: 'Linehaul was successfully updated.' }\n format.json { render :show, status: :ok, location: @linehaul }\n else\n format.html { render :edit }\n format.json { render json: @linehaul.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @line_item.update(line_item_params)\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @line_item.update(line_item_params)\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @line_item.update(line_item_params)\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end",
"def update\n respond_to do |format|\n if @diner.update(diner_params)\n format.html { redirect_to @diner, notice: 'Diner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @diner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line_item = LineItem.find(params[:id])\n\n respond_to do |format|\n if @line_item.update_attributes(params[:line_item])\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @applied_line.update(applied_line_params)\n format.html { redirect_to @applied_line, notice: 'Applied line was successfully updated.' }\n format.json { render :show, status: :ok, location: @applied_line }\n else\n format.html { render :edit }\n format.json { render json: @applied_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lineitem = Lineitem.find(params[:id])\n\n respond_to do |format|\n if @lineitem.update_attributes(params[:lineitem])\n format.html { redirect_to @lineitem, notice: 'Lineitem was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lineitem.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, opts = {})\n request(:patch, path, opts).body\n end",
"def patch(path, data, params = {}, request_options = {})\n request(:patch, path, data, params)\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 update\n @runner = Runner.find(params[:id])\n\n respond_to do |format|\n if @runner.update_attributes(params[:runner])\n format.html { redirect_to @runner, notice: 'Runner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @runner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @lineup = Lineup.find(params[:id])\n\n respond_to do |format|\n if @lineup.update_attributes(params[:lineup])\n format.html { redirect_to @lineup, notice: 'Lineup was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lineup.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @line = Line.find(params[:id])\n @budget = @line.budget\n\n respond_to do |format|\n if @line.update_attributes(params[:line])\n format.html { redirect_to budget_path(@budget), notice: 'Line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @batting_line = BattingLine.find(params[:id])\n\n respond_to do |format|\n if @batting_line.update_attributes(params[:batting_line])\n format.html { redirect_to @batting_line, notice: 'Batting line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @batting_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @line_item.update(line_item_params)\n format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }\n format.json { render :show, status: :ok, location: @line_item }\n else\n format.html { render :edit }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\nend",
"def update_by_body\n @person = Person.find(person_update_params[:id])\n\n if @person.update_attributes(person_update_params)\n render json: { status: 'PUT Success' }, status: :ok\n else\n render json: { status: 'Error', message:'Error updating person', person: @person.errors }, status: :unprocessable_entity\n end\n end",
"def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def update\n #@user = User.find(params[:id])\n \n if @trainer.update(trainer_params)\n render json: @trainer\n else\n render json: @trainer.errors, status: :unprocessable_entity\n end\nend",
"def update\n @retailer = Retailer.find(params[:id])\n\n respond_to do |format|\n if @retailer.update_attributes(params[:retailer])\n format.html { redirect_to @retailer, notice: \"Retailer was successfully updated.\"}\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @retailer.errors, status: \"unprocessable_entry\" }\n end\n end\n end",
"def patch\n end",
"def update\n respond_to do |format|\n if @linhkien.update(linhkien_params)\n format.html { redirect_to @linhkien, notice: 'Linhkien was successfully updated.' }\n format.json { render :show, status: :ok, location: @linhkien }\n else\n format.html { render :edit }\n format.json { render json: @linhkien.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @headline.update(headline_params)\n format.html { redirect_to @headline, notice: 'Headline was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @headline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @airlin = Airlin.find(params[:id])\n\n respond_to do |format|\n if @airlin.update_attributes(params[:airlin])\n format.html { redirect_to @airlin, notice: 'Airlin was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @airlin.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @staffer = Staffer.find(params[:id])\n\n respond_to do |format|\n if @staffer.update_attributes(params[:staffer])\n format.html { redirect_to @staffer, notice: 'Staffer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @staffer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n # @retailer = Retailer.find(params[:id])\n respond_to do |format|\n if @retailer.update_attributes(params[:retailer])\n format.html { redirect_to @retailer, notice: 'Retailer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @retailer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n @participants = Participant.all\n @users = User.all\n if @lineitem.update(lineitem_params)\n format.html { redirect_to @lineitem, notice: 'Lineitem was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @lineitem.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @timeline.update(timeline_params)\n format.html { redirect_to @timeline, notice: 'Timeline was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @timeline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @prayer = Prayer.find(params[:id])\n\n respond_to do |format|\n if @prayer.update_attributes(params[:prayer])\n format.html { redirect_to @prayer, notice: 'Prayer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @prayer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @prayer = Prayer.find(params[:id])\n\n respond_to do |format|\n if @prayer.update_attributes(params[:prayer])\n format.html { redirect_to @prayer, notice: 'Prayer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @prayer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @prayer = Prayer.find(params[:id])\n\n respond_to do |format|\n if @prayer.update_attributes(params[:prayer])\n format.html { redirect_to @prayer, notice: 'Prayer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @prayer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(url, data)\n RestClient.put url, data, :content_type => :json\nend",
"def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end",
"def update\n @student = Student.find(params[:student_id])\n @lunchdetention = @student.lunchdetentions.find(params[:id])\n\n respond_to do |format|\n if @lunchdetention.update_attributes(params[:lunchdetention])\n format.html { redirect_to :back, notice: 'lunchdetention was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @lunchdetention.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(path)\n output { patch(path, params) }\n end",
"def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end",
"def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end",
"def update\n @retailer = Retailer.find(params[:id])\n\n respond_to do |format|\n if @retailer.update_attributes(params[:retailer])\n format.html { redirect_to @retailer, notice: 'Retailer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @retailer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @line_item.update(line_item_params)\n format.html { redirect_to @line_item, notice: \"Line item was successfully updated.\" }\n format.json { render :show, status: :ok, location: @line_item }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\nend",
"def update(resource,identifier,json)\n raise 'Not Yet Implemented'\n end",
"def update!(**args)\n @client = args[:client] if args.key?(:client)\n @list_update_requests = args[:list_update_requests] if args.key?(:list_update_requests)\n end",
"def update\n @litter = Litter.find(params[:id])\n @sires = Sire.find(:all,:order=>\"name\")\n @dames = Dame.find(:all,:order=>\"name\")\n\n respond_to do |format|\n if @litter.update_attributes(params[:litter])\n format.html { redirect_to(litters_path, :notice => 'Litter was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @litter.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @timeline = Timeline.find(params[:id])\n\n respond_to do |format|\n if @timeline.update_attributes(params[:timeline])\n format.html { redirect_to @timeline, notice: 'Timeline was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @timeline.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @timeline = Timeline.find(params[:id])\n\n respond_to do |format|\n if @timeline.update_attributes(params[:timeline])\n format.html { redirect_to @timeline, notice: 'Timeline was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @timeline.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 partial_update(klass, id, patchset, options = {}, format = nil)\n headers = {}\n headers[:accept] = \"#{format}\" if format\n format ||= @default_format\n options = { resource: klass, id: id, format: format}.merge options\n if [FHIR::Formats::ResourceFormat::RESOURCE_XML, FHIR::Formats::ResourceFormat::RESOURCE_XML_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_XML\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_XML}\"\n elsif [FHIR::Formats::ResourceFormat::RESOURCE_JSON, FHIR::Formats::ResourceFormat::RESOURCE_JSON_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_JSON\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_JSON}\"\n end\n headers[:prefer] = @return_preference if @use_return_preference\n reply = patch resource_url(options), patchset, fhir_headers(headers)\n reply.resource = parse_reply(klass, format, reply)\n reply.resource_class = klass\n reply\n end",
"def update\n @sample_line = SampleLine.find(params[:id])\n\n respond_to do |format|\n if @sample_line.update_attributes(params[:sample_line])\n format.html { redirect_to @sample_line, notice: 'Sample line was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sample_line.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @request.assign_json_attributes(params) if @request.resume?\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { render :show, status: :ok, location: @request }\n else\n format.html { render :edit }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mineral = Mineral.find(params[:id])\n \n respond_to do |format|\n if @mineral.update_attributes(params[:mineral])\n format.html { redirect_to @mineral, notice: 'Mineral was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mineral.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @flightline = Flightline.find(params[:id])\n\n respond_to do |format|\n if @flightline.update_attributes(params[:flightline])\n format.html { redirect_to(@flightline, :notice => 'Flightline was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @flightline.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
[
"0.63021463",
"0.6240131",
"0.62213457",
"0.6167319",
"0.6144966",
"0.61180913",
"0.60936266",
"0.60936266",
"0.60729194",
"0.6064583",
"0.6004544",
"0.5993123",
"0.5982784",
"0.59353393",
"0.59270674",
"0.5896436",
"0.58894765",
"0.5865916",
"0.5860658",
"0.5841712",
"0.5834162",
"0.5829178",
"0.5829178",
"0.58208954",
"0.58064467",
"0.58064467",
"0.58047456",
"0.58011174",
"0.57907695",
"0.57824534",
"0.57812667",
"0.5769375",
"0.5757032",
"0.5752971",
"0.57472235",
"0.5740824",
"0.5735349",
"0.57332945",
"0.5732866",
"0.57317483",
"0.5731584",
"0.57309484",
"0.57262486",
"0.5725921",
"0.5719157",
"0.5703905",
"0.5703905",
"0.5703905",
"0.5703905",
"0.5703905",
"0.5702158",
"0.5702158",
"0.5702158",
"0.5696266",
"0.56923985",
"0.5682057",
"0.56784767",
"0.5672444",
"0.5667686",
"0.5662788",
"0.56612736",
"0.5657623",
"0.5651348",
"0.5639946",
"0.56386185",
"0.5637083",
"0.5637082",
"0.5635138",
"0.56292385",
"0.5624124",
"0.5620574",
"0.5620571",
"0.5619457",
"0.56114113",
"0.5609336",
"0.56029946",
"0.56021273",
"0.55963",
"0.55954534",
"0.55954534",
"0.55954534",
"0.55948395",
"0.5582623",
"0.5572706",
"0.5570628",
"0.5570125",
"0.5570125",
"0.55658543",
"0.5565156",
"0.5562811",
"0.5558875",
"0.5554985",
"0.55536544",
"0.55536544",
"0.55454457",
"0.5540739",
"0.5540553",
"0.552923",
"0.55277926",
"0.552594"
] |
0.6334987
|
0
|
DELETE /liners/1 DELETE /liners/1.json
|
def destroy
@liner.destroy
respond_to do |format|
format.html { redirect_to liners_url, notice: 'Liner was successfully destroyed.' }
format.json { head :no_content }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def destroy\n @line = Line.find(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to new_line_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item1 = LineItem1.find(params[:id])\n @line_item1.destroy\n\n respond_to do |format|\n format.html { redirect_to line_item1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line = Line.find_by_no(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to lines_url }\n format.json { head :no_content }\n end\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 @line = Line.find(params[:id])\n @line.destroy\n\n respond_to do |format|\n format.html { redirect_to budget_path(@line.budget) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_liver.destroy\n respond_to do |format|\n format.html { redirect_to line_livers_url, notice: 'Line liver was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line.destroy\n respond_to do |format|\n format.html { redirect_to lines_url, notice: \"Line was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lineitem.destroy\n respond_to do |format|\n format.html { redirect_to lineitems_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lineitem = Lineitem.find(params[:id])\n @lineitem.destroy\n\n respond_to do |format|\n format.html { redirect_to lineitems_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @item_line = ItemLine.find(params[:id])\n @item_line.destroy\n\n respond_to do |format|\n format.html { redirect_to item_lines_url }\n format.json { head :no_content }\n end\n end",
"def delete!\n Recliner.delete(uri)\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invent_journal_line = InventJournalLine.find(params[:id])\n @invent_journal_line.destroy\n\n respond_to do |format|\n format.html { redirect_to invent_journal_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @lineup = Lineup.find(params[:id])\n @lineup.destroy\n\n respond_to do |format|\n format.html { redirect_to lineups_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mlines = @book.lines.multiple(params[:id])\n @mlines.each {|l| l.destroy}\n respond_to do |format|\n format.html { redirect_to book_multiple_lines_url(@book) }\n format.json { head :ok }\n end\n end",
"def destroy\n @line_detail.destroy\n respond_to do |format|\n format.html { redirect_to line_details_url }\n format.json { head :no_content }\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 @sample_line = SampleLine.find(params[:id])\n @sample_line.destroy\n\n respond_to do |format|\n format.html { redirect_to sample_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @batting_line = BattingLine.find(params[:id])\n @batting_line.destroy\n\n respond_to do |format|\n format.html { redirect_to batting_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_items.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @storyline = Storyline.find(params[:id])\n @storyline.destroy\n\n respond_to do |format|\n format.html { redirect_to storylines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\t\t@line_item.destroy\n\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to line_items_url, notice: \"Req ID: #{@line_item.id} removed.\" }\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend",
"def delete_from_entzumena\n headline = Headline.where({:source_item_type => params[:source_item_type], :source_item_id => params[:source_item_id]}).first\n if headline.destroy\n render :json => true, :status => 200\n else\n render :json => false, :status => :error\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: \"Line item was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @applied_line.destroy\n respond_to do |format|\n format.html { redirect_to applied_lines_url, notice: 'Applied line 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 delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @sub1_line_item.destroy\n respond_to do |format|\n format.html { redirect_to sub1_line_items_url, notice: 'Sub1 line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n Line.transaction do\n @line.destroy!\n end\n respond_to do |format|\n format.html { redirect_to node_lines_url(@node), notice: 'Line was successfully destroyed.' }\n format.json { head :no_content }\n format.js\n end\n end",
"def destroy\n @linehaul.destroy\n respond_to do |format|\n format.html { redirect_to linehauls_url, notice: 'Linehaul was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @journal_line = JournalLine.find(params[:id])\n @journal_line.destroy\n\n respond_to do |format|\n format.html { redirect_to(journal_lines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @trainer = Trainer.find(params[:id])\n @trainer.destroy\n\n respond_to do |format|\n format.html { redirect_to trainers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @trainer = Trainer.find(params[:id])\n @trainer.destroy\n\n respond_to do |format|\n format.html { redirect_to trainers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cruise_line.destroy\n respond_to do |format|\n format.html { redirect_to cruise_lines_url, notice: 'Cruise line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @budget_line.destroy\n respond_to do |format|\n format.html { redirect_to budget_lines_url, notice: 'Budget line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @timeline.destroy\n respond_to do |format|\n format.html { redirect_to timelines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n #@line = Line.find(params[:id])\n #@line.destroy\n\n #respond_to do |format|\n #format.html { redirect_to(lines_url) }\n #format.xml { head :ok }\n #end\n @line.destroy\n redirect_to lines_path, :flash => { :success => \"Line deleted!\" }\n\n end",
"def destroy\n @lifeline.destroy\n respond_to do |format|\n format.html { redirect_to lifelines_url, notice: 'Lifeline was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n destroy_line_item_response\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\nend",
"def destroy\n @trainer = Trainer.find(params[:id])\n @trainer.destroy\n\n head :no_content\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to line_items_url, notice: \"Line item was successfully destroyed.\" }\n format.json { head :no_content }\n end\nend",
"def destroy\n @lineaedesal = Lineaedesal.find(params[:id])\n @lineaedesal.destroy\n\n respond_to do |format|\n format.html { redirect_to(lineaedesals_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @timeline = Timeline.find(params[:id])\n @timeline.destroy\n\n respond_to do |format|\n format.html { redirect_to timelines_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Alien.delete(params[\"id\"])\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 record = InvoiceLineItem.find(params[:id])\n record.destroy\n\n respond_to do |format| \n format.json { head :no_content }\n end\n end",
"def destroy\n @line_up.destroy\n respond_to do |format|\n format.html { redirect_to line_ups_url, notice: 'Line up was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.html { redirect_to @line_item.cart, notice: t('line_items.destroy.lineDelete') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @linhkien.destroy\n respond_to do |format|\n format.html { redirect_to linhkiens_url, notice: 'Linhkien was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_station = LineStation.find(params[:id])\n @line_station.destroy\n\n respond_to do |format|\n format.html { redirect_to line_stations_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item.destroy\n respond_to do |format|\n format.js {}\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = line_items.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n end\n end",
"def destroy\n @linea = Linea.find(params[:id])\n @linea.destroy\n\n respond_to do |format|\n format.html { redirect_to(lineas_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @pump_line = PumpLine.find(params[:id])\n @pump_line.destroy\n\n respond_to do |format|\n format.html { redirect_to(pump_lines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @order_line = OrderLine.find(params[:id])\n @order_line.destroy\n\n respond_to do |format|\n format.html { redirect_to orders_url }\n format.json { head :no_content }\n end\n end",
"def delete\n DB.exec(\"DELETE FROM line WHERE id = #{self.id};\")\n end",
"def destroy\n @esseline.destroy\n respond_to do |format|\n format.html { redirect_to esselines_url, notice: 'Esseline was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line.destroy\n respond_to do |format|\n format.html { redirect_to attachment_line_list_path(@line.attachment), notice: 'Line was successfully destroyed.' }\n end\n end",
"def destroy\n @headline.destroy\n respond_to do |format|\n format.html { redirect_to headlines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @headline.destroy\n respond_to do |format|\n format.html { redirect_to headlines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @route_line = RouteLine.find(params[:id])\n @route_line.destroy\n\n respond_to do |format|\n format.html { redirect_to(route_lines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @flightline = Flightline.find(params[:id])\n @flightline.destroy\n\n respond_to do |format|\n format.html { redirect_to(flightlines_url) }\n format.xml { head :ok }\n end\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def destroy\n @time_line.destroy\n respond_to do |format|\n format.html { redirect_to time_lines_url, notice: 'Time line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @trade_line.destroy\n respond_to do |format|\n format.html { redirect_to trade_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.js\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @lineitem = Lineitem.find(params[:id])\r\n @lineitem.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(lineitems_url) }\r\n format.xml { head :ok }\r\n end\r\n end",
"def destroy\n @line_pet.destroy\n respond_to do |format|\n format.html { redirect_to line_pets_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @trail = Trail.find(params[:id])\n @trail.destroy\n\n respond_to do |format|\n format.html { redirect_to trails_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @clothing_line.destroy\n respond_to do |format|\n format.html { redirect_to clothing_lines_url, notice: 'Clothing line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @trail = Trail.find(params[:id])\n @trail.destroy\n\n respond_to do |format|\n format.html { redirect_to trails_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @weekline = Weekline.find(params[:id])\n @weekline.destroy\n\n respond_to do |format|\n format.html { redirect_to weeklines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @credit_line = CreditLine.find(params[:id])\n @credit_line.destroy\n\n respond_to do |format|\n format.html { redirect_to credit_lines_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @textline.destroy\n respond_to do |format|\n format.html { redirect_to textlines_url, notice: 'Textline was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_destination.destroy\n respond_to do |format|\n format.html { redirect_to line_destinations_url, notice: 'Line destination was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rayon = Rayon.find(params[:id])\n @rayon.destroy\n\n respond_to do |format|\n format.html { redirect_to rayons_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ledger_entry = LedgerEntry.find(params[:id])\n @ledger_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to ledger_entries_url }\n format.json { head :ok }\n end\n end",
"def delete_demo(id)\n delete_record \"/demos/#{id}\"\n end",
"def destroy\n @itinerary = Itinerary.find(params[:id])\n @itinerary.destroy\n\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @timeline = Timeline.find(params[:id])\n @timeline.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_timelines_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @donation_line = DonationLine.find(params[:id])\n @donation_line.destroy\n\n respond_to do |format|\n format.html { redirect_to donation_lines_url }\n format.json { head :ok }\n end\n end",
"def delete(path, params)\n headers = {:Authorization => \"token #{token}\", :content_type => :json, :accept => :json}\n res = RestClient.delete(\"#{github_api_uri}/#{path}\", params.to_json, headers)\n Yajl.load(res)\n end",
"def destroy\n @popularty_line_item = PopulartyLineItem.find(params[:id])\n @popularty_line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to popularty_line_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @search_line.destroy\n respond_to do |format|\n format.html { redirect_to search_lines_url, notice: 'Search line was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shipping_line = ShippingLine.find(params[:id])\n @shipping_line.destroy\n\n respond_to do |format|\n format.html { redirect_to shipping_lines_url }\n format.json { head :no_content }\n end\n end"
] |
[
"0.6721495",
"0.6701221",
"0.66580856",
"0.6639705",
"0.65312654",
"0.6512321",
"0.64748347",
"0.6471383",
"0.64278835",
"0.64278835",
"0.6427347",
"0.64245266",
"0.64131874",
"0.64053595",
"0.6404969",
"0.6404969",
"0.6404969",
"0.6404969",
"0.63895476",
"0.63891643",
"0.6352684",
"0.63523597",
"0.6346461",
"0.6316812",
"0.6316156",
"0.63083",
"0.63000077",
"0.6299239",
"0.62706757",
"0.6261131",
"0.6247434",
"0.6247434",
"0.6247434",
"0.6247434",
"0.6247434",
"0.6247434",
"0.6239296",
"0.6232727",
"0.6228558",
"0.6228339",
"0.6225212",
"0.6213523",
"0.62108564",
"0.61933243",
"0.61926585",
"0.61926585",
"0.6191916",
"0.61809146",
"0.61744255",
"0.6160877",
"0.6151729",
"0.6149375",
"0.6148055",
"0.61460876",
"0.6141048",
"0.61356837",
"0.611927",
"0.6114626",
"0.6111843",
"0.6085378",
"0.60838664",
"0.6078231",
"0.6076492",
"0.60588664",
"0.6047703",
"0.6046938",
"0.60457516",
"0.60406554",
"0.60294926",
"0.6028856",
"0.60283756",
"0.6021655",
"0.6020135",
"0.6016993",
"0.6016993",
"0.6011608",
"0.60076034",
"0.6006536",
"0.59974146",
"0.5996995",
"0.5991672",
"0.5971001",
"0.5970161",
"0.59675044",
"0.59611917",
"0.5959414",
"0.59518564",
"0.5947607",
"0.5947386",
"0.5945839",
"0.592877",
"0.59269994",
"0.5919576",
"0.5917857",
"0.5894707",
"0.589459",
"0.58915836",
"0.5888769",
"0.58887184",
"0.5888024"
] |
0.71730655
|
0
|
Use callbacks to share common setup or constraints between actions.
|
def set_liner
@liner = Liner.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
|
Never trust parameters from the scary internet, only allow the white list through.
|
def liner_params
puts(params)
params.require(:liner).permit(:new_liner_reference, :previous_liner_reference, :liner_reference, :location, :row, :collumn, :structure, :plant, :width, :height, :thickness, :original_thickness, :thickness_loss_per_day, :current_thickness)
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 valid_params_request?; 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 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 safe_params\n params.require(:user).permit(:name)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\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 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 url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"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 valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def filtering_params\n params.permit(:email)\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\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 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 url_whitelist; 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 admin_social_network_params\n params.require(:social_network).permit!\n end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\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 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 maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\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 url_params\n params[:url].permit(:full)\n end",
"def backend_user_params\n params.permit!\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"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 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 droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\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.6980957",
"0.6783065",
"0.6747844",
"0.6741468",
"0.67356336",
"0.6592548",
"0.65036845",
"0.64978707",
"0.64825076",
"0.64795035",
"0.64560914",
"0.64397955",
"0.6379666",
"0.6376688",
"0.6366702",
"0.6319728",
"0.6300833",
"0.6300629",
"0.6294277",
"0.6293905",
"0.6291174",
"0.62905735",
"0.6283171",
"0.6242344",
"0.62403613",
"0.6218049",
"0.62143815",
"0.62104696",
"0.61949855",
"0.6178671",
"0.6176147",
"0.6173327",
"0.6163395",
"0.6153005",
"0.6151833",
"0.6147288",
"0.61224324",
"0.6118827",
"0.61075264",
"0.61054534",
"0.6092497",
"0.6080082",
"0.60710967",
"0.60627776",
"0.60219413",
"0.60175914",
"0.60153484",
"0.60107356",
"0.60081726",
"0.60081726",
"0.60013986",
"0.6000165",
"0.59978646",
"0.59936947",
"0.59925723",
"0.5992084",
"0.59796256",
"0.5967569",
"0.5960056",
"0.59589803",
"0.5958441",
"0.5958401",
"0.5952607",
"0.5952406",
"0.5944409",
"0.59391016",
"0.593842",
"0.593842",
"0.5933845",
"0.59312123",
"0.5926475",
"0.59248453",
"0.59179676",
"0.59109294",
"0.59101623",
"0.5908172",
"0.59058356",
"0.5899052",
"0.5897749",
"0.5896101",
"0.58942914",
"0.58939576",
"0.5892063",
"0.5887407",
"0.588292",
"0.58797663",
"0.587367",
"0.58681566",
"0.5868038",
"0.5866578",
"0.58665025",
"0.58655846",
"0.58640826",
"0.5863465",
"0.5862226",
"0.586065",
"0.58581287",
"0.5854443",
"0.5854172",
"0.58507544",
"0.5849934"
] |
0.0
|
-1
|
Convert an image of text into a binarized (light and dark) view Perform an adaptive binarization algorithm on the input image to prepare it for further OCR operations.
|
def preprocessing_binarize(image_file, opts = {})
data, _status_code, _headers = preprocessing_binarize_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def preprocessing_binarize_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_advanced_with_http_info(image_file, opts)\n data\n end",
"def binarize id\n m_begin \"binarize\"\n put_image(id, get_image(id).bilevel_channel(QuantumRange/2))\n# put_image(id, @var_table[id].quantize(2, GRAYColorspace, NoDitherMethod) )\n m_end \"binarize\"\n end",
"def recognize(image)\n # quantize to two-color\n image = quantize_image(image)\n\n # the binary string we expect to see from the output nodes\n assign_inputs image\n\n calculate_hidden_outputs\n calculate_final_outputs\n\n #@output_values.each.with_index { |v, i| puts \"index: #{i} => #{v}\" }\n\n # process results\n #\n binary_string = quantized_result.inject(\"\") { |accum, bit| \"#{accum}#{bit.to_s}\" }\n binary_string.to_i(2)\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def blur_image\r\n\r\n#define new image array with identical length to old array\r\n image1 = Array.new(@image.length){\r\n Array.new(@image[0].length){}}\r\n\r\n#start indexing through each cell and define values for rows and columns\r\n @image.each_with_index { |val, rowindex|\r\n val.each_with_index {|val1, colindex| \r\n\r\n#hardcoding 'nil' index values into zeroes \r\n if image1 [rowindex][colindex] != 1 \r\n then image1 [rowindex][colindex] = 0 \r\n end\r\n\r\n#if currently indexed cell has a value of 1 in original array, cell value in new array will be 1\r\n if val1 > 0 \r\n then image1 [rowindex][colindex] = 1\r\n\r\n#define value of cell directly below currently indexed cell as 1, unless it is the last cell in a column.\r\n if colindex != val.length-1\r\n then image1 [rowindex][colindex +1] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define value of cell directly above it as 1.\r\n if colindex != 0 then\r\n image1 [rowindex][colindex -1] = 1\r\n end\r\n\r\n#define value of the cell to the RIGHT of the currently indexed cell as 1, unless it is the last cell in a row.\r\n if rowindex != @image.length-1 then\r\n image1 [rowindex +1][colindex] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define the value of the cell to the LEFT of it as 1.\r\n if rowindex != 0 then\r\n image1 [rowindex -1][colindex] = 1\r\n end\r\n\r\n end\r\n\r\n }} \r\n\r\n#show blurred image array\r\n image1.each do |cell|\r\n puts cell.join\r\n end\r\n end",
"def break_text_with_image(width, textarray, draw)\n tokens = textarray.flat_map{ |x| x.respond_to?(:split) ? x.split(/ /) : x }\n tokens = tokens.flat_map{ |x| x.respond_to?(:split) ? x.split(/(?<=\\n)/) : x }\n\n result = []\n line = []\n linelength = 0\n\n tokens.each_with_index do |item, i|\n itemlength = item.class == Image ?\n item.columns : draw.get_type_metrics(item + ' ').width\n\n if (line.empty?)\n line << item\n else\n if (width != 0 && itemlength + linelength > width)\n result << line\n line = [item]\n linelength = 0\n else\n t = line.pop\n\n if (t.class != Image)\n t += ' '\n elsif (item.class != Image)\n item = ' ' + item\n end\n\n if (t.class == Image or item.class == Image)\n line << t << item\n else\n line << t + item\n end\n end\n end\n\n if (item.class != Image and item.include?(\"\\n\"))\n line[0].sub!(\"\\n\", '')\n result << line\n line = []\n linelength = 0\n next\n end\n\n linelength += itemlength\n end\n\n unless (line.empty?)\n result << line\n end\n\n return result\n end",
"def apply_label(text, image)\n image.composite(build_label(text),\n Magick::CenterGravity,\n Magick::HardLightCompositeOp)\n end",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def enhance_image(image)\n colors = image.get_pixels.flatten\n colors.map! { |color| color**2 / 255 }\n blob = colors.pack('C*') # Recreate the original image, credit to stackoverflow.com/questions/53764046\n image = MiniMagick::Image.import_pixels(blob, image.width, image.height, 8, 'rgb')\n image.statistic('mean', '6x6')\n image.threshold(threshold_percent)\n image.statistic('median', '9x9') # Replace with object discard below set size\n end",
"def preprocessing_binarize_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def output_image\n @image_blur_array.each do |row|\n puts row.join\n end\n end",
"def blur(distance)\n row_max = @image[0].length() - 1\n column_max = @image.length() - 1\n\n ones = self.get_ones\n\n while distance > 0\n ones.each do |one|\n vert = one[1]\n horiz = one[0]\n \n # down \n @image[vert + distance][horiz] = 1 unless vert + distance > column_max\n\n # up\n @image[vert - distance][horiz] = 1 unless vert - distance < 0\n\n # right\n @image[vert][horiz + distance] = 1 unless horiz + distance > row_max\n\n # left\n @image[vert][horiz - distance] = 1 unless horiz - distance < 0\n\n sub_distance = distance\n diag = 1\n while sub_distance > 1\n\n # bottom sides\n unless vert + sub_distance - 1 > column_max || horiz - diag < 0 || horiz + diag > row_max\n @image[vert + sub_distance - 1][horiz - diag] = 1\n @image[vert + sub_distance - 1][horiz + diag] = 1 \n end\n\n # top\n unless vert - sub_distance + 1 < 0 || horiz - diag < 0 || horiz + diag > row_max\n @image[vert - sub_distance + 1][horiz - diag] = 1\n @image[vert - sub_distance + 1][horiz + diag] = 1\n end\n\n # right sides\n unless vert - diag < 0 || vert + diag > column_max || horiz + sub_distance - 1 > column_max\n @image[vert - 1][horiz + sub_distance - diag] = 1\n @image[vert + 1][horiz + sub_distance - diag] = 1\n end\n\n # left sides\n unless vert - diag < 0 || vert + diag > column_max || horiz + sub_distance - 1 < 0\n @image[vert - 1][horiz - sub_distance + diag] = 1\n @image[vert + 1][horiz - sub_distance + diag] = 1\n end\n\n sub_distance -= 1\n diag += 1\n\n end\n end\n\n distance -= 1\n end\n\n end",
"def preprocessing_binarize_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def analyze_ballot_image filename, dpi, result, upstream\n reset_analyzer filename, dpi, result, upstream\n open_ballot_image :ballot, filename, dpi\n locate_ballot\n sanity_check_ballot_coords\n analyze_vote_ovals\n analyze_barcode\n sanity_check\n compile_results result\n end",
"def blur(image, r, c, distance)\n\n # Set the column length and row length\n image_height = image.length\n image_width = image[0].length\n\n # start looking at the rows at index[0]\n start_row = r - distance # number \n if start_row < 0\n start_row = 0\n end\n\n # start column all the way to the left\n start_col = c - distance\n if start_col < 0\n start_col\n end\n\n end_row = r + distance\n if end_row > image_height - 1\n end_row = image_height - 1\n end\n\n end_col = c + distance\n if end_col > image_width - 1\n end_col = image_width - 1\n end\n\n for i in (start_row..end_row)\n for j in (start_col..end_col)\n if within_manhatten_distance?(i, j, r, c, distance)\n image[i][j] = 2\n end\n end\n end\nend",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def add_blur_to_image\n r = 0\n c = 0\n rc = 0\n n = 1\n z = []\n u = @y.size.to_i\n while n <= u\n @ary.each_index do |r|\n @ary[r].each_index do |c|\n if ((c.to_i - y[rc][1].to_i).abs + (r.to_i - y[rc][0].to_i).abs).between?(1, @distance.to_i);\n z << [r.to_i, c.to_i]\n end\n end\n end\n r = 0\n c = 0\n rc += 1\n n += 1\n end\n zz=[]\n r1 = 0\n c1 = 0\n z.each do |r|\n r1 = r[0].to_i\n c1 = r[1].to_i\n @ary[r1][c1] = 1\n end\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def text_color_for_image(image)\n dominant = dominant_color(image)\n brightness = brightness(dominant)\n # Por ahora sólo devolvemos blanco o negro.\n # Si lo vemos muy feo, pensar una solución\n # más inteligente.\n if brightness < 255 / 2\n \"#fff\"\n else\n \"#000\"\n end\n end",
"def preprocess_image(path)\n MiniMagick::Tool::Convert.new.yield_self do |convert|\n convert << path\n\n if config.localization_preprocessing != :none\n # general preprocessing\n convert.colorspace \"Gray\"\n convert.normalize\n\n if config.localization_preprocessing == :full\n # try to reduce shadows (based on https://legacy.imagemagick.org/Usage/compose/#divide)\n convert.stack do |stack|\n convert.clone 0\n convert.sample \"25%\"\n convert.blur \"30x10\"\n convert.resize \"400%\"\n end\n convert.compose \"DivideSrc\"\n convert.composite\n\n # remove short vertical features\n convert.morphology \"Close\", \"3x6: 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1\"\n # remove small features and flaws\n convert.morphology \"Close:3\", \"Square:1\"\n end\n\n convert.threshold \"50%\"\n end\n\n convert.depth 8\n convert << \"gray:-\"\n\n MiniMagick::Shell.new.run(convert.command)\n end.first\n end",
"def prepareBackgroundImage(text)\n # Margins within the text Rect\n x_margin = 5\n y_margin = 1\n\n dynamic_font = self.titleLabel.font\n # We really don't care about the constraintSize just yet\n constraintSize = CGSizeMake(200, 37)\n current_size = text.sizeWithFont(dynamic_font, constrainedToSize:constraintSize, lineBreakMode: NSLineBreakByWordWrapping)\n\n # These are the images that should be concatenated.\n # They are the same height.\n pointer = UIImage.imageNamed(\"marker_pointer_unviewed.png\")\n balloon = UIImage.imageNamed(\"map_marker_unviewed.png\")\n\n # We are going to put the text in the balloon, which is at this rect. The\n # balloon should have x_margin space on each horizontal size, and y_margin\n # on each vertical side.\n\n textRect = Rect(pointer.size.width,\n pointer.size.height - current_size.height + y_margin * 2,\n current_size.width + x_margin * 2,\n pointer.size.height - current_size.height + y_margin * 2)\n\n # The size of the entire image should be the pointer + the width of the text rect\n # and the height of the images, which are the same height\n img_size = Size(pointer.size.width + textRect.size.width, pointer.size.height)\n pointed = UIImage.canvas(img_size) do |context|\n pointer.drawAtPoint([0,0])\n # We create a stretchable image between the x_margin pixels on each horizontal side\n insets = EdgeInsets(0, 15, 0, 45)\n img = balloon.resizableImageWithCapInsets(insets)\n # We draw that this image, which is the same height as the pointer to cover the textRect\n # This operation is basically filling the image next to the pointer to the desired size\n img.drawInRect(Rect(pointer.size.width, 0, textRect.size.width, pointer.size.height))\n end\n self.setBackgroundImage(pointed, forState: UIControlStateNormal)\n #self.setBackgroundImage(pointed.darken, forState: UIControlStateHighlighted)\n # The text gets drawn centered on the entire size of the button.\n # So, we have to offset the centers with insets so that the\n # center of the text is in the center of the text Rect.\n # The coordinate system is 0,0 at bottom left, so we need to inset right,\n # and up, which means we have a positive left, and a negative top inset.\n # Furthermore the text must be inset by the margins inside the\n # calculated Rect.\n contentRect = Rect([0,0],pointed.size)\n titleCenter = Point [CGRectGetMidX(contentRect), CGRectGetMidY(contentRect)]\n textRectCenter = Point [CGRectGetMidX(textRect), CGRectGetMidY(textRect)]\n top = textRectCenter.y - titleCenter.y + y_margin\n left = textRectCenter.x - titleCenter.x + x_margin\n puts \"titleCenter #{titleCenter.inspect} textCenter #{textRectCenter.inspect}\"\n puts \"top #{-top} left #{left}\"\n w = EdgeInsets(-top, left, 0, 0)\n self.titleEdgeInsets = w\n self.size = pointed.size\n end",
"def blur_image(distance)\r\n @length = @image.length\r\n @width = 0\r\n @image.each do |x|\r\n x.each do |cell|\r\n @width += 1\r\n end\r\n end\r\n i = 0\r\n j = 0\r\n n = distance\r\n while n > 0\r\n i = 0\r\n j = 0 \r\n while i < @length\r\n j = 0\r\n while j < @width\r\n if @image[i][j] == 1\r\n\r\n # This looks down from the rows\r\n if i < @length - 1\r\n if @image[i+1][j] == 0\r\n @image[i+1][j] = 2\r\n end\r\n end\r\n\r\n # This looks up from the rows\r\n if i > 0 && @image[i-1][j] == 0\r\n @image[i-1][j] = 2 \r\n end\r\n\r\n # This looks to the right until it gets to the end.\r\n if @image[i][j+1] == 0\r\n @image[i][j+1] = 2\r\n end\r\n\r\n # This looks to te left. I tried to set this so it will never look over the side of the array.\r\n # I'm afraid of what might happen if my program does that too muc.\r\n if j > 0 && @image[i][j - 1] == 0\r\n @image[i][j - 1] = 2\r\n end\r\n end\r\n j += 1\r\n end\r\n i += 1\r\n end\r\n # This code goes back through the array and turns the temporary shade values into 1s for output.\r\n i = 0\r\n j = 0\r\n while i < @length\r\n j = 0\r\n while j < @width\r\n if @image[i][j] == 2\r\n @image[i][j] = 1\r\n end\r\n j += 1\r\n end\r\n i += 1\r\n end\r\n n -= 1\r\n puts n\r\n end\r\n \r\n puts \"Inside blur_image\\n\"\r\n puts \"\\n\"\r\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def design2image\n\n bkgImg = Image.read(\"#{Rails.root}/public/#{params[:bkg]}\").first\n\n sideTop = 36\n sideLeft = 95\n sideWidth = 216\n sideHeight = 353\n\n side = params[:side]\n if side == 'SLEEVE'\n sideWidth = 162\n sideHeight = 250\n end\n #ART Processing\n arts = params[:art];\n art_tops = params[:art_top];\n art_lefts = params[:art_left];\n \n \n #Image.new(columns, rows) ~ (width, height)\n containSide = Magick::Image.new(sideWidth, sideHeight) do\n self.background_color = 'none'\n end\n\n i=0\n if arts\n clipArt = Image.read(\"#{Rails.root}/public/#{arts[0]}\").first\n clipArtTop = art_tops[i].to_i if art_tops[i]\n clipArtLeft = art_lefts[i].to_i if art_lefts[i]\n containSide = containSide.composite(clipArt, clipArtLeft, clipArtTop, OverCompositeOp)\n end\n\n #TEXT Processing\n texts = params[:text];\n text_tops = params[:text_top];\n text_lefts = params[:text_left];\n\n\n if texts\n textArtTop = text_tops[i].to_i if text_tops[i]\n textArtLeft = text_lefts[i].to_i if text_lefts[i]\n gc = Magick::Draw.new\n textArt = Magick::Image.new(300, 200) do\n self.background_color = 'none'\n end\n gc.annotate(textArt, 0, 0, 0, 0, texts[i]) do\n self.gravity = Magick::NorthWestGravity\n self.pointsize = 22\n self.font_family = \"Times\"\n self.fill = '#0000A9'\n self.stroke = \"none\"\n end\n end\n\n containSide.composite!(textArt, textArtLeft || 0, textArtTop || 0, OverCompositeOp) if textArt\n \n bkgImg.composite!(containSide, sideLeft, sideTop, OverCompositeOp)\n bkgImg.scale!(0.5)\n\n send_data bkgImg.to_blob, :disposition => 'inline', :type => 'image/png'\n\n# output = get_working_image(@session_id)\n# unless File.exist?(output)\n# FileUtils.cp(\"#{RAILS_ROOT}/public/images/#{params[:textart]}.png\", output)\n# img = Image.read(output).first\n# img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n# img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n# img.background_color = \"none\"\n# img = img.rotate(params[:r].to_f) unless params[:r].blank?\n# img.write(output)\n# end\n# img = Image.read(output).first\n# send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def binarization(color, threshold)\n mid = ((color.red / 257) + (color.green / 257) + (color.blue / 257)) / 3\n return mid > threshold ? \"#fff\" : '#000'\nend",
"def photo_text_s(image, text, alt_text = t(text))\n image_tag('image/todd_ramirez_' + image,\n alt: alt_text,\n title: alt_text) + tag(:br) +\n content_tag(:itext, t(text)) + tag(:br) + tag(:br) + tag(:br) + tag(:br)\n end",
"def blurred\r\n unos = []\r\n # nested loops for rows and columns\r\n @paint.each_with_index do |row, rownum| # iterating over elements in the main array for rows \r\n row.each_with_index do |element, colnum| # iterating over elements in each subarray for columns\r\n if element == 1\r\n unos << [rownum, colnum]\r\n end\r\n end\r\n end\r\n\r\n unos.each do |rownum, colnum| \r\n # assigning \"1\" above \"1\"s, except for first row\r\n @paint[rownum -1][colnum] = 1 unless rownum == 0\r\n # assigning \"1\" below \"1\"s, except for last row\r\n @paint[rownum +1][colnum] = 1 unless rownum >= @paint.length-1\r\n # assigning \"1\" to the left of \"1\"s, except for first column\r\n @paint[rownum][colnum -1] = 1 unless colnum == 0\r\n # assigning \"1\" to the right of \"1\"s, except for last column\r\n @paint[rownum][colnum +1] = 1 unless colnum >= @paint[rownum].length-1\r\n end\r\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def colorize(text)\n Albino.new(text, self).colorize(:O => 'stripnl=false')\n end",
"def recognize_detect_text_fine(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_fine_with_http_info(image_file, opts)\n data\n end",
"def display_alternative_text_image(image)\n # Interface method\n end",
"def photo_text(image, text, alt_text = t(text))\n image_tag('image/todd_ramirez_' + image,\n alt: alt_text,\n title: alt_text) + tag(:br) +\n content_tag(:itext, t(text)) + tag(:br)\n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def image_ocr_photo_to_text_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_to_text ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_to_text\"\n end\n # resource path\n local_var_path = '/ocr/photo/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_to_text\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def image_ocr_photo_recognize_business_card(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_business_card_with_http_info(image_file, opts)\n data\n end",
"def analyze_barcode\n Barcode_Columns.times do |barcode_col_index|\n barcode_pos = transform_point(BPoint.new(barcode_col_index, Barcode_Row-1), :bottombias)\n @upstream.ann_point(barcode_pos.x, barcode_pos.y)\n score = shrink_to_one(:ballot, barcode_pos.x - i2p(TM_Width)/2.0, barcode_pos.y-i2p(TM_Height)/2.0, i2p(TM_Width), i2p(TM_Height))\n if score < (QuantumRange * BarCodeDetectThresh).to_int then\n @raw_barcode << barcode_col_index\n end\n end\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def transform(manHatDist)\r\n\t\tpixel_on = []\r\n\t\tmanHatDist.times do\r\n\t\t@image.each.with_index do |row, row_index|\r\n\t\t\trow.each.with_index do |pixel, col_index|\r\n\t\t\t\tif pixel == 1\r\n\t\t\t\t\tpixel_on.push [row_index, col_index]\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\t\tpixel_on.each do |touple|\r\n\t\t\t#blur(*touple)\r\n\t\t\trow_index, col_index = touple\r\n\t\t\tblur(row_index, col_index)\r\n\t\tend\r\n\tend\r\n\tend",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def darken(options={})\n filter_name = 'CIColorControls'\n filter_options = {\n inputBrightness: options[:brightness] || -0.5,\n inputSaturation: options[:saturation] || -0.2,\n }\n\n cg_input_image = CIImage.alloc.initWithImage(self)\n darken_filter = CIFilter.filterWithName(filter_name)\n raise Exception.new(\"Filter not found: #{filter_name}\") unless darken_filter\n\n darken_filter.setDefaults\n darken_filter.setValue(cg_input_image, forKey:'inputImage')\n filter_options.each_pair do |key, value|\n darken_filter.setValue(value, forKey:key)\n end\n output = darken_filter.valueForKey('outputImage')\n\n context = CIContext.contextWithOptions(nil)\n cg_output_image = context.createCGImage(output, fromRect:output.extent)\n output_image = UIImage.imageWithCGImage(cg_output_image)\n\n return output_image\n end",
"def text(section_type: :default)\n img = @image \n \n # resample if an image 4\"x4\" is less than 300dpi \n if img.columns * img.rows < 144000\n img = img.resample(300)\n end\n \n params = SECTION_PARAMS[:default].merge(SECTION_PARAMS[section_type])\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n\n if @text == \"\"\n img = img.white_threshold(245)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n if @text == \"\"\n img = img.quantize(256,Magick::GRAYColorspace)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n @text\n end",
"def blur!\r\n ones = get_ones\r\n ones.each do |found_row_number, found_col_number| \r\n @picture[found_row_number -1][found_col_number] = 1 unless found_row_number == 0 #up\r\n @picture[found_row_number +1][found_col_number] = 1 unless found_row_number == @picture.length-1 #down\r\n @picture[found_row_number][found_col_number -1] = 1 unless found_col_number == 0 #left\r\n @picture[found_row_number][found_col_number +1] = 1 unless found_col_number == @picture[found_row_number].length-1 #right\r\n end\r\n end",
"def toaster_filter\n manipulate! do |img|\n img.modulate '150,80,100'\n img.gamma 1.1\n img.contrast\n img.contrast\n img.contrast\n img.contrast\n img = yield(img) if block_given?\n img\n end\n end",
"def blur\n things_to_blur = []\n # looking for 1s to blur going through each array\n @grid.each_with_index do |or_row, row_index|\n or_row.each_with_index do |cell, cell_index|\n #is this current cell a 1?\n if cell == 1\n #run function on code\n recursive_blur(Point.new(cell_index, row_index), things_to_blur)\n end\n end\n end\n things_to_blur.each do |point|\n @grid[point.y][point.x] = 1\n end\n output_image\n end",
"def computeProjection\n w,h = @type==:vertical ? [@image.width, @image.height] : [@image.height, @image.width]\n mw,mh = @type==:vertical ? [@image.width, @image.height-@image.borders.bottom] : [@image.height, @image.width-@image.borders.right]\n content_mask = Array.new(w){[false, 0]}\n\n w.times do |a|\n obj_height = 0\n gap = 0\n (h-mh).times do |b|\n x,y = @type==:vertical ? [a,b] : [b,a]\n idx = @image.index(x, y)\n #p [idx, w, h, mh, a, b, x, y, @image.width, @image.height]\n if @data[idx] <= @threshold\n obj_height += 1\n obj_height += gap if gap <= @image.min_obj_size\n gap = 0\n else\n gap += 1\n content_mask[a] = [true, b] if obj_height > @image.min_obj_size\n obj_height = 0\n end\n end\n end\n\n content_mask\n end",
"def generate(options = {})\n options.reverse_merge!(\n :fontsize => 25,\n :padding => 20,\n :color => '#000',\n :background => '#fff',\n :fontweight => 'bold',\n :rotate => true,\n :font => config['font']\n ).symbolize_keys!\n\n options[:fontweight] = case options[:fontweight]\n when 'bold' then 700\n else 400\n end\n \n text = Magick::Draw.new\n text.pointsize = options[:fontsize]\n text.font_weight = options[:fontweight]\n text.fill = options[:color]\n text.gravity = Magick::CenterGravity\n text.font = options[:font] if options[:font]\n \n #rotate text 5 degrees left or right\n text.rotation = (rand(2)==1 ? 5 : -5) if options[:rotate]\n \n metric = text.get_type_metrics(self.string)\n\n #add bg\n canvas = Magick::ImageList.new\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = options[:background]\n }\n\n #add text\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = 'transparent'\n }.annotate(text, 0, 0, 0, 0, self.string).wave(1, 50)\n\n #add noise\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n p = Magick::Pixel.from_color(options[:background])\n p.opacity = Magick::MaxRGB/2\n self.background_color = p\n }.add_noise(Magick::LaplacianNoise)\n\n self.image = canvas.flatten_images.blur_image(1)\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def text_label(text:, dpi: 100, text_colour: [0, 0, 0, 255], shadow_colour: [255, 255, 255, 150], blur: 1.5)\n text_mask, = Vips::Image.text(text, dpi: dpi)\n\n canvas_width = text_mask.width + 10\n canvas_height = text_mask.height + 10\n text_mask = text_mask.gravity('west', canvas_width, canvas_height)\n # use 0 - 1 for the masks\n text_mask /= 255\n\n shadow_mask = text_mask.gaussblur(blur)\n # credit: https://github.com/libvips/pyvips/issues/204\n text_mask = text_mask * text_colour + ((text_mask * -1) + 1) * shadow_mask * shadow_colour\n\n text_mask.unpremultiply.copy(interpretation: 'srgb')\n end",
"def blur(image)\n convolve(to_narray(image), GAUSS).to_a\n end",
"def recognize_detect_text_large_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_large ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_large\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/large'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'TextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_large\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def image_ocr_post_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_post ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_post\"\n end\n # resource path\n local_var_path = '/ocr/image/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n header_params[:'preprocessing'] = opts[:'preprocessing'] if !opts[:'preprocessing'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def binarize(inputs)\n return inputs.map{|pixel|\n pixel > 0.5 ? 1.0 : 0.0\n }\n end",
"def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end",
"def recognize_detect_text_fine_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_fine ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_fine\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/fine'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'FineTextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_fine\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def filter_black_and_white_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: FilterApi.filter_black_and_white ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling FilterApi.filter_black_and_white\"\n end\n # resource path\n local_var_path = '/image/filter/black-and-white'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: FilterApi#filter_black_and_white\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def convert\n @value = \"\"\n @areas.each do |area|\n image = RTesseract.new(@source.to_s,@options)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:width].to_i, area[:height].to_i)\n @value << image.to_s\n end\n rescue\n raise RTesseract::ConversionError\n end",
"def build_canvas(lines_of_text_blocks)\n # Grab the greatest values for each line\n line_baseline = []\n line_height = []\n line_width = []\n lines_of_text_blocks.each_index do |i|\n baselines = (lines_of_text_blocks[i].sort { |a,b| a.baseline <=> b.baseline })\n heights = (lines_of_text_blocks[i].sort { |a,b| a.height <=> b.height })\n line_baseline << baselines.last.baseline\n line_height << heights.last.height - heights.last.line_spacing\n width = 0\n lines_of_text_blocks[i].each { |l| width += l.width }\n line_width << width\n end\n \n # set up canvas height and width\n @width = line_width.sort.last\n height = 0\n line_spacing_height = 0\n line_height.each { |h| height += h ; line_spacing_height += (h * (@options[:line_spacing] || 0)) }\n line_spacing_height -= (line_height.last * (@options[:line_spacing] || 0))\n @height = height + line_spacing_height\n \n options = nil\n if @options[:matte]\n options = @options.dup\n options[:bgcolor] = 'transparent'\n else\n options = @options\n end\n \n @canvas = IQ::Image::Canvas.new(@width, @height, options)\n \n # actually go through the lines and do stuff with them to make the canvas\n # for each line align each text block with the baseline\n top = 0\n lines_of_text_blocks.each_index do |i|\n left = 0\n lines_of_text_blocks[i].each do |text_block|\n offset = (line_baseline[i] - text_block.baseline)\n @canvas.overlay!(text_block.to_canvas, :dest_x => left, :dest_y => top + offset)\n left += text_block.width\n end\n top += line_height[i] + ((@options[:line_spacing] || 0) * line_height[i])\n end\n @canvas\n end",
"def blur(distance)\r\n # instantiate variables\r\n @b_array = Array.new(array.length) { Array.new(array[0].length,0) }\r\n min_y= 0\r\n max_y = b_array.length - 1\r\n min_x = 0 \r\n max_x = b_array[0].length - 1\r\n blurred_coordinates = []\r\n #iterate through each row of the array, passing down index and value\r\n array.each_with_index do |row,row_i|\r\n #iterate through each column (value) passing index and value\r\n row.each_with_index do |col,col_i| \r\n if row[col_i] == 1 \r\n blurred_coordinates << get_manhattan_set(row_i,col_i,distance)\r\n end\r\n end\r\n end\r\n\r\n blurred_coordinates.each do |set|\r\n set.each do |point|\r\n unless point[0]< min_x || point[1] < min_y || point[0]> max_y || point[1] > max_x\r\n @b_array[point[0]][point[1]] = 1\r\n end\r\n end \r\n end\r\n end",
"def do_overlay_image(image, hash)\n #puts \"get image\"\n #puts \"#{hash.inspect}\"\n #puts \"Image: #{hash[:image_path]}\"\n #puts \"File exists? #{File.exists?(hash[:image_path])}\"\n overlay_i = Magick::ImageList.new(hash[:image_path]).first\n #puts \"Do we want to colorize?\"\n if hash.has_key? :colorize\n \n #opc = hash[:opacity]\n overlay_i = do_colorize(overlay_i, hash.merge({:opacity=>0.5})) #overlay_i.colorize(opc, opc, opc, hash[:colorize])\n end\n return image.composite(overlay_i, 0, image.rows-overlay_i.rows, Magick::OverCompositeOp)\n end",
"def recognize_detect_text_large(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_large_with_http_info(image_file, opts)\n data\n end",
"def bbcodeize(text)\n text = text.dup\n TagList.each do |tag|\n if Tags.has_key?(tag)\n apply_tag(text, tag)\n else\n self.send(tag, text)\n end\n # Replace the matching random ids for the following tags: spoiler, nsfw, mp3\n @random_id = random_string\n 2.times { text = text.sub('_RANDOM_ID_', @random_id) }\n end\n text\n end",
"def detect_bandaid(image:, area: 2000)\n objects = detect_image(image: image)\n objects.each_with_index do |object, i|\n remove(i) if object.width * object.height > area\n end\n end",
"def optimized_image(image,x,y)\n return image.variant(resize_to_fill: [x,y]).processed\n end",
"def build_label(text)\n shading = false\n\n label = Magick::Image.new(@options[:width], @options[:height])\n image = Magick::Draw.new\n image.gravity = Magick::CenterGravity\n image.pointsize = @options[:width] / 4\n image.font = 'Helvetica'\n image.font_weight = Magick::NormalWeight\n image.stroke = 'none'\n image.annotate(label, 0, 0, 0, 0, text)\n label = label.shade(shading, 310, 30)\n\n return label\n end",
"def blur(distance)\n @distance = distance\n find_pixel_eq_1\n add_blur_to_image\n \n j = @ary.size\n q = @ary.flatten.size\n wa = q / j - 1\n l = q / j\n k = @ary.flatten\n m = 0\n n = l - 1\n while n <= q\n puts k[m..n].join\n m += l\n n += l\n end \n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def blur_pixel(ones_array)\n ones_array.each do |point_array|\n # => breaks the point_array inner arrays into its two parts --\n # => wouldn't work if there was stuff in the middle\n row = point_array.first\n col = point_array.last\n # => this is where the transformation happens\n @image_array[row - 1][col] = 1\n @image_array[row][col - 1] = 1 unless col == 0\n @image_array[row + 1][col] = 1 unless row >= @num_row - 1\n @image_array[row][col + 1] = 1 unless col >= @num_col - 1 \n\n end\n end",
"def darken(options={})\n filter_options = {\n 'inputSaturation' => options[:saturation] || 0,\n 'inputBrightness' => options[:brightness] || 0,\n }\n\n darken_filter = CIFilter.color_controls(filter_options)\n output = self.apply_filter(darken_filter)\n return UIImage.imageWithCIImage(output, scale:self.scale, orientation:self.imageOrientation)\n end",
"def generate_controls(text)\n contents_text = \"\"\n loop do\n c = text.slice!(/./m)\n case c\n when nil\n break\n #--------------------------\n # DEFAULT FEATURES\n #-----------------------\n when \"\\x01\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n @last_color = $1.to_i\n contents.font.color = text_color($1.to_i)\n \n #--------------------------\n # * NMS FEATURES!!\n #-----------------------\n when \"\\x83\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n\n new_line if (@contents_x + 24 > contents.width)\n\n # Draw ICON\n ucIcon = UCIcon.new(self, Rect.new(@contents_x, @contents_y, 24, 24), $1.to_i)\n @cControlsList.push(ucIcon)\n @contents_x += 24\n when \"\\x84\"\n text.sub!(/\\[(.*?)\\]/, \"\")\n contents.font.name = $1.to_s\n when \"\\x85\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n contents.font.size = $1.to_i\n when \"\\x86\"\n contents.font.name = Font.default_name \n when \"\\x87\"\n contents.font.size = Font.default_size\n when \"\\x88\"\n contents.font.bold = contents.font.bold == true ? false : true\n when \"\\x89\"\n contents.font.italic = contents.font.italic == true ? false : true\n when \"\\x93\"\n contents.font.shadow = contents.font.shadow == true ? false : true\n when \"\\x11\"\n text.sub!(/\\[(.*?)\\]/, \"\")\n a = $1.to_s.split(',')\n bitmap = Cache.picture(a[0])\n\n new_line if (@contents_x + bitmap.width > contents.width)\n \n # Size\n if !a[1].nil? && !a[1].empty?\n width = a[1].to_i\n else\n width = bitmap.width\n end\n if !a[2].nil? && !a[2].empty?\n height = a[2].to_i\n else\n height = bitmap.height\n end\n \n # Border\n if !a[3].nil? && !a[3].empty?\n border = a[3].to_i \n else\n border = 0\n end\n if !a[4].nil? && !a[4].empty?\n border_color = text_color(a[4].to_i)\n else\n border_color = nil\n end\n\n # Draw Image\n ucImageBorder = UCImageBorder.new(self, Rect.new(@contents_x, @contents_y, width, height),\n bitmap, Rect.new(0,0, width-border*2, height-border*2),\n 0, 255, 0, border, border_color)\n @cControlsList.push(ucImageBorder)\n \n @contents_x += width\n @biggest_text_height = height if height > @biggest_text_height\n #bitmap.dispose\n when \"\\x12\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n\n new_line if (@contents_x + 96 > contents.width)\n\n # Draw Face\n actor = Game_Actor.new($1.to_i)\n ucCharFace = UCCharacterFace.new(self, Rect.new(@contents_x, @contents_y, 96, 96), actor)\n @cControlsList.push(ucCharFace)\n \n @biggest_text_height = 96 if 96 > @biggest_text_height\n else\n # Draw Text\n next_char = text.slice(/./m)\n contents_text += c\n if next_char == nil || next_char.match(/[\\x01-\\x12\\x80-\\xff]/) != nil\n text_height = contents.get_text_height(contents_text)\n if text_height < WLH\n text_height = WLH\n end\n @biggest_text_height = text_height if text_height > @biggest_text_height\n\n rect = Rect.new(@contents_x, @contents_y, contents.width, @biggest_text_height)\n cLabel = CLabel.new(self, rect, contents_text, 0, contents.font.clone, \n true, false, 3)\n @cControlsList.push(cLabel)\n \n lines = contents.split_multiline(rect, contents_text, 3)\n if lines.size > 1\n text_height = contents.get_text_height(contents_text)\n if text_height < WLH\n text_height = WLH\n end\n text_height = @biggest_text_height + text_height * (lines.size-2)\n @biggest_text_height = text_height if text_height > @biggest_text_height\n new_line\n end\n\n contents_text = \"\"\n @contents_x += contents.get_text_width(lines[lines.size-1])\n end\n \n end\n end\n\n end",
"def image_processing\n \tpixel_array_img1 = read_file_image(\"book4_no_table.jpg\")\n \tpixel_array_img2 = read_file_image(\"net_book5.jpg\")\n\n\n \tpixel_array_sq_img1 = []\n \tpixel_array_sq_img2 = []\n \tpixel_array_img1x2 = []\n \t##################FALTA AQUI ALGO\n\n \t###### ARRAY OF PIXEL ARRAY\n \t# SQUARE IMAGE IMG_1\n \tpixel_array_sq_img1 = square_array(pixel_array_img1)\t\t\n\t\tpixel_array_sq_img2 = square_array(pixel_array_img2)\n \tpixel_array_img1x2 = product_array(pixel_array_img1,pixel_array_img2)\n\n\t\t# Apply convolve filter two image array\n\t\timg_1_convolve_filter = convolve(pixel_array_img1,@gaussian_kernel)\n\t\timg_2_convolve_filter = convolve(pixel_array_img2,@gaussian_kernel)\n\n\t\t## Array Square\n\t\timg_1_convolve_filter_sq = square_array(img_1_convolve_filter)\n\t\timg_2_convolve_filter_sq = square_array(img_2_convolve_filter)\n\t\timg_2x1_convolve_filter = product_array(img_1_convolve_filter,img_2_convolve_filter)\n\n\t\t#Convolve FILTER Square IMG1 and IMG2\n\t\timg_1_sq_convolve_filter = convolve(pixel_array_sq_img1,@gaussian_kernel)\n\t\timg_2_sq_convolve_filter = convolve(pixel_array_sq_img2,@gaussian_kernel)\n\n\t\t#Convolve FILTER to Product IMG1 and IMG2 \n\t\timg_1x2_convolve_filter = convolve(pixel_array_img1x2,@gaussian_kernel)\n\n\t\timg_1_sq_convolve_filter = difference_array(img_1_sq_convolve_filter,img_1_convolve_filter_sq)\n\t\timg_2_sq_convolve_filter = difference_array(img_2_sq_convolve_filter,img_2_convolve_filter_sq)\n\t\timg_1x2_convolve_filter = difference_array(img_1x2_convolve_filter,img_2x1_convolve_filter)\n\n\n\n\t\t#c1/c2 constants\n\t #First use: manual fitting\n\t c_1=6.5025\n\t c_2=58.5225\n\t \n\t #Second use: change k1,k2 & c1,c2 depend on L (width of color map)\n\t l=255\n\t k_1=0.01\n\t c_1=(k_1*l)**2\n\t k_2=0.03\n\t c_2=(k_2*l)**2\n\t \n\t #Numerator of SSIM\n\t num_ssim = \n\t product_array(\n\t \tmultiple_and_factor_increment(2,img_2x1_convolve_filter,c_1),\n\t \tmultiple_and_factor_increment(2,img_1x2_convolve_filter,c_2))\n\t ##Denominator of SSIM\n\t den_ssim = product_array(sum_two_array_and_incremente(img_1_convolve_filter_sq,img_2_convolve_filter_sq,c_1),sum_two_array_and_incremente(img_1_sq_convolve_filter,img_2_sq_convolve_filter,c_2))\n\t ##SSIM\n\t index = division_and_average(num_ssim,den_ssim)\n\n\t puts index\n\n end",
"def to_image(opts={})\n with_options opts do\n canvas = Magick::Image.new(full_width, full_height)\n bars = Magick::Draw.new\n\n x1 = margin\n y1 = margin\n\n if barcode.two_dimensional?\n encoding.each do |line|\n line.split(//).map{|c| c == '1' }.each do |bar|\n if bar\n x2 = x1+(xdim-1)\n y2 = y1+(ydim-1)\n # For single pixels use point\n if x1 == x2 && y1 == y2\n bars.point(x1,y1)\n else\n bars.rectangle(x1, y1, x2, y2)\n end\n end\n x1 += xdim\n end\n x1 = margin\n y1 += ydim\n end\n else\n booleans.each do |bar|\n if bar\n x2 = x1+(xdim-1)\n y2 = y1+(height-1)\n bars.rectangle(x1, y1, x2, y2)\n end\n x1 += xdim\n end\n end\n\n bars.draw(canvas)\n\n canvas\n end\n end",
"def draw_cassette_feature( image, feature, x, y, params = {} )\n width = feature.width\n height = @feature_height\n colour = feature.render_options[ \"colour\" ] || params[:colour] || \"white\"\n font = feature.render_options[ \"font\" ] || params[:font] || \"black\"\n label = params[:label] || feature.feature_name\n drawing = Magick::Draw.new\n\n # create a block\n drawing.stroke( \"black\" )\n drawing.fill( colour )\n drawing.rectangle( x, @top_margin, x + width, @image_height - @bottom_margin )\n drawing.draw( image )\n\n # annotate the block\n pointsize = @font_size\n drawing.annotate( image, width, height, x, @top_margin, label ) do\n self.fill = font\n self.font_weight = Magick::BoldWeight\n self.gravity = Magick::CenterGravity\n self.pointsize = pointsize\n end\n\n return image\n end",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end",
"def _binary_mask_stuff_internal!(text)\n # Keep original size, so can check haven't resized it\n orig_size = text.size\n\n # Replace ASCII email addresses...\n text.gsub!(MySociety::Validate.email_find_regexp) do |email| \n email.gsub(/[^@.]/, 'x')\n end\n\n # And replace UCS-2 ones (for Microsoft Office documents)...\n # Find emails, by finding them in parts of text that have ASCII\n # equivalents to the UCS-2\n ascii_chars = text.gsub(/\\0/, \"\")\n emails = ascii_chars.scan(MySociety::Validate.email_find_regexp)\n # Convert back to UCS-2, making a mask at the same time\n emails.map! {|email| [\n Iconv.conv('ucs-2', 'ascii', email[0]), \n Iconv.conv('ucs-2', 'ascii', email[0].gsub(/[^@.]/, 'x'))\n ] }\n # Now search and replace the UCS-2 email with the UCS-2 mask\n for email, mask in emails\n text.gsub!(email, mask)\n end\n\n # Replace censor items\n self.info_request.apply_censor_rules_to_binary!(text)\n\n raise \"internal error in binary_mask_stuff\" if text.size != orig_size\n end",
"def traitementMonochrome()\n return @image = @image.quantize(2, GRAYColorspace)\n end",
"def blur_pixel(ones_array)\n ones_array.each do |point_array|\n # => breaks the point_array inner arrays into its two parts --\n # => wouldn't work if there was stuff in the middle\n row = point_array.first\n col = point_array.last\n # => this is where the transformation happens\n @image_array[row - 1][col] = 1\n @image_array[row][col - 1] = 1 unless col == 0\n @image_array[row + 1][col] = 1 unless row >= @num_row - 1\n @image_array[row][col + 1] = 1 unless col >= @num_col - 1 \n end\n end",
"def mark_image(image)\n images = Magick::Image.from_blob(image) # from_blob returns array of images\n image = images[0] # method is receiving just one image\n\n mark = Magick::Image.new(image.columns, image.rows)\n\n gc = Magick::Draw.new\n gc.gravity = Magick::CenterGravity\n gc.pointsize = 32\n gc.font_family = \"Arial\"\n gc.font_weight = Magick::BoldWeight\n gc.stroke = 'none'\n gc.annotate(mark, 0, 0, 0, 0, WATERMARK_STRING)\n\n mark = mark.shade(true, 310, 30)\n\n image.composite!(mark, Magick::CenterGravity, Magick::HardLightCompositeOp)\n\n image = image.to_blob\n return image\nend",
"def imgify(tweet)\n return tweet\nend",
"def cleanup image\n m_begin \"cleanup\"\n img = get_image(image)\n img = img.gaussian_blur(8)\n img = img.threshold((QuantumRange * 0.999).to_int)\n img = img.gaussian_blur(14)\n img = img.threshold(0)\n m_end \"cleanup\"\n set_variable(image, img)\n end",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def image_ocr_photo_to_text(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_to_text_with_http_info(image_file, opts)\n data\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def generate\n MiniMagick::Tool::Convert.new do |i|\n i.font random_font\n i.size image_size\n i.pointsize config[:font_size]\n i.fill config[:font_color]\n i.gravity \"center\"\n i.canvas config[:background]\n i.draw \"text 0,0 '#{text}'\"\n i.noise + \"Gaussian\"\n i << \"#{config[:format]}:-\"\n end\n end",
"def image_ocr_photo_recognize_business_card_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_recognize_business_card ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_recognize_business_card\"\n end\n # resource path\n local_var_path = '/ocr/photo/recognize/business-card'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'BusinessCardRecognitionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_recognize_business_card\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def createAscii(options = {})\n if @status == true\n options = {\"width\" => 90, \"color\" => true}.merge(options)\n\t img = Magick::Image.from_blob(@data).first\n\t width = options[\"width\"]\n\t scale = (width.to_f / img.columns)\n\t \n\t height = ((img.rows * scale) / 2).to_i\n\t # puts height\n\t if height >= 100\n\t \theight = 80\n\t end\n\n\t border = \"+#{'-' * width}+\\n\"\n\t output = border.dup\n\n\t img.resize!(width, height)\n\t color_image = img.dup if options[\"color\"]\n\t img = img.quantize(@image_chars.length, Magick::GRAYColorspace).normalize\n\t quantum_calc = Magick::QuantumRange / (@image_chars.length - 1)\n\n\t \n\t img.view(0, 0, width, height) do |view|\n\t \n\t height.times do |i|\n\t \n\t output << '|'\n\t width.times do |j|\n\n\t character = @image_chars[view[i][j].red/quantum_calc] \n\n\t if options[\"color\"]\n\t pix = color_image.pixel_color(j,i)\n\t character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))\n\t end\n\n\t output << character\n\t end\n\n\t output << \"|\\n\"\n\t end\n\t end\n\n\n\t output << border\n\t return output\n end\n end",
"def apply(template_image)\n self.scale\n\n image = Magick::ImageList.new(self.artwork.image.path)\n\n image[0].rotate!(rotation) unless rotation.nil?\n image.resize!(self.width, self.height)\n\n center_x = template_image.columns / 2\n crop_image!(image, center_x)\n\n self.image_x += template_image.columns / 2 if self.leg == 'right'\n\n # x_copies = (image[0].columns / template[0].columns).ceil\n # y_copies = (image[0].rows / template[0].rows).ceil\n\n # To be tiling, see http://www.imagemagick.org/RMagick/doc/ilist.html#mosaic\n # tiled = Magick::ImageList.new\n # page = Magick::Rectangle.new(0,0,0,0)\n # x_copies.times do |x|\n # y_copies.times do |y|\n\n # end\n # end\n\n design_image = template_image[0].composite(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n\n if mirror\n design_image.flop!\n design_image.composite!(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n design_image.flop!\n end\n\n intermediate_location = \"#{Dir.tmpdir}/#{SecureRandom.hex}.png\"\n design_image.write(intermediate_location)\n intermediate_location\n end",
"def show\n @samples = ImageReaderService.new(@image).analyze.generate_samples 4\n end",
"def create\n @bwimage = Bwimage.new(params[:bwimage])\n\n respond_to do |format|\n if @bwimage.save\n format.html { redirect_to @bwimage, notice: 'Bwimage was successfully created.' }\n format.json { render json: @bwimage, status: :created, location: @bwimage }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bwimage.errors, status: :unprocessable_entity }\n end\n end\n end",
"def apply_filter(filter)\n filter.setValue(self.ciimage, forKey: 'inputImage')\n return filter.valueForKey('outputImage')\n end",
"def Process(text)\n text.to_str.gsub(/:\\(?([a-z0-9\\+\\-_]+)\\)?:/) do |match|\n\t \n # checks, if user wanted an animated smiley or not\n animated = false\n if (match.include?('(') && match.include?(')'))\n animated = true\n end\n\n # proposed image path, if image is locally available\n\tif animated\n local_image = File.join(Dir.pwd, 'public', 'smileys', 'animated', $1 + '.gif')\n else\n local_image = File.join(Dir.pwd, 'public', 'smileys', 'general', $1 + '.png')\n end\n\n # returns image tag, if image locally exists\n if File.exist?(local_image)\n ImageTag($1, animated)\n\n # image doesn't exists locally\n else\n # stores the image and returns image tag, if smiley is valid\n if SmileyExist($1, animated)\n ImageStore($1, animated)\n ImageTag($1, animated)\n else\n if animated\n '('+$1+')'\n else\n ':'+$1+':'\n end\n end\n end\n\n end\n end",
"def create\n @txt = Txt.new(params[:txt])\n\n \n respond_to do |format|\n if @txt.save\n \n # long text parser \n $KCODE='utf8'\n require 'jcode'\n d_str =''\n @txt.longtext.each {|s_str| \n while s_str.jsize > NUM_WORD_PER_LINE\n tmp_str = s_str.scan(/./)[0,NUM_WORD_PER_LINE].join\n d_str += tmp_str + \"\\n\\n\"\n s_str = s_str[tmp_str.size,s_str.size-tmp_str.size]\n if s_str == nil then break end\n #puts s_str.jsize \n end\n if s_str!=nil then d_str += s_str end\n d_str += \"\\n\"\n }\n \n #--- path and name. to be config/updated in new environments\n font_path = 'D:\\\\fonts'\n images_path = \"public/images\"\n output_path = 'public/images/outputs'\n bg_image_path = images_path + \"/\"+ \"background.png\"\n\n require 'find'\n # do the same thing for each available fonts\n Find.find(font_path) do |f|\n img = Magick::Image.read(bg_image_path).first #图片路径\n src_img = Magick::Image.read(images_path+'/user_image.JPG').first # to be replaced with user's picture url\n src_img.crop_resized!(320,320) # 照片的目标尺寸\n src_img.border!(10, 10, \"#f0f0ff\") #相框的颜色,宽度\n frame_img = Magick::Image.read(images_path+'/frame.png').first # picture frame\n frame_img.composite!(src_img, 0, 0, Magick::OverCompositeOp)\n img.composite!(frame_img, 20, 20, Magick::OverCompositeOp)\n \n gc= Magick::Draw.new\n gc.annotate(img, 0, 0, 420, 50, d_str) do #可以设置文字的位置,参数分别为路径、宽度、高度、横坐标、纵坐标\n #self.gravity = Magick::CenterGravity\n self.font = f\n self.pointsize = FONT_SIZE #字体的大小\n self.fill = '#fff' #字体的颜色\n self.stroke = \"none\"\n end \n font_file_name = File.basename(f, 'ttf')\n file_path = output_path + \"/\"+ @txt.image_url + \"_\" + font_file_name + \"png\" \n img.write(file_path) \n end\n \n #@path = file_name\n format.html { redirect_to(@txt, :notice => 'Txt was successfully created.') }\n format.xml { render :xml => @txt, :status => :created, :location => @txt }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @txt.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def monochrome! \n\t\treturn @image = @image.quantize(2, Magick::GRAYColorspace) \n\tend"
] |
[
"0.59254843",
"0.57710195",
"0.5659876",
"0.5643329",
"0.55341864",
"0.5517297",
"0.5444709",
"0.5424364",
"0.53248155",
"0.52780914",
"0.52743953",
"0.5258123",
"0.52495515",
"0.5228497",
"0.52118057",
"0.52086914",
"0.5180699",
"0.5142263",
"0.51032317",
"0.51001775",
"0.50779665",
"0.50599444",
"0.5039374",
"0.50059265",
"0.49497086",
"0.4942615",
"0.4940438",
"0.49299195",
"0.49022081",
"0.48964235",
"0.4892705",
"0.48732853",
"0.48721293",
"0.48406672",
"0.48108622",
"0.48040447",
"0.47874624",
"0.47831333",
"0.476129",
"0.47462228",
"0.47445577",
"0.47441936",
"0.4741764",
"0.4736298",
"0.47362468",
"0.4734744",
"0.47301692",
"0.4724807",
"0.47239694",
"0.4721972",
"0.46821126",
"0.4676515",
"0.4673404",
"0.46656758",
"0.46584457",
"0.46457484",
"0.46411902",
"0.46382305",
"0.46113846",
"0.4607988",
"0.4592679",
"0.45712268",
"0.45675743",
"0.45556173",
"0.45462066",
"0.4545597",
"0.4530683",
"0.4529616",
"0.45250982",
"0.45155534",
"0.4511288",
"0.45080656",
"0.4504253",
"0.45034668",
"0.44959378",
"0.44867897",
"0.4486017",
"0.44859582",
"0.44806445",
"0.4479621",
"0.44792598",
"0.44781485",
"0.44760707",
"0.4462792",
"0.44602558",
"0.4451933",
"0.44519296",
"0.4431842",
"0.44267866",
"0.442673",
"0.44082",
"0.44063026",
"0.44046617",
"0.43986687",
"0.4397528",
"0.43948695",
"0.43941566",
"0.4392749",
"0.4387599",
"0.4371942"
] |
0.55367297
|
4
|
Convert an image of text into a binarized (light and dark) view Perform an adaptive binarization algorithm on the input image to prepare it for further OCR operations.
|
def preprocessing_binarize_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize"
end
# resource path
local_var_path = '/ocr/preprocessing/image/binarize'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_binarize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def preprocessing_binarize_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_advanced_with_http_info(image_file, opts)\n data\n end",
"def binarize id\n m_begin \"binarize\"\n put_image(id, get_image(id).bilevel_channel(QuantumRange/2))\n# put_image(id, @var_table[id].quantize(2, GRAYColorspace, NoDitherMethod) )\n m_end \"binarize\"\n end",
"def recognize(image)\n # quantize to two-color\n image = quantize_image(image)\n\n # the binary string we expect to see from the output nodes\n assign_inputs image\n\n calculate_hidden_outputs\n calculate_final_outputs\n\n #@output_values.each.with_index { |v, i| puts \"index: #{i} => #{v}\" }\n\n # process results\n #\n binary_string = quantized_result.inject(\"\") { |accum, bit| \"#{accum}#{bit.to_s}\" }\n binary_string.to_i(2)\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def preprocessing_binarize(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_with_http_info(image_file, opts)\n data\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def blur_image\r\n\r\n#define new image array with identical length to old array\r\n image1 = Array.new(@image.length){\r\n Array.new(@image[0].length){}}\r\n\r\n#start indexing through each cell and define values for rows and columns\r\n @image.each_with_index { |val, rowindex|\r\n val.each_with_index {|val1, colindex| \r\n\r\n#hardcoding 'nil' index values into zeroes \r\n if image1 [rowindex][colindex] != 1 \r\n then image1 [rowindex][colindex] = 0 \r\n end\r\n\r\n#if currently indexed cell has a value of 1 in original array, cell value in new array will be 1\r\n if val1 > 0 \r\n then image1 [rowindex][colindex] = 1\r\n\r\n#define value of cell directly below currently indexed cell as 1, unless it is the last cell in a column.\r\n if colindex != val.length-1\r\n then image1 [rowindex][colindex +1] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define value of cell directly above it as 1.\r\n if colindex != 0 then\r\n image1 [rowindex][colindex -1] = 1\r\n end\r\n\r\n#define value of the cell to the RIGHT of the currently indexed cell as 1, unless it is the last cell in a row.\r\n if rowindex != @image.length-1 then\r\n image1 [rowindex +1][colindex] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define the value of the cell to the LEFT of it as 1.\r\n if rowindex != 0 then\r\n image1 [rowindex -1][colindex] = 1\r\n end\r\n\r\n end\r\n\r\n }} \r\n\r\n#show blurred image array\r\n image1.each do |cell|\r\n puts cell.join\r\n end\r\n end",
"def break_text_with_image(width, textarray, draw)\n tokens = textarray.flat_map{ |x| x.respond_to?(:split) ? x.split(/ /) : x }\n tokens = tokens.flat_map{ |x| x.respond_to?(:split) ? x.split(/(?<=\\n)/) : x }\n\n result = []\n line = []\n linelength = 0\n\n tokens.each_with_index do |item, i|\n itemlength = item.class == Image ?\n item.columns : draw.get_type_metrics(item + ' ').width\n\n if (line.empty?)\n line << item\n else\n if (width != 0 && itemlength + linelength > width)\n result << line\n line = [item]\n linelength = 0\n else\n t = line.pop\n\n if (t.class != Image)\n t += ' '\n elsif (item.class != Image)\n item = ' ' + item\n end\n\n if (t.class == Image or item.class == Image)\n line << t << item\n else\n line << t + item\n end\n end\n end\n\n if (item.class != Image and item.include?(\"\\n\"))\n line[0].sub!(\"\\n\", '')\n result << line\n line = []\n linelength = 0\n next\n end\n\n linelength += itemlength\n end\n\n unless (line.empty?)\n result << line\n end\n\n return result\n end",
"def apply_label(text, image)\n image.composite(build_label(text),\n Magick::CenterGravity,\n Magick::HardLightCompositeOp)\n end",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def enhance_image(image)\n colors = image.get_pixels.flatten\n colors.map! { |color| color**2 / 255 }\n blob = colors.pack('C*') # Recreate the original image, credit to stackoverflow.com/questions/53764046\n image = MiniMagick::Image.import_pixels(blob, image.width, image.height, 8, 'rgb')\n image.statistic('mean', '6x6')\n image.threshold(threshold_percent)\n image.statistic('median', '9x9') # Replace with object discard below set size\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def output_image\n @image_blur_array.each do |row|\n puts row.join\n end\n end",
"def blur(distance)\n row_max = @image[0].length() - 1\n column_max = @image.length() - 1\n\n ones = self.get_ones\n\n while distance > 0\n ones.each do |one|\n vert = one[1]\n horiz = one[0]\n \n # down \n @image[vert + distance][horiz] = 1 unless vert + distance > column_max\n\n # up\n @image[vert - distance][horiz] = 1 unless vert - distance < 0\n\n # right\n @image[vert][horiz + distance] = 1 unless horiz + distance > row_max\n\n # left\n @image[vert][horiz - distance] = 1 unless horiz - distance < 0\n\n sub_distance = distance\n diag = 1\n while sub_distance > 1\n\n # bottom sides\n unless vert + sub_distance - 1 > column_max || horiz - diag < 0 || horiz + diag > row_max\n @image[vert + sub_distance - 1][horiz - diag] = 1\n @image[vert + sub_distance - 1][horiz + diag] = 1 \n end\n\n # top\n unless vert - sub_distance + 1 < 0 || horiz - diag < 0 || horiz + diag > row_max\n @image[vert - sub_distance + 1][horiz - diag] = 1\n @image[vert - sub_distance + 1][horiz + diag] = 1\n end\n\n # right sides\n unless vert - diag < 0 || vert + diag > column_max || horiz + sub_distance - 1 > column_max\n @image[vert - 1][horiz + sub_distance - diag] = 1\n @image[vert + 1][horiz + sub_distance - diag] = 1\n end\n\n # left sides\n unless vert - diag < 0 || vert + diag > column_max || horiz + sub_distance - 1 < 0\n @image[vert - 1][horiz - sub_distance + diag] = 1\n @image[vert + 1][horiz - sub_distance + diag] = 1\n end\n\n sub_distance -= 1\n diag += 1\n\n end\n end\n\n distance -= 1\n end\n\n end",
"def preprocessing_binarize_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def analyze_ballot_image filename, dpi, result, upstream\n reset_analyzer filename, dpi, result, upstream\n open_ballot_image :ballot, filename, dpi\n locate_ballot\n sanity_check_ballot_coords\n analyze_vote_ovals\n analyze_barcode\n sanity_check\n compile_results result\n end",
"def blur(image, r, c, distance)\n\n # Set the column length and row length\n image_height = image.length\n image_width = image[0].length\n\n # start looking at the rows at index[0]\n start_row = r - distance # number \n if start_row < 0\n start_row = 0\n end\n\n # start column all the way to the left\n start_col = c - distance\n if start_col < 0\n start_col\n end\n\n end_row = r + distance\n if end_row > image_height - 1\n end_row = image_height - 1\n end\n\n end_col = c + distance\n if end_col > image_width - 1\n end_col = image_width - 1\n end\n\n for i in (start_row..end_row)\n for j in (start_col..end_col)\n if within_manhatten_distance?(i, j, r, c, distance)\n image[i][j] = 2\n end\n end\n end\nend",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def add_blur_to_image\n r = 0\n c = 0\n rc = 0\n n = 1\n z = []\n u = @y.size.to_i\n while n <= u\n @ary.each_index do |r|\n @ary[r].each_index do |c|\n if ((c.to_i - y[rc][1].to_i).abs + (r.to_i - y[rc][0].to_i).abs).between?(1, @distance.to_i);\n z << [r.to_i, c.to_i]\n end\n end\n end\n r = 0\n c = 0\n rc += 1\n n += 1\n end\n zz=[]\n r1 = 0\n c1 = 0\n z.each do |r|\n r1 = r[0].to_i\n c1 = r[1].to_i\n @ary[r1][c1] = 1\n end\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def text_color_for_image(image)\n dominant = dominant_color(image)\n brightness = brightness(dominant)\n # Por ahora sólo devolvemos blanco o negro.\n # Si lo vemos muy feo, pensar una solución\n # más inteligente.\n if brightness < 255 / 2\n \"#fff\"\n else\n \"#000\"\n end\n end",
"def preprocess_image(path)\n MiniMagick::Tool::Convert.new.yield_self do |convert|\n convert << path\n\n if config.localization_preprocessing != :none\n # general preprocessing\n convert.colorspace \"Gray\"\n convert.normalize\n\n if config.localization_preprocessing == :full\n # try to reduce shadows (based on https://legacy.imagemagick.org/Usage/compose/#divide)\n convert.stack do |stack|\n convert.clone 0\n convert.sample \"25%\"\n convert.blur \"30x10\"\n convert.resize \"400%\"\n end\n convert.compose \"DivideSrc\"\n convert.composite\n\n # remove short vertical features\n convert.morphology \"Close\", \"3x6: 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1\"\n # remove small features and flaws\n convert.morphology \"Close:3\", \"Square:1\"\n end\n\n convert.threshold \"50%\"\n end\n\n convert.depth 8\n convert << \"gray:-\"\n\n MiniMagick::Shell.new.run(convert.command)\n end.first\n end",
"def prepareBackgroundImage(text)\n # Margins within the text Rect\n x_margin = 5\n y_margin = 1\n\n dynamic_font = self.titleLabel.font\n # We really don't care about the constraintSize just yet\n constraintSize = CGSizeMake(200, 37)\n current_size = text.sizeWithFont(dynamic_font, constrainedToSize:constraintSize, lineBreakMode: NSLineBreakByWordWrapping)\n\n # These are the images that should be concatenated.\n # They are the same height.\n pointer = UIImage.imageNamed(\"marker_pointer_unviewed.png\")\n balloon = UIImage.imageNamed(\"map_marker_unviewed.png\")\n\n # We are going to put the text in the balloon, which is at this rect. The\n # balloon should have x_margin space on each horizontal size, and y_margin\n # on each vertical side.\n\n textRect = Rect(pointer.size.width,\n pointer.size.height - current_size.height + y_margin * 2,\n current_size.width + x_margin * 2,\n pointer.size.height - current_size.height + y_margin * 2)\n\n # The size of the entire image should be the pointer + the width of the text rect\n # and the height of the images, which are the same height\n img_size = Size(pointer.size.width + textRect.size.width, pointer.size.height)\n pointed = UIImage.canvas(img_size) do |context|\n pointer.drawAtPoint([0,0])\n # We create a stretchable image between the x_margin pixels on each horizontal side\n insets = EdgeInsets(0, 15, 0, 45)\n img = balloon.resizableImageWithCapInsets(insets)\n # We draw that this image, which is the same height as the pointer to cover the textRect\n # This operation is basically filling the image next to the pointer to the desired size\n img.drawInRect(Rect(pointer.size.width, 0, textRect.size.width, pointer.size.height))\n end\n self.setBackgroundImage(pointed, forState: UIControlStateNormal)\n #self.setBackgroundImage(pointed.darken, forState: UIControlStateHighlighted)\n # The text gets drawn centered on the entire size of the button.\n # So, we have to offset the centers with insets so that the\n # center of the text is in the center of the text Rect.\n # The coordinate system is 0,0 at bottom left, so we need to inset right,\n # and up, which means we have a positive left, and a negative top inset.\n # Furthermore the text must be inset by the margins inside the\n # calculated Rect.\n contentRect = Rect([0,0],pointed.size)\n titleCenter = Point [CGRectGetMidX(contentRect), CGRectGetMidY(contentRect)]\n textRectCenter = Point [CGRectGetMidX(textRect), CGRectGetMidY(textRect)]\n top = textRectCenter.y - titleCenter.y + y_margin\n left = textRectCenter.x - titleCenter.x + x_margin\n puts \"titleCenter #{titleCenter.inspect} textCenter #{textRectCenter.inspect}\"\n puts \"top #{-top} left #{left}\"\n w = EdgeInsets(-top, left, 0, 0)\n self.titleEdgeInsets = w\n self.size = pointed.size\n end",
"def blur_image(distance)\r\n @length = @image.length\r\n @width = 0\r\n @image.each do |x|\r\n x.each do |cell|\r\n @width += 1\r\n end\r\n end\r\n i = 0\r\n j = 0\r\n n = distance\r\n while n > 0\r\n i = 0\r\n j = 0 \r\n while i < @length\r\n j = 0\r\n while j < @width\r\n if @image[i][j] == 1\r\n\r\n # This looks down from the rows\r\n if i < @length - 1\r\n if @image[i+1][j] == 0\r\n @image[i+1][j] = 2\r\n end\r\n end\r\n\r\n # This looks up from the rows\r\n if i > 0 && @image[i-1][j] == 0\r\n @image[i-1][j] = 2 \r\n end\r\n\r\n # This looks to the right until it gets to the end.\r\n if @image[i][j+1] == 0\r\n @image[i][j+1] = 2\r\n end\r\n\r\n # This looks to te left. I tried to set this so it will never look over the side of the array.\r\n # I'm afraid of what might happen if my program does that too muc.\r\n if j > 0 && @image[i][j - 1] == 0\r\n @image[i][j - 1] = 2\r\n end\r\n end\r\n j += 1\r\n end\r\n i += 1\r\n end\r\n # This code goes back through the array and turns the temporary shade values into 1s for output.\r\n i = 0\r\n j = 0\r\n while i < @length\r\n j = 0\r\n while j < @width\r\n if @image[i][j] == 2\r\n @image[i][j] = 1\r\n end\r\n j += 1\r\n end\r\n i += 1\r\n end\r\n n -= 1\r\n puts n\r\n end\r\n \r\n puts \"Inside blur_image\\n\"\r\n puts \"\\n\"\r\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def design2image\n\n bkgImg = Image.read(\"#{Rails.root}/public/#{params[:bkg]}\").first\n\n sideTop = 36\n sideLeft = 95\n sideWidth = 216\n sideHeight = 353\n\n side = params[:side]\n if side == 'SLEEVE'\n sideWidth = 162\n sideHeight = 250\n end\n #ART Processing\n arts = params[:art];\n art_tops = params[:art_top];\n art_lefts = params[:art_left];\n \n \n #Image.new(columns, rows) ~ (width, height)\n containSide = Magick::Image.new(sideWidth, sideHeight) do\n self.background_color = 'none'\n end\n\n i=0\n if arts\n clipArt = Image.read(\"#{Rails.root}/public/#{arts[0]}\").first\n clipArtTop = art_tops[i].to_i if art_tops[i]\n clipArtLeft = art_lefts[i].to_i if art_lefts[i]\n containSide = containSide.composite(clipArt, clipArtLeft, clipArtTop, OverCompositeOp)\n end\n\n #TEXT Processing\n texts = params[:text];\n text_tops = params[:text_top];\n text_lefts = params[:text_left];\n\n\n if texts\n textArtTop = text_tops[i].to_i if text_tops[i]\n textArtLeft = text_lefts[i].to_i if text_lefts[i]\n gc = Magick::Draw.new\n textArt = Magick::Image.new(300, 200) do\n self.background_color = 'none'\n end\n gc.annotate(textArt, 0, 0, 0, 0, texts[i]) do\n self.gravity = Magick::NorthWestGravity\n self.pointsize = 22\n self.font_family = \"Times\"\n self.fill = '#0000A9'\n self.stroke = \"none\"\n end\n end\n\n containSide.composite!(textArt, textArtLeft || 0, textArtTop || 0, OverCompositeOp) if textArt\n \n bkgImg.composite!(containSide, sideLeft, sideTop, OverCompositeOp)\n bkgImg.scale!(0.5)\n\n send_data bkgImg.to_blob, :disposition => 'inline', :type => 'image/png'\n\n# output = get_working_image(@session_id)\n# unless File.exist?(output)\n# FileUtils.cp(\"#{RAILS_ROOT}/public/images/#{params[:textart]}.png\", output)\n# img = Image.read(output).first\n# img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n# img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n# img.background_color = \"none\"\n# img = img.rotate(params[:r].to_f) unless params[:r].blank?\n# img.write(output)\n# end\n# img = Image.read(output).first\n# send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def binarization(color, threshold)\n mid = ((color.red / 257) + (color.green / 257) + (color.blue / 257)) / 3\n return mid > threshold ? \"#fff\" : '#000'\nend",
"def blurred\r\n unos = []\r\n # nested loops for rows and columns\r\n @paint.each_with_index do |row, rownum| # iterating over elements in the main array for rows \r\n row.each_with_index do |element, colnum| # iterating over elements in each subarray for columns\r\n if element == 1\r\n unos << [rownum, colnum]\r\n end\r\n end\r\n end\r\n\r\n unos.each do |rownum, colnum| \r\n # assigning \"1\" above \"1\"s, except for first row\r\n @paint[rownum -1][colnum] = 1 unless rownum == 0\r\n # assigning \"1\" below \"1\"s, except for last row\r\n @paint[rownum +1][colnum] = 1 unless rownum >= @paint.length-1\r\n # assigning \"1\" to the left of \"1\"s, except for first column\r\n @paint[rownum][colnum -1] = 1 unless colnum == 0\r\n # assigning \"1\" to the right of \"1\"s, except for last column\r\n @paint[rownum][colnum +1] = 1 unless colnum >= @paint[rownum].length-1\r\n end\r\n end",
"def photo_text_s(image, text, alt_text = t(text))\n image_tag('image/todd_ramirez_' + image,\n alt: alt_text,\n title: alt_text) + tag(:br) +\n content_tag(:itext, t(text)) + tag(:br) + tag(:br) + tag(:br) + tag(:br)\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def colorize(text)\n Albino.new(text, self).colorize(:O => 'stripnl=false')\n end",
"def recognize_detect_text_fine(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_fine_with_http_info(image_file, opts)\n data\n end",
"def display_alternative_text_image(image)\n # Interface method\n end",
"def photo_text(image, text, alt_text = t(text))\n image_tag('image/todd_ramirez_' + image,\n alt: alt_text,\n title: alt_text) + tag(:br) +\n content_tag(:itext, t(text)) + tag(:br)\n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def image_ocr_photo_to_text_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_to_text ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_to_text\"\n end\n # resource path\n local_var_path = '/ocr/photo/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_to_text\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def image_ocr_photo_recognize_business_card(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_business_card_with_http_info(image_file, opts)\n data\n end",
"def analyze_barcode\n Barcode_Columns.times do |barcode_col_index|\n barcode_pos = transform_point(BPoint.new(barcode_col_index, Barcode_Row-1), :bottombias)\n @upstream.ann_point(barcode_pos.x, barcode_pos.y)\n score = shrink_to_one(:ballot, barcode_pos.x - i2p(TM_Width)/2.0, barcode_pos.y-i2p(TM_Height)/2.0, i2p(TM_Width), i2p(TM_Height))\n if score < (QuantumRange * BarCodeDetectThresh).to_int then\n @raw_barcode << barcode_col_index\n end\n end\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def transform(manHatDist)\r\n\t\tpixel_on = []\r\n\t\tmanHatDist.times do\r\n\t\t@image.each.with_index do |row, row_index|\r\n\t\t\trow.each.with_index do |pixel, col_index|\r\n\t\t\t\tif pixel == 1\r\n\t\t\t\t\tpixel_on.push [row_index, col_index]\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\t\tpixel_on.each do |touple|\r\n\t\t\t#blur(*touple)\r\n\t\t\trow_index, col_index = touple\r\n\t\t\tblur(row_index, col_index)\r\n\t\tend\r\n\tend\r\n\tend",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def darken(options={})\n filter_name = 'CIColorControls'\n filter_options = {\n inputBrightness: options[:brightness] || -0.5,\n inputSaturation: options[:saturation] || -0.2,\n }\n\n cg_input_image = CIImage.alloc.initWithImage(self)\n darken_filter = CIFilter.filterWithName(filter_name)\n raise Exception.new(\"Filter not found: #{filter_name}\") unless darken_filter\n\n darken_filter.setDefaults\n darken_filter.setValue(cg_input_image, forKey:'inputImage')\n filter_options.each_pair do |key, value|\n darken_filter.setValue(value, forKey:key)\n end\n output = darken_filter.valueForKey('outputImage')\n\n context = CIContext.contextWithOptions(nil)\n cg_output_image = context.createCGImage(output, fromRect:output.extent)\n output_image = UIImage.imageWithCGImage(cg_output_image)\n\n return output_image\n end",
"def text(section_type: :default)\n img = @image \n \n # resample if an image 4\"x4\" is less than 300dpi \n if img.columns * img.rows < 144000\n img = img.resample(300)\n end\n \n params = SECTION_PARAMS[:default].merge(SECTION_PARAMS[section_type])\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n\n if @text == \"\"\n img = img.white_threshold(245)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n if @text == \"\"\n img = img.quantize(256,Magick::GRAYColorspace)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n @text\n end",
"def blur!\r\n ones = get_ones\r\n ones.each do |found_row_number, found_col_number| \r\n @picture[found_row_number -1][found_col_number] = 1 unless found_row_number == 0 #up\r\n @picture[found_row_number +1][found_col_number] = 1 unless found_row_number == @picture.length-1 #down\r\n @picture[found_row_number][found_col_number -1] = 1 unless found_col_number == 0 #left\r\n @picture[found_row_number][found_col_number +1] = 1 unless found_col_number == @picture[found_row_number].length-1 #right\r\n end\r\n end",
"def toaster_filter\n manipulate! do |img|\n img.modulate '150,80,100'\n img.gamma 1.1\n img.contrast\n img.contrast\n img.contrast\n img.contrast\n img = yield(img) if block_given?\n img\n end\n end",
"def blur\n things_to_blur = []\n # looking for 1s to blur going through each array\n @grid.each_with_index do |or_row, row_index|\n or_row.each_with_index do |cell, cell_index|\n #is this current cell a 1?\n if cell == 1\n #run function on code\n recursive_blur(Point.new(cell_index, row_index), things_to_blur)\n end\n end\n end\n things_to_blur.each do |point|\n @grid[point.y][point.x] = 1\n end\n output_image\n end",
"def computeProjection\n w,h = @type==:vertical ? [@image.width, @image.height] : [@image.height, @image.width]\n mw,mh = @type==:vertical ? [@image.width, @image.height-@image.borders.bottom] : [@image.height, @image.width-@image.borders.right]\n content_mask = Array.new(w){[false, 0]}\n\n w.times do |a|\n obj_height = 0\n gap = 0\n (h-mh).times do |b|\n x,y = @type==:vertical ? [a,b] : [b,a]\n idx = @image.index(x, y)\n #p [idx, w, h, mh, a, b, x, y, @image.width, @image.height]\n if @data[idx] <= @threshold\n obj_height += 1\n obj_height += gap if gap <= @image.min_obj_size\n gap = 0\n else\n gap += 1\n content_mask[a] = [true, b] if obj_height > @image.min_obj_size\n obj_height = 0\n end\n end\n end\n\n content_mask\n end",
"def generate(options = {})\n options.reverse_merge!(\n :fontsize => 25,\n :padding => 20,\n :color => '#000',\n :background => '#fff',\n :fontweight => 'bold',\n :rotate => true,\n :font => config['font']\n ).symbolize_keys!\n\n options[:fontweight] = case options[:fontweight]\n when 'bold' then 700\n else 400\n end\n \n text = Magick::Draw.new\n text.pointsize = options[:fontsize]\n text.font_weight = options[:fontweight]\n text.fill = options[:color]\n text.gravity = Magick::CenterGravity\n text.font = options[:font] if options[:font]\n \n #rotate text 5 degrees left or right\n text.rotation = (rand(2)==1 ? 5 : -5) if options[:rotate]\n \n metric = text.get_type_metrics(self.string)\n\n #add bg\n canvas = Magick::ImageList.new\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = options[:background]\n }\n\n #add text\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = 'transparent'\n }.annotate(text, 0, 0, 0, 0, self.string).wave(1, 50)\n\n #add noise\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n p = Magick::Pixel.from_color(options[:background])\n p.opacity = Magick::MaxRGB/2\n self.background_color = p\n }.add_noise(Magick::LaplacianNoise)\n\n self.image = canvas.flatten_images.blur_image(1)\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def text_label(text:, dpi: 100, text_colour: [0, 0, 0, 255], shadow_colour: [255, 255, 255, 150], blur: 1.5)\n text_mask, = Vips::Image.text(text, dpi: dpi)\n\n canvas_width = text_mask.width + 10\n canvas_height = text_mask.height + 10\n text_mask = text_mask.gravity('west', canvas_width, canvas_height)\n # use 0 - 1 for the masks\n text_mask /= 255\n\n shadow_mask = text_mask.gaussblur(blur)\n # credit: https://github.com/libvips/pyvips/issues/204\n text_mask = text_mask * text_colour + ((text_mask * -1) + 1) * shadow_mask * shadow_colour\n\n text_mask.unpremultiply.copy(interpretation: 'srgb')\n end",
"def blur(image)\n convolve(to_narray(image), GAUSS).to_a\n end",
"def recognize_detect_text_large_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_large ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_large\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/large'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'TextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_large\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def image_ocr_post_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_post ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_post\"\n end\n # resource path\n local_var_path = '/ocr/image/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n header_params[:'preprocessing'] = opts[:'preprocessing'] if !opts[:'preprocessing'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def binarize(inputs)\n return inputs.map{|pixel|\n pixel > 0.5 ? 1.0 : 0.0\n }\n end",
"def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end",
"def recognize_detect_text_fine_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_fine ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_fine\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/fine'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'FineTextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_fine\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def filter_black_and_white_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: FilterApi.filter_black_and_white ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling FilterApi.filter_black_and_white\"\n end\n # resource path\n local_var_path = '/image/filter/black-and-white'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: FilterApi#filter_black_and_white\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def convert\n @value = \"\"\n @areas.each do |area|\n image = RTesseract.new(@source.to_s,@options)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:width].to_i, area[:height].to_i)\n @value << image.to_s\n end\n rescue\n raise RTesseract::ConversionError\n end",
"def build_canvas(lines_of_text_blocks)\n # Grab the greatest values for each line\n line_baseline = []\n line_height = []\n line_width = []\n lines_of_text_blocks.each_index do |i|\n baselines = (lines_of_text_blocks[i].sort { |a,b| a.baseline <=> b.baseline })\n heights = (lines_of_text_blocks[i].sort { |a,b| a.height <=> b.height })\n line_baseline << baselines.last.baseline\n line_height << heights.last.height - heights.last.line_spacing\n width = 0\n lines_of_text_blocks[i].each { |l| width += l.width }\n line_width << width\n end\n \n # set up canvas height and width\n @width = line_width.sort.last\n height = 0\n line_spacing_height = 0\n line_height.each { |h| height += h ; line_spacing_height += (h * (@options[:line_spacing] || 0)) }\n line_spacing_height -= (line_height.last * (@options[:line_spacing] || 0))\n @height = height + line_spacing_height\n \n options = nil\n if @options[:matte]\n options = @options.dup\n options[:bgcolor] = 'transparent'\n else\n options = @options\n end\n \n @canvas = IQ::Image::Canvas.new(@width, @height, options)\n \n # actually go through the lines and do stuff with them to make the canvas\n # for each line align each text block with the baseline\n top = 0\n lines_of_text_blocks.each_index do |i|\n left = 0\n lines_of_text_blocks[i].each do |text_block|\n offset = (line_baseline[i] - text_block.baseline)\n @canvas.overlay!(text_block.to_canvas, :dest_x => left, :dest_y => top + offset)\n left += text_block.width\n end\n top += line_height[i] + ((@options[:line_spacing] || 0) * line_height[i])\n end\n @canvas\n end",
"def blur(distance)\r\n # instantiate variables\r\n @b_array = Array.new(array.length) { Array.new(array[0].length,0) }\r\n min_y= 0\r\n max_y = b_array.length - 1\r\n min_x = 0 \r\n max_x = b_array[0].length - 1\r\n blurred_coordinates = []\r\n #iterate through each row of the array, passing down index and value\r\n array.each_with_index do |row,row_i|\r\n #iterate through each column (value) passing index and value\r\n row.each_with_index do |col,col_i| \r\n if row[col_i] == 1 \r\n blurred_coordinates << get_manhattan_set(row_i,col_i,distance)\r\n end\r\n end\r\n end\r\n\r\n blurred_coordinates.each do |set|\r\n set.each do |point|\r\n unless point[0]< min_x || point[1] < min_y || point[0]> max_y || point[1] > max_x\r\n @b_array[point[0]][point[1]] = 1\r\n end\r\n end \r\n end\r\n end",
"def do_overlay_image(image, hash)\n #puts \"get image\"\n #puts \"#{hash.inspect}\"\n #puts \"Image: #{hash[:image_path]}\"\n #puts \"File exists? #{File.exists?(hash[:image_path])}\"\n overlay_i = Magick::ImageList.new(hash[:image_path]).first\n #puts \"Do we want to colorize?\"\n if hash.has_key? :colorize\n \n #opc = hash[:opacity]\n overlay_i = do_colorize(overlay_i, hash.merge({:opacity=>0.5})) #overlay_i.colorize(opc, opc, opc, hash[:colorize])\n end\n return image.composite(overlay_i, 0, image.rows-overlay_i.rows, Magick::OverCompositeOp)\n end",
"def recognize_detect_text_large(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_large_with_http_info(image_file, opts)\n data\n end",
"def bbcodeize(text)\n text = text.dup\n TagList.each do |tag|\n if Tags.has_key?(tag)\n apply_tag(text, tag)\n else\n self.send(tag, text)\n end\n # Replace the matching random ids for the following tags: spoiler, nsfw, mp3\n @random_id = random_string\n 2.times { text = text.sub('_RANDOM_ID_', @random_id) }\n end\n text\n end",
"def detect_bandaid(image:, area: 2000)\n objects = detect_image(image: image)\n objects.each_with_index do |object, i|\n remove(i) if object.width * object.height > area\n end\n end",
"def optimized_image(image,x,y)\n return image.variant(resize_to_fill: [x,y]).processed\n end",
"def build_label(text)\n shading = false\n\n label = Magick::Image.new(@options[:width], @options[:height])\n image = Magick::Draw.new\n image.gravity = Magick::CenterGravity\n image.pointsize = @options[:width] / 4\n image.font = 'Helvetica'\n image.font_weight = Magick::NormalWeight\n image.stroke = 'none'\n image.annotate(label, 0, 0, 0, 0, text)\n label = label.shade(shading, 310, 30)\n\n return label\n end",
"def blur(distance)\n @distance = distance\n find_pixel_eq_1\n add_blur_to_image\n \n j = @ary.size\n q = @ary.flatten.size\n wa = q / j - 1\n l = q / j\n k = @ary.flatten\n m = 0\n n = l - 1\n while n <= q\n puts k[m..n].join\n m += l\n n += l\n end \n end",
"def blur_pixel(ones_array)\n ones_array.each do |point_array|\n # => breaks the point_array inner arrays into its two parts --\n # => wouldn't work if there was stuff in the middle\n row = point_array.first\n col = point_array.last\n # => this is where the transformation happens\n @image_array[row - 1][col] = 1\n @image_array[row][col - 1] = 1 unless col == 0\n @image_array[row + 1][col] = 1 unless row >= @num_row - 1\n @image_array[row][col + 1] = 1 unless col >= @num_col - 1 \n\n end\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def darken(options={})\n filter_options = {\n 'inputSaturation' => options[:saturation] || 0,\n 'inputBrightness' => options[:brightness] || 0,\n }\n\n darken_filter = CIFilter.color_controls(filter_options)\n output = self.apply_filter(darken_filter)\n return UIImage.imageWithCIImage(output, scale:self.scale, orientation:self.imageOrientation)\n end",
"def to_image(opts={})\n with_options opts do\n canvas = Magick::Image.new(full_width, full_height)\n bars = Magick::Draw.new\n\n x1 = margin\n y1 = margin\n\n if barcode.two_dimensional?\n encoding.each do |line|\n line.split(//).map{|c| c == '1' }.each do |bar|\n if bar\n x2 = x1+(xdim-1)\n y2 = y1+(ydim-1)\n # For single pixels use point\n if x1 == x2 && y1 == y2\n bars.point(x1,y1)\n else\n bars.rectangle(x1, y1, x2, y2)\n end\n end\n x1 += xdim\n end\n x1 = margin\n y1 += ydim\n end\n else\n booleans.each do |bar|\n if bar\n x2 = x1+(xdim-1)\n y2 = y1+(height-1)\n bars.rectangle(x1, y1, x2, y2)\n end\n x1 += xdim\n end\n end\n\n bars.draw(canvas)\n\n canvas\n end\n end",
"def generate_controls(text)\n contents_text = \"\"\n loop do\n c = text.slice!(/./m)\n case c\n when nil\n break\n #--------------------------\n # DEFAULT FEATURES\n #-----------------------\n when \"\\x01\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n @last_color = $1.to_i\n contents.font.color = text_color($1.to_i)\n \n #--------------------------\n # * NMS FEATURES!!\n #-----------------------\n when \"\\x83\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n\n new_line if (@contents_x + 24 > contents.width)\n\n # Draw ICON\n ucIcon = UCIcon.new(self, Rect.new(@contents_x, @contents_y, 24, 24), $1.to_i)\n @cControlsList.push(ucIcon)\n @contents_x += 24\n when \"\\x84\"\n text.sub!(/\\[(.*?)\\]/, \"\")\n contents.font.name = $1.to_s\n when \"\\x85\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n contents.font.size = $1.to_i\n when \"\\x86\"\n contents.font.name = Font.default_name \n when \"\\x87\"\n contents.font.size = Font.default_size\n when \"\\x88\"\n contents.font.bold = contents.font.bold == true ? false : true\n when \"\\x89\"\n contents.font.italic = contents.font.italic == true ? false : true\n when \"\\x93\"\n contents.font.shadow = contents.font.shadow == true ? false : true\n when \"\\x11\"\n text.sub!(/\\[(.*?)\\]/, \"\")\n a = $1.to_s.split(',')\n bitmap = Cache.picture(a[0])\n\n new_line if (@contents_x + bitmap.width > contents.width)\n \n # Size\n if !a[1].nil? && !a[1].empty?\n width = a[1].to_i\n else\n width = bitmap.width\n end\n if !a[2].nil? && !a[2].empty?\n height = a[2].to_i\n else\n height = bitmap.height\n end\n \n # Border\n if !a[3].nil? && !a[3].empty?\n border = a[3].to_i \n else\n border = 0\n end\n if !a[4].nil? && !a[4].empty?\n border_color = text_color(a[4].to_i)\n else\n border_color = nil\n end\n\n # Draw Image\n ucImageBorder = UCImageBorder.new(self, Rect.new(@contents_x, @contents_y, width, height),\n bitmap, Rect.new(0,0, width-border*2, height-border*2),\n 0, 255, 0, border, border_color)\n @cControlsList.push(ucImageBorder)\n \n @contents_x += width\n @biggest_text_height = height if height > @biggest_text_height\n #bitmap.dispose\n when \"\\x12\"\n text.sub!(/\\[([0-9]+)\\]/, \"\")\n\n new_line if (@contents_x + 96 > contents.width)\n\n # Draw Face\n actor = Game_Actor.new($1.to_i)\n ucCharFace = UCCharacterFace.new(self, Rect.new(@contents_x, @contents_y, 96, 96), actor)\n @cControlsList.push(ucCharFace)\n \n @biggest_text_height = 96 if 96 > @biggest_text_height\n else\n # Draw Text\n next_char = text.slice(/./m)\n contents_text += c\n if next_char == nil || next_char.match(/[\\x01-\\x12\\x80-\\xff]/) != nil\n text_height = contents.get_text_height(contents_text)\n if text_height < WLH\n text_height = WLH\n end\n @biggest_text_height = text_height if text_height > @biggest_text_height\n\n rect = Rect.new(@contents_x, @contents_y, contents.width, @biggest_text_height)\n cLabel = CLabel.new(self, rect, contents_text, 0, contents.font.clone, \n true, false, 3)\n @cControlsList.push(cLabel)\n \n lines = contents.split_multiline(rect, contents_text, 3)\n if lines.size > 1\n text_height = contents.get_text_height(contents_text)\n if text_height < WLH\n text_height = WLH\n end\n text_height = @biggest_text_height + text_height * (lines.size-2)\n @biggest_text_height = text_height if text_height > @biggest_text_height\n new_line\n end\n\n contents_text = \"\"\n @contents_x += contents.get_text_width(lines[lines.size-1])\n end\n \n end\n end\n\n end",
"def image_processing\n \tpixel_array_img1 = read_file_image(\"book4_no_table.jpg\")\n \tpixel_array_img2 = read_file_image(\"net_book5.jpg\")\n\n\n \tpixel_array_sq_img1 = []\n \tpixel_array_sq_img2 = []\n \tpixel_array_img1x2 = []\n \t##################FALTA AQUI ALGO\n\n \t###### ARRAY OF PIXEL ARRAY\n \t# SQUARE IMAGE IMG_1\n \tpixel_array_sq_img1 = square_array(pixel_array_img1)\t\t\n\t\tpixel_array_sq_img2 = square_array(pixel_array_img2)\n \tpixel_array_img1x2 = product_array(pixel_array_img1,pixel_array_img2)\n\n\t\t# Apply convolve filter two image array\n\t\timg_1_convolve_filter = convolve(pixel_array_img1,@gaussian_kernel)\n\t\timg_2_convolve_filter = convolve(pixel_array_img2,@gaussian_kernel)\n\n\t\t## Array Square\n\t\timg_1_convolve_filter_sq = square_array(img_1_convolve_filter)\n\t\timg_2_convolve_filter_sq = square_array(img_2_convolve_filter)\n\t\timg_2x1_convolve_filter = product_array(img_1_convolve_filter,img_2_convolve_filter)\n\n\t\t#Convolve FILTER Square IMG1 and IMG2\n\t\timg_1_sq_convolve_filter = convolve(pixel_array_sq_img1,@gaussian_kernel)\n\t\timg_2_sq_convolve_filter = convolve(pixel_array_sq_img2,@gaussian_kernel)\n\n\t\t#Convolve FILTER to Product IMG1 and IMG2 \n\t\timg_1x2_convolve_filter = convolve(pixel_array_img1x2,@gaussian_kernel)\n\n\t\timg_1_sq_convolve_filter = difference_array(img_1_sq_convolve_filter,img_1_convolve_filter_sq)\n\t\timg_2_sq_convolve_filter = difference_array(img_2_sq_convolve_filter,img_2_convolve_filter_sq)\n\t\timg_1x2_convolve_filter = difference_array(img_1x2_convolve_filter,img_2x1_convolve_filter)\n\n\n\n\t\t#c1/c2 constants\n\t #First use: manual fitting\n\t c_1=6.5025\n\t c_2=58.5225\n\t \n\t #Second use: change k1,k2 & c1,c2 depend on L (width of color map)\n\t l=255\n\t k_1=0.01\n\t c_1=(k_1*l)**2\n\t k_2=0.03\n\t c_2=(k_2*l)**2\n\t \n\t #Numerator of SSIM\n\t num_ssim = \n\t product_array(\n\t \tmultiple_and_factor_increment(2,img_2x1_convolve_filter,c_1),\n\t \tmultiple_and_factor_increment(2,img_1x2_convolve_filter,c_2))\n\t ##Denominator of SSIM\n\t den_ssim = product_array(sum_two_array_and_incremente(img_1_convolve_filter_sq,img_2_convolve_filter_sq,c_1),sum_two_array_and_incremente(img_1_sq_convolve_filter,img_2_sq_convolve_filter,c_2))\n\t ##SSIM\n\t index = division_and_average(num_ssim,den_ssim)\n\n\t puts index\n\n end",
"def draw_cassette_feature( image, feature, x, y, params = {} )\n width = feature.width\n height = @feature_height\n colour = feature.render_options[ \"colour\" ] || params[:colour] || \"white\"\n font = feature.render_options[ \"font\" ] || params[:font] || \"black\"\n label = params[:label] || feature.feature_name\n drawing = Magick::Draw.new\n\n # create a block\n drawing.stroke( \"black\" )\n drawing.fill( colour )\n drawing.rectangle( x, @top_margin, x + width, @image_height - @bottom_margin )\n drawing.draw( image )\n\n # annotate the block\n pointsize = @font_size\n drawing.annotate( image, width, height, x, @top_margin, label ) do\n self.fill = font\n self.font_weight = Magick::BoldWeight\n self.gravity = Magick::CenterGravity\n self.pointsize = pointsize\n end\n\n return image\n end",
"def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def traitementMonochrome()\n return @image = @image.quantize(2, GRAYColorspace)\n end",
"def _binary_mask_stuff_internal!(text)\n # Keep original size, so can check haven't resized it\n orig_size = text.size\n\n # Replace ASCII email addresses...\n text.gsub!(MySociety::Validate.email_find_regexp) do |email| \n email.gsub(/[^@.]/, 'x')\n end\n\n # And replace UCS-2 ones (for Microsoft Office documents)...\n # Find emails, by finding them in parts of text that have ASCII\n # equivalents to the UCS-2\n ascii_chars = text.gsub(/\\0/, \"\")\n emails = ascii_chars.scan(MySociety::Validate.email_find_regexp)\n # Convert back to UCS-2, making a mask at the same time\n emails.map! {|email| [\n Iconv.conv('ucs-2', 'ascii', email[0]), \n Iconv.conv('ucs-2', 'ascii', email[0].gsub(/[^@.]/, 'x'))\n ] }\n # Now search and replace the UCS-2 email with the UCS-2 mask\n for email, mask in emails\n text.gsub!(email, mask)\n end\n\n # Replace censor items\n self.info_request.apply_censor_rules_to_binary!(text)\n\n raise \"internal error in binary_mask_stuff\" if text.size != orig_size\n end",
"def blur_pixel(ones_array)\n ones_array.each do |point_array|\n # => breaks the point_array inner arrays into its two parts --\n # => wouldn't work if there was stuff in the middle\n row = point_array.first\n col = point_array.last\n # => this is where the transformation happens\n @image_array[row - 1][col] = 1\n @image_array[row][col - 1] = 1 unless col == 0\n @image_array[row + 1][col] = 1 unless row >= @num_row - 1\n @image_array[row][col + 1] = 1 unless col >= @num_col - 1 \n end\n end",
"def mark_image(image)\n images = Magick::Image.from_blob(image) # from_blob returns array of images\n image = images[0] # method is receiving just one image\n\n mark = Magick::Image.new(image.columns, image.rows)\n\n gc = Magick::Draw.new\n gc.gravity = Magick::CenterGravity\n gc.pointsize = 32\n gc.font_family = \"Arial\"\n gc.font_weight = Magick::BoldWeight\n gc.stroke = 'none'\n gc.annotate(mark, 0, 0, 0, 0, WATERMARK_STRING)\n\n mark = mark.shade(true, 310, 30)\n\n image.composite!(mark, Magick::CenterGravity, Magick::HardLightCompositeOp)\n\n image = image.to_blob\n return image\nend",
"def cleanup image\n m_begin \"cleanup\"\n img = get_image(image)\n img = img.gaussian_blur(8)\n img = img.threshold((QuantumRange * 0.999).to_int)\n img = img.gaussian_blur(14)\n img = img.threshold(0)\n m_end \"cleanup\"\n set_variable(image, img)\n end",
"def imgify(tweet)\n return tweet\nend",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def image_ocr_photo_to_text(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_to_text_with_http_info(image_file, opts)\n data\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def generate\n MiniMagick::Tool::Convert.new do |i|\n i.font random_font\n i.size image_size\n i.pointsize config[:font_size]\n i.fill config[:font_color]\n i.gravity \"center\"\n i.canvas config[:background]\n i.draw \"text 0,0 '#{text}'\"\n i.noise + \"Gaussian\"\n i << \"#{config[:format]}:-\"\n end\n end",
"def image_ocr_photo_recognize_business_card_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_recognize_business_card ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_recognize_business_card\"\n end\n # resource path\n local_var_path = '/ocr/photo/recognize/business-card'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'BusinessCardRecognitionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_recognize_business_card\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def createAscii(options = {})\n if @status == true\n options = {\"width\" => 90, \"color\" => true}.merge(options)\n\t img = Magick::Image.from_blob(@data).first\n\t width = options[\"width\"]\n\t scale = (width.to_f / img.columns)\n\t \n\t height = ((img.rows * scale) / 2).to_i\n\t # puts height\n\t if height >= 100\n\t \theight = 80\n\t end\n\n\t border = \"+#{'-' * width}+\\n\"\n\t output = border.dup\n\n\t img.resize!(width, height)\n\t color_image = img.dup if options[\"color\"]\n\t img = img.quantize(@image_chars.length, Magick::GRAYColorspace).normalize\n\t quantum_calc = Magick::QuantumRange / (@image_chars.length - 1)\n\n\t \n\t img.view(0, 0, width, height) do |view|\n\t \n\t height.times do |i|\n\t \n\t output << '|'\n\t width.times do |j|\n\n\t character = @image_chars[view[i][j].red/quantum_calc] \n\n\t if options[\"color\"]\n\t pix = color_image.pixel_color(j,i)\n\t character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))\n\t end\n\n\t output << character\n\t end\n\n\t output << \"|\\n\"\n\t end\n\t end\n\n\n\t output << border\n\t return output\n end\n end",
"def apply(template_image)\n self.scale\n\n image = Magick::ImageList.new(self.artwork.image.path)\n\n image[0].rotate!(rotation) unless rotation.nil?\n image.resize!(self.width, self.height)\n\n center_x = template_image.columns / 2\n crop_image!(image, center_x)\n\n self.image_x += template_image.columns / 2 if self.leg == 'right'\n\n # x_copies = (image[0].columns / template[0].columns).ceil\n # y_copies = (image[0].rows / template[0].rows).ceil\n\n # To be tiling, see http://www.imagemagick.org/RMagick/doc/ilist.html#mosaic\n # tiled = Magick::ImageList.new\n # page = Magick::Rectangle.new(0,0,0,0)\n # x_copies.times do |x|\n # y_copies.times do |y|\n\n # end\n # end\n\n design_image = template_image[0].composite(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n\n if mirror\n design_image.flop!\n design_image.composite!(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n design_image.flop!\n end\n\n intermediate_location = \"#{Dir.tmpdir}/#{SecureRandom.hex}.png\"\n design_image.write(intermediate_location)\n intermediate_location\n end",
"def show\n @samples = ImageReaderService.new(@image).analyze.generate_samples 4\n end",
"def create\n @bwimage = Bwimage.new(params[:bwimage])\n\n respond_to do |format|\n if @bwimage.save\n format.html { redirect_to @bwimage, notice: 'Bwimage was successfully created.' }\n format.json { render json: @bwimage, status: :created, location: @bwimage }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bwimage.errors, status: :unprocessable_entity }\n end\n end\n end",
"def apply_filter(filter)\n filter.setValue(self.ciimage, forKey: 'inputImage')\n return filter.valueForKey('outputImage')\n end",
"def Process(text)\n text.to_str.gsub(/:\\(?([a-z0-9\\+\\-_]+)\\)?:/) do |match|\n\t \n # checks, if user wanted an animated smiley or not\n animated = false\n if (match.include?('(') && match.include?(')'))\n animated = true\n end\n\n # proposed image path, if image is locally available\n\tif animated\n local_image = File.join(Dir.pwd, 'public', 'smileys', 'animated', $1 + '.gif')\n else\n local_image = File.join(Dir.pwd, 'public', 'smileys', 'general', $1 + '.png')\n end\n\n # returns image tag, if image locally exists\n if File.exist?(local_image)\n ImageTag($1, animated)\n\n # image doesn't exists locally\n else\n # stores the image and returns image tag, if smiley is valid\n if SmileyExist($1, animated)\n ImageStore($1, animated)\n ImageTag($1, animated)\n else\n if animated\n '('+$1+')'\n else\n ':'+$1+':'\n end\n end\n end\n\n end\n end",
"def create\n @txt = Txt.new(params[:txt])\n\n \n respond_to do |format|\n if @txt.save\n \n # long text parser \n $KCODE='utf8'\n require 'jcode'\n d_str =''\n @txt.longtext.each {|s_str| \n while s_str.jsize > NUM_WORD_PER_LINE\n tmp_str = s_str.scan(/./)[0,NUM_WORD_PER_LINE].join\n d_str += tmp_str + \"\\n\\n\"\n s_str = s_str[tmp_str.size,s_str.size-tmp_str.size]\n if s_str == nil then break end\n #puts s_str.jsize \n end\n if s_str!=nil then d_str += s_str end\n d_str += \"\\n\"\n }\n \n #--- path and name. to be config/updated in new environments\n font_path = 'D:\\\\fonts'\n images_path = \"public/images\"\n output_path = 'public/images/outputs'\n bg_image_path = images_path + \"/\"+ \"background.png\"\n\n require 'find'\n # do the same thing for each available fonts\n Find.find(font_path) do |f|\n img = Magick::Image.read(bg_image_path).first #图片路径\n src_img = Magick::Image.read(images_path+'/user_image.JPG').first # to be replaced with user's picture url\n src_img.crop_resized!(320,320) # 照片的目标尺寸\n src_img.border!(10, 10, \"#f0f0ff\") #相框的颜色,宽度\n frame_img = Magick::Image.read(images_path+'/frame.png').first # picture frame\n frame_img.composite!(src_img, 0, 0, Magick::OverCompositeOp)\n img.composite!(frame_img, 20, 20, Magick::OverCompositeOp)\n \n gc= Magick::Draw.new\n gc.annotate(img, 0, 0, 420, 50, d_str) do #可以设置文字的位置,参数分别为路径、宽度、高度、横坐标、纵坐标\n #self.gravity = Magick::CenterGravity\n self.font = f\n self.pointsize = FONT_SIZE #字体的大小\n self.fill = '#fff' #字体的颜色\n self.stroke = \"none\"\n end \n font_file_name = File.basename(f, 'ttf')\n file_path = output_path + \"/\"+ @txt.image_url + \"_\" + font_file_name + \"png\" \n img.write(file_path) \n end\n \n #@path = file_name\n format.html { redirect_to(@txt, :notice => 'Txt was successfully created.') }\n format.xml { render :xml => @txt, :status => :created, :location => @txt }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @txt.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def monochrome! \n\t\treturn @image = @image.quantize(2, Magick::GRAYColorspace) \n\tend"
] |
[
"0.59265715",
"0.5771552",
"0.5659796",
"0.5642477",
"0.5538126",
"0.55338806",
"0.55168307",
"0.54437375",
"0.5421915",
"0.5322964",
"0.52762336",
"0.52564114",
"0.5248734",
"0.5228602",
"0.52128536",
"0.5208213",
"0.51808894",
"0.51410204",
"0.5101911",
"0.5099944",
"0.5076722",
"0.5058766",
"0.50394243",
"0.5003354",
"0.49481237",
"0.4940903",
"0.4940089",
"0.49277166",
"0.49008173",
"0.48948213",
"0.4892325",
"0.48720127",
"0.48711926",
"0.4840204",
"0.48094133",
"0.48029554",
"0.4784463",
"0.47808626",
"0.4760034",
"0.47452533",
"0.4744875",
"0.47442725",
"0.47406083",
"0.47363392",
"0.47357586",
"0.4733099",
"0.47294313",
"0.47233865",
"0.47231218",
"0.4720728",
"0.46818963",
"0.4675555",
"0.46727842",
"0.46633685",
"0.4655672",
"0.46466127",
"0.46397018",
"0.46376127",
"0.46125075",
"0.46070468",
"0.45916212",
"0.45703086",
"0.45671895",
"0.45553228",
"0.45471406",
"0.45437238",
"0.45289063",
"0.4528574",
"0.45245248",
"0.45141664",
"0.4509504",
"0.45084694",
"0.45033348",
"0.4502283",
"0.4494688",
"0.4486566",
"0.44859433",
"0.44845426",
"0.44803208",
"0.44784695",
"0.44775808",
"0.44761094",
"0.4475676",
"0.4462636",
"0.44590858",
"0.44507784",
"0.4450575",
"0.4429928",
"0.4426006",
"0.44248182",
"0.44082874",
"0.44063094",
"0.4403755",
"0.43983287",
"0.43974805",
"0.43956494",
"0.43940526",
"0.43901893",
"0.43863055",
"0.43713316"
] |
0.52756774
|
11
|
Convert an image of text into a binary (light and dark) view with ML Perform an advanced adaptive, Deep Learningbased binarization algorithm on the input image to prepare it for further OCR operations. Provides enhanced accuracy than adaptive binarization. Image will be upsampled to 300 DPI if it has a DPI below 300.
|
def preprocessing_binarize_advanced(image_file, opts = {})
data, _status_code, _headers = preprocessing_binarize_advanced_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize(image)\n # quantize to two-color\n image = quantize_image(image)\n\n # the binary string we expect to see from the output nodes\n assign_inputs image\n\n calculate_hidden_outputs\n calculate_final_outputs\n\n #@output_values.each.with_index { |v, i| puts \"index: #{i} => #{v}\" }\n\n # process results\n #\n binary_string = quantized_result.inject(\"\") { |accum, bit| \"#{accum}#{bit.to_s}\" }\n binary_string.to_i(2)\n end",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def enhance_image(image)\n colors = image.get_pixels.flatten\n colors.map! { |color| color**2 / 255 }\n blob = colors.pack('C*') # Recreate the original image, credit to stackoverflow.com/questions/53764046\n image = MiniMagick::Image.import_pixels(blob, image.width, image.height, 8, 'rgb')\n image.statistic('mean', '6x6')\n image.threshold(threshold_percent)\n image.statistic('median', '9x9') # Replace with object discard below set size\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def train(image, target_char)\n # quantize to two-color\n image = quantize_image(image)\n #image.write(filename_for_quantized_image(target_char, 'gif'))\n\n # the binary string we expect to see from the output nodes\n @target_binary_string = char_to_binary_string(target_char)\n\n # feed the image data forward through the network to obtain a result\n #\n assign_inputs image\n calculate_hidden_outputs\n calculate_final_outputs\n\n # propagate the error correction backward through the net\n #\n calculate_output_errors\n calculate_hidden_errors\n adjust_output_weights\n adjust_input_weights\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def analyze_ballot_image filename, dpi, result, upstream\n reset_analyzer filename, dpi, result, upstream\n open_ballot_image :ballot, filename, dpi\n locate_ballot\n sanity_check_ballot_coords\n analyze_vote_ovals\n analyze_barcode\n sanity_check\n compile_results result\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def preprocess_image(path)\n MiniMagick::Tool::Convert.new.yield_self do |convert|\n convert << path\n\n if config.localization_preprocessing != :none\n # general preprocessing\n convert.colorspace \"Gray\"\n convert.normalize\n\n if config.localization_preprocessing == :full\n # try to reduce shadows (based on https://legacy.imagemagick.org/Usage/compose/#divide)\n convert.stack do |stack|\n convert.clone 0\n convert.sample \"25%\"\n convert.blur \"30x10\"\n convert.resize \"400%\"\n end\n convert.compose \"DivideSrc\"\n convert.composite\n\n # remove short vertical features\n convert.morphology \"Close\", \"3x6: 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1\"\n # remove small features and flaws\n convert.morphology \"Close:3\", \"Square:1\"\n end\n\n convert.threshold \"50%\"\n end\n\n convert.depth 8\n convert << \"gray:-\"\n\n MiniMagick::Shell.new.run(convert.command)\n end.first\n end",
"def apply_label(text, image)\n image.composite(build_label(text),\n Magick::CenterGravity,\n Magick::HardLightCompositeOp)\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def text_color_for_image(image)\n dominant = dominant_color(image)\n brightness = brightness(dominant)\n # Por ahora sólo devolvemos blanco o negro.\n # Si lo vemos muy feo, pensar una solución\n # más inteligente.\n if brightness < 255 / 2\n \"#fff\"\n else\n \"#000\"\n end\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def recognize_detect_text_large_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_large ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_large\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/large'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'TextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_large\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def text(section_type: :default)\n img = @image \n \n # resample if an image 4\"x4\" is less than 300dpi \n if img.columns * img.rows < 144000\n img = img.resample(300)\n end\n \n params = SECTION_PARAMS[:default].merge(SECTION_PARAMS[section_type])\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n\n if @text == \"\"\n img = img.white_threshold(245)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n if @text == \"\"\n img = img.quantize(256,Magick::GRAYColorspace)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n @text\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def recognize_detect_text_fine(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_fine_with_http_info(image_file, opts)\n data\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def classify_image\n\n\t\trequire 'rubygems'\n\t\trequire 'RMagick'\n\t\trequire \"open-uri\"\n\n\t\timagelist = Magick::ImageList.new # not sure why using ImageList and not an Image, but thats the example. can try rewrite \n\t\turlimage = open(params[:url]) # Image URL \n\t\timagelist.from_blob(urlimage.read)\n\t\timage = imagelist.cur_image\n\n\tputs \"image opened, color coding\"\n\n\t\tcolorcodes = {\n\t\t\t:red => [255,0,0],\n\t\t\t:green => [0,255,0],\n\t\t\t:blue => [0,0,255],\n\t\t\t:yellow => [255,255,0],\n\t\t}\n\t\t@colors = {}\n\t\t@classmodel = ClassModel.find params[:classmodel]\n\t\tclassnames = @classmodel.classnames.split(',') # user-supplied classes; \n\t\tclassnames.each_with_index do |classname,index|\n\t\t\t@colors[classname] = colorcodes.to_a[index]\n\t\tend\n\n\tputs \"assembling classes\"\n\n\t\tclasses = ClassModel.find(params[:classmodel]).to_hash\n\n\tputs \"parsing pixels and writing new pixels\"\n\n\t\t@percentages = {}\n\t\tclasses.each do |classname,classbands|\n\t\t\t@percentages[classname] = 0\n\t\tend\n\n\t\t# this can also surely be more efficient, look at: http://www.simplesystems.org/RMagick/doc/image2.html#import_pixels\n\t\t(0..image.columns-1).each do |x|\n\t\t\t(0..image.rows-1).each do |y|\n\t\t\t\t# classify the pixel\n\t\t\t\t# first, extract a JSON string of the colors... inefficient but a start:\n\t\t\t\ta = image.export_pixels(x, y, 1, 1, \"RGB\");\n\t\t\t\tpixel_string = {\"red\" => a[0]/255,\"green\" => a[1]/255,\"blue\" => a[2]/255} # MaxRGB is 255^2\n\t\t\t\t\t#puts pixel_string\n\t\t\t\tclosest = CartesianClassifier.closest_hash(pixel_string,classes)\n\t\t\t\t\t#puts closest\n\t\t\t\t@percentages[closest] += 1\n\t\t\t\t# match the resulting class to a color and write to a pixel\n\t\t\t\ta = colorcodes[@colors[closest][0]].map { |c| c*255 } #MaxRGB is 255^2\n\t\t\t\timage.import_pixels(x, y, 1, 1, \"RGB\", a);\n\t\t\tend\n\t\tend\n\n\t\t@percentages.each do |key,value|\n\t\t\t@percentages[key] = (100*((1.00 * value) / (image.rows*image.columns))).to_i\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\tformat.html { \n\t\t\t\t@b64 = Base64.encode64(image.to_blob)\n\t\t\t}\n\t\t\tformat.png { \n\t\t\t\theaders['Content-Type'] = 'image/png'\n\t\t\t\theaders['Cache-Control'] = 'public'\n\t\t\t\theaders['Expires'] = 'Mon, 28 Jul 2020 23:30:00 GMT'\n\t\t\t\trender :text => image.to_blob\n\t\t\t}\n\t\tend\n\tend",
"def analyze_and_return_labels_with_score\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n file_name = self.image_on_disk\n response = image_annotator.label_detection image: file_name\n return_data = Hash.new()\n response.responses.each do |res|\n res.label_annotations.each do |label|\n return_data[label.description] = label.score\n end\n end\n return_data\n end",
"def recognize_detect_text_large(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_large_with_http_info(image_file, opts)\n data\n end",
"def show\n @samples = ImageReaderService.new(@image).analyze.generate_samples 4\n end",
"def recognize_detect_text_fine_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_fine ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_fine\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/fine'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'FineTextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_fine\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def classify(text)\n classify_features(features_of(text)).last\n end",
"def display_alternative_text_image(image)\n # Interface method\n end",
"def apply_image_transformation?\n true\n end",
"def classify(text)\n result, score = classify_with_score(text)\n result = nil if score < @threshold || score == Float::INFINITY if threshold_enabled?\n result\n end",
"def process_image(image_path, output_directory)\n parts = image_path.split(\"/\")\n filename = parts[parts.length - 1]\n image_small_path = output_directory + lowercase_filetype(filename)\n ratio = 0.125\n ratio = 0.071\n command = \"CoreImageTool load my_image #{image_path} \\\n filter my_image CILanczosScaleTransform scale=#{ratio} \\\n store my_image #{image_small_path} public.jpeg\"\n puts \"processing #{image_path} #{image_small_path}\"\n system(command) \n end",
"def preprocessing_binarize_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def classify(text)\n choose classifications(text)\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def image_ocr_post_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_post ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_post\"\n end\n # resource path\n local_var_path = '/ocr/image/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n header_params[:'preprocessing'] = opts[:'preprocessing'] if !opts[:'preprocessing'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_image_grey_scale\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_grey_scale = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_grey_scale\n end",
"def image_ocr_photo_to_text_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_to_text ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_to_text\"\n end\n # resource path\n local_var_path = '/ocr/photo/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_to_text\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end",
"def break_text_with_image(width, textarray, draw)\n tokens = textarray.flat_map{ |x| x.respond_to?(:split) ? x.split(/ /) : x }\n tokens = tokens.flat_map{ |x| x.respond_to?(:split) ? x.split(/(?<=\\n)/) : x }\n\n result = []\n line = []\n linelength = 0\n\n tokens.each_with_index do |item, i|\n itemlength = item.class == Image ?\n item.columns : draw.get_type_metrics(item + ' ').width\n\n if (line.empty?)\n line << item\n else\n if (width != 0 && itemlength + linelength > width)\n result << line\n line = [item]\n linelength = 0\n else\n t = line.pop\n\n if (t.class != Image)\n t += ' '\n elsif (item.class != Image)\n item = ' ' + item\n end\n\n if (t.class == Image or item.class == Image)\n line << t << item\n else\n line << t + item\n end\n end\n end\n\n if (item.class != Image and item.include?(\"\\n\"))\n line[0].sub!(\"\\n\", '')\n result << line\n line = []\n linelength = 0\n next\n end\n\n linelength += itemlength\n end\n\n unless (line.empty?)\n result << line\n end\n\n return result\n end",
"def preprocessing_binarize_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def generate\n MiniMagick::Tool::Convert.new do |i|\n i.font random_font\n i.size image_size\n i.pointsize config[:font_size]\n i.fill config[:font_color]\n i.gravity \"center\"\n i.canvas config[:background]\n i.draw \"text 0,0 '#{text}'\"\n i.noise + \"Gaussian\"\n i << \"#{config[:format]}:-\"\n end\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def convert_standalone_image(el, _opts, img); end",
"def imagemagick?; end",
"def design2image\n\n bkgImg = Image.read(\"#{Rails.root}/public/#{params[:bkg]}\").first\n\n sideTop = 36\n sideLeft = 95\n sideWidth = 216\n sideHeight = 353\n\n side = params[:side]\n if side == 'SLEEVE'\n sideWidth = 162\n sideHeight = 250\n end\n #ART Processing\n arts = params[:art];\n art_tops = params[:art_top];\n art_lefts = params[:art_left];\n \n \n #Image.new(columns, rows) ~ (width, height)\n containSide = Magick::Image.new(sideWidth, sideHeight) do\n self.background_color = 'none'\n end\n\n i=0\n if arts\n clipArt = Image.read(\"#{Rails.root}/public/#{arts[0]}\").first\n clipArtTop = art_tops[i].to_i if art_tops[i]\n clipArtLeft = art_lefts[i].to_i if art_lefts[i]\n containSide = containSide.composite(clipArt, clipArtLeft, clipArtTop, OverCompositeOp)\n end\n\n #TEXT Processing\n texts = params[:text];\n text_tops = params[:text_top];\n text_lefts = params[:text_left];\n\n\n if texts\n textArtTop = text_tops[i].to_i if text_tops[i]\n textArtLeft = text_lefts[i].to_i if text_lefts[i]\n gc = Magick::Draw.new\n textArt = Magick::Image.new(300, 200) do\n self.background_color = 'none'\n end\n gc.annotate(textArt, 0, 0, 0, 0, texts[i]) do\n self.gravity = Magick::NorthWestGravity\n self.pointsize = 22\n self.font_family = \"Times\"\n self.fill = '#0000A9'\n self.stroke = \"none\"\n end\n end\n\n containSide.composite!(textArt, textArtLeft || 0, textArtTop || 0, OverCompositeOp) if textArt\n \n bkgImg.composite!(containSide, sideLeft, sideTop, OverCompositeOp)\n bkgImg.scale!(0.5)\n\n send_data bkgImg.to_blob, :disposition => 'inline', :type => 'image/png'\n\n# output = get_working_image(@session_id)\n# unless File.exist?(output)\n# FileUtils.cp(\"#{RAILS_ROOT}/public/images/#{params[:textart]}.png\", output)\n# img = Image.read(output).first\n# img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n# img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n# img.background_color = \"none\"\n# img = img.rotate(params[:r].to_f) unless params[:r].blank?\n# img.write(output)\n# end\n# img = Image.read(output).first\n# send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n\n end",
"def scanned_image\n scanned_eligibility\n end",
"def generate(options = {})\n options.reverse_merge!(\n :fontsize => 25,\n :padding => 20,\n :color => '#000',\n :background => '#fff',\n :fontweight => 'bold',\n :rotate => true,\n :font => config['font']\n ).symbolize_keys!\n\n options[:fontweight] = case options[:fontweight]\n when 'bold' then 700\n else 400\n end\n \n text = Magick::Draw.new\n text.pointsize = options[:fontsize]\n text.font_weight = options[:fontweight]\n text.fill = options[:color]\n text.gravity = Magick::CenterGravity\n text.font = options[:font] if options[:font]\n \n #rotate text 5 degrees left or right\n text.rotation = (rand(2)==1 ? 5 : -5) if options[:rotate]\n \n metric = text.get_type_metrics(self.string)\n\n #add bg\n canvas = Magick::ImageList.new\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = options[:background]\n }\n\n #add text\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = 'transparent'\n }.annotate(text, 0, 0, 0, 0, self.string).wave(1, 50)\n\n #add noise\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n p = Magick::Pixel.from_color(options[:background])\n p.opacity = Magick::MaxRGB/2\n self.background_color = p\n }.add_noise(Magick::LaplacianNoise)\n\n self.image = canvas.flatten_images.blur_image(1)\n end",
"def build_label(text)\n shading = false\n\n label = Magick::Image.new(@options[:width], @options[:height])\n image = Magick::Draw.new\n image.gravity = Magick::CenterGravity\n image.pointsize = @options[:width] / 4\n image.font = 'Helvetica'\n image.font_weight = Magick::NormalWeight\n image.stroke = 'none'\n image.annotate(label, 0, 0, 0, 0, text)\n label = label.shade(shading, 310, 30)\n\n return label\n end",
"def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end",
"def output_image\n @image_blur_array.each do |row|\n puts row.join\n end\n end",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def test_png_text_metadata\n\n keywords = [\"Title\", \"Author\", \"Copyright\", \"Description\", \"Software\", \"Disclaimer\"]\n\n each_file_with_updated_info do\n |file_path|\n\n #Valid png with text metadata\n if @test_feature == \"c\" && @parameter[0] == \"t\"\n\n img = Imgrb::Image.new(file_path, :only_metadata)\n\n text_type = @parameter[1]\n if text_type == \"0\"\n assert img.texts.empty?, \"Image does not contain text metadata, but img.texts is not empty!\"\n elsif text_type == \"1\" || text_type == \"z\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert keywords.include? txt.keyword\n assert txt.text.length > 0\n end\n #img.texts.each{|txt| txt.report}\n elsif text_type == \"e\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"en\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert_equal txt.translated_keyword, txt.keyword\n assert txt.text.length > 0\n end\n elsif text_type == \"f\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"fi\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"g\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"el\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"h\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"hi\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"j\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"ja\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n end\n end\n end\n\n end",
"def img!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 21 )\n\n type = IMG\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 348:7: 'img'\n match( \"img\" )\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__, 21 )\n\n end",
"def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end",
"def classify(text)\n rating = @classifiers[@mailbox].rate text\n rating > @threshold\n end",
"def image\n image = Weatherman::Image.new(attribute('image'))\n do_convertions(image, [:width, :to_i], [:height, :to_i], :title, :link, :url)\n end",
"def convert\n @value = \"\"\n @areas.each do |area|\n image = RTesseract.new(@source.to_s,@options)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:width].to_i, area[:height].to_i)\n @value << image.to_s\n end\n rescue\n raise RTesseract::ConversionError\n end",
"def detect_labels path_to_image_file:\n# [START detect_labels]\n # [START importing_libraries]\n require \"google/cloud/vision\"\n # [END importing_libraries]\n\n # [START create_vision_client]\n vision = Google::Cloud::Vision.new\n # [END create_vision_client]\n\n # [START annotate_image]\n image = vision.image path_to_image_file\n annotation = vision.annotate image, labels: true\n labels = annotation.labels\n # [END annotate_image]\n\n # [START print_labels]\n puts \"Image labels:\"\n labels.each do |label|\n puts label.description\n end\n # [END print_labels]\n# [END detect_labels]\nend",
"def darken(options={})\n filter_name = 'CIColorControls'\n filter_options = {\n inputBrightness: options[:brightness] || -0.5,\n inputSaturation: options[:saturation] || -0.2,\n }\n\n cg_input_image = CIImage.alloc.initWithImage(self)\n darken_filter = CIFilter.filterWithName(filter_name)\n raise Exception.new(\"Filter not found: #{filter_name}\") unless darken_filter\n\n darken_filter.setDefaults\n darken_filter.setValue(cg_input_image, forKey:'inputImage')\n filter_options.each_pair do |key, value|\n darken_filter.setValue(value, forKey:key)\n end\n output = darken_filter.valueForKey('outputImage')\n\n context = CIContext.contextWithOptions(nil)\n cg_output_image = context.createCGImage(output, fromRect:output.extent)\n output_image = UIImage.imageWithCGImage(cg_output_image)\n\n return output_image\n end",
"def create_advanced\n image_service = ImageGeneratingService.new(self, 'Advanced.jpg', 'image/jpeg', 69)\n output_path = image_service.generate\n original_size_mb = File.size(output_path).to_f / 2**20\n if original_size_mb > 1.0\n image_service.generate_resized(1200)\n end\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def monochrome! \n\t\treturn @image = @image.quantize(2, Magick::GRAYColorspace) \n\tend",
"def blur_image\r\n\r\n#define new image array with identical length to old array\r\n image1 = Array.new(@image.length){\r\n Array.new(@image[0].length){}}\r\n\r\n#start indexing through each cell and define values for rows and columns\r\n @image.each_with_index { |val, rowindex|\r\n val.each_with_index {|val1, colindex| \r\n\r\n#hardcoding 'nil' index values into zeroes \r\n if image1 [rowindex][colindex] != 1 \r\n then image1 [rowindex][colindex] = 0 \r\n end\r\n\r\n#if currently indexed cell has a value of 1 in original array, cell value in new array will be 1\r\n if val1 > 0 \r\n then image1 [rowindex][colindex] = 1\r\n\r\n#define value of cell directly below currently indexed cell as 1, unless it is the last cell in a column.\r\n if colindex != val.length-1\r\n then image1 [rowindex][colindex +1] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define value of cell directly above it as 1.\r\n if colindex != 0 then\r\n image1 [rowindex][colindex -1] = 1\r\n end\r\n\r\n#define value of the cell to the RIGHT of the currently indexed cell as 1, unless it is the last cell in a row.\r\n if rowindex != @image.length-1 then\r\n image1 [rowindex +1][colindex] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define the value of the cell to the LEFT of it as 1.\r\n if rowindex != 0 then\r\n image1 [rowindex -1][colindex] = 1\r\n end\r\n\r\n end\r\n\r\n }} \r\n\r\n#show blurred image array\r\n image1.each do |cell|\r\n puts cell.join\r\n end\r\n end",
"def preprocessing_binarize(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_with_http_info(image_file, opts)\n data\n end",
"def create\n @text2_image = Text2Image.new(params[:text2_image])\n \n @text2_image.create_image(params[:text2_image][:text])\n\n respond_to do |format|\n if @text2_image.save\n\n format.html { redirect_to @text2_image, notice: 'Text2 image was successfully created.' }\n format.json { render json: @text2_image, status: :created, location: @text2_image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @text2_image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def classify(text)\n positive_value = 1\n neutral_value = 1\n negative_value = 1\n\n word = text.split(/\\W+/)\n word = word.drop(1) if word.first == ''\n word.each_with_index { |_, i|\n find_instances(word[i])\n positive_value *= ((((positive_polarity.to_f/positive_population.to_f).to_f) * ((positive_polarity).to_f))/word_pop)\n negative_value *= ((((negative_polarity.to_f/negative_population.to_f).to_f) * ((negative_polarity).to_f))/word_pop)\n neutral_value *= ((((neutral_polarity.to_f/neutral_population.to_f).to_f) * ((neutral_polarity).to_f))/word_pop)\n }\n total_counter(negative_value, neutral_value, positive_value)\n\n rescue => error\n puts error.backtrace\n\n end",
"def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend",
"def run\n outputs = nil\n \n in_tmp_dir do\n image = tmp_path 'text_to_image.jpg'\n Image::Editing::Cmd::TextToImage.new(text, image, @options).run!\n\n outputs = ImageToVideo.new(image, @output_without_extension, duration, @log_folder).run\n end\n\n outputs\n end",
"def mark_image(image)\n images = Magick::Image.from_blob(image) # from_blob returns array of images\n image = images[0] # method is receiving just one image\n\n mark = Magick::Image.new(image.columns, image.rows)\n\n gc = Magick::Draw.new\n gc.gravity = Magick::CenterGravity\n gc.pointsize = 32\n gc.font_family = \"Arial\"\n gc.font_weight = Magick::BoldWeight\n gc.stroke = 'none'\n gc.annotate(mark, 0, 0, 0, 0, WATERMARK_STRING)\n\n mark = mark.shade(true, 310, 30)\n\n image.composite!(mark, Magick::CenterGravity, Magick::HardLightCompositeOp)\n\n image = image.to_blob\n return image\nend",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def update\n respond_to do |format|\n if @image.update(image_params)\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully updated.' }\n format.json { render :show, status: :ok, location: @image }\n else\n format.html { render :edit }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @txt = Txt.new(params[:txt])\n\n \n respond_to do |format|\n if @txt.save\n \n # long text parser \n $KCODE='utf8'\n require 'jcode'\n d_str =''\n @txt.longtext.each {|s_str| \n while s_str.jsize > NUM_WORD_PER_LINE\n tmp_str = s_str.scan(/./)[0,NUM_WORD_PER_LINE].join\n d_str += tmp_str + \"\\n\\n\"\n s_str = s_str[tmp_str.size,s_str.size-tmp_str.size]\n if s_str == nil then break end\n #puts s_str.jsize \n end\n if s_str!=nil then d_str += s_str end\n d_str += \"\\n\"\n }\n \n #--- path and name. to be config/updated in new environments\n font_path = 'D:\\\\fonts'\n images_path = \"public/images\"\n output_path = 'public/images/outputs'\n bg_image_path = images_path + \"/\"+ \"background.png\"\n\n require 'find'\n # do the same thing for each available fonts\n Find.find(font_path) do |f|\n img = Magick::Image.read(bg_image_path).first #图片路径\n src_img = Magick::Image.read(images_path+'/user_image.JPG').first # to be replaced with user's picture url\n src_img.crop_resized!(320,320) # 照片的目标尺寸\n src_img.border!(10, 10, \"#f0f0ff\") #相框的颜色,宽度\n frame_img = Magick::Image.read(images_path+'/frame.png').first # picture frame\n frame_img.composite!(src_img, 0, 0, Magick::OverCompositeOp)\n img.composite!(frame_img, 20, 20, Magick::OverCompositeOp)\n \n gc= Magick::Draw.new\n gc.annotate(img, 0, 0, 420, 50, d_str) do #可以设置文字的位置,参数分别为路径、宽度、高度、横坐标、纵坐标\n #self.gravity = Magick::CenterGravity\n self.font = f\n self.pointsize = FONT_SIZE #字体的大小\n self.fill = '#fff' #字体的颜色\n self.stroke = \"none\"\n end \n font_file_name = File.basename(f, 'ttf')\n file_path = output_path + \"/\"+ @txt.image_url + \"_\" + font_file_name + \"png\" \n img.write(file_path) \n end\n \n #@path = file_name\n format.html { redirect_to(@txt, :notice => 'Txt was successfully created.') }\n format.xml { render :xml => @txt, :status => :created, :location => @txt }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @txt.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def train_pixel\n\t\tif CartesianClassifier.train(params[:classname],params[:bands],params[:author])\n\t\t\trender :text => \"trained as '\"+params[:classname]+\"', you happy now?\", :layout => false\n\t\telse\n\t\t\trender :text => \"failed to train\", :layout => false\n\t\tend\n\tend",
"def binarize id\n m_begin \"binarize\"\n put_image(id, get_image(id).bilevel_channel(QuantumRange/2))\n# put_image(id, @var_table[id].quantize(2, GRAYColorspace, NoDitherMethod) )\n m_end \"binarize\"\n end",
"def imagemagick7?; end",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def traitementMonochrome()\n return @image = @image.quantize(2, GRAYColorspace)\n end",
"def grayscale\n with_command \"-type Grayscale\"\n end",
"def toaster_filter\n manipulate! do |img|\n img.modulate '150,80,100'\n img.gamma 1.1\n img.contrast\n img.contrast\n img.contrast\n img.contrast\n img = yield(img) if block_given?\n img\n end\n end",
"def darken(options={})\n filter_options = {\n 'inputSaturation' => options[:saturation] || 0,\n 'inputBrightness' => options[:brightness] || 0,\n }\n\n darken_filter = CIFilter.color_controls(filter_options)\n output = self.apply_filter(darken_filter)\n return UIImage.imageWithCIImage(output, scale:self.scale, orientation:self.imageOrientation)\n end",
"def convert_to_tiff_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ConvertApi.convert_to_tiff ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ConvertApi.convert_to_tiff\"\n end\n # resource path\n local_var_path = '/image/convert/to/tiff'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ConvertApi#convert_to_tiff\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def createAscii(options = {})\n if @status == true\n options = {\"width\" => 90, \"color\" => true}.merge(options)\n\t img = Magick::Image.from_blob(@data).first\n\t width = options[\"width\"]\n\t scale = (width.to_f / img.columns)\n\t \n\t height = ((img.rows * scale) / 2).to_i\n\t # puts height\n\t if height >= 100\n\t \theight = 80\n\t end\n\n\t border = \"+#{'-' * width}+\\n\"\n\t output = border.dup\n\n\t img.resize!(width, height)\n\t color_image = img.dup if options[\"color\"]\n\t img = img.quantize(@image_chars.length, Magick::GRAYColorspace).normalize\n\t quantum_calc = Magick::QuantumRange / (@image_chars.length - 1)\n\n\t \n\t img.view(0, 0, width, height) do |view|\n\t \n\t height.times do |i|\n\t \n\t output << '|'\n\t width.times do |j|\n\n\t character = @image_chars[view[i][j].red/quantum_calc] \n\n\t if options[\"color\"]\n\t pix = color_image.pixel_color(j,i)\n\t character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))\n\t end\n\n\t output << character\n\t end\n\n\t output << \"|\\n\"\n\t end\n\t end\n\n\n\t output << border\n\t return output\n end\n end",
"def recognize\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def image_magick(image)\n Open3.capture3(\n \"convert\", image.cached, # What to convert?\n \"-resize\", \"#{image.width}x#{image.height}^\", # resizing\n \"-gravity\", \"center\", \"-crop\", \"#{image.width}x#{image.height}+0+0\", # cropping\n \"-background\", \"#ffffff\", # background color in case image was transparent\n \"+repage\", \"-flatten\", # Discard canvas size and squash into single layer\n image.resized # Target path of output\n )\n end",
"def grayscale?(input)\n # By testing the average saturation of the image we can guess if it's\n # grayscale (then the saturation is 0)\n # Source: http://www.imagemagick.org/discourse-server/viewtopic.php?t=19580\n options = [\n input.shellescape,\n '-colorspace HSL',\n '-channel g',\n '-separate +channel',\n '-format \"%[fx:mean]\"',\n 'info:'\n ]\n raw = `convert #{options.join(' ')}`.chomp.to_f\n raw.zero?\n end",
"def greyScale? \n\t\treturn @image.grey? \n\tend",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def draw_cassette_feature( image, feature, x, y, params = {} )\n width = feature.width\n height = @feature_height\n colour = feature.render_options[ \"colour\" ] || params[:colour] || \"white\"\n font = feature.render_options[ \"font\" ] || params[:font] || \"black\"\n label = params[:label] || feature.feature_name\n drawing = Magick::Draw.new\n\n # create a block\n drawing.stroke( \"black\" )\n drawing.fill( colour )\n drawing.rectangle( x, @top_margin, x + width, @image_height - @bottom_margin )\n drawing.draw( image )\n\n # annotate the block\n pointsize = @font_size\n drawing.annotate( image, width, height, x, @top_margin, label ) do\n self.fill = font\n self.font_weight = Magick::BoldWeight\n self.gravity = Magick::CenterGravity\n self.pointsize = pointsize\n end\n\n return image\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def camaleon_image_optimizer_on_active(plugin)\n end",
"def summary_img\n num_tracks_needed = 1\n\n begin\n p = Bio::Graphics::Page.new(:width => 962, :height => 150, :number_of_intervals => 10)\n\n #separate features into mRNA or gene features\n\n genes = @features.select { |x| x.feature == 'gene' }\n if not genes.empty?\n gene_track = p.add_track(:glyph => :directed,\n :fill_color => :green_white_radial,\n :label => false\n )\n # mrna_track = p.add_track(:glyph => :transcript,\n # :exon_fill_color => :red_white_h,\n # :utr_fill_color => :blue_white_h\n # )\ngenes.each do |gene|\n feat = Bio::Graphics::MiniFeature.new(:start => gene.start,\n :end => gene.end,\n :strand => gene.strand,\n :id => gene.gff_id)\n gene_track.add(feat)\nend\nend\n\nproteins = @features.select { |x| x.feature == 'protein' }\n\nif not proteins.empty?\n protein_track = p.add_track(\n :glyph => :generic,\n :fill_color => :yellow_white_radial,\n :label => false\n )\n proteins.each do |protein|\n feat = Bio::Graphics::MiniFeature.new(:start => protein.start,\n :end => protein.end,\n :id => protein.gff_id\n )\n protein_track.add(feat)\n end\nend\n\n\nmrnas = @features.select { |x| x.feature == 'mRNA' }\n@mrnas = mrnas\nif not mrnas.empty?\n mrna_track = p.add_track(:glyph => :transcript,\n :exon_fill_color => :red_white_h,\n :utr_fill_color => :blue_white_h,\n :label => false,\n :gap_marker => 'angled'\n )\n mrnas.each do |m|\n exons = []\n utrs = []\n m.children.each do |d|\n if d.feature == 'exon'\n exons << d.start\n exons << d.end\n end\n if d.feature == 'five_prime_UTR' or d.feature == 'three_prime_UTR'\n utrs << d.start\n utrs << d.end\n end\n exons.sort!\n utrs.sort!\n end\n @exons = exons\n @utrs = utrs\n\n if exons.empty?\n exons = [m.start, m.end]\n end\n\n if utrs.empty?\n utrs = [m.start, m.end]\n end\n feat = Bio::Graphics::MiniFeature.new(\n :start => m.start,\n :end => m.end,\n :strand => m.strand,\n :exons => exons,\n :utrs => utrs,\n :id => m.gff_id\n )\n mrna_track.add(feat)\n end\nend\n@svg = p.get_markup\nrescue\n @svg = \"\"\nend\n\nend",
"def convert!(image, format, page = nil, &block)\n with_minimagick(image) do |img|\n img.format(format.downcase, page, &block)\n end\n end",
"def image_ocr_photo_recognize_business_card(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_business_card_with_http_info(image_file, opts)\n data\n end",
"def pixelate\n\t\t\tmax_level = @post.resolution_level - 1\n\t\t\tmax_resolution = 2**max_level;\n\n\t\t\timg = Magick::ImageList.new(@post.image.path(:medium))\n\t\t\tstep = img.columns / max_resolution\n\t\t\ttemplate = Magick::Image.new(step, step)\n\t\t\tpixel_matrices = Array.new(max_level + 1)\n\n\t\t\t# Initialize 3D array: [level][row][col]\n\t\t\tfor level in 0..max_level do\n\t\t\t\tpixel_matrices[level] = level == max_level ? Array.new(2**level) { Array.new(2**level) } : nil\n\t\t\tend\n\n\t\t\tfor r in 0...max_resolution do\n\t\t\t\tfor c in 0...max_resolution do\n\t\t\t\t\t# Cut image into blocks\n\t\t\t\t\tblock = img.export_pixels_to_str( c * step, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t r * step,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t step,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t step )\n\t\t\t\t\taverage_pixel = template.import_pixels(0,0,step, step, \"RGB\", block).scale(1,1).pixel_color(0,0)\n\n\t\t\t\t\t# Translate red,green,blue value into 8-bit depth from 16-bit depth (default RMagick)\n\t\t\t\t\tpixel_matrices[max_level][r][c] = [average_pixel.red, average_pixel.green, average_pixel.blue].map! { |x| convert_16bit_to_8bit_with_damping(x) }\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# Compute the remaining levels\n\t\t\tfor level in max_level.downto(1) do\n\t\t\t\taverage = Array.new(2**(level-1)) { Array.new(2**(level-1)) { Array.new(3, 0.0) } }\n\t\t\t\tfor r in 0...2**level do\n\t\t\t\t\tfor c in 0...2**level do\n\t\t\t\t\t\taverage[r / 2][c / 2][0] += pixel_matrices[level][r][c][0] / 4\n\t\t\t\t\t\taverage[r / 2][c / 2][1] += pixel_matrices[level][r][c][1] / 4\n\t\t\t\t\t\taverage[r / 2][c / 2][2] += pixel_matrices[level][r][c][2] / 4\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tpixel_matrices[level-1] = Array.new(average)\n\t\t\tend\n\t\t\t@post.pixel_matrices = pixel_matrices\n\t\t\t@post.save\n\t\tend",
"def detect( str )\n sums = {}\n results = (num_processes.nil? or !EncodingEstimator::ParallelSupport.supported?) ?\n detect_st( str, combinations ) : detect_mt( str, combinations )\n\n results.each do |result|\n sums[result.key] = sums.fetch(result.key, 0.0) + result.score\n end\n\n range = EncodingEstimator::RangeScale.new( sums.values.min, sums.values.max )\n\n scaled_scores = {}\n sums.each do |k,s|\n scaled_scores[ k ] = range.scale s\n end\n\n EncodingEstimator::Detection.new( scaled_scores, @conversions )\n end"
] |
[
"0.625005",
"0.5837121",
"0.57955396",
"0.56946397",
"0.56144047",
"0.55855155",
"0.5580679",
"0.55004734",
"0.54777443",
"0.54315495",
"0.5407322",
"0.5384784",
"0.53844863",
"0.5331769",
"0.530962",
"0.5291183",
"0.5279446",
"0.5228138",
"0.5177895",
"0.51711464",
"0.5151197",
"0.5138676",
"0.51379323",
"0.513434",
"0.5108214",
"0.51027983",
"0.5093254",
"0.5041424",
"0.5021004",
"0.5003035",
"0.49933112",
"0.49656257",
"0.4962674",
"0.496061",
"0.4957388",
"0.49571538",
"0.494184",
"0.49406",
"0.49260032",
"0.4902417",
"0.48933604",
"0.48837888",
"0.48807585",
"0.48807386",
"0.48708618",
"0.48639563",
"0.48473966",
"0.48179474",
"0.4815732",
"0.48046064",
"0.4799247",
"0.47818545",
"0.478047",
"0.47772175",
"0.4775472",
"0.47535992",
"0.47501302",
"0.4742486",
"0.47344348",
"0.4730854",
"0.47235727",
"0.47219995",
"0.47133607",
"0.46974337",
"0.4692587",
"0.4689866",
"0.46895865",
"0.46850353",
"0.46740553",
"0.46631122",
"0.46544152",
"0.4650705",
"0.46448505",
"0.46433732",
"0.46346116",
"0.4627522",
"0.46223876",
"0.4619153",
"0.46188313",
"0.46183193",
"0.4612134",
"0.46035555",
"0.45796883",
"0.45791194",
"0.45743382",
"0.4573951",
"0.45677054",
"0.45614493",
"0.4560365",
"0.45563227",
"0.45496753",
"0.4536059",
"0.45358032",
"0.4530449",
"0.45243445",
"0.4522509",
"0.45162383",
"0.45161247",
"0.45151436",
"0.45101115"
] |
0.5202608
|
18
|
Convert an image of text into a binary (light and dark) view with ML Perform an advanced adaptive, Deep Learningbased binarization algorithm on the input image to prepare it for further OCR operations. Provides enhanced accuracy than adaptive binarization. Image will be upsampled to 300 DPI if it has a DPI below 300.
|
def preprocessing_binarize_advanced_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize_advanced ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize_advanced"
end
# resource path
local_var_path = '/ocr/preprocessing/image/binarize/advanced'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_binarize_advanced\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize(image)\n # quantize to two-color\n image = quantize_image(image)\n\n # the binary string we expect to see from the output nodes\n assign_inputs image\n\n calculate_hidden_outputs\n calculate_final_outputs\n\n #@output_values.each.with_index { |v, i| puts \"index: #{i} => #{v}\" }\n\n # process results\n #\n binary_string = quantized_result.inject(\"\") { |accum, bit| \"#{accum}#{bit.to_s}\" }\n binary_string.to_i(2)\n end",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def enhance_image(image)\n colors = image.get_pixels.flatten\n colors.map! { |color| color**2 / 255 }\n blob = colors.pack('C*') # Recreate the original image, credit to stackoverflow.com/questions/53764046\n image = MiniMagick::Image.import_pixels(blob, image.width, image.height, 8, 'rgb')\n image.statistic('mean', '6x6')\n image.threshold(threshold_percent)\n image.statistic('median', '9x9') # Replace with object discard below set size\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def train(image, target_char)\n # quantize to two-color\n image = quantize_image(image)\n #image.write(filename_for_quantized_image(target_char, 'gif'))\n\n # the binary string we expect to see from the output nodes\n @target_binary_string = char_to_binary_string(target_char)\n\n # feed the image data forward through the network to obtain a result\n #\n assign_inputs image\n calculate_hidden_outputs\n calculate_final_outputs\n\n # propagate the error correction backward through the net\n #\n calculate_output_errors\n calculate_hidden_errors\n adjust_output_weights\n adjust_input_weights\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def analyze_ballot_image filename, dpi, result, upstream\n reset_analyzer filename, dpi, result, upstream\n open_ballot_image :ballot, filename, dpi\n locate_ballot\n sanity_check_ballot_coords\n analyze_vote_ovals\n analyze_barcode\n sanity_check\n compile_results result\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def preprocess_image(path)\n MiniMagick::Tool::Convert.new.yield_self do |convert|\n convert << path\n\n if config.localization_preprocessing != :none\n # general preprocessing\n convert.colorspace \"Gray\"\n convert.normalize\n\n if config.localization_preprocessing == :full\n # try to reduce shadows (based on https://legacy.imagemagick.org/Usage/compose/#divide)\n convert.stack do |stack|\n convert.clone 0\n convert.sample \"25%\"\n convert.blur \"30x10\"\n convert.resize \"400%\"\n end\n convert.compose \"DivideSrc\"\n convert.composite\n\n # remove short vertical features\n convert.morphology \"Close\", \"3x6: 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1 1,-,1\"\n # remove small features and flaws\n convert.morphology \"Close:3\", \"Square:1\"\n end\n\n convert.threshold \"50%\"\n end\n\n convert.depth 8\n convert << \"gray:-\"\n\n MiniMagick::Shell.new.run(convert.command)\n end.first\n end",
"def apply_label(text, image)\n image.composite(build_label(text),\n Magick::CenterGravity,\n Magick::HardLightCompositeOp)\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def text_color_for_image(image)\n dominant = dominant_color(image)\n brightness = brightness(dominant)\n # Por ahora sólo devolvemos blanco o negro.\n # Si lo vemos muy feo, pensar una solución\n # más inteligente.\n if brightness < 255 / 2\n \"#fff\"\n else\n \"#000\"\n end\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def recognize_detect_text_large_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_large ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_large\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/large'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'TextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_large\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def text(section_type: :default)\n img = @image \n \n # resample if an image 4\"x4\" is less than 300dpi \n if img.columns * img.rows < 144000\n img = img.resample(300)\n end\n \n params = SECTION_PARAMS[:default].merge(SECTION_PARAMS[section_type])\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n\n if @text == \"\"\n img = img.white_threshold(245)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n if @text == \"\"\n img = img.quantize(256,Magick::GRAYColorspace)\n r = RTesseract.new(img, params) \n @text = r.to_s.strip\n end\n\n @text\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def preprocessing_binarize_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_advanced_with_http_info(image_file, opts)\n data\n end",
"def recognize_detect_text_fine(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_fine_with_http_info(image_file, opts)\n data\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def classify_image\n\n\t\trequire 'rubygems'\n\t\trequire 'RMagick'\n\t\trequire \"open-uri\"\n\n\t\timagelist = Magick::ImageList.new # not sure why using ImageList and not an Image, but thats the example. can try rewrite \n\t\turlimage = open(params[:url]) # Image URL \n\t\timagelist.from_blob(urlimage.read)\n\t\timage = imagelist.cur_image\n\n\tputs \"image opened, color coding\"\n\n\t\tcolorcodes = {\n\t\t\t:red => [255,0,0],\n\t\t\t:green => [0,255,0],\n\t\t\t:blue => [0,0,255],\n\t\t\t:yellow => [255,255,0],\n\t\t}\n\t\t@colors = {}\n\t\t@classmodel = ClassModel.find params[:classmodel]\n\t\tclassnames = @classmodel.classnames.split(',') # user-supplied classes; \n\t\tclassnames.each_with_index do |classname,index|\n\t\t\t@colors[classname] = colorcodes.to_a[index]\n\t\tend\n\n\tputs \"assembling classes\"\n\n\t\tclasses = ClassModel.find(params[:classmodel]).to_hash\n\n\tputs \"parsing pixels and writing new pixels\"\n\n\t\t@percentages = {}\n\t\tclasses.each do |classname,classbands|\n\t\t\t@percentages[classname] = 0\n\t\tend\n\n\t\t# this can also surely be more efficient, look at: http://www.simplesystems.org/RMagick/doc/image2.html#import_pixels\n\t\t(0..image.columns-1).each do |x|\n\t\t\t(0..image.rows-1).each do |y|\n\t\t\t\t# classify the pixel\n\t\t\t\t# first, extract a JSON string of the colors... inefficient but a start:\n\t\t\t\ta = image.export_pixels(x, y, 1, 1, \"RGB\");\n\t\t\t\tpixel_string = {\"red\" => a[0]/255,\"green\" => a[1]/255,\"blue\" => a[2]/255} # MaxRGB is 255^2\n\t\t\t\t\t#puts pixel_string\n\t\t\t\tclosest = CartesianClassifier.closest_hash(pixel_string,classes)\n\t\t\t\t\t#puts closest\n\t\t\t\t@percentages[closest] += 1\n\t\t\t\t# match the resulting class to a color and write to a pixel\n\t\t\t\ta = colorcodes[@colors[closest][0]].map { |c| c*255 } #MaxRGB is 255^2\n\t\t\t\timage.import_pixels(x, y, 1, 1, \"RGB\", a);\n\t\t\tend\n\t\tend\n\n\t\t@percentages.each do |key,value|\n\t\t\t@percentages[key] = (100*((1.00 * value) / (image.rows*image.columns))).to_i\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\tformat.html { \n\t\t\t\t@b64 = Base64.encode64(image.to_blob)\n\t\t\t}\n\t\t\tformat.png { \n\t\t\t\theaders['Content-Type'] = 'image/png'\n\t\t\t\theaders['Cache-Control'] = 'public'\n\t\t\t\theaders['Expires'] = 'Mon, 28 Jul 2020 23:30:00 GMT'\n\t\t\t\trender :text => image.to_blob\n\t\t\t}\n\t\tend\n\tend",
"def recognize_detect_text_large(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_text_large_with_http_info(image_file, opts)\n data\n end",
"def analyze_and_return_labels_with_score\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n file_name = self.image_on_disk\n response = image_annotator.label_detection image: file_name\n return_data = Hash.new()\n response.responses.each do |res|\n res.label_annotations.each do |label|\n return_data[label.description] = label.score\n end\n end\n return_data\n end",
"def show\n @samples = ImageReaderService.new(@image).analyze.generate_samples 4\n end",
"def recognize_detect_text_fine_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_text_fine ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_text_fine\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-text/fine'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'FineTextDetectionResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_text_fine\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def classify(text)\n classify_features(features_of(text)).last\n end",
"def display_alternative_text_image(image)\n # Interface method\n end",
"def apply_image_transformation?\n true\n end",
"def classify(text)\n result, score = classify_with_score(text)\n result = nil if score < @threshold || score == Float::INFINITY if threshold_enabled?\n result\n end",
"def process_image(image_path, output_directory)\n parts = image_path.split(\"/\")\n filename = parts[parts.length - 1]\n image_small_path = output_directory + lowercase_filetype(filename)\n ratio = 0.125\n ratio = 0.071\n command = \"CoreImageTool load my_image #{image_path} \\\n filter my_image CILanczosScaleTransform scale=#{ratio} \\\n store my_image #{image_small_path} public.jpeg\"\n puts \"processing #{image_path} #{image_small_path}\"\n system(command) \n end",
"def classify(text)\n choose classifications(text)\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def image_ocr_post_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_post ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_post\"\n end\n # resource path\n local_var_path = '/ocr/image/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n header_params[:'preprocessing'] = opts[:'preprocessing'] if !opts[:'preprocessing'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def image_ocr_photo_to_text_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ImageOcrApi.image_ocr_photo_to_text ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ImageOcrApi.image_ocr_photo_to_text\"\n end\n # resource path\n local_var_path = '/ocr/photo/toText'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'recognitionMode'] = opts[:'recognition_mode'] if !opts[:'recognition_mode'].nil?\n header_params[:'language'] = opts[:'language'] if !opts[:'language'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'ImageToTextResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ImageOcrApi#image_ocr_photo_to_text\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_image_grey_scale\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_grey_scale = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_grey_scale\n end",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end",
"def break_text_with_image(width, textarray, draw)\n tokens = textarray.flat_map{ |x| x.respond_to?(:split) ? x.split(/ /) : x }\n tokens = tokens.flat_map{ |x| x.respond_to?(:split) ? x.split(/(?<=\\n)/) : x }\n\n result = []\n line = []\n linelength = 0\n\n tokens.each_with_index do |item, i|\n itemlength = item.class == Image ?\n item.columns : draw.get_type_metrics(item + ' ').width\n\n if (line.empty?)\n line << item\n else\n if (width != 0 && itemlength + linelength > width)\n result << line\n line = [item]\n linelength = 0\n else\n t = line.pop\n\n if (t.class != Image)\n t += ' '\n elsif (item.class != Image)\n item = ' ' + item\n end\n\n if (t.class == Image or item.class == Image)\n line << t << item\n else\n line << t + item\n end\n end\n end\n\n if (item.class != Image and item.include?(\"\\n\"))\n line[0].sub!(\"\\n\", '')\n result << line\n line = []\n linelength = 0\n next\n end\n\n linelength += itemlength\n end\n\n unless (line.empty?)\n result << line\n end\n\n return result\n end",
"def preprocessing_binarize_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_binarize ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_binarize\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/binarize'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_binarize\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def generate\n MiniMagick::Tool::Convert.new do |i|\n i.font random_font\n i.size image_size\n i.pointsize config[:font_size]\n i.fill config[:font_color]\n i.gravity \"center\"\n i.canvas config[:background]\n i.draw \"text 0,0 '#{text}'\"\n i.noise + \"Gaussian\"\n i << \"#{config[:format]}:-\"\n end\n end",
"def convert_standalone_image(el, _opts, img); end",
"def imagemagick?; end",
"def design2image\n\n bkgImg = Image.read(\"#{Rails.root}/public/#{params[:bkg]}\").first\n\n sideTop = 36\n sideLeft = 95\n sideWidth = 216\n sideHeight = 353\n\n side = params[:side]\n if side == 'SLEEVE'\n sideWidth = 162\n sideHeight = 250\n end\n #ART Processing\n arts = params[:art];\n art_tops = params[:art_top];\n art_lefts = params[:art_left];\n \n \n #Image.new(columns, rows) ~ (width, height)\n containSide = Magick::Image.new(sideWidth, sideHeight) do\n self.background_color = 'none'\n end\n\n i=0\n if arts\n clipArt = Image.read(\"#{Rails.root}/public/#{arts[0]}\").first\n clipArtTop = art_tops[i].to_i if art_tops[i]\n clipArtLeft = art_lefts[i].to_i if art_lefts[i]\n containSide = containSide.composite(clipArt, clipArtLeft, clipArtTop, OverCompositeOp)\n end\n\n #TEXT Processing\n texts = params[:text];\n text_tops = params[:text_top];\n text_lefts = params[:text_left];\n\n\n if texts\n textArtTop = text_tops[i].to_i if text_tops[i]\n textArtLeft = text_lefts[i].to_i if text_lefts[i]\n gc = Magick::Draw.new\n textArt = Magick::Image.new(300, 200) do\n self.background_color = 'none'\n end\n gc.annotate(textArt, 0, 0, 0, 0, texts[i]) do\n self.gravity = Magick::NorthWestGravity\n self.pointsize = 22\n self.font_family = \"Times\"\n self.fill = '#0000A9'\n self.stroke = \"none\"\n end\n end\n\n containSide.composite!(textArt, textArtLeft || 0, textArtTop || 0, OverCompositeOp) if textArt\n \n bkgImg.composite!(containSide, sideLeft, sideTop, OverCompositeOp)\n bkgImg.scale!(0.5)\n\n send_data bkgImg.to_blob, :disposition => 'inline', :type => 'image/png'\n\n# output = get_working_image(@session_id)\n# unless File.exist?(output)\n# FileUtils.cp(\"#{RAILS_ROOT}/public/images/#{params[:textart]}.png\", output)\n# img = Image.read(output).first\n# img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n# img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n# img.background_color = \"none\"\n# img = img.rotate(params[:r].to_f) unless params[:r].blank?\n# img.write(output)\n# end\n# img = Image.read(output).first\n# send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n\n end",
"def scanned_image\n scanned_eligibility\n end",
"def generate(options = {})\n options.reverse_merge!(\n :fontsize => 25,\n :padding => 20,\n :color => '#000',\n :background => '#fff',\n :fontweight => 'bold',\n :rotate => true,\n :font => config['font']\n ).symbolize_keys!\n\n options[:fontweight] = case options[:fontweight]\n when 'bold' then 700\n else 400\n end\n \n text = Magick::Draw.new\n text.pointsize = options[:fontsize]\n text.font_weight = options[:fontweight]\n text.fill = options[:color]\n text.gravity = Magick::CenterGravity\n text.font = options[:font] if options[:font]\n \n #rotate text 5 degrees left or right\n text.rotation = (rand(2)==1 ? 5 : -5) if options[:rotate]\n \n metric = text.get_type_metrics(self.string)\n\n #add bg\n canvas = Magick::ImageList.new\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = options[:background]\n }\n\n #add text\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n self.background_color = 'transparent'\n }.annotate(text, 0, 0, 0, 0, self.string).wave(1, 50)\n\n #add noise\n canvas << Magick::Image.new(metric.width+options[:padding], metric.height+options[:padding]){\n p = Magick::Pixel.from_color(options[:background])\n p.opacity = Magick::MaxRGB/2\n self.background_color = p\n }.add_noise(Magick::LaplacianNoise)\n\n self.image = canvas.flatten_images.blur_image(1)\n end",
"def build_label(text)\n shading = false\n\n label = Magick::Image.new(@options[:width], @options[:height])\n image = Magick::Draw.new\n image.gravity = Magick::CenterGravity\n image.pointsize = @options[:width] / 4\n image.font = 'Helvetica'\n image.font_weight = Magick::NormalWeight\n image.stroke = 'none'\n image.annotate(label, 0, 0, 0, 0, text)\n label = label.shade(shading, 310, 30)\n\n return label\n end",
"def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end",
"def output_image\n @image_blur_array.each do |row|\n puts row.join\n end\n end",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def test_png_text_metadata\n\n keywords = [\"Title\", \"Author\", \"Copyright\", \"Description\", \"Software\", \"Disclaimer\"]\n\n each_file_with_updated_info do\n |file_path|\n\n #Valid png with text metadata\n if @test_feature == \"c\" && @parameter[0] == \"t\"\n\n img = Imgrb::Image.new(file_path, :only_metadata)\n\n text_type = @parameter[1]\n if text_type == \"0\"\n assert img.texts.empty?, \"Image does not contain text metadata, but img.texts is not empty!\"\n elsif text_type == \"1\" || text_type == \"z\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert keywords.include? txt.keyword\n assert txt.text.length > 0\n end\n #img.texts.each{|txt| txt.report}\n elsif text_type == \"e\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"en\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert_equal txt.translated_keyword, txt.keyword\n assert txt.text.length > 0\n end\n elsif text_type == \"f\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"fi\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"g\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"el\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"h\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"hi\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n elsif text_type == \"j\"\n assert_equal 6, img.texts.size\n img.texts.each do\n |txt|\n assert txt.international?\n assert_equal \"ja\".force_encoding(\"646\"), txt.language\n assert keywords.include? txt.keyword\n assert txt.translated_keyword.length > 0\n assert txt.text.length > 0\n end\n end\n end\n end\n\n end",
"def img!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 21 )\n\n type = IMG\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 348:7: 'img'\n match( \"img\" )\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__, 21 )\n\n end",
"def scale(width: @image.width, height: @image.height,\n algorithm: 'bilineal') # bilinear, nearest_neighbor\n if algorithm == 'nearest_neighbor'\n Image.new(@image.resample_nearest_neighbor(width, height), path)\n else\n Image.new(@image.resample_bilinear(width, height), path)\n end\n end",
"def classify(text)\n rating = @classifiers[@mailbox].rate text\n rating > @threshold\n end",
"def image\n image = Weatherman::Image.new(attribute('image'))\n do_convertions(image, [:width, :to_i], [:height, :to_i], :title, :link, :url)\n end",
"def convert\n @value = \"\"\n @areas.each do |area|\n image = RTesseract.new(@source.to_s,@options)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:width].to_i, area[:height].to_i)\n @value << image.to_s\n end\n rescue\n raise RTesseract::ConversionError\n end",
"def detect_labels path_to_image_file:\n# [START detect_labels]\n # [START importing_libraries]\n require \"google/cloud/vision\"\n # [END importing_libraries]\n\n # [START create_vision_client]\n vision = Google::Cloud::Vision.new\n # [END create_vision_client]\n\n # [START annotate_image]\n image = vision.image path_to_image_file\n annotation = vision.annotate image, labels: true\n labels = annotation.labels\n # [END annotate_image]\n\n # [START print_labels]\n puts \"Image labels:\"\n labels.each do |label|\n puts label.description\n end\n # [END print_labels]\n# [END detect_labels]\nend",
"def darken(options={})\n filter_name = 'CIColorControls'\n filter_options = {\n inputBrightness: options[:brightness] || -0.5,\n inputSaturation: options[:saturation] || -0.2,\n }\n\n cg_input_image = CIImage.alloc.initWithImage(self)\n darken_filter = CIFilter.filterWithName(filter_name)\n raise Exception.new(\"Filter not found: #{filter_name}\") unless darken_filter\n\n darken_filter.setDefaults\n darken_filter.setValue(cg_input_image, forKey:'inputImage')\n filter_options.each_pair do |key, value|\n darken_filter.setValue(value, forKey:key)\n end\n output = darken_filter.valueForKey('outputImage')\n\n context = CIContext.contextWithOptions(nil)\n cg_output_image = context.createCGImage(output, fromRect:output.extent)\n output_image = UIImage.imageWithCGImage(cg_output_image)\n\n return output_image\n end",
"def create_advanced\n image_service = ImageGeneratingService.new(self, 'Advanced.jpg', 'image/jpeg', 69)\n output_path = image_service.generate\n original_size_mb = File.size(output_path).to_f / 2**20\n if original_size_mb > 1.0\n image_service.generate_resized(1200)\n end\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def monochrome! \n\t\treturn @image = @image.quantize(2, Magick::GRAYColorspace) \n\tend",
"def blur_image\r\n\r\n#define new image array with identical length to old array\r\n image1 = Array.new(@image.length){\r\n Array.new(@image[0].length){}}\r\n\r\n#start indexing through each cell and define values for rows and columns\r\n @image.each_with_index { |val, rowindex|\r\n val.each_with_index {|val1, colindex| \r\n\r\n#hardcoding 'nil' index values into zeroes \r\n if image1 [rowindex][colindex] != 1 \r\n then image1 [rowindex][colindex] = 0 \r\n end\r\n\r\n#if currently indexed cell has a value of 1 in original array, cell value in new array will be 1\r\n if val1 > 0 \r\n then image1 [rowindex][colindex] = 1\r\n\r\n#define value of cell directly below currently indexed cell as 1, unless it is the last cell in a column.\r\n if colindex != val.length-1\r\n then image1 [rowindex][colindex +1] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define value of cell directly above it as 1.\r\n if colindex != 0 then\r\n image1 [rowindex][colindex -1] = 1\r\n end\r\n\r\n#define value of the cell to the RIGHT of the currently indexed cell as 1, unless it is the last cell in a row.\r\n if rowindex != @image.length-1 then\r\n image1 [rowindex +1][colindex] = 1\r\n end\r\n\r\n#if the currently indexed cell is 1, then define the value of the cell to the LEFT of it as 1.\r\n if rowindex != 0 then\r\n image1 [rowindex -1][colindex] = 1\r\n end\r\n\r\n end\r\n\r\n }} \r\n\r\n#show blurred image array\r\n image1.each do |cell|\r\n puts cell.join\r\n end\r\n end",
"def preprocessing_binarize(image_file, opts = {})\n data, _status_code, _headers = preprocessing_binarize_with_http_info(image_file, opts)\n data\n end",
"def create\n @text2_image = Text2Image.new(params[:text2_image])\n \n @text2_image.create_image(params[:text2_image][:text])\n\n respond_to do |format|\n if @text2_image.save\n\n format.html { redirect_to @text2_image, notice: 'Text2 image was successfully created.' }\n format.json { render json: @text2_image, status: :created, location: @text2_image }\n else\n format.html { render action: \"new\" }\n format.json { render json: @text2_image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def classify(text)\n positive_value = 1\n neutral_value = 1\n negative_value = 1\n\n word = text.split(/\\W+/)\n word = word.drop(1) if word.first == ''\n word.each_with_index { |_, i|\n find_instances(word[i])\n positive_value *= ((((positive_polarity.to_f/positive_population.to_f).to_f) * ((positive_polarity).to_f))/word_pop)\n negative_value *= ((((negative_polarity.to_f/negative_population.to_f).to_f) * ((negative_polarity).to_f))/word_pop)\n neutral_value *= ((((neutral_polarity.to_f/neutral_population.to_f).to_f) * ((neutral_polarity).to_f))/word_pop)\n }\n total_counter(negative_value, neutral_value, positive_value)\n\n rescue => error\n puts error.backtrace\n\n end",
"def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend",
"def run\n outputs = nil\n \n in_tmp_dir do\n image = tmp_path 'text_to_image.jpg'\n Image::Editing::Cmd::TextToImage.new(text, image, @options).run!\n\n outputs = ImageToVideo.new(image, @output_without_extension, duration, @log_folder).run\n end\n\n outputs\n end",
"def mark_image(image)\n images = Magick::Image.from_blob(image) # from_blob returns array of images\n image = images[0] # method is receiving just one image\n\n mark = Magick::Image.new(image.columns, image.rows)\n\n gc = Magick::Draw.new\n gc.gravity = Magick::CenterGravity\n gc.pointsize = 32\n gc.font_family = \"Arial\"\n gc.font_weight = Magick::BoldWeight\n gc.stroke = 'none'\n gc.annotate(mark, 0, 0, 0, 0, WATERMARK_STRING)\n\n mark = mark.shade(true, 310, 30)\n\n image.composite!(mark, Magick::CenterGravity, Magick::HardLightCompositeOp)\n\n image = image.to_blob\n return image\nend",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def update\n respond_to do |format|\n if @image.update(image_params)\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully updated.' }\n format.json { render :show, status: :ok, location: @image }\n else\n format.html { render :edit }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @txt = Txt.new(params[:txt])\n\n \n respond_to do |format|\n if @txt.save\n \n # long text parser \n $KCODE='utf8'\n require 'jcode'\n d_str =''\n @txt.longtext.each {|s_str| \n while s_str.jsize > NUM_WORD_PER_LINE\n tmp_str = s_str.scan(/./)[0,NUM_WORD_PER_LINE].join\n d_str += tmp_str + \"\\n\\n\"\n s_str = s_str[tmp_str.size,s_str.size-tmp_str.size]\n if s_str == nil then break end\n #puts s_str.jsize \n end\n if s_str!=nil then d_str += s_str end\n d_str += \"\\n\"\n }\n \n #--- path and name. to be config/updated in new environments\n font_path = 'D:\\\\fonts'\n images_path = \"public/images\"\n output_path = 'public/images/outputs'\n bg_image_path = images_path + \"/\"+ \"background.png\"\n\n require 'find'\n # do the same thing for each available fonts\n Find.find(font_path) do |f|\n img = Magick::Image.read(bg_image_path).first #图片路径\n src_img = Magick::Image.read(images_path+'/user_image.JPG').first # to be replaced with user's picture url\n src_img.crop_resized!(320,320) # 照片的目标尺寸\n src_img.border!(10, 10, \"#f0f0ff\") #相框的颜色,宽度\n frame_img = Magick::Image.read(images_path+'/frame.png').first # picture frame\n frame_img.composite!(src_img, 0, 0, Magick::OverCompositeOp)\n img.composite!(frame_img, 20, 20, Magick::OverCompositeOp)\n \n gc= Magick::Draw.new\n gc.annotate(img, 0, 0, 420, 50, d_str) do #可以设置文字的位置,参数分别为路径、宽度、高度、横坐标、纵坐标\n #self.gravity = Magick::CenterGravity\n self.font = f\n self.pointsize = FONT_SIZE #字体的大小\n self.fill = '#fff' #字体的颜色\n self.stroke = \"none\"\n end \n font_file_name = File.basename(f, 'ttf')\n file_path = output_path + \"/\"+ @txt.image_url + \"_\" + font_file_name + \"png\" \n img.write(file_path) \n end\n \n #@path = file_name\n format.html { redirect_to(@txt, :notice => 'Txt was successfully created.') }\n format.xml { render :xml => @txt, :status => :created, :location => @txt }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @txt.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def train_pixel\n\t\tif CartesianClassifier.train(params[:classname],params[:bands],params[:author])\n\t\t\trender :text => \"trained as '\"+params[:classname]+\"', you happy now?\", :layout => false\n\t\telse\n\t\t\trender :text => \"failed to train\", :layout => false\n\t\tend\n\tend",
"def binarize id\n m_begin \"binarize\"\n put_image(id, get_image(id).bilevel_channel(QuantumRange/2))\n# put_image(id, @var_table[id].quantize(2, GRAYColorspace, NoDitherMethod) )\n m_end \"binarize\"\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def imagemagick7?; end",
"def traitementMonochrome()\n return @image = @image.quantize(2, GRAYColorspace)\n end",
"def grayscale\n with_command \"-type Grayscale\"\n end",
"def darken(options={})\n filter_options = {\n 'inputSaturation' => options[:saturation] || 0,\n 'inputBrightness' => options[:brightness] || 0,\n }\n\n darken_filter = CIFilter.color_controls(filter_options)\n output = self.apply_filter(darken_filter)\n return UIImage.imageWithCIImage(output, scale:self.scale, orientation:self.imageOrientation)\n end",
"def toaster_filter\n manipulate! do |img|\n img.modulate '150,80,100'\n img.gamma 1.1\n img.contrast\n img.contrast\n img.contrast\n img.contrast\n img = yield(img) if block_given?\n img\n end\n end",
"def convert_to_tiff_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ConvertApi.convert_to_tiff ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling ConvertApi.convert_to_tiff\"\n end\n # resource path\n local_var_path = '/image/convert/to/tiff'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ConvertApi#convert_to_tiff\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def createAscii(options = {})\n if @status == true\n options = {\"width\" => 90, \"color\" => true}.merge(options)\n\t img = Magick::Image.from_blob(@data).first\n\t width = options[\"width\"]\n\t scale = (width.to_f / img.columns)\n\t \n\t height = ((img.rows * scale) / 2).to_i\n\t # puts height\n\t if height >= 100\n\t \theight = 80\n\t end\n\n\t border = \"+#{'-' * width}+\\n\"\n\t output = border.dup\n\n\t img.resize!(width, height)\n\t color_image = img.dup if options[\"color\"]\n\t img = img.quantize(@image_chars.length, Magick::GRAYColorspace).normalize\n\t quantum_calc = Magick::QuantumRange / (@image_chars.length - 1)\n\n\t \n\t img.view(0, 0, width, height) do |view|\n\t \n\t height.times do |i|\n\t \n\t output << '|'\n\t width.times do |j|\n\n\t character = @image_chars[view[i][j].red/quantum_calc] \n\n\t if options[\"color\"]\n\t pix = color_image.pixel_color(j,i)\n\t character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))\n\t end\n\n\t output << character\n\t end\n\n\t output << \"|\\n\"\n\t end\n\t end\n\n\n\t output << border\n\t return output\n end\n end",
"def recognize\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def image_magick(image)\n Open3.capture3(\n \"convert\", image.cached, # What to convert?\n \"-resize\", \"#{image.width}x#{image.height}^\", # resizing\n \"-gravity\", \"center\", \"-crop\", \"#{image.width}x#{image.height}+0+0\", # cropping\n \"-background\", \"#ffffff\", # background color in case image was transparent\n \"+repage\", \"-flatten\", # Discard canvas size and squash into single layer\n image.resized # Target path of output\n )\n end",
"def grayscale?(input)\n # By testing the average saturation of the image we can guess if it's\n # grayscale (then the saturation is 0)\n # Source: http://www.imagemagick.org/discourse-server/viewtopic.php?t=19580\n options = [\n input.shellescape,\n '-colorspace HSL',\n '-channel g',\n '-separate +channel',\n '-format \"%[fx:mean]\"',\n 'info:'\n ]\n raw = `convert #{options.join(' ')}`.chomp.to_f\n raw.zero?\n end",
"def greyScale? \n\t\treturn @image.grey? \n\tend",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def draw_cassette_feature( image, feature, x, y, params = {} )\n width = feature.width\n height = @feature_height\n colour = feature.render_options[ \"colour\" ] || params[:colour] || \"white\"\n font = feature.render_options[ \"font\" ] || params[:font] || \"black\"\n label = params[:label] || feature.feature_name\n drawing = Magick::Draw.new\n\n # create a block\n drawing.stroke( \"black\" )\n drawing.fill( colour )\n drawing.rectangle( x, @top_margin, x + width, @image_height - @bottom_margin )\n drawing.draw( image )\n\n # annotate the block\n pointsize = @font_size\n drawing.annotate( image, width, height, x, @top_margin, label ) do\n self.fill = font\n self.font_weight = Magick::BoldWeight\n self.gravity = Magick::CenterGravity\n self.pointsize = pointsize\n end\n\n return image\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def camaleon_image_optimizer_on_active(plugin)\n end",
"def summary_img\n num_tracks_needed = 1\n\n begin\n p = Bio::Graphics::Page.new(:width => 962, :height => 150, :number_of_intervals => 10)\n\n #separate features into mRNA or gene features\n\n genes = @features.select { |x| x.feature == 'gene' }\n if not genes.empty?\n gene_track = p.add_track(:glyph => :directed,\n :fill_color => :green_white_radial,\n :label => false\n )\n # mrna_track = p.add_track(:glyph => :transcript,\n # :exon_fill_color => :red_white_h,\n # :utr_fill_color => :blue_white_h\n # )\ngenes.each do |gene|\n feat = Bio::Graphics::MiniFeature.new(:start => gene.start,\n :end => gene.end,\n :strand => gene.strand,\n :id => gene.gff_id)\n gene_track.add(feat)\nend\nend\n\nproteins = @features.select { |x| x.feature == 'protein' }\n\nif not proteins.empty?\n protein_track = p.add_track(\n :glyph => :generic,\n :fill_color => :yellow_white_radial,\n :label => false\n )\n proteins.each do |protein|\n feat = Bio::Graphics::MiniFeature.new(:start => protein.start,\n :end => protein.end,\n :id => protein.gff_id\n )\n protein_track.add(feat)\n end\nend\n\n\nmrnas = @features.select { |x| x.feature == 'mRNA' }\n@mrnas = mrnas\nif not mrnas.empty?\n mrna_track = p.add_track(:glyph => :transcript,\n :exon_fill_color => :red_white_h,\n :utr_fill_color => :blue_white_h,\n :label => false,\n :gap_marker => 'angled'\n )\n mrnas.each do |m|\n exons = []\n utrs = []\n m.children.each do |d|\n if d.feature == 'exon'\n exons << d.start\n exons << d.end\n end\n if d.feature == 'five_prime_UTR' or d.feature == 'three_prime_UTR'\n utrs << d.start\n utrs << d.end\n end\n exons.sort!\n utrs.sort!\n end\n @exons = exons\n @utrs = utrs\n\n if exons.empty?\n exons = [m.start, m.end]\n end\n\n if utrs.empty?\n utrs = [m.start, m.end]\n end\n feat = Bio::Graphics::MiniFeature.new(\n :start => m.start,\n :end => m.end,\n :strand => m.strand,\n :exons => exons,\n :utrs => utrs,\n :id => m.gff_id\n )\n mrna_track.add(feat)\n end\nend\n@svg = p.get_markup\nrescue\n @svg = \"\"\nend\n\nend",
"def image_ocr_photo_recognize_business_card(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_business_card_with_http_info(image_file, opts)\n data\n end",
"def convert!(image, format, page = nil, &block)\n with_minimagick(image) do |img|\n img.format(format.downcase, page, &block)\n end\n end",
"def pixelate\n\t\t\tmax_level = @post.resolution_level - 1\n\t\t\tmax_resolution = 2**max_level;\n\n\t\t\timg = Magick::ImageList.new(@post.image.path(:medium))\n\t\t\tstep = img.columns / max_resolution\n\t\t\ttemplate = Magick::Image.new(step, step)\n\t\t\tpixel_matrices = Array.new(max_level + 1)\n\n\t\t\t# Initialize 3D array: [level][row][col]\n\t\t\tfor level in 0..max_level do\n\t\t\t\tpixel_matrices[level] = level == max_level ? Array.new(2**level) { Array.new(2**level) } : nil\n\t\t\tend\n\n\t\t\tfor r in 0...max_resolution do\n\t\t\t\tfor c in 0...max_resolution do\n\t\t\t\t\t# Cut image into blocks\n\t\t\t\t\tblock = img.export_pixels_to_str( c * step, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t r * step,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t step,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t step )\n\t\t\t\t\taverage_pixel = template.import_pixels(0,0,step, step, \"RGB\", block).scale(1,1).pixel_color(0,0)\n\n\t\t\t\t\t# Translate red,green,blue value into 8-bit depth from 16-bit depth (default RMagick)\n\t\t\t\t\tpixel_matrices[max_level][r][c] = [average_pixel.red, average_pixel.green, average_pixel.blue].map! { |x| convert_16bit_to_8bit_with_damping(x) }\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# Compute the remaining levels\n\t\t\tfor level in max_level.downto(1) do\n\t\t\t\taverage = Array.new(2**(level-1)) { Array.new(2**(level-1)) { Array.new(3, 0.0) } }\n\t\t\t\tfor r in 0...2**level do\n\t\t\t\t\tfor c in 0...2**level do\n\t\t\t\t\t\taverage[r / 2][c / 2][0] += pixel_matrices[level][r][c][0] / 4\n\t\t\t\t\t\taverage[r / 2][c / 2][1] += pixel_matrices[level][r][c][1] / 4\n\t\t\t\t\t\taverage[r / 2][c / 2][2] += pixel_matrices[level][r][c][2] / 4\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tpixel_matrices[level-1] = Array.new(average)\n\t\t\tend\n\t\t\t@post.pixel_matrices = pixel_matrices\n\t\t\t@post.save\n\t\tend",
"def detect( str )\n sums = {}\n results = (num_processes.nil? or !EncodingEstimator::ParallelSupport.supported?) ?\n detect_st( str, combinations ) : detect_mt( str, combinations )\n\n results.each do |result|\n sums[result.key] = sums.fetch(result.key, 0.0) + result.score\n end\n\n range = EncodingEstimator::RangeScale.new( sums.values.min, sums.values.max )\n\n scaled_scores = {}\n sums.each do |k,s|\n scaled_scores[ k ] = range.scale s\n end\n\n EncodingEstimator::Detection.new( scaled_scores, @conversions )\n end"
] |
[
"0.6249741",
"0.58387315",
"0.5795003",
"0.56958514",
"0.56134284",
"0.558428",
"0.5581397",
"0.5499139",
"0.54791594",
"0.54326797",
"0.5406956",
"0.53870916",
"0.5385192",
"0.53341883",
"0.5310227",
"0.529243",
"0.5280662",
"0.52283746",
"0.5201758",
"0.51803356",
"0.51712203",
"0.5151637",
"0.51401263",
"0.51399493",
"0.5132789",
"0.51098424",
"0.51040864",
"0.50945747",
"0.50411814",
"0.50218946",
"0.5002209",
"0.49666518",
"0.49638692",
"0.4962168",
"0.495914",
"0.49575403",
"0.49433297",
"0.49425918",
"0.49260685",
"0.4902231",
"0.4894328",
"0.48830923",
"0.48827177",
"0.48803687",
"0.4870767",
"0.48634082",
"0.48476386",
"0.48178354",
"0.4816102",
"0.48058435",
"0.47984937",
"0.47813386",
"0.47799987",
"0.4777562",
"0.47765785",
"0.47538346",
"0.47484094",
"0.47430602",
"0.4734824",
"0.4730492",
"0.4724711",
"0.47220504",
"0.47121713",
"0.46991348",
"0.46911225",
"0.4688944",
"0.4688494",
"0.46865797",
"0.4674419",
"0.46618018",
"0.4654369",
"0.46518165",
"0.46468854",
"0.46448418",
"0.46356714",
"0.46269426",
"0.4620296",
"0.46191022",
"0.46188524",
"0.461869",
"0.461012",
"0.460275",
"0.45795864",
"0.457902",
"0.4574526",
"0.45734474",
"0.4567322",
"0.4561782",
"0.45604998",
"0.45554078",
"0.45490488",
"0.45361167",
"0.4535586",
"0.45313153",
"0.45228574",
"0.45213258",
"0.45179027",
"0.45167303",
"0.45133835",
"0.45106018"
] |
0.49927145
|
31
|
Get the angle of the page / document / receipt Analyzes a photo or image of a document and identifies the rotation angle of the page.
|
def preprocessing_get_page_angle(image_file, opts = {})
data, _status_code, _headers = preprocessing_get_page_angle_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def angle\n @angle\n end",
"def angle()\n a, c = @view__.angle, @context__\n c ? c.fromDegrees__(a) : a * Processing::GraphicsContext::DEG2RAD__\n end",
"def angle(path)\n io_for(path).angle\n end",
"def angle\r\n self.data.map(&:angle)\r\n end",
"def angle\n Math.atan2(@y, @x)\n end",
"def angle\n v = to_vec\n if v[1] == 0.0\n nil\n else\n v.angle\n end\n end",
"def preprocessing_get_page_angle_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_get_page_angle ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_get_page_angle\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/get-page-angle'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'GetPageAngleResult')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_get_page_angle\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def angle\n Math.atan2( @y, @x )\n end",
"def get_rotation\n return @rotation\n end",
"def angle\n rad / Math::PI * 180\n end",
"def angle\n ns = norm\n x_ = @x / ns\n y_ = @y / ns\n\n Math.atan2(x_, y_)\n end",
"def angle_of_specified_radius\n @angle_of_radius\n end",
"def angle_deg\n angle * RAD_TO_DEG\n end",
"def angle(p)\n Math.atan2(p.y - self.y, p.x - self.x)\n end",
"def angle_diff(angle1, angle2)\n end",
"def calculate_orientation\n x, y = @components.values\n if x.pos? and y.zero?\n 0.deg\n elsif x.zero? and y.pos?\n 90.deg\n elsif x.neg? and y.zero?\n 180.deg\n elsif x.zero? and y.neg?\n 270.deg\n elsif x.pos? and y.pos?\n Math.atan( y/x ).rad # Will return an Angle object (with the property \"degrees\")\n elsif x.neg? and y.pos?\n angle = Math.atan( y/x.abs ).rad\n (180 - angle.deg).deg # Will return an Angle object (with the property \"degrees\")\n elsif x.neg? and y.neg?\n angle = Math.atan( y.abs/x.abs ).rad\n (180 + angle.deg).deg # Will return an Angle object (with the property \"degrees\")\n elsif x.pos? and y.neg?\n angle = Math.atan( y.abs/x ).rad\n (360 - angle.deg).deg\n end\n end",
"def radians\n Science::Angle.new(self, :radians)\n end",
"def angle(*args)\n Math.acos(self.dot(*args))\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def calc_angle(hours, minutes)\n angel = (minutes * 6 - (hours * 60 + minutes) * 0.5).abs\n if angel > 180\n 360 - angel.abs\n else\n angel.abs\n end\nend",
"def angle_to(key)\n p1 = {\n x: (row_offset.to_f)+((width)/2),\n y: (row.number.to_f)-((height)/2)+(height)\n }\n\n p2 = {\n x: (key.row_offset.to_f)+((key.width)/2),\n y: (key.row.number.to_f)-((key.height)/2)+(key.height)\n }\n\n Math.atan2(p2[:x] - p1[:x], p2[:y] - p1[:y]) * 180 / Math::PI\n end",
"def radians\n self * 180 / Math::PI\n end",
"def angle_a\n Angle.new(\n self,\n :a,\n (\n (\n Math.acos((b**2 + c**2 - a**2) / (2.0 * b * c)) * 180\n ) / Math::PI\n )\n )\n end",
"def orientation \n @position - @prev_position\n end",
"def pdf_to_sign\n _get_pdf_to_sign\n end",
"def angle_at(point)\n Point.angle(centre, point)\n end",
"def radian_angle\n @angle * Math::PI / 180.0\n end",
"def angle_between(p1, p2)\n vect_p1 = p1 - self\n vect_p2 = p2 - self\n\n theta = vect_p1.polar - vect_p2.polar\n theta += 360.0 if theta < 0.0\n theta = 360.0 - theta if theta > 180.0\n return theta\n end",
"def angles_diff(a1, a2)\n diff = a2 - a1\n while diff > Math::PI\n diff -= 2.0 * Math::PI\n end\n while diff < -Math::PI\n diff += 2.0 * Math::PI\n end\n diff\n end",
"def calculate_radians\n if x_length == 0 || y_length == 0\n angle_to_start_of_quadrant\n else\n case angle_to_end_of_quadrant\n when DEGREES_90\n angle_ignoring_quadrant\n when DEGREES_180\n DEGREES_180 - angle_ignoring_quadrant\n when DEGREES_270\n DEGREES_180 + angle_ignoring_quadrant\n else\n DEGREES_360 - angle_ignoring_quadrant\n end\n end\n end",
"def getAngle(c1,c2)\n x = c2[0] - c1[0]\n y = c2[1] - c1[1]\n x = x <= -180 ? x + 360 : x\n x = x >= 180 ? x - 360 : x\n\n a = Math.atan2(y, x)\n rescue\n p \"Error x=#{x}, y=#{y} sq= #{Math.sqrt(x*x+y*y)} rat=#{x / Math.sqrt(x*x+y*y)}\"\n raise Error\n end",
"def angle(x1, y1, x2, y2)\n end",
"def required_rotation_for_upright_display\n required_rotation_orientation_in_degrees = (360 - self.orientation) % 360\n return required_rotation_orientation_in_degrees\n end",
"def start_angle\n end",
"def rotate angle\n position = \"#{@placement[:s]}x#{@placement[:s]}+#{@placement[:x]}+#{@placement[:y]}\"\n @image.run_command(\"convert\", @image.path, \"-rotate #{360 - angle}\", @image.path)\n @image.run_command(\"convert\", @image.path, \"-gravity Center -crop #{position}\", @image.path)\n end",
"def get_degree note\n relative_note = note - @tonic # we are only concerned with the note relative to the tonic\n octave = (relative_note.to_i / 12) - 1\n index = @intervals.index(@intervals.find{|n| n >= relative_note % 12})\n return \"#{((octave + 1) * @intervals.size) + 7}#\" unless index # if index is nil, it means note is a sharpened 7th index... we add 1 to octave to account for the -1st octave\n degree = index + 1\n approximate_degree = ((octave + 1) * 7) + degree\n accidental = ACCIDENTALS[relative_note - (((octave + 1) * 12) + @intervals[index])]\n return \"#{approximate_degree}#{accidental}\"\n end",
"def angle_from_input\n\n return if @path.size < 2\n return unless @active_controller.is_a? Symbol\n\n i = @active_controller == :start ? 0 : 1\n corner = @path[-i]\n ref_vector = @path[-i] - @path[1 - 3 * i]\n input_vector = corner - @ip.position\n return unless input_vector.valid?\n return if input_vector.parallel? Z_AXIS\n return if input_vector.parallel? ref_vector\n\n angle = -(MyGeom.angle_in_plane input_vector, ref_vector)\n angle -= GRAPHICAL_ANGLES[i]\n angle = ((angle+90.degrees)%180.degrees)-90.degrees\n\n @end_angles[i] = angle\n\n end",
"def rotate(angle, x, y, &block)\n cur_page.rotate(angle, x, y, &block)\n end",
"def calc_angle(x1, y1, x2, y2)\r\n# - - - - - - - - - - - - - - - - - - - -\r\n if (x1 == x2)\r\n if (y2 >= y1)\r\n return 0\r\n else\r\n return 180\r\n end #else\r\n elsif (y1 == y2)\r\n if (x2 >= x1)\r\n return 90\r\n else\r\n return 270\r\n end #else\r\n else\r\n x1 = x1 + 0.0 # force to be floating point\r\n x2 = x2 + 0.0 # force to floating point\r\n slope = (y2-y1) / (x2-x1)\r\n radians = Math.atan(slope)\r\n degrees = conv_radian_to_degree(radians)\r\n # Handle Adjusting Quadrent\r\n if ((x2 > x1) && (y2 > y1))\r\n # Quadrent 1;\r\n degrees = degrees\r\n elsif ((x2 > x1) && (y2 < y1))\r\n # Quadrent 2\r\n degrees = 90 - degrees;\r\n elsif ((x2 < x1) && (y2 < y1))\r\n # Quadrent 3\r\n degrees = 270 - degrees\r\n else\r\n # must be Quadrent 4\r\n degrees = 270 - degrees\r\n end # else\r\n end # else\r\n return degrees\r\nend",
"def angle_delta(angle1, angle2)\n \t delta = (angle1 - angle2).abs\n \t if delta >= Math::PI\n \t delta = (((2 * Math::PI) - angle1) + angle2).abs\n \t end\n \t return delta\n \tend",
"def angle_from other_point\n Geometry.angle_from self, other_point\n end",
"def norm_angle(angle)\n while angle < 0; angle += Const::PI2; end\n while angle > Const::PI2; angle -= Const::PI2; end\n return angle\n rescue => e\n raise\n end",
"def convert_to_radians(degrees)\n degrees * PI / 180\nend",
"def other_angle(a, b)\n 180 - (a + b)\nend",
"def degrees\n self * Math::PI / 180\n end",
"def calc_point_rotated_abs(x,y, angle)\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n curr_angle = calc_angle(0,0,x,y)\r\n rel_amt = angle - curr_angle\r\n return calc_point_rotate_relative(x,y,rel_amt)\r\nend",
"def other_angle(a, b)\n 180 - (a + b)\nend",
"def page_size\n page_size = @reader.crop_box(1)\n if @reader.page_rotation(1) % 180 == 0\n [page_size.width, page_size.height]\n else\n [page_size.height, page_size.width]\n end\n end",
"def is_angle?(); @type == GRT_ANGLE; end",
"def aperture\n f = image_exif[\"FNumber\"]\n return nil if f.blank?\n (Rational(*(f.split('/').map( &:to_i )))).to_f\n end",
"def angle_rads \n\t\t\t2.0 * Math.atan2( self.vec.mag, self.scalar ) \n\t\tend",
"def line_angle(p1,p2)\n v1 = RBA::DPoint.new(1,0)\n v2 = p2-p1\n return vector_angle(v1,v2)\n end",
"def orientation\n p1, p2, p3 = *convex_sub_polygon\n det = (p2[0]-p1[0])*(p3[1]-p1[1]) - (p3[0]-p1[0])*(p2[1]-p1[1])\n @orientation ||= (det < 0)? 1 : -1\n end",
"def yaw\n to_euler[0]\n end",
"def anglecw\n 360 - angle\n end",
"def to_radians\n self * Math::PI.fdiv(180)\n end",
"def angle_to body\n dx = body.x - self.x\n dy = body.y - self.y\n\n (R2D * Math.atan2(dy, dx)).degrees\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def angles\n [angle_a, angle_b, angle_c]\n end",
"def rotate(angle_x = 0, angle_y = 0, angle_z = 0)\n\t\tc = 0; cx = 0; cy = 0; cz = 0\n\t\t# get middle point\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tcx += b[0]\n\t\t\t\tcy += b[1]\n\t\t\t\tcz += b[2]\n\t\t\t\tc +=1\n\t\t\tend\n\t\tend\n\t\tcx /= c; cy /= c; cz /= c\n\t\t# rotate points\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tx = b[0]; y = b[1]; z = b[2]\n\n\t\t\t\tx, y, z = rotate_point(x, y, z, cx, cy, cz, angle_x, angle_y, angle_z)\n\n\t\t\t\tb[0] = x; b[1] = y; b[2] = z\n\t\t\tend\n\t\tend\n\tend",
"def rotate(angle, around_x=0, around_y=0, &rendering_code); end",
"def degrees\n self * Math::PI / 180.0\n end",
"def determine_angle(angle, range)\n range.include?(angle) ? angle.to_f : angle.divmod(MAX_DEGREE_RANGE).last\nend",
"def yaw \n\t\t\t# tan(yaw) = 2(xy+wz) / (w^2 + x^2 - y^2 - z^2)\n\t\t\tx = @elem[X]; y = @elem[Y]; z = @elem[Z]; w = @elem[W]\n\t\t\treturn Math::atan( (2 * (x*y + w*z)) / (w**2 + x**2 - y**2 - z**2) )\n\t\tend",
"def /(other)\n return self.class.radians(@angle / other)\n end",
"def normalize_heading(angle)\n \t return angle % (2 * Math::PI)\n \tend",
"def rotations\n self.to_s.rotations.collect { |s| s.to_i }\n end",
"def cur_angle\n MSPhysics::Newton::Hinge.get_cur_angle(@address)\n end",
"def angle_between(vector2)\n end",
"def cur_angle\n MSPhysics::Newton::Corkscrew.get_cur_angle(@address)\n end",
"def angle_equation_of_time() \r\n delta_orbit() + delta_oblique()\r\n end",
"def getGeoAngle(c1,c2)\n x = c2[0] - c1[0]\n y = c2[1] - c1[1]\n y = y <= -180 ? y+360 : y\n y = y >= 180 ? y-360 : y\n\n ca = getCentralAngle(c1,c2)\n dist = EARTH_RADIUS_FEET * ca\n ca1 = getCentralAngle(c1,[c2[0],c1[1]])\n dist1 = EARTH_RADIUS_FEET * ca1 * sign(x)\n ca2 = getCentralAngle(c2,[c2[0],c1[1]])\n dist2 = EARTH_RADIUS_FEET * ca2 * sign(y)\n\n angle = Math.atan2(dist2,dist1)\n end",
"def get_angle(vertices_hash)\n raise 'not circular enough for this call' if !circular\n t_v1, t_v2 = translate_edge(vertices_hash)\n dot_product = self.class.get_dot_product(t_v1, t_v2)\n origin = Vertex.new(0,0)\n magnitude_t_v1 = get_distance(origin, t_v1)\n magnitude_t_v2 = get_distance(origin, t_v2)\n cosine = dot_product / (magnitude_t_v1 * magnitude_t_v2)\n Math.acos(cosine)\n end",
"def angle(vector1,vector2)\n\n small = 0.00000001\n undefined = 999999.1\n\n magnitudevector1 = magnitude(vector1)\n magnitudevector2 = magnitude(vector2)\n if (magnitudevector1*magnitudevector2) > (small**2)\n aux = vdot(vector1,vector2)/(magnitudevector1*magnitudevector2)\n if aux.abs> 1.0\n aux = signal(aux) * 1.0\n end\n return Math.acos(aux)\n else\n return undefined\n end\n end",
"def rt_ascen\n radian_to_degree(bigdecimal_atan2(bigdecimal_cos(degree_to_radian(obliquity)) * bigdecimal_sin(degree_to_radian(ec_lon)), bigdecimal_cos(degree_to_radian(ec_lon))))\n end",
"def find_rotation_point(words)\n front_idx = 0\n back_idx = words.length - 1\n \n while front_idx <= back_idx\n middle = ((back_idx - front_idx) / 2) + front_idx\n current = words[middle] \n word_before = (middle - 1 < 0) ? nil : words[middle - 1]\n word_after = words[middle + 1] \n\n last_word = word_after.nil?\n first_word = word_before.nil?\n if first_word\n return middle if current < word_after\n return middle + 1\n elsif last_word \n return middle if current < word_before\n return middle - 1\n elsif current < word_before && current < word_after\n return middle\n end\n if words[middle] < words[0]\n back_idx = middle - 1\n elsif words[middle] > words[0]\n front_idx = middle + 1\n end\n end\n nil\nend",
"def atan\n math :atan\n end",
"def angle x1, y1, a, m, c\n x2, y2 = project x1, y1, a, m\n line x1, y1, x2, y2, c\n end",
"def to_rad(angle)\n angle * Math::PI / 180\n end",
"def get_annotation page_number, annotation_index\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 if annotation_index == ''\n raise 'annotation index not specified'\n end\n \n str_uri = $product_uri + '/pdf/' + @filename + '/pages/' + page_number.to_s + '/annotations/' + annotation_index.to_s\n str_signed_uri = Aspose::Cloud::Common::Utils.sign(str_uri) \n response_stream = RestClient.get(str_signed_uri, {:accept=>'application/json'})\n \n stream_hash = JSON.parse(response_stream)\n \n return stream_hash['Annotation']\n \n \n rescue Exception=>e\n print e\n end\n end",
"def find_rotation_pt(arr)\n return 0 if arr.length == 1 || arr.empty?\n\n mid = arr.length / 2\n return mid if out_of_order?(arr[mid - 1], arr[mid]) == -1\n\n left = find_rotation_pt(arr[0...mid])\n right = find_rotation_pt(arr[mid..-1])\n\n return right > 0 ? mid + right : left\nend",
"def angle_to other_point\n Geometry.angle_to self, other_point\n end",
"def angle_direction(a,b)\n magnitude = angle_difference(a,b)\n if angle_difference(a + 1, b) < magnitude\n magnitude\n else\n -magnitude\n end\n end",
"def ml_Aries() \r\n # jd = @ta * DJC # convert first term back to jdn - J2000\r\n # old terms \t\r\n # angle = (36000.770053608 / DJC + 360) * jd # 36000.770053608 = 0.9856473662862 * DJC\r\n # total = [ -1.0/3.8710000e7, 3.87930e-4, 0, 100.460618375 ].inject(0.0) {|p, a| p * ta[0] + a} + 180 + angle \r\n # newer terms seem to be in arcseconds / 15.0\r\n # 0.0000013, - 0.0000062, 0.0931118, 307.4771600, 8639877.3173760, 24110.5493771\r\n # angle = (35999.4888224 / DJC + 360) * jd \r\n # total = angle + 280.460622404583 +\r\n # @ta[ 0 ] * 1.281154833333 +\r\n # @ta[ 1 ] * 3.87965833333e-4 +\r\n # @ta[ 2 ] * -2.58333333333e-8 +\r\n # @ta[ 3 ] * 5.41666666666e-9\r\n # total = [5.41666666666e-9, -2.58333333333e-8, 3.87965833333e-4, 1.281154833333, 280.460622404583].inject(0.0) {|p, a| p * @ta + a} \r\n # mod_360( angle + total ) * D2R\r\n dt = 67.184 \r\n tt = @ajd + dt / 86400.0#Celes.ut1tt(@ajd, 0, dt)\r\n Celes.gmst06(@ajd, 0, tt, 0) \r\n end",
"def angle_c\n Angle.new(\n self,\n :c,\n (\n (\n Math.acos((a**2 + b**2 - c**2) / (2.0 * a * b)) * 180\n ) / Math::PI\n )\n )\n end",
"def edit_pdf_rotate_all_pages_with_http_info(input_file, rotation_angle, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: EditPdfApi.edit_pdf_rotate_all_pages ...'\n end\n # verify the required parameter 'input_file' is set\n if @api_client.config.client_side_validation && input_file.nil?\n fail ArgumentError, \"Missing the required parameter 'input_file' when calling EditPdfApi.edit_pdf_rotate_all_pages\"\n end\n # verify the required parameter 'rotation_angle' is set\n if @api_client.config.client_side_validation && rotation_angle.nil?\n fail ArgumentError, \"Missing the required parameter 'rotation_angle' when calling EditPdfApi.edit_pdf_rotate_all_pages\"\n end\n # resource path\n local_var_path = '/convert/edit/pdf/pages/rotate/all'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'rotationAngle'] = rotation_angle\n\n # form parameters\n form_params = {}\n form_params['inputFile'] = input_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: EditPdfApi#edit_pdf_rotate_all_pages\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def angle_to(point)\n Ubiquity::Geoformulas.angle self.lat, self.lon, point.lat, point.lon\n end",
"def map_direction_to_angle(dir)\n return $direction_map[dir]\nend",
"def yaw\n @grpc.pan_angle\n end",
"def calculate_heading()\n @heading[:x], @heading[:y] = Params::directional_vector @angle\n end",
"def degrees\n self\n end",
"def rad\n x = self[0]\n y = self[1]\n if x >= 0 && y >= 0\n Math.atan( y.to_f/x )\n elsif x < 0 && y >= 0\n Math::PI + Math.atan( y.to_f/x )\n elsif x < 0 && y < 0\n Math::PI + Math.atan( y.to_f/x )\n else\n 2*Math::PI + Math.atan( y.to_f/x )\n end\n end",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def polar\n theta = 0.0\n if Point.close_to(self.x, 0)\n if self.y > 0\n theta = 90.0\n elsif self.y < 0\n theta = 270.0\n end\n else\n theta = Point.rad2deg(Math.atan(self.y/self.x))\n if self.x < 0.0\n theta += 180.0\n end\n if theta < 0.0\n theta += 360.0\n end\n end\n theta\n end",
"def to_radians(deg)\n deg * Math::PI / 180\n end",
"def angle_delta_oblique() \r\n #al(@ma, @ta, Celes.faom03(@ta)) - ra_Sun()\r\n al_Sun() - ra_Sun() \r\n end",
"def safe_angle(angle)\n if angle < @angle_range.min\n @angle_range.min\n elsif angle > @angle_range.max\n @angle_range.max\n else\n angle\n end\n end",
"def radians(deg)\n deg * Math::PI / 180\n end",
"def to_radians(n)\n r = n * (Math::PI / 180)\n return r\n end",
"def angle_with( vector )\n Math.acos( max(min(udot(vector),MAX_UDOT_PRODUCT), MIN_UDOT_PRODUCT) )\n end"
] |
[
"0.6770511",
"0.6355038",
"0.63267356",
"0.61359376",
"0.59200954",
"0.5912687",
"0.58901113",
"0.5869649",
"0.5843366",
"0.5825865",
"0.5711544",
"0.56564385",
"0.5617053",
"0.5522956",
"0.54968333",
"0.5480202",
"0.54528534",
"0.53941053",
"0.5391114",
"0.53884804",
"0.5365826",
"0.5365198",
"0.5350418",
"0.5347965",
"0.5336461",
"0.53124887",
"0.52869505",
"0.5276761",
"0.5238073",
"0.52376074",
"0.52365464",
"0.5210731",
"0.5208049",
"0.51719856",
"0.5158142",
"0.5156201",
"0.5139084",
"0.5118632",
"0.5110398",
"0.5108867",
"0.51013494",
"0.5101203",
"0.5073505",
"0.50699896",
"0.50645614",
"0.505114",
"0.5050078",
"0.5035461",
"0.5034011",
"0.5032797",
"0.50319195",
"0.5029338",
"0.50253785",
"0.5025228",
"0.50188476",
"0.50123036",
"0.49882534",
"0.49808338",
"0.49689457",
"0.4939818",
"0.49388936",
"0.49336597",
"0.49150077",
"0.49102026",
"0.49096918",
"0.49079537",
"0.4902967",
"0.48873803",
"0.48868206",
"0.48743102",
"0.48704925",
"0.48556855",
"0.4848185",
"0.48475033",
"0.48413286",
"0.48390472",
"0.48383975",
"0.48379493",
"0.48378286",
"0.48366773",
"0.48314977",
"0.4830372",
"0.48170036",
"0.48095414",
"0.4808056",
"0.48057732",
"0.47982067",
"0.4789742",
"0.4786897",
"0.47829357",
"0.47764018",
"0.47737557",
"0.47695613",
"0.4767868",
"0.47645652",
"0.47640508",
"0.47616142",
"0.4759872",
"0.47580215",
"0.47536322"
] |
0.6324517
|
3
|
Get the angle of the page / document / receipt Analyzes a photo or image of a document and identifies the rotation angle of the page.
|
def preprocessing_get_page_angle_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_get_page_angle ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_get_page_angle"
end
# resource path
local_var_path = '/ocr/preprocessing/image/get-page-angle'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'GetPageAngleResult')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_get_page_angle\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def angle\n @angle\n end",
"def angle()\n a, c = @view__.angle, @context__\n c ? c.fromDegrees__(a) : a * Processing::GraphicsContext::DEG2RAD__\n end",
"def angle(path)\n io_for(path).angle\n end",
"def preprocessing_get_page_angle(image_file, opts = {})\n data, _status_code, _headers = preprocessing_get_page_angle_with_http_info(image_file, opts)\n data\n end",
"def angle\r\n self.data.map(&:angle)\r\n end",
"def angle\n Math.atan2(@y, @x)\n end",
"def angle\n v = to_vec\n if v[1] == 0.0\n nil\n else\n v.angle\n end\n end",
"def angle\n Math.atan2( @y, @x )\n end",
"def get_rotation\n return @rotation\n end",
"def angle\n rad / Math::PI * 180\n end",
"def angle\n ns = norm\n x_ = @x / ns\n y_ = @y / ns\n\n Math.atan2(x_, y_)\n end",
"def angle_of_specified_radius\n @angle_of_radius\n end",
"def angle_deg\n angle * RAD_TO_DEG\n end",
"def angle(p)\n Math.atan2(p.y - self.y, p.x - self.x)\n end",
"def angle_diff(angle1, angle2)\n end",
"def calculate_orientation\n x, y = @components.values\n if x.pos? and y.zero?\n 0.deg\n elsif x.zero? and y.pos?\n 90.deg\n elsif x.neg? and y.zero?\n 180.deg\n elsif x.zero? and y.neg?\n 270.deg\n elsif x.pos? and y.pos?\n Math.atan( y/x ).rad # Will return an Angle object (with the property \"degrees\")\n elsif x.neg? and y.pos?\n angle = Math.atan( y/x.abs ).rad\n (180 - angle.deg).deg # Will return an Angle object (with the property \"degrees\")\n elsif x.neg? and y.neg?\n angle = Math.atan( y.abs/x.abs ).rad\n (180 + angle.deg).deg # Will return an Angle object (with the property \"degrees\")\n elsif x.pos? and y.neg?\n angle = Math.atan( y.abs/x ).rad\n (360 - angle.deg).deg\n end\n end",
"def radians\n Science::Angle.new(self, :radians)\n end",
"def angle(*args)\n Math.acos(self.dot(*args))\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def calc_angle(hours, minutes)\n angel = (minutes * 6 - (hours * 60 + minutes) * 0.5).abs\n if angel > 180\n 360 - angel.abs\n else\n angel.abs\n end\nend",
"def angle_to(key)\n p1 = {\n x: (row_offset.to_f)+((width)/2),\n y: (row.number.to_f)-((height)/2)+(height)\n }\n\n p2 = {\n x: (key.row_offset.to_f)+((key.width)/2),\n y: (key.row.number.to_f)-((key.height)/2)+(key.height)\n }\n\n Math.atan2(p2[:x] - p1[:x], p2[:y] - p1[:y]) * 180 / Math::PI\n end",
"def radians\n self * 180 / Math::PI\n end",
"def angle_a\n Angle.new(\n self,\n :a,\n (\n (\n Math.acos((b**2 + c**2 - a**2) / (2.0 * b * c)) * 180\n ) / Math::PI\n )\n )\n end",
"def orientation \n @position - @prev_position\n end",
"def pdf_to_sign\n _get_pdf_to_sign\n end",
"def angle_at(point)\n Point.angle(centre, point)\n end",
"def radian_angle\n @angle * Math::PI / 180.0\n end",
"def angle_between(p1, p2)\n vect_p1 = p1 - self\n vect_p2 = p2 - self\n\n theta = vect_p1.polar - vect_p2.polar\n theta += 360.0 if theta < 0.0\n theta = 360.0 - theta if theta > 180.0\n return theta\n end",
"def angles_diff(a1, a2)\n diff = a2 - a1\n while diff > Math::PI\n diff -= 2.0 * Math::PI\n end\n while diff < -Math::PI\n diff += 2.0 * Math::PI\n end\n diff\n end",
"def calculate_radians\n if x_length == 0 || y_length == 0\n angle_to_start_of_quadrant\n else\n case angle_to_end_of_quadrant\n when DEGREES_90\n angle_ignoring_quadrant\n when DEGREES_180\n DEGREES_180 - angle_ignoring_quadrant\n when DEGREES_270\n DEGREES_180 + angle_ignoring_quadrant\n else\n DEGREES_360 - angle_ignoring_quadrant\n end\n end\n end",
"def getAngle(c1,c2)\n x = c2[0] - c1[0]\n y = c2[1] - c1[1]\n x = x <= -180 ? x + 360 : x\n x = x >= 180 ? x - 360 : x\n\n a = Math.atan2(y, x)\n rescue\n p \"Error x=#{x}, y=#{y} sq= #{Math.sqrt(x*x+y*y)} rat=#{x / Math.sqrt(x*x+y*y)}\"\n raise Error\n end",
"def angle(x1, y1, x2, y2)\n end",
"def required_rotation_for_upright_display\n required_rotation_orientation_in_degrees = (360 - self.orientation) % 360\n return required_rotation_orientation_in_degrees\n end",
"def start_angle\n end",
"def rotate angle\n position = \"#{@placement[:s]}x#{@placement[:s]}+#{@placement[:x]}+#{@placement[:y]}\"\n @image.run_command(\"convert\", @image.path, \"-rotate #{360 - angle}\", @image.path)\n @image.run_command(\"convert\", @image.path, \"-gravity Center -crop #{position}\", @image.path)\n end",
"def get_degree note\n relative_note = note - @tonic # we are only concerned with the note relative to the tonic\n octave = (relative_note.to_i / 12) - 1\n index = @intervals.index(@intervals.find{|n| n >= relative_note % 12})\n return \"#{((octave + 1) * @intervals.size) + 7}#\" unless index # if index is nil, it means note is a sharpened 7th index... we add 1 to octave to account for the -1st octave\n degree = index + 1\n approximate_degree = ((octave + 1) * 7) + degree\n accidental = ACCIDENTALS[relative_note - (((octave + 1) * 12) + @intervals[index])]\n return \"#{approximate_degree}#{accidental}\"\n end",
"def angle_from_input\n\n return if @path.size < 2\n return unless @active_controller.is_a? Symbol\n\n i = @active_controller == :start ? 0 : 1\n corner = @path[-i]\n ref_vector = @path[-i] - @path[1 - 3 * i]\n input_vector = corner - @ip.position\n return unless input_vector.valid?\n return if input_vector.parallel? Z_AXIS\n return if input_vector.parallel? ref_vector\n\n angle = -(MyGeom.angle_in_plane input_vector, ref_vector)\n angle -= GRAPHICAL_ANGLES[i]\n angle = ((angle+90.degrees)%180.degrees)-90.degrees\n\n @end_angles[i] = angle\n\n end",
"def rotate(angle, x, y, &block)\n cur_page.rotate(angle, x, y, &block)\n end",
"def calc_angle(x1, y1, x2, y2)\r\n# - - - - - - - - - - - - - - - - - - - -\r\n if (x1 == x2)\r\n if (y2 >= y1)\r\n return 0\r\n else\r\n return 180\r\n end #else\r\n elsif (y1 == y2)\r\n if (x2 >= x1)\r\n return 90\r\n else\r\n return 270\r\n end #else\r\n else\r\n x1 = x1 + 0.0 # force to be floating point\r\n x2 = x2 + 0.0 # force to floating point\r\n slope = (y2-y1) / (x2-x1)\r\n radians = Math.atan(slope)\r\n degrees = conv_radian_to_degree(radians)\r\n # Handle Adjusting Quadrent\r\n if ((x2 > x1) && (y2 > y1))\r\n # Quadrent 1;\r\n degrees = degrees\r\n elsif ((x2 > x1) && (y2 < y1))\r\n # Quadrent 2\r\n degrees = 90 - degrees;\r\n elsif ((x2 < x1) && (y2 < y1))\r\n # Quadrent 3\r\n degrees = 270 - degrees\r\n else\r\n # must be Quadrent 4\r\n degrees = 270 - degrees\r\n end # else\r\n end # else\r\n return degrees\r\nend",
"def angle_delta(angle1, angle2)\n \t delta = (angle1 - angle2).abs\n \t if delta >= Math::PI\n \t delta = (((2 * Math::PI) - angle1) + angle2).abs\n \t end\n \t return delta\n \tend",
"def angle_from other_point\n Geometry.angle_from self, other_point\n end",
"def norm_angle(angle)\n while angle < 0; angle += Const::PI2; end\n while angle > Const::PI2; angle -= Const::PI2; end\n return angle\n rescue => e\n raise\n end",
"def convert_to_radians(degrees)\n degrees * PI / 180\nend",
"def other_angle(a, b)\n 180 - (a + b)\nend",
"def degrees\n self * Math::PI / 180\n end",
"def calc_point_rotated_abs(x,y, angle)\r\n# - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n curr_angle = calc_angle(0,0,x,y)\r\n rel_amt = angle - curr_angle\r\n return calc_point_rotate_relative(x,y,rel_amt)\r\nend",
"def other_angle(a, b)\n 180 - (a + b)\nend",
"def page_size\n page_size = @reader.crop_box(1)\n if @reader.page_rotation(1) % 180 == 0\n [page_size.width, page_size.height]\n else\n [page_size.height, page_size.width]\n end\n end",
"def aperture\n f = image_exif[\"FNumber\"]\n return nil if f.blank?\n (Rational(*(f.split('/').map( &:to_i )))).to_f\n end",
"def is_angle?(); @type == GRT_ANGLE; end",
"def angle_rads \n\t\t\t2.0 * Math.atan2( self.vec.mag, self.scalar ) \n\t\tend",
"def line_angle(p1,p2)\n v1 = RBA::DPoint.new(1,0)\n v2 = p2-p1\n return vector_angle(v1,v2)\n end",
"def orientation\n p1, p2, p3 = *convex_sub_polygon\n det = (p2[0]-p1[0])*(p3[1]-p1[1]) - (p3[0]-p1[0])*(p2[1]-p1[1])\n @orientation ||= (det < 0)? 1 : -1\n end",
"def yaw\n to_euler[0]\n end",
"def anglecw\n 360 - angle\n end",
"def to_radians\n self * Math::PI.fdiv(180)\n end",
"def angle_to body\n dx = body.x - self.x\n dy = body.y - self.y\n\n (R2D * Math.atan2(dy, dx)).degrees\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def angles\n [angle_a, angle_b, angle_c]\n end",
"def rotate(angle_x = 0, angle_y = 0, angle_z = 0)\n\t\tc = 0; cx = 0; cy = 0; cz = 0\n\t\t# get middle point\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tcx += b[0]\n\t\t\t\tcy += b[1]\n\t\t\t\tcz += b[2]\n\t\t\t\tc +=1\n\t\t\tend\n\t\tend\n\t\tcx /= c; cy /= c; cz /= c\n\t\t# rotate points\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tx = b[0]; y = b[1]; z = b[2]\n\n\t\t\t\tx, y, z = rotate_point(x, y, z, cx, cy, cz, angle_x, angle_y, angle_z)\n\n\t\t\t\tb[0] = x; b[1] = y; b[2] = z\n\t\t\tend\n\t\tend\n\tend",
"def rotate(angle, around_x=0, around_y=0, &rendering_code); end",
"def degrees\n self * Math::PI / 180.0\n end",
"def determine_angle(angle, range)\n range.include?(angle) ? angle.to_f : angle.divmod(MAX_DEGREE_RANGE).last\nend",
"def /(other)\n return self.class.radians(@angle / other)\n end",
"def yaw \n\t\t\t# tan(yaw) = 2(xy+wz) / (w^2 + x^2 - y^2 - z^2)\n\t\t\tx = @elem[X]; y = @elem[Y]; z = @elem[Z]; w = @elem[W]\n\t\t\treturn Math::atan( (2 * (x*y + w*z)) / (w**2 + x**2 - y**2 - z**2) )\n\t\tend",
"def normalize_heading(angle)\n \t return angle % (2 * Math::PI)\n \tend",
"def rotations\n self.to_s.rotations.collect { |s| s.to_i }\n end",
"def cur_angle\n MSPhysics::Newton::Hinge.get_cur_angle(@address)\n end",
"def angle_between(vector2)\n end",
"def cur_angle\n MSPhysics::Newton::Corkscrew.get_cur_angle(@address)\n end",
"def angle_equation_of_time() \r\n delta_orbit() + delta_oblique()\r\n end",
"def getGeoAngle(c1,c2)\n x = c2[0] - c1[0]\n y = c2[1] - c1[1]\n y = y <= -180 ? y+360 : y\n y = y >= 180 ? y-360 : y\n\n ca = getCentralAngle(c1,c2)\n dist = EARTH_RADIUS_FEET * ca\n ca1 = getCentralAngle(c1,[c2[0],c1[1]])\n dist1 = EARTH_RADIUS_FEET * ca1 * sign(x)\n ca2 = getCentralAngle(c2,[c2[0],c1[1]])\n dist2 = EARTH_RADIUS_FEET * ca2 * sign(y)\n\n angle = Math.atan2(dist2,dist1)\n end",
"def get_angle(vertices_hash)\n raise 'not circular enough for this call' if !circular\n t_v1, t_v2 = translate_edge(vertices_hash)\n dot_product = self.class.get_dot_product(t_v1, t_v2)\n origin = Vertex.new(0,0)\n magnitude_t_v1 = get_distance(origin, t_v1)\n magnitude_t_v2 = get_distance(origin, t_v2)\n cosine = dot_product / (magnitude_t_v1 * magnitude_t_v2)\n Math.acos(cosine)\n end",
"def angle(vector1,vector2)\n\n small = 0.00000001\n undefined = 999999.1\n\n magnitudevector1 = magnitude(vector1)\n magnitudevector2 = magnitude(vector2)\n if (magnitudevector1*magnitudevector2) > (small**2)\n aux = vdot(vector1,vector2)/(magnitudevector1*magnitudevector2)\n if aux.abs> 1.0\n aux = signal(aux) * 1.0\n end\n return Math.acos(aux)\n else\n return undefined\n end\n end",
"def rt_ascen\n radian_to_degree(bigdecimal_atan2(bigdecimal_cos(degree_to_radian(obliquity)) * bigdecimal_sin(degree_to_radian(ec_lon)), bigdecimal_cos(degree_to_radian(ec_lon))))\n end",
"def find_rotation_point(words)\n front_idx = 0\n back_idx = words.length - 1\n \n while front_idx <= back_idx\n middle = ((back_idx - front_idx) / 2) + front_idx\n current = words[middle] \n word_before = (middle - 1 < 0) ? nil : words[middle - 1]\n word_after = words[middle + 1] \n\n last_word = word_after.nil?\n first_word = word_before.nil?\n if first_word\n return middle if current < word_after\n return middle + 1\n elsif last_word \n return middle if current < word_before\n return middle - 1\n elsif current < word_before && current < word_after\n return middle\n end\n if words[middle] < words[0]\n back_idx = middle - 1\n elsif words[middle] > words[0]\n front_idx = middle + 1\n end\n end\n nil\nend",
"def get_annotation page_number, annotation_index\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 if annotation_index == ''\n raise 'annotation index not specified'\n end\n \n str_uri = $product_uri + '/pdf/' + @filename + '/pages/' + page_number.to_s + '/annotations/' + annotation_index.to_s\n str_signed_uri = Aspose::Cloud::Common::Utils.sign(str_uri) \n response_stream = RestClient.get(str_signed_uri, {:accept=>'application/json'})\n \n stream_hash = JSON.parse(response_stream)\n \n return stream_hash['Annotation']\n \n \n rescue Exception=>e\n print e\n end\n end",
"def angle x1, y1, a, m, c\n x2, y2 = project x1, y1, a, m\n line x1, y1, x2, y2, c\n end",
"def atan\n math :atan\n end",
"def to_rad(angle)\n angle * Math::PI / 180\n end",
"def find_rotation_pt(arr)\n return 0 if arr.length == 1 || arr.empty?\n\n mid = arr.length / 2\n return mid if out_of_order?(arr[mid - 1], arr[mid]) == -1\n\n left = find_rotation_pt(arr[0...mid])\n right = find_rotation_pt(arr[mid..-1])\n\n return right > 0 ? mid + right : left\nend",
"def angle_to other_point\n Geometry.angle_to self, other_point\n end",
"def angle_direction(a,b)\n magnitude = angle_difference(a,b)\n if angle_difference(a + 1, b) < magnitude\n magnitude\n else\n -magnitude\n end\n end",
"def ml_Aries() \r\n # jd = @ta * DJC # convert first term back to jdn - J2000\r\n # old terms \t\r\n # angle = (36000.770053608 / DJC + 360) * jd # 36000.770053608 = 0.9856473662862 * DJC\r\n # total = [ -1.0/3.8710000e7, 3.87930e-4, 0, 100.460618375 ].inject(0.0) {|p, a| p * ta[0] + a} + 180 + angle \r\n # newer terms seem to be in arcseconds / 15.0\r\n # 0.0000013, - 0.0000062, 0.0931118, 307.4771600, 8639877.3173760, 24110.5493771\r\n # angle = (35999.4888224 / DJC + 360) * jd \r\n # total = angle + 280.460622404583 +\r\n # @ta[ 0 ] * 1.281154833333 +\r\n # @ta[ 1 ] * 3.87965833333e-4 +\r\n # @ta[ 2 ] * -2.58333333333e-8 +\r\n # @ta[ 3 ] * 5.41666666666e-9\r\n # total = [5.41666666666e-9, -2.58333333333e-8, 3.87965833333e-4, 1.281154833333, 280.460622404583].inject(0.0) {|p, a| p * @ta + a} \r\n # mod_360( angle + total ) * D2R\r\n dt = 67.184 \r\n tt = @ajd + dt / 86400.0#Celes.ut1tt(@ajd, 0, dt)\r\n Celes.gmst06(@ajd, 0, tt, 0) \r\n end",
"def edit_pdf_rotate_all_pages_with_http_info(input_file, rotation_angle, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: EditPdfApi.edit_pdf_rotate_all_pages ...'\n end\n # verify the required parameter 'input_file' is set\n if @api_client.config.client_side_validation && input_file.nil?\n fail ArgumentError, \"Missing the required parameter 'input_file' when calling EditPdfApi.edit_pdf_rotate_all_pages\"\n end\n # verify the required parameter 'rotation_angle' is set\n if @api_client.config.client_side_validation && rotation_angle.nil?\n fail ArgumentError, \"Missing the required parameter 'rotation_angle' when calling EditPdfApi.edit_pdf_rotate_all_pages\"\n end\n # resource path\n local_var_path = '/convert/edit/pdf/pages/rotate/all'\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/octet-stream'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'rotationAngle'] = rotation_angle\n\n # form parameters\n form_params = {}\n form_params['inputFile'] = input_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: EditPdfApi#edit_pdf_rotate_all_pages\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def angle_c\n Angle.new(\n self,\n :c,\n (\n (\n Math.acos((a**2 + b**2 - c**2) / (2.0 * a * b)) * 180\n ) / Math::PI\n )\n )\n end",
"def angle_to(point)\n Ubiquity::Geoformulas.angle self.lat, self.lon, point.lat, point.lon\n end",
"def map_direction_to_angle(dir)\n return $direction_map[dir]\nend",
"def yaw\n @grpc.pan_angle\n end",
"def calculate_heading()\n @heading[:x], @heading[:y] = Params::directional_vector @angle\n end",
"def degrees\n self\n end",
"def rad\n x = self[0]\n y = self[1]\n if x >= 0 && y >= 0\n Math.atan( y.to_f/x )\n elsif x < 0 && y >= 0\n Math::PI + Math.atan( y.to_f/x )\n elsif x < 0 && y < 0\n Math::PI + Math.atan( y.to_f/x )\n else\n 2*Math::PI + Math.atan( y.to_f/x )\n end\n end",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def polar\n theta = 0.0\n if Point.close_to(self.x, 0)\n if self.y > 0\n theta = 90.0\n elsif self.y < 0\n theta = 270.0\n end\n else\n theta = Point.rad2deg(Math.atan(self.y/self.x))\n if self.x < 0.0\n theta += 180.0\n end\n if theta < 0.0\n theta += 360.0\n end\n end\n theta\n end",
"def to_radians(deg)\n deg * Math::PI / 180\n end",
"def angle_delta_oblique() \r\n #al(@ma, @ta, Celes.faom03(@ta)) - ra_Sun()\r\n al_Sun() - ra_Sun() \r\n end",
"def safe_angle(angle)\n if angle < @angle_range.min\n @angle_range.min\n elsif angle > @angle_range.max\n @angle_range.max\n else\n angle\n end\n end",
"def radians(deg)\n deg * Math::PI / 180\n end",
"def to_radians(n)\n r = n * (Math::PI / 180)\n return r\n end",
"def angle_with( vector )\n Math.acos( max(min(udot(vector),MAX_UDOT_PRODUCT), MIN_UDOT_PRODUCT) )\n end"
] |
[
"0.6768921",
"0.63535494",
"0.6324994",
"0.6323119",
"0.61341214",
"0.5917737",
"0.5910855",
"0.5867298",
"0.58424896",
"0.58236796",
"0.5709026",
"0.5654838",
"0.5614643",
"0.55210483",
"0.5494646",
"0.54773164",
"0.5451332",
"0.53925353",
"0.53895533",
"0.53867155",
"0.5365026",
"0.5363826",
"0.5348522",
"0.53464764",
"0.5338479",
"0.53109306",
"0.52845687",
"0.52748597",
"0.5235992",
"0.523579",
"0.5235523",
"0.5208473",
"0.52066946",
"0.5170301",
"0.5157793",
"0.51556146",
"0.51377124",
"0.5118368",
"0.5108311",
"0.5107292",
"0.5100229",
"0.5099745",
"0.5071909",
"0.5067369",
"0.50628793",
"0.5049762",
"0.5047428",
"0.5035709",
"0.503314",
"0.5032556",
"0.50292253",
"0.5027897",
"0.5023106",
"0.50230306",
"0.50174075",
"0.5010785",
"0.49867743",
"0.4979323",
"0.4966629",
"0.49385402",
"0.4937873",
"0.4932064",
"0.49129984",
"0.49087706",
"0.49079645",
"0.49070337",
"0.49020222",
"0.4885541",
"0.48849306",
"0.48726535",
"0.48680925",
"0.48539472",
"0.48462403",
"0.48461518",
"0.48387164",
"0.48383826",
"0.48378077",
"0.48369962",
"0.48368043",
"0.48354256",
"0.4830388",
"0.48291695",
"0.48146358",
"0.48076317",
"0.48064098",
"0.48063013",
"0.47957987",
"0.47875124",
"0.47844166",
"0.4781605",
"0.47753114",
"0.4772111",
"0.47682983",
"0.47653705",
"0.476312",
"0.47618526",
"0.47604746",
"0.47584653",
"0.4756028",
"0.47518882"
] |
0.58898544
|
7
|
Detect and unrotate a document image Detect and unrotate an image of a document (e.g. that was scanned at an angle). Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unrotate(image_file, opts = {})
data, _status_code, _headers = preprocessing_unrotate_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def rotate_image(image)\n\nend",
"def fix_exif_rotation\n manipulate! do |img|\n img.tap(&:auto_orient)\n end\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def fix_exif_rotation\n return unless self.file.content_type.start_with? 'image'\n \n manipulate! do |img|\n img.tap(&:auto_orient)\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def checkrotation(filepath)\n\t# rotate if needed - normally these are 300 wide by 419 high\n\timg = Magick::Image.read(filepath).first\n\n\tif(img.columns > img.rows) # too wide so rotate left\n\t\timg.rotate!(-90)\n\t\timg.write(filepath)\n\tend\t\nend",
"def preprocessing_unrotate_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_advanced_with_http_info(image_file, opts)\n data\n end",
"def scanned_image\n scanned_eligibility\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def rotate\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.rotate(90)\n img.write('public' + @photo.attachment_url)\n end",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def preprocessing_unrotate_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def rotated\n RawImage.new(@image.getRotated())\n end",
"def preprocessing_unskew(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)\n data\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def scanned_image\n scanned_retreat\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def apply_image_transformation?\n true\n end",
"def transform_image # :norobots:\n pass_query_params\n if image = find_or_goto_index(Image, params[:id].to_s)\n if check_permission!(image)\n if params[:op] == 'rotate_left'\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'rotate_right'\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'mirror'\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? or\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_to(:action => 'show_image', :id => image, :params => query_params)\n else\n redirect_to(:action => 'show_image', :id => image, :params => query_params,\n :size => params[:size])\n end\n end\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def transform_pdfs_to_readabilitycleaned_rtf(group)\n pdf_documents = []\n\n # To safely be able to add/remove records, we need real references to the documents\n count = 0\n each_pdf_document(group) do |record|\n # TODO: Check for \"Don't rtf me!\"-tag\n pdf_documents << record.get\n @pdf_to_rtf_log.debug \"Get: '#{record.name}' (#{record.kind})\"\n count += 1\n end\n @pdf_to_rtf_log.debug \"--- #{count} PDFs ---\"\n\n pdf_documents.each do |record|\n transform_a_pdf_to_readabilitycleaned_rtf(record)\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def scanned_image\n scanned_certificate\n end",
"def transform_image\n pass_query_params\n image = find_or_goto_index(Image, params[:id].to_s)\n return unless image\n\n if check_permission!(image)\n case params[:op]\n when \"rotate_left\"\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n when \"rotate_right\"\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n when \"mirror\"\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? ||\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_with_query(action: \"show_image\", id: image)\n else\n redirect_with_query(action: \"show_image\", id: image,\n size: params[:size])\n end\n end",
"def auto_orient\n manipulate! do |image|\n o = image.get('exif-Orientation').to_i rescue nil\n o ||= image.get('exif-ifd0-Orientation').to_i rescue 1\n case o\n when 1\n # Do nothing, everything is peachy\n when 6\n image.rot270\n when 8\n image.rot180\n when 3\n image.rot90\n else\n raise('Invalid value for Orientation: ' + o.to_s)\n end\n image.set('exif-Orientation', '')\n image.set('exif-ifd0-Orientation', '')\n end\n end",
"def rotateAndFlip(image)\n return image.transpose.flip\nend",
"def preprocessing_unskew_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unskew\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def get_image_credit(page_doc)\n\timage_credit = page_doc.css('body center:nth-child(2)')\n\timage_credit.search('.//b')[0].remove\n\timage_credit.search('.//br').remove\n\timage_credit.search('center').remove\n\treturn image_credit.inner_html.strip!\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def rotate angle\n position = \"#{@placement[:s]}x#{@placement[:s]}+#{@placement[:x]}+#{@placement[:y]}\"\n @image.run_command(\"convert\", @image.path, \"-rotate #{360 - angle}\", @image.path)\n @image.run_command(\"convert\", @image.path, \"-gravity Center -crop #{position}\", @image.path)\n end",
"def auto_orient\n manipulate! do |image|\n o = image.get('exif-Orientation').to_i rescue nil\n o ||= image.get('exif-ifd0-Orientation').to_i rescue 1\n case o\n when 1\n # Do nothing, everything is peachy\n when 6\n image.rot270\n when 8\n image.rot180\n when 3\n image.rot90\n else\n raise('Invalid value for Orientation: ' + o.to_s)\n end\n image.set_type GObject::GSTR_TYPE, 'exif-Orientation', ''\n image.set_type GObject::GSTR_TYPE, 'exif-ifd0-Orientation', ''\n end\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def create\n @document = Document.new(document_params)\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when \"English\"\n @translation = EnglishRegistrationCertificate.new()\n @translation.document = @document\n\n #here comes preProcessing and OCR things\n end\n else\n #here should be redirection to document#new\n end\n\n respond_to do |format|\n if @document.save\n params[:document_images]['image'].each do |i|\n @document_image = @document.document_images.create!(:image => i)\n @imageUrl = @document_image.image.current_path\n @imageDimensions = FastImage.size(@imageUrl) #=> [x,y]\n\n #working stuff\n response = Ocr.processDocument(@document.doc_type, @document.language, @document.document_images.load)\n @xmlTranslation = Nokogiri::XML(response)\n\n #\n # Temporary\n #\n @translation.registrationNumber = '1234567'\n @translation.circle = 'ABC 123 kółko'\n @translation.registeredKeeper = \"Andrzej Strzelba\"\n @translation.referenceNumber = \"1234 5678 90\"\n @translation.previousRegisteredKeeper = \"Bartek Walaszek, BFF\"\n @translation.dateOfPurchase = \"20.11.2014\"\n @translation.numberOfPreviousOwners = \"3\"\n @translation.specialNotes = \"Niemiec płakał jak sprzedawał. Niemiec odwoził do granicy!\"\n\n #\n # Here comes the XML parser\n #\n @translation.parseResponse(response)\n\n #\n # BTW. translation variable 4 document is sensless - we have to remove it as soon as possible :: when parsed response will be saved in database (EnglishRegistrationCetificate)\n #\n @document.translation = @xmlTranslation.css(\"value\").text\n\n #\n # @document variables should be set before savin' !!\n #\n\n @document.save\n end\n\n if @translation.save\n\n format.html { redirect_to @document, notice: 'Document was successfully created.' }\n format.json { render action: 'show', status: :created, location: @document }\n else\n @document.destroy\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n else\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_rotate_flipped_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def delete_files\n\t\t\tFileUtils.rm_rf(@clean_image)\n\t\t\tFileUtils.rm_rf(@image) if pdf?\n\t\tend",
"def preprocessing_unrotate_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def rotate_180!\n pixels.reverse!\n self\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def test_delete_unprotect_document\n filename = 'SampleProtectedBlankWordDocument.docx'\n remote_name = 'TestDeleteUnprotectDocument.docx'\n body = ProtectionRequest.new({:Password => 'aspose'})\n\n st_request = PutCreateRequest.new remote_test_folder + test_folder + '/' + remote_name, File.open(local_test_folder + test_folder + '/' + filename, \"r\").read\n @storage_api.put_create st_request\n\n request = DeleteUnprotectDocumentRequest.new remote_name, body, remote_test_folder + test_folder\n result = @words_api.delete_unprotect_document request\n assert_equal 200, result.code\n end",
"def destroy_ipaper_document\n ScribdFu::destroy(ipaper_document) if ipaper_document\n end",
"def imageDeSteg(password, image)\n # Suck in the image\n original_image = Magick::Image.read(image).first\n\n # Initialize the bits array\n bits = []\n\n # For each pixel in the image\n original_image.each_pixel do |pixel, col, row|\n # Set colors to their current value\n red = pixel.red\n green = pixel.green\n blue = pixel.blue\n\n # If the red value for the pixel is odd\n if (red%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the green value for the pixel is odd\n if (green%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the blue value for the pixel is odd\n if (blue%2 == 1)\n bits << 1\n else\n bits << 0\n end\n end\n\n # Initialize the encrypted_length_bits\n encrypted_length_bits = \"\"\n\n # For the first 256 characters in the array\n for counter in (0..255)\n # Append the value to the encrypted_length_bits\n encrypted_length_bits = encrypted_length_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted length bits to a string\n encrypted_length = Stegg.convertBinaryToString(encrypted_length_bits)\n\n # Decrypt the encrypted length\n cipher = Gibberish::AES.new(password)\n length = cipher.decrypt(encrypted_length, :binary => true)\n\n # Initialize the encrypted_data_bits\n encrypted_data_bits = \"\"\n\n # Data starts at 256 and goes through the length\n last_bit = 255 + length.to_i()\n \n # For character 256 through the last bit\n for counter in (256..last_bit)\n # Append the value to the encrypted_data_bits\n encrypted_data_bits = encrypted_data_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted data bits to a string\n encrypted_data = Stegg.convertBinaryToString(encrypted_data_bits)\n\n # Decrypt the encrypted data\n data = cipher.decrypt(encrypted_data, :binary => true)\n\n # Return the data\n return data\n end",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def show\n #@document = Document.find(params[:id])\n #\n # Above line is unnecesary because there is this magic before_action :set_document ... hell yeah\n #\n @documentImages = @document.document_images.load\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when 'English'\n @translation = @document.english_registration_certificate\n #appid = CGI.escape(\"Seeker of words in documents\")\n #passss = CGI.escape(\"IGP0S5KYsUi7WpYCiTa8refF\")\n #\n # Here comes the EACH loop over all the images stored in @documentImages objects - probablu mulpile request :: submitImage\n #\n #filename = @document.image.current_path\n #language = \"English\"\n #url = \"http://#{appid}:#{passss}@cloud.ocrsdk.com\"\n @document.translation\n end\n else\n @translation = EnglishRegistrationCertificate.new()\n end\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def unactive\n @unactive.image\n end",
"def retreat_verification(is_verify)\n retreat_verification = @candidate.retreat_verification\n retreat_verification_params = params[:candidate][:retreat_verification_attributes]\n\n if retreat_verification_params[:remove_retreat_verification_picture] == 'Remove'\n retreat_verification.scanned_image.destroy\n # destroy does not set scanned_retreat_id to nil\n retreat_verification.scanned_retreat_id = nil\n retreat_verification.save!\n else\n setup_file_params(\n retreat_verification_params[:retreat_verification_picture],\n retreat_verification,\n :scanned_retreat_attributes, retreat_verification_params\n )\n end\n event_with_picture_update_private(RetreatVerification, admin_verified: is_verify)\n end",
"def rotate(degrees)\n rsp = @flickr.send_request('flickr.photos.transform.rotate', {:photo_id => self.id, :degrees => degrees}, :post)\n true\n end",
"def clear_rotation_tag(regen_thumbnail = false)\n option = \"-norot\"\n option << \" -rgt\" if regen_thumbnail\n Jhead.call(option, @match, @pattern)\n end",
"def despeckle image\n m_begin \"despeckle\"\n set_variable(image, get_image(image).despeckle)\n m_end \"despeckle\"\n end",
"def image_ocr_photo_recognize_receipt(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_receipt_with_http_info(image_file, opts)\n data\n end",
"def rotate_origo(angle_x = 0, angle_y = 0, angle_z = 0)\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tx = b[0]; y = b[1]; z = b[2]\n\n\t\t\t\tx, y, z = rotate_point(x, y, z, 0, 0, 0, angle_x, angle_y, angle_z)\n\n\t\t\t\tb[0] = x; b[1] = y; b[2] = z\n\t\t\tend\n\t\tend\n\tend",
"def auto_orient\n manipulate! do |img|\n img.auto_orient\n img\n end\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def negate_image\n @image = image.not\n end",
"def maybe_remove(asset)\n # don't need it if we already don't have hocr or textonly_pdf\n return if !asset.hocr && !asset.file_derivatives[:textonly_pdf]\n\n asset.hocr = nil\n # this kithe command will save record to, persisting the hocr=nil,\n # atomically concurrently safely making the change.\n asset.remove_derivatives(:textonly_pdf, allow_other_changes: true)\n end",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def rotate_flip_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def detect_pdf_gcs gcs_source_uri:, gcs_destination_uri:\n # [START vision_text_detection_pdf_gcs]\n # [START vision_text_detection_pdf_gcs_migration]\n # gcs_source_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/example.pdf'\"\n # gcs_destination_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/prefix_'\"\n\n require \"google/cloud/vision\"\n require \"google/cloud/storage\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n operation = image_annotator.document_text_detection(\n image: gcs_source_uri,\n mime_type: \"application/pdf\",\n batch_size: 2,\n destination: gcs_destination_uri,\n async: true\n )\n\n puts \"Waiting for the operation to finish.\"\n operation.wait_until_done!\n # [END vision_text_detection_pdf_gcs_migration]\n\n # Once the request has completed and the output has been\n # written to GCS, we can list all the output files.\n storage = Google::Cloud::Storage.new\n\n bucket_name, prefix = gcs_destination_uri.match(\"gs://([^/]+)/(.+)\").captures\n bucket = storage.bucket bucket_name\n\n # List objects with the given prefix.\n puts \"Output files:\"\n blob_list = bucket.files prefix: prefix\n blob_list.each do |file|\n puts file.name\n end\n\n # Process the first output file from GCS.\n # Since we specified a batch_size of 2, the first response contains\n # the first two pages of the input file.\n output = blob_list[0]\n json_string = output.download\n response = JSON.parse json_string.string\n\n # The actual response for the first page of the input file.\n first_page_response = response[\"responses\"][0]\n annotation = first_page_response[\"fullTextAnnotation\"]\n\n # Here we print the full text from the first page.\n # The response contains more information:\n # annotation/pages/blocks/paragraphs/words/symbols\n # including confidence scores and bounding boxes\n puts \"Full text:\\n#{annotation['text']}\"\n # [END vision_text_detection_pdf_gcs]\nend",
"def rotate_image_right!(albid, imgid)\n img = image(albid, imgid)\n IMagick.rotate_right(_(img[:path]))\n IMagick.rotate_right(_(img[:thumb]))\n true\n end",
"def verify_image(path)\n end",
"def read_image(image_name)\n tempfile = Tempfile.new(image_name)\n tempfile.write @docx_archive.get_input_stream(\"word/media/#{image_name}\").read\n tempfile.close\n tempfile\n end",
"def convert_to_image page_number, image_format\n begin\n \n if page_number == ''\n raise('page number not specified')\n end\n \n if image_format == ''\n raise 'image format not specified'\n end\n \n str_uri = $product_uri + '/pdf/' + @filename + '/pages/' + page_number.to_s + '?format=' + image_format\n str_signed_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n \n response_stream = RestClient.get(str_signed_uri, {:accept=>'application/json'}) \n \n valid_output = Aspose::Cloud::Common::Utils.validate_output(response_stream)\n \n if valid_output == '' \n output_path = $out_put_location + Aspose::Cloud::Common::Utils.get_filename(@filename) + '_' + page_number.to_s + '.' + image_format\n Aspose::Cloud::Common::Utils.save_file(response_stream,output_path)\n return ''\n else\n return valid_output\n end\n \n rescue Exception=>e\n print e \n end \n end",
"def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end",
"def reset\n File.open(@input_path, \"rb\") do |f|\n begin\n tmp = Tempfile.new(\"minimagic\")\n tmp.binmode \n tmp.write(f.read)\n ensure\n tmp.close\n end \n @path = tmp.path\n end\n verify_image(@path)\n self\n end",
"def process!(document); end",
"def build_pdf_object(document)\n color_space =\n case channels\n when 1\n :DeviceGray\n when 3\n :DeviceRGB\n when 4\n :DeviceCMYK\n else\n raise ArgumentError, 'JPG uses an unsupported number of channels'\n end\n\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n ColorSpace: color_space,\n BitsPerComponent: bits,\n Width: width,\n Height: height\n )\n\n # add extra decode params for CMYK images. By swapping the\n # min and max values from the default, we invert the colours. See\n # section 4.8.4 of the spec.\n if color_space == :DeviceCMYK\n obj.data[:Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]\n end\n\n obj.stream << @data\n obj.stream.filters << :DCTDecode\n obj\n end",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end"
] |
[
"0.65515685",
"0.57661265",
"0.57574654",
"0.5617368",
"0.561659",
"0.54309416",
"0.54123574",
"0.5409436",
"0.53968537",
"0.526657",
"0.52456695",
"0.52381593",
"0.51836926",
"0.5181587",
"0.5152635",
"0.5125302",
"0.51029867",
"0.50686276",
"0.5058208",
"0.5053604",
"0.50460905",
"0.502313",
"0.50155926",
"0.49960616",
"0.4995343",
"0.49865216",
"0.49378765",
"0.49198785",
"0.48982525",
"0.48834023",
"0.48742992",
"0.48732683",
"0.4788239",
"0.47866103",
"0.47602385",
"0.47484386",
"0.47465453",
"0.4690136",
"0.46814403",
"0.46698254",
"0.4669788",
"0.46668032",
"0.46662706",
"0.46570674",
"0.4649194",
"0.46206817",
"0.46013",
"0.45889485",
"0.45882526",
"0.45866805",
"0.4582426",
"0.45768774",
"0.45677736",
"0.45412213",
"0.45239946",
"0.4507071",
"0.4504452",
"0.4497031",
"0.44897276",
"0.4485071",
"0.44790804",
"0.44707012",
"0.44656876",
"0.44581112",
"0.44561085",
"0.44433632",
"0.44262153",
"0.44185475",
"0.44118088",
"0.44004416",
"0.43943724",
"0.43640175",
"0.4363619",
"0.4334493",
"0.4329011",
"0.43132177",
"0.43038523",
"0.43030715",
"0.4294753",
"0.42922062",
"0.42820334",
"0.42803624",
"0.42750847",
"0.4273461",
"0.42695534",
"0.42610642",
"0.4255563",
"0.4247848",
"0.42428243",
"0.42405275",
"0.42395395",
"0.42307708",
"0.42255485",
"0.4224736",
"0.4221617",
"0.42095795",
"0.42084932",
"0.4204943",
"0.42032608",
"0.41910917"
] |
0.52896756
|
9
|
Detect and unrotate a document image Detect and unrotate an image of a document (e.g. that was scanned at an angle). Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unrotate_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate"
end
# resource path
local_var_path = '/ocr/preprocessing/image/unrotate'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_unrotate\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def rotate_image(image)\n\nend",
"def fix_exif_rotation\n manipulate! do |img|\n img.tap(&:auto_orient)\n end\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def preprocessing_unrotate(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_with_http_info(image_file, opts)\n data\n end",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def fix_exif_rotation\n return unless self.file.content_type.start_with? 'image'\n \n manipulate! do |img|\n img.tap(&:auto_orient)\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def checkrotation(filepath)\n\t# rotate if needed - normally these are 300 wide by 419 high\n\timg = Magick::Image.read(filepath).first\n\n\tif(img.columns > img.rows) # too wide so rotate left\n\t\timg.rotate!(-90)\n\t\timg.write(filepath)\n\tend\t\nend",
"def preprocessing_unrotate_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_advanced_with_http_info(image_file, opts)\n data\n end",
"def scanned_image\n scanned_eligibility\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def rotate\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.rotate(90)\n img.write('public' + @photo.attachment_url)\n end",
"def rotated\n RawImage.new(@image.getRotated())\n end",
"def preprocessing_unskew(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)\n data\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def scanned_image\n scanned_retreat\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def apply_image_transformation?\n true\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def transform_image # :norobots:\n pass_query_params\n if image = find_or_goto_index(Image, params[:id].to_s)\n if check_permission!(image)\n if params[:op] == 'rotate_left'\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'rotate_right'\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'mirror'\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? or\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_to(:action => 'show_image', :id => image, :params => query_params)\n else\n redirect_to(:action => 'show_image', :id => image, :params => query_params,\n :size => params[:size])\n end\n end\n end",
"def transform_pdfs_to_readabilitycleaned_rtf(group)\n pdf_documents = []\n\n # To safely be able to add/remove records, we need real references to the documents\n count = 0\n each_pdf_document(group) do |record|\n # TODO: Check for \"Don't rtf me!\"-tag\n pdf_documents << record.get\n @pdf_to_rtf_log.debug \"Get: '#{record.name}' (#{record.kind})\"\n count += 1\n end\n @pdf_to_rtf_log.debug \"--- #{count} PDFs ---\"\n\n pdf_documents.each do |record|\n transform_a_pdf_to_readabilitycleaned_rtf(record)\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def scanned_image\n scanned_certificate\n end",
"def transform_image\n pass_query_params\n image = find_or_goto_index(Image, params[:id].to_s)\n return unless image\n\n if check_permission!(image)\n case params[:op]\n when \"rotate_left\"\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n when \"rotate_right\"\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n when \"mirror\"\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? ||\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_with_query(action: \"show_image\", id: image)\n else\n redirect_with_query(action: \"show_image\", id: image,\n size: params[:size])\n end\n end",
"def auto_orient\n manipulate! do |image|\n o = image.get('exif-Orientation').to_i rescue nil\n o ||= image.get('exif-ifd0-Orientation').to_i rescue 1\n case o\n when 1\n # Do nothing, everything is peachy\n when 6\n image.rot270\n when 8\n image.rot180\n when 3\n image.rot90\n else\n raise('Invalid value for Orientation: ' + o.to_s)\n end\n image.set('exif-Orientation', '')\n image.set('exif-ifd0-Orientation', '')\n end\n end",
"def rotateAndFlip(image)\n return image.transpose.flip\nend",
"def preprocessing_unskew_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unskew\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def get_image_credit(page_doc)\n\timage_credit = page_doc.css('body center:nth-child(2)')\n\timage_credit.search('.//b')[0].remove\n\timage_credit.search('.//br').remove\n\timage_credit.search('center').remove\n\treturn image_credit.inner_html.strip!\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def rotate angle\n position = \"#{@placement[:s]}x#{@placement[:s]}+#{@placement[:x]}+#{@placement[:y]}\"\n @image.run_command(\"convert\", @image.path, \"-rotate #{360 - angle}\", @image.path)\n @image.run_command(\"convert\", @image.path, \"-gravity Center -crop #{position}\", @image.path)\n end",
"def auto_orient\n manipulate! do |image|\n o = image.get('exif-Orientation').to_i rescue nil\n o ||= image.get('exif-ifd0-Orientation').to_i rescue 1\n case o\n when 1\n # Do nothing, everything is peachy\n when 6\n image.rot270\n when 8\n image.rot180\n when 3\n image.rot90\n else\n raise('Invalid value for Orientation: ' + o.to_s)\n end\n image.set_type GObject::GSTR_TYPE, 'exif-Orientation', ''\n image.set_type GObject::GSTR_TYPE, 'exif-ifd0-Orientation', ''\n end\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def create\n @document = Document.new(document_params)\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when \"English\"\n @translation = EnglishRegistrationCertificate.new()\n @translation.document = @document\n\n #here comes preProcessing and OCR things\n end\n else\n #here should be redirection to document#new\n end\n\n respond_to do |format|\n if @document.save\n params[:document_images]['image'].each do |i|\n @document_image = @document.document_images.create!(:image => i)\n @imageUrl = @document_image.image.current_path\n @imageDimensions = FastImage.size(@imageUrl) #=> [x,y]\n\n #working stuff\n response = Ocr.processDocument(@document.doc_type, @document.language, @document.document_images.load)\n @xmlTranslation = Nokogiri::XML(response)\n\n #\n # Temporary\n #\n @translation.registrationNumber = '1234567'\n @translation.circle = 'ABC 123 kółko'\n @translation.registeredKeeper = \"Andrzej Strzelba\"\n @translation.referenceNumber = \"1234 5678 90\"\n @translation.previousRegisteredKeeper = \"Bartek Walaszek, BFF\"\n @translation.dateOfPurchase = \"20.11.2014\"\n @translation.numberOfPreviousOwners = \"3\"\n @translation.specialNotes = \"Niemiec płakał jak sprzedawał. Niemiec odwoził do granicy!\"\n\n #\n # Here comes the XML parser\n #\n @translation.parseResponse(response)\n\n #\n # BTW. translation variable 4 document is sensless - we have to remove it as soon as possible :: when parsed response will be saved in database (EnglishRegistrationCetificate)\n #\n @document.translation = @xmlTranslation.css(\"value\").text\n\n #\n # @document variables should be set before savin' !!\n #\n\n @document.save\n end\n\n if @translation.save\n\n format.html { redirect_to @document, notice: 'Document was successfully created.' }\n format.json { render action: 'show', status: :created, location: @document }\n else\n @document.destroy\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n else\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_rotate_flipped_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def delete_files\n\t\t\tFileUtils.rm_rf(@clean_image)\n\t\t\tFileUtils.rm_rf(@image) if pdf?\n\t\tend",
"def preprocessing_unrotate_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def rotate_180!\n pixels.reverse!\n self\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def test_delete_unprotect_document\n filename = 'SampleProtectedBlankWordDocument.docx'\n remote_name = 'TestDeleteUnprotectDocument.docx'\n body = ProtectionRequest.new({:Password => 'aspose'})\n\n st_request = PutCreateRequest.new remote_test_folder + test_folder + '/' + remote_name, File.open(local_test_folder + test_folder + '/' + filename, \"r\").read\n @storage_api.put_create st_request\n\n request = DeleteUnprotectDocumentRequest.new remote_name, body, remote_test_folder + test_folder\n result = @words_api.delete_unprotect_document request\n assert_equal 200, result.code\n end",
"def destroy_ipaper_document\n ScribdFu::destroy(ipaper_document) if ipaper_document\n end",
"def imageDeSteg(password, image)\n # Suck in the image\n original_image = Magick::Image.read(image).first\n\n # Initialize the bits array\n bits = []\n\n # For each pixel in the image\n original_image.each_pixel do |pixel, col, row|\n # Set colors to their current value\n red = pixel.red\n green = pixel.green\n blue = pixel.blue\n\n # If the red value for the pixel is odd\n if (red%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the green value for the pixel is odd\n if (green%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the blue value for the pixel is odd\n if (blue%2 == 1)\n bits << 1\n else\n bits << 0\n end\n end\n\n # Initialize the encrypted_length_bits\n encrypted_length_bits = \"\"\n\n # For the first 256 characters in the array\n for counter in (0..255)\n # Append the value to the encrypted_length_bits\n encrypted_length_bits = encrypted_length_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted length bits to a string\n encrypted_length = Stegg.convertBinaryToString(encrypted_length_bits)\n\n # Decrypt the encrypted length\n cipher = Gibberish::AES.new(password)\n length = cipher.decrypt(encrypted_length, :binary => true)\n\n # Initialize the encrypted_data_bits\n encrypted_data_bits = \"\"\n\n # Data starts at 256 and goes through the length\n last_bit = 255 + length.to_i()\n \n # For character 256 through the last bit\n for counter in (256..last_bit)\n # Append the value to the encrypted_data_bits\n encrypted_data_bits = encrypted_data_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted data bits to a string\n encrypted_data = Stegg.convertBinaryToString(encrypted_data_bits)\n\n # Decrypt the encrypted data\n data = cipher.decrypt(encrypted_data, :binary => true)\n\n # Return the data\n return data\n end",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def show\n #@document = Document.find(params[:id])\n #\n # Above line is unnecesary because there is this magic before_action :set_document ... hell yeah\n #\n @documentImages = @document.document_images.load\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when 'English'\n @translation = @document.english_registration_certificate\n #appid = CGI.escape(\"Seeker of words in documents\")\n #passss = CGI.escape(\"IGP0S5KYsUi7WpYCiTa8refF\")\n #\n # Here comes the EACH loop over all the images stored in @documentImages objects - probablu mulpile request :: submitImage\n #\n #filename = @document.image.current_path\n #language = \"English\"\n #url = \"http://#{appid}:#{passss}@cloud.ocrsdk.com\"\n @document.translation\n end\n else\n @translation = EnglishRegistrationCertificate.new()\n end\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def unactive\n @unactive.image\n end",
"def retreat_verification(is_verify)\n retreat_verification = @candidate.retreat_verification\n retreat_verification_params = params[:candidate][:retreat_verification_attributes]\n\n if retreat_verification_params[:remove_retreat_verification_picture] == 'Remove'\n retreat_verification.scanned_image.destroy\n # destroy does not set scanned_retreat_id to nil\n retreat_verification.scanned_retreat_id = nil\n retreat_verification.save!\n else\n setup_file_params(\n retreat_verification_params[:retreat_verification_picture],\n retreat_verification,\n :scanned_retreat_attributes, retreat_verification_params\n )\n end\n event_with_picture_update_private(RetreatVerification, admin_verified: is_verify)\n end",
"def rotate(degrees)\n rsp = @flickr.send_request('flickr.photos.transform.rotate', {:photo_id => self.id, :degrees => degrees}, :post)\n true\n end",
"def clear_rotation_tag(regen_thumbnail = false)\n option = \"-norot\"\n option << \" -rgt\" if regen_thumbnail\n Jhead.call(option, @match, @pattern)\n end",
"def despeckle image\n m_begin \"despeckle\"\n set_variable(image, get_image(image).despeckle)\n m_end \"despeckle\"\n end",
"def image_ocr_photo_recognize_receipt(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_receipt_with_http_info(image_file, opts)\n data\n end",
"def rotate_origo(angle_x = 0, angle_y = 0, angle_z = 0)\n\t\t@rect.each do |a|\n\t\t\ta.each do |b|\n\t\t\t\tx = b[0]; y = b[1]; z = b[2]\n\n\t\t\t\tx, y, z = rotate_point(x, y, z, 0, 0, 0, angle_x, angle_y, angle_z)\n\n\t\t\t\tb[0] = x; b[1] = y; b[2] = z\n\t\t\tend\n\t\tend\n\tend",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def auto_orient\n manipulate! do |img|\n img.auto_orient\n img\n end\n end",
"def negate_image\n @image = image.not\n end",
"def maybe_remove(asset)\n # don't need it if we already don't have hocr or textonly_pdf\n return if !asset.hocr && !asset.file_derivatives[:textonly_pdf]\n\n asset.hocr = nil\n # this kithe command will save record to, persisting the hocr=nil,\n # atomically concurrently safely making the change.\n asset.remove_derivatives(:textonly_pdf, allow_other_changes: true)\n end",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def rotate_flip_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def detect_pdf_gcs gcs_source_uri:, gcs_destination_uri:\n # [START vision_text_detection_pdf_gcs]\n # [START vision_text_detection_pdf_gcs_migration]\n # gcs_source_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/example.pdf'\"\n # gcs_destination_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/prefix_'\"\n\n require \"google/cloud/vision\"\n require \"google/cloud/storage\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n operation = image_annotator.document_text_detection(\n image: gcs_source_uri,\n mime_type: \"application/pdf\",\n batch_size: 2,\n destination: gcs_destination_uri,\n async: true\n )\n\n puts \"Waiting for the operation to finish.\"\n operation.wait_until_done!\n # [END vision_text_detection_pdf_gcs_migration]\n\n # Once the request has completed and the output has been\n # written to GCS, we can list all the output files.\n storage = Google::Cloud::Storage.new\n\n bucket_name, prefix = gcs_destination_uri.match(\"gs://([^/]+)/(.+)\").captures\n bucket = storage.bucket bucket_name\n\n # List objects with the given prefix.\n puts \"Output files:\"\n blob_list = bucket.files prefix: prefix\n blob_list.each do |file|\n puts file.name\n end\n\n # Process the first output file from GCS.\n # Since we specified a batch_size of 2, the first response contains\n # the first two pages of the input file.\n output = blob_list[0]\n json_string = output.download\n response = JSON.parse json_string.string\n\n # The actual response for the first page of the input file.\n first_page_response = response[\"responses\"][0]\n annotation = first_page_response[\"fullTextAnnotation\"]\n\n # Here we print the full text from the first page.\n # The response contains more information:\n # annotation/pages/blocks/paragraphs/words/symbols\n # including confidence scores and bounding boxes\n puts \"Full text:\\n#{annotation['text']}\"\n # [END vision_text_detection_pdf_gcs]\nend",
"def rotate_image_right!(albid, imgid)\n img = image(albid, imgid)\n IMagick.rotate_right(_(img[:path]))\n IMagick.rotate_right(_(img[:thumb]))\n true\n end",
"def verify_image(path)\n end",
"def read_image(image_name)\n tempfile = Tempfile.new(image_name)\n tempfile.write @docx_archive.get_input_stream(\"word/media/#{image_name}\").read\n tempfile.close\n tempfile\n end",
"def convert_to_image page_number, image_format\n begin\n \n if page_number == ''\n raise('page number not specified')\n end\n \n if image_format == ''\n raise 'image format not specified'\n end\n \n str_uri = $product_uri + '/pdf/' + @filename + '/pages/' + page_number.to_s + '?format=' + image_format\n str_signed_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n \n response_stream = RestClient.get(str_signed_uri, {:accept=>'application/json'}) \n \n valid_output = Aspose::Cloud::Common::Utils.validate_output(response_stream)\n \n if valid_output == '' \n output_path = $out_put_location + Aspose::Cloud::Common::Utils.get_filename(@filename) + '_' + page_number.to_s + '.' + image_format\n Aspose::Cloud::Common::Utils.save_file(response_stream,output_path)\n return ''\n else\n return valid_output\n end\n \n rescue Exception=>e\n print e \n end \n end",
"def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end",
"def reset\n File.open(@input_path, \"rb\") do |f|\n begin\n tmp = Tempfile.new(\"minimagic\")\n tmp.binmode \n tmp.write(f.read)\n ensure\n tmp.close\n end \n @path = tmp.path\n end\n verify_image(@path)\n self\n end",
"def process!(document); end",
"def build_pdf_object(document)\n color_space =\n case channels\n when 1\n :DeviceGray\n when 3\n :DeviceRGB\n when 4\n :DeviceCMYK\n else\n raise ArgumentError, 'JPG uses an unsupported number of channels'\n end\n\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n ColorSpace: color_space,\n BitsPerComponent: bits,\n Width: width,\n Height: height\n )\n\n # add extra decode params for CMYK images. By swapping the\n # min and max values from the default, we invert the colours. See\n # section 4.8.4 of the spec.\n if color_space == :DeviceCMYK\n obj.data[:Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]\n end\n\n obj.stream << @data\n obj.stream.filters << :DCTDecode\n obj\n end",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end"
] |
[
"0.6553658",
"0.57664627",
"0.5758398",
"0.56170475",
"0.56168735",
"0.54295",
"0.54106456",
"0.5407409",
"0.5397315",
"0.5290326",
"0.52672964",
"0.5245596",
"0.5235849",
"0.5181416",
"0.51793104",
"0.5151516",
"0.5123107",
"0.51022315",
"0.5069915",
"0.5056831",
"0.5054204",
"0.5046892",
"0.5022804",
"0.5016162",
"0.49954164",
"0.49932835",
"0.493627",
"0.49215025",
"0.48978797",
"0.48838103",
"0.4873488",
"0.4873119",
"0.47886798",
"0.47865304",
"0.47596222",
"0.4746859",
"0.4746053",
"0.46896264",
"0.46807763",
"0.4670057",
"0.46691507",
"0.46676576",
"0.4663791",
"0.46549577",
"0.46480593",
"0.46217823",
"0.4601531",
"0.4589015",
"0.45887557",
"0.4586753",
"0.45809627",
"0.45746267",
"0.45662794",
"0.45411277",
"0.45237723",
"0.4506327",
"0.45032609",
"0.44970712",
"0.44881317",
"0.4483491",
"0.4479925",
"0.44709647",
"0.44646668",
"0.44582003",
"0.4454275",
"0.4443522",
"0.442466",
"0.44192734",
"0.44125402",
"0.44003364",
"0.43933317",
"0.43631703",
"0.4362989",
"0.43344727",
"0.432934",
"0.43146402",
"0.43039918",
"0.43007007",
"0.4294189",
"0.42925397",
"0.42826322",
"0.4278805",
"0.42733797",
"0.42725942",
"0.42707336",
"0.4263004",
"0.42552704",
"0.4246061",
"0.42423695",
"0.4240402",
"0.42371556",
"0.42305654",
"0.42238617",
"0.42231613",
"0.4221943",
"0.42092988",
"0.42087248",
"0.42043924",
"0.42024994",
"0.41919664"
] |
0.49868545
|
26
|
Detect and unrotate a document image (advanced) Detect and unrotate an image of a document (e.g. that was scanned at an angle) using deep learning. Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unrotate_advanced(image_file, opts = {})
data, _status_code, _headers = preprocessing_unrotate_advanced_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def rotate_image(image)\n\nend",
"def scanned_image\n scanned_eligibility\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def preprocessing_unrotate(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_with_http_info(image_file, opts)\n data\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def scanned_image\n scanned_retreat\n end",
"def preprocessing_unrotate_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def apply_image_transformation?\n true\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.tap(&:auto_orient)\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def transform_image # :norobots:\n pass_query_params\n if image = find_or_goto_index(Image, params[:id].to_s)\n if check_permission!(image)\n if params[:op] == 'rotate_left'\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'rotate_right'\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'mirror'\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? or\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_to(:action => 'show_image', :id => image, :params => query_params)\n else\n redirect_to(:action => 'show_image', :id => image, :params => query_params,\n :size => params[:size])\n end\n end\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def preprocessing_unskew(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)\n data\n end",
"def show\n #@document = Document.find(params[:id])\n #\n # Above line is unnecesary because there is this magic before_action :set_document ... hell yeah\n #\n @documentImages = @document.document_images.load\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when 'English'\n @translation = @document.english_registration_certificate\n #appid = CGI.escape(\"Seeker of words in documents\")\n #passss = CGI.escape(\"IGP0S5KYsUi7WpYCiTa8refF\")\n #\n # Here comes the EACH loop over all the images stored in @documentImages objects - probablu mulpile request :: submitImage\n #\n #filename = @document.image.current_path\n #language = \"English\"\n #url = \"http://#{appid}:#{passss}@cloud.ocrsdk.com\"\n @document.translation\n end\n else\n @translation = EnglishRegistrationCertificate.new()\n end\n end",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def scanned_image\n scanned_certificate\n end",
"def preprocessing_unrotate_advanced_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate_advanced ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate_advanced\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate/advanced'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate_advanced\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def rotate\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.rotate(90)\n img.write('public' + @photo.attachment_url)\n end",
"def fix_exif_rotation\n return unless self.file.content_type.start_with? 'image'\n \n manipulate! do |img|\n img.tap(&:auto_orient)\n img = yield(img) if block_given?\n img\n end\n end",
"def transform_image\n pass_query_params\n image = find_or_goto_index(Image, params[:id].to_s)\n return unless image\n\n if check_permission!(image)\n case params[:op]\n when \"rotate_left\"\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n when \"rotate_right\"\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n when \"mirror\"\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? ||\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_with_query(action: \"show_image\", id: image)\n else\n redirect_with_query(action: \"show_image\", id: image,\n size: params[:size])\n end\n end",
"def preprocessing_unskew_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unskew\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def checkrotation(filepath)\n\t# rotate if needed - normally these are 300 wide by 419 high\n\timg = Magick::Image.read(filepath).first\n\n\tif(img.columns > img.rows) # too wide so rotate left\n\t\timg.rotate!(-90)\n\t\timg.write(filepath)\n\tend\t\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def create\n @document = Document.new(document_params)\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when \"English\"\n @translation = EnglishRegistrationCertificate.new()\n @translation.document = @document\n\n #here comes preProcessing and OCR things\n end\n else\n #here should be redirection to document#new\n end\n\n respond_to do |format|\n if @document.save\n params[:document_images]['image'].each do |i|\n @document_image = @document.document_images.create!(:image => i)\n @imageUrl = @document_image.image.current_path\n @imageDimensions = FastImage.size(@imageUrl) #=> [x,y]\n\n #working stuff\n response = Ocr.processDocument(@document.doc_type, @document.language, @document.document_images.load)\n @xmlTranslation = Nokogiri::XML(response)\n\n #\n # Temporary\n #\n @translation.registrationNumber = '1234567'\n @translation.circle = 'ABC 123 kółko'\n @translation.registeredKeeper = \"Andrzej Strzelba\"\n @translation.referenceNumber = \"1234 5678 90\"\n @translation.previousRegisteredKeeper = \"Bartek Walaszek, BFF\"\n @translation.dateOfPurchase = \"20.11.2014\"\n @translation.numberOfPreviousOwners = \"3\"\n @translation.specialNotes = \"Niemiec płakał jak sprzedawał. Niemiec odwoził do granicy!\"\n\n #\n # Here comes the XML parser\n #\n @translation.parseResponse(response)\n\n #\n # BTW. translation variable 4 document is sensless - we have to remove it as soon as possible :: when parsed response will be saved in database (EnglishRegistrationCetificate)\n #\n @document.translation = @xmlTranslation.css(\"value\").text\n\n #\n # @document variables should be set before savin' !!\n #\n\n @document.save\n end\n\n if @translation.save\n\n format.html { redirect_to @document, notice: 'Document was successfully created.' }\n format.json { render action: 'show', status: :created, location: @document }\n else\n @document.destroy\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n else\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n end\n end",
"def detect_pdf_gcs gcs_source_uri:, gcs_destination_uri:\n # [START vision_text_detection_pdf_gcs]\n # [START vision_text_detection_pdf_gcs_migration]\n # gcs_source_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/example.pdf'\"\n # gcs_destination_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/prefix_'\"\n\n require \"google/cloud/vision\"\n require \"google/cloud/storage\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n operation = image_annotator.document_text_detection(\n image: gcs_source_uri,\n mime_type: \"application/pdf\",\n batch_size: 2,\n destination: gcs_destination_uri,\n async: true\n )\n\n puts \"Waiting for the operation to finish.\"\n operation.wait_until_done!\n # [END vision_text_detection_pdf_gcs_migration]\n\n # Once the request has completed and the output has been\n # written to GCS, we can list all the output files.\n storage = Google::Cloud::Storage.new\n\n bucket_name, prefix = gcs_destination_uri.match(\"gs://([^/]+)/(.+)\").captures\n bucket = storage.bucket bucket_name\n\n # List objects with the given prefix.\n puts \"Output files:\"\n blob_list = bucket.files prefix: prefix\n blob_list.each do |file|\n puts file.name\n end\n\n # Process the first output file from GCS.\n # Since we specified a batch_size of 2, the first response contains\n # the first two pages of the input file.\n output = blob_list[0]\n json_string = output.download\n response = JSON.parse json_string.string\n\n # The actual response for the first page of the input file.\n first_page_response = response[\"responses\"][0]\n annotation = first_page_response[\"fullTextAnnotation\"]\n\n # Here we print the full text from the first page.\n # The response contains more information:\n # annotation/pages/blocks/paragraphs/words/symbols\n # including confidence scores and bounding boxes\n puts \"Full text:\\n#{annotation['text']}\"\n # [END vision_text_detection_pdf_gcs]\nend",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def rotateAndFlip(image)\n return image.transpose.flip\nend",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def imageDeSteg(password, image)\n # Suck in the image\n original_image = Magick::Image.read(image).first\n\n # Initialize the bits array\n bits = []\n\n # For each pixel in the image\n original_image.each_pixel do |pixel, col, row|\n # Set colors to their current value\n red = pixel.red\n green = pixel.green\n blue = pixel.blue\n\n # If the red value for the pixel is odd\n if (red%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the green value for the pixel is odd\n if (green%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the blue value for the pixel is odd\n if (blue%2 == 1)\n bits << 1\n else\n bits << 0\n end\n end\n\n # Initialize the encrypted_length_bits\n encrypted_length_bits = \"\"\n\n # For the first 256 characters in the array\n for counter in (0..255)\n # Append the value to the encrypted_length_bits\n encrypted_length_bits = encrypted_length_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted length bits to a string\n encrypted_length = Stegg.convertBinaryToString(encrypted_length_bits)\n\n # Decrypt the encrypted length\n cipher = Gibberish::AES.new(password)\n length = cipher.decrypt(encrypted_length, :binary => true)\n\n # Initialize the encrypted_data_bits\n encrypted_data_bits = \"\"\n\n # Data starts at 256 and goes through the length\n last_bit = 255 + length.to_i()\n \n # For character 256 through the last bit\n for counter in (256..last_bit)\n # Append the value to the encrypted_data_bits\n encrypted_data_bits = encrypted_data_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted data bits to a string\n encrypted_data = Stegg.convertBinaryToString(encrypted_data_bits)\n\n # Decrypt the encrypted data\n data = cipher.decrypt(encrypted_data, :binary => true)\n\n # Return the data\n return data\n end",
"def transform_pdfs_to_readabilitycleaned_rtf(group)\n pdf_documents = []\n\n # To safely be able to add/remove records, we need real references to the documents\n count = 0\n each_pdf_document(group) do |record|\n # TODO: Check for \"Don't rtf me!\"-tag\n pdf_documents << record.get\n @pdf_to_rtf_log.debug \"Get: '#{record.name}' (#{record.kind})\"\n count += 1\n end\n @pdf_to_rtf_log.debug \"--- #{count} PDFs ---\"\n\n pdf_documents.each do |record|\n transform_a_pdf_to_readabilitycleaned_rtf(record)\n end\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def recognize\nend",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def rotated\n RawImage.new(@image.getRotated())\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def convert images_directory , pdfs_directory\n\n # Get all files from that directory\n all_images = Dir.entries(images_directory)\n\n #Segregate only the required the question paper images , just in case the directory contains other files\n all_images.keep_if { |a| ((a.start_with? \"mid-\") || (a.start_with? \"end-\")) && ((a.end_with? \".jpg\") || (a.end_with? \".png\") || (a.end_with? \".tif\") || (a.end_with? \".gif\") || (a.end_with? \".svg\") || (a.end_with? \".bmp\"))}\n\n #Store number of images as a variable to show % finished\n number_of_images = all_images.count\n\n # Initialisation of variables like Array of names of papers , eg. mid-spring-2016-MA20104\n Dir.chdir(images_directory)\n papernames_array = []\n i = 0\n all_images = all_images.sort\n stack = Magick::ImageList.new\n\n #Loop through all paper images & batch merge them into PDFs , even if a paper has 3 pages / images\n all_images.each do |file|\n papernames_array[i] = file[0..22]\n if i == 0\n Dir.chdir(images_directory)\n stack = Magick::ImageList.new\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n else\n if papernames_array[i].eql? papernames_array[i-1]\n Dir.chdir(images_directory)\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n else\n Dir.chdir(pdfs_directory)\n stack.write(papernames_array[i-1]+\".pdf\")\n Dir.chdir(images_directory)\n stack = Magick::ImageList.new\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n end\n if i == number_of_images-1\n Dir.chdir(pdfs_directory)\n stack.write(papernames_array[i]+\".pdf\")\n end\n end\n i = i + 1\n percentage = (i.to_f/number_of_images.to_f) * 100\n puts \"Processing #{i}/#{number_of_images} images , #{percentage}% done\"\n end\nend",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def all_images\n # For all images:\n image_text_files = Dir\n .children(folder_path)\n .select do |path|\n path.start_with?('output-')\n end\n .sort\n # .tap{|fs| puts fs }\n image_text_data = image_text_files.map do |path|\n File.read(File.join(folder_path, path))\n end\n image_jsons = image_text_data.map do |json_string|\n JSON.parse(json_string)\n end\n page_regex = /#{image_prefix}(\\d+)#{image_suffix}/\n ordered_image_jsons = image_jsons.sort do |a, b|\n a_uri = a['responses'].first['context']['uri']\n b_uri = b['responses'].first['context']['uri']\n a_num = a_uri.match(page_regex)[1].to_i\n b_num = b_uri.match(page_regex)[1].to_i\n a_num <=> b_num\n end\n\n ordered_images_count = ordered_image_jsons.count\n ordered_image_jsons.each.with_index do |ordered_image_json, image_index|\n # next unless image_index == 4\n\n puts \"Processing image #{image_index+1} of #{ordered_images_count}\"\n uri = ordered_image_json['responses'].first['context']['uri']\n # puts \"Processing URI #{uri}\"\n page_number = uri.match(page_regex)[1].to_i\n # puts \"Processing page number #{page_number}\"\n\n input_image_path = full_image_path(page_number)\n # puts \"File.exist?(#{input_image_path}): #{File.exist?(input_image_path)}\"\n image = Magick::Image.read(input_image_path)[0]\n # json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n # json_text = File.read(json_path)\n # json = JSON.parse(json_text)\n\n bounding_box = ordered_image_json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n confidence_symbols_to_colors = {\n # very_confidence: '#BED1D8',\n # very_confidence: '#000000',\n very_confidence: '#555',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n numbers_to_stroke_opacity = {\n 80..100 => '35%',\n 60..80 => '100%',\n 31..60 => '100%',\n 0..30 => '100%'\n }\n numbers_to_stroke_width = {\n 80..100 => 2,\n # 80..100 => 4,\n 50..80 => 5,\n # 50..80 => 4,\n 31..50 => 5,\n 0..30 => 5\n }\n\n pages = ordered_image_json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbols_total = symbols.count\n symbols.each.with_index do |symbol, symbol_index|\n # next unless symbol_index == 41\n\n # puts \" Processing symbol #{symbol_index+1} of #{symbols_total}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence = symbol['confidence'] || 0\n confidence_number = (confidence * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n stroke_opacity = numbers_to_stroke_opacity.select{|n| n === confidence_number }.values.first\n stroke_width = numbers_to_stroke_width.select{|n| n === confidence_number }.values.first\n\n draw = Magick::Draw.new\n draw.fill_opacity(0)\n draw.stroke(color)\n draw.stroke_opacity(stroke_opacity)\n # draw.stroke_opacity('100%')\n draw.stroke_width(stroke_width)\n\n p1x = vertices[0]['x'] || 0\n p1y = vertices[0]['y'] || 0\n # p2x = vertices[1]['x']\n # p2y = vertices[1]['y']\n # p3x = vertices[3]['x']\n # p3y = vertices[3]['y']\n p4x = vertices[2]['x'] || 0\n p4y = vertices[2]['y'] || 0\n\n unless p1x && p1y && p4x && p4y\n # unless p1x && p1y && p2x && p2y && p3x && p3y && p4x && p4y\n puts \"Error: Missing at least one vertex for image json block from file #{image_text_files[image_index]} for page#{page_number}.jpg\"\n puts \"Error: Vertices:\"\n puts vertices\n next\n end\n\n # puts \"trying to draw rectangle at #{p1x}, #{p1y}, #{p3x}, #{p3y}\"\n # draw.roundrectangle(p1x, p1y, p4x, p4y, 5, 5)\n draw.rectangle(p1x, p1y, p4x, p4y)\n # draw.line(p1x, p1y, p2x, p2y)\n # draw.line(p1x, p1y, p3x, p3y)\n # draw.line(p2x, p2y, p4x, p4y)\n # draw.line(p3x, p3y, p4x, p4y)\n\n draw.draw(image)\n next\n end\n # After exploring this, I'm confident that missing vertices should be\n # treated as 0s\n altered_image_suffix = image_suffix\n .split('.')\n .insert(1, 'symbol_confidence')\n .join('.')\n output_image_path = \"#{full_image_prefix}#{page_number}#{altered_image_suffix}\"\n # output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.symbol_confidence.missingvertices.jpg\"\n image.write(output_image_path)\n end\n puts \"Finished drawing on images...\"\nend",
"def ssim_processing(image_file_path,book_original_image)\n\t\tinstance = SSIM.new\n\t\t#Get folder where crop image it is saved\n\t\tfolder_path = get_path_without_image_name(image_file_path)\n\n\t\tinstance.fill_gaussian_kernel\n\t\tindex = instance.image_processing(\"#{folder_path}image_crop.jpg\",book_original_image)\n\t\treturn index\n\tend",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def imagemagick?; end",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def genarate_normalized_images(filepath, should_skip)\n if should_skip\n puts \"skipping computing flow fields\"\n else\n blacklist = [\".ppm\", \".flo\", \".txt\"]\n input_imgs_fnames = Dir[\"#{filepath}*.*\"].reject do |fname|\n blacklist.any? do |forbidden_name|\n fname.include?(forbidden_name)\n end\n end\n\n unless input_imgs_fnames.empty?\n fextension = input_imgs_fnames.first.split(\".\").last\n system(\"mogrify -format ppm #{filepath}/*.#{fextension}\")\n end\n end\n end",
"def detect; end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def process_image path, placement = {}\n p 'Generating propeller data...'\n @propeller_data = @propeller_processor.process path, placement\n\n p 'Generating preview...'\n @preview = @preview_processor.generate @propeller_data\n\n @interface.processed @preview\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def build_pdf_object(document)\n color_space =\n case channels\n when 1\n :DeviceGray\n when 3\n :DeviceRGB\n when 4\n :DeviceCMYK\n else\n raise ArgumentError, 'JPG uses an unsupported number of channels'\n end\n\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n ColorSpace: color_space,\n BitsPerComponent: bits,\n Width: width,\n Height: height\n )\n\n # add extra decode params for CMYK images. By swapping the\n # min and max values from the default, we invert the colours. See\n # section 4.8.4 of the spec.\n if color_space == :DeviceCMYK\n obj.data[:Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]\n end\n\n obj.stream << @data\n obj.stream.filters << :DCTDecode\n obj\n end",
"def detect!; end",
"def img!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 21 )\n\n type = IMG\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 348:7: 'img'\n match( \"img\" )\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__, 21 )\n\n end",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def detect_labels path_to_image_file:\n# [START detect_labels]\n # [START importing_libraries]\n require \"google/cloud/vision\"\n # [END importing_libraries]\n\n # [START create_vision_client]\n vision = Google::Cloud::Vision.new\n # [END create_vision_client]\n\n # [START annotate_image]\n image = vision.image path_to_image_file\n annotation = vision.annotate image, labels: true\n labels = annotation.labels\n # [END annotate_image]\n\n # [START print_labels]\n puts \"Image labels:\"\n labels.each do |label|\n puts label.description\n end\n # [END print_labels]\n# [END detect_labels]\nend",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def atest_ID_25836_edit_profile_pic_02\n login_as_user1\n go_to_edit_profile_page\n verify_unable_to_upload_non_image_file \"PDFDocument\"\n end",
"def scanned_prof_image\n scanned_prof\n end",
"def Redact(input, output, vec, app)\n\tdoc = PDFDoc.new(input)\n\tif doc.InitSecurityHandler\n\t\tRedactor.Redact(doc, vec, app, false, true)\n\t\tdoc.Save(output, SDFDoc::E_linearized)\n\tend\nend",
"def pdf_ocr_pdf_to_words_with_location(image_file, opts = {})\n data, _status_code, _headers = pdf_ocr_pdf_to_words_with_location_with_http_info(image_file, opts)\n data\n end",
"def create_rotate_flipped_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def retrofy\r\n Gosu::enable_undocumented_retrofication\r\n self\r\n \r\n #\r\n # The below code depends on the bad opengl gem\r\n # And it could affect other images anyhow... \r\n # So let's use Gosu::enable_undocumented_retrofication until further notice.\r\n #\r\n \r\n #glBindTexture(GL_TEXTURE_2D, self.gl_tex_info.tex_name)\r\n #glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\r\n #glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\r\n #self\r\n end",
"def despeckle image\n m_begin \"despeckle\"\n set_variable(image, get_image(image).despeckle)\n m_end \"despeckle\"\n end",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def process!(document); end",
"def detect_web_gcs image_path:\n # [START vision_web_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.web_detection(\n image: image_path,\n max_results: 15 # optional, defaults to 10\n )\n\n response.responses.each do |res|\n res.web_detection.web_entities.each do |entity|\n puts entity.description\n end\n\n res.web_detection.full_matching_images.each do |match|\n puts match.url\n end\n end\n # [END vision_web_detection_gcs]\nend",
"def initialize(input_file, output_file, options, type)\n\t\t\t@output_file = output_file\n\t\t\t@options = options\n\t\t\t@type = handle_output_type(type)\n\t\t\t@input_file = input_file\n\t\t\tif pdf?(input_file)\n\t\t\t\t@image = OCR::Path.new(input_file).image_path\n\t\t\t\tconvert_to_img\n\t\t\telse\n\t\t\t\t@image = input_file\n\t\t\tend\n\t\t\t@clean_image = OCR::Path.new(output_file).clean_image_path\n\t\tend",
"def reset\n File.open(@input_path, \"rb\") do |f|\n begin\n tmp = Tempfile.new(\"minimagic\")\n tmp.binmode \n tmp.write(f.read)\n ensure\n tmp.close\n end \n @path = tmp.path\n end\n verify_image(@path)\n self\n end"
] |
[
"0.6634254",
"0.61188626",
"0.56217086",
"0.5557502",
"0.5505193",
"0.54923713",
"0.5489433",
"0.54034656",
"0.5369795",
"0.5303366",
"0.52833045",
"0.52772856",
"0.5215921",
"0.5203122",
"0.5158877",
"0.5149264",
"0.5148406",
"0.51152325",
"0.50803614",
"0.5076563",
"0.50739765",
"0.5061746",
"0.50447005",
"0.50233513",
"0.50022537",
"0.4978363",
"0.49579853",
"0.49573615",
"0.49367437",
"0.49300608",
"0.4927214",
"0.4919481",
"0.49124375",
"0.49097282",
"0.48948425",
"0.48910302",
"0.4843735",
"0.48305637",
"0.48252696",
"0.48202065",
"0.48176402",
"0.48062503",
"0.48038092",
"0.47380826",
"0.47363725",
"0.47232336",
"0.47115678",
"0.47090974",
"0.46915567",
"0.4685389",
"0.46728677",
"0.4669398",
"0.4666295",
"0.46630886",
"0.4659087",
"0.4650654",
"0.4638988",
"0.462454",
"0.46046185",
"0.45801124",
"0.45766318",
"0.45678475",
"0.4561006",
"0.45537823",
"0.45533043",
"0.45412612",
"0.45393333",
"0.4524428",
"0.45056438",
"0.45000598",
"0.44994873",
"0.4489321",
"0.44837752",
"0.44732356",
"0.4466442",
"0.44512355",
"0.44490668",
"0.44219926",
"0.44198126",
"0.44081506",
"0.43977407",
"0.4394322",
"0.43890318",
"0.43809944",
"0.43807417",
"0.43778557",
"0.43766063",
"0.43725356",
"0.4363819",
"0.43585244",
"0.43510324",
"0.4315189",
"0.43151116",
"0.43145272",
"0.43136993",
"0.43101713",
"0.43027964",
"0.43022636",
"0.42904553",
"0.42899856"
] |
0.51618785
|
14
|
Detect and unrotate a document image (advanced) Detect and unrotate an image of a document (e.g. that was scanned at an angle) using deep learning. Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unrotate_advanced_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate_advanced ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate_advanced"
end
# resource path
local_var_path = '/ocr/preprocessing/image/unrotate/advanced'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_unrotate_advanced\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def rotate_image(image)\n\nend",
"def scanned_image\n scanned_eligibility\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def preprocessing_unrotate_advanced(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_advanced_with_http_info(image_file, opts)\n data\n end",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def rotate image, angle, outimage=nil\n m_begin \"rotate\"\n img = get_image(image)\n if false\n rotated = img.rotate(angle)\n else\n#\n# from newsgroup: The alternative way to rotate is to use -filter point +distort SRT {angle} +repage\n#\n rotated = img.resize(img.columns, img.rows, PointFilter)\n rotated = img.distort(ScaleRotateTranslateDistortion, [angle])\n end\n outimage = image if outimage.nil?\n put_image(outimage, rotated)\n m_end \"rotate\"\n end",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def preprocessing_unrotate(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unrotate_with_http_info(image_file, opts)\n data\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def scanned_image\n scanned_retreat\n end",
"def preprocessing_unrotate_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unrotate ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unrotate\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unrotate'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unrotate\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def apply_image_transformation?\n true\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.tap(&:auto_orient)\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def transform_image # :norobots:\n pass_query_params\n if image = find_or_goto_index(Image, params[:id].to_s)\n if check_permission!(image)\n if params[:op] == 'rotate_left'\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'rotate_right'\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n elsif params[:op] == 'mirror'\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? or\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_to(:action => 'show_image', :id => image, :params => query_params)\n else\n redirect_to(:action => 'show_image', :id => image, :params => query_params,\n :size => params[:size])\n end\n end\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def preprocessing_unskew(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)\n data\n end",
"def show\n #@document = Document.find(params[:id])\n #\n # Above line is unnecesary because there is this magic before_action :set_document ... hell yeah\n #\n @documentImages = @document.document_images.load\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when 'English'\n @translation = @document.english_registration_certificate\n #appid = CGI.escape(\"Seeker of words in documents\")\n #passss = CGI.escape(\"IGP0S5KYsUi7WpYCiTa8refF\")\n #\n # Here comes the EACH loop over all the images stored in @documentImages objects - probablu mulpile request :: submitImage\n #\n #filename = @document.image.current_path\n #language = \"English\"\n #url = \"http://#{appid}:#{passss}@cloud.ocrsdk.com\"\n @document.translation\n end\n else\n @translation = EnglishRegistrationCertificate.new()\n end\n end",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def scanned_image\n scanned_certificate\n end",
"def rotate\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.rotate(90)\n img.write('public' + @photo.attachment_url)\n end",
"def fix_exif_rotation\n return unless self.file.content_type.start_with? 'image'\n \n manipulate! do |img|\n img.tap(&:auto_orient)\n img = yield(img) if block_given?\n img\n end\n end",
"def transform_image\n pass_query_params\n image = find_or_goto_index(Image, params[:id].to_s)\n return unless image\n\n if check_permission!(image)\n case params[:op]\n when \"rotate_left\"\n image.transform(:rotate_left)\n flash_notice(:image_show_transform_note.t)\n when \"rotate_right\"\n image.transform(:rotate_right)\n flash_notice(:image_show_transform_note.t)\n when \"mirror\"\n image.transform(:mirror)\n flash_notice(:image_show_transform_note.t)\n else\n flash_error(\"Invalid operation #{params[:op].inspect}\")\n end\n end\n if params[:size].blank? ||\n params[:size].to_sym == (@user ? @user.image_size : :medium)\n redirect_with_query(action: \"show_image\", id: image)\n else\n redirect_with_query(action: \"show_image\", id: image,\n size: params[:size])\n end\n end",
"def preprocessing_unskew_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unskew\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def checkrotation(filepath)\n\t# rotate if needed - normally these are 300 wide by 419 high\n\timg = Magick::Image.read(filepath).first\n\n\tif(img.columns > img.rows) # too wide so rotate left\n\t\timg.rotate!(-90)\n\t\timg.write(filepath)\n\tend\t\nend",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def create\n @document = Document.new(document_params)\n case @document.doc_type\n when 'registration_certificate'\n case @document.language\n when \"English\"\n @translation = EnglishRegistrationCertificate.new()\n @translation.document = @document\n\n #here comes preProcessing and OCR things\n end\n else\n #here should be redirection to document#new\n end\n\n respond_to do |format|\n if @document.save\n params[:document_images]['image'].each do |i|\n @document_image = @document.document_images.create!(:image => i)\n @imageUrl = @document_image.image.current_path\n @imageDimensions = FastImage.size(@imageUrl) #=> [x,y]\n\n #working stuff\n response = Ocr.processDocument(@document.doc_type, @document.language, @document.document_images.load)\n @xmlTranslation = Nokogiri::XML(response)\n\n #\n # Temporary\n #\n @translation.registrationNumber = '1234567'\n @translation.circle = 'ABC 123 kółko'\n @translation.registeredKeeper = \"Andrzej Strzelba\"\n @translation.referenceNumber = \"1234 5678 90\"\n @translation.previousRegisteredKeeper = \"Bartek Walaszek, BFF\"\n @translation.dateOfPurchase = \"20.11.2014\"\n @translation.numberOfPreviousOwners = \"3\"\n @translation.specialNotes = \"Niemiec płakał jak sprzedawał. Niemiec odwoził do granicy!\"\n\n #\n # Here comes the XML parser\n #\n @translation.parseResponse(response)\n\n #\n # BTW. translation variable 4 document is sensless - we have to remove it as soon as possible :: when parsed response will be saved in database (EnglishRegistrationCetificate)\n #\n @document.translation = @xmlTranslation.css(\"value\").text\n\n #\n # @document variables should be set before savin' !!\n #\n\n @document.save\n end\n\n if @translation.save\n\n format.html { redirect_to @document, notice: 'Document was successfully created.' }\n format.json { render action: 'show', status: :created, location: @document }\n else\n @document.destroy\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n else\n format.html { render action: 'new' }\n format.json { render json: @document.errors, status: :unprocessable_entity }\n end\n end\n end",
"def detect_pdf_gcs gcs_source_uri:, gcs_destination_uri:\n # [START vision_text_detection_pdf_gcs]\n # [START vision_text_detection_pdf_gcs_migration]\n # gcs_source_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/example.pdf'\"\n # gcs_destination_uri = \"Google Cloud Storage URI, eg. 'gs://my-bucket/prefix_'\"\n\n require \"google/cloud/vision\"\n require \"google/cloud/storage\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n operation = image_annotator.document_text_detection(\n image: gcs_source_uri,\n mime_type: \"application/pdf\",\n batch_size: 2,\n destination: gcs_destination_uri,\n async: true\n )\n\n puts \"Waiting for the operation to finish.\"\n operation.wait_until_done!\n # [END vision_text_detection_pdf_gcs_migration]\n\n # Once the request has completed and the output has been\n # written to GCS, we can list all the output files.\n storage = Google::Cloud::Storage.new\n\n bucket_name, prefix = gcs_destination_uri.match(\"gs://([^/]+)/(.+)\").captures\n bucket = storage.bucket bucket_name\n\n # List objects with the given prefix.\n puts \"Output files:\"\n blob_list = bucket.files prefix: prefix\n blob_list.each do |file|\n puts file.name\n end\n\n # Process the first output file from GCS.\n # Since we specified a batch_size of 2, the first response contains\n # the first two pages of the input file.\n output = blob_list[0]\n json_string = output.download\n response = JSON.parse json_string.string\n\n # The actual response for the first page of the input file.\n first_page_response = response[\"responses\"][0]\n annotation = first_page_response[\"fullTextAnnotation\"]\n\n # Here we print the full text from the first page.\n # The response contains more information:\n # annotation/pages/blocks/paragraphs/words/symbols\n # including confidence scores and bounding boxes\n puts \"Full text:\\n#{annotation['text']}\"\n # [END vision_text_detection_pdf_gcs]\nend",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def fix_exif_rotation\n manipulate! do |img|\n img.auto_orient\n img = yield(img) if block_given?\n img\n end\n end",
"def rotateAndFlip(image)\n return image.transpose.flip\nend",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def imageDeSteg(password, image)\n # Suck in the image\n original_image = Magick::Image.read(image).first\n\n # Initialize the bits array\n bits = []\n\n # For each pixel in the image\n original_image.each_pixel do |pixel, col, row|\n # Set colors to their current value\n red = pixel.red\n green = pixel.green\n blue = pixel.blue\n\n # If the red value for the pixel is odd\n if (red%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the green value for the pixel is odd\n if (green%2 == 1)\n bits << 1\n else\n bits << 0\n end\n\n # If the blue value for the pixel is odd\n if (blue%2 == 1)\n bits << 1\n else\n bits << 0\n end\n end\n\n # Initialize the encrypted_length_bits\n encrypted_length_bits = \"\"\n\n # For the first 256 characters in the array\n for counter in (0..255)\n # Append the value to the encrypted_length_bits\n encrypted_length_bits = encrypted_length_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted length bits to a string\n encrypted_length = Stegg.convertBinaryToString(encrypted_length_bits)\n\n # Decrypt the encrypted length\n cipher = Gibberish::AES.new(password)\n length = cipher.decrypt(encrypted_length, :binary => true)\n\n # Initialize the encrypted_data_bits\n encrypted_data_bits = \"\"\n\n # Data starts at 256 and goes through the length\n last_bit = 255 + length.to_i()\n \n # For character 256 through the last bit\n for counter in (256..last_bit)\n # Append the value to the encrypted_data_bits\n encrypted_data_bits = encrypted_data_bits + bits[counter].to_s()\n end\n\n # Convert the binary encrypted data bits to a string\n encrypted_data = Stegg.convertBinaryToString(encrypted_data_bits)\n\n # Decrypt the encrypted data\n data = cipher.decrypt(encrypted_data, :binary => true)\n\n # Return the data\n return data\n end",
"def transform_pdfs_to_readabilitycleaned_rtf(group)\n pdf_documents = []\n\n # To safely be able to add/remove records, we need real references to the documents\n count = 0\n each_pdf_document(group) do |record|\n # TODO: Check for \"Don't rtf me!\"-tag\n pdf_documents << record.get\n @pdf_to_rtf_log.debug \"Get: '#{record.name}' (#{record.kind})\"\n count += 1\n end\n @pdf_to_rtf_log.debug \"--- #{count} PDFs ---\"\n\n pdf_documents.each do |record|\n transform_a_pdf_to_readabilitycleaned_rtf(record)\n end\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def normalize_rotation(driver, image, rotation)\n return if rotation && rotation.zero?\n\n num_quadrants = 0\n if !rotation.nil?\n if (rotation % RIGHT_ANGLE).nonzero?\n raise Applitools::EyesError.new('Currently only quadrant rotations are supported. Current rotation: '\\\n \"#{rotation}\")\n end\n num_quadrants = (rotation / RIGHT_ANGLE).to_i\n elsif rotation.nil? && driver.mobile_device? && driver.landscape_orientation? && image.height > image.width\n # For Android, we need to rotate images to the right, and for iOS to the left.\n num_quadrants = driver.android? ? 1 : -1\n end\n\n Applitools::Utils::ImageUtils.quadrant_rotate!(image, num_quadrants)\n end",
"def process_image(user, image)\n image_tags = image.tags.split(\", \") # Tags in the image, as a neat and tidy array\n\n # Select the tags to keep in the full link by intersecting file tags with user tags\n user_tags = user.file_tags ? user.file_tags.split(\",\") : []\n link_tags = (image_tags & user_tags).join \"_\"\n\n # The default construct\n result = {\n indexer: image.indexer,\n thumb_link: image.thumb_link,\n direct_link: image.base_link + link_tags + image.extension,\n checked: false,\n css_id: \"link\"\n }\n\n # Grab the user's tags in arrays\n best_list = user.best_tags ? user.best_tags.split(\",\") : []\n good_list = user.good_tags ? user.good_tags.split(\",\") : []\n bad_list = user.bad_tags ? user.bad_tags.split(\",\") : []\n worst_list = user.worst_tags ? user.worst_tags.split(\",\") : []\n\n # First the easy ones...\n if worst_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n elsif best_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n else\n # Then, the score checking to let rating come into play\n if image.score.to_i >= 100\n result[:css_id] = \"highlight\"\n elsif image.score.to_i <= -5\n result[:css_id] = \"redlight\"\n else\n # Last, low priority weights\n if good_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"highlight\"\n elsif bad_list.any? { |tag| image_tags.include?(tag) }\n result[:css_id] = \"redlight\"\n end\n end\n end\n\n # Check mark red (bad) images automatically\n result[:checked] = true if result[:css_id] == \"redlight\"\n result\n end",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def recognize\nend",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def rotated\n RawImage.new(@image.getRotated())\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def convert images_directory , pdfs_directory\n\n # Get all files from that directory\n all_images = Dir.entries(images_directory)\n\n #Segregate only the required the question paper images , just in case the directory contains other files\n all_images.keep_if { |a| ((a.start_with? \"mid-\") || (a.start_with? \"end-\")) && ((a.end_with? \".jpg\") || (a.end_with? \".png\") || (a.end_with? \".tif\") || (a.end_with? \".gif\") || (a.end_with? \".svg\") || (a.end_with? \".bmp\"))}\n\n #Store number of images as a variable to show % finished\n number_of_images = all_images.count\n\n # Initialisation of variables like Array of names of papers , eg. mid-spring-2016-MA20104\n Dir.chdir(images_directory)\n papernames_array = []\n i = 0\n all_images = all_images.sort\n stack = Magick::ImageList.new\n\n #Loop through all paper images & batch merge them into PDFs , even if a paper has 3 pages / images\n all_images.each do |file|\n papernames_array[i] = file[0..22]\n if i == 0\n Dir.chdir(images_directory)\n stack = Magick::ImageList.new\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n else\n if papernames_array[i].eql? papernames_array[i-1]\n Dir.chdir(images_directory)\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n else\n Dir.chdir(pdfs_directory)\n stack.write(papernames_array[i-1]+\".pdf\")\n Dir.chdir(images_directory)\n stack = Magick::ImageList.new\n incoming = Magick::ImageList.new file\n stack.concat(incoming)\n end\n if i == number_of_images-1\n Dir.chdir(pdfs_directory)\n stack.write(papernames_array[i]+\".pdf\")\n end\n end\n i = i + 1\n percentage = (i.to_f/number_of_images.to_f) * 100\n puts \"Processing #{i}/#{number_of_images} images , #{percentage}% done\"\n end\nend",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def all_images\n # For all images:\n image_text_files = Dir\n .children(folder_path)\n .select do |path|\n path.start_with?('output-')\n end\n .sort\n # .tap{|fs| puts fs }\n image_text_data = image_text_files.map do |path|\n File.read(File.join(folder_path, path))\n end\n image_jsons = image_text_data.map do |json_string|\n JSON.parse(json_string)\n end\n page_regex = /#{image_prefix}(\\d+)#{image_suffix}/\n ordered_image_jsons = image_jsons.sort do |a, b|\n a_uri = a['responses'].first['context']['uri']\n b_uri = b['responses'].first['context']['uri']\n a_num = a_uri.match(page_regex)[1].to_i\n b_num = b_uri.match(page_regex)[1].to_i\n a_num <=> b_num\n end\n\n ordered_images_count = ordered_image_jsons.count\n ordered_image_jsons.each.with_index do |ordered_image_json, image_index|\n # next unless image_index == 4\n\n puts \"Processing image #{image_index+1} of #{ordered_images_count}\"\n uri = ordered_image_json['responses'].first['context']['uri']\n # puts \"Processing URI #{uri}\"\n page_number = uri.match(page_regex)[1].to_i\n # puts \"Processing page number #{page_number}\"\n\n input_image_path = full_image_path(page_number)\n # puts \"File.exist?(#{input_image_path}): #{File.exist?(input_image_path)}\"\n image = Magick::Image.read(input_image_path)[0]\n # json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n # json_text = File.read(json_path)\n # json = JSON.parse(json_text)\n\n bounding_box = ordered_image_json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n confidence_symbols_to_colors = {\n # very_confidence: '#BED1D8',\n # very_confidence: '#000000',\n very_confidence: '#555',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n numbers_to_stroke_opacity = {\n 80..100 => '35%',\n 60..80 => '100%',\n 31..60 => '100%',\n 0..30 => '100%'\n }\n numbers_to_stroke_width = {\n 80..100 => 2,\n # 80..100 => 4,\n 50..80 => 5,\n # 50..80 => 4,\n 31..50 => 5,\n 0..30 => 5\n }\n\n pages = ordered_image_json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbols_total = symbols.count\n symbols.each.with_index do |symbol, symbol_index|\n # next unless symbol_index == 41\n\n # puts \" Processing symbol #{symbol_index+1} of #{symbols_total}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence = symbol['confidence'] || 0\n confidence_number = (confidence * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n stroke_opacity = numbers_to_stroke_opacity.select{|n| n === confidence_number }.values.first\n stroke_width = numbers_to_stroke_width.select{|n| n === confidence_number }.values.first\n\n draw = Magick::Draw.new\n draw.fill_opacity(0)\n draw.stroke(color)\n draw.stroke_opacity(stroke_opacity)\n # draw.stroke_opacity('100%')\n draw.stroke_width(stroke_width)\n\n p1x = vertices[0]['x'] || 0\n p1y = vertices[0]['y'] || 0\n # p2x = vertices[1]['x']\n # p2y = vertices[1]['y']\n # p3x = vertices[3]['x']\n # p3y = vertices[3]['y']\n p4x = vertices[2]['x'] || 0\n p4y = vertices[2]['y'] || 0\n\n unless p1x && p1y && p4x && p4y\n # unless p1x && p1y && p2x && p2y && p3x && p3y && p4x && p4y\n puts \"Error: Missing at least one vertex for image json block from file #{image_text_files[image_index]} for page#{page_number}.jpg\"\n puts \"Error: Vertices:\"\n puts vertices\n next\n end\n\n # puts \"trying to draw rectangle at #{p1x}, #{p1y}, #{p3x}, #{p3y}\"\n # draw.roundrectangle(p1x, p1y, p4x, p4y, 5, 5)\n draw.rectangle(p1x, p1y, p4x, p4y)\n # draw.line(p1x, p1y, p2x, p2y)\n # draw.line(p1x, p1y, p3x, p3y)\n # draw.line(p2x, p2y, p4x, p4y)\n # draw.line(p3x, p3y, p4x, p4y)\n\n draw.draw(image)\n next\n end\n # After exploring this, I'm confident that missing vertices should be\n # treated as 0s\n altered_image_suffix = image_suffix\n .split('.')\n .insert(1, 'symbol_confidence')\n .join('.')\n output_image_path = \"#{full_image_prefix}#{page_number}#{altered_image_suffix}\"\n # output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.symbol_confidence.missingvertices.jpg\"\n image.write(output_image_path)\n end\n puts \"Finished drawing on images...\"\nend",
"def ssim_processing(image_file_path,book_original_image)\n\t\tinstance = SSIM.new\n\t\t#Get folder where crop image it is saved\n\t\tfolder_path = get_path_without_image_name(image_file_path)\n\n\t\tinstance.fill_gaussian_kernel\n\t\tindex = instance.image_processing(\"#{folder_path}image_crop.jpg\",book_original_image)\n\t\treturn index\n\tend",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def imagemagick?; end",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def genarate_normalized_images(filepath, should_skip)\n if should_skip\n puts \"skipping computing flow fields\"\n else\n blacklist = [\".ppm\", \".flo\", \".txt\"]\n input_imgs_fnames = Dir[\"#{filepath}*.*\"].reject do |fname|\n blacklist.any? do |forbidden_name|\n fname.include?(forbidden_name)\n end\n end\n\n unless input_imgs_fnames.empty?\n fextension = input_imgs_fnames.first.split(\".\").last\n system(\"mogrify -format ppm #{filepath}/*.#{fextension}\")\n end\n end\n end",
"def detect; end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def process_image path, placement = {}\n p 'Generating propeller data...'\n @propeller_data = @propeller_processor.process path, placement\n\n p 'Generating preview...'\n @preview = @preview_processor.generate @propeller_data\n\n @interface.processed @preview\n end",
"def image_ocr_photo_recognize_form_advanced(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_advanced_with_http_info(image_file, opts)\n data\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def build_pdf_object(document)\n color_space =\n case channels\n when 1\n :DeviceGray\n when 3\n :DeviceRGB\n when 4\n :DeviceCMYK\n else\n raise ArgumentError, 'JPG uses an unsupported number of channels'\n end\n\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n ColorSpace: color_space,\n BitsPerComponent: bits,\n Width: width,\n Height: height\n )\n\n # add extra decode params for CMYK images. By swapping the\n # min and max values from the default, we invert the colours. See\n # section 4.8.4 of the spec.\n if color_space == :DeviceCMYK\n obj.data[:Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]\n end\n\n obj.stream << @data\n obj.stream.filters << :DCTDecode\n obj\n end",
"def detect!; end",
"def img!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 21 )\n\n type = IMG\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 348:7: 'img'\n match( \"img\" )\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__, 21 )\n\n end",
"def detect_labels path_to_image_file:\n# [START detect_labels]\n # [START importing_libraries]\n require \"google/cloud/vision\"\n # [END importing_libraries]\n\n # [START create_vision_client]\n vision = Google::Cloud::Vision.new\n # [END create_vision_client]\n\n # [START annotate_image]\n image = vision.image path_to_image_file\n annotation = vision.annotate image, labels: true\n labels = annotation.labels\n # [END annotate_image]\n\n # [START print_labels]\n puts \"Image labels:\"\n labels.each do |label|\n puts label.description\n end\n # [END print_labels]\n# [END detect_labels]\nend",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def atest_ID_25836_edit_profile_pic_02\n login_as_user1\n go_to_edit_profile_page\n verify_unable_to_upload_non_image_file \"PDFDocument\"\n end",
"def scanned_prof_image\n scanned_prof\n end",
"def Redact(input, output, vec, app)\n\tdoc = PDFDoc.new(input)\n\tif doc.InitSecurityHandler\n\t\tRedactor.Redact(doc, vec, app, false, true)\n\t\tdoc.Save(output, SDFDoc::E_linearized)\n\tend\nend",
"def pdf_ocr_pdf_to_words_with_location(image_file, opts = {})\n data, _status_code, _headers = pdf_ocr_pdf_to_words_with_location_with_http_info(image_file, opts)\n data\n end",
"def create_rotate_flipped_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end",
"def retrofy\r\n Gosu::enable_undocumented_retrofication\r\n self\r\n \r\n #\r\n # The below code depends on the bad opengl gem\r\n # And it could affect other images anyhow... \r\n # So let's use Gosu::enable_undocumented_retrofication until further notice.\r\n #\r\n \r\n #glBindTexture(GL_TEXTURE_2D, self.gl_tex_info.tex_name)\r\n #glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\r\n #glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\r\n #self\r\n end",
"def despeckle image\n m_begin \"despeckle\"\n set_variable(image, get_image(image).despeckle)\n m_end \"despeckle\"\n end",
"def image(size: T.unsafe(nil), search_terms: T.unsafe(nil), match_all: T.unsafe(nil)); end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def detect_web_gcs image_path:\n # [START vision_web_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.web_detection(\n image: image_path,\n max_results: 15 # optional, defaults to 10\n )\n\n response.responses.each do |res|\n res.web_detection.web_entities.each do |entity|\n puts entity.description\n end\n\n res.web_detection.full_matching_images.each do |match|\n puts match.url\n end\n end\n # [END vision_web_detection_gcs]\nend",
"def process!(document); end",
"def initialize(input_file, output_file, options, type)\n\t\t\t@output_file = output_file\n\t\t\t@options = options\n\t\t\t@type = handle_output_type(type)\n\t\t\t@input_file = input_file\n\t\t\tif pdf?(input_file)\n\t\t\t\t@image = OCR::Path.new(input_file).image_path\n\t\t\t\tconvert_to_img\n\t\t\telse\n\t\t\t\t@image = input_file\n\t\t\tend\n\t\t\t@clean_image = OCR::Path.new(output_file).clean_image_path\n\t\tend",
"def reset\n File.open(@input_path, \"rb\") do |f|\n begin\n tmp = Tempfile.new(\"minimagic\")\n tmp.binmode \n tmp.write(f.read)\n ensure\n tmp.close\n end \n @path = tmp.path\n end\n verify_image(@path)\n self\n end"
] |
[
"0.6633301",
"0.61185",
"0.5620179",
"0.55576986",
"0.5506062",
"0.5493298",
"0.5488623",
"0.5403662",
"0.53708833",
"0.53043514",
"0.5281883",
"0.52762115",
"0.5215337",
"0.5203908",
"0.51616627",
"0.51587886",
"0.5149557",
"0.5148939",
"0.5114118",
"0.5080157",
"0.507535",
"0.5074337",
"0.50619143",
"0.5044348",
"0.5023598",
"0.5003734",
"0.49790305",
"0.49589232",
"0.49574864",
"0.49374798",
"0.4930306",
"0.49279425",
"0.49185658",
"0.49116653",
"0.49092245",
"0.48944834",
"0.489169",
"0.48310032",
"0.4825831",
"0.48204476",
"0.4817372",
"0.4806334",
"0.48039246",
"0.473765",
"0.47363105",
"0.47230226",
"0.47121596",
"0.4709688",
"0.4691092",
"0.46859843",
"0.46737534",
"0.46697626",
"0.46666753",
"0.4661589",
"0.46592322",
"0.46510527",
"0.46397346",
"0.46244234",
"0.46056455",
"0.45803297",
"0.4577337",
"0.4567538",
"0.45609406",
"0.45530117",
"0.45529395",
"0.45412365",
"0.45400426",
"0.45232934",
"0.45056424",
"0.44995746",
"0.44993335",
"0.44887036",
"0.4483633",
"0.44743085",
"0.44657475",
"0.44508386",
"0.44491002",
"0.4421871",
"0.44196796",
"0.4408217",
"0.43968636",
"0.4395183",
"0.43899935",
"0.43830895",
"0.4380786",
"0.43777838",
"0.4375597",
"0.4373105",
"0.43631047",
"0.4358284",
"0.4350966",
"0.43158433",
"0.43151248",
"0.43143976",
"0.4313235",
"0.43100628",
"0.43033916",
"0.43014267",
"0.42900363",
"0.42892832"
] |
0.48440546
|
37
|
Detect and unskew a photo of a document Detect and unskew a photo of a document (e.g. taken on a cell phone) into a perfectly square image. Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unskew(image_file, opts = {})
data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)
data
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def preprocessing_unskew_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew\"\n end\n # resource path\n local_var_path = '/ocr/preprocessing/image/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PreprocessingApi#preprocessing_unskew\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def ssim_processing(image_file_path,book_original_image)\n\t\tinstance = SSIM.new\n\t\t#Get folder where crop image it is saved\n\t\tfolder_path = get_path_without_image_name(image_file_path)\n\n\t\tinstance.fill_gaussian_kernel\n\t\tindex = instance.image_processing(\"#{folder_path}image_crop.jpg\",book_original_image)\n\t\treturn index\n\tend",
"def square_image_crop\n if (self.crops)\n if !(self.crop_x.nil? || self.crop_y.nil? || self.crop_w.nil? || self.crop_h.nil?)\n @image = MiniMagick::Image.open(self.photo.url)\n # if image is larger than our max screen size, the cropped image will be incorrect (resizing)\n @image.sample(((700/@image[:width].to_f) * 100).to_s + \"%\") if @image[:width] > 700\n @image.crop(\"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\")\n @image.set(\"page\", \"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\") \n self.square_image = @image\n end\n end\n end",
"def scanned_image\n scanned_eligibility\n end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def extract_cover\n puts 'Extract front cover'\n extract_png(1, 'cover')\n puts 'Extract back cover'\n extract_png(page_count, 'back')\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def scanned_image\n scanned_certificate\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def sharpen\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.sharpen(0.0, 1.0)\n img.write('public' + @photo.attachment_url)\n end",
"def test_image(photo)\n photo = File.expand_path(photo)\n path = photo.sub(/\\.jpe?g/i, '.copy.jpg')\n FileUtils.cp photo, path\n `automator -i #{path} #{Photoapp.gem_dir(\"lib/adjust-image.workflow\")}`\n\n Photo.new(path, logo, self).write(path)\n end",
"def apply_image_transformation?\n true\n end",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def crop\n\n @user_document_id = params[:document_to_crop_id]\n @user = current_user\n @profile = @user.profile\n @user_document = @user.documents.find(@user_document_id)\n @user_document.crop_x = params[:coordinates][:crop_x].to_i.to_s\n @user_document.crop_y = params[:coordinates][:crop_y].to_i.to_s\n @user_document.crop_w = params[:coordinates][:crop_w].to_i.to_s\n @user_document.crop_h = params[:coordinates][:crop_h].to_i.to_s\n\n begin\n if @user_document.document.reprocess!\n respond_to do |format|\n format.json { render :json => [:user_document_id=>@user_document_id], :status => :ok }\n end\n\n else\n respond_to do |format|\n #format.html { redirect_to(edit_profile_url(@profile), :notice => 'There was an issue with video upload. Please try again') }\n format.json { render :json => [:error_message => 'conversion failure'], :status => :ok }\n end\n end\n\n rescue Paperclip::Errors::NotIdentifiedByImageMagickError\n respond_to do |format|\n #format.html { redirect_to(edit_profile_url(@profile), :notice => 'There was an issue with video upload. Please try again') }\n format.json { render :json => [:error_message => 'cannot convert filetype'], :status => :ok }\n end\n end\n\n end",
"def computeProjection\n w,h = @type==:vertical ? [@image.width, @image.height] : [@image.height, @image.width]\n mw,mh = @type==:vertical ? [@image.width, @image.height-@image.borders.bottom] : [@image.height, @image.width-@image.borders.right]\n content_mask = Array.new(w){[false, 0]}\n\n w.times do |a|\n obj_height = 0\n gap = 0\n (h-mh).times do |b|\n x,y = @type==:vertical ? [a,b] : [b,a]\n idx = @image.index(x, y)\n #p [idx, w, h, mh, a, b, x, y, @image.width, @image.height]\n if @data[idx] <= @threshold\n obj_height += 1\n obj_height += gap if gap <= @image.min_obj_size\n gap = 0\n else\n gap += 1\n content_mask[a] = [true, b] if obj_height > @image.min_obj_size\n obj_height = 0\n end\n end\n end\n\n content_mask\n end",
"def sepia\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.sepiatone()\n img.write('public' + @photo.attachment_url)\n end",
"def scanned_image\n scanned_retreat\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def manualcrop\n if model.crop?\n x = model.x.to_d\n y = model.y.to_d\n x2 = model.x2.to_d\n y2 = model.y2.to_d\n scale = model.scale.to_d\n\n manipulate! do |img|\n img = img.scale(1/scale)\n img = img.crop(x, y, x2-x, y2-y)\n end\n end\n end",
"def no_photo(width, height)\n no_photo_image = part_image.resize_to_fit(width, height)\n create_custom_part(no_photo_image)\n image.to_image\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def verify_image(path)\n end",
"def square_images\n @template[:message][:attachment][:payload][:image_aspect_ratio] = 'square'\n self\n end",
"def image_processing\n \tpixel_array_img1 = read_file_image(\"book4_no_table.jpg\")\n \tpixel_array_img2 = read_file_image(\"net_book5.jpg\")\n\n\n \tpixel_array_sq_img1 = []\n \tpixel_array_sq_img2 = []\n \tpixel_array_img1x2 = []\n \t##################FALTA AQUI ALGO\n\n \t###### ARRAY OF PIXEL ARRAY\n \t# SQUARE IMAGE IMG_1\n \tpixel_array_sq_img1 = square_array(pixel_array_img1)\t\t\n\t\tpixel_array_sq_img2 = square_array(pixel_array_img2)\n \tpixel_array_img1x2 = product_array(pixel_array_img1,pixel_array_img2)\n\n\t\t# Apply convolve filter two image array\n\t\timg_1_convolve_filter = convolve(pixel_array_img1,@gaussian_kernel)\n\t\timg_2_convolve_filter = convolve(pixel_array_img2,@gaussian_kernel)\n\n\t\t## Array Square\n\t\timg_1_convolve_filter_sq = square_array(img_1_convolve_filter)\n\t\timg_2_convolve_filter_sq = square_array(img_2_convolve_filter)\n\t\timg_2x1_convolve_filter = product_array(img_1_convolve_filter,img_2_convolve_filter)\n\n\t\t#Convolve FILTER Square IMG1 and IMG2\n\t\timg_1_sq_convolve_filter = convolve(pixel_array_sq_img1,@gaussian_kernel)\n\t\timg_2_sq_convolve_filter = convolve(pixel_array_sq_img2,@gaussian_kernel)\n\n\t\t#Convolve FILTER to Product IMG1 and IMG2 \n\t\timg_1x2_convolve_filter = convolve(pixel_array_img1x2,@gaussian_kernel)\n\n\t\timg_1_sq_convolve_filter = difference_array(img_1_sq_convolve_filter,img_1_convolve_filter_sq)\n\t\timg_2_sq_convolve_filter = difference_array(img_2_sq_convolve_filter,img_2_convolve_filter_sq)\n\t\timg_1x2_convolve_filter = difference_array(img_1x2_convolve_filter,img_2x1_convolve_filter)\n\n\n\n\t\t#c1/c2 constants\n\t #First use: manual fitting\n\t c_1=6.5025\n\t c_2=58.5225\n\t \n\t #Second use: change k1,k2 & c1,c2 depend on L (width of color map)\n\t l=255\n\t k_1=0.01\n\t c_1=(k_1*l)**2\n\t k_2=0.03\n\t c_2=(k_2*l)**2\n\t \n\t #Numerator of SSIM\n\t num_ssim = \n\t product_array(\n\t \tmultiple_and_factor_increment(2,img_2x1_convolve_filter,c_1),\n\t \tmultiple_and_factor_increment(2,img_1x2_convolve_filter,c_2))\n\t ##Denominator of SSIM\n\t den_ssim = product_array(sum_two_array_and_incremente(img_1_convolve_filter_sq,img_2_convolve_filter_sq,c_1),sum_two_array_and_incremente(img_1_sq_convolve_filter,img_2_sq_convolve_filter,c_2))\n\t ##SSIM\n\t index = division_and_average(num_ssim,den_ssim)\n\n\t puts index\n\n end",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def test04()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n windowContextName = SecureRandom.uuid\n createWindowContextCommand = CommandModule.make_createwindowcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: windowContextName)\n windowContextObject = SmigIDHash.make_objectid(\n objecttype: :nsgraphicscontext,\n objectname: windowContextName)\n theCommands.add_command(createWindowContextCommand)\n theCommands.add_tocleanupcommands_closeobject(windowContextObject)\n\n # Need to initialize the window to having a white background.\n windowRect = MIShapes.make_rectangle(size: imageDimensions,\n origin: { :x => 0, :y => 0 } )\n whiteColor = MIColor.make_rgbacolor(1.0, 1.0, 1.0)\n drawBackgroundElement = MIDrawElement.new(:fillrectangle)\n drawBackgroundElement.rectangle = windowRect\n drawBackgroundElement.fillcolor = whiteColor\n \n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n drawElements = MIDrawElement.new(:arrayofelements)\n drawElements.add_drawelement_toarrayofelements(drawBackgroundElement)\n drawElements.add_drawelement_toarrayofelements(drawImageElement)\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(windowContextObject,\n drawinstructions: drawElements)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, windowContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n FileUtils.rm_f(tempFile) unless tempFile.nil?\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\nend",
"def extract_graphic\n if !Cache.screenshot(@save_number, header).nil?\n bitmap_screenshot = Cache.screenshot(@save_number, header)\n @screenshot.zoom_x = 2\n @screenshot.zoom_y = 2\n else @virtualb = DataManager.load_screenshot(@save_number)\n if @virtualb.nil?\n bitmap_screenshot = black_bitmap\n else\n bitmap_screenshot = @virtualb.get_bitmap\n @screenshot.zoom_x = 2\n @screenshot.zoom_y = 2\n Cache.add_screenshot(@save_number, bitmap_screenshot, header[:key])\n end\n end\n @screenshot.bitmap = bitmap_screenshot\n @screenshot_loaded = false\n @loading_bar.disappear\n end",
"def get_image_credit(page_doc)\n\timage_credit = page_doc.css('body center:nth-child(2)')\n\timage_credit.search('.//b')[0].remove\n\timage_credit.search('.//br').remove\n\timage_credit.search('center').remove\n\treturn image_credit.inner_html.strip!\nend",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color disimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def show\n # require \"mini_magick\"\n #\n # @codeimage = @code.image\n # croppedcode = @codeimage.cropped\n # compositecode = @codeimage.composite\n # base = Base.last.image\n #\n # newimage = MiniMagick::Image.open(croppedcode.url)\n # baseimage = MiniMagick::Image.open(base.url)\n # newimage.rotate(\"-10\")\n #\n # newimage = baseimage.composite(newimage) do |c|\n # c.compose(\"Darken\")\n # c.geometry(\"200x200+215+70\")\n # c.gravity(\"southeast\")\n # end\n\n\n # newimage.write(@codeimage.composite.url)\n\n if Code.count > 1\n if Code.first.created_at < 7.days.ago\n Code.first.delete\n end\n end\n\n redirect_to root_url\n\n end",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color dissimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def from_blob(blob)\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_from_blob(blob)\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def optimize_for_pagespeed\n # according to https://developers.google.com/speed/docs/insights/OptimizeImages\n if self.file.content_type == 'image/jpeg'\n # convert orig.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG orig_converted.jpg\n manipulate! do |img|\n img.sampling_factor '4:2:0'\n img.strip\n img.quality 85\n img.interlace 'JPEG'\n img\n end\n else\n # convert cuppa.png -strip cuppa_converted.png\n manipulate! do |img|\n img.strip\n img\n end\n end\n end",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def to_face\n image.crop(crop_params)\n image.write(outfile)\n Face.new(outfile)\n end",
"def imagemagick?; end",
"def testsnapshot(onwindow: false)\n baseImageName = \"AfterDrawSnapshot.jpg\"\n begin\n # 1. Create window or bitmap context. width: 800, height: 600\n bitmapObject = if onwindow\n SmigHelpers.create_window(width: 800, height: 600)\n else\n SmigHelpers.create_bitmapcontext(width: 800, height: 600)\n end\n\n # 2. Try and draw a snapshot\n didThrow = false\n begin\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n rescue RuntimeError => e\n # 3. Take note that drawing the snapshot failed.\n didThrow = true\n end\n\n # 3. Continued. Raise an exception if snapshot failed & exception not thrown\n unless didThrow\n raise \"Draw shapshot should have failed as no snapshot has been taken\"\n end\n\n if onwindow\n # Need to initialize the window to having a white background.\n windowRect = MIShapes.make_rectangle(size:{ :width => 800,\n :height => 600 },\n origin: { :x => 0, :y => 0 } )\n whiteColor = MIColor.make_rgbacolor(1.0, 1.0, 1.0)\n drawBackgroundElement = MIDrawElement.new(:fillrectangle)\n drawBackgroundElement.rectangle = windowRect\n drawBackgroundElement.fillcolor = whiteColor\n drawBackgroundCommand = CommandModule.make_drawelement(bitmapObject, \n drawinstructions: drawBackgroundElement)\n Smig.perform_command(drawBackgroundCommand)\n end\n\n # 4. Draw some stuff into the bitmap context.\n points = []\n points.push(MIShapes.make_point(100, 50))\n points.push(MIShapes.make_point(700, 50))\n points.push(MIShapes.make_point(400, 550))\n newPath = MIPath.new\n newPath.add_triangle(points: points)\n drawElement = MIDrawElement.new(:fillpath)\n drawElement.fillcolor = MIColor.make_rgbacolor(0.8, 0.2, 0.1)\n drawElement.arrayofpathelements = newPath\n drawElement.startpoint = points[0]\n drawElementCommand = CommandModule.make_drawelement(bitmapObject, \n drawinstructions: drawElement)\n Smig.perform_command(drawElementCommand)\n # 5. Take a snapshot\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :takesnapshot))\n # 6. Draw the snapshot into the bitmap context.\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n # 7. Draw some more stuff into it\n points = []\n points.push(MIShapes.make_point(100, 550))\n points.push(MIShapes.make_point(700, 550))\n points.push(MIShapes.make_point(400, 50))\n newPath = MIPath.new\n newPath.add_triangle(points: points)\n drawElement = MIDrawElement.new(:fillpath)\n drawElement.fillcolor = MIColor.make_rgbacolor(0.2, 0.7, 0.1)\n drawElement.arrayofpathelements = newPath\n drawElement.startpoint = points[0]\n drawElementCommand = CommandModule.make_drawelement(bitmapObject,\n drawinstructions: drawElement)\n Smig.perform_command(drawElementCommand)\n # 8. Export an image from the bitmap\n tempFile2 = File.join(Dir.tmpdir(), \"BeforeSnapshot.jpg\")\n SmigHelpers.save_image(imagesource: bitmapObject, pathtofile: tempFile2)\n # 9. Draw the snap shot into the bitmap context\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n # 10. Save the bitmap context to an image file.\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n SmigHelpers.save_image(imagesource: bitmapObject, pathtofile: tempFile)\n origFile = File.join($compareImageDir, baseImageName)\n\n unless AreImageFilesSame(origFile, tempFile)\n # 11. Report if different.\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts \"Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n Smig.close_object_nothrow(bitmapObject)\n# `open #{tempFile}`\n# `open #{tempFile2}`\n# `open #{origFile}`\n FileUtils.rm_f(tempFile)\n FileUtils.rm_f(tempFile2)\n end\nend",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def clean_folder\n return unless cropped_image.croppers.any?\n\n cs = CropperService.new(cropped_image)\n cs.clean_variant_folder\n end",
"def cleanup image\n m_begin \"cleanup\"\n img = get_image(image)\n img = img.gaussian_blur(8)\n img = img.threshold((QuantumRange * 0.999).to_int)\n img = img.gaussian_blur(14)\n img = img.threshold(0)\n m_end \"cleanup\"\n set_variable(image, img)\n end",
"def charcoal\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.charcoal(0.0, 1.0)\n img.write('public' + @photo.attachment_url)\n end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def getVerifiedImage\n # Ensure that @sourceImage and @overlayPosition is populated.\n populateMissingData\n\n # Add the overlay, and return the binary image data.\n return VerifyMe::composeOverlay(@sourceImage, @overlayPosition, @sourceImageFormat)\n end",
"def image_by_cropping_to_rect(aRect)\n if aRect.is_a? CGRect\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect.origin.x*self.scale, aRect.origin.y*self.scale], [aRect.size.width*self.scale, aRect.size.height*self.scale]])\n else\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect[0][0]*self.scale, aRect[0][1]*self.scale], [aRect[1][0]*self.scale, aRect[1][1]*self.scale]])\n end\n UIImage.imageWithCGImage(cropped, scale:self.scale, orientation:self.imageOrientation)\n end",
"def clipart\n output = get_working_image(@session_id)\n unless File.exist?(output)\n FileUtils.cp(\"#{Rails.root}/public/#{params[:src]}\", output)\n img = Image.read(output).first\n img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n img.background_color = \"none\"\n img.rotate!(params[:r].to_f) unless params[:r].blank?\n\n #For embroidery\n if params[:emb] == 'true'\n img = img.ordered_dither\n end\n #FLIP/FLOP/Transpose/Transverse\n if params[:ff] == 'flip'\n img.flip!\n elsif params[:ff] == 'flop'\n img.flop!\n elsif params[:ff] == 'transpose'\n img.transpose!\n elsif params[:ff] == 'transverse'\n img.transverse!\n end\n #Extracts a channel\n if params[:ec] == 'R'\n img = img.channel(Magick::RedChannel)\n elsif params[:ec] == 'G'\n img = img.channel(Magick::GreenChannel)\n elsif params[:ec] == 'B'\n img = img.channel(Magick::BlueChannel)\n end\n\n #Applies a special effect to the image - QuantumRange\n img = img.sepiatone(Magick::QuantumRange * params[:qr].to_f) unless params[:qr].blank?\n\n #Vignette (Shape Edge)\n if params[:vig] == 'true'\n img = img.vignette\n end\n\n #Wet Floor\n if params[:wf]\n img = img.wet_floor\n end\n img.write(output)\n end\n img = Image.read(output).first\n send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n end",
"def image_ocr_photo_recognize_receipt(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_receipt_with_http_info(image_file, opts)\n data\n end",
"def processPhotoJob(image)\n image.regenerate_styles!\n end",
"def imgify(tweet)\n return tweet\nend",
"def verify_image\n unless Rails.env.production?\n return true\n end\n # image challenge check\n challenge = @session['uc']\n @session['uc'] = nil\n verify_image = false\n if challenge && @params[:imageChallenge]\n verify_image = challenge.checkResponse(@params[:imageChallenge])\n end\n raise InvalidChallengeValue unless verify_image\n end",
"def rm_centroid_on(corner)\n c = @grom.rm_crop_area(corner)\n p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)\n # puts \"REG #{@grom.rm_blur} - #{@grom.rm_dilate} - C #{c.inspect}\"\n n = NPatch.new(p, c.w, c.h)\n cx, cy, sd = n.centroid\n st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)\n status = st ? :edgy : :ok\n return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}\n end",
"def atest_ID_25836_edit_profile_pic_02\n login_as_user1\n go_to_edit_profile_page\n verify_unable_to_upload_non_image_file \"PDFDocument\"\n end",
"def test02()\n begin\n tempFile = nil\n baseImageName = \"DSCN0749-Bloom.jpg\"\n inputImageFile = File.join($directory, \"images/DSCN0749.JPG\")\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n objectName = SecureRandom.uuid\n makeImporterCommand = CommandModule.make_createimporter(inputImageFile,\n name: objectName)\n importerObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: objectName)\n theCommands.add_command(makeImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(importerObject)\n \n objectName = SecureRandom.uuid\n imageDims = SpotlightCommand.get_imagedimensions(inputImageFile)\n makeWindowContextCommand = CommandModule.make_createwindowcontext(\n width: imageDims[:width],\n height: imageDims[:height],\n borderlesswindow: true,\n name: objectName)\n windowObject = SmigIDHash.make_objectid(objecttype: :nsgraphicscontext,\n objectname: objectName)\n theCommands.add_command(makeWindowContextCommand)\n theCommands.add_tocleanupcommands_closeobject(windowObject)\n drawImageElement = MIDrawImageElement.new\n drawImageElement.set_imagefile_imagesource(source_object: importerObject,\n imageindex: 0)\n imageDims = SpotlightCommand.get_imagedimensions(inputImageFile)\n destRect = MIShapes.make_rectangle(size: imageDims)\n drawImageElement.destinationrectangle = destRect\n drawElementCommand = CommandModule.make_drawelement(windowObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawElementCommand)\n filterChain = MIFilterChain.new(windowObject)\n \n filter = MIFilter.new(:CIBloom)\n radiusProperty = MIFilterProperty.make_cinumberproperty(key: :inputRadius,\n value: 20.0)\n filter.add_property(radiusProperty)\n intensityProperty = MIFilterProperty.make_cinumberproperty(\n key: :inputIntensity, value: 0.6)\n filter.add_property(intensityProperty)\n importerObject[:imageindex] = 0\n inputImageProp= MIFilterProperty.make_ciimageproperty(value: importerObject)\n filter.add_property(inputImageProp)\n filterChain.add_filter(filter)\n filterChainObjectName = SecureRandom.uuid\n filterChainObject = SmigIDHash.make_objectid(objecttype: :imagefilterchain,\n objectname: filterChainObjectName)\n makeFilterChainCommand = CommandModule.make_createimagefilterchain(\n filterChain,\n name: filterChainObjectName)\n theCommands.add_command(makeFilterChainCommand)\n theCommands.add_tocleanupcommands_closeobject(filterChainObject)\n renderFilterChain = MIFilterChainRender.new\n theRect = MIShapes.make_rectangle(xloc: \"0.25 * $imagewidth\",\n yloc: \"0.33 * $imageheight\",\n width: \"0.5 * $imagewidth\",\n height: \"0.4 * $imageheight\")\n variables = { :imagewidth => imageDims[:width],\n :imageheight => imageDims[:height] }\n renderFilterChain.sourcerectangle = theRect\n renderFilterChain.destinationrectangle = theRect\n# renderFilterChain.variables = variables\n makeRenderFilterChainCommand = CommandModule.make_renderfilterchain(\n filterChainObject, renderinstructions: renderFilterChain,\n createimage: true)\n theCommands.add_command(makeRenderFilterChainCommand)\n theCommands.variables = variables\n exporterName = SecureRandom.uuid\n pathtofile = File.join(Dir.tmpdir(), baseImageName)\n createExporterCommand = CommandModule.make_createexporter(pathtofile,\n export_type: :\"public.jpeg\",\n name: exporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: exporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n windowObject, imageindex: 0)\n theCommands.add_command(addImageToExporterCommand)\n exportCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportCommand)\n Smig.perform_commands(theCommands)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 3)\n # 10. Report if different.\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts \"Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def scanned_prof_image\n scanned_prof\n end",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def test_thumbnail_creation\n\t\tdoc = nil\n\t\tassert_difference(Document, :count, 2) do\n\t\t\tfile_data = fixture_file_upload('/files/upload.jpg','image/jpeg')\n\t\t\tdoc = DocImage.new({:uploaded_data=>file_data, :site_select=>sites(:arusha).id})\n\t\t\tdoc.user = users(:login)\n\t\t\tassert doc.save\n\t\tend\n\t\t# check that pic was stored as expected\n\t\tpic = Document.find_by_filename('upload.jpg')\n\t\tassert_equal doc, pic\n\t\tassert pic.is_a?(DocImage)\n\t\tassert_equal 448, pic.width\n\t\tassert_equal 604, pic.height\n\t\tassert_equal 128303, pic.size\n\t\tassert_equal users(:login), pic.user\n\t\t# check that thumbnail was generated as expected\n\t\tthumb = pic.thumbnails.find_by_thumbnail('thumb')\n\t\tassert thumb.is_a?(DocImage)\n\t\tassert_equal 74, thumb.width\n\t\tassert_equal 100, thumb.height\n\t\t#assert_equal 'upload_t.jpg', thumb.filename\n\t\tassert_equal sites(:arusha), thumb.site\n\t\tassert_equal users(:login), thumb.user\n\t\tassert(thumb.size > 0)\n\t\tassert(thumb.content.size > 0)\n\t\t# remove the document and it's thumb\n\t\tassert_difference(Document, :count, -2) do\n\t\t\tassert pic.destroy.frozen?\n\t\tend\n\t\t\n\t\t# test with image smaller than scaling\n\t\tdoc = nil\n\t\tassert_difference(Document, :count, 2) do\n\t\t\tfile_data = fixture_file_upload('/files/upload64.jpg','image/jpeg')\n\t\t\tdoc = DocImage.new({:uploaded_data=>file_data, :site_select=>sites(:arusha).id})\n\t\t\tdoc.user = users(:login)\n\t\t\tassert doc.save\n\t\tend\n\t\t# check that pic was stored as expected\n\t\tpic = Document.find_by_filename('upload64.jpg')\n\t\tassert_equal doc, pic\n\t\tassert pic.is_a?(DocImage)\n\t\tassert_equal 64, pic.width\n\t\tassert_equal 64, pic.height\n\t\tassert_equal 7261, pic.size\n\t\tassert_equal users(:login), pic.user\n\t\t# check that thumbnail was generated as expected\n\t\tthumb = pic.thumbnails.find_by_thumbnail('thumb')\n\t\tassert thumb.is_a?(DocImage)\n\t\tassert_equal 64, thumb.width\n\t\tassert_equal 64, thumb.height\n\t\t#assert_equal 'upload64_t.jpg', thumb.filename\n\t\tassert_equal sites(:arusha), thumb.site\n\t\tassert_equal users(:login), thumb.user\n\t\tassert(thumb.size > 0)\n\t\tassert(thumb.content.size > 0)\n\t\t# remove the document and it's thumb\n\t\tassert_difference(Document, :count, -2) do\n\t\t\tassert pic.destroy.frozen?\n\t\tend\n\tend",
"def conforms_to_image\n return true if @uti == \"com.adobe.photoshop-image\"\n return true if @uti == \"com.adobe.illustrator.ai-image\"\n return true if @uti == \"com.compuserve.gif\"\n return true if @uti == \"com.microsoft.bmp\"\n return true if @uti == \"com.microsoft.ico\"\n return true if @uti == \"com.truevision.tga-image\"\n return true if @uti == \"com.sgi.sgi-image\"\n return true if @uti == \"com.ilm.openexr-image\"\n return true if @uti == \"com.kodak.flashpix.image\"\n return true if @uti == \"public.fax\"\n return true if @uti == \"public.jpeg\"\n return true if @uti == \"public.jpeg-2000\"\n return true if @uti == \"public.tiff\"\n return true if @uti == \"public.camera-raw-image\"\n return true if @uti == \"com.apple.pict\"\n return true if @uti == \"com.apple.macpaint-image\"\n return true if @uti == \"public.png\"\n return true if @uti == \"public.xbitmap-image\"\n return true if @uti == \"com.apple.quicktime-image\"\n return true if @uti == \"com.apple.icns\"\n return false\n end",
"def shrink_to_one image, xpos, ypos, width, height\n# if @intermediate_images\n# tmp_image = \"vo-#{xpos}-#{ypos}\".to_sym\n# copy_subimage image, xpos, ypos, width, height, tmp_image\n# d_write_image(tmp_image)\n# end\n img = get_image(image)\n checkbox_pixels = img.excerpt(xpos, ypos, width, height)\n shrink_to_one = checkbox_pixels.scale(1,1)\n return shrink_to_one.get_pixels(0,0,1,1)[0].red\n end",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def normalize_photo(photo)\n get_photo_response = get_photo(photo.id)\n sizes = client.photos.getSizes(photo_id: photo.id)\n {\n source: 'flickr',\n key: photo.id,\n photo_thumbnail: get_photo_size(sizes, 'Thumbnail'),\n photo_small: get_photo_size(sizes, 'Small 400'),\n photo_medium: get_photo_size(sizes, 'Medium 800'),\n photo_large: get_photo_size(sizes, 'Large 1600'),\n created_at: get_photo_response.dateuploaded,\n url: Flickr.url_photopage(photo),\n description: get_photo_response.description,\n title: get_photo_response.title,\n }\n end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def crop(rect)\n if self.scale > 1.0\n rect = CGRectMake(rect.origin.x * self.scale,\n rect.origin.y * self.scale,\n rect.size.width * self.scale,\n rect.size.height * self.scale)\n end\n\n cgimage = CGImageCreateWithImageInRect(self.CGImage, rect)\n result = UIImage.imageWithCGImage(cgimage, scale:self.scale, orientation:self.imageOrientation)\n\n return result\n end",
"def rm_centroid_on(corner)\n c = @grom.rm_crop_area(corner)\n p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)\n # byebug\n n = NPatch.new(p, c.w, c.h)\n cx, cy, sd = n.centroid\n st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)\n status = st ? :edgy : :ok\n return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def rotate_image(image)\n\nend"
] |
[
"0.6463487",
"0.596406",
"0.5716911",
"0.5609173",
"0.5600361",
"0.55608743",
"0.55219686",
"0.5446535",
"0.53948486",
"0.52019495",
"0.5163967",
"0.5124965",
"0.51209027",
"0.50989497",
"0.5086853",
"0.50702876",
"0.4986477",
"0.49540937",
"0.49487537",
"0.49201196",
"0.48868376",
"0.4860178",
"0.48551816",
"0.48531708",
"0.48362103",
"0.48323956",
"0.48178545",
"0.4816711",
"0.48124135",
"0.48046607",
"0.47976902",
"0.47905222",
"0.47858587",
"0.47612697",
"0.47528324",
"0.4741893",
"0.47343153",
"0.47339693",
"0.47251037",
"0.472358",
"0.47234392",
"0.4711034",
"0.47102776",
"0.46417668",
"0.46403643",
"0.4619366",
"0.46018583",
"0.45900494",
"0.45874256",
"0.45768407",
"0.4566778",
"0.45607987",
"0.45459926",
"0.454413",
"0.45359755",
"0.45356265",
"0.45211098",
"0.45198554",
"0.45166135",
"0.450922",
"0.4505364",
"0.4498899",
"0.4498187",
"0.44853508",
"0.44805878",
"0.44756487",
"0.44690275",
"0.44669035",
"0.44599694",
"0.44581524",
"0.4458093",
"0.44367993",
"0.44115096",
"0.44081604",
"0.4408033",
"0.44030195",
"0.44024518",
"0.4388876",
"0.43886423",
"0.4380904",
"0.43807656",
"0.43775463",
"0.43771815",
"0.43687806",
"0.43615946",
"0.43615898",
"0.43604603",
"0.4359672",
"0.43563756",
"0.4353884",
"0.4346367",
"0.4346344",
"0.43444893",
"0.43433368",
"0.4328005",
"0.43241954",
"0.43196052",
"0.4311906",
"0.430777",
"0.430716"
] |
0.51649195
|
10
|
Detect and unskew a photo of a document Detect and unskew a photo of a document (e.g. taken on a cell phone) into a perfectly square image. Great for document scanning applications; once unskewed, this image is perfect for converting to PDF using the Convert API or optical character recognition using the OCR API.
|
def preprocessing_unskew_with_http_info(image_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PreprocessingApi.preprocessing_unskew ...'
end
# verify the required parameter 'image_file' is set
if @api_client.config.client_side_validation && image_file.nil?
fail ArgumentError, "Missing the required parameter 'image_file' when calling PreprocessingApi.preprocessing_unskew"
end
# resource path
local_var_path = '/ocr/preprocessing/image/unskew'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'text/json', 'application/xml', 'text/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['imageFile'] = image_file
# http body (model)
post_body = nil
auth_names = ['Apikey']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PreprocessingApi#preprocessing_unskew\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def recognize_detect_and_unskew_document(image_file, opts = {})\n data, _status_code, _headers = recognize_detect_and_unskew_document_with_http_info(image_file, opts)\n data\n end",
"def recognize_detect_and_unskew_document_with_http_info(image_file, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RecognizeApi.recognize_detect_and_unskew_document ...'\n end\n # verify the required parameter 'image_file' is set\n if @api_client.config.client_side_validation && image_file.nil?\n fail ArgumentError, \"Missing the required parameter 'image_file' when calling RecognizeApi.recognize_detect_and_unskew_document\"\n end\n # resource path\n local_var_path = '/image/recognize/detect-document/unskew'\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', 'application/xml', 'text/xml'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n header_params[:'PostProcessingEffect'] = opts[:'post_processing_effect'] if !opts[:'post_processing_effect'].nil?\n\n # form parameters\n form_params = {}\n form_params['imageFile'] = image_file\n\n # http body (model)\n post_body = nil\n auth_names = ['Apikey']\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 => 'String')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RecognizeApi#recognize_detect_and_unskew_document\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def deskew image\n m_begin \"deskew\"\n set_variable(image, get_image(image).deskew)\n m_end \"deskew\"\n end",
"def deskew_image(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end",
"def deskew_angle(img)\n temp = Tempfile.new 'split-subjects-vertically'\n sample = img.clone\n # inset crop 10% from borders:\n sample_inset = 0.10\n sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)\n sample.write temp.path\n sample.write \"temp.sample.jpg\"\n angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f\n # If angle is greater than this, it's probably an error\n angle.abs >= 2 ? 0 : angle\nend",
"def recognize_text_on_pic(pic_location = nil)\n img = process_image(pic_location)\n tess = RTesseract.new(img)\n tess.to_s # recognize\n end",
"def single_image\n page_number = 1\n\n input_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.jpg\"\n image = Magick::Image.read(input_image_path)[0]\n json_path =\"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/output-#{page_number}-to-#{page_number}.json\"\n json_text = File.read(json_path)\n json = JSON.parse(json_text)\n\n bounding_box = json[\"responses\"].first[\"textAnnotations\"][1][\"boundingPoly\"]\n vertices = bounding_box[\"vertices\"]\n\n draw = Magick::Draw.new\n\n # For drawing boxes around all words.\n # text_annotations = json[\"responses\"].first[\"textAnnotations\"][1..-1]\n # text_annotations.each do |text_annotation|\n # bounding_box = text_annotation[\"boundingPoly\"]\n # vertices = bounding_box[\"vertices\"]\n\n # p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n # p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n # p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n # p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n # draw.line(p1[0],p1[1], p2[0], p2[1])\n # draw.line(p1[0],p1[1], p3[0], p3[1])\n # draw.line(p2[0],p2[1], p4[0], p4[1])\n # draw.line(p3[0],p3[1], p4[0], p4[1])\n # end\n\n # For drawing colored boxes around all symbols\n\n confidence_symbols_to_colors = {\n very_confidence: '#BED1D8',\n moderately_confidence: '#FFAE03',\n sort_of_confidence: '#E67F0D',\n low_confidence: '#E9190F'\n }\n\n numbers_to_confidence_symbols = {\n 80..100 => :very_confidence,\n 50..80 => :moderately_confidence,\n 31..50 => :sort_of_confidence,\n 0..30 => :low_confidence\n }\n\n pages = json[\"responses\"].first[\"fullTextAnnotation\"]['pages']\n blocks = pages.map{|p| p['blocks'] }.flatten.compact\n paragraphs = blocks.map{|b| b['paragraphs'] }.flatten.compact\n words = paragraphs.map{|p| p['words'] }.flatten.compact\n symbols = words.map{|w| w['symbols'] }.flatten.compact\n symbol_total = symbols.count\n symbols.each.with_index do |symbol, index|\n puts \"Processing symbol #{index} of #{symbol_count}\"\n bounding_box = symbol[\"boundingBox\"]\n vertices = bounding_box[\"vertices\"]\n confidence_number = (symbol['confidence'] * 100).to_i\n confidence_symbol = numbers_to_confidence_symbols.select{|n| n === confidence_number }.values.first\n color = confidence_symbols_to_colors[confidence_symbol]\n\n draw.stroke(color)\n draw.stroke_width(5)\n\n p1 = [ vertices[0]['x'], vertices[0]['y'] ]\n p2 = [ vertices[1]['x'], vertices[1]['y'] ]\n p3 = [ vertices[3]['x'], vertices[3]['y'] ]\n p4 = [ vertices[2]['x'], vertices[2]['y'] ]\n\n draw.line(p1[0],p1[1], p2[0], p2[1])\n draw.line(p1[0],p1[1], p3[0], p3[1])\n draw.line(p2[0],p2[1], p4[0], p4[1])\n draw.line(p3[0],p3[1], p4[0], p4[1])\n\n draw.draw(image)\n end\n output_image_path = \"/Users/kyle/Dropbox/code/kyletolle/handwriting_transcription/page#{page_number}.5px.symbols.jpg\"\n image.write(output_image_path)\nend",
"def clean_img\n\t\t\tname = 'simple-ocr'\n\t\t\tg = Gem::Specification.find_by_name(name)\n\t\t\t`sh #{File.join(g.full_gem_path, 'lib/textcleaner')} -g -e stretch -f 25 -o 20 -t 30 -u -s 1 -T -p 20 '#{@image}' '#{@clean_image}'`\n\t\tend",
"def readText(qxd = 915, qyd = 76, axd = 388, ayd = 42, qx0 = 335, qy0 = 659, aAx0 = 366, aAy0 = 765, aDx0 = 913, aDy0 = 840) #for default measurements to function correctly, left edge of game screen should be around 190 pixels in.\n\t#r = rand(100000).to_s\n\t#system('screencapture /Users/rorycampbell/Documents/smallfrybeta/screenshot' + r + '.jpg')\n\t#img = Magick::Image.read('screenshot' + r + '.jpg').first\n\timg = Magick::Image.read('screenshotPNI.jpg').first\n\tquestion = img.crop(qx0, qy0, qxd, qyd, true).bilevel_channel(17000)\n\tanswerA = img.crop(aAx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerB = img.crop(aDx0, aAy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerC = img.crop(aAx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\tanswerD = img.crop(aDx0, aDy0, axd, ayd, true).bilevel_channel(17000)\n\n\n\tquestion.write('question.jpg')\n\tanswerA.write('answerA.jpg')\n\tanswerB.write('answerB.jpg')\n\tanswerC.write('answerC.jpg')\n\tanswerD.write('answerD.jpg')\n\n\te = Tesseract::Engine.new {|e|\n\t e.language = :eng\n\t e.blacklist = '|_'\n\t}\n\n\tq = e.text_for('question.jpg').strip.gsub(/\\n/,\" \")\n\taA = e.text_for('answerA.jpg').strip \n\taB = e.text_for('answerB.jpg').strip \n\taC = e.text_for('answerC.jpg').strip \n\taD = e.text_for('answerD.jpg').strip\n\n\tqAndA = []\n\tqAndA << q << aA << aB << aC << aD\n\tqAndA.each do |text|\n\t\ttext.gsub!(')’','y')\n\tend\n\n\treturn qAndA \nend",
"def ocr_proc(img)\n Tesseract::Engine.new do |e|\n e.image = img\n end\n end",
"def preprocessing_unskew(image_file, opts = {})\n data, _status_code, _headers = preprocessing_unskew_with_http_info(image_file, opts)\n data\n end",
"def process_image_black_and_white\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n OpenCV::Cv::cvtColor(image, image, OpenCV::Cv::COLOR_BGR2GRAY)\n\n size = OpenCV::Cv::Size.new(5,5)\n OpenCV::Cv::GaussianBlur(image, image, size, 0)\n OpenCV::Cv::adaptive_threshold(image, image, 251, OpenCV::CV_ADAPTIVE_THRESH_GAUSSIAN_C, OpenCV::CV_THRESH_BINARY, 19, 11)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_black_and_white = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_black_and_white\n end",
"def detect_marks inimage, x, y, width, height, direction, threshold, rowcol, minsize, outimage, segments, comment \n copy_subimage inimage, x, y, width, height, outimage\n d_write_image outimage, comment+\"_subimage\"\n project_image outimage, direction\n d_write_image outimage, comment+\"_projected\"\n threshold outimage, threshold\n d_write_image outimage, comment+\"_thresholded\"\n find_black_segments rowcol, outimage, segments, minsize\n end",
"def process_2up(pdf_file, work_dir, prefix, image_type)\n image_option = image_type_to_pdfimages_option(image_type)\n # The output should be work_dir + prefix with a \"/\" in between, either from work_dir or added in if needed\n output = work_dir + (work_dir[-1] != \"/\" ? \"/\" : \"\") + prefix\n\n # Extract the PDF pages as the appropriate image type\n result = `pdfimages #{image_option} #{pdf_file} #{output}`\n\n last_page = 0\n # Split out the image pages into new images, each of which is one page of the original\n # Delete the original image file.\n # TODO .jpg here should be fixed\n # Remember the highest page number (in the original PDF)\n files = Dir.glob(output + \"-*.jpg\")\n files.each() {\n |file|\n if file =~ /#{prefix}-(\\d+).jpg/\n last_page = $1.to_i() unless last_page > $1.to_i()\n else\n next # Do not touch files that do not meet the naming pattern\n end\n puts(\"process file [#{file}] ... current last page: #{last_page}\")\n # Split the page into two.\n `convert -crop 100%x50% +repage #{file} #{file}`\n File.delete(file)\n }\n\n # The split out pages are numbered [0 ... last_pdf_page -1]\n # From now, consider pages to be [1 ... last_page]\n last_page += 1\n \n # Now we have a set of files with names like #{prefix}-PPP-NN.jpg\n # where PPP is the original PDF page number and NN is 00 for the upper part of the\n # original page and 01 for the lower part of the original page.\n # Rotate +90 when PPP is even and +270 (i.e. -90) when PPP is odd.\n 1.upto(last_page) {\n |ppp|\n rotation = ppp.odd?() ? 90 : 270\n [\"0\", \"1\"].each() {\n |nn|\n fname = \"#{output}-%3.3d-#{nn}.jpg\" % (ppp - 1)\n output_page_number = (nn == \"0\") ? ppp : (2*last_page) - (ppp -1)\n puts(\"Working on #{fname} for output page #{output_page_number}\")\n `convert -rotate #{rotation} #{fname} #{output}-final-#{\"%4.4d\" % output_page_number}.jpg`\n File.delete(fname)\n output_page_number += 1\n }\n }\n\n # Put all the final files together into one PDF\n `convert #{output}-final-*.jpg #{output}-final.pdf`\n puts(\"Resulting pdf: #{output}-final.pdf\")\nend",
"def convert_result\n convert_text\n RTesseract::Utils.remove_files([file_with_ext])\n end",
"def convert_document_to_img_or_flatten\n if document_extension.microsoft_file?\n ConvertMicrosoftFileToPdfJob.perform_later(self.id)\n elsif document_extension.image_file?\n ConvertDocumentImgToPdfJob.perform_later(self.id)\n elsif document_extension.pdf_file?\n if is_source_chat?\n #If document came in as drag and drop in web app chat, then just flatten\n #it. Don't convert it to pages yet - that will be done when this doc\n #is saved.\n FlattenPdfJob.perform_later(self.id)\n else\n ConvertDocumentPdfToImgJob.perform_later(self.id)\n end\n else\n SlackHelper.ping({channel: \"#errors\", username: \"DocumentExtensionService\", message: \"Invalid file extension when trying to convert Document: #{self.id}\"})\n end\n end",
"def black_and_white\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.quantize(256, Magick::GRAYColorspace)\n img.write('public' + @photo.attachment_url)\n end",
"def recreate\n #photo = Photo.find(params[:id])\n #degrees = if params[:direction] == 'left' then -90 else 90 end\n\n #~ #main photo\n #~ image = Magick::ImageList.new(photo.file)\n #~ image = image.rotate(degrees)\n #~ image.write(photo.file)\n\n # thumb\n @photoset = Photoset.find(params[:id])\n #@photos = Photo.find(:all)\n for photo in @photoset.photos \n # render :text => photo.id and return\n photo = Photo.find(photo.id)\n if !photo.image.blank?\n original_image = RAILS_ROOT + \"/public/photo/image/#{photo.id}/#{File.basename(photo.image)}\"\n \n main = RAILS_ROOT + \"/public/photo/image/#{photo.id}/main/#{File.basename(photo.image)}\"\n \n #~ thumbnail = RAILS_ROOT + \"/public/photo/image/#{photo.id}/thumbnail/#{File.basename(photo.image)}\"\n \n #~ submain = RAILS_ROOT + \"/public/photo/image/#{photo.id}/submain/#{File.basename(photo.image)}\"\n \n\n \n \n image = Magick::ImageList.new(original_image) \n image = image.change_geometry!('600x450>') { |c, r, i| i.resize!(c, r) } \n image.write(main)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('51x51!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(thumbnail)\n \n #~ image = Magick::ImageList.new(original_image) \n #~ image = image.change_geometry!('97x97!') { |c, r, i| i.resize!(c, r) } \n #~ image.write(submain) \n \n end\n \n end\n render :text => \"image croped\"\n #redirect_to :action => 'index'\n end",
"def extract_first_page_images\n #######\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n Docsplit.extract_images(file.path, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"public/#{self.docsplit_dir}\" )\n \n # def store_path(for_file=filename)\n # # File.join([store_dir, full_filename(for_file)].compact)\n # \"#{self.model.class.to_s.underscore}\" + \"/\" + \"#{mounted_as}\" + \"/\" + \"#{self.model.user.uuid.to_s}\" + \"/\" + \"#{self.model.slug}\" + \"/\" + \"#{(version_name || :original).to_s}\" + \"_\" + \"#{self.file.basename}\" + \".jpg\"\n # end\n # if Rails.env.production?\n # document.store!(new_file=\"#{output_path}/200x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/700x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # document.store!(new_file=\"#{output_path}/1000x/#{document.model.file_name.chomp(document.model.document.file.extension)[0..-2]}_1.jpg}\")\n # end\n # Docsplit.extract_images(document.file.file, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: \"/tmp/uploads/docsplit/#{model.class.to_s.underscore}/#{model.slug}\")\n\n\n # ::Docsplit.extract_images(self.pdf, :size => %w{200x 700x 1000x}, :format => :jpg, :pages => %w{1}, output: output_path)\n # if Rails.env.production?\n # # Rename file folders. \n # FileUtils.mv local_output_path + \"160x\", s3_output_path + \"160x\"\n # FileUtils.mv local_output_path + \"700x\", s3_output_path + \"700x\"\n # FileUtils.mv local_output_path + \"1000x\", s3_output_path + \"1000x\"\n # end\n \n true\n # self\n end",
"def process_image_enhenced\n file_name = \"#{Rails.root}/tmp/temp-#{self.id}.jpg\"\n\n open(file_name, 'wb') do |file|\n file << open(self.image_uncompressed.url).read\n end\n\n image = OpenCV::Cv::Mat.new\n image = OpenCV::Cv::imread file_name\n\n image.convertTo(image, -1, 1.4, 30)\n\n photo = OpenCV::Cv::imwrite \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\", image\n\n file = File.open \"#{Rails.root}/tmp/black_and_white-#{self.id}.png\"\n\n self.image_enhenced = file\n\n begin\n self.save!\n rescue CarrierWave::ProcessingError => error\n raise error.cause\n end\n\n self.exam.check_for_enhenced\n end",
"def ssim_processing(image_file_path,book_original_image)\n\t\tinstance = SSIM.new\n\t\t#Get folder where crop image it is saved\n\t\tfolder_path = get_path_without_image_name(image_file_path)\n\n\t\tinstance.fill_gaussian_kernel\n\t\tindex = instance.image_processing(\"#{folder_path}image_crop.jpg\",book_original_image)\n\t\treturn index\n\tend",
"def square_image_crop\n if (self.crops)\n if !(self.crop_x.nil? || self.crop_y.nil? || self.crop_w.nil? || self.crop_h.nil?)\n @image = MiniMagick::Image.open(self.photo.url)\n # if image is larger than our max screen size, the cropped image will be incorrect (resizing)\n @image.sample(((700/@image[:width].to_f) * 100).to_s + \"%\") if @image[:width] > 700\n @image.crop(\"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\")\n @image.set(\"page\", \"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\") \n self.square_image = @image\n end\n end\n end",
"def scanned_image\n scanned_eligibility\n end",
"def image_for(document)\n master_file_id = document[\"section_id_ssim\"].try :first\n\n video_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('moving image'.titleize) } rescue 0\n audio_count = document[\"avalon_resource_type_ssim\"].count{|m| m.start_with?('sound recording'.titleize) } rescue 0\n\n if master_file_id\n if video_count > 0\n thumbnail_master_file_path(master_file_id)\n elsif audio_count > 0\n asset_path('audio_icon.png')\n else\n nil\n end\n else\n if video_count > 0 && audio_count > 0\n asset_path('hybrid_icon.png')\n elsif video_count > audio_count\n asset_path('video_icon.png')\n elsif audio_count > video_count\n asset_path('audio_icon.png')\n else\n nil\n end\n end\n end",
"def load_and_dark_correct_image(im_set)\n\n im_set.image = FileInteraction.load_image(im_set.image_fn)\n im_set.mask = FileInteraction.load_image(im_set.mask_fn)\n \n if (@dark_image) then\n\n im_set.image = im_set.image.writableInstance\n\n isf = ImageSubtractionFilter.new\n\n isf.setSubtractPlanarImage(true)\n\n isf.setReferenceImage(@dark_image)\n isf.apply(im_set.image)\n\n end\n \n end",
"def extract_cover\n puts 'Extract front cover'\n extract_png(1, 'cover')\n puts 'Extract back cover'\n extract_png(page_count, 'back')\n end",
"def process_plain_text!( backfill = false, ocr = false )\n if backfill\n %x( mkdir #{folder} )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at making directory.\"\n end\n n = PDF::Reader.new(file_path).page_count\n else\n n = PDF::Reader.new(file_path_opt).page_count\n end\n for i in 1..n\n if ocr\n # TODO: This will generate image versions so we need to clean them later\n %x( pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at pdf to ppm. Command: pdftoppm #{file_path_opt} -gray -r 300 -f #{i} -l #{i} -singlefile '#{folder}/#{i}_out'\"\n return false\n end\n Rails.logger.info 'Out: ' + i.to_s + '_out.pgm'\n file_path_txt_stripped = file_path_txt.gsub('.txt','')\n %x( tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at OCR. Command: tesseract '#{folder}/#{i}_out.pgm' '#{folder}/#{i}_#{file_path_txt_stripped}'\"\n return false\n end\n Rails.logger.info 'Out: ' + folder + '/' + i.to_s + '_' + file_path_txt\n # TODO: Clean pgm's here\n file_to_delete = folder + '/' + i.to_s + '_out.pgm'\n File.delete( file_to_delete )\n else\n %x( pdftotext -f #{i} -l #{i} #{file_path_opt} '#{folder}/#{i}_#{file_path_txt}' )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at processing plain text. Command: pdftotext #{file_path} '#{folder}/#{file_path_txt}'\"\n return false\n end\n end\n end\n unless merge_txt_pages!(n)\n Rails.logger.error \"Merging txt files failed.\"\n return false\n end\n %x( cp #{folder}/#{file_path_txt} ../../document_txt_cache )\n unless $?.exitstatus == 0\n Rails.logger.error \"Failed at copying to cache. Command: cp #{folder}/#{file_path_txt} ../../document_txt_cache\"\n return false\n else\n Rails.logger.info 'Processed plain text file'\n return true\n end\n end",
"def scanned_image\n scanned_certificate\n end",
"def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend",
"def sharpen\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.sharpen(0.0, 1.0)\n img.write('public' + @photo.attachment_url)\n end",
"def test_image(photo)\n photo = File.expand_path(photo)\n path = photo.sub(/\\.jpe?g/i, '.copy.jpg')\n FileUtils.cp photo, path\n `automator -i #{path} #{Photoapp.gem_dir(\"lib/adjust-image.workflow\")}`\n\n Photo.new(path, logo, self).write(path)\n end",
"def apply_image_transformation?\n true\n end",
"def main\n ImageManip::inspect_image(@image_path)\n dimensions = ImageManip::get_dimensions(@image_path)\n sharp_pixels = get_accidental_pixels(@sharp_path)\n flat_pixels = get_accidental_pixels(@flat_path)\n edits = Hash.new\n edits[:lower_left] = [dimensions[0] / 2, dimensions[1] / 2]\n edits[:rgb_array] = sharp_pixels\n ImageManip::draw_2D_object(@image_path, './new_staff.gif', edits)\n edits[:lower_left] = [dimensions[0] / 3, dimensions[1] / 3]\n edits[:rgb_array] = flat_pixels\n ImageManip::draw_2D_object('./new_staff.gif', './new_staff.gif', edits)\n end",
"def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end",
"def crop\n\n @user_document_id = params[:document_to_crop_id]\n @user = current_user\n @profile = @user.profile\n @user_document = @user.documents.find(@user_document_id)\n @user_document.crop_x = params[:coordinates][:crop_x].to_i.to_s\n @user_document.crop_y = params[:coordinates][:crop_y].to_i.to_s\n @user_document.crop_w = params[:coordinates][:crop_w].to_i.to_s\n @user_document.crop_h = params[:coordinates][:crop_h].to_i.to_s\n\n begin\n if @user_document.document.reprocess!\n respond_to do |format|\n format.json { render :json => [:user_document_id=>@user_document_id], :status => :ok }\n end\n\n else\n respond_to do |format|\n #format.html { redirect_to(edit_profile_url(@profile), :notice => 'There was an issue with video upload. Please try again') }\n format.json { render :json => [:error_message => 'conversion failure'], :status => :ok }\n end\n end\n\n rescue Paperclip::Errors::NotIdentifiedByImageMagickError\n respond_to do |format|\n #format.html { redirect_to(edit_profile_url(@profile), :notice => 'There was an issue with video upload. Please try again') }\n format.json { render :json => [:error_message => 'cannot convert filetype'], :status => :ok }\n end\n end\n\n end",
"def computeProjection\n w,h = @type==:vertical ? [@image.width, @image.height] : [@image.height, @image.width]\n mw,mh = @type==:vertical ? [@image.width, @image.height-@image.borders.bottom] : [@image.height, @image.width-@image.borders.right]\n content_mask = Array.new(w){[false, 0]}\n\n w.times do |a|\n obj_height = 0\n gap = 0\n (h-mh).times do |b|\n x,y = @type==:vertical ? [a,b] : [b,a]\n idx = @image.index(x, y)\n #p [idx, w, h, mh, a, b, x, y, @image.width, @image.height]\n if @data[idx] <= @threshold\n obj_height += 1\n obj_height += gap if gap <= @image.min_obj_size\n gap = 0\n else\n gap += 1\n content_mask[a] = [true, b] if obj_height > @image.min_obj_size\n obj_height = 0\n end\n end\n end\n\n content_mask\n end",
"def scanned_image\n scanned_retreat\n end",
"def sepia\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.sepiatone()\n img.write('public' + @photo.attachment_url)\n end",
"def manualcrop\n if model.crop?\n x = model.x.to_d\n y = model.y.to_d\n x2 = model.x2.to_d\n y2 = model.y2.to_d\n scale = model.scale.to_d\n\n manipulate! do |img|\n img = img.scale(1/scale)\n img = img.crop(x, y, x2-x, y2-y)\n end\n end\n end",
"def test03()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n size: imageDimensions,\n name: bitmapContextName)\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n theCommands.add_command(createBitmapContextCommand)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n\n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n # FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def no_photo(width, height)\n no_photo_image = part_image.resize_to_fit(width, height)\n create_custom_part(no_photo_image)\n image.to_image\n end",
"def test_get_document_drawing_object_image_data_online\n request_document = File.open(File.join(local_test_folder, local_file))\n request = GetDocumentDrawingObjectImageDataOnlineRequest.new(document: request_document, index: 0, node_path: 'sections/0')\n\n result = @words_api.get_document_drawing_object_image_data_online(request)\n assert_equal false, result.nil?\n end",
"def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend",
"def verify_image(path)\n end",
"def square_images\n @template[:message][:attachment][:payload][:image_aspect_ratio] = 'square'\n self\n end",
"def image_processing\n \tpixel_array_img1 = read_file_image(\"book4_no_table.jpg\")\n \tpixel_array_img2 = read_file_image(\"net_book5.jpg\")\n\n\n \tpixel_array_sq_img1 = []\n \tpixel_array_sq_img2 = []\n \tpixel_array_img1x2 = []\n \t##################FALTA AQUI ALGO\n\n \t###### ARRAY OF PIXEL ARRAY\n \t# SQUARE IMAGE IMG_1\n \tpixel_array_sq_img1 = square_array(pixel_array_img1)\t\t\n\t\tpixel_array_sq_img2 = square_array(pixel_array_img2)\n \tpixel_array_img1x2 = product_array(pixel_array_img1,pixel_array_img2)\n\n\t\t# Apply convolve filter two image array\n\t\timg_1_convolve_filter = convolve(pixel_array_img1,@gaussian_kernel)\n\t\timg_2_convolve_filter = convolve(pixel_array_img2,@gaussian_kernel)\n\n\t\t## Array Square\n\t\timg_1_convolve_filter_sq = square_array(img_1_convolve_filter)\n\t\timg_2_convolve_filter_sq = square_array(img_2_convolve_filter)\n\t\timg_2x1_convolve_filter = product_array(img_1_convolve_filter,img_2_convolve_filter)\n\n\t\t#Convolve FILTER Square IMG1 and IMG2\n\t\timg_1_sq_convolve_filter = convolve(pixel_array_sq_img1,@gaussian_kernel)\n\t\timg_2_sq_convolve_filter = convolve(pixel_array_sq_img2,@gaussian_kernel)\n\n\t\t#Convolve FILTER to Product IMG1 and IMG2 \n\t\timg_1x2_convolve_filter = convolve(pixel_array_img1x2,@gaussian_kernel)\n\n\t\timg_1_sq_convolve_filter = difference_array(img_1_sq_convolve_filter,img_1_convolve_filter_sq)\n\t\timg_2_sq_convolve_filter = difference_array(img_2_sq_convolve_filter,img_2_convolve_filter_sq)\n\t\timg_1x2_convolve_filter = difference_array(img_1x2_convolve_filter,img_2x1_convolve_filter)\n\n\n\n\t\t#c1/c2 constants\n\t #First use: manual fitting\n\t c_1=6.5025\n\t c_2=58.5225\n\t \n\t #Second use: change k1,k2 & c1,c2 depend on L (width of color map)\n\t l=255\n\t k_1=0.01\n\t c_1=(k_1*l)**2\n\t k_2=0.03\n\t c_2=(k_2*l)**2\n\t \n\t #Numerator of SSIM\n\t num_ssim = \n\t product_array(\n\t \tmultiple_and_factor_increment(2,img_2x1_convolve_filter,c_1),\n\t \tmultiple_and_factor_increment(2,img_1x2_convolve_filter,c_2))\n\t ##Denominator of SSIM\n\t den_ssim = product_array(sum_two_array_and_incremente(img_1_convolve_filter_sq,img_2_convolve_filter_sq,c_1),sum_two_array_and_incremente(img_1_sq_convolve_filter,img_2_sq_convolve_filter,c_2))\n\t ##SSIM\n\t index = division_and_average(num_ssim,den_ssim)\n\n\t puts index\n\n end",
"def test05()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage_a05.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n drawImageElement.contextalpha = 0.5\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n # tempFile = File.join($compareImageDir, baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\n end\nend",
"def normalize(file_type)\n return @img_data if file_type == 'pdf'\n\n label_image = MiniMagick::Image.read(@img_data)\n label_image.combine_options do |img|\n img.rotate(90) if label_image.width > label_image.height\n img.rotate(180) if [:fedex].include?(@carrier)\n img.bordercolor('#ffffff')\n img.border('1x1')\n img.trim\n end\n\n @img_data = label_image.to_blob\n end",
"def test02()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage.jpg\"\n begin\n # Create the object that will contain the list of commands.\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n\n # Create the name for the importer object.\n importerName = SecureRandom.uuid\n \n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n theCommands.add_command(createImporterCommand)\n\n # Create the image importer object id so we can refer to it later on.\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n\n # Get the dimensions of the image at image index 0 in the image file.\n # So we can calculate how big the bitmap context can be.\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n\n # Create the bitmap context object command but first make the name\n bitmapContextName = SecureRandom.uuid\n createBitmapContextCommand = CommandModule.make_createbitmapcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: bitmapContextName)\n\n # Add the create bitmap context to the list of commands\n theCommands.add_command(createBitmapContextCommand)\n\n # Create the bitmapcontext object id so we can refer to it later on.\n bitmapContextObject = SmigIDHash.make_objectid(objecttype: :bitmapcontext,\n objectname: bitmapContextName)\n\n # Prepare for the draw element action.\n # The draw element action will draw a rotated image into the bitmapcontext\n width = imageDimensions[:width] * 0.5\n height = imageDimensions[:height] * 0.5\n x = width * 0.5\n y = height * 0.5\n theSize = MIShapes.make_size(width, height)\n theOrigin = MIShapes.make_point(x, y)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n contextTransform = MITransformations.make_contexttransformation()\n MITransformations.add_translatetransform(contextTransform,\n { :x => width, :y => height })\n MITransformations.add_rotatetransform(contextTransform, Math::PI / 4.0)\n MITransformations.add_translatetransform(contextTransform,\n { :x => -width, :y => -height })\n drawImageElement.contexttransformations = contextTransform\n\n # Create the drawelement command.\n drawCommand = CommandModule.make_drawelement(bitmapContextObject,\n drawinstructions: drawImageElement)\n\n # Add the draw element command to the list of commands.\n theCommands.add_command(drawCommand)\n\n # Prepare for creating the image exporter object command\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n \n # Make the image file export object command.\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n \n # Make the add an image to the exporter object command.\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, bitmapContextObject)\n theCommands.add_command(addImageToExporterCommand)\n \n # Make the do export command\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n\n # Add close object commands to the cleanup command list.\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n theCommands.add_tocleanupcommands_closeobject(bitmapContextObject)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n\n # now actually carry out the commands.\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n unless tempFile.nil?\n FileUtils.rm_f(tempFile)\n # Open3.capture2(\"open\", origFile)\n # Open3.capture2(\"open\", tempFile)\n end\n end\nend",
"def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end",
"def test04()\n imageFile = $directory + \"/images/DSCN0733.JPG\"\n baseImageName = \"rotatedimage2.jpg\"\n begin\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n importerName = SecureRandom.uuid\n createImporterCommand = CommandModule.make_createimporter(imageFile,\n name: importerName)\n imageImporterObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: importerName)\n theCommands.add_command(createImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(imageImporterObject)\n imageDimensions = SpotlightCommand.get_imagedimensions(imageFile)\n windowContextName = SecureRandom.uuid\n createWindowContextCommand = CommandModule.make_createwindowcontext(\n width: imageDimensions[:width],\n height: imageDimensions[:height],\n name: windowContextName)\n windowContextObject = SmigIDHash.make_objectid(\n objecttype: :nsgraphicscontext,\n objectname: windowContextName)\n theCommands.add_command(createWindowContextCommand)\n theCommands.add_tocleanupcommands_closeobject(windowContextObject)\n\n # Need to initialize the window to having a white background.\n windowRect = MIShapes.make_rectangle(size: imageDimensions,\n origin: { :x => 0, :y => 0 } )\n whiteColor = MIColor.make_rgbacolor(1.0, 1.0, 1.0)\n drawBackgroundElement = MIDrawElement.new(:fillrectangle)\n drawBackgroundElement.rectangle = windowRect\n drawBackgroundElement.fillcolor = whiteColor\n \n theSize = MIShapes.make_size(imageDimensions[:width] * 0.5,\n imageDimensions[:height] * 0.5)\n theOrigin = MIShapes.make_point(imageDimensions[:width] * 0.25,\n imageDimensions[:height] * 0.25)\n sourceRect = MIShapes.make_rectangle(size: theSize, origin: theOrigin)\n destRect = sourceRect\n drawImageElement = MIDrawImageElement.new()\n drawImageElement.set_imagefile_imagesource(source_object: imageImporterObject,\n imageindex: 0)\n drawImageElement.destinationrectangle = destRect\n affineTransform = MITransformations.make_affinetransform(\n m11: 0.707, m12: 0.707, m21: -0.707,\n m22: 0.707, tX: 373.74, tY: -221.29)\n drawImageElement.affinetransform = affineTransform\n drawElements = MIDrawElement.new(:arrayofelements)\n drawElements.add_drawelement_toarrayofelements(drawBackgroundElement)\n drawElements.add_drawelement_toarrayofelements(drawImageElement)\n # With the draw element put together, now create the draw element command\n drawCommand = CommandModule.make_drawelement(windowContextObject,\n drawinstructions: drawElements)\n theCommands.add_command(drawCommand)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n imageExporterName = SecureRandom.uuid\n createExporterCommand = CommandModule.make_createexporter(tempFile,\n export_type: \"public.jpeg\",\n name: imageExporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: imageExporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(\n exporterObject, windowContextObject)\n theCommands.add_command(addImageToExporterCommand)\n exportImageToFileCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportImageToFileCommand)\n commandsHash = theCommands.commandshash\n $teststring = commandsHash.to_json\n theResult = Smig.perform_commands(commandsHash)\n puts \"The result is: \" + theResult unless theResult.length.zero?\n\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 0)\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts $teststring + \" Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n FileUtils.rm_f(tempFile) unless tempFile.nil?\n # Open3.capture2(\"open\", tempFile)\n # Open3.capture2(\"open\", origFile)\n end\nend",
"def extract_graphic\n if !Cache.screenshot(@save_number, header).nil?\n bitmap_screenshot = Cache.screenshot(@save_number, header)\n @screenshot.zoom_x = 2\n @screenshot.zoom_y = 2\n else @virtualb = DataManager.load_screenshot(@save_number)\n if @virtualb.nil?\n bitmap_screenshot = black_bitmap\n else\n bitmap_screenshot = @virtualb.get_bitmap\n @screenshot.zoom_x = 2\n @screenshot.zoom_y = 2\n Cache.add_screenshot(@save_number, bitmap_screenshot, header[:key])\n end\n end\n @screenshot.bitmap = bitmap_screenshot\n @screenshot_loaded = false\n @loading_bar.disappear\n end",
"def get_image_credit(page_doc)\n\timage_credit = page_doc.css('body center:nth-child(2)')\n\timage_credit.search('.//b')[0].remove\n\timage_credit.search('.//br').remove\n\timage_credit.search('center').remove\n\treturn image_credit.inner_html.strip!\nend",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color disimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def glean\n update_and_decorate\n @what = params[:what].to_sym\n @pageurl = params[:url] # To glean images from another page\n if @gleaning = GleaningServices.completed_gleaning_for((@pageurl || @decorator.object), 'Image')\n if @gleaning.bad?\n @decorator.errors.add :gleaning, \"encountered HTTP #{@gleaning.http_status} error: #{@gleaning.err_msg}\"\n end\n if @gleaning.errors.present?\n flash.now[:error] = \"Can't extract images from there: #{@gleaning.errors.messages}\"\n elsif @gleaning.images.blank?\n flash.now[:error] = 'Sorry, we couldn\\'t get any images from that page.'\n else\n flash.now[:success] = 'Images found! Click on an image from the list below to select it.'\n end\n else\n flash.now[:error] = \"Gleaning can't be done on #{@decorator.collection_name.gsub '_', ''}\"\n end\n end",
"def test_get_document_drawing_object_image_data\n remote_file_name = 'TestGetDocumentDrawingObjectImageData.docx'\n\n upload_file File.join(local_test_folder, local_file), remote_data_folder + '/' + remote_file_name\n\n request = GetDocumentDrawingObjectImageDataRequest.new(name: remote_file_name, index: 0, node_path: 'sections/0', folder: remote_data_folder)\n\n result = @words_api.get_document_drawing_object_image_data(request)\n assert_equal false, result.nil?\n end",
"def show\n # require \"mini_magick\"\n #\n # @codeimage = @code.image\n # croppedcode = @codeimage.cropped\n # compositecode = @codeimage.composite\n # base = Base.last.image\n #\n # newimage = MiniMagick::Image.open(croppedcode.url)\n # baseimage = MiniMagick::Image.open(base.url)\n # newimage.rotate(\"-10\")\n #\n # newimage = baseimage.composite(newimage) do |c|\n # c.compose(\"Darken\")\n # c.geometry(\"200x200+215+70\")\n # c.gravity(\"southeast\")\n # end\n\n\n # newimage.write(@codeimage.composite.url)\n\n if Code.count > 1\n if Code.first.created_at < 7.days.ago\n Code.first.delete\n end\n end\n\n redirect_to root_url\n\n end",
"def convert_image_resource(path)\n puts(\"Updating and trimming image file '#{path}'\")\n image = MiniMagick::Image.open(path)\n image.combine_options do |co|\n co.fuzz(\"90%\") # color dissimilarity threshold to get all shadows, see https://github.com/fastlane/fastlane/pull/14199\n co.trim(\"+repage\") # `+repage` removes meta-data\n end\n image.write(path)\nend",
"def initialize(document)\n @document = document\n\n image_uri = ImageRecognition::ImageUriParser.parse(document)\n ImageRecognition::ImageLoader.save_image(image_uri)\n end",
"def create\n @image = Image.new(image_params)\n @image.text = ''\n respond_to do |format|\n if @image.save\n @image.text = RTesseract.new(Rails.root.join('public', 'assets', @image.id.to_s, @image.url.file.filename).to_s, lang: 'eng+khm', :processor => \"none\")\n @image.update(image_params)\n format.html { redirect_to @image, notice: 'Image was successfully created.' }\n format.json { render :show, status: :created, location: @image }\n else\n format.html { render :new }\n format.json { render json: @image.errors, status: :unprocessable_entity }\n end\n end\n end",
"def postprocess(html_document)\n # if more transforms are added here, some sort of proper pipeline\n # should be considered\n doc = Nokogiri::HTML::DocumentFragment.parse(html_document)\n doc = make_img_src_urls_protocol_relative(doc)\n remove_comments(doc.to_s)\n end",
"def from_blob(blob)\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_from_blob(blob)\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def depolarize\n @image.run_command(\"convert\", @image.path, \"-virtual-pixel Black -distort DePolar 0\", @image.path)\n end",
"def ocr!\n @txt = \"\"\n @areas.each do |area|\n image = Rocrad.new(@src.to_s)\n image.crop!(area[:x].to_i, area[:y].to_i, area[:w].to_i, area[:h].to_i)\n @txt << image.to_s\n end\n @txt\n end",
"def optimize_for_pagespeed\n # according to https://developers.google.com/speed/docs/insights/OptimizeImages\n if self.file.content_type == 'image/jpeg'\n # convert orig.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG orig_converted.jpg\n manipulate! do |img|\n img.sampling_factor '4:2:0'\n img.strip\n img.quality 85\n img.interlace 'JPEG'\n img\n end\n else\n # convert cuppa.png -strip cuppa_converted.png\n manipulate! do |img|\n img.strip\n img\n end\n end\n end",
"def flip\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.flip!\n img.write('public' + @photo.attachment_url)\n end",
"def to_face\n image.crop(crop_params)\n image.write(outfile)\n Face.new(outfile)\n end",
"def imagemagick?; end",
"def testsnapshot(onwindow: false)\n baseImageName = \"AfterDrawSnapshot.jpg\"\n begin\n # 1. Create window or bitmap context. width: 800, height: 600\n bitmapObject = if onwindow\n SmigHelpers.create_window(width: 800, height: 600)\n else\n SmigHelpers.create_bitmapcontext(width: 800, height: 600)\n end\n\n # 2. Try and draw a snapshot\n didThrow = false\n begin\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n rescue RuntimeError => e\n # 3. Take note that drawing the snapshot failed.\n didThrow = true\n end\n\n # 3. Continued. Raise an exception if snapshot failed & exception not thrown\n unless didThrow\n raise \"Draw shapshot should have failed as no snapshot has been taken\"\n end\n\n if onwindow\n # Need to initialize the window to having a white background.\n windowRect = MIShapes.make_rectangle(size:{ :width => 800,\n :height => 600 },\n origin: { :x => 0, :y => 0 } )\n whiteColor = MIColor.make_rgbacolor(1.0, 1.0, 1.0)\n drawBackgroundElement = MIDrawElement.new(:fillrectangle)\n drawBackgroundElement.rectangle = windowRect\n drawBackgroundElement.fillcolor = whiteColor\n drawBackgroundCommand = CommandModule.make_drawelement(bitmapObject, \n drawinstructions: drawBackgroundElement)\n Smig.perform_command(drawBackgroundCommand)\n end\n\n # 4. Draw some stuff into the bitmap context.\n points = []\n points.push(MIShapes.make_point(100, 50))\n points.push(MIShapes.make_point(700, 50))\n points.push(MIShapes.make_point(400, 550))\n newPath = MIPath.new\n newPath.add_triangle(points: points)\n drawElement = MIDrawElement.new(:fillpath)\n drawElement.fillcolor = MIColor.make_rgbacolor(0.8, 0.2, 0.1)\n drawElement.arrayofpathelements = newPath\n drawElement.startpoint = points[0]\n drawElementCommand = CommandModule.make_drawelement(bitmapObject, \n drawinstructions: drawElement)\n Smig.perform_command(drawElementCommand)\n # 5. Take a snapshot\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :takesnapshot))\n # 6. Draw the snapshot into the bitmap context.\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n # 7. Draw some more stuff into it\n points = []\n points.push(MIShapes.make_point(100, 550))\n points.push(MIShapes.make_point(700, 550))\n points.push(MIShapes.make_point(400, 50))\n newPath = MIPath.new\n newPath.add_triangle(points: points)\n drawElement = MIDrawElement.new(:fillpath)\n drawElement.fillcolor = MIColor.make_rgbacolor(0.2, 0.7, 0.1)\n drawElement.arrayofpathelements = newPath\n drawElement.startpoint = points[0]\n drawElementCommand = CommandModule.make_drawelement(bitmapObject,\n drawinstructions: drawElement)\n Smig.perform_command(drawElementCommand)\n # 8. Export an image from the bitmap\n tempFile2 = File.join(Dir.tmpdir(), \"BeforeSnapshot.jpg\")\n SmigHelpers.save_image(imagesource: bitmapObject, pathtofile: tempFile2)\n # 9. Draw the snap shot into the bitmap context\n Smig.perform_command(CommandModule.make_snapshot(bitmapObject,\n snapshottype: :drawsnapshot))\n # 10. Save the bitmap context to an image file.\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n SmigHelpers.save_image(imagesource: bitmapObject, pathtofile: tempFile)\n origFile = File.join($compareImageDir, baseImageName)\n\n unless AreImageFilesSame(origFile, tempFile)\n # 11. Report if different.\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts \"Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n Smig.close_object_nothrow(bitmapObject)\n# `open #{tempFile}`\n# `open #{tempFile2}`\n# `open #{origFile}`\n FileUtils.rm_f(tempFile)\n FileUtils.rm_f(tempFile2)\n end\nend",
"def image_ocr_photo_recognize_form(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_form_with_http_info(image_file, opts)\n data\n end",
"def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end",
"def composing\n background = Image.read('test.png').first\n avatar = Image.read('499317.jpeg').first\n\n avatar_resized = avatar.resize_to_fit(40,40)\n avatar_resized.border!(1, 1, 'black')\n avatar_resized.shadow(2, 5, 3)\n\n marketing_image = background.composite(avatar_resized, 30, 58, OverCompositeOp)\n\n text = \"耀你的命 show me your lives!\"\n\n content = Magick::Draw.new\n content.annotate(marketing_image, 0, 0, 60, 550, text) do\n self.font = './ZuiYouTi-2.ttf'\n self.pointsize = 24\n self.font_weight = Magick::BoldWeight\n self.fill = 'black'\n self.gravity = Magick::SouthEastGravity\n end\n\n\n marketing_image.write(\"marketing_image.png\")\nend",
"def cleanup image\n m_begin \"cleanup\"\n img = get_image(image)\n img = img.gaussian_blur(8)\n img = img.threshold((QuantumRange * 0.999).to_int)\n img = img.gaussian_blur(14)\n img = img.threshold(0)\n m_end \"cleanup\"\n set_variable(image, img)\n end",
"def clean_folder\n return unless cropped_image.croppers.any?\n\n cs = CropperService.new(cropped_image)\n cs.clean_variant_folder\n end",
"def generate_images\n Docsplit.extract_images(@files.to_s)\n end",
"def convert_main\n input = @input\n middle = File.join(@directory, 'middle.pdf')\n cleaned = File.join(@directory, 'cleaned.pdf')\n margins = File.join(@directory, 'margins.pdf')\n resized = File.join(@directory, 'resized.pdf')\n flattened = File.join(@directory, 'flatenned.pdf')\n final = File.join(@directory, 'main.pdf')\n\n puts 'Extract middle part of pdf'\n extract_middle(input, middle)\n\n puts 'Clean the file'\n clean_file(middle, cleaned)\n\n puts 'Add margins'\n add_margins(cleaned, margins)\n\n puts 'Resize and set black and white'\n resize_and_set_black_and_white(margins, resized)\n\n puts 'Remove transparency'\n remove_transparency(resized, flattened)\n\n # Cleanup\n `mv #{flattened.shellescape} #{final.shellescape}`\n `rm #{middle.shellescape}`\n `rm #{cleaned.shellescape}`\n `rm #{margins.shellescape}`\n `rm #{resized.shellescape}`\n end",
"def charcoal\n @photo = Photo.find(params[:id])\n img = Magick::Image.read('public' + @photo.attachment_url).first\n img = img.charcoal(0.0, 1.0)\n img.write('public' + @photo.attachment_url)\n end",
"def getVerifiedImage\n # Ensure that @sourceImage and @overlayPosition is populated.\n populateMissingData\n\n # Add the overlay, and return the binary image data.\n return VerifyMe::composeOverlay(@sourceImage, @overlayPosition, @sourceImageFormat)\n end",
"def image_by_cropping_to_rect(aRect)\n if aRect.is_a? CGRect\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect.origin.x*self.scale, aRect.origin.y*self.scale], [aRect.size.width*self.scale, aRect.size.height*self.scale]])\n else\n cropped = CGImageCreateWithImageInRect(self.CGImage, [[aRect[0][0]*self.scale, aRect[0][1]*self.scale], [aRect[1][0]*self.scale, aRect[1][1]*self.scale]])\n end\n UIImage.imageWithCGImage(cropped, scale:self.scale, orientation:self.imageOrientation)\n end",
"def image_ocr_photo_recognize_receipt(image_file, opts = {})\n data, _status_code, _headers = image_ocr_photo_recognize_receipt_with_http_info(image_file, opts)\n data\n end",
"def clipart\n output = get_working_image(@session_id)\n unless File.exist?(output)\n FileUtils.cp(\"#{Rails.root}/public/#{params[:src]}\", output)\n img = Image.read(output).first\n img = img.scale(params[:rs].to_f) unless params[:rs].blank?\n img = img.level_colors(params[:b] || \"\", params[:w] || \"\", true) if params[:b] || params[:w]\n img.background_color = \"none\"\n img.rotate!(params[:r].to_f) unless params[:r].blank?\n\n #For embroidery\n if params[:emb] == 'true'\n img = img.ordered_dither\n end\n #FLIP/FLOP/Transpose/Transverse\n if params[:ff] == 'flip'\n img.flip!\n elsif params[:ff] == 'flop'\n img.flop!\n elsif params[:ff] == 'transpose'\n img.transpose!\n elsif params[:ff] == 'transverse'\n img.transverse!\n end\n #Extracts a channel\n if params[:ec] == 'R'\n img = img.channel(Magick::RedChannel)\n elsif params[:ec] == 'G'\n img = img.channel(Magick::GreenChannel)\n elsif params[:ec] == 'B'\n img = img.channel(Magick::BlueChannel)\n end\n\n #Applies a special effect to the image - QuantumRange\n img = img.sepiatone(Magick::QuantumRange * params[:qr].to_f) unless params[:qr].blank?\n\n #Vignette (Shape Edge)\n if params[:vig] == 'true'\n img = img.vignette\n end\n\n #Wet Floor\n if params[:wf]\n img = img.wet_floor\n end\n img.write(output)\n end\n img = Image.read(output).first\n send_data img.to_blob, :disposition => 'inline', :type => 'image/png'\n end",
"def processPhotoJob(image)\n image.regenerate_styles!\n end",
"def imgify(tweet)\n return tweet\nend",
"def verify_image\n unless Rails.env.production?\n return true\n end\n # image challenge check\n challenge = @session['uc']\n @session['uc'] = nil\n verify_image = false\n if challenge && @params[:imageChallenge]\n verify_image = challenge.checkResponse(@params[:imageChallenge])\n end\n raise InvalidChallengeValue unless verify_image\n end",
"def rm_centroid_on(corner)\n c = @grom.rm_crop_area(corner)\n p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)\n # puts \"REG #{@grom.rm_blur} - #{@grom.rm_dilate} - C #{c.inspect}\"\n n = NPatch.new(p, c.w, c.h)\n cx, cy, sd = n.centroid\n st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)\n status = st ? :edgy : :ok\n return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}\n end",
"def atest_ID_25836_edit_profile_pic_02\n login_as_user1\n go_to_edit_profile_page\n verify_unable_to_upload_non_image_file \"PDFDocument\"\n end",
"def scanned_prof_image\n scanned_prof\n end",
"def test02()\n begin\n tempFile = nil\n baseImageName = \"DSCN0749-Bloom.jpg\"\n inputImageFile = File.join($directory, \"images/DSCN0749.JPG\")\n theCommands = CommandModule::SmigCommands.new\n theCommands.saveresultstype = :lastcommandresult\n objectName = SecureRandom.uuid\n makeImporterCommand = CommandModule.make_createimporter(inputImageFile,\n name: objectName)\n importerObject = SmigIDHash.make_objectid(objecttype: :imageimporter,\n objectname: objectName)\n theCommands.add_command(makeImporterCommand)\n theCommands.add_tocleanupcommands_closeobject(importerObject)\n \n objectName = SecureRandom.uuid\n imageDims = SpotlightCommand.get_imagedimensions(inputImageFile)\n makeWindowContextCommand = CommandModule.make_createwindowcontext(\n width: imageDims[:width],\n height: imageDims[:height],\n borderlesswindow: true,\n name: objectName)\n windowObject = SmigIDHash.make_objectid(objecttype: :nsgraphicscontext,\n objectname: objectName)\n theCommands.add_command(makeWindowContextCommand)\n theCommands.add_tocleanupcommands_closeobject(windowObject)\n drawImageElement = MIDrawImageElement.new\n drawImageElement.set_imagefile_imagesource(source_object: importerObject,\n imageindex: 0)\n imageDims = SpotlightCommand.get_imagedimensions(inputImageFile)\n destRect = MIShapes.make_rectangle(size: imageDims)\n drawImageElement.destinationrectangle = destRect\n drawElementCommand = CommandModule.make_drawelement(windowObject,\n drawinstructions: drawImageElement)\n theCommands.add_command(drawElementCommand)\n filterChain = MIFilterChain.new(windowObject)\n \n filter = MIFilter.new(:CIBloom)\n radiusProperty = MIFilterProperty.make_cinumberproperty(key: :inputRadius,\n value: 20.0)\n filter.add_property(radiusProperty)\n intensityProperty = MIFilterProperty.make_cinumberproperty(\n key: :inputIntensity, value: 0.6)\n filter.add_property(intensityProperty)\n importerObject[:imageindex] = 0\n inputImageProp= MIFilterProperty.make_ciimageproperty(value: importerObject)\n filter.add_property(inputImageProp)\n filterChain.add_filter(filter)\n filterChainObjectName = SecureRandom.uuid\n filterChainObject = SmigIDHash.make_objectid(objecttype: :imagefilterchain,\n objectname: filterChainObjectName)\n makeFilterChainCommand = CommandModule.make_createimagefilterchain(\n filterChain,\n name: filterChainObjectName)\n theCommands.add_command(makeFilterChainCommand)\n theCommands.add_tocleanupcommands_closeobject(filterChainObject)\n renderFilterChain = MIFilterChainRender.new\n theRect = MIShapes.make_rectangle(xloc: \"0.25 * $imagewidth\",\n yloc: \"0.33 * $imageheight\",\n width: \"0.5 * $imagewidth\",\n height: \"0.4 * $imageheight\")\n variables = { :imagewidth => imageDims[:width],\n :imageheight => imageDims[:height] }\n renderFilterChain.sourcerectangle = theRect\n renderFilterChain.destinationrectangle = theRect\n# renderFilterChain.variables = variables\n makeRenderFilterChainCommand = CommandModule.make_renderfilterchain(\n filterChainObject, renderinstructions: renderFilterChain,\n createimage: true)\n theCommands.add_command(makeRenderFilterChainCommand)\n theCommands.variables = variables\n exporterName = SecureRandom.uuid\n pathtofile = File.join(Dir.tmpdir(), baseImageName)\n createExporterCommand = CommandModule.make_createexporter(pathtofile,\n export_type: :\"public.jpeg\",\n name: exporterName)\n exporterObject = SmigIDHash.make_objectid(objecttype: :imageexporter,\n objectname: exporterName)\n theCommands.add_command(createExporterCommand)\n theCommands.add_tocleanupcommands_closeobject(exporterObject)\n addImageToExporterCommand = CommandModule.make_addimage(exporterObject, \n windowObject, imageindex: 0)\n theCommands.add_command(addImageToExporterCommand)\n exportCommand = CommandModule.make_export(exporterObject)\n theCommands.add_command(exportCommand)\n Smig.perform_commands(theCommands)\n tempFile = File.join(Dir.tmpdir(), baseImageName)\n origFile = File.join($compareImageDir, baseImageName)\n unless AreImageFilesSame(origFile, tempFile, 3)\n # 10. Report if different.\n raise \"Different image files: \" + origFile + \" and \" + tempFile\n end\n rescue RuntimeError => e\n $errorcode = Smig.exitvalue\n unless $errorcode.zero?\n puts \"Exit string: \" + Smig.exitstring\n puts \"Exit status: \" + $errorcode.to_s\n end\n puts e.message\n puts e.backtrace.to_s\n# exit 240\n ensure\n FileUtils.rm_f(tempFile) unless tempFile.nil?\n end\nend",
"def detect_document_text_gcs image_path:\n # [START vision_fulltext_detection_gcs]\n # image_path = \"Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'\"\n\n require \"google/cloud/vision\"\n\n image_annotator = Google::Cloud::Vision::ImageAnnotator.new\n\n response = image_annotator.document_text_detection image: image_path\n\n text = \"\"\n response.responses.each do |res|\n res.text_annotations.each do |annotation|\n text << annotation.description\n end\n end\n\n puts text\n # [END vision_fulltext_detection_gcs]\nend",
"def test_thumbnail_creation\n\t\tdoc = nil\n\t\tassert_difference(Document, :count, 2) do\n\t\t\tfile_data = fixture_file_upload('/files/upload.jpg','image/jpeg')\n\t\t\tdoc = DocImage.new({:uploaded_data=>file_data, :site_select=>sites(:arusha).id})\n\t\t\tdoc.user = users(:login)\n\t\t\tassert doc.save\n\t\tend\n\t\t# check that pic was stored as expected\n\t\tpic = Document.find_by_filename('upload.jpg')\n\t\tassert_equal doc, pic\n\t\tassert pic.is_a?(DocImage)\n\t\tassert_equal 448, pic.width\n\t\tassert_equal 604, pic.height\n\t\tassert_equal 128303, pic.size\n\t\tassert_equal users(:login), pic.user\n\t\t# check that thumbnail was generated as expected\n\t\tthumb = pic.thumbnails.find_by_thumbnail('thumb')\n\t\tassert thumb.is_a?(DocImage)\n\t\tassert_equal 74, thumb.width\n\t\tassert_equal 100, thumb.height\n\t\t#assert_equal 'upload_t.jpg', thumb.filename\n\t\tassert_equal sites(:arusha), thumb.site\n\t\tassert_equal users(:login), thumb.user\n\t\tassert(thumb.size > 0)\n\t\tassert(thumb.content.size > 0)\n\t\t# remove the document and it's thumb\n\t\tassert_difference(Document, :count, -2) do\n\t\t\tassert pic.destroy.frozen?\n\t\tend\n\t\t\n\t\t# test with image smaller than scaling\n\t\tdoc = nil\n\t\tassert_difference(Document, :count, 2) do\n\t\t\tfile_data = fixture_file_upload('/files/upload64.jpg','image/jpeg')\n\t\t\tdoc = DocImage.new({:uploaded_data=>file_data, :site_select=>sites(:arusha).id})\n\t\t\tdoc.user = users(:login)\n\t\t\tassert doc.save\n\t\tend\n\t\t# check that pic was stored as expected\n\t\tpic = Document.find_by_filename('upload64.jpg')\n\t\tassert_equal doc, pic\n\t\tassert pic.is_a?(DocImage)\n\t\tassert_equal 64, pic.width\n\t\tassert_equal 64, pic.height\n\t\tassert_equal 7261, pic.size\n\t\tassert_equal users(:login), pic.user\n\t\t# check that thumbnail was generated as expected\n\t\tthumb = pic.thumbnails.find_by_thumbnail('thumb')\n\t\tassert thumb.is_a?(DocImage)\n\t\tassert_equal 64, thumb.width\n\t\tassert_equal 64, thumb.height\n\t\t#assert_equal 'upload64_t.jpg', thumb.filename\n\t\tassert_equal sites(:arusha), thumb.site\n\t\tassert_equal users(:login), thumb.user\n\t\tassert(thumb.size > 0)\n\t\tassert(thumb.content.size > 0)\n\t\t# remove the document and it's thumb\n\t\tassert_difference(Document, :count, -2) do\n\t\t\tassert pic.destroy.frozen?\n\t\tend\n\tend",
"def conforms_to_image\n return true if @uti == \"com.adobe.photoshop-image\"\n return true if @uti == \"com.adobe.illustrator.ai-image\"\n return true if @uti == \"com.compuserve.gif\"\n return true if @uti == \"com.microsoft.bmp\"\n return true if @uti == \"com.microsoft.ico\"\n return true if @uti == \"com.truevision.tga-image\"\n return true if @uti == \"com.sgi.sgi-image\"\n return true if @uti == \"com.ilm.openexr-image\"\n return true if @uti == \"com.kodak.flashpix.image\"\n return true if @uti == \"public.fax\"\n return true if @uti == \"public.jpeg\"\n return true if @uti == \"public.jpeg-2000\"\n return true if @uti == \"public.tiff\"\n return true if @uti == \"public.camera-raw-image\"\n return true if @uti == \"com.apple.pict\"\n return true if @uti == \"com.apple.macpaint-image\"\n return true if @uti == \"public.png\"\n return true if @uti == \"public.xbitmap-image\"\n return true if @uti == \"com.apple.quicktime-image\"\n return true if @uti == \"com.apple.icns\"\n return false\n end",
"def shrink_to_one image, xpos, ypos, width, height\n# if @intermediate_images\n# tmp_image = \"vo-#{xpos}-#{ypos}\".to_sym\n# copy_subimage image, xpos, ypos, width, height, tmp_image\n# d_write_image(tmp_image)\n# end\n img = get_image(image)\n checkbox_pixels = img.excerpt(xpos, ypos, width, height)\n shrink_to_one = checkbox_pixels.scale(1,1)\n return shrink_to_one.get_pixels(0,0,1,1)[0].red\n end",
"def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend",
"def normalize_photo(photo)\n get_photo_response = get_photo(photo.id)\n sizes = client.photos.getSizes(photo_id: photo.id)\n {\n source: 'flickr',\n key: photo.id,\n photo_thumbnail: get_photo_size(sizes, 'Thumbnail'),\n photo_small: get_photo_size(sizes, 'Small 400'),\n photo_medium: get_photo_size(sizes, 'Medium 800'),\n photo_large: get_photo_size(sizes, 'Large 1600'),\n created_at: get_photo_response.dateuploaded,\n url: Flickr.url_photopage(photo),\n description: get_photo_response.description,\n title: get_photo_response.title,\n }\n end",
"def convert\n generate_uid\n tmp_file = Pathname.new(Dir::tmpdir).join(\"#{@uid}_#{@source.basename}\")\n tmp_image = image_to_tiff\n `#{@command} '#{tmp_image}' '#{tmp_file.to_s}' #{lang} #{psm} #{config_file} #{clear_console_output}`\n @value = File.read(\"#{tmp_file.to_s}.txt\").to_s\n @uid = nil\n remove_file([tmp_image,\"#{tmp_file.to_s}.txt\"])\n rescue\n raise RTesseract::ConversionError\n end",
"def apply(image)\n image.view(0,0,image.columns,image.rows) do |view|\n eyes.each { |eye| do_redeye(eye,view) }\n end\n end",
"def crop(rect)\n if self.scale > 1.0\n rect = CGRectMake(rect.origin.x * self.scale,\n rect.origin.y * self.scale,\n rect.size.width * self.scale,\n rect.size.height * self.scale)\n end\n\n cgimage = CGImageCreateWithImageInRect(self.CGImage, rect)\n result = UIImage.imageWithCGImage(cgimage, scale:self.scale, orientation:self.imageOrientation)\n\n return result\n end",
"def rm_centroid_on(corner)\n c = @grom.rm_crop_area(corner)\n p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)\n # byebug\n n = NPatch.new(p, c.w, c.h)\n cx, cy, sd = n.centroid\n st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)\n status = st ? :edgy : :ok\n return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}\n end",
"def highlight(img=@image.constitute)\n to_boxes.each do |box|\n box.highlight(img)\n end\n img\n end",
"def rotate_image(image)\n\nend"
] |
[
"0.64648074",
"0.5964211",
"0.5717935",
"0.5609446",
"0.56007886",
"0.5557735",
"0.5518511",
"0.5445434",
"0.5391624",
"0.5199129",
"0.51659375",
"0.5163276",
"0.51233906",
"0.51185113",
"0.5097995",
"0.50681937",
"0.49847692",
"0.49519026",
"0.49463594",
"0.49191478",
"0.4884316",
"0.48580208",
"0.48532575",
"0.4849896",
"0.48361376",
"0.4829707",
"0.48164782",
"0.48146507",
"0.4807603",
"0.48028105",
"0.47958347",
"0.4787793",
"0.47816965",
"0.4759225",
"0.4752058",
"0.47393465",
"0.4731749",
"0.47314847",
"0.47236592",
"0.4722163",
"0.47218838",
"0.47096115",
"0.47068048",
"0.46400252",
"0.4638206",
"0.46167082",
"0.45991215",
"0.45875624",
"0.4584578",
"0.4575033",
"0.45637947",
"0.45583373",
"0.4544557",
"0.4542032",
"0.45354155",
"0.45341983",
"0.4518336",
"0.4517719",
"0.45139167",
"0.45057276",
"0.45041376",
"0.44977367",
"0.44974574",
"0.44826955",
"0.44783163",
"0.4474556",
"0.44672993",
"0.44635138",
"0.44576952",
"0.4456898",
"0.4456639",
"0.44333285",
"0.44091782",
"0.44086424",
"0.44079",
"0.44004858",
"0.44001696",
"0.43871126",
"0.43868974",
"0.43800336",
"0.43776962",
"0.43752244",
"0.4373765",
"0.43678036",
"0.43627423",
"0.4359908",
"0.43579534",
"0.435773",
"0.43539315",
"0.43512738",
"0.4343878",
"0.43436337",
"0.43419102",
"0.4340735",
"0.4325292",
"0.4323261",
"0.43185297",
"0.43131778",
"0.43056184",
"0.43043494"
] |
0.508696
|
15
|
Tabulation Min cost for a stair is the min for either of the last 2, plus itself O(N) time, O(N) space (table)
|
def min_cost_climbing_stairs(cost)
cost = cost + [0]
table = Array.new(cost.length) { nil }
table[0] = cost[0]
table[1] = cost[1]
table.each_with_index do |_val, i|
next if i < 2
table[i] = [table[i-1], table[i-2]].min
table[i] += cost[i]
end
table.last
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def min_cost(stairs)\n min_step_cost = [stairs[0], stairs[1]]\n idx = 2\n while idx < stairs.length\n min_step_cost[idx] = stairs[idx] + [min_step_cost[idx - 1], min_step_cost[idx - 2]].min\n idx += 1\n end\n p min_step_cost\n [min_step_cost[-2], min_step_cost[-1]].min\nend",
"def min_cost_climbing_stairs(cost)\n cost = cost + [0]\n\n last = cost[1]\n last_last = cost[0]\n\n cost[2..-1].each do |cost|\n new_cost = cost + [last, last_last].min\n last_last = last\n last = new_cost\n end\n\n last\nend",
"def min_cost_climbing_stairs(cost)\n [step(cost, 0), step(cost, 1)].min\nend",
"def min_cost(costs)\n n = costs.length\n return 0 if n == 0\n \n (1..n - 1).each do |i|\n costs[i][0] += [costs[i - 1][1], costs[i - 1][2]].min\n costs[i][1] += [costs[i - 1][0], costs[i - 1][2]].min\n costs[i][2] += [costs[i - 1][0], costs[i - 1][1]].min\n end\n \n [costs[n - 1][0], costs[n - 1][1], costs[n - 1][2]].min \n \nend",
"def min_cost(costs)\n costs.reduce([0]*3) { |prev, now| now.map { |n| n + prev.rotate![0,2].min } }.min\nend",
"def min_cost_climbing_stairs(cost)\n i = cost.length - 3\n while i >= 0\n cost[i] += [cost[i+1], cost[i+2]].min\n i -= 1\n end\n\n [cost[0], cost[1]]\nend",
"def min_cost_climbing_stairs(arr)\n next_one, next_two = 0, 0\n curr = 0\n\n (arr.length - 1).downto(0).each do |i|\n curr = arr[i] + min(next_one, next_two)\n next_two = next_one\n next_one = curr\n end\n\n return min(next_one, next_two)\nend",
"def min_cost2(costs)\n return 0 if costs.empty?\n \n pre_red = costs[0][0]\n pre_green = costs[0][1]\n pre_blue = costs[0][2]\n\n costs[1..-1].each_with_index do |cost, i|\n current_red = cost[0] + [pre_blue, pre_green].min\n current_green = cost[1] + [pre_red, pre_blue].min\n current_blue = cost[2] + [pre_red, pre_green].min\n\n pre_red = current_red\n pre_green = current_green\n pre_blue = current_blue\n end\n\n # p [pre_red, pre_green, pre_blue]\n [pre_red, pre_green, pre_blue].min\nend",
"def getMinimumCost(k, c)\n c.sort.reverse.map.with_index do |cost, i|\n cost * (1 + i / k)\n end.sum\nend",
"def min_cost(cost, m, n)\n if n < 0 || m < 0\n return 100000\n elsif m == 0 && n == 0\n return cost[m][n]\n else\n return cost[m][n] + find_min( min_cost(cost, m-1, n-1),\n min_cost(cost, m-1, n),\n min_cost(cost, m, n-1))\n end\nend",
"def min_cost(cost, inf)\n # dist[i] stores minimum cost to reach station i from station 0.\n dist = {};\n\n i = 0\n n = cost.length\n while i < n do\n dist[i] = inf\n i += 1\n end\n dist[0] = 0\n\n # Go through every station and check if using it as an intermediate station gives better path\n i = 0\n while i < n do\n j = i + 1\n while j < n do\n c = dist[i] + cost[i][j]\n dist[j] = c if dist[j] > c\n j += 1\n end\n i += 1\n end\n return dist[n-1];\nend",
"def min_cost(costs)\n prev_color_path1 = 0\n prev_color_path2 = 1\n path1 = costs[0][prev_color_path1]\n path2 = costs[0][prev_color_path2]\n \n if costs[0][2] < path1\n if path1 < path2\n path2 = path1\n prev_color_path2 = prev_color_path1\n path1 = costs[0][2]\n prev_color_path1 = 2\n end\n elsif costs[0][2] < path2\n if path2 < path1\n path1 = path2\n prev_color_path1 = prev_color_path2\n path2 = costs[0][2]\n prev_color_path2 = 2\n end\n end\n\n costs[1..-1].each do |cost|\n min1 = nil\n min1idx = nil\n # for first path\n cost.each_with_index do |amt, idx|\n next if idx == prev_color_path1\n if min1\n if amt < min1\n min1 = amt\n prev_color_path1 = idx\n else\n next\n end\n else\n min1 = amt\n min1idx = idx\n end\n end\n path1 += min1\n\n \n min2 = nil\n min2idx = nil\n # for second path\n cost.each_with_index do |amt, idx|\n next if idx == prev_color_path2\n if min2\n if amt < min2\n min2 = amt\n prev_color_path2 = idx\n else\n next\n end\n else\n min2 = amt\n min2idx = idx\n end\n end\n \n path2 += min2\n end\n\n path1 < path2 ? path1 : path2\nend",
"def swap_table\n current_cost = compute_cost(@people)\n for i in (0..@people.size-1)\n for j in (0..@people.size-1)\n current_cost = swap_if_increases_cost(current_cost, i, j)\n end\n end\n\n current_cost\n end",
"def optimize(ary, total)\n return [] if ary.empty?\n table = []\n (ary.size+1).times { |i| table[i] = [] }\n (0..total).each { |zerg| table[0][zerg] = 0 }\n (1..ary.size).each do |base|\n table[base][0] = 0\n (1..total).each do |zerg|\n if ary[base-1].zerg <= zerg && (ary[base-1].minerals + table[base-1][zerg - ary[base-1].zerg] > table[base-1][zerg])\n table[base][zerg] = ary[base-1].minerals + table[base-1][zerg - ary[base-1][1]]\n else\n table[base][zerg] = table[base-1][zerg]\n end\n end\n end\n result = []\n i, k = ary.size, total\n while i > 0 && k > 0\n if table[i][k] != table[i-1][k]\n result << ary[i-1]\n k -= ary[i-1].zerg\n end\n i -= 1\n end\n result\nend",
"def getMinimumCost(k, c)\n cost = 0\n c.sort.reverse.each_with_index do |price, idx|\n # (previous purchases + current purchases) * price\n sub_cost = ((idx / k) + 1) * price \n puts \"((#{idx} / #{k}) + 1) * #{price} = #{sub_cost}\"\n cost += sub_cost\n end\n cost\nend",
"def knapsack_table(weights, values, capacity)\n table = []\n\n (0..capacity).each do |i|\n table[i] = []\n\n (0...weights.length).each do |j|\n if i.zero?\n table[i][j] = 0\n elsif j.zero?\n table[i][j] = weights[j] > i ? 0 : values[j]\n else\n option1 = table[i][j - 1]\n option2 = weights[j] > i ? 0 : table[i - weights[j]][j - 1] + values[j]\n\n optimum = [option1, option2].max\n table[i][j] = optimum\n end\n end\n end\n \n table\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = [] \n (0..capacity).each do |i|\n solution_table[i] = [] \n\n (0...weights.length).each do |j|\n if i == 0 \n solution_table[i][j] = 0 \n elsif j == 0 \n solution_table[i][j] = weights[j] > i ? 0 : values[j]\n else \n option1 = solution_table[i][j-1]\n option2 = weights[j] > i ? 0 : solution_table[i - weights[j]][j-1] + values[j]\n optimum = [option1, option2].max \n solution_table[i][j] = optimum \n end \n end \n end \n solution_table\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n\n (0..capacity).each do |i|\n solution_table[i] = []\n (0...weights.length).each do |j|\n if i == 0 \n solution_table[i][j] = 0\n elsif j == 0 \n solution_table[i][j] = weights[j] < i ? 0 : values[j]\n else \n option1 = solution_table[i][j - 1]\n option2 = weights[j] < i ? 0 : solution_table[i - weights[j]][j - 1] + values[j]\n optimum = [option1, option2].max\n solution_table[i][j] = optimum\n end \n end \n end \n sotlution_table\n end",
"def knapsack_table(weights, values, capacity)\n table = [Array.new(values.length) {0}]\n (1..capacity).each do |capacity|\n prev = 0\n best = []\n values.length.times do |i|\n value = values[i]\n weight = weights[i]\n if i == 0 && weight <= capacity\n take = value\n else\n take = value + table[capacity - weight][i - 1] if capacity - weight >= 0\n end\n if take && take > prev\n best[i] = take\n else\n best[i] = prev\n end\n prev = best[i]\n end\n table.push(best)\n end\n table\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length){Array.new(capacity+1)}\n (0...weights.length).each do |row|\n (0..capacity).each do |col|\n if col < weights[row]\n table[row][col] = table[row-1][col] unless row == 0\n table[row][col] = 0 if row == 0\n else \n val = values[row]\n weight = weights[row]\n left_over = table[row-1][col-weight].nil? ? 0 : table[row-1][col-weight]\n old_val = row == 0 ? val : table[row-1][col]\n table[row][col] = [old_val, val + left_over].max\n end \n end \n end \n table\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n\n (0..capacity).each do |cap|\n solution_table[cap] = []\n (0...weights.length).each do |idx|\n if capacity == 0 \n solution_table[cap][idx] = 0\n elsif idx == 0 \n solution_table[cap][idx] = weights[idx] > cap ? 0 : values[idx]\n else\n option1 = solution_table[cap][idx - 1]\n option2 = weights[idx] > cap ? 0 : solution_table[cap - weights[idx]][idx - 1] + values[idx]\n optimum = [option1, option2].max\n solution_table[cap][idx] = optimum\n end \n end \n end \n solution_table\n end",
"def knapsack_table(weights, values, capacity)\n result_table = []\n (0..capacity).each do |idx1|\n result_table[idx1] = []\n (0..weights.length - 1).each do |idx2|\n if idx1 == 0\n result_table[idx1][idx2] = 0\n elsif idx2 == 0\n result_table[idx1][idx2] = weights[0] > idx1 ? 0 : values[0]\n else\n opt1 = result_table[idx1][idx2 - 1]\n opt2 = idx1 < weights[idx2] ? 0 : result_table[idx1 - weights[idx2]][idx2 - 1] + values[idx2]\n optimum = [opt1, opt2].max\n result_table[idx1][idx2] = optimum\n end\n end\n end\n result_table\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n\n (0..capacity).each do |i|\n solution_table[i] = []\n\n (0...weights.length).each do |j|\n if i == 0\n solution_table[i][j] = 0\n elsif j == 0\n solution_table[i][j] = weights[j] > i ? 0 : values[j]\n else\n option1 = solution_table[i][j - 1]\n option2 = weights[j] > i ? 0 : solution_table[i - weights[j]][j - 1] + values[j]\n optimum = [option1, option2].max\n solution_table[i][j] = optimum\n end\n end\n end\n\n solution_table\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new\n\n (0..capacity).each do |i|\n table[i] = Array.new\n\n (0...weights.length).each do |j|\n if i == 0\n table[i][j] = 0\n elsif j == 0\n table[i][j] = weights[j] > i ? 0 : values[j]\n else\n x = table[i][j - 1]\n y = weights[j] > i ? 0 : table[i - weights[j]][j - 1] + values[j]\n\n table[i][j] = [x, y].max\n end\n end\n end\n\n return table.last.last\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n\n (0..capacity).each do |i|\n solution_table[i] = []\n\n (0...weights.length).each do |j|\n if i == 0\n solution_table[i][j] = 0\n elsif j == 0\n solution_table[i][j] = weights[0] > i ? 0 : values.first\n else\n option1 = solution_table[i][j - 1]\n option2 = i < weights[j] ? 0 : solution_table[i - weights[j]][j - 1] + values[j]\n optimum = [option1, option2].max\n solution_table[i][j] = optimum\n end\n end\n end\n\n solution_table\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n (0..capacity).each do |i|\n solution_table[i] = []\n (0..weights.length - 1).each do |j|\n if i == 0\n solution_table[i][j] = 0\n elsif j == 0\n solution_table[i][j] = weights[0] > i ? 0 : values[0]\n else\n option1 = solution_table[i][j - 1]\n option2 = i < weights[j] ? 0 : solution_table[i - weights[j]][j - 1] + values[j]\n optimum = [option1, option2].max\n solution_table[i][j] = optimum\n end\n end\n end\n\n solution_table\n end",
"def solution(a)\n min_val = 10_000\n min_pos = 0\n \n sums = [0]\n for i in (0..a.count - 1) \n sums << sums.last + a[i] \n end\n for p in (0..a.count - 2)\n for q in (p + 1..[p + 2, a.count - 1].min)\n s = (sums[q + 1] - sums[p]).to_f / (q - p + 1)\n if s < min_val\n min_val = s\n min_pos = p\n end\n end\n end\n min_pos\nend",
"def knapsack_table(weights, values, capacity)\n solution_table = [] # solution_table[0] = [] 0,\n\n (0..capacity).each do |i| # 0..3 ,0, 1\n solution_table[i] = []\n #Go throught the weights one by one by index\n values.length.times.each do |j| # 0..3 0,1, 2\n if i == 0 # 0 == 0 true\n # if capacity is zero. then 0 is the only value that can be placed into the set\n solution_table[i][j] = 0 # solution_table[0][0] = 0 solution_table = [[0,0,0], [1, 1, 1, ]]\n elsif j == 0\n # for the first item in our list we can check fot capacity\n # if our weights < capacity, put zero, otherwise put valye\n solution_table[i][j] = weights[0] > i ? 0 : values.first\n else\n # the first option is the entery considering the previous item at this capacity\n option1 = solution_table[i][j - 1] # 1, 1\n #the secound option (assuming enough capacity)- is the max value of the smaller bag\n option2 = i < weights[j] ? 0 : solution_table[i - weights[j]][j - 1] + values[j] # 0\n #choose max from this options\n optimum = [option1, option2].max # [1,0] 1 = max\n solution_table[i][j] = optimum\n end\n end\n end\n solution_table\n end",
"def min_ops(n)\n\n # Step 1:\n # Create a table containing the minimum operations\n # needed to reach n given our permitted operators.\n all_parents = Array.new\n all_min_ops = [0] + [nil] * n\n\n (1..n+1).each do |k|\n curr_parent = k - 1\n curr_min_ops = all_min_ops[curr_parent] + 1\n [2, 3].each do |i|\n if k % i == 0\n parent = k / i\n num_ops = all_min_ops[parent] + 1\n if num_ops < curr_min_ops\n curr_parent, curr_min_ops = parent, num_ops\n end\n end\n end\n all_parents[k], all_min_ops[k] = curr_parent, curr_min_ops\n end\n\n # Step 2: Trace back to find the optimal choices\n # made in the previous step.\n numbers = Array.new\n k = n\n while k > 0\n numbers << k\n k = all_parents[k]\n end\n puts numbers.size - 1\n numbers.reverse\nend",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length) { Array.new(capacity + 1) {0} }\n min_weight = weights.min\n weights.each_with_index do |weight, row|\n (min_weight..capacity).each do |col|\n if weight > col && row > 0\n table[row][col] = table[row - 1][col]\n elsif row > 0\n table[row][col] = [values[row] + table[row - 1][col - weight],\n table[row - 1][col]].max\n elsif weight <= col\n table[row][col] = values[row]\n end\n end\n end\n table\n end",
"def calculate_optimal_k\n k=0\n @k_optimal = Array.new(@size)\n (3..@size).each{|n|\n k+=1 while(cost(n,k)<cost(n,k+1))\n @k_optimal[n]=k\n }\n end",
"def solution(coins, sum)\n sums = Hash.new\n sums[0] = 0\n\n (1..sum).each do |s|\n counts = Array.new\n\n coins.each do |c|\n next if c > s\n counts << sums[s-c] + 1 if !sums[s-c].nil?\n end\n\n sums[s] = counts.min\n end\n sums[sum]\nend",
"def knapsack_table(weights, values, capacity)\n max = 0\n if weights.length == 1\n max = capacity < weights[0] ? 0 : values[0]\n end\n weights.each_with_index do |w,i|\n if values[i] > max && capacity > w\n max += values[i]\n capacity -= w\n end\n end\n max\n end",
"def knapsack_table(weights, values, capacity)\n matrix = Array.new(values.length) { Array.new(capacity + 1, 0) }\n (0..capacity).each do |cap|\n matrix[0][cap] = cap < weights[0] ? 0 : values[0]\n end\n (1...values.length).each do |i|\n (0..capacity).each do |cap_i|\n if cap_i < weights[i]\n matrix[i][cap_i] = matrix[i - 1][cap_i]\n else\n matrix[i][cap_i] = [\n values[i] + matrix[i - 1][cap_i - weights[i]],\n matrix[i - 1][cap_i]\n ].max\n end\n end\n end\n matrix[values.length - 1][capacity]\n end",
"def knapsack_table(weights, values, capacity)\n table = []\n\n (0..capacity).each do |cap|\n table[cap] = []\n\n (0...weights.length).each do |weight|\n if cap.zero?\n table[cap][weight] = 0\n elsif weight.zero?\n table[cap][weight] = values[0]\n table[cap][weight] = 0 if weights[0] > cap\n else\n option1 = table[cap][weight - 1]\n if weights[weight] > cap\n option2 = 0\n else\n option2 = table[cap - weights[weight]][weight - 1] + values[weight]\n end\n table[cap][weight] = [option1, option2].max\n end\n end\n end\n\n table\n\n end",
"def knapsack_table(weights, values, capacity)\n return 0 if capacity == 1\n end",
"def solution(a)\n # write your code in Ruby 2.2\n binding.pry\n trips = Hash.new {|h,k| h[k]=0}\n start = 0\n ending = 0\n min = nil\n a.each_with_index do |trip,i|\n ending = i\n\n if trips[trip] == 0\n min = ending - start\n end\n trips[trip] += 1\n\n while start < ending\n break if trips[a[start]] - 1 == 0\n trips[start] -= 1\n start += 1\n min = ending - start if ending-start < min\n end\n end\n min\nend",
"def knapsack_table(weights, values, capacity)\n n = weights.length\n table = Array.new(capacity + 1) { Array.new(n, 0) }\n\n 1.upto(capacity) do |c|\n (0...n).each do |i|\n if weights[i] > c\n table[c][i] = table[c][i - 1]\n elsif i == 0\n table[c][i] = values[i]\n else\n prev_val = table[c][i - 1]\n table[c][i] = [prev_val, table[c - weights[i]][i - 1] + values[i]].max\n end\n end\n end\n\n table\n end",
"def calculate_table(target_num)\n # this is our \"table\"\n minimum_num_of_steps = [0]\n\n (1..target_num).each do |num|\n # set an initial value in our table to weigh against\n minimum_num_of_steps[num] = Float::INFINITY\n\n if num == 1\n minimum_num_of_steps[num] = 0\n else\n # calculate values then get rid of decimals since they wouldn't make sense as indices\n # consider that we're starting with integers anyway so float results don't really work\n values = OPERATIONS.map { |op| self.send(op[0], num, op[1]) }\n values.reject! { |v| v % 1 != 0 }\n # for each valid operation's value, look at the number of steps for the index/number we're at\n # and if it's lower than the current step count in the table overwrite it\n values.each do |value|\n # current_num_steps = minimum_num_of_steps[num - value] + 1\n current_num_steps = minimum_num_of_steps[value] + 1\n\n if current_num_steps < minimum_num_of_steps[num]\n minimum_num_of_steps[num] = current_num_steps\n end\n end\n end\n end\n\n minimum_num_of_steps\nend",
"def solve\n a = Time.new\n for i in 0..@itemsSize - 1\n @table[0][i] = 0\n end\n \n for i in 1..@itemsSize - 1\n price = @problem.prices[i-1]\n weight = @problem.weights[i-1]\n for w in 1..@weights - 1\n if weight <= w\n if (price + @table[w - weight][i - 1]) > @table[w][i -1]\n @table [w][i]= price + @table[w - weight][i - 1]\n else\n @table[w][i] = @table[w][i - 1]\n end\n else\n @table[w][i] = @table[w][i - 1]\n end\n end\n end\n \n \n prev_item = 0\n for i in 1..@itemsSize - 1\n curr_item = @table[@weights - 1][i]\n if prev_item < curr_item\n @best_configuration.push(1)\n else\n @best_configuration.push(0)\n end\n prev_item = curr_item\n end\n \n @best_fitness = @table[@weights - 1][@itemsSize - 1]\n \n b = Time.new\n @time = b-a\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length) {Array.new(capacity + 1, 0)}\n \n table.each_index do |weight_idx|\n wt = weights[weight_idx]\n val = values[weight_idx]\n \n table[weight_idx].each_index do |curr_capacity|\n next if curr_capacity == 0\n \n if weight_idx == 0 #sets first row\n table[weight_idx][curr_capacity] = (curr_capacity >= wt ? val : 0)\n else \n cap_diff = (curr_capacity - wt >= 0 ? curr_capacity - wt : 0) #account for if capacity is smaller than weight\n calc_val = val + table[weight_idx - 1][cap_diff]\n prev_val = table[weight_idx - 1][curr_capacity]\n \n table[weight_idx][curr_capacity] = [calc_val, prev_val].max\n end\n end\n end\n \n p table\n end",
"def knapsack_table(weights, values, capacity)\n # iterate over the weights\n # nested - iterate over the table array\n # For each capacity_idx < weight, push into the current capacity array..\n # either a 0 or the last value in the current capacity array (which ever is larger)\n # For capacity_idx >= weight\n # compare capacity[idx].last to (capacity[idx-weight].second_to_last + value of current weight)\n # Which ever is larger, push into capacity[idx]\n\n table = Array.new(capacity + 1) { Array.new }\n\n weights.each_with_index do |weight, wv_id|\n table.each_with_index do |local_solutions, current_cap|\n new_value = 0\n if current_cap < weight\n new_value = local_solutions[-1] || new_value\n else\n if wv_id == 0\n new_value = values[wv_id]\n else\n with_weight = table[current_cap - weight][-2] + values[wv_id]\n without_weight = local_solutions.last\n new_value =[with_weight, without_weight].max\n end\n end\n local_solutions << new_value\n end\n end\n\n table\n end",
"def phase_1_min(list)\n smallest = 0\n list.each_with_index do |num1, indx1|\n list.each_with_index do |num2, indx2|\n next if indx1 == indx2\n smallest = num1 if num1 < num2 && num1 < smallest\n end\n end\n smallest\nend",
"def dp(array)\n ary_size = array.size\n queue = [0]\n for i in 0..(ary_size - 1) do\n if i == 0\n queue << array[i]\n else\n cost_1 = (queue[i - 1] - array[i]).abs\n cost_2 = (queue[i - 2] - array[i]).abs\n queue << [cost_1, cost_2].min\n end\n end\n return queue.last\nend",
"def knapsack_table(weights, values, capacity)\n cache = [[0, 0, 0]]\n return cache[-1] if capacity <= 0\n end",
"def knapsack_table(weights, values, capacity)\n\t\tt = Array.new(weights.length) { Array.new(capacity + 1) } # make a weighs\n\t\tweights.length.times {|i| t[i][0] = 0 }\t\t\t\t\t\t\t\t\t\t# set 1st column to zeros\n\n\t\tt.each_index do |i|\n\t\t\tt[i].each_index do |j|\n\t\t\t\twt_i = weights[i]\n\t\t\t\tvl_i = values[i]\n\t\t\t\tprev = t[i - 1][j] || 0\n\n\t\t\t\tif j < wt_i\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# The current capacity can't hold the current weight\n\t\t\t\t\tt[i][j] = prev\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# So make it the previous column's answer (without wt[i])\n\t\t\t\telse\n\t\t\t\t\ta = vl_i #+ t[i - 1][j - wt_i]\t\t\t\t\t\t\t\t\t\t\t\t# The current value + the above row minus the current's weight\n\t\t\t\t\tif (i - 1 >= 0)\n\t\t\t\t\t\ta += t[i - 1][j - wt_i]\n\t\t\t\t\tend\n\n\t\t\t\t\tb = prev\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# The previous\n\t\t\t\t\tt[i][j] = [a, b].max\n\t\t\t\tend\n\t\t\tend\n\t\tend\n end",
"def best_toothpicks(i)\n options = []\n rem = 0\n \n if i < 8 || i == 11\n options << [[[i, 1]]]\n else \n while true\n ar = i.prime_division\n option = [merge_primes(ar)]\n option += best_toothpicks(rem) if rem > 0\n options << option\n \n # this is something i'm not happy about. larger numbers (7) improve performance,\n # but i'm afraid smaller ones (3) may find better solutions\n if ar.detect {|e| e.first > 5 }\n i -= 1\n rem += 1\n else\n break\n end\n end\n end\n return options.min {|a, b| cost(a) <=> cost(b) }\nend",
"def calculate_total_cost(a, stripped_row, k)\n total_cost = 0\n count = 0\n sum = 0\n delivery = \"\"\n mul_value = (a[:\"Cost Per GB\"].to_i * stripped_row[1].to_i)\n if mul_value >= a[:\"Minimum Cost\"].to_i\n if count > 0\n if mul_value < sum\n sum = mul_value\n delivery = k\n total_cost = sum\n return total_cost, delivery\n end\n else\n sum = mul_value\n count += 1\n total_cost = sum\n delivery = k\n return total_cost, delivery\n end\n end\n end",
"def knapsack_table(weights, values, capacity)\n solution_table = []\n # Build solutions for knapsacks of increasing capacity\n (0..capacity).each do |i|\n solution_table[i] = []\n # go through the weights one by one, by index\n (0..weights.length - 1).each do |j|\n if i == 0\n # if the capacity is 0, then 0 is how much value can be placed in any slot\n solution_table[i][j] = 0\n elsif j == 0\n # for the first item in our list, you must check for capacity\n # if there is, then you enter its value in the first slot, otherwise 0\n solution_table[i][j] = weights[0] > i ? 0 : values[0]\n else\n # the first option is the entry from considering the previous item at this capacity\n option1 = solution_table[i][j - 1]\n # the second option (assuming enough capacity) is the entry from a smaller bag\n # (with enough room for this item) plus this item's value\n option2 = i < weights[j] ? 0 : solution_table[i - weights[j]][j - 1] + values[j]\n # the actual entry for this item is the optimum of the two choices\n optimum = [option1, option2].max\n solution_table[i][j] = optimum\n end\n end\n end\n\n solution_table\n end",
"def knapsack_table(weights, values, capacity)\n cache = {\n 0 => [[0, 0, 0]]\n }\n return cache if n < 1\n (1..n)\n end",
"def knapsack_table(weights, values, capacity)\n knapsack_cache = {0 => Array.new(weights.length, 0)}\n (1..capacity).each do |c|\n knapsack_cache[c] = c == weights[0] ? [values[0]] : [0]\n end\n (1...weights.length).each do |col|\n (1..capacity).each do |c|\n current_weight = weights[col]\n current_value = values[col]\n if c < current_weight\n knapsack_cache[c][col] = knapsack_cache[c][col - 1]\n else\n new_value = knapsack_cache[c - current_weight][col - 1] + current_value\n knapsack_cache[c][col] = [new_value, knapsack_cache[c][col - 1]].max\n end\n end\n end\n knapsack_cache\n\n end",
"def knapsack_table(weights, values, capacity)\n return 0 if capacity <= 0 || weights.length == 0\n\n i = weights.length - 1\n\n @knapsack[capacity] = [] if @knapsack[capacity].nil?\n\n return @knapsack[capacity][i] if @knapsack[capacity][i]\n\n prev = knapsack_table(weights[0...i], values[0...i], capacity)\n other = knapsack_table(weights[0...i], values[0...i], capacity - weights[i]) + values[i]\n return prev if weights[i] > capacity\n choices = [prev, other]\n max = choices.max\n @knapsack[capacity][i] = max\n max\nend",
"def min_size_heuristic(amount,comb,coins)\n rem = amount-comb.sum\n return Infinity if rem < 0\n comb.size+rem.to_f/(coins.select{|c|c<=rem&&c<=comb.max}.max) rescue comb.size\nend",
"def solution(a)\n return 0 if a.count <= 1\n \n max_profit = 0\n min_price = a.first\n a[1..-1].each { |price|\n max_profit = [max_profit, price - min_price].max\n min_price = [min_price, price].min\n }\n max_profit\nend",
"def two_city_sched_cost(costs)\n\treturn 0 if costs == nil || costs.size == 0 # Return 0 if costs array is nil or empty.\n\t# Sort array by difference in each subarray in descending order.\n\tcosts = costs.sort_by{|cost| cost[1] - cost[0]}.reverse\n\tmid = costs.size/2 # Get mid.\n\tsum = 0\n\t# Traverse costs array.\n\t# For first half, get first element of every subarray and add to sum.\n\t# For second half, get second element of every subarray and add to sum.\n\tfor i in 0..costs.size-1 do\n\t\tif i < mid\n\t\t\tsum = sum + costs[i][0]\n\t\telse\n\t\t\tsum = sum + costs[i][1]\n\t\tend\t\n\tend\n\treturn(sum) # Return sum\n\nend",
"def min_unfairness (candy, n, k)\n # First, sorting the array\n candy.sort!\n\n # puts candy.inspect\n\n # Initialize with the first and k element \n min = candy[k-1] - candy[0]\n\n # For each subsequential k elements, we have to find the min. unfairness\n for i in 1..(n-k) \n # puts \"i=#{i} n[i+k]=#{candy[i+k-1]} n[i]=#{candy[i]} : #{candy[i+k-1] - candy[i]} | min=#{min}\"\n min = candy[i+k-1] - candy[i] if candy[i+k-1] - candy[i] < min\n end\n\n return min\nend",
"def knapsack_table(weights, values, capacity)\n num_items = weights.length\n weight_val_hash = {}\n (1..num_items).each do |i|\n weight_val_hash[i] = [weights[i - 1], values[i - 1]]\n end\n table = Array.new(num_items + 1) { Array.new(capacity + 1)}\n table[0].each_index do |idx|\n table[0][idx] = 0\n end\n (1..num_items).each do |i|\n weight, value = weight_val_hash[i]\n (0..capacity).each do |j|\n if weight > j\n table[i][j] = table[i-1][j]\n else\n table[i][j] = [table[i-1][j], table[i-1][j - weight] + value].max\n end\n end\n end\n return table\n end",
"def knapsack_table(weights, values, capacity)\n n = weights.length\n array = Array.new(capacity + 1) { Array.new(n, 0) }\n\n (1..capacity).each do |j|\n (0...n).each do |i|\n if weights[i] > j\n array[j][i] = array[j][i - 1]\n elsif i == 0\n array[j][i] = values[i]\n else\n prev_val = array[j][i - 1]\n array[j][i] = [prev_val, array[j - weights[i]][i - 1] + values[i]].max\n end\n end\n end\n\n array\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n\n end",
"def knapsack_table(weights, values, capacity)\n end",
"def solution(a)\n (0..a.size - 2).map { |i| ( a[0..i].inject(:+) - a[i+1..a.size].inject(:+) ).abs }.min\nend",
"def mine_total(i, j)\n return is_mined(@data[i-1][j-1]) +\n is_mined(@data[i-1][j]) +\n is_mined(@data[i-1][j+1]) +\n is_mined(@data[i][j-1]) +\n is_mined(@data[i][j+1]) +\n is_mined(@data[i+1][j-1]) +\n is_mined(@data[i+1][j]) +\n is_mined(@data[i+1][j+1]);\n end",
"def knapsack_table(weights, values, capacity)\n return 0 if capacity == 0 \n solution = [] \n sum_val = 0\n weights.each_with_index do |weight, idx| \n if capacity - weight >= 0 \n sum_val += values[idx] \n capacity -= weight \n end \n end \n len = weights.length\n sum_val\n end",
"def gift_cost gift_counts, costs\n black_count, white_count = gift_counts\n black_cost, white_cost, conversion_cost = costs\n \n if conversion_cost + [black_cost, white_cost].min >= [black_cost, white_cost].max \n # just buy what we need, dont do any converting\n return (black_count * black_cost) + (white_count * white_cost)\n else\n # its better to buy all cheapest and convert what we need to the other\n cost = [black_cost, white_cost].min * gift_counts.reduce(&:+)\n if black_cost < white_cost\n cost += white_count * conversion_cost\n else\n cost += black_count * conversion_cost\n end\n return cost\n end\n \nend",
"def formingMagicSquare(s)\r\n out = 100\r\n for i in 0...8 do\r\n cost = 0\r\n for j in 0...3 do\r\n for k in 0...3 do\r\n cost += ($magic_square[i][j][k] - s[j][k]).abs\r\n end\r\n end\r\n puts cost\r\n out = [out, cost].min\r\n end \r\n out\r\nend",
"def calculate_min_slots(matrix)\n output = []\n @sums.each.with_index do |e, i|\n if e == @min\n output << i\n end\n end\n #require 'pry';binding.pry\n output\n end",
"def knapsack_table(weights, values, capacity)\n return 0 if capacity <= 0 || weights.length == 0\n\n i = weights.length - 1\n\n @knapsack[capacity] = [] if @knapsack[capacity].nil?\n\n return @knapsack[capacity][i] if @knapsack[capacity][i]\n\n prev = knapsack_table(weights[0...i], values[0...i], capacity)\n other = knapsack_table(weights[0...i], values[0...i], capacity - weights[i]) + values[i]\n return prev if weights[i] > capacity\n choices = [prev, other]\n max = choices.max\n @knapsack[capacity][i] = max\n max\n end",
"def knapsack_table(weights, values, capacity)\n return 0 if capacity <= 0 || weights.length == 0\n\n i = weights.length - 1\n\n @knapsack[capacity] = [] if @knapsack[capacity].nil?\n\n return @knapsack[capacity][i] if @knapsack[capacity][i]\n\n prev = knapsack_table(weights[0...i], values[0...i], capacity)\n other = knapsack_table(weights[0...i], values[0...i], capacity - weights[i]) + values[i]\n return prev if weights[i] > capacity\n choices = [prev, other]\n max = choices.max\n @knapsack[capacity][i] = max\n max\n end",
"def min() end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(capacity + 1) {[]}\n weights_hash = {\n weights[0] => values[0],\n weights[1] => values[1],\n weights[2] => values[2]\n }\n\n weights.each_with_index do |weight, i|\n (0..capacity).each_with_index do |cap, j|\n if i == 0\n if weight < cap\n table[j] << weights_hash[weight]\n else\n table[j] << 0\n end\n else\n if weight < cap\n item_value = weights_hash[weight]\n p \"item value\"\n p item_value\n p \"value you can add to item\"\n p table[cap - weight][i - 1]\n total_value = table[cap - weight][i - 1] + item_value\n input = [total_value, table[cap][i - 1]].max\n table[j] << input\n else\n table[j] << table[j][i - 1]\n end\n end\n end\n\n end\n\n table\n end",
"def ukp3(ukpi, ret_table = true)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n # step one\n g = Array.new(c+1, 0)\n d = Array.new(c+1, n-1)\n sort_items_by_profitability!(items)\n\n gy_col = nil\n dy_col = nil\n if ret_table then\n gy_col = Array.new(c+1) { [] }\n dy_col = Array.new(c+1) { [] }\n end\n\n ys = y_star(items, true)\n min_necessary_steps = ys < c+1 ? ys : c+1\n # step two to six\n min_necessary_steps.times do | y |\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n items.each_with_index do | item, j |\n if y - item[:w] >= 0 && j <= d[y - item[:w]] then\n v = g[y - item[:w]] + item[:p]\n if v > g[y] then\n g[y] = v\n d[y] = j\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n end\n end\n end\n end\n\n if min_necessary_steps != c+1 then\n extra_capacity = c - ys\n c1, a1 = items[0][:p], items[0][:w]\n qt_best_item_used = Rational(extra_capacity, a1).ceil\n space_used_by_best_item = qt_best_item_used*a1\n profit_generated_by_best_item = qt_best_item_used*c1\n g[c] = g[c-space_used_by_best_item] + profit_generated_by_best_item\n end\n\n table = \"y\\tg(y)\\t\\td(y)\\n\"\n if ret_table then\n (c+1).times do | y |\n table << \"#{y}\\t#{gy_col[y].join(' ')}\\t\\t#{dy_col[y].join(' ')}\\n\"\n end\n end\n \n if ret_table then\n table\n else\n g\n end\nend",
"def min_cost_connect_points(points)\n total = 0\n visited = [true] + [false] * (points.length - 1)\n min_costs = {}\n current_id = 0\n\n (points.length - 1).times do\n min = nil\n next_id = nil\n points.each_with_index do |point, index|\n next if visited[index]\n\n new_min = manhattan_distance(points[current_id], points[index])\n\n if !min_costs[index] || min_costs[index] > new_min\n min_costs[index] = new_min\n else\n new_min = min_costs[index]\n end\n\n if !min || new_min < min\n min = min_costs[index] < new_min ? min_costs[index] : new_min\n next_id = index\n end\n end\n\n total += min\n visited[next_id] = true\n current_id = next_id\n end\n\n total\nend",
"def flatlandSpaceStations(n,c,m)\r\n answer = 0\r\n cc = c.sort()\r\n\r\n for i in (0..cc.size-2) do\r\n answer = [answer,(cc[i+1]-cc[i])/2].max\r\n end\r\n answer = [answer, cc[0], n-1 - cc[-1]].max\r\nend",
"def make_table( given, can )\n\ttable = initialize_table(given, can)\t# init row of 0s\n\t# need one more row than columns (n + 1) rows\n\tcan = [0] + can\n\n\t(0...(given.length)).each do |x|\n\t\t(1...(can.length + 1)).each do |s|\n\t\t\t# do not calculate min for lower diagonals\n\t\t\t# cannot possibly process x_1 with the power of s_2, nor x_2 with s_3\n\t\t\tif s - x < 2\t\n\t\t\t\t\n\t\t\t\ttable[s][x] = min( given[x], can[s] )\n\n\t\t\t\tif s == 1 && x > 1\n\t\t\t\t\ttable[s][x] += column_max( table, x - s - 1 )\n\t\t\t\telsif x >= 1\n\t\t\t\t\ttable[s][x] += table[ s - 1 ][ x - 1 ]\n\t\t\t\tend\n\t\t\tend \n\t\tend\n\tend\n\treturn table\nend",
"def solver(flights)\n (p all_paths(flights)).min_by { |path| cost_of_path(path) }\nend",
"def minimum_total(triangle)\n return triangle[0][0] if triangle.size < 2\n (triangle.size - 2).downto(0).each { |i|\n 0.upto(triangle[i].size - 1).each { |j|\n triangle[i][j] += [triangle[i + 1][j], triangle[i + 1][j + 1]].min\n }\n }\n \n triangle[0][0]\nend",
"def super_frog_hops(num_stairs, max_stairs)\n cache = [[[]], [[1]]]\n return cache[num_stairs] if num_stairs < 2\n \n (2..num_stairs).each do |stairs|\n new_comb = []\n (1..max_stairs).each do |jump|\n if stairs - jump < 0\n next\n else\n cache[stairs - jump].each do |subarr|\n next_com = subarr + [jump] \n new_comb << next_com\n end \n end \n end \n cache[stairs] = new_comb\n end \n cache[num_stairs]\n end",
"def dbl_linear(n)\n result = [1] # base\n\n i = 0 # pointer for 2x + 1\n j = 0 # pointer for 3x + 1\n\n until result.size == n + 1 # because n is an index (size - 1)\n list1 = 2 * result[i] + 1\n list2 = 3 * result[j] + 1\n min = [list1, list2].min\n\n result << min\n\n i += 1 if min == list1\n j += 1 if min == list2\n end\n\n result.last\nend"
] |
[
"0.7375758",
"0.73328644",
"0.7282645",
"0.7211329",
"0.71643794",
"0.70403475",
"0.69406575",
"0.6725482",
"0.66565967",
"0.65938365",
"0.6552746",
"0.6501378",
"0.6259403",
"0.6194432",
"0.61776084",
"0.6142893",
"0.6129097",
"0.61223733",
"0.6067645",
"0.6051536",
"0.60426307",
"0.6014826",
"0.60102236",
"0.6005337",
"0.60048187",
"0.59917897",
"0.596438",
"0.59590685",
"0.59409916",
"0.59398943",
"0.59299713",
"0.5912692",
"0.58751017",
"0.5874896",
"0.58675927",
"0.5866729",
"0.5856189",
"0.5843775",
"0.58376855",
"0.5830993",
"0.582797",
"0.5815373",
"0.5804367",
"0.580196",
"0.5796219",
"0.5779895",
"0.5773102",
"0.57638437",
"0.5750855",
"0.5745832",
"0.5744862",
"0.5731298",
"0.572462",
"0.5723603",
"0.5691563",
"0.568461",
"0.56694037",
"0.566495",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.565779",
"0.56324714",
"0.56288564",
"0.5626539",
"0.56256497",
"0.5624998",
"0.5622224",
"0.5618988",
"0.56107414",
"0.56107414",
"0.5605799",
"0.5605032",
"0.560203",
"0.55962175",
"0.55947864",
"0.5592535",
"0.5581607",
"0.5581472",
"0.55805457",
"0.5571974"
] |
0.8278453
|
0
|
Tabulation with space optimization O(N) time, O(1) space
|
def min_cost_climbing_stairs(cost)
cost = cost + [0]
last = cost[1]
last_last = cost[0]
cost[2..-1].each do |cost|
new_cost = cost + [last, last_last].min
last_last = last
last = new_cost
end
last
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def table\n words.scan\n bigrams.scan\n\n list = words.top_weighted(max)\n\n if sort\n list = list.sort_by{ |w| w.to_s }\n end\n\n index = {}\n list.each_with_index do |w, i|\n index[w.spelling] = i\n end\n\n tbl = []\n\n list.each_with_index do |w, i|\n s = ilog(words.weighted_probability(w))\n\n blist = bigrams.matching_bigrams(w.to_s)\n blist = blist.sort_by{ |b| bigrams.score(b) }.reverse\n blist = blist.map{ |b| b.word2 }.uniq\n\n b = []\n blist.each do |w|\n i = index[w]\n b << i+1 if i\n break if b.size == num\n end\n\n # ensure there are at least the required number of bigrams\n until b.size >= num\n b << 0\n end\n\n tbl << [s, w, b]\n end\n\n return tbl\n end",
"def kmp_table(word)\n\t\t\tn = word.capacity\n\t\t\tunless n >= 2\n\t\t\t\traise ArgumentError.new(\"expected n >= 2 but was #{n}\")\n\t\t\tend\n\t\t\ttable = Memory.new(n)\n\t\t\ttable[1] = 0\n\t\t\ti = 0\n\t\t\tj = 1\n\t\t\twhile j + 1 < n\n\t\t\t\tif word[i].eql?(word[j])\n\t\t\t\t\ti += 1\n\t\t\t\t\tj += 1\n\t\t\t\t\ttable[j] = i\n\t\t\t\telsif i != 0\n\t\t\t\t\ti = table[i]\n\t\t\t\telse\n\t\t\t\t\tj += 1\n\t\t\t\t\ttable[j] = i\n\t\t\t\tend\n\t\t\tend\n\t\t\treturn table\n\t\tend",
"def calc_tabsets( lines )\n divlines = []\n tab_sets = []\n lines.each_with_index do |line, i|\n if line.index(/^[+][+-=]*[+]$/) #or line.index(/^\\+=/)\n divlines << i\n j = -1\n while j\n j = line.index('+',j+1)\n tab_sets << j if ! tab_sets.include?(j) if j\n end\n end\n end\n tab_sets.sort!\n divlines.each {|i| tab_sets.each {|t| lines[i][t..t] = '+'} }\n tab_sets\n end",
"def swap_table\n current_cost = compute_cost(@people)\n for i in (0..@people.size-1)\n for j in (0..@people.size-1)\n current_cost = swap_if_increases_cost(current_cost, i, j)\n end\n end\n\n current_cost\n end",
"def multiplication_table(size)\n table = []\n size.times do |row|\n table << []\n size.times do |i|\n table[row] << (row + 1) * (i + 1)\n end\n end\n return table\nend",
"def table\n table = {}\n (-1...v1.length).each { |x| table[[x, -1]] = 0 }\n (0...v2.length).each { |y| table[[-1, y]] = 0 }\n\n (0...v1.length).each do |x|\n (0...v2.length).each do |y|\n if v1[x] == v2[y]\n table[[x,y]] = table[[x-1, y-1]] + 1\n else\n table[[x,y]] = [table[[x-1,y]], table[[x,y-1]]].max\n end\n end\n end\n table\n end",
"def make_table( given, can )\n\ttable = initialize_table(given, can)\t# init row of 0s\n\t# need one more row than columns (n + 1) rows\n\tcan = [0] + can\n\n\t(0...(given.length)).each do |x|\n\t\t(1...(can.length + 1)).each do |s|\n\t\t\t# do not calculate min for lower diagonals\n\t\t\t# cannot possibly process x_1 with the power of s_2, nor x_2 with s_3\n\t\t\tif s - x < 2\t\n\t\t\t\t\n\t\t\t\ttable[s][x] = min( given[x], can[s] )\n\n\t\t\t\tif s == 1 && x > 1\n\t\t\t\t\ttable[s][x] += column_max( table, x - s - 1 )\n\t\t\t\telsif x >= 1\n\t\t\t\t\ttable[s][x] += table[ s - 1 ][ x - 1 ]\n\t\t\t\tend\n\t\t\tend \n\t\tend\n\tend\n\treturn table\nend",
"def create_table(set, prefix, n, t_size)\r\n \t# base case\r\n if t_size.zero?\r\n @table_array[@table_i] = prefix.chars\r\n @table_i += 1\r\n return\r\n end\r\n \r\n # recursive case\r\n set.each do |x|\r\n new_prefix = prefix + x\r\n create_table(set, new_prefix, n, t_size - 1)\r\n end\r\n end",
"def do_table\n @table = Hash.new { |h,k| h[k] = Hash.new }\n\n @grammar.productions.each do |lhs, prods|\n prods.each do |prod|\n if prod.rhs.size > 0\n i = 0\n sub_first = @grammar.first_set(prod.rhs[0])\n while sub_first.include?(Grammar::EPSILON)\n sub_first -= [Grammar::EPSILON]\n i += 1\n sub_first += @grammar.first_set(prod.rhs[i])\n end\n\n sub_first.each { |sym| table[lhs][sym] = prod }\n\n else\n @grammar.follow_set(lhs).each { |sym| table[lhs][sym] = prod }\n end\n end\n end\n end",
"def calculate_table(target_num)\n # this is our \"table\"\n minimum_num_of_steps = [0]\n\n (1..target_num).each do |num|\n # set an initial value in our table to weigh against\n minimum_num_of_steps[num] = Float::INFINITY\n\n if num == 1\n minimum_num_of_steps[num] = 0\n else\n # calculate values then get rid of decimals since they wouldn't make sense as indices\n # consider that we're starting with integers anyway so float results don't really work\n values = OPERATIONS.map { |op| self.send(op[0], num, op[1]) }\n values.reject! { |v| v % 1 != 0 }\n # for each valid operation's value, look at the number of steps for the index/number we're at\n # and if it's lower than the current step count in the table overwrite it\n values.each do |value|\n # current_num_steps = minimum_num_of_steps[num - value] + 1\n current_num_steps = minimum_num_of_steps[value] + 1\n\n if current_num_steps < minimum_num_of_steps[num]\n minimum_num_of_steps[num] = current_num_steps\n end\n end\n end\n end\n\n minimum_num_of_steps\nend",
"def generate_table\n letters.reverse.each_with_index do |letter, index|\n row = build_row(letter, index)\n table << row\n table.unshift(row) unless index == 0\n end\n end",
"def calculate_truth_table\r\n false_s = @char_set[0]\r\n truth_s = @char_set[1]\r\n @table_array.each do |x|\r\n trues = x.count(truth_s)\r\n trues == @size ? x.push(truth_s) : x.push(false_s)\r\n trues > 0 ? x.push(truth_s) : x.push(false_s)\r\n trues.odd? ? x.push(truth_s) : x.push(false_s) \r\n end\r\n end",
"def optimize(ary, total)\n return [] if ary.empty?\n table = []\n (ary.size+1).times { |i| table[i] = [] }\n (0..total).each { |zerg| table[0][zerg] = 0 }\n (1..ary.size).each do |base|\n table[base][0] = 0\n (1..total).each do |zerg|\n if ary[base-1].zerg <= zerg && (ary[base-1].minerals + table[base-1][zerg - ary[base-1].zerg] > table[base-1][zerg])\n table[base][zerg] = ary[base-1].minerals + table[base-1][zerg - ary[base-1][1]]\n else\n table[base][zerg] = table[base-1][zerg]\n end\n end\n end\n result = []\n i, k = ary.size, total\n while i > 0 && k > 0\n if table[i][k] != table[i-1][k]\n result << ary[i-1]\n k -= ary[i-1].zerg\n end\n i -= 1\n end\n result\nend",
"def calcresult\n tmptab = []\n i = 0\n\n until ((word1.bits[i] == nil) || (word2.bits[i] == nil))\n if (word1.bits[i] == word2.bits[i])\n if (word1.bits[i] == 1)\n tmptab.push(1)\n else\n tmptab.push(0)\n end\n else\n tmptab.push(0)\n end\n i += 1\n end\n \n # Checking whether the words are not of the same size\n if (word1.bits[i] == nil)\n until (word2.bits[i] == nil)\n tmptab.push(0)\n i += 1\n end\n else\n until (word1.bits[i] == nil)\n tmptab.push(0)\n i += 1\n end\n end\n\n return tmptab\n end",
"def make_tabula_recta\n letters = @letter_set.dup\n table = []\n letters.length.times do\n table.push letters.dup\n letters.push letters.shift\n end\n indices = {}\n letters = letters.each_with_index { |letter, i| indices[letter] = i }\n [table, indices]\n end",
"def get_Table(value, elements)\n #arr_data = values.clone #recivimos el arreglo de elementos y copiamos\n countArray = Array.new()\n array = value.split(\"\")\n\n for i in 0..(elements.length - 1)\n elements[i].setTimes(array.count(elements[i].getCode()))##Cargamos los datos al objeto Inormation\n end\n return elements\n end",
"def table(vals, probs)\n\tn = vals.length\n\trel = if probs[0].to_s.match(/\\d+\\{\\,\\}\\d+/) then 'w' else 'n' end\n\t\"\\\\begin{tabular}{*{#{n+1}}{ >{$} r <{$} }} \" + \\\n\t\"x_i & #{vals.join(\" & \")} \\\\\\\\ \" + \\\n\t\"#{rel}_i & #{probs.join(\" & \")} \" + \\\n\t\"\\\\end{tabular}\"\nend",
"def copy \n t = @tab.clone ;\n for i in 0..3\n t[i] = t[i].clone\n end\n Table.new(t) ;\n end",
"def vector\n result = []\n next_candiate = 2\n while result.size < @table_size\n (result << next_candiate) if prime?(next_candiate)\n next_candiate += 1\n end\n result\n end",
"def calcresult\n tmptab = []\n i = 0\n\n until ((word1.bits[i] == nil) || (word2.bits[i] == nil))\n if ((word1.bits[i] == 1) || (word2.bits[i] == 1))\n tmptab.push(1)\n else\n tmptab.push(0)\n end\n i += 1\n end\n\n # Checking if one of the words are not of the same size\n if (word1.bits[i] == nil)\n until (word2.bits[i] == nil)\n tmptab.push(word2.bits[i])\n i += 1\n end\n else\n until (word1.bits[i] == nil)\n tmptab.push(word1.bits[i])\n i += 1\n end\n end\n\n return tmptab\n end",
"def create_table\n dimension_length = (@numbers_to_multiply.length - 1)\n @multiplication_table = []\n new_table_row = [\" \"]\n\n for i in 0..dimension_length\n new_table_row << @numbers_to_multiply[i]\n end\n\n new_table_row\n @multiplication_table << new_table_row\n\n for x in 0..dimension_length \n new_table_row = []\n new_table_row << @numbers_to_multiply[x]\n # rowValues = \"#{@numbers_to_multiply[x]} |\"\n for y in 0..dimension_length\n nextEntry = @numbers_to_multiply[x] * @numbers_to_multiply[y]\n new_table_row << nextEntry\n end\n @multiplication_table << new_table_row\n end\n end",
"def ids(tab, offset, n, ep, x)\n ret = (0..n - 1).to_a.product((\"A\"..\"E\").to_a).map{ |s|\n tab + \"-\" + s[1].to_s + \"-\" + s[0].to_s.rjust(2,\"0\")\n }\n if x\n ret += (0..n - 1).to_a.map{ |s| tab + \"-X-\" + s.to_s.rjust(2,\"0\") }\n end\n if !ep\n ret = ret.map{ |e| (0..4).to_a.map{ |l| e + \"-\" + l.to_s.rjust(2,\"0\") } }.flatten\n end\n ret = ret.each_with_index.map{ |l, i| [offset + i, l] }.to_h\nend",
"def print_table\n\t\t@start_map.each {|k,v|\n\t\t\tr = @end_map[k]\n\t\t\tdiff = r-v\n\t\t\tputs \"#{k} => #{v} | #{r} diff #{diff}\"\n\t\t}\n end",
"def build_table(strings)\n size = strings.size\n table = []\n 0.upto(size - 1).each {|i| table << []} #init table\n 0.upto(size-1) do |i|\n 0.upto(size-1) do |j|\n if i == j\n table[i][j] = MIN_VALUE\n else\n table[i][j] = overlay_length(strings[i], strings[j])\n end\n end\n end\n table\n end",
"def multiplication_table(n)\n i = 1\n larger_table = []\n while i <= n\n j=1\n smaller_table = []\n while j <= n\n if (i*j).to_s.length == 1\n smaller_table << (i*j).to_s\n else\n smaller_table << (i*j).to_s\n end\n j += 1\n end\n larger_table << smaller_table\n i += 1\n end\n larger_table\nend",
"def knapsack_table(weights, values, capacity)\n cache = {\n 0 => [[0, 0, 0]]\n }\n return cache if n < 1\n (1..n)\n end",
"def multiple_tables(max)\n (1..max).map{ |y| (1..max).map{ |x| (\"%4d\" % (x*y)).to_i } }\nend",
"def table(array_table)\n\t\tputs \" _____1___________2____________3_____ \".colorize(:green)\n\t\tputs \" | | | |\".colorize(:green)\n\t\tputs \" | #{array_table[0]*3} | #{array_table[1]*3} | #{array_table[2]*3} |\".colorize(:green)\n\t\tputs \"A | #{array_table[0]*3} | #{array_table[1]*3} | #{array_table[2]*3} |\".colorize(:green)\n\t\tputs \" | #{array_table[0]*3} | #{array_table[1]*3} | #{array_table[2]*3} |\".colorize(:green)\n\t\tputs \" |___________|___________|____________|\".colorize(:green)\n\t\tputs \" | | | |\".colorize(:green)\n\t\tputs \"B | #{array_table[3]*3} | #{array_table[4]*3} | #{array_table[5]*3} |\".colorize(:green)\n\t\tputs \" | #{array_table[3]*3} | #{array_table[4]*3} | #{array_table[5]*3} |\".colorize(:green)\n\t\tputs \" | #{array_table[3]*3} | #{array_table[4]*3} | #{array_table[5]*3} |\".colorize(:green)\n\t\tputs \" |___________|___________|____________|\".colorize(:green)\n\t\tputs \" | | | |\".colorize(:green) \n\t\tputs \" | #{array_table[6]*3} | #{array_table[7]*3} | #{array_table[8]*3} |\".colorize(:green) \n\t\tputs \"C | #{array_table[6]*3} | #{array_table[7]*3} | #{array_table[8]*3} |\".colorize(:green)\n\t\tputs \" | #{array_table[6]*3} | #{array_table[7]*3} | #{array_table[8]*3} |\".colorize(:green)\n\t\tputs \" |___________|___________|____________|\".colorize(:green)\n\tend",
"def times_table(rows)\n if rows > 0\n array = (1..rows).to_a\n\n i = 1\n while i <= rows\n puts array.map {|e| \"#{e*i} \"}.join(' ')\n i += 1\n end\n end\nend",
"def calculate_multiplication_table\n \tprime_array.each_with_index do |element1, index1|\n \t\toutput_array[index1] = []\n \t\tprime_array.each_with_index do |element2, index2|\n\t \t\tif(index1 == 0 && index2 == 0)\n\t \t\t\toutput_array[index1][index2] = element1\n\t \t\telsif (index1 == 0)\n\t \t\t\toutput_array[index1][index2] = element2\n\t \t\telsif (index2 == 0)\n\t \t\t\toutput_array[index1][index2] = element1\n\t \t\telse\n \t\t\t\toutput_array[index1][index2] = element2*element1\n \t\t\tend\n \t\tend\n \tend\n \treturn output_array\n end",
"def calc_tree\n tree = []\n n = 1\n while n <= @n\n result = []\n result = [[0, 1]] if n == 1\n tree.each do |row|\n line1 = []\n line2 = []\n row.each_with_index do |elem, i|\n line1 << \"#{elem}0\" if i.positive?\n line2 << \"#{elem}0\" if i.zero?\n line2 << \"#{elem}1\"\n end\n result << line1 unless row.count == 1\n result << line2\n end\n tree = result\n n += 1\n end\n tree\n end",
"def hash_table(arr)\n dict = hash(arr)\n arr_dict = []\n (0..10).each do |key|\n next unless dict[key]\n\n list = dict[key]\n list.each do |item|\n arr_dict << item\n end\n end\n arr_dict\nend",
"def generate_table(grammar)\n branch_index = 0\n term_indices = grammar.terminal_indices\n columns = grammar.terminals.length + 1\n\n table = Array.new(grammar.rules.length) do\n Array.new(columns, -1)\n end\n\n grammar.rules.each_with_index do |rule, rule_index|\n rule.branches.each do |branch|\n branch.first_set.each do |step|\n # For terminals we'll base the column index on the terminal index.\n if step.is_a?(Terminal)\n terminal_index = term_indices[step]\n\n table[rule_index][terminal_index + 1] = branch_index\n\n # For the rest (= epsilon) we'll update all columns that haven't\n # been updated yet.\n else\n table[rule_index].each_with_index do |col, col_index|\n table[rule_index][col_index] = branch_index if col == -1\n end\n end\n end\n\n branch_index += 1\n end\n end\n\n return table\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length){Array.new(capacity+1)}\n (0...weights.length).each do |row|\n (0..capacity).each do |col|\n if col < weights[row]\n table[row][col] = table[row-1][col] unless row == 0\n table[row][col] = 0 if row == 0\n else \n val = values[row]\n weight = weights[row]\n left_over = table[row-1][col-weight].nil? ? 0 : table[row-1][col-weight]\n old_val = row == 0 ? val : table[row-1][col]\n table[row][col] = [old_val, val + left_over].max\n end \n end \n end \n table\n end",
"def opx_dump_tabulator_data(tab)\n print \"Tabulator Data Summary\\n\"\n print \" Jurisdiction UID: #{tab.uids['jurisdiction'][0]}\\n\"\n print \" Election UID: #{tab.uids['election'][0]}\\n\"\n ['district','precinct','contest','candidate','question','counter',\n 'file','reporting group'].each do |k|\n length = tab.uids[k].length.to_s\n myuids = tab.uids[k].sort\n type = (k =~ /^report/ ? \"Reporting Groups\" : \"#{k.capitalize} UIDs\")\n if (myuids.length == 0)\n prefix = \" #{type} (NONE)\\n\"\n else\n prefix = \" #{type} (#{myuids.length.to_s}): \"\n print prefix\n if (myuids.length > 10)\n prefix = \" \"\n print \"\\n#{prefix}\"\n end\n opx_pp(myuids, prefix.length, prefix.length, 78)\n end\n end\n missing = (tab.counts_expected - tab.counts_accumulated)\n count = missing.length\n total = tab.counts_expected.length\n print \" Expected Counts \"\n if (total == 0)\n print \"(NONE)\\n\"\n else\n print \"(#{total}): Counter UID, Reporting Group, Precinct UIDs\\n\"\n tab.uids[\"counter\"].sort.each do |cid|\n if (tab.counts_expected.any? {|ce| ce[0] == cid})\n rgs = tab.uids[\"reporting group\"].sort.select { |rg|\n tab.counts_expected.any? {|ce| ce[0] == cid && ce[1] == rg }}\n rgs.each { |rg|\n pids = tab.uids[\"precinct\"].sort.select { |pid|\n tab.counts_expected.any? {|ce| ce == [cid, rg, pid]}}\n print \" #{cid}, #{rg}, #{pids.uniq.inspect.gsub(/\\\"/,\"\")}\\n\"}\n end\n end\n end\n print \" Missing Counts \"\n if (count == 0)\n print \"(NONE)\\n\"\n else\n print \"(#{count}): Counter UID, Precinct UID, Reporting Group\\n\"\n missing.each do |cid, rg, pid|\n print \" #{cid}, #{pid}, #{rg}\\n\"\n end\n end\n if (tab.counts_contests.keys.length == 0)\n print \" Contests (NONE)\\n\"\n else\n print \" Contests (\",tab.counts_contests.keys.length.to_s,\"):\"\n print \" Contest UID: overvote, undervote, write-in, Candidate UIDs\\n\"\n end\n tab.counts_contests.keys.sort.each do |k|\n v = tab.counts_contests[k]\n print \" #{k}: \"\n print \"overvote = #{v[\"overvote_count\"]}, \"\n print \"undervote = #{v[\"undervote_count\"]}, \"\n print \"writeins = #{v[\"writein_count\"]}\\n\"\n v[\"candidate_count_list\"].each do |item|\n print \" #{item[\"candidate_ident\"]} = #{item[\"count\"]}\\n\"\n end\n end\n if (tab.counts_questions.keys.length == 0)\n print \" Questions (NONE)\\n\"\n else\n print \" Questions (\",tab.counts_questions.keys.length.to_s,\"):\"\n print \" Question UID: overvote, undervote, Answers\\n\"\n end\n tab.counts_questions.keys.sort.each do |k|\n v = tab.counts_questions[k]\n print \" #{k}: \"\n print \"overvote = #{v[\"overvote_count\"]}, \"\n print \"undervote = #{v[\"undervote_count\"]}\\n\"\n v[\"answer_count_list\"].each do |item|\n print \" #{item[\"answer\"]} = #{item[\"count\"]}\\n\"\n end\n end\n print \"\\n\"\n rescue => e\n opx_err(\"Fatal failure while dumping Tabulator data\", e)\n end",
"def fibonacci(n)\n # create an array with n elements \n # result_table will contain the final results \n result_table = Array.new(n, 0)\n \n # initial elements of the sequence \n result_table[0] = 0\n result_table[1] = 1\n \n # Fist element already calculated\n # we start with the 3rd \n tab_index = 2\n (n-2).times do\n # the array element is equal to the sum of 2 previous elements\n result_table[tab_index] = result_table[tab_index-1] + result_table[tab_index-2] \n tab_index += 1\n end\n \n return result_table\nend",
"def display_table(orders)\n table_hash = Hash.new([])\n tables = []\n items = []\n orders.each do |order|\n items << order[2]\n if !table_hash.has_key?(order[1])\n table_hash[order[1]] = []\n end\n table_hash[order[1]] << order[2]\n end\n\n header = items.uniq.sort.unshift(\"Table\")\n tables << header\n table_hash.keys.map {|key| key.to_i}.sort.each do |table|\n table = table.to_s\n hash = Hash.new(0)\n table_order = table_hash[table]\n table_order.each do |item|\n if !hash.has_key?(item)\n hash[item] = 0\n end\n hash[item] += 1\n end\n new_row = [table]\n items.uniq.sort.each do |item|\n if !hash.has_key?(item)\n hash[item] = 0\n end\n new_row << hash[item].to_s\n end\n tables << new_row\n end\n\n return tables\nend",
"def dp_possible_trees(n)\n array = Array.new(n+2) { Array.new(n+1) { 0 } }\n (0...n+2).to_a.each do |i|\n array[i][0] = 1\n end\n\n sum = 0\n (1...n+1).to_a.each do |i|\n sum = 0\n (1..i).to_a.each do |j|\n array[j][i] = array[n+1][i-j] * array[n+1][j-1]\n sum += array[j][i]\n end\n array[n+1][i] = sum\n end\n array[n+1].last\nend",
"def gentbl(t)\n colszs=[]\n t.each do |line|\n line.size.times do |i|\n elem = line[i]\n sz = elem.to_s.size\n colszs[i] = sz if !colszs[i] or colszs[i] < sz \n end \n end\n out = \"\"\n t.each do |line|\n line.size.times do |i|\n elem = line[i].to_s\n col = \" \" * colszs[i]\n elem.size.times do |j|\n col[j] = elem[j]\n end\n out += col + \" \"\n end\n out += \"\\n\"\n end\n return out\nend",
"def ll_table\n\t\ttable = {}\n\t\tnon_terminals.each do |non_term|\n\t\t\ttable[non_term] = {}\n\t\t\tp_sets = predict_sets(non_term)\n\t\t\tp_sets.each_index do |i|\n\t\t\t\tp_sets[i].each do |term|\n\t\t\t\t\ttable[non_term][term] = i\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\treturn table\n\tend",
"def test_table\n return <<HERE;\n 2 3 5 7 11\n 3 9 15 21 33\n 5 15 25 35 55\n 7 21 35 49 77\n 11 33 55 77 121\nHERE\nend",
"def times_table(rows)\n n = 0\n rw = rows - 1\n while n <= rw\n \tn += 1\n \ty = 1\n while y <= rows\n print y*n\n print ' '\n y+=1\n end\n puts ''\n end\nend",
"def solution2\n n = 1000\n\n hsh = Hash.new([])\n\n (1..n).each do |x|\n (1..n).each do |y|\n hsh[x**3 + y**3] += [x, y]\n end\n end\n\n hsh.values\nend",
"def to_array(array=nil)\n if array\n array.start = 0\n array.total = @size\n else\n array = Array.new @size\n end\n\n i = 0\n while i < @capacity\n array[@table[i+2]] = @table[i+1] if @table[i]\n i += 4\n end\n\n unless @spill.empty?\n i = @spill.to_iter 3\n while i.next\n array[i.at(2)] = i.at(1) if i.item\n end\n end\n\n array\n end",
"def mksegments(table)\n disjoint, = table.basis(table.instructions)\n remaining = Set.new(table.instructions)\n segment_id = table.instructions.head.segment_use.id\n segments = []\n\n # Scan each interesting element location\n disjoint.each do |(m, n), map|\n if remaining.empty?\n # We've already generated results for each possible instruction\n break\n end\n\n # Likely many values are mapped to only a few unique keys; in this\n # case, `instructions` is a singleton array (that's what makes the\n # value non-ambiguous, there's only one possible instruction)\n map.each do |value, instructions|\n op, = instructions\n repeatable = op.segment_use.definition.element_uses.at(m).repeatable?\n elements = Array.new(m)\n elements[m] =\n if n.nil?\n if repeatable\n repeated(value)\n else\n value\n end\n else\n components = Array.new(n)\n components[n] = value\n\n if repeatable\n repeated(composite(components))\n else\n composite(components)\n end\n end\n\n if remaining.member?(op)\n remaining.delete(op)\n segments.push([op, mksegment_tok(@reader.segment_dict, segment_id, elements, nil)])\n end\n end\n end\n\n segments\n end",
"def tally!(file_count)\n @table.each do |words, bigram|\n bigram.tally!(table.size, file_count)\n end\n end",
"def ukp2(ukpi, ret_table = true)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n # step one\n g = Array.new(c+1, 0)\n d = Array.new(c+1, n-1)\n sort_items_by_profitability!(items)\n\n gy_col = nil\n dy_col = nil\n if ret_table then\n gy_col = Array.new(c+1) { [] }\n dy_col = Array.new(c+1) { [] }\n end\n\n # step two to six\n (c+1).times do | y |\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n items.each_with_index do | item, j |\n if y - item[:w] >= 0 && j <= d[y - item[:w]] then\n v = g[y - item[:w]] + item[:p]\n if v > g[y] then\n g[y] = v\n d[y] = j\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n end\n end\n end\n end\n\n table = \"y\\tg(y)\\t\\td(y)\\n\"\n if ret_table then\n (c+1).times do | y |\n table << \"#{y}\\t#{gy_col[y].join(' ')}\\t\\t#{dy_col[y].join(' ')}\\n\"\n end\n end\n \n if ret_table then\n table\n else\n g\n end\nend",
"def initTableMapping\n $map = Array.new(2000) { Array.new(2000,\"\") }\n $final_map = Array.new(2000) { Array.new(2000,\"\") }\n $hash = Hash.new(0)\nend",
"def knapsack_table(weights, values, capacity)\n table = [Array.new(values.length) {0}]\n (1..capacity).each do |capacity|\n prev = 0\n best = []\n values.length.times do |i|\n value = values[i]\n weight = weights[i]\n if i == 0 && weight <= capacity\n take = value\n else\n take = value + table[capacity - weight][i - 1] if capacity - weight >= 0\n end\n if take && take > prev\n best[i] = take\n else\n best[i] = prev\n end\n prev = best[i]\n end\n table.push(best)\n end\n table\n end",
"def amicables(limit)\n numbers = Array.new(limit, 0)\n (1...limit).each do |i|\n ((i * 2)...limit).step(i) do |j|\n numbers[j] += i\n end\n end\n result = []\n numbers.each_with_index do |j, i|\n if j < limit && i == numbers[j] && i != j\n result << i\n end\n end\n result\nend",
"def ptn(a)\n if a.size == 1 then\n return [a]\n end\n ret = Array.new\n # 重ならないパターン\n ret += a.perms\n # 重なるパターン\n h1 = Hash.new\n for i in 0..a.size - 1\n for j in i + 1..a.size - 1\n key = [a[i], 0, a[j]].to_s\n if !h1.key?(key) then\n h1.store(key, nil)\n h2 = Hash.new\n # a[i]とa[j]を範囲をずらしながら重ねる\n for k in 0..a[i].size + a[j].size\n t = [0] * a[j].size + a[i] + [0] * a[j].size\n for m in 0..a[j].size - 1\n t[k + m] += a[j][m]\n end\n # 余分な0を取り除く\n t.delete(0)\n # 4より大きい値がないかチェック\n next if t.any? {|v| v > 4}\n # 9より長くないかチェック\n next if t.size > 9\n # 重複チェック\n if !h2.key?(t.to_s) then\n h2.store(t.to_s, nil)\n # 残り\n t2 = a.dup\n t2.delete_at(i)\n t2.delete_at(j - 1)\n # 再帰呼び出し\n ret += ptn([t] + t2)\n end\n end\n end\n end\n end\n return ret\nend",
"def tdist(n, t); p_t(n, t); end",
"def nudge!(nx, ny, nz)\n src_table = self.dup\n xs, ys, zs = tabclone.xsize, tabclone.ysize, tabclone.zsize\n if zs > 1\n iterate do |n, x, y, z|\n self[(x + nx) % xs, (y + ny) % ys, (z + nz) % zs] = n\n end\n elsif ys > 0\n iterate do |n, x, y|\n self[(x + nx) % xs, (y + ny) % ys] = n\n end\n else\n iterate do |n, x|\n self[(x + nx) % xs] = n\n end\n end\n return self\n end",
"def knapsack_table(weights, values, capacity)\n knapsack_cache = {0 => Array.new(weights.length, 0)}\n (1..capacity).each do |c|\n knapsack_cache[c] = c == weights[0] ? [values[0]] : [0]\n end\n (1...weights.length).each do |col|\n (1..capacity).each do |c|\n current_weight = weights[col]\n current_value = values[col]\n if c < current_weight\n knapsack_cache[c][col] = knapsack_cache[c][col - 1]\n else\n new_value = knapsack_cache[c - current_weight][col - 1] + current_value\n knapsack_cache[c][col] = [new_value, knapsack_cache[c][col - 1]].max\n end\n end\n end\n knapsack_cache\n\n end",
"def splice_table(*tables)\n table = tables.shift\n tables.each do |new_table|\n table.each_with_index do |row, i|\n table[i] = row + new_table[i]\n end\n end\n table\nend",
"def transpose() end",
"def transition_table(pattern, radix)\n table = Hash.new\n (0..pattern.length).each do |i|\n table[\"state:#{i}\"] = {pattern: pattern[0...i]}\n end\n\n (0...pattern.length).each do |i|\n radix.each do |char|\n str = table[\"state:#{i}\"][:pattern] + char\n discard_num = 0\n (i+1).downto(0) do |j|\n if table[\"state:#{j}\"][:pattern] == str.chars.drop(discard_num).join\n table[\"state:#{i}\"][char] = \"state:#{j}\"\n next\n end\n discard_num += 1\n end\n end\n end\n\n table\nend",
"def initialize\n # Set the initial number of slots to 5\n @slots = 5 \n # Initialize all of the slots with nil values.\n fill_table @slots \n # Set up auxiliary functions, h1 and h2\n @h1 = -> (k) { k % @slots }\n @h2 = -> (k) { 1 + (k % (@slots - 1)) }\n # Set size (occupied positions) to 0.\n self.size = 0\n # Set the number of rebuilds to zero. (If the table grows past certain threshold we have to rebuild it.)\n @rebuilds = 0\nend",
"def perm(table)\n table.split(' ').map{ |bit| self[bit.to_i-1] }\nend",
"def test_table_too\n return <<HERE;\n 2 3 5 7 11\n 2 4 6 10 14 22\n 3 6 9 15 21 33\n 5 10 15 25 35 55\n 7 14 21 35 49 77\n 11 22 33 55 77 121\nHERE\nend",
"def putOnTable\n # take the 12 cards on top of the deck and deal on \"table\"\n @cardsOnTable = @cards[0..11]\n 12.times{@cards.shift}\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length) { Array.new(capacity + 1) {0} }\n min_weight = weights.min\n weights.each_with_index do |weight, row|\n (min_weight..capacity).each do |col|\n if weight > col && row > 0\n table[row][col] = table[row - 1][col]\n elsif row > 0\n table[row][col] = [values[row] + table[row - 1][col - weight],\n table[row - 1][col]].max\n elsif weight <= col\n table[row][col] = values[row]\n end\n end\n end\n table\n end",
"def knapsack_table(weights, values, capacity)\n n = weights.length\n table = Array.new(capacity + 1) { Array.new(n, 0) }\n\n 1.upto(capacity) do |c|\n (0...n).each do |i|\n if weights[i] > c\n table[c][i] = table[c][i - 1]\n elsif i == 0\n table[c][i] = values[i]\n else\n prev_val = table[c][i - 1]\n table[c][i] = [prev_val, table[c - weights[i]][i - 1] + values[i]].max\n end\n end\n end\n\n table\n end",
"def create_times_table\n\treturn_array = []\n\tgame_array = []\n\n\t#2 * 2-9\n\t#3 * 3-9\n\t#4 * 4-9\n\t# etc ...\n\n\t(2..9).each do |i|\n\t\t(i..9).each do |j|\n\t\t\tgame_array << i * j\n\t\t\tgame_array << i \n\t\t\tgame_array << j\n\t\t\t2.times do \n\t\t\t\tgame_array << add_wrong(9, game_array)\n\t\t\tend\n\t\t\t2.times do\n\t\t\t\tgame_array << add_wrong(20, game_array)\n\t\t\tend\n\t\t\t2.times do \n\t\t\t\tgame_array << add_wrong(81, game_array)\n\t\t\tend\n\n\t\t\treturn_array << game_array\n\t\t\tgame_array = []\n\t\tend\n\tend\n\treturn_array.each do |game_array|\n\t\tTimes.create(level: 10, t1: game_array[0],\n\t\t\tt2: game_array[1], t3: game_array[2],\n\t\t\tt4: game_array[3], t5: game_array[4],\n\t\t\tt6: game_array[5], t7: game_array[6],\n\t\t\tt8: game_array[7], t9: game_array[8])\n\tend\n\t\t\t\nend",
"def expand_tabs(n=8)\n n = n.to_int\n raise ArgumentError, \"n must be >= 0\" if n < 0\n return gsub(/\\t/, \"\") if n == 0\n return gsub(/\\t/, \" \") if n == 1\n str = self.dup\n while\n str.gsub!(/^([^\\t\\n]*)(\\t+)/) { |f|\n val = ( n * $2.size - ($1.size % n) )\n $1 << (' ' * val)\n }\n end\n str\n end",
"def expand_tabs(n=8)\n n = n.to_int\n raise ArgumentError, \"n must be >= 0\" if n < 0\n return gsub(/\\t/, \"\") if n == 0\n return gsub(/\\t/, \" \") if n == 1\n str = self.dup\n while\n str.gsub!(/^([^\\t\\n]*)(\\t+)/) { |f|\n val = ( n * $2.size - ($1.size % n) )\n $1 << (' ' * val)\n }\n end\n str\n end",
"def filas(tablero)\r\n\t#Fila0\r\n\t\te = 0\r\n\t\t@fila0 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila0 << tablero[0,e]\r\n\t\t\te += 1\r\n\t\tend\r\n\r\n\t#Fila1\r\n\t\te = 0\r\n\t\t@fila1 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila1 << tablero[1,e]\r\n\t\t\te += 1\r\n\t\tend\r\n\r\n\t#Fila2\r\n\t\te = 0\r\n\t\t@fila2 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila2 << tablero[2,e]\r\n\t\t\te += 1\r\n\t\tend\r\n\r\n\t#Fila3\r\n\t\te = 0\r\n\t\t@fila3 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila3 << tablero[3,e]\r\n\t\t\te += 1\r\n\t\tend\r\n\r\n\t#Fila4\r\n\t\te = 0\r\n\t\t@fila4 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila4 << tablero[4,e]\r\n\t\t\te += 1\r\n\t\tend\r\n\r\n\r\n\t#Fila5\r\n\t\te = 0\r\n\t\t@fila5 = Array.new\r\n\t\twhile e < 7\r\n\t\t\t@fila5 << tablero[5,e]\r\n\t\t\te += 1\r\n\t\tend\r\nend",
"def knapsack_table(weights, values, capacity)\n n = weights.length\n array = Array.new(capacity + 1) { Array.new(n, 0) }\n\n (1..capacity).each do |j|\n (0...n).each do |i|\n if weights[i] > j\n array[j][i] = array[j][i - 1]\n elsif i == 0\n array[j][i] = values[i]\n else\n prev_val = array[j][i - 1]\n array[j][i] = [prev_val, array[j - weights[i]][i - 1] + values[i]].max\n end\n end\n end\n\n array\n end",
"def output_table(output=$stdout)\n word_list = words.sort_by{ |w| words.rank(w) }.reverse\n\n word_list = word_list[0, MAX_WORDS]\n\n sets = []\n word_list.each_with_index do |w, i|\n bigram_list = bigrams.matching_bigrams(w.spelling)\n bigram_list = bigram_list.sort_by{ |b| bigrams.rank(b) }.reverse\n bigram_list = bigram_list.map{ |b| b.word2 }.uniq\n bigram_list = bigram_list[0,6] # maximum of six bigrams\n sets << [w.spelling] + bigram_list\n end\n\n sets.each do |w|\n output.puts(w.join(' ')) \n end\n end",
"def knapsack_table(weights, values, capacity)\n num_items = weights.length\n weight_val_hash = {}\n (1..num_items).each do |i|\n weight_val_hash[i] = [weights[i - 1], values[i - 1]]\n end\n table = Array.new(num_items + 1) { Array.new(capacity + 1)}\n table[0].each_index do |idx|\n table[0][idx] = 0\n end\n (1..num_items).each do |i|\n weight, value = weight_val_hash[i]\n (0..capacity).each do |j|\n if weight > j\n table[i][j] = table[i-1][j]\n else\n table[i][j] = [table[i-1][j], table[i-1][j - weight] + value].max\n end\n end\n end\n return table\n end",
"def toh_iterative(n)\n t = [['A', 'B', 'C']]\n col = 0 # starting column\n top = 1 # starting top disk\n n.downto(1) do |i|\n t.unshift([i, '', '']) # build starting tower array\n end\n t.to_table # print it\n moves = 2 ** n - 1\n\n moves.times do \n !n.even? ? left = 1 : left = -1 # if n odd, move odd disks left, else move right.\n startcol = col\n startrow = t.transpose[col].index(top)\n\n if !top.even?\n # move left if disk odd and n odd. move right if disk odd and n even.\n col -= left\n else\n # move right if disk even and n odd. move left if disk even and n odd.\n col += left \n end\n\n col = 2 if col < 0 # If moves off edge, swing it back around.\n col = 0 if col > 2\n \n endtop = t.transpose[col].detect {|d| d != ''} # top disk in new column\n row = t.transpose[col].index(endtop) - 1 # 1st empty row in new column\n\n t[startrow][startcol] = '' # erase entry in disk's previous location\n t[row][col] = top # write disk in new location\n t.to_table\n\n top_maybe = []\n\n (0..2).each do |c| # What disk do we move next?\n top_maybe[c] = t.transpose[c].detect {|d| d != ''} # top disk in column c\n\n # May not move current disk in next move. Make it high so it's not picked.\n top_maybe[c] = 100 if c == col \n top_maybe[c] = 100 if top_maybe[c].is_a?(String) # Column is empty\n end\n\n top = top_maybe.min # Next disk is smallest possible one.\n col = top_maybe.index(top)\n end\nend",
"def generate_table(t_sym, f_sym, size)\n table_output = \"\"\n 0.upto(2**size.to_i - 1).each do |n|\n num = (\"%0#{size}b\" % n)\n # Format the binary string with the user's true/false symbols\n f_num = format_num t_sym, f_sym, num\n # Execute boolean operations on each binary string\n num_and = op_and t_sym, f_sym, num\n num_or = op_or t_sym, f_sym, num\n num_nand = op_nand t_sym, f_sym, num_and\n num_nor = op_nor t_sym, f_sym, num_or\n num_xor = op_xor t_sym, f_sym, num\n num_single = op_single t_sym, f_sym, num\n # Return the value for each row\n table_output += \"#{f_num} #{num_and} #{num_or} #{num_nand} #{num_nor} #{num_xor} #{num_single}\\n\"\n end\n table_output\nend",
"def feedable_wells_table(plate)\n tab = plate.matrix.map do |row|\n row.map do |id|\n next \"(empty)\" if id == -1\n well = Item.find(id)\n {content: \"#{well.id}\", check: is_feedable(well) ? true : false}\n end\n end\n tab.unshift((1..6).to_a)\n ['', 'A', 'B', 'C', 'D'].each.with_index{ |str, i| tab[i].unshift(str) }\n return tab\n end",
"def cal_row(n)\n f = []\n (0..n/2).each do |k|\n f << if k == 0\n 1\n else\n (@prev_row[k] + @prev_row[k-1])\n end\n end\n f.concat(f[0, (n+1)/2].reverse)\n end",
"def slice(table)\n head, body, array_h, array_b = 4.times.map { [] }\n index = 0\n first_column = 0\n second_column = 1\n\n (0...table.original_columns * table.original_rows).each do |col_index|\n row = table.rows[index]\n array_h += [row[first_column]]\n array_b += [row[second_column]]\n\n if col_index % table.original_columns == 2\n head << array_h\n body << array_b\n array_h, array_b = [], []\n end\n index += 1\n end\n [head, body]\n end",
"def collect\r\n array = []\r\n @table.each do |subarray|\r\n array.concat subarray\r\n end\r\n array\r\n end",
"def tabulate(labels, data, indent = 0,style=\"simple\" )\n raise \"Invalid table style!\" unless $template.keys.include? style\n raise 'Label and data do not have equal columns!' unless labels.size == data.transpose.size\n\n data = data.inject([]){|rs, r| rs += r.to_rows }\n data = data.unshift(labels).transpose\n padding = $template[style][:padding] \n data = data.collect {|c| \n c.collect {|e| ' ' * padding + e.to_s + ' ' * padding } \n }\n widths = data.collect {|c| c.collect {|a| a.width}.max } \n newdata = []\n data.each_with_index {|c,i|\n newdata << c.collect { |e| e + ' '*(widths[i] - e.width) }\n }\n data = newdata\n data = data.transpose\n data = [ $template[style][:hlframe] + data[0].join($template[style][:fs]) + $template[style][:hrframe] ] + \\\n data[1..-1].collect {|l| $template[style][:lframe] + l.join($template[style][:fs]) + $template[style][:rframe] }\n lines = []\n if !$template[style][:tframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:tframe] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n lines << data[0]\n if !$template[style][:hs].to_s.empty? and !$template[style][:lframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:hs] *n }.join($template[style][:cross]) + $template[style][:cross]\n elsif !$template[style][:hs].to_s.empty?\n lines << widths.collect{|n| $template[style][:hs] *n }.join($template[style][:cross])\n end\n data[1..-2].each{ |line|\n lines << line\n if !$template[style][:rs].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:rs] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n }\n lines << data[-1]\n if !$template[style][:bframe].to_s.empty?\n lines << $template[style][:cross] + widths.collect{|n| $template[style][:bframe] *n }.join($template[style][:cross]) + $template[style][:cross]\n end\n lines.collect {|l| ' '*indent + l}.join(\"\\n\")\nend",
"def tabulate_outcomes(state)\n #return early if we have a cached solution for the given [state]\n if out = @TAB_CACHE[state.board_bits]\n return out\n end\n \n @iteration_count += 1\n out = {x: 0, o: 0, cat:0}\n \n #if this state has a winner, it's easy\n if w = state.winner\n out[w] = 1\n case w\n when @opponent\n out[:worst] = -1\n when @playing_mark\n out[:worst] = 1\n else\n out[:worst] = 0\n end\n \n return out\n end\n \n #loop through each possible move\n state.legal_moves.each do |q|\n outcomes = tabulate_outcomes q\n \n #raw counts\n [:x, :o, :cat].each {|k| out[k] += outcomes[k]}\n \n #if it's the other player's turn assume they make the best move they can, and vice versa\n if state.next_turn_taker == @opponent\n out[:worst] = outcomes[:worst] if (!out[:worst] || (outcomes[:worst] < out[:worst]))\n else\n out[:worst] = outcomes[:worst] if (!out[:worst] || (outcomes[:worst] > out[:worst]))\n end\n end\n \n cache_solution(state, out)\n \n return out\n end",
"def fillout\n count.times do |j|\n self[j].clear_hits\n reps = (@len.to_f / (mapee(j).length)).round\n self[j] << reps.eqly_spaced\n end\n end",
"def partial_table(ary, sep=',')\n indexes = []\n res = \"\"\n ary.each_with_index do |field, i|\n idx = @ocp_solution[:headers].find_index(field)\n if idx then\n indexes << idx\n else\n ary.delete_at i\n end\n end\n res << ary.join(sep) + \"\\n\"\n self.length.times do |i|\n res << indexes.inject([]) {|a,e| a << @ocp_solution[:data][e][i] }.join(sep) + \"\\n\"\n end\n return res\n end",
"def print_prime_table\n out = ''\n prime_array = print_prime\n top_line = \"\\t#{prime_array.join(\"\\t\")}\"\n out += top_line + \"\\n\"\n for prime_row in prime_array\n line = \"\"\n line += \"#{prime_row}\\t\"\n for prime_col in prime_array\n line += \"#{prime_row * prime_col}\\t\"\n end\n out += line + \"\\n\"\n end\n out\n end",
"def createHashTable()\n \n #Loop to parse alphabetically sorted letters in given word,\n #create hash table\n\n for i in 0..@sortedWord.length-1\n currentLetter = @sortedWord[i]\n \n #Check if currentLetter already has entry. If so, increment currentLetter's \n #occurrencesOfLetter. Then multiply it with global @multiLetterDivisor. If\n #letter has 2 occurrences, @multiLetterDivisor gets multiplied by 2. If it\n #has 3 occurrences, it gets multiplied by 2 and then 3, which is 3!\n #So when hash table is complete, @multiLetterDivisor globally tracks total\n #factorial division needed spanning all letters\n \n if @letterHash.has_key? currentLetter\n @letterHash[currentLetter][\"occurrencesOfLetter\"] =\n @letterHash[currentLetter].fetch(\"occurrencesOfLetter\", 0) + 1\n @multiLetterDivisor *= @letterHash[currentLetter][\"occurrencesOfLetter\"]\n \n #if no entry exists then first occurrence of this letter.\n #Assign global @uniqueLetterCount to this letter's alphabetical index\n #Set occurrencesOfLetter to 1. Increment @uniqueLetterCount.\n \n else\n @letterHash[currentLetter][\"alphabeticalIndex\"] = @uniqueLetterCount\n @letterHash[currentLetter][\"occurrencesOfLetter\"] = 1\n @uniqueLetterCount += 1\n \n #For first letter in alphabetical sequence, totalLettersBefore is 0.\n #For all others, set it to global @totalLetterCount\n \n if (@uniqueLetterCount == 0)\n @letterHash[currentLetter][\"totalLettersBefore\"] = 0\n else\n @letterHash[currentLetter][\"totalLettersBefore\"] = @totalLetterCount\n end \n end\n \n #1 letter has been added to hash table. Increment global\n #@totalLetterCount\n \n @totalLetterCount += 1\n end\n end",
"def run_tests\r\n File.open \"output_1_big.txt\", \"w\" do |output|\r\n File.open \"A-large.in\" do |input|\r\n number_of_tests = input.gets.to_i\r\n number_of_tests.times do |test_number|\r\n test = input.gets.split /\\s+/, 2\r\n n = test[0].to_i\r\n k = test[1].to_i\r\n table=[]\r\n n.times do |row|\r\n table[row] = input.gets.chomp\r\n end\r\n\r\n p table\r\n table = rotate_table table, n\r\n p table\r\n puts check_k_in_table table, n, k\r\n output.puts \"Case ##{test_number + 1}: \" + check_k_in_table(table, n, k)\r\n\r\n end\r\n end\r\n end\r\nend",
"def knapsack_table(weights, values, capacity)\n table = []\n\n (0..capacity).each do |i|\n table[i] = []\n\n (0...weights.length).each do |j|\n if i.zero?\n table[i][j] = 0\n elsif j.zero?\n table[i][j] = weights[j] > i ? 0 : values[j]\n else\n option1 = table[i][j - 1]\n option2 = weights[j] > i ? 0 : table[i - weights[j]][j - 1] + values[j]\n\n optimum = [option1, option2].max\n table[i][j] = optimum\n end\n end\n end\n \n table\n end",
"def tarjan\n @t_index = 0\n @t_stack = []\n @tg_index = {}\n @tg_lowlink = {}\n @t_result = []\n \n @t_pstack = []\n @t_forindex = Hash.new(0)\n @t_onstack = Hash.new(false)\n @g.each_key do |k|\n if @tg_index[k] == nil\n tarjan_iter(k)\n end\n end\n @t_result.sort!.reverse!\n end",
"def bitmap\n bit_table.flatten.each_with_index.map do |bit, index|\n [index, bit_table.transpose.flatten.index(bit)]\n end.to_h\nend",
"def txXX_(n, x); tdist(n, x); end",
"def pair_sum_using_hash_table(input, target_sum)\n # hash which will store nos\n hash_table = {}\n \n # target sum should be 10\n #target_sum = 10\n\n # put both no's in array which sums up to 10\n result = []\n \n for i in input do\n tmp_result = target_sum - i\n # if tmp_result is present in hash then break , we found our nos\n if hash_table.has_key?(tmp_result)\n result << i \n result << tmp_result\n break\n else\n # if equation result is not present in hash then put i in hash\n hash_table[i] = true\n end\n end\n ap \"Out put #{result}\"\n return result\nend",
"def two_sum(nums, target)\n table = {}\n i = 0\n while i < nums.length\n table[target - nums[i]] = i\n i += 1\n end\n \n j = 0\n while j < nums.length\n if table.key?(nums[j]) && j != table[nums[j]]\n return [j, table[nums[j]]] \n end\n j += 1\n end\nend",
"def table_data\n @building_groups.reduce([]) do |table, bg|\n table << energy_row(bg)\n end\n end",
"def times_table(rows)\n 1.upto(rows) do |y|\n puts\n 1.upto(rows) { |x| print \"#{x * y} \"}\n end\nend",
"def print_table\n dimension_length = (@numbers_to_multiply.length)\n topColumn = \"\"\n for i in 0..dimension_length\n topColumn += \" #{@multiplication_table[0][i]} |\"\n end\n for x in 0..dimension_length \n rowValues = \"\"\n for y in 0..dimension_length\n nextEntry = @multiplication_table[x][y]\n rowValues << \" #{nextEntry} |\"\n end\n puts rowValues\n end\n end",
"def table_size_for(entry_count); end",
"def valid_table(cards_showing)\n\n # make hash of all table cards\n # id is the key, location is the value\n table_hash = Hash.new\n return [] if cards_showing.length < 1\n\n (0...cards_showing.length).each {|i| table_hash[cards_showing[i].id] = i}\n\n (0...cards_showing.length).each do |card1|\n (1...cards_showing.length).each do |card2|\n if card1 == card2 #skip if same card\n next\n end\n\n # Find attributes of the last card needed\n # Using the attributes of any two cards, you can determine what the final card would be that would make a set\n # This finds the attributes of that last card, which is later used to see if that card is available\n card_to_find = 27 * ((6- cards_showing[card1].number - cards_showing[card2].number) % 3)\n card_to_find += 9 * ((6- cards_showing[card1].color - cards_showing[card2].color) %3)\n card_to_find += 3 * ((6- cards_showing[card1].shape - cards_showing[card2].shape) %3)\n card_to_find += (6-cards_showing[card1].shade - cards_showing[card2].shade) %3\n\n # cardToFind is now the card ID for the last card\n return [card1, card2, table_hash[card_to_find]] if table_hash.include? card_to_find\n\n end\n end\n\n return []\n end",
"def knapsack_table(weights, values, capacity)\n table = []\n\n (0..capacity).each do |cap|\n table[cap] = []\n\n (0...weights.length).each do |weight|\n if cap.zero?\n table[cap][weight] = 0\n elsif weight.zero?\n table[cap][weight] = values[0]\n table[cap][weight] = 0 if weights[0] > cap\n else\n option1 = table[cap][weight - 1]\n if weights[weight] > cap\n option2 = 0\n else\n option2 = table[cap - weights[weight]][weight - 1] + values[weight]\n end\n table[cap][weight] = [option1, option2].max\n end\n end\n end\n\n table\n\n end",
"def copy\n result = HashTablet.new(@table.size)\n each {|element| result.insert(element) }\n return result\n end",
"def knapsack_table(weights, values, capacity)\n result_table = []\n (0..capacity).each do |idx1|\n result_table[idx1] = []\n (0..weights.length - 1).each do |idx2|\n if idx1 == 0\n result_table[idx1][idx2] = 0\n elsif idx2 == 0\n result_table[idx1][idx2] = weights[0] > idx1 ? 0 : values[0]\n else\n opt1 = result_table[idx1][idx2 - 1]\n opt2 = idx1 < weights[idx2] ? 0 : result_table[idx1 - weights[idx2]][idx2 - 1] + values[idx2]\n optimum = [opt1, opt2].max\n result_table[idx1][idx2] = optimum\n end\n end\n end\n result_table\n end",
"def knapsack_table(weights, values, capacity)\n # iterate over the weights\n # nested - iterate over the table array\n # For each capacity_idx < weight, push into the current capacity array..\n # either a 0 or the last value in the current capacity array (which ever is larger)\n # For capacity_idx >= weight\n # compare capacity[idx].last to (capacity[idx-weight].second_to_last + value of current weight)\n # Which ever is larger, push into capacity[idx]\n\n table = Array.new(capacity + 1) { Array.new }\n\n weights.each_with_index do |weight, wv_id|\n table.each_with_index do |local_solutions, current_cap|\n new_value = 0\n if current_cap < weight\n new_value = local_solutions[-1] || new_value\n else\n if wv_id == 0\n new_value = values[wv_id]\n else\n with_weight = table[current_cap - weight][-2] + values[wv_id]\n without_weight = local_solutions.last\n new_value =[with_weight, without_weight].max\n end\n end\n local_solutions << new_value\n end\n end\n\n table\n end",
"def knapsack_table(weights, values, capacity)\n table = Array.new(weights.length) {Array.new(capacity + 1, 0)}\n \n table.each_index do |weight_idx|\n wt = weights[weight_idx]\n val = values[weight_idx]\n \n table[weight_idx].each_index do |curr_capacity|\n next if curr_capacity == 0\n \n if weight_idx == 0 #sets first row\n table[weight_idx][curr_capacity] = (curr_capacity >= wt ? val : 0)\n else \n cap_diff = (curr_capacity - wt >= 0 ? curr_capacity - wt : 0) #account for if capacity is smaller than weight\n calc_val = val + table[weight_idx - 1][cap_diff]\n prev_val = table[weight_idx - 1][curr_capacity]\n \n table[weight_idx][curr_capacity] = [calc_val, prev_val].max\n end\n end\n end\n \n p table\n end",
"def tabulate2 content, options\n widths = calculate_column_widths(content, 99)\n str = \"| \"\n sep = \"+\"\n widths.each do |w|\n str << \"%-#{w}s | \"\n sep << (\"-\"*(w+2)) + \"+\"\n end\n data = []\n data << sep \n content.each_with_index {|line, ix| \n data << str % line \n data << sep if ix == 0\n }\n data << sep\n require 'tempfile'\n tmpfile = Tempfile.new('SQL.XXXXXX')\n filename = tmpfile.path\n #filename = Shellwords.escape(filename)\n #puts \"Writing to #{filename}\"\n tmpfile.write(data.join(\"\\n\"))\n tmpfile.close # need to flush, otherwise write is buffered\n return filename\nend",
"def find_amicables(n)\n pairs = []\n sum = 0\n for i in 0..n do \n next if pairs.include? i\n d = sum_proper_divisors(i)\n next if d == i\n p = sum_proper_divisors(d)\n if p == i \n pairs << d\n pairs << i\n sum += d + i\n end\n end\n return sum\nend"
] |
[
"0.61604905",
"0.61149704",
"0.596614",
"0.5892388",
"0.58655864",
"0.58407664",
"0.5838778",
"0.5828102",
"0.5818131",
"0.57730997",
"0.5750076",
"0.5703398",
"0.5667486",
"0.5655089",
"0.56133693",
"0.5580554",
"0.5569902",
"0.55595005",
"0.55564255",
"0.55481046",
"0.55347925",
"0.55231595",
"0.54513764",
"0.5439821",
"0.5438322",
"0.54188037",
"0.54117775",
"0.53877044",
"0.53815925",
"0.5371274",
"0.5357842",
"0.5352687",
"0.5339285",
"0.5334132",
"0.53166205",
"0.53131616",
"0.53122526",
"0.5310648",
"0.5310128",
"0.5309714",
"0.53040075",
"0.53036773",
"0.5277395",
"0.5264852",
"0.5262968",
"0.5252405",
"0.5251989",
"0.5251546",
"0.5240609",
"0.523084",
"0.5221753",
"0.5216191",
"0.5204578",
"0.5202702",
"0.5191007",
"0.5190364",
"0.518329",
"0.51820594",
"0.5180591",
"0.51758",
"0.5173758",
"0.5163555",
"0.5149758",
"0.51433843",
"0.5139385",
"0.5139385",
"0.513882",
"0.5131776",
"0.51243925",
"0.51184565",
"0.5099463",
"0.5097262",
"0.5092897",
"0.50822693",
"0.5080011",
"0.50762326",
"0.50758576",
"0.5072257",
"0.5066305",
"0.50607437",
"0.50606287",
"0.5057151",
"0.5053214",
"0.5052615",
"0.50489837",
"0.5047989",
"0.50450116",
"0.50404686",
"0.5035883",
"0.5033711",
"0.50315344",
"0.50279635",
"0.5022162",
"0.50209415",
"0.5015053",
"0.50142765",
"0.5012177",
"0.50097305",
"0.5007061",
"0.50062025",
"0.4999968"
] |
0.0
|
-1
|
this part between def and end is called a method
|
def play_paper
@computer_move = ["rock","paper","scissors"].sample
if @computer_move == "paper"
@outcome = "tie"
elsif @computer_move == "scissors"
@outcome = "lose"
else
@outcome = "win"
end
render("games/play_paper.html.erb")
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def end; end",
"def end; end",
"def end; 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 end_point; end",
"def methods() end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def start; end",
"def end\n end",
"def end\n end",
"def end() end",
"def call() end",
"def _end!; end",
"def end\n end",
"def start;end",
"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 begin; end",
"def begin() end",
"def starting; end",
"def main_end ; end",
"def finished; end",
"def at_end; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def methods; end",
"def method\n\t\t# code code\n\tend",
"def end\n end",
"def method2() end",
"def end_point=(_arg0); end",
"def implementation; end",
"def implementation; end",
"def probers; end",
"def final; end",
"def started; end",
"def r; end",
"def r; end",
"def done; end",
"def finished=(_arg0); end",
"def ...\nend",
"def calls; end",
"def calls; end",
"def method\r\nend",
"def returns; end",
"def called_from; end",
"def called_from; end",
"def do()\r\n\tend",
"def run() end",
"def schubert; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def run; end",
"def invoke; end",
"def run(_); end",
"def run(_); end",
"def incomplete\r\n\r\n end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end",
"def finish; end"
] |
[
"0.7925137",
"0.7925137",
"0.7925137",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7761054",
"0.7673119",
"0.754368",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.75311446",
"0.7502537",
"0.7502537",
"0.7491666",
"0.73709327",
"0.7360083",
"0.7323251",
"0.73105353",
"0.72904897",
"0.72904897",
"0.72904897",
"0.72904897",
"0.72904897",
"0.72904897",
"0.72904897",
"0.72904897",
"0.7275798",
"0.72016776",
"0.7177998",
"0.7170285",
"0.7126918",
"0.71070826",
"0.7073447",
"0.7073447",
"0.7073447",
"0.7073447",
"0.7059241",
"0.7050738",
"0.70498794",
"0.704601",
"0.70405775",
"0.70405775",
"0.6999051",
"0.6963644",
"0.6959263",
"0.69396526",
"0.69396526",
"0.6931",
"0.6909169",
"0.6900489",
"0.6894826",
"0.6894826",
"0.6877035",
"0.68548214",
"0.68412566",
"0.68412566",
"0.68396825",
"0.68318",
"0.6750053",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.67483264",
"0.6746114",
"0.67320955",
"0.67320955",
"0.67207015",
"0.6720365",
"0.6720365",
"0.6720365",
"0.6720365",
"0.6720365",
"0.6720365",
"0.6720365",
"0.6720365"
] |
0.0
|
-1
|
Public: Build a list of 'file' objects (same as used when showing the loglist(s)) and return the items that are related to the current post (specified by the 'title' parameter). Params: title Title of article to compare with filelist to find current. pre Boolean indicating whether this is a finished or workinprogress (pre) log entry. Determines different filelist to process. Returns an array of hashes with a predetermined maximum length
|
def related_logs(title, pre=false)
logs = begin
if pre
with_cache('log-pre-file-list') {
log_list(LOG_PRE_META[:path], LOG_PRE_META[:regex], pre)
}
else
with_cache('log-file-list') {
log_list(LOG_META[:path], LOG_META[:regex])
}
end
end
related_files = []
curr_file = logs.select{|l| l[:name] == title}.first
logs.delete(curr_file)
top_logs = logs.select{|l| l[:date] > curr_file[:date]}.reverse
if curr_file
top_logs.each do |l|
related_files << l if related_files.count < 3 && title != l[:name]
end
else
related_files = logs.take(3)
end
if related_files.count < 3
related_files.concat(logs.take(3 - related_files.count)).uniq!
end
related_files.sort{|a,b| b[:date] <=> a[:date]}
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def file_by_title(title)\n if title.is_a?(Array)\n return self.root_collection.file_by_title(title)\n else\n return files(\"q\" => [\"title = ?\", title], \"maxResults\" => 1)[0]\n end\n end",
"def formatted_file_list(title, source_files); end",
"def list\n ret = get()\n return [] if ret.is_a? Hash and ret.has_key? :error\n ret.map{|i| FileItem.new(i)}\n end",
"def page_diffs(title)\n title = normalize_title(title)\n list = []\n \n store.commits(100).each do |commit|\n diffs = commit.diffs(\"#{title}.md\")\n list << [commit, diffs] unless diffs.empty?\n end\n\n list\n end",
"def posts\n # diffable_files = `git status --porcelain | awk '!match($1, \"D\"){print $2}' | grep .md`.split(\"\\n\")\n diffable_files = `git diff --name-only --diff-filter=ACMRTUXB origin/master... | grep .md`.split(\"\\n\")\n\n posts = diffable_files.select do |filename|\n File.ctime(filename) > Time.new(2014,9,3)\n end\n\n posts\n end",
"def fetch_files(program)\n program = init_fields(program)\n files = []\n\n SouvlakiRS.logger.info \" Trying to fetch: '#{program[:pub_title]}', use html? #{program[:use_html]}\"\n\n begin\n agent = init_agent\n files += if program[:use_html]\n from_html(agent, program)\n else\n rss, date, error = rss_shows_available(agent, program[:show_name_uri], program[:show_date])\n if rss.nil?\n program[:err_msg] = error if error\n return []\n end\n\n SouvlakiRS.logger.info \" date match (#{date})\"\n from_rss(agent, rss)\n end\n rescue StandardError => e\n SouvlakiRS.logger.error \" Fetch error: #{e}\"\n end\n\n # logout\n # logout(agent)\n # uri = \"#{@creds[:base_uri]}?op=logout&\"\n # agent.get(uri)\n\n files\n end",
"def formatted_file_list(title, source_files)\n title_id = title.gsub(/^[^a-zA-Z]+/, \"\").gsub(/[^a-zA-Z0-9\\-\\_]/, \"\")\n # Silence a warning by using the following variable to assign to itself:\n # \"warning: possibly useless use of a variable in void context\"\n # The variable is used by ERB via binding.\n title_id = title_id\n template(\"file_list\").result(binding)\n end",
"def list\n\t\tfiles.map! { |filename|\n\t\t\t{:title => file_to_pagename(filename), :link => filename.chomp(\".md\")}\n\t\t}\n\tend",
"def list\n\t\tfiles.map! { |filename|\n\t\t\t{:title => file_to_pagename(filename), :link => filename.chomp(\".md\")}\n\t\t}\n\tend",
"def formatted_file_list(title, result, source_files, options = {})\n title_id = title.gsub(/^[^a-zA-Z]+/, \"\").gsub(/[^a-zA-Z0-9\\-\\_]/, \"\")\n # Silence a warning by using the following variable to assign to itself:\n # \"warning: possibly useless use of a variable in void context\"\n # The variable is used by ERB via binding.\n title_id = title_id\n options = options\n\n template(\"file_list\").result(binding)\n end",
"def files\n array = []\n @list.each do |k,v|\n array += v.filename\n end\n array\n end",
"def posts\n return @posts if defined? @posts\n\n diffable_files = `git diff -z --name-only --diff-filter=ACRTUXB origin/master -- content/changes/`.split(\"\\0\")\n\n @posts = diffable_files.select do |filename|\n ext = File.extname(filename)\n ext == \".md\" || ext == \".html\"\n end\nend",
"def find_other_post (utilHash)\n fileList = []\n if (utilHash[\"technical\"])\n fileList += Dir[utilHash[\"blog_path\"] + \"t*.html\"]\n end\n if (utilHash[\"cultural\"])\n fileList += Dir[utilHash[\"blog_path\"] + \"c*.html\"]\n end\n return fileList\nend",
"def file_list\n @file_list\n end",
"def getLogsSingleFileByDate(path,start_file_name,from_date,asc_by_fname,persist_from_date)\n require 'date'\n logs_date = Date.new\n valid_items = nil\n if(from_date != nil)\n begin\n from_date = Date.parse(from_date)\n rescue Exception => ex\n puts \"[Logstat] : Incorrect 'from_date' parameter: #{from_date}\"\n return\n end\n end\n date_regex = /\\A((\\d{1,2}[-\\/]\\d{1,2}[-\\/]\\d{4})|(\\d{4}[-\\/]\\d{1,2}[-\\/]\\d{1,2}))/\n list_logs = Array.new\n check_log_start = false\n log_items = \"\"\n\n File.foreach(path+\"/\"+start_file_name) do |line|\n #check first line start with a date string\n if((line.strip != \"\") && (line =~ date_regex))\n str_date = line[date_regex,1]\n #check if date is validate\n begin\n logs_date = Date.parse(str_date)\n #if monitor type is date\n if(from_date != nil)\n #if monitor only 1 file or multi file with sort by ASC file name\n if(asc_by_fname == nil || asc_by_fname) \n if(from_date <= logs_date)\n check_log_start = true\n valid_items = true\n else\n if(valid_items)\n list_logs << log_items\n end\n valid_items = false\n end\n else\n #if monitor multi file with sort by DESC file name\n if(from_date >= logs_date)\n check_log_start = true\n valid_items = true\n else\n if(valid_items)\n list_logs << log_items\n end\n valid_items = false\n end\n end\n else\n check_log_start = true\n end\n persist_from_date[\"persist_from_date\"] = str_date\n rescue Exception => e\n check_log_start = false\n puts \"[Logstat] : #{e}\"\n end\n else\n check_log_start = false\n end\n #Add log_items to list_logs\n if(valid_items.nil?)\n if(check_log_start )\n if(log_items.strip != \"\")\n list_logs << log_items\n end\n #New logs items\n log_items = line\n else\n if(log_items.strip != \"\")\n log_items += line\n end\n end\n else\n #if a new logs start,and previous items is valid then add it to list log\n if(check_log_start && valid_items)\n if(log_items.strip != \"\")\n list_logs << log_items\n end\n #New logs items\n log_items = line\n else\n if(log_items.strip != \"\")\n log_items += line\n end\n end\n end\n end\n\n #Last items\n if(valid_items == true )\n list_logs << log_items\n end\n return list_logs\nend",
"def queue_files_for_processing( args )\n\t\t# only queue up files that can have id3 tags to begin with.\n\t\tfiles = clean_file_list( args )\n\n\t\t# add the files to the queue\n\t\tif( files.length == 0 )\n\t\t\tputs \"None of the files were MP3s!!\"\n\t\t\t#FIXME: should this be an exception?\n\t\telse\n\n\t\t\t# Set the track number limits\n\t\t\tcount \t\t\t\t= @renumber_start_at\n\t\t\t@total_tracks = files.length\n\n\t\t\tfiles.each { |x|\n\t\t\t\tputs \"checking #{x}...\"\n\n\t\t\t\t# list its current id3 tag contents.\n\t\t\t\tputs \"\\tid3v2 says this:\"\n\t\t\t\tputs \"\\t\\t#{ID3Tagger::list_file( x )}\"\n\n\t\t\t\t# tell the user what the program intends to change\n\t\t\t\tputs build_proposal_string( count ) + \"\\n\"\n\n\t\t\t\t# add the file to the queue\n\t\t\t\tadd( x, count )\n\t\t\t\tcount = count + 1\n\t\t\t}\n\n\t\t\t# keep files in order\n\t\t\t@files.rehash\n\t\tend\n\tend",
"def commits_on_pr_files(pr, months_back)\n\n oldest = Time.at(Time.at(pr[:created_at]).to_i - 3600 * 24 * 30 * months_back)\n commits = commit_entries(pr, at_open = true)\n\n commits_per_file = commits.flat_map { |c|\n unless c[:files].nil?\n JSON.parse(c[:files]).map { |f|\n [c[:sha], f[\"filename\"]]\n }\n else\n []\n end\n }.select{|x| x.size > 1}.group_by {|c|\n c[1]\n }\n\n commits_per_file.keys.reduce({}) do |acc, filename|\n commits_in_pr = commits_per_file[filename].map{|x| x[0]} # get the shas of pr related commits\n\n walker = Rugged::Walker.new(git)\n walker.sorting(Rugged::SORT_DATE)\n walker.push(pr[:base_commit])\n\n commit_list = walker.select do |c|\n c.time > oldest\n end.reduce([]) do |acc1, c|\n if c.diff(paths: [filename.to_s]).size > 0 and\n not commits_in_pr.include? c.oid # (oid is the object id - c.oid gets the commit sha). this commit is not part of pr's commits\n acc1 << c.oid\n end\n acc1\n end\n acc.merge({filename => commit_list})\n end\n end",
"def file_list\n end",
"def files\n list = []\n if @data['info'].key?('files')\n @data['info']['files'].each do |file|\n list << { 'name' => file['path'], 'length' => file['length'] }\n end\n return list\n end\n\n if @data['info'].key?('name') && @data['info'].key?('length')\n list << { 'name' => @data['info']['name'], 'length' => @data['info']['length'] }\n end\n list\n end",
"def create_list_of_files\n @path=find_repository_and_basepath\n @table.window.setTitle(@path)\n files=[]\n Find.find(@path) do |file|\n # we don't want any files from a repository in the list \n next if file=~/(\\.hg|\\.svn|\\.git|\\.pyc)/ \n\n # neither do we want dotfiles in the list\n next if File.basename(file)=~/^\\./ \n \n # file matches, add it to the resulting list\n files << file if FileTest.file?(file)\n\n # wir bauen hier mal einen kleinen Idiotentest ein. Wenn wir mehr\n # als 10000 Dateien gefunden haben dann sind wir vermtl. in einem \n # falschen Verzeichniss und brechen die Suche ab.\n if files.length>10000\n NSRunInformationalAlertPanel('Large directory found!',\n \"Gathered more than 10k files from directory '#{@path}', aborting search!\",'OK',nil,nil)\n NSApp.stop(self)\n raise 'error'\n end\n end\n #@files=files.sort_by { |match| File.basename(match) }\n @files=files.sort\n end",
"def files\n page = get_page\n offset = PER_PAGE * page\n get_run_logs(:limit => PER_PAGE, :offset => offset)\n end",
"def get_post_by_title(oauth_token, title, ref)\n result = nil\n result = get_all_posts_in_pr_for_user(oauth_token).find { |x| x.title == title } if ref\n result = get_all_posts(oauth_token).find { |x| x.title == title } if !ref\n result.images.each { |x| PostImageManager.instance.add_downloaded_image(x) } if result\n result\n end",
"def recents\n files = session[:user].x_files.all(:last_update.gte => (DateTime.now - 20.days), folder: false, limit: 20)\n files_list = []\n files.each do |file|\n files_list.push(file.description(session[:user])) if file.folder || (!file.folder && file.uploaded)\n end\n @result = { files: files_list, success: true }\n end",
"def children\n c = file_log.children(file_node)\n c.map do |x|\n VersionedFile.new(@repo, @path, :file_id => x, :file_log => file_log)\n end \n end",
"def list_files\n @synth_files = CreatedFile.find_all_by_content_type(\"synthesis\",\n :include => :researcher, \n :order => \"created_at DESC, created_file DESC\")\n end",
"def commits_on_pr_files(pr, months_back)\n\n oldest = Time.at(Time.at(pr[:created_at]).to_i - 3600 * 24 * 30 * months_back)\n pr_against = pull_req_entry(pr[:id])['base']['sha']\n commits = commit_entries(pr[:id])\n\n commits_per_file = commits.flat_map { |c|\n c['files'].map { |f|\n [c['sha'], f['filename']]\n }\n }.group_by {|c|\n c[1]\n }\n\n commits_per_file.keys.reduce({}) do |acc, filename|\n commits_in_pr = commits_per_file[filename].map{|x| x[0]}\n\n walker = Rugged::Walker.new(repo)\n walker.sorting(Rugged::SORT_DATE)\n walker.push(pr_against)\n\n commit_list = walker.take_while do |c|\n c.time > oldest\n end.reduce([]) do |acc1, c|\n if c.diff(paths: [filename.to_s]).size > 0 and\n not commits_in_pr.include? c.oid\n acc1 << c.oid\n end\n acc1\n end\n acc.merge({filename => commit_list})\n end\n end",
"def static_content_work_file_set_find_by_title( work:, work_title:, file_set_title:, path: )\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"work_title=#{work_title}\",\n \"file_set_title=#{file_set_title}\",\n \"path=#{path}\",\n \"\" ] if static_content_controller_behavior_verbose\n return nil unless work\n return nil unless file_set_title\n if work_view_content_enable_cache\n id = StaticContentControllerBehavior.static_content_cache_get( key: path )\n return static_content_find_by_id( id: id ) if id.present?\n end\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"work.id=#{work.id}\",\n \"work.title=#{work.title}\",\n \"work.file_set_ids=#{work.file_set_ids}\",\n \"work.file_sets.size=#{work.file_sets.size}\",\n \"\" ] if static_content_controller_behavior_verbose\n work.file_sets.each do |fs|\n # TODO: verify\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"fs.title.join(#{fs.title.join}) ==? file_set_title(#{file_set_title})\",\n # \"file_set_title=#{file_set_title}\",\n \"\" ] if static_content_controller_behavior_verbose\n if fs.title.join == file_set_title\n id = fs.id\n if work_view_content_enable_cache\n StaticContentControllerBehavior.static_content_cache_id( key: path, id: id )\n end\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"fs.title.join(#{fs.title.join}) ==? file_set_title(#{file_set_title})\",\n \">>> Found <<<\",\n \"\" ] if static_content_controller_behavior_verbose\n return fs\n end\n end\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"file_set_title=#{file_set_title})\",\n \">>> Not found <<<\",\n \"\" ] if static_content_controller_behavior_verbose\n return nil\n end",
"def filelist\n @filelist ||= begin\n list = common_filelist(super) # Always pick up the parent list\n list\n end\n end",
"def getLogsByDate(path,start_file_name,from_date,asc_by_fname)\n require 'date'\n persist_from_date = Hash.new\n persist_start_file_name = start_file_name\n list_logs = Array.new\n if(asc_by_fname == nil)\n #Get logs from single file\n if(start_file_name == nil)\n puts \"[Logstat] : 'start_file_name' parameter must be required !\"\n return\n end\n list_logs = getLogsSingleFileByDate(path,start_file_name,from_date,asc_by_fname,persist_from_date)\n else\n #Get logs from multi files\n sorted_by_modified = Dir.entries(path).sort_by {|f| File.mtime(File.join(path,f))} .reject{|entry| entry == \".\" || entry == \"..\" || File.directory?(File.join(path,entry))}\n if(asc_by_fname)\n #File sorted ASC\n if(start_file_name == nil )\n start_file_name = sorted_by_modified.first\n end\n Dir.entries(path).sort.each do |log_file|\n\n if File.file?(File.join(path,log_file))\n if((start_file_name <=> log_file) <= 0)\n list_logs.concat(getLogsSingleFileByDate(path,log_file,from_date,asc_by_fname,persist_from_date))\n persist_start_file_name = log_file\n end\n end\n end\n else\n #File sorted DESC\n if(start_file_name == nil )\n start_file_name = sorted_by_modified.last\n end\n Dir.entries(path).sort.reverse.each do |log_file|\n if File.file?(File.join(path,log_file))\n if((start_file_name <=> log_file) >= 0)\n list_logs.concat(getLogsSingleFileByDate(path,log_file,from_date,asc_by_fname,persist_from_date))\n persist_start_file_name = log_file\n end\n end\n end\n end\n end\n finalData = Hash.new\n finalData[\"list_logs\"] = list_logs\n #Persistent data for next monitoring\n persist_data = Hash.new\n persist_data[\"start_file_name\"] = persist_start_file_name\n persist_data[\"from_date\"] = persist_from_date[\"persist_from_date\"]\n finalData[\"persistent_data\"] = persist_data\n return finalData\nend",
"def parse\n records = []\n files.each do |fname|\n records += parse_file(fname)\n end\n\n @notes = records.sort\n end",
"def files\n cached = FileAttachment.list_cache\n files = cached.select{|f|f.post_id == id}\n end",
"def file_list(hash)\n\nend",
"def file_list(hash)\n\nend",
"def files\n entries.map(&:filepath)\n end",
"def main()\n res = @s.execute_get(@s.url_for(\"var/search/needsprocessing.json\"))\n unless res.code == '200'\n raise \"Failed to retrieve list to process [#{res.code}]\"\n end\n\n process_results = JSON.parse(res.body)['results']\n log \"processing #{process_results.size} entries\"\n unless process_results.size > 0\n return\n end\n\n # Create some temporary directories.\n Dir.mkdir DOCS_DIR unless File.directory? DOCS_DIR\n Dir.mkdir PREV_DIR unless File.directory? PREV_DIR\n Dir.mkdir PDFS_DIR unless File.directory? PDFS_DIR\n\n # Create a temporary file in the DOCS_DIR for all the pending files and outputs all the filenames in the terminal.\n Dir.chdir DOCS_DIR\n queued_files = process_results.collect do |result|\n FileUtils.touch result['_path']\n end\n\n log \" \"\n log \"Starts a new batch of queued files: #{queued_files.join(', ')}\"\n\n Dir['*'].each do |id|\n FileUtils.rm_f id\n log \"processing #{id}\"\n\n begin\n meta_file = @s.execute_get @s.url_for(\"p/#{id}.json\")\n unless meta_file.code == '200'\n raise \"Failed to process: #{id}\"\n end\n\n meta = JSON.parse meta_file.body\n mime_type = meta['_mimeType']\n given_extension = meta[\"sakai:fileextension\"]\n extension = determine_file_extension_with_mime_type(mime_type, given_extension)\n filename = id + extension\n log \"with filename: #{filename}\"\n\n if ignore_processing?(mime_type) || extension.eql?('')\n if extension.eql?('')\n log \"ignoring processing of #{filename}, no preview can be generated for files without a known mime type\"\n log \"The file's original extension was #{given_extension}, and it's mime type is #{mime_type}\"\n else\n log \"ignoring processing of #{filename}, no preview can be generated for #{mime_type} files\"\n end\n else\n # Making a local copy of the file.\n content_file = @s.execute_get @s.url_for(\"p/#{id}\")\n unless ['200', '204'].include? content_file.code\n raise \"Failed to process file: #{id}, status: #{content_file.code}\"\n end\n File.open(filename, 'wb') { |f| f.write content_file.body }\n\n if process_as_image? extension\n extension = output_extension extension\n page_count = 1\n filename_thumb = 'thumb' + extension\n\n content = resize_and_write_file filename, filename_thumb, 900\n post_file_to_server id, content, :normal, page_count, extension\n\n content = resize_and_write_file filename, filename_thumb, 180, 225\n post_file_to_server id, content, :small, page_count, extension\n\n FileUtils.rm_f DOCS_DIR + \"/#{filename_thumb}\"\n else\n begin\n # Check if user wants autotagging\n user_id = meta[\"sakai:pool-content-created-for\"]\n user_file = @s.execute_get @s.url_for(\"/system/me?uid=#{user_id}\")\n unless user_file.code == '200'\n raise \"Failed to get user: #{uid}\"\n end\n user = JSON.parse(user_file.body)\n if user[\"user\"][\"properties\"][\"isAutoTagging\"] != \"false\"\n # Get text from the document\n Docsplit.extract_text filename, :ocr => false\n text_content = IO.read(id + \".txt\")\n terms = extract_terms(text_content)\n tags = \"\"\n terms.each_with_index do |t, i|\n tags += \"- #{t}\\n\"\n terms[i] = \"/tags/#{t}\"\n end\n # Generate tags for document\n @s.execute_post @s.url_for(\"p/#{id}\"), {':operation' => 'tag', 'key' => terms}\n log \"Generate tags for #{id}, #{terms}\"\n admin_id = \"admin\"\n origin_file_name = meta[\"sakai:pooled-content-file-name\"]\n if not terms.nil? and terms.length > 0 and user[\"user\"][\"properties\"][\"sendTagMsg\"] and user[\"user\"][\"properties\"][\"sendTagMsg\"] != \"false\"\n msg_body = \"We have automatically added the following tags for #{origin_file_name}:\\n\\n #{tags}\\n\\nThese tags were created to aid in the discoverability of your content.\\n\\nRegards, \\nThe Sakai Team\"\n @s.execute_post(@s.url_for(\"~#{admin_id}/message.create.html\"), {\n \"sakai:type\" => \"internal\",\n \"sakai:sendstate\" => \"pending\",\n \"sakai:messagebox\" => \"outbox\",\n \"sakai:to\" => \"internal:#{user_id}\",\n \"sakai:from\" => \"#{admin_id}\",\n \"sakai:subject\" => \"We've added some tags to #{origin_file_name}\",\n \"sakai:body\" => msg_body,\n \"_charset_\" => \"utf-8\",\n \"sakai:category\" => \"message\"\n })\n log \"sending message from #{admin_id} user to #{user_id}\"\n end\n end\n rescue Exception => msg\n log \"failed to generate document tags: #{msg}\", :warn\n end\n\n # Generating image previews of the document.\n if only_first_page? extension\n Docsplit.extract_images filename, :size => '1000x', :format => :jpg, :pages => 1\n else\n Docsplit.extract_images filename, :size => '1000x', :format => :jpg\n end\n\n # Skip documents with a page count of 0, just to be sure.\n next if Dir[id + '_*'].size == 0\n\n Dir.mkdir PREV_DIR + \"/#{id}\" unless File.directory? PREV_DIR + \"/#{id}\"\n\n # Moving these previews to another directory: \"PREVS_DIR/filename/index.jpg\".\n Dir[id + '_*'].each_with_index do |preview, index|\n FileUtils.mv \"#{id}_#{index + 1}.jpg\", \"#{PREV_DIR}/#{id}/#{index}.jpg\"\n end\n\n Dir.chdir PREV_DIR + \"/#{id}\"\n page_count = Dir[\"*\"].size\n\n # Upload each preview and create+upload a thumbnail.\n for index in (0..page_count - 1)\n filename_p = \"#{index}.jpg\"\n # Upload the generated preview of this page.\n nbytes, content = File.size(filename_p), nil\n File.open(filename_p, \"rb\") { |f| content = f.read nbytes }\n post_file_to_server id, content, :large, index + 1\n\n # Generate 2 thumbnails and upload them to the server.\n filename_thumb = File.basename(filename_p, '.*') + '.normal.jpg'\n content = resize_and_write_file filename_p, filename_thumb, 700\n post_file_to_server id, content, :normal, index + 1\n\n filename_thumb = File.basename(filename_p, '.*') + '.small.jpg'\n content = resize_and_write_file filename_p, filename_thumb, 180, 225\n post_file_to_server id, content, :small, index + 1\n end\n\n FileUtils.remove_dir PREV_DIR + \"/#{id}\"\n end\n # Pass on the page_count\n @s.execute_post @s.url_for(\"p/#{id}\"), {\"sakai:pagecount\" => page_count, \"sakai:hasPreview\" => \"true\"}\n\n # Change to the documents directory otherwise we won't find the next file.\n Dir.chdir DOCS_DIR\n end\n\n #SAKAI TO PDF\n # We check if mimetype is sakaidoc\n if(mime_type == \"x-sakai/document\")\n if (File.exist?(\"../wkhtmltopdf\"))\n # Go to PDF Dir\n Dir.chdir PDFS_DIR\n\n #delay in secs\n $delay = \"20\"\n\n #filename with extension\n filename_p = id + \".pdf\"\n\n # We parse the structure data to var structure (we do not need the rest)\n structure = JSON.parse meta['structure0']\n\n # Create var and add beginning of code line to run\n line = \"../wkhtmltopdf \"\n\n # Go through structure and add the pagelink for each page id\n structure.each do |page|\n link = \"content#l=\" + page[0] + \"&p=\" + id\n link = @s.url_for(link)\n link = \"'\" + link + \"' \"\n line += link\n end\n\n # Fetch cookie value to get access to all content\n # USERNAME PASSWORD SERVER\n $username = \"admin\"\n auth = \"../auth.sh \" + $username + \" \" + $pw + \" \" + $preview_referer\n cookietoken = `#{auth}`\n\n # Append end of line containing arguments for print css, delay and authentication\n line += filename_p + \" --print-media-type --redirect-delay \" + $delay + \"000 --cookie 'sakai-trusted-authn' \" + cookietoken\n\n # Run the command line (run wkhtmltopdf)\n `#{line}`\n\n # We read the content from the pdf in the PDF directory\n content = open(filename_p, 'rb') { |f| f.read }\n\n # We post it to server through this function\n post_pdf_to_server id, content\n @s.execute_post @s.url_for(\"p/#{id}\"), {\"sakai:processing_failed\" => \"false\"}\n #Change dir\n Dir.chdir DOCS_DIR\n else\n @s.execute_post @s.url_for(\"p/#{id}\"), {\"sakai:processing_failed\" => \"true\"}\n log \"PDF Converter (wkhtmltopdf) not present in directory\"\n log \"Cannot convert Sakai document to PDF\"\n log \"Continuing without conversion\"\n end\n end\n rescue Exception => msg\n # Output a timestamp + the error message whenever an exception is raised\n # and flag this file as failed for processing.\n log \"error generating preview/thumbnail (ID: #{id}): #{msg.inspect}\\n#{msg.backtrace.join(\"\\n\")}\", :warn\n @s.execute_post @s.url_for(\"p/#{id}\"), {\"sakai:processing_failed\" => \"true\"}\n ensure\n # No matter what we flag the file as processed and delete the temp copied file.\n @s.execute_post @s.url_for(\"p/#{id}\"), {\"sakai:needsprocessing\" => \"false\"}\n FileUtils.rm_f DOCS_DIR + \"/#{filename}\"\n end\n end\n\n FileUtils.remove_dir PDFS_DIR\n FileUtils.remove_dir PREV_DIR\n FileUtils.remove_dir DOCS_DIR\nend",
"def list\n BakFile.where('saved = ?', true).each do |file|\n Log.instance.info(\"#{file.fid},#{file.dkey},#{file.length},#{file.classname}\")\n break if SignalHandler.instance.should_quit\n end\n end",
"def build_posts_index\n @posts_index = []\n @posts ||= Dir.glob (Pathname.pwd.join(\"posts\", \"*.md\"))\n @posts.each do |p|\n post = Kobayashi::Post.parse_post(p.to_s)\n index_of_post = {:date => post.time, :title => post.title, :url => post.url,\n :file => p,\n :tags => post.tags.map { |t| t.parameterize }\n }\n @posts_index << index_of_post\n end\n # reverse sort the array of Hashes by Date\n @posts_index = @posts_index.sort_by { |ti| ti[:date] }.reverse\n @posts_index\n end",
"def file_listing(commit)\n # The only reason this doesn't work 100% of the time is because grit doesn't :/\n # if i find a fix, it'll go upstream :D\n count = 0\n out = commit.diffs.map do |diff|\n count = count + 1\n if diff.deleted_file\n %(<li class='file_rm'><a href='#file_#{count}'>#{diff.a_path}</a></li>)\n else\n cla = diff.new_file ? \"add\" : \"diff\"\n %(<li class='file_#{cla}'><a href='#file_#{count}'>#{diff.a_path}</a></li>)\n end\n end\n \"<ul id='files'>#{out.join}</ul>\"\n end",
"def build_file_list\n puts_and_logs 'Finding files...'\n file_list = []\n config[:source].each do |entry|\n if File.directory?(entry)\n populate_list_of_files_from_directory(file_list, entry) \n next\n end\n if File.file?(entry)\n populate_list_of_files_from_file(file_list, entry) \n next\n end\n logger.warn \"\\\"#{entry}\\\" is neither a directory nor a regular file. Ignored...\"\n end\n logger.debug(file_list)\n file_list\n end",
"def list\n @file_list.to_a\n end",
"def get_all_posts(oauth_token)\n result = []\n client = Octokit::Client.new(access_token: oauth_token)\n posts = client.contents(full_repo_name, path: '_posts')\n posts.each do |post|\n oldest_commit = get_oldest_commit_for_file(client, post.path)\n username = client.user[:login]\n if username == oldest_commit[:author][:login]\n post_api_response = client.contents(full_repo_name, path: post.path)\n\n post_model = create_post_from_api_response(post_api_response, nil)\n image_paths = KramdownService.get_all_image_paths(post_model.contents)\n\n images = []\n image_paths.each do | image_path |\n image_content = client.contents(full_repo_name, path: image_path)\n images << create_post_image(image_path, image_content.content)\n end\n\n post_model.images = images\n \n result << post_model\n end\n end\n result\n end",
"def title_issues(title)\n issues_array = self.issues.select do |issue|\n issue.comic.title == title\n end\n issues_array.sort\n end",
"def get_files(params)\n if params[:sort] == 'name' then\n sort = \"upload_file_name ASC\"\n else\n sort = \"created_on DESC\"\n end\n\n # Set currently viewing by key\n if params[:key] then\n @viewing_by = params[:key]\n @title << \" - #{@viewing_by.pluralize}\" \n @files = UserUpload.paginate(\n :order => sort,\n :page => params[:page],\n :conditions => [\"#{UserUpload.connection.quote_column_name(\"type\")} = ?\", @viewing_by], # and thumbnail is NULL\n :per_page => 30\n )\n else\n @files = UserUpload.paginate(\n :order => sort,\n :page => params[:page],\n # :conditions => \"#{connection.quote_column_name(\"thumbnail\")} is NULL\",\n :per_page => 30\n )\n end\n end",
"def read_posts\n self.posts = []\n posts_dir = File.join(source_path, \"posts\")\n entries = Dir.entries(posts_dir).reject{|f| File.directory?(f)}\n entries.each do |name|\n self.posts << Post.create(posts_dir, name)\n end\n posts.sort! \n end",
"def entries(path=nil, identifier=nil)\r\n logger.debug \"<cvs> entries '#{path}' with identifier '#{identifier}'\"\r\n path_with_project=\"#{url}#{with_leading_slash(path)}\"\r\n entries = Entries.new\r\n cmd = \"#{CVS_BIN} -d #{root_url} rls -e\"\r\n cmd << \" -D \\\"#{time_to_cvstime(identifier)}\\\"\" if identifier\r\n cmd << \" #{shell_quote path_with_project}\"\r\n shellout(cmd) do |io|\r\n io.each_line(){|line|\r\n fields=line.chop.split('/',-1)\r\n logger.debug(\">>InspectLine #{fields.inspect}\")\r\n \r\n if fields[0]!=\"D\"\r\n entries << Entry.new({:name => fields[-5],\r\n #:path => fields[-4].include?(path)?fields[-4]:(path + \"/\"+ fields[-4]),\r\n :path => \"#{path}/#{fields[-5]}\",\r\n :kind => 'file',\r\n :size => nil,\r\n :lastrev => Revision.new({\r\n :revision => fields[-4],\r\n :name => fields[-4],\r\n :time => Time.parse(fields[-3]),\r\n :author => ''\r\n })\r\n })\r\n else\r\n entries << Entry.new({:name => fields[1],\r\n :path => \"#{path}/#{fields[1]}\",\r\n :kind => 'dir',\r\n :size => nil,\r\n :lastrev => nil\r\n })\r\n end\r\n }\r\n end\r\n return nil if $? && $?.exitstatus != 0\r\n entries.sort_by_name\r\n end",
"def process_all_primary_files\n # NOTE: I investigated concurrent processing of files\n # to speed up this process, however I didn't pursue it\n # further: This process is highly CPU intensive, so the\n # only way to get a significant speedup is to use\n # multiple CPUs/Cores. In MRI this is only possible\n # with multiple processes. I didn't want to go through\n # the trouble of IPC to collect all files' operations.\n # It would be easier if we could use threads, however\n # that would require jruby or rbx. So I'm sticking with\n # sequential processing for now.\n Dir.glob(\n File.join(@repository.base_dir, '**/content/**/*.at')\n ).map { |absolute_file_path|\n next nil if !@file_list.any? { |e| absolute_file_path.index(e) }\n # Skip non content_at files\n unless absolute_file_path =~ /\\/content\\/.+\\d{4}\\.at\\z/\n raise \"shouldn't get here\"\n end\n\n # Note: @any_content_type may be the wrong one, however finding\n # corresponding STM CSV file will still work as it doesn't rely\n # on config but das regex replacements on file path only.\n content_at_file_to = Repositext::RFile::ContentAt.new(\n File.read(absolute_file_path),\n @language,\n absolute_file_path,\n @any_content_type\n )\n\n @logger.info(\" - process #{ content_at_file_to.repo_relative_path(true) }\")\n\n soff = SubtitleOperationsForFile.new(\n content_at_file_to,\n @repository.base_dir,\n {\n from_git_commit: @from_git_commit,\n to_git_commit: @to_git_commit,\n prev_last_operation_id: @prev_last_operation_id,\n execution_context: @execution_context,\n }\n ).compute\n\n if soff.operations.any?\n @prev_last_operation_id = soff.last_operation_id\n soff\n else\n # Return nil if no subtitle operations exist for this file\n nil\n end\n }.compact\n end",
"def create_page_filename_list\n\n missing, expected = [], []\n\n unless @has_mets\n\n # Without METS, there's no way to find out which files should be present, so we won't be able to figure out if something is missing.\n # We also lack knowing what order they should be in. Ah well...\n\n @datafiles.sort!\n @datafiles = @datafiles.sort_by { |x| x[/\\d+/].to_i } # sort by number\n expected += @datafiles.select { |name| name =~ /\\.tiff$|\\.tif$|\\.jp2$|\\.jp2k$|\\.jpg$|\\.jpeg$/i }\n\n else\n\n # This checks the filenames in the list @datafiles (what's in the\n # package directory, less the metadata files) against the\n # filenames declared in the METS file table of contents (a\n # structmap). While datafiles is a simple list of filenames, the\n # table of contents provies a Struct::Page with slots :title,\n # :level, :image_filename, :image_mimetype, and :valid_repeat.\n # A :valid_repeat file is ignored.\n\n @table_of_contents.pages.each do |entry|\n next if entry.valid_repeat\n expected.push entry.image_filename\n missing.push entry.image_filename if @datafiles.grep(entry.image_filename).empty?\n end\n end\n\n unexpected = @datafiles - expected\n unexpected.delete_if { |x| x =~ /^Thumbs.db$/i } # common cruft\n\n unless unexpected.empty?\n warning \"The #{pretty_class_name} #{@directory_name} has the following #{unexpected.count} unexpected #{ unexpected.length == 1 ? 'file' : 'files'} that will not be processed:\"\n warning unexpected.map { |name| \" - #{name}\" }.sort\n end\n\n ## TODO: bug here reporting an error, 'name' somehow gets nil, see FSU's package FSU_Flambeau_04301979 started 2017-08-09 14:41:39\n\n unless missing.empty?\n error \"The #{pretty_class_name} #{@directory_name} is missing the following #{missing.count} required #{ missing.length == 1 ? 'file' : 'files'} declared in the mets.xml file:\"\n error missing.map { |name| \" - #{name}\" }.sort\n return false\n end\n\n @page_filenames = expected - missing\n end",
"def filename(title, now)\n File.join('_posts', format('%d-%02d-%02d-%s.md', now.year, now.month, now.day, file_title(title)))\nend",
"def by_file\n @by_file ||= notes.group_by(&:file)\n end",
"def retrieve_posts(dir); end",
"def list_all_files()\n\t\tfiles = Hash.new\n\t\trefresh_access_token()\n\t\trequest_url = \"https://www.googleapis.com/drive/v2/files?access_token=#{@access_token}\"\n\t\tresponse = RestClient.get request_url\n\t\tresponse_body = JSON.parse(response.body)\n\t\tresponse_body['items'].each do |item|\n\t\t\t\tfiles[item['id']] = item['title']\n\t\tend\n\t\treturn files\n\tend",
"def files\n entries.map{ |f| FileObject[path, f] }\n end",
"def file_list(nginx_log_path)\n list=[]\n list.push(nginx_log_path)\n file_1hour_ago=\"#{nginx_log_path}.#{(Time.now-3600).strftime(\"%Y%m%d%H\").to_s}\"\n list.push(file_1hour_ago) if File.exist?(file_1hour_ago)\n list\n end",
"def populate_list_of_files_from_file(file_list, entry)\n logger.debug \"\\\"#{entry}\\\" is a file. Processing...\"\n file_list << entry\n # Find images if any\n Find.find(File.dirname(entry)) do |file|\n file_list << file if (File.file?(file) && is_image?(file))\n end\n end",
"def get_content(folder = nil, sort = nil)\n abs_path = folder ? ROOT + folder : ROOT\n \n # build array if pairs: [filename, :type, is_textfile]\n sorter = case sort\n when 'name' then '| sort -f'\n when 'ctime' then '-c'\n when 'mtime' then '--sort=time'\n when 'size' then '--sort=size'\n else ''\n end\n\n list_files(abs_path, sorter).map do |obj|\n file_path = abs_path + obj\n [obj,\n if file_path.file?; :file\n elsif file_path.directory?; :dir\n elsif file_path.symlink?; :link\n end,\n \n !!`file \"#{file_path.to_s.shellescape}\"`.force_encoding(Encoding::UTF_8).sub(file_path.to_s, '').index(/text/i)\n ]\n end\n end",
"def get_file_events(gf_pid, obj_identifier)\n query = \"select intellectual_object_id, institution_id, \" +\n \"identifier, event_type, date_time, detail, \" +\n \"outcome, outcome_detail, outcome_information, \" +\n \"object, agent, generic_file_id, generic_file_identifier \" +\n \"from premis_events_solr where generic_file_id = ?\"\n if @file_events_query.nil?\n @file_events_query = @db.prepare(query)\n end\n result_set = @file_events_query.execute(gf_pid)\n events = []\n result_set.each_hash do |row|\n events.push(get_event(row, obj_identifier))\n end\n events\n end",
"def files\n # fetch the appropriate files\n filenames = Dir.glob(@path + \"/*.mp3\")\n filenames.map { |filename| @files << File.basename(filename) }\n @files\n end",
"def all_files_with_access\n return [] unless id.present?\n member_file_set_title_ids.sort { |x,y| x[0].upcase <=> y[0].upcase }\n end",
"def recent_files\n # print -rl -- **/*(Dom[1,10])\n @title = 'Recent files'\n # zsh D DOT_GLOB, show dot files\n # zsh om order on modification time\n @files = `zsh -c 'print -rl -- **/*(Dom[1,15])'`.split(\"\\n\").reject { |f| f[0] == '.' }\nend",
"def list_files(env, res, tag, path)\n files = []\n git(\"ls-tree\", \"-z\", \"#{tag}:#{path}\") do |io|\n io.each_line(\"\\0\") do |line|\n line.chomp!(\"\\0\")\n #STDERR.puts line\n info, file = line.split(/\\t/, 2)\n mode, type, object = info.split(/ /)\n files << {\n :mode => mode,\n :type => type,\n :object => object,\n :file => file,\n }\n end\n end\n files = files.sort_by{|h| h[:file] }\n E_list_files.result(binding)\n end",
"def create_filename(newpost)\n File.readlines(newpost).each do |line|\n tidytitle = ''\n # Extract title from the h2 line, and create tidytitle and filename\n if line =~ />\\w.*h2/\n # $& returns exact match, not entire line. Strip the tags surroundging the title.\n @title = $&.sub('>','').sub('</a></h2','') \n # Remove illegaal characters from title\n tidytitle = @title.downcase.gsub(/(#|%|&|\\*|<|>|\\{|\\}|\\\\|:|;|,|<|>|\\?|\\/|\\+|'|!|\\.)/,'').gsub(/ /,'-').gsub(/-+/,'-') + '.html'\n # Create filename preceded with datestamp\n @filename = @filedate + '-' + tidytitle\n break\n end\n end\nend",
"def books\n result = []\n if @filename2books\n @filename2books.each do |_filename,books|\n next if books.empty?\n\n books.each do |wr_book|\n result << wr_book.__getobj__ if wr_book.weakref_alive?\n end\n end\n end\n result\n end",
"def documents_for(path, site_path = '')\n ethon = ethon_easy_json_requester\n ethon.url = \"#{computed_web_api_url(site_path)}GetFolderByServerRelativeUrl('#{uri_escape path}')/Files\"\n ethon.perform\n check_and_raise_failure(ethon)\n\n threads = []\n rv = []\n result = JSON.parse( ethon.response_body )\n result['d']['results'].each do |file|\n file_struct = OpenStruct.new(\n title: file['Title'],\n path: file['ServerRelativeUrl'],\n name: file['Name'],\n url: \"#{base_url}#{file['ServerRelativeUrl']}\",\n created_at: Time.parse(file['TimeCreated']),\n updated_at: Time.parse(file['TimeLastModified']),\n record_type: nil,\n date_of_issue: nil,\n )\n\n threads << Thread.new {\n ethon2 = ethon_easy_json_requester\n server_relative_url = \"#{site_path}#{path}/#{file['Name']}\"\n ethon2.url = \"#{computed_web_api_url(site_path)}GetFileByServerRelativeUrl('#{uri_escape server_relative_url}')/ListItemAllFields\"\n ethon2.perform\n rs = JSON.parse(ethon2.response_body)['d']\n file_struct.record_type = rs['Record_Type']\n file_struct.date_of_issue = rs['Date_of_issue']\n\n rv << file_struct\n }\n end\n threads.each { |t| t.join }\n rv\n end",
"def doc_list(item, key, title)\n\t\tif (@config[:docs] == nil)\n\t\t\treturn\n\t\tend\n\n\t\tif (item[:docs_key] != key)\n\t\t\treturn\n\t\tend\n\n\t\tdoc_list_all(item, key, title)\n\tend",
"def get_all_posts_in_pr_for_user(oauth_token)\n result = []\n client = Octokit::Client.new(access_token: oauth_token)\n pull_requests_for_user = get_open_post_editor_pull_requests(oauth_token)\n \n pull_requests_for_user.each do | pull_request |\n pull_request_files = client.pull_request_files(full_repo_name, pull_request[:number])\n\n post = nil\n images = []\n pull_request_files.each do | pull_request_file |\n contents_url_params = CGI.parse(pull_request_file[:contents_url])\n\n # The CGI.parse method returns a hash with the key being the URL and the value being an array of\n # URI parameters so in order to get the ref we need to grab the first value in the hash and the first\n # URI parameter in the first hash value\n ref = contents_url_params.values.first.first\n file_contents = client.contents(full_repo_name, path: pull_request_file[:filename], ref: ref)\n\n if pull_request_file[:filename].ends_with?('.md')\n post = create_post_from_api_response(file_contents, ref)\n result << post\n else\n images << create_post_image(pull_request_file[:filename], file_contents.content)\n end\n end\n\n post.images = images\n end\n result\n end",
"def list_books_w_matching_title(title)\n books = @mybooks.get_books_by_title(title)\n\tbooks.each {|book| puts \"#{book[:key]} | #{book[:author]}, #{book[:title]}\"}\nend",
"def list_buffers\n arr = []\n @_buffers_conf.each_with_index do |e, i|\n t = e[:title] || \"no title for #{i}\"\n #$log.debug \" TITLE is #{e.title} , t is #{t} \"\n arr << t\n end\n ix = popuplist arr\n buffer_at ix\n end",
"def create_lists\n pid_files_dir = Rails.root.join('tmp', 'external_files_conversion', timestamp)\n FileUtils.mkdir_p pid_files_dir\n file_path = \"#{pid_files_dir}/large_objects.txt\"\n File.open(file_path, 'w') { |file| file.puts(large_objects) }\n lists_of_pids = small_objects.each_slice(NUMBER_OF_PIDS_PER_FILE).to_a\n lists_of_pids.each_with_index do |list, index|\n file_path = \"#{pid_files_dir}/#{index}.txt\"\n File.open(file_path, 'w') { |file| file.puts(list) }\n pid_lists << file_path\n end\n end",
"def files_at_commit(pr, filter = lambda { |x| true })\n sha = pr[:base_commit]\n begin\n files = lslr(git.lookup(sha).tree)\n rescue StandardError => e\n log pr[:id]\n log \"Cannot find commit #{sha} in base repo\" # some are in the other branches\n return nil # not to the default branch\n end\n\n # # find the eariler than and closest to the creation time of commit\n # sha = commit_closest_earlier_pr(pr)\n # begin\n # files = sha.nil? ? [] : lslr(git.lookup(sha).tree)\n # rescue StandardError => e\n # log \"Cannot find commit #{sha} in base repo\" # some are in the other branches\n # files = [] # no files found before the pr\n # end\n\n\n if files.size <= 0\n log \"No files for commit #{sha}\"\n end\n files.select { |x| filter.call(x) }\n\n end",
"def get_current_files\n get_files(OcflTools::Utils.version_string_to_int(@head))\n end",
"def search_for_title(title)\n parameters = {\n 'folderId' => find_public_folder,\n 'q' => \"title = '#{title}'\", # full_title\n 'fields' => 'items/id'}\n client = google_api_client\n drive = client.discovered_api('drive', 'v2')\n result = client.execute(:api_method => drive.children.list,\n :parameters => parameters)\n if result.status == 200\n if result.data.items.length > 0\n result.data.items[0]['id']\n elsif result.data.items.length == 0\n nil\n else\n nil\n end\n end\n end",
"def process_files(log)\n each_exercise_file do |root, position, original_id, title|\n\n description = markdown(root, 'description') || (log.no_description title; next)\n\n hint = markdown(root, 'hint')\n\n meta = meta(root) || (log.no_meta(title); next)\n\n test_code, test_extension = test_code(root) || (log.no_test title; next)\n\n extra_code, _extra_extension = extra_code(root)\n\n language = language(test_extension) || (log.no_lang(title); next)\n\n expectations = (expectations(root).try { |it| it['expectations'] } || []).map do |e|\n Expectation.new(binding: e['binding'], inspection: e['inspection'])\n end\n\n yield original_id,\n {title: title,\n description: description,\n hint: hint,\n tag_list: meta['tags'],\n locale: meta['locale'],\n language: language,\n expectations: expectations,\n author: @author,\n test: test_code,\n extra_code: extra_code,\n position: position}\n end\n end",
"def compute_changed_and_risk_files(params)\n commit_hash, file_arr = commit_info(params)\n changed_file_freq = file_arr.flatten!.each_with_object(Hash.new(0)) {|file, freq_acc| freq_acc[file] += 1}\n changed_g2_files = []\n changed_file_freq.select {|file, freq| changed_g2_files << file if freq > 2}\n risk_files = changed_g2_files.dup\n rf = risk_files.each_with_object({}) do |file, acc|\n author_set = Set.new\n commit_hash.each do |file_arr, author|\n acc[file] = (author_set << author ) if file_arr.include? (file)\n end\n end\n rf.delete_if {|_file, author_arr| author_arr.length < 2}\n {\n \"changed_files\" => changed_g2_files,\n \"risk_files\" => rf\n }\n end",
"def files_in_branches\n result = Mortadella::Horizontal.new headers: %w[BRANCH NAME CONTENT]\n existing_local_branches(order: :main_first).each do |branch|\n files_in(branch: branch).each do |file|\n result << [branch, file, content_of(file: file, for_sha: branch)]\n end\n end\n result.table\nend",
"def runMulFrMulOpenedFiles(openedFiles)\n\t\ttitleArr=nil\n\t\ttitleArr=@oc[\"TitleString\"].split(\"@\") if @oc[\"TitleString\"]!=\"\"\n\t\tstyleArr=@oc[\"StyleIndices\"].split(\",\")\n\n\t\t# ---- eventually create vertical bars, which are\n\t\t# ---- nothing else than custom made data files\n\t\tif @oc[\"Bars\"] != \"\"\n\n\t\t\t# ---- If no titles are requested, then we create\n\t\t\t# ---- a dummy title array\n\t\t\tif titleArr==nil\n\t\t\t\ttitleArr=[]\n\t\t\t\t(1..openedFiles.length).each { |i| titleArr.push(\"default-title\") }\n\t\t\tend\n\n\t\t\tbarArr=@oc[\"Bars\"].split(\"@\")\n\t\t\tbarArr.each do |b|\n\t\t\t\t# ---- Parse the bar coordinates\n\t\t\t\tbd=b.split(\",\")\n\t\t\t\tif bd.length!=2\n\t\t\t\t\t$stderr.printf \"%ssyntax error in option -B or --bar!\\n\",$err\n\t\t\t\t\texit 1\n\t\t\t\tend\n\n\t\t\t\t# ---- Create the file and add it to the list of files\n\t\t\t\ttmpf=Tempfile.new(\"eplot\")\n\t\t\t\ttmpf.printf \"%s %s\",bd[0],bd[1]\n\t\t\t\ttmpf.flush\n\t\t\t\topenedFiles.push(tmpf)\n\n\t\t\t\t# ---- Create the entries in the title array\n\t\t\t\tlen=openedFiles.length\n\t\t\t\tif titleArr\n\t\t\t\t\tif titleArr.length<len\n\t\t\t\t\t\ttitleArr.push(\"bar-notitle\")\n\t\t\t\t\telse\n\t\t\t\t\t\ttitleArr[len-1]=\"bar-notitle\"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\t# ---- dump the files if requested\n\t\tdumpFiles(openedFiles) if @oc[\"DumpFiles\"]\n\n\t\t# ---- process all files\n\t\ti=1\n\t\tcom=\"\"\n\t\topenedFiles.each do |f|\n\t\t\tcom=com+\", \" if i>1\n\t\t\tcom=com+\"\\\"\"+f.path+\"\\\" \"\n\n\t\t\t# ---- do we have a title?\n\t\t\tif titleArr\n\t\t\t\tif i>titleArr.length\n\t\t\t\t\t$stderr.printf \"%syou need to specify a title for each curve!\\n\",$err\n\t\t\t\t\texit 1\n\t\t\t\tend\n\t\t\t\tcase titleArr[i-1]\n\t\t\t\t\twhen \"bar-notitle\"\n\t\t\t\t\t\tcom=com+\"notitle \"\n\n\t\t\t\t\twhen \"empty-notitle\"\n\t\t\t\t\t\tcom=com+\"notitle \"\n\n\t\t\t\t\twhen \"default-title\"\n\t\t\t\t\t\t;\n\t\t\t\t\telse\n\t\t\t\t\t\tcom=com+\"title \\\"\"+titleArr[i-1]+\"\\\" \"\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tif titleArr!=nil and titleArr[i-1]==\"bar-notitle\"\n\t\t\t\tcom=com+\"with impulses ls \"+$barStyleIndex\n\t\t\telse\n\t\t\t\tcom=com+\"with \"+@oc[\"LineType\"]+\" ls \"+styleArr[i-1]\n\t\t\tend\n\t\t\ti=i+1\n\t\tend\n\t\tplot(com,true)\n\tend",
"def find_metadata(*args)\n results = []\n @filesets.each do |volid, fileset|\n results += fileset.find_metadata(*args)\n end\n return results\n end",
"def collectFileInformation(tracks, flavor, startTimes, real_start_time)\n startTimes.each do |file|\n pathToFile = File.join(file[\"filepath\"], file[\"filename\"])\n\n BigBlueButton.logger.info( \"PathToFile: #{pathToFile}\")\n\n if (File.exists?(pathToFile))\n # File Integrity check\n if (!FFMPEG::Movie.new(pathToFile).valid?)\n BigBlueButton.logger.info( \"The file #{pathToFile} is ffmpeg-invalid and won't be ingested\")\n next\n end\n\n tracks.push( { \"flavor\": flavor,\n \"startTime\": file[\"timestamp\"] - real_start_time,\n \"path\": pathToFile\n } )\n end\n end\n\n return tracks\nend",
"def read_posts(dir); end",
"def files\n # fetch the appropriate files\n file_paths = Dir.glob(@path + \"/*.mp3\")\n file_paths.map { |file_path| @files << File.basename(file_path) }\n @files\n end",
"def get_changed_file_list\n command = \"git log -m -1 --name-only --pretty='format:' $(git rev-parse origin/master)\"\n file_paths = []\n features = {}\n features.compare_by_identity\n\n Open3.popen3(command) do |stdin, stdout, stderr|\n files = stdout.read.gsub! \"\\n\", \",\"\n file_paths = files.split(\",\")\n puts \"Found files:\\n#{file_paths}\"\n end\n\n puts \"Count files in push: #{file_paths.count}\"\n\n file_paths.each do |file_path|\n if file_path.include?(\".feature\")\n puts \"Added: #{file_path}\"\n folder = get_name_folder_from_path file_path\n features.store(folder, file_path)\n end\n end\n\n puts \"\\n\"\n puts \"Count feature files: #{features.count}\"\n features.sort\nend",
"def list_files(docx)\n\tfiles = []\n\tZip::Archive.open(docx, Zip::CREATE) do |zipfile|\n\t\tn = zipfile.num_files # gather entries\n\n\t\tn.times do |i|\n\t\t\tentry_name = zipfile.get_name(i) # get entry name from archive\n\t\t\tfiles.push(entry_name)\n\t\tend\n\tend\n\treturn files\nend",
"def parse_files\r\n ln_count = 0\r\n\r\n settings.file_order.each do |f|\r\n out = make_file(\"tmp.press\")\r\n\r\n ln_count += parse_lines(f, out)\r\n\r\n out.close\r\n tmp_files << out\r\n end\r\n\r\n ln_count\r\n end",
"def files\n return [] unless meta?\n filename = meta['path'] + '/' + meta['filename']\n [\n Inch::Utils::CodeLocation.new('', filename, meta['lineno'])\n ]\n end",
"def get_file_load_list\n json_file_path = File.join(SDESK_ROOT_PATH, 'configs', 'file_list.json')\n json_data = load_json_file json_file_path\n return [] unless json_data\n\n flist_arr = []\n json_data.each_pair do |dir_name, file_h|\n file_h.each_pair do |fname, queue_id|\n flist_arr << [File.join(dir_name, fname+'.rb'), queue_id]\n end\n end\n flist_arr.sort_by!{|arr| arr.last}\n flist_arr.map(&:first)\n end",
"def backlinks(title, filter = \"all\")\n titles = []\n blcontinue = nil\n begin\n form_data =\n {'action' => 'query',\n 'list' => 'backlinks',\n 'bltitle' => title,\n 'blfilterredir' => filter,\n 'bllimit' => @options[:limit] }\n form_data['blcontinue'] = blcontinue if blcontinue\n res, blcontinue = make_api_request(form_data, '//query-continue/backlinks/@blcontinue')\n titles += REXML::XPath.match(res, \"//bl\").map { |x| x.attributes[\"title\"] }\n end while blcontinue\n titles\n end",
"def film_title_list(films)\n film_titles = films.map { |f| f['title'] }\n '- ' + film_titles.join(\" \\n - \")\nend",
"def files; entries.find_all {|e| e.is_a? SiteFile} end",
"def file_names\n names = []\n frm.table(:class=>/listHier lines/, :text=>/Title/).rows.each do |row|\n next if row.td(:class=>\"specialLink\").exist? == false\n next if row.td(:class=>\"specialLink\").link(:title=>\"Folder\").exist?\n names << row.td(:class=>\"specialLink\").link(:href=>/access.content/, :index=>1).text\n end\n return names\n end",
"def with_title(items)\n return items if title.nil?\n return items.none if title.blank?\n\n items.where(title: title)\n end",
"def get_entries(date = nil)\r\n if date.nil?\r\n list = []\r\n for i in @log\r\n list.push(i)\r\n end\r\n elsif @log[date].nil?\r\n list = nil\r\n else\r\n list = @log[date]\r\n end\r\n list\r\n end",
"def build_filelist(source_file, rule_name)\n basename = source_file.pathmap('%n') # base name without ext\n prefix = \"#{CONF[\"project\"]}-#{rule_name}--#{basename}\"\n src_lines = File.readlines(source_file)\n\n filelist = {\n source: source_file,\n mp3: \"#{DIR[:mp3]}/#{prefix}.mp3\",\n compile: \"#{DIR[:compile]}/#{prefix}.wav\",\n concat: 1.upto(src_lines.size).map { |n| \"#{DIR[:concat]}/#{prefix}--#{'%04d' % n}.wav\" },\n raw: [],\n say_args_by_raw: {},\n movie_concat: \"#{DIR[:movie]}/CONCAT_#{prefix}.txt\",\n movie: \"#{DIR[:movie]}/#{prefix}.mp4\",\n movie_pics: [],\n app_sounds: [],\n }\n\n\n field_voice = CONF['field'].to_a\n src_lines.each_with_index do |line, line_index|\n line.chomp!\n\n raw_by_field = {}\n line.split(/\\t/).each_with_index do |content, index|\n field, voice = field_voice[index]\n next unless voice\n filename_safe_content = get_filename(content)\n # p [filename_safe_content, content]\n\n if (filelist[:movie_pics][line_index].nil?)\n filelist[:movie_pics].push \"#{DIR[:movie_pics]}/#{filename_safe_content}.png\"\n end\n\n app_config = CONF['app'][rule_name]\n if app_config\n app_root = app_config['app_root']\n if app_root\n if (filelist[:app_sounds][line_index].nil?)\n filelist[:app_sounds].push app_config['sounds'].size.times.map { |n|\n File.join(app_root, \"sounds\", \"#{filename_safe_content}-#{n + 1}.wav\")\n }\n end\n end\n end\n\n filter = CONF['filter'][field]\n content = Filter.send(filter, content) if filter\n digest = Digest::SHA256.hexdigest(voice + content)\n raw_file = \"#{DIR[:raw]}/#{digest}.wav\"\n filelist[:say_args_by_raw][raw_file] = [voice, content]\n raw_by_field[field] = raw_file\n end\n filelist[:raw] << raw_by_field\n end\n filelist\nend",
"def query_by_duplicates\n tmp = self.clone\n tmp.list = list.select {|k,v| v.filename.count > 1}\n end",
"def files\n i = 0\n @@arr_path.each do |path|\n if path.include?(params[:fold])\n # Remove path from current path\n @@arr_path = @@arr_path[0..i]\n @path = ''\n\n @@arr_path.each do |e| # Put path from array to @path\n @path = @path + e + ' >> '\n end\n @@temp_path = @path\n\n # Get content: folders, file, count\n @content = BrowsingFile.bind_folder params[:fold]\n @file = BrowsingFile.bind_files params[:fold]\n\n render 'index' # Reload index page\n return\n end\n i += 1\n end\n end",
"def file_sets_for(work)\n Hyrax.custom_queries.find_child_file_sets(resource: work)\n end",
"def read_files(docs)\n return if docs.size == 0\n tika_cmd = \"java -jar #{TIKA_PATH} #{docs.map{|e|\"\\\"\"+e.uri+\"\\\"\"}.join(\" \")}\"\n debug \"#{docs.size} / #{tika_cmd}\"\n contents = `#{tika_cmd}`\n warn \"[read_files] Command #{tika_cmd} failed!\" if contents.blank? || contents =~ /^Exception/\n #debugger\n begin\n Hpricot(contents).search(\"/html\").each_with_index do |content,i|\n title = content.search(\"title\")[0].inner_text\n #title = content.search(\"p\")[0].inner_text if title.blank?\n body = content.search(\"body\").inner_text\n docs[i].write_attribute(:title, (title.blank?)? docs[i].uri : title )\n docs[i].write_attribute(:content, body[0..FileCollector::MAX_FILE_LENGTH] )\n end\n rescue Exception => e\n #print(e)\n error \"[read_files] Error #{e.inspect}\"\n end\n end",
"def files\n @files ||= []\n end",
"def search_files(params)\n # return if no search term entered\n return nil if params[:term].blank?\n \n result = {:term => params[:term], :current_page => params[:page], :per_page => 100, :previous_page => nil, :next_page => nil, :results => []}\n search_term_escaped = params[:term].gsub(\"'\", %q(\\\\\\'))\n \n # Build out search params\n parameters = {}\n parameters['q'] = \"title contains '#{search_term_escaped}'\"\n parameters['pageToken'] = result[:current_page].to_s if result[:current_page].to_s.present?\n parameters['maxResults'] = result[:per_page]\n \n begin\n drive = @client.discovered_api('drive', 'v2')\n api_result = @client.execute(:api_method => drive.files.list, :parameters => parameters)\n rescue\n return nil\n end\n \n if api_result.status == 200\n files = api_result.data\n files.items.each do |item|\n result[:results] << self.item_into_standard_format(item)\n end\n # Pagination\n #result[:next_page] = files.next_page_token\n else\n result[:error] = {:code => api_result.status, :message => api_result.data['error']['message']} \n end\n result\n end",
"def paragraphs_of( path, *args )\n return [] unless test(?f, path)\n\n title = String === args.first ? args.shift : nil\n paragraphs = File.read(path).delete(\"\\r\").split(%r/\\n\\n+/)\n\n if title.nil? then\n title = '.+'\n single_section = false\n else\n title = Regexp.escape(title)\n single_section = true\n end\n\n start_rgxp = [%r/\\A[=#]+\\s*#{title}/i, %r/\\A#{title}\\n[=-]+\\s*\\Z/i]\n end_rgxp = [%r/\\A[=#]+/i, %r/\\A.+\\n[=-]+\\s*\\Z/i]\n\n result = []\n matching = false\n rgxp = start_rgxp\n\n paragraphs.each do |p|\n if rgxp.any? { |r| p =~ r }\n if matching && single_section\n break\n end\n matching = true\n rgxp = end_rgxp\n next\n end\n\n if matching\n result << p\n end\n end\n\n args.empty? ? result : result.values_at(*args)\n end",
"def files\n filenames || []\n end",
"def readFiles\n rError = nil\n\n # Check the repository\n if (File.exists?(@LocalRepository))\n @LstFiles = nil\n if (@FilesFileName != nil)\n if (File.exists?(@FilesFileName))\n File.open(@FilesFileName, 'r') do |iFile|\n @LstFiles = iFile.readlines.map do |iLine|\n next iLine.strip\n end\n end\n else\n rError = MissingFilesFileError.new(\"Missing Files file: #{@FilesFileName}\")\n end\n end\n if (rError == nil)\n # Construct the files list as seen on the command line\n @StrFiles = ''\n if (@LstFiles != nil)\n @LstFiles.each do |iFileName|\n if (iFileName.include?(' '))\n @StrFiles += \" \\\"#{iFileName}\\\"\"\n else\n @StrFiles += \" #{iFileName}\"\n end\n end\n end\n if (File.exists?(@TasksFileName))\n @LstTasks = nil\n File.open(@TasksFileName, 'r') do |iFile|\n @LstTasks = iFile.readlines.map do |iLine|\n next iLine.strip\n end\n end\n if (File.exists?(@TicketsFileName))\n @LstTickets = nil\n File.open(@TicketsFileName, 'r') do |iFile|\n @LstTickets = iFile.readlines.map do |iLine|\n next iLine.strip\n end\n end\n else\n rError = MissingTicketsFileError.new(\"Missing Tickets file: #{@TicketsFileName}\")\n end\n else\n rError = MissingTasksFileError.new(\"Missing Tasks file: #{@TasksFileName}\")\n end\n end\n else\n rError = MissingLocalRepositoryError.new(\"Missing local repository: #{@LocalRepository}\")\n end\n\n return rError\n end"
] |
[
"0.5901373",
"0.54093146",
"0.53490376",
"0.51821136",
"0.5099016",
"0.50472564",
"0.5040822",
"0.5007242",
"0.5007242",
"0.48155662",
"0.48111278",
"0.4796713",
"0.47855008",
"0.47633484",
"0.47456014",
"0.47180527",
"0.46884465",
"0.46787164",
"0.46664047",
"0.4666243",
"0.46499836",
"0.4646241",
"0.4636797",
"0.46292788",
"0.4622332",
"0.46222195",
"0.46075666",
"0.46060866",
"0.4596919",
"0.4590769",
"0.45810685",
"0.45741013",
"0.45741013",
"0.45706734",
"0.45663974",
"0.45491126",
"0.45330516",
"0.45249462",
"0.45162925",
"0.450982",
"0.45076835",
"0.44794098",
"0.44745502",
"0.44704053",
"0.44626686",
"0.4446682",
"0.442363",
"0.43904385",
"0.4383414",
"0.43725458",
"0.4355083",
"0.4351778",
"0.4347243",
"0.43406782",
"0.43396345",
"0.43358034",
"0.4324276",
"0.43181944",
"0.43111363",
"0.43110052",
"0.43004885",
"0.42957336",
"0.4295008",
"0.42947",
"0.42927125",
"0.4281315",
"0.42794457",
"0.4278763",
"0.42780733",
"0.4272162",
"0.42683926",
"0.42670128",
"0.42628542",
"0.42577195",
"0.42479283",
"0.42465007",
"0.42463848",
"0.42402807",
"0.42318964",
"0.42303216",
"0.42296067",
"0.4225422",
"0.42193478",
"0.4216562",
"0.42107096",
"0.42048582",
"0.42021635",
"0.41961727",
"0.41940305",
"0.4188646",
"0.41847146",
"0.41808614",
"0.4179035",
"0.41747937",
"0.4172663",
"0.41694888",
"0.4168367",
"0.4159508",
"0.41579834",
"0.4156154"
] |
0.73172647
|
0
|
Feel free to google "how to generate a random number in ruby"
|
def roll
randomValue = rand(6)+1
randomValue
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def generate_number\r\n return randomNumber = 1 + rand(100)\r\n end",
"def get_random_number()\n rand(0x7fffffff).to_s\nend",
"def gen_num\n rand(1..100)\nend",
"def random_number\n t = Time.now.to_f / (Time.now.to_f % Time.now.to_i)\n random_seed = t * 1103515245 + 12345;\n (random_seed / 65536) % 32768;\nend",
"def rand\n return extract_number / (2**32 -1).to_f\n end",
"def random\n 1 + (10 * rand(0))\n end",
"def generate_number\r\n \r\n #Generate and return a random number between 1 and 1000\r\n return randomNo = 1 + rand(1000)\r\n \r\n end",
"def random_no\n rand(5000)\nend",
"def random_number\n rand(0..20)\n end",
"def random_num_generator\n return rand(1..100)\nend",
"def random_num_generator\n return rand(1..100)\nend",
"def generate_random_number\n rand(1..6) + 1\nend",
"def generate_number\r\n \r\n #Generate and return a random number between 1 and 100\r\n return randomNo = 1 + rand($maxChallengeRange)\r\n \r\n end",
"def generate_one_random_number()\r\n @l = @total_no_of_bits + 1\r\n bit_string = @total_sequence.join('')\r\n numerator = bit_string.to_i(2)\r\n random_number = numerator *1.0 / 2**@l\r\n\r\n return random_number\r\n end",
"def srand(num=0) end",
"def number_generator\n rand(1..20)\n end",
"def generate_number\n \n #generate and return a random number from 1 to 100\n return randomNO = 1 + rand(1000)\n\n end",
"def pick_random_number(digits=1)\n min = 10 ** (digits - 1)\n max = (10 ** digits ) - 1\n semirandom = min + rand(max-min)\n semirandom += 1 if semirandom == 666 #would be unpleasant to receive...\n return semirandom\n end",
"def generate_random_number\n (1..10).to_a.sample\nend",
"def get_random\n File.read(\"/dev/urandom\", 8).unpack(\"H*\")[0].hex\n rescue\n rand(9117854927)\n end",
"def randomizer\n number = rand(0..1)\n return number\nend",
"def random_number\n rand(1..20)\nend",
"def make_not_so_random!\n srand 1213\nend",
"def rand_digit #generate random digit\n\treturn rand(10)\nend",
"def random_number \n rand(6) + 1 \nend",
"def random_number\n rand 0..20\nend",
"def getRand()\n # With 32-bit MAX_INT to be able to have cool numbers\n return Random.rand() * 2147483647;\nend",
"def random_int(max)\n rand(max)\nend",
"def get_random_number(max_value = 10)\n\trand(max_value)\nend",
"def randomNum()\r\n num = rand(1..10)\r\nend",
"def nostalgia; return rand end",
"def digit\n rand(10)\n end",
"def generate_random()\n begin\n r = Kernel.rand()\n end while r == 0.0\n \n if use_flt?\n BigDecimal(r.to_s)\n else\n r\n end\n end",
"def uniform_int(n)\n (rand()*n).to_i\nend",
"def number\n\t\"#{Time.now.to_i}-#{rand(1_000_000)}\"\n end",
"def rand_nr\n return rand(1..2)\nend",
"def get_rand\n rand = \"\";\n File.open(\"/dev/urandom\").read(20).each_byte{|x| rand << sprintf(\"%02x\",x)}\n rand\nend",
"def random_number(min, max)\n rand(max-min+1)+min\n end",
"def random_num(min, max)\n rand(max - min + 1) + min\nend",
"def random_to_one\n return rand()\n end",
"def random_to_one\n return rand()\n end",
"def random_to_one\n return rand()\n end",
"def random_to_one\n return rand()\n end",
"def n_generator\n number = rand(10..30)\n end",
"def random_number(seed, range)\n seed = seed.to_i\n return nil if seed <= 0\n rng2 = Random.new(seed)\n num = rng2.rand(range) + 1\n num\n end",
"def new_account_number\n return rand(99999999)\n end",
"def new_account_number\n return rand(99999999)\n end",
"def random_num(min, max)\n rand(max - min + 1) + min\nend",
"def non_zero_digit\n rand(1..9)\n end",
"def random_account_number\r\n acct_num = rand(10**11).to_s.rjust(11, '1')\r\n return acct_num\r\n end",
"def make_rand\n Random.new_seed\n return Random.new\n end",
"def random(range)\n return rand(range + 1)\nend",
"def random\n card = rand(1..52)\n card.to_i\n end",
"def random\n card = rand(1..52)\n card.to_i\n end",
"def ran_str_maker\r\n length = 10\r\n ran_str = rand(36**length).to_s(36)\r\n return ran_str\r\nend",
"def rand_num(range)\n num = @rng.rand(range) + 1\n num\n end",
"def test_random_number_generation\n rand = @game.get_random_number(0, 10)\n assert rand <= 10 && rand >= 0\n end",
"def gen_random_int\n $lasti = ($lasti * IA + IC) % IM\nend",
"def randomBitNum x\n bitString = \"1\"\n (1...x).each do\n bitString += rand(2).to_s\n end\n return bitString.to_i(2)\nend",
"def randomBitNum x\n bitString = \"1\"\n (1...x).each do\n bitString += rand(2).to_s\n end\n return bitString.to_i(2)\nend",
"def get_random_number\n\t\trandom_num = rand(@deck.length)\n\tend",
"def rand_id\n rand(10**7...10**8).to_s\nend",
"def random_id\n rand(1000000) + 20000\nend",
"def rand(max=0) end",
"def rand\n warn \"STUB: rand in distribution.rb\"\n end",
"def random_number( bits )\n m = (1..bits-2).map{ rand() > 0.5 ? '1' : '0' }.join\n s = \"1\" + m + \"1\"\n s.to_i( 2 )\n end",
"def generate_number(store)\n store.number = loop do\n random_number = Digest::SHA1.hexdigest([Time.now, rand].join)[0..5].upcase\n break random_number unless Store.exists?(number: random_number)\n end\n end",
"def random_account_number\n acct_num = rand(10**11).to_s.rjust(11, '1')\n return acct_num\n end",
"def rand\n Kernel.rand(self)\n end",
"def generator_rand(max)\n return nil if max < 0\n\n result = rand(max + 1)\n result\n end",
"def rand_id\n rand(10**7...10**8).to_s\n end",
"def get_random_number(gender)\n\t\tcount = total_count(gender)\n\t\tset_random_seed\n\t\treturn rand(1..count)\n\tend",
"def random20\n rand(20) + 1\n end",
"def get_next_uuid\n rand(8**32).to_s(36)\n end",
"def gen_rand b\n p = rand(2**b)+2**b-1\n while ! rand_test p\n# puts p\n p += 1\n end\n p\nend",
"def get_new_random_number random_numbers\n random_number = 0\n begin\n random_number = rand @working_dataset.get_dataset_size\n end while (random_numbers.has_key?(random_number))\n random_numbers[random_number] = 1\n return random_number\n end",
"def rand_digit\n ascii = Random.rand(10) + 48\n return ascii.chr\nend",
"def random_integer(limit)\n Rubinius.primitive :randomizer_rand_int\n raise PrimitiveFailure, \"Randomizer#rand_int primitive failed\"\n end",
"def random_integer(limit)\n Rubinius.primitive :randomizer_rand_int\n raise PrimitiveFailure, \"Randomizer#rand_int primitive failed\"\n end",
"def sequence_number\n @sequence_number ||= rand(0xFFFFFFFF)\n end",
"def random_float\n rand * rand(10)\n end",
"def get_rand range\n\t\t@random_number = rand(range)\n\tend",
"def any_number(*options)\n number = (rand(2 * MAX_RAND) - MAX_RAND).to_f/100.0\n if options.include? :positive\n number + MAX_RAND\n elsif options.include? :negative\n number - MAX_RAND\n else\n number\n end\n end",
"def random\n rand - rand\nend",
"def generateCode()\n require 'securerandom'\n return SecureRandom.hex\n end",
"def generate_number\n if self.respond_to? :inv_cdf\n inv_cdf(rand)\n else\n generate_sample 1\n end\n end",
"def rand(max)\n max-1\nend",
"def generate_int\n UUIDTools::UUID.random_create.to_i\n end",
"def initialize(num = rand(52))\n self.num = num\n end",
"def generate_random_number_except_123\n x = rand(1000)\n throw :finish if x == 123\nend",
"def random_status_number_generator\n Random.rand(1..10)\n end",
"def rand_phone options={}\r\n\t\"210#{random(1111111, 9999999).to_s}\"\r\nend",
"def rand_seed\n rand(0x7fffffff)\n end",
"def random_integer(max_size)\r\n 1 + rand(max_size)\r\n end",
"def gen_speed\n rand + 15.0\n end",
"def generate_order_number\n r = Random.new\n \"#{self.class.to_s.gsub(/[a-z]/, '')}#{Time.now.to_i}\"\n end",
"def usw_random(max=-1, min=0)\n Sass::Script::Number.new( max.to_i < 0 ? rand() : rand(min.to_i .. max.to_i ))\n end",
"def randr(min, max)\n rand(max - min + 1) + min\nend",
"def random(num_bytes)\n SecureRandom.random_bytes(num_bytes)\n end",
"def int(size)\n rand(size).to_i\n end",
"def randstr\n\trand(36 ** 8).to_s(36)\nend"
] |
[
"0.8495249",
"0.83665675",
"0.8312836",
"0.8223235",
"0.8188632",
"0.81023866",
"0.8082494",
"0.80452955",
"0.80336106",
"0.8030636",
"0.8030636",
"0.80123246",
"0.79662156",
"0.7955537",
"0.7934739",
"0.7909762",
"0.78774667",
"0.78719956",
"0.78630906",
"0.78546405",
"0.78182465",
"0.78144264",
"0.7806386",
"0.77860206",
"0.7784265",
"0.7769858",
"0.7765166",
"0.76942825",
"0.76324296",
"0.7621901",
"0.76177186",
"0.760963",
"0.76073915",
"0.7576107",
"0.75621784",
"0.7535127",
"0.748124",
"0.74642575",
"0.74561596",
"0.7454499",
"0.7454499",
"0.7454499",
"0.7454499",
"0.74522763",
"0.7438381",
"0.7436939",
"0.7436939",
"0.7433478",
"0.7418257",
"0.73946893",
"0.739268",
"0.7388281",
"0.7385159",
"0.7384897",
"0.73724973",
"0.7367194",
"0.7335837",
"0.7312186",
"0.7306853",
"0.7306853",
"0.7306526",
"0.73022056",
"0.73000467",
"0.7298165",
"0.72974473",
"0.72960377",
"0.7296036",
"0.72936445",
"0.72889656",
"0.7279382",
"0.72765255",
"0.72656846",
"0.72603023",
"0.72545",
"0.72519815",
"0.7225546",
"0.7208775",
"0.7195972",
"0.7195972",
"0.7187876",
"0.7176327",
"0.71478534",
"0.71434057",
"0.71375996",
"0.7111428",
"0.7104107",
"0.7093457",
"0.7091851",
"0.70779335",
"0.7069373",
"0.7051465",
"0.6980642",
"0.6951931",
"0.69453204",
"0.69326097",
"0.6931686",
"0.6919324",
"0.6913043",
"0.69050646",
"0.68936175",
"0.6893159"
] |
0.0
|
-1
|
return an HTML form for creating a new user
|
def new
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def new\n\t@user = User.new\n\t@title = \"Sign up\"\n end",
"def new\n\t@title = \"Sign Up\"\n\t@user = User.new\n end",
"def new\n\t\tmissing unless WAYGROUND['ALLOW_SIGNUP']\n\t\t@user = User.new(params[:user])\n\t\t@user.time_zone = Time.zone.name unless params[:user]\n\t\t@user.valid? if params[:user]\n\t\t@page_title = 'New User Registration'\n\tend",
"def new\n @myuser = User.new # Create a new user in memory, whose params will be filled by the form\n end",
"def new\n # create new user object ONLY (does not save a user to the database)\n # this lets the form_for in our view know to create a form with\n # with html attributes designated to create a new user\n @user = User.new\n end",
"def new\n # When a http GET request to '/users/new' is received, have it render:\n # a view file with an empty form to create a new user.\n end",
"def new\n\t\t @user = User.new\t\t#lo devo passare nella form per la create\n\tend",
"def new\n @title = \"Sign up\"\n @user = User.new\n end",
"def new\n @title = \"Sign up\"\n @user= User.new\n end",
"def new\n @user = User.new\n @title = \"Sign up\"\n #@action = \"New Action\"\n end",
"def new\n @title = \"Signup Page\"\n @user = User.new\n end",
"def create\n @title = t('admin.users.new.title')\n @user = User.new(params[:user])\n\n if @user.save\n js_notify message: t('admin.users.create.success'), type: 'alert-success', time: 2500\n render partial: 'user', content_type: 'text/html', locals: { user: @user }\n else\n render partial: 'new', status: :unprocessable_entity\n end\n end",
"def new\n @user = User.new\n @button_text = \"Sign up!\"\n @show_tos = true\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @user }\n end\n end",
"def new\n @title = t('admin.users.new.title')\n @user = User.new\n\n render partial: 'new', content_type: 'text/html'\n end",
"def new\n only_provides :html\n @user = User.new\n display @user\n end",
"def create\n @user = User.new(params[:user])\n if @user.save\n redirect_to users_path, notice: t('users.update.updated')\n else\n @page_title = t(\"actions.new_user\")\n render action: 'new'\n end\n end",
"def new\n @user = User.new\n @btn_text = t('users.new.btn_signup')\n @title = t('app_name') + ' | ' + t('users.new.title')\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def create\n if params[:submit]\n @user = User.new(params[:user])\n \n respond_to do |format|\n if @user.save\n format.html { redirect_to '/', 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 else\n @user = User.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end\n end",
"def new\n @title=\"Sign Up\"\n @user = User.new\n end",
"def new\n if params[:submit]\n @user = User.new(params[:user])\n \n respond_to do |format|\n if @user.save\n format.html { redirect_to '/', 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 else\n @user = User.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end\n end",
"def new_user\n\t\t@resource = User.new\n\t\t@resource_name = 'user'\n\tend",
"def new\n @title = \"Sign-In or Register\"\n @user = User.new\n\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\t\n\t\tif @user.save\n\t\t\tredirect_to users_path\n\t\telse\n\t\t\trender 'new'\n\t\tend\n\tend",
"def create\n # Wenn Formular abgeschickt\n if ! params[:user].nil?\n if params[:user][:password] == params[:user][:password2] \n # Wird gesetzt damit die Create-Forms verschwinden\n @inputs = true; \n # entferne Passwortwiederhohlung aus den Parametern um User zu erzeugen\n params[:user].delete(:password2) \n # Erster Benutzer muss Admin sein\n if User.find(:all).length == 0\n params[:user][:access]=\"admin\"\n else\n params[:user][:access]=\"leecher\"\n end\n @newuser = User.new(params[:user])\n # @created wird gesetzt zur erstellungsmessage, da komischerweise ein\n # zugriff auf @newuser.valid? nicht fruchtet\n if @newuser.valid?\n @created=true\n # Wenn user Admin ist,(erste anmeldung) setze die Variable un erstelle ein basis genre\n if params[:user][:access]==\"admin\"\n @admin = true\n Genre.create(:name => \"unknown\")\n end\n end\n @newuser.save\n else \n # Wenn diese Variable nil ist, sind beide Passwörter nicht gleich\n @bothpw=true\n end \n end\n respond_to do |format|\n format.html \n format.xml \n end\n end",
"def create\n if user.save\n redirect_to users_path\n else\n render 'new'\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n format.html\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html\n end\n end",
"def new\n @title = \"Signup\"\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @title = \"Sign Up\"\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @user = User.new(session[:form])\n session[:form] = nil # remove temporary form data\n end",
"def new\n @user = flash[:form_data] || User.new\n @title = 'New user'\n\n render_view(:form)\n end",
"def create\n\t\t@user = User.new(params[:user])\n\t\tif @user.save\n\t\t\tredirect_to root_url, notice: \"Added new user to the database\"\n\t\telse\n\t\t\trender \"new\"\n\t\tend\n\tend",
"def new\n @user = User.new\n render template:'modals/signup-modal', layout: false\n end",
"def new\n @title = \"sign up\"\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def create\n # When a http POST request to '/users' is received from the form rendered in\n # '/users/new', have it create a user with the information from the input field.\n # After creating the user, redirect to the '/users' route.\n @user = User.create(params[:user])\n redirect_to action: \"index\"\n end",
"def create\n @new_user = NewUser.new(new_user_params)\n\n respond_to do |format|\n if @new_user.save\n format.html { redirect_to @new_user, notice: 'New user was successfully created.' }\n format.json { render :show, status: :created, location: @new_user }\n else\n format.html { render :new }\n format.json { render json: @new_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @user = User.new\n @stylesheet = \"new_user\"\n @google_fonts = \"Josefin+Slab|Rock+Salt\"\n @title = \"Bakery Market | New User Registration\"\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new_user\n \trender action: 'new_user'\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\tif @user.save\n\t\t\tflash[:notice] = \"Thanks for signing up\"\n\t\t\tredirect_to root_url\n\t\telse \n\t\t\trender 'new'\n\t\tend \n\tend",
"def create\n name = params[:name]\n email = params[:email]\n password = params[:password]\n new_user = User.create!(\n name: name,\n email: email,\n password: password,\n )\n\n response = \"Hey #{name}, You are registered successfully!\"\n render plain: response\n end",
"def new\n unless current_user.admin?\n flash[:error] = \"Users can only be created by administrators.\"\n redirect_to (request.env[\"HTTP_REFERER\"] || root_path) and return\n end\n \n @user = User.new\n end",
"def new\n @user = User.new\n @title = \"Sign Up\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def add_new_user()\n new_user_link.click\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n flash[:user] = t('user_create')\n redirect_to user_path(@user)\n else\n render 'new'\n end\n end",
"def new\n if logged_in?\n redirect_to user_path(current_user) # Redirect to user show page if logged in\n else \n @user = User.new # Stub a new user\n render layout: 'welcome' # Render sign up form with welcome layout\n end \n end",
"def new\n @new_user = User.new\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n redirect_to user_path(@user)\n else\n render :new\n end\n end",
"def create\n @user = User.new params[:user]\n if @user.save\n flash[:notice] = \"#{@user.full_name} was successfully added.\"\n redirect_to users_path\n else\n render :action => :new\n end\n end",
"def new\n\t\t@user = User.new\n\t\trender :new\n\tend",
"def create\n\t\tif @user.save\n\t\t\tflash[:notice] = \"Your account has been successfully created!\"\n\t\t\tUserMailer.welcome_email(@user).deliver!\n\t\t\tredirect_to root_url\n\t\telse\n\t\t\tflash[:error] = get_all_errors\n\t\t\trender 'new'\n\t\tend\n\tend",
"def new\n @user = user.new\n\t\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def new\n @user = User.new\n render :new\n end",
"def new\n @user = User.new\n render :new\n end",
"def new\n @user = User.new\n render :new\n end",
"def create\n @user = user_from_params\n if @user.save\n sign_in @user\n redirect_back_or url_after_create\n else\n render template: \"users/new\"\n end\n end",
"def create\n user = User.create(\n username: params[:username],\n email: params[:email],\n bio: params[:bio]\n )\n if user.errors.any?\n @errors = user.errors\n render :new\n else\n redirect_to root_path\n end\n end",
"def create\n @user = User.new(\n fname: params[:user][:fname],\n lname: params[:user][:lname]\n )\n\n if @user.save\n flash[:notice] = \"The user was created\"\n redirect_to user_path(@user)\n else\n # flash[:alert] = \"The user was not created\"\n render :new\n end\n end",
"def user_new(opts = {})\n call(\"user\", \"new\", opts)\n end",
"def create \n @myuser = User.new(params[:user]) # 'user' is a dictionary created by the signup form and containing the new user's filled-in parameters\n if @myuser.save\n flash[:success] = \"Welcome to the Sample App!\"\n redirect_to @myuser\n else\n render 'new'\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n redirect_to root_path, notice: 'User was successfully created'\n else\n render action: 'new'\n end\n end",
"def new\n # give form access to model methods\n @user = User.new\n end",
"def new\n @user = User.new\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\tif @user.save\n\t\t\tredirect_to login_path\n\t\telse\n\t\t\trender :new\n\t\tend\n\tend",
"def new\n # Diese Seite ist User-unabhängig\n @independent = true\n @action = \"Registrieren\"\n @header = {\"back\" => root_path, \"ajax\" => true, \"title\" => \"Registrieren\"}\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n end",
"def create\n @user = User.new(params[:user])\n\n if @user.save\n flash[:notice] = t('users.create.notice')\n redirect_to users_path\n else\n render :action => \"new\"\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @user }\n end\n end",
"def new \n @user = User.new\n @current_uri = request.env['PATH_INFO']\n render :layout => \"signup_login\"\n end",
"def create\n\t\tuser_params = params.require(:user).permit(:first_name, :last_name, :email, :password)\n\t\t@user = User.create(user_params)\n\t\tlogin(@user) #log in user\n\t\tredirect_to \"/users/#{@user.id}\" #go to show\n\tend",
"def create\n @user = User.new user_params #authenticating the user's information. fill in the db with these values.\n if @user.save #if it saves,\n redirect_to \"/users/#{ @user.id }\" #redirect to their profile page\n else\n render :new #if not new form.\n end\n end",
"def create\n @user = User.new(params[:user])\n\n if @user.save\n redirect_to(root_url, :notice => 'User was successfully created.')\n else\n render :action => \"new\"\n end\n end",
"def new\n\t \t@user = User.new\n\t \t#get the type of user being created based on what button was clicked\n\t\t@type = params[:type]\n\n\t\t#produce a list of supervisors\n\t\t@sups = User.where(type: Supervisor)\n\n\t\trender(\"new\")\n\t end",
"def create\n @user = User.new(user_params)\n if @user.save\n redirect_to @user, notice: 'Se creo un usuario exitosamente.'\n else\n render :new\n end\n end",
"def new\n @user = User.new\n @title = \"Signup to Studyers\"\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\n\t\tif @user.save\n\t\t\tsign_in @user\n\t\t\tflash[:success] = \"Welcome, #{@user.name}!\"\n\t\t\tredirect_to root_path\n\t\telse\n\t\t\trender action: 'new'\n\t\tend\n\n\tend",
"def create\n\t\t@user = User.new(user_params)\n\t\tif @user.save\n\t\t\tsign_in @user\n\t\t\tflash[:success] = \"Successful Registration\"\n\t\t\tredirect_to problems_url\n\t else\n\t render 'new'\n\t end\n\tend",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { flash.now[:info] = t('users.create.success'); redirect_to root_path }\n format.json { render json: @user, status: :created, location: @user }\n else\n @btn_text = t('users.new.btn_signup')\n @user.password = ''\n @user.password_confirmation = ''\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[:user])\n @user.attributes.each do |attr, val|\n logger.debug(\"attr: #{attr}, val: #{val}\")\n end\n\n if @user.save\n flash[:success] = \"Successfully created account, please sign in\"\n redirect_to login_path\n else\n flash[:warning] = \"Couldn't process the user\"\n render action: \"new\"\n end\n\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n redirect_to users_path, notice: \"ユーザが保存されました\"\n else\n render :new\n end\n end",
"def new\n @user = User.new \n end",
"def new\n \n @user = User.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n \n end",
"def new\n if logged_in?\n # User who has logged in has no need to access create action\n redirect_to current_user\n else\n # Get ready to display signup page by declaring instance var\n \t @user = User.new\n end\n end",
"def new\n @user = User.new\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n logger.debug(\"Create a new user\")\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user }\n end\n end",
"def new\n @user = User.new\n session[:form] = \"register\"\n end",
"def new\n \t@user = User.new\n \t@titre = \"Inscription\"\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\t# If user was save with succes, then sign in automaticly, else, render new.\n\t\tif @user.save\n\t\t\tsign_in @user\n\t\t \tflash[:sucess] = \"Seja bem-vindo!\"\n\t\t\tredirect_to :action => :show, :id => @user.id\n\t\t\tCUSTOM_LOGGER.info(\"Created and associated user to params #{@user.to_yaml}\")\n\t\telse\n\t\t\trender 'new'\n\t\t\tCUSTOM_LOGGER.error(\"Not created and associated user to params #{@user.to_yaml}\")\n\t\tend\n\tend",
"def create\n @user = User.new(params[:user])\n @user.attributes = params[:user]\n if @user.save\n flash[:success] = I18n.t('users.created')\n redirect_to users_path\n else\n self.bread\n add_crumb(I18n.t('users.new'),new_user_path)\n render 'new'\n end\n end",
"def new\n @user = User.new \n end",
"def create\n @user = User.new(params[:user])\n \n if @user.create_first\n flash[:message] = \"<h2>#{t('welcome', :scope => 'refinery.users.create', :who => @user.username).gsub(/\\.$/, '')}.</h2>\".html_safe\n\n sign_in(@user)\n redirect_back_or_default(refinery.admin_root_path)\n else\n render :new\n end\n end",
"def create\n @user = User.new(params[:user])\n if @user.save\n flash[:notice] = 'Registration successfull.' \n redirect_to root_url\n else\n render :action => \"new\"\n end\n end",
"def new\n @user = User.new\n @is_signup = true\n end",
"def new\n\t\t@user = User.new\n\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml { render :xml => @user }\n\t\tend\n\tend",
"def new\n\t\t@user = User.new\n\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.xml { render :xml => @user }\n\t\tend\n\tend",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def new\n @user = User.new()\n end",
"def new\n @user = User.new()\n end",
"def new\n @user = User.new()\n end"
] |
[
"0.7706145",
"0.7576483",
"0.74910504",
"0.74815553",
"0.7411804",
"0.73993486",
"0.73825485",
"0.7295869",
"0.72639287",
"0.7241989",
"0.7207495",
"0.7204781",
"0.7203938",
"0.72020185",
"0.7193657",
"0.71522295",
"0.71294606",
"0.7122919",
"0.7086613",
"0.70711076",
"0.7056484",
"0.7045485",
"0.7018619",
"0.70057535",
"0.70004964",
"0.699509",
"0.69884115",
"0.6975448",
"0.6973255",
"0.6965445",
"0.696345",
"0.6958611",
"0.69454104",
"0.6944357",
"0.69443506",
"0.69365907",
"0.6922383",
"0.6919671",
"0.6918011",
"0.6913471",
"0.6912719",
"0.6906574",
"0.6901389",
"0.68972737",
"0.68933886",
"0.6892248",
"0.68908024",
"0.68892485",
"0.68873996",
"0.6878379",
"0.68695796",
"0.6869123",
"0.6869123",
"0.6869123",
"0.6866243",
"0.6863846",
"0.686032",
"0.68593174",
"0.68563896",
"0.6851935",
"0.6851087",
"0.68510675",
"0.68468165",
"0.68449044",
"0.6843198",
"0.684271",
"0.6829972",
"0.6825628",
"0.6821192",
"0.68185514",
"0.681662",
"0.68165785",
"0.6815324",
"0.6812465",
"0.6808661",
"0.68086237",
"0.6807813",
"0.6803623",
"0.68021333",
"0.6801543",
"0.67989445",
"0.6796865",
"0.67903006",
"0.6789555",
"0.6788631",
"0.67859226",
"0.6784553",
"0.67830384",
"0.6782715",
"0.67813617",
"0.6779006",
"0.6778628",
"0.6778628",
"0.6776186",
"0.6776186",
"0.6776186",
"0.6776186",
"0.6776186",
"0.67700905",
"0.67700905",
"0.67676395"
] |
0.0
|
-1
|
Hit this endpoint as soon as user logs in If user is already in the database, redirect to team page, otherwise go to edit page
|
def login_check
if not is_logged_in session
# should never get in here
redirect_to :action => :index
end
sunet = session[:user_hash]["username"]
if User.find_by_sunet(sunet)
redirect_to :action => :index
else
# create new user
gn = session[:user_hash]["gn"] || ""
sn = session[:user_hash]["sn"] || ""
phone = session[:user_hash]["phone_number"] || ""
major = session[:user_hash]["org"] || ""
@user = User.new(:sunet => sunet, :first_name => gn.titlecase, :last_name => sn.titlecase, :bio => "I dance for Basmati Raas!", :is_alumni => false, :is_undergrad => true, :phone => phone, :major => major)
@user.save
flash[:notice] = "Welcome! We started filling out your profile. Please upload a picture and update your information."
redirect_to "/users/#{@user.id}/edit"
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def user_belongs_to_team!\n if signed_in? && current_team.present?\n redirect_to root_app_url unless current_team_role\n end\n end",
"def authorized_for_team\n team = Team.find(params[:id]);\n redirect_to root_path unless team.users_ids.include?(current_user.id) || \n current_user.in_tab_room?(team.tournament);\n end",
"def show\n if current_team\n if ! (current_team.email == @team.email)\n redirect_to '/'\n end\n end\n end",
"def show\n redirect_to team_path(@user.team) if @user.team\n end",
"def showUserTeam\n redirect_to team_showUserTeam_path\n end",
"def check_use_team\r\n if !params[:team_id].nil?\r\n users = Team.find_by_id(params[:team_id]).users\r\n if !(users.include?(current_user))\r\n redirect_to frontend_root_path,\r\n notice: \"Team not Assigned\"\r\n end\r\n end\r\n end",
"def edit_before_tournament_starts\n team = Team.find(params[:id])\n redirect_to root_path unless \n (team.users_ids.include?(current_user.id) && \n (team.tournament.status == GlobalConstants::TOURNAMENT_STATUS[:future]))\n end",
"def ensure_correct_user \n # compare some params vs something in the session/current_user\n unless params[:id].to_i == session[:user_id]\n redirect_to all_teams_path, alert: \"Not Authorized\"\n end\n end",
"def check_access(team)\n if !team.is_in?(user)\n flash[:error] = \"Vous ne faites pas partie de cette équipe\"\n redirect_referrer\n end\n end",
"def check_role\n redirect_to root_path unless current_user && current_user.evo_team?\n end",
"def user_edits\n redirect_to home_path if current_user != User.find(params[:id])\n end",
"def authenticate_user!\n if !signed_in?\n session[:user_return_to] = request.path if request.path\n redirect_to \"/auth/githubteammember\"\n end\n end",
"def valid_auth\n if @user.auth == 0\n flash[:warning] = \"Your can not create Team\"\n redirect_to :action => \"index\"\n end\n end",
"def update\n redirect_back fallback_location: root_path unless current_user_admin? || (@user.id == current_user.id)\n\n unless @user\n flash[:alert] = \"We can not find account\"\n return redirect_back fallback_location: root_path\n end\n\n respond_to do |format|\n if @user&.update(user_params)\n\n if @user.user_type == \"team\"\n unless @user.team\n @team = Team.find_by(name: @user.name)\n\n if @team\n return redirect_to should_join_team_path(@team)\n else\n @user.create_team\n end\n end\n end\n\n return redirect_to users_admins_path if current_user_admin?\n format.html { redirect_to events_path, notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def centerleder_access\r\n if current_user.access? :team_new_edit_delete\r\n return true\r\n elsif current_user\r\n puts \"centerleder_access current_user: #{current_user.inspect}\"\r\n flash[:notice] = \"Du har ikke adgang til denne side\"\r\n redirect_to teams_path\r\n else\r\n puts \"centerleder_access NOT LOGGED IN\"\r\n flash[:notice] = \"Du har ikke adgang til denne side\"\r\n redirect_to login_path\r\n end\r\n end",
"def login \n\t\n\t\t# redirect user to their team library if he or she visits the login screen but is already logged in\n\t\tif !session[:user_id].nil?\n\t\t\tredirect_to(:controller => :flash_teams, :action => :index)\n\t\tend\t\t\n\t\t\n\t\t@title = \"Login\"\n\t\t\n\tend",
"def correct_user\n @user = Volunteer.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def set_team\n @contact = Contact.user_scope().find_by(id: params[:id])\n if !@contact.present?\n redirect_to teams_path, :flash => { :error => \"Team member Not Found!\" }\n end\n end",
"def correct_user\n @jogtime = Jogtime.find(params[:id])\n redirect_to(root_url) unless (current_user.id == @jogtime.user_id) || current_user.admin?\n end",
"def correct_user\n unless Presenter.find_by(user_id: current_user) == find_presenter\n if current_user.admin?\n redirect_to edit_presenter_profile_path\n else\n flash[:danger] = \"Unauthorized Access\"\n redirect_to root_url\n end \n end\n end",
"def check_accept_access\n @user_invite = current_user.user_invites.find_by id: params[:id]\n @team = @user_invite&.team\n redirect_back(fallback_location: user_root_path, alert: I18n.t('invites.invalid_permissions')) if @user_invite.nil?\n end",
"def add_to_team\n session[:current_team_id] = Team.find_by(id: params[:id]).id\n redirect_to heros_path\n end",
"def after_sign_in_path_for(_resource)\n if current_user && current_user.sign_in_count == 1\n edit_user_path(current_user)\n elsif current_user.sports.empty? || current_user.goals.empty?\n edit_user_path(current_user)\n else\n root_path\n end\n end",
"def check_current_user\n redirect_to '/' unless @user.id == current_user.id\n end",
"def logged_in\n found_florist = Florist.where(status: \"Active\").where(company_id: params[\"company_id\"]).first \n if found_florist != nil\n found_user = Employee.where(status: \"Active\").where(florist_id: found_florist.id).where(username: params[\"username\"]).first\n if found_user && found_user.authenticate(params[\"password\"])\n session[\"found_user_id\"] = found_user.id\n session[\"found_florist_id\"] = found_florist.id\n redirect_to home_path and return\n else # do nothing\n end\n end\n render(:login, layout:false) and return\n end",
"def redirect_to_user_page\n if teacher_signed_in?\n redirect_to :controller => 'search'\n elsif volunteer_signed_in?\n redirect_to :controller => 'conversations'\n end\n end",
"def new\n respond_to do |format|\n if SimTeam.find_by_user_id( current_user )\n flash[:error] = 'You already own a team.'\n @sim_team = SimTeam.find_by_user_id( current_user )\n format.html { render :action => \"yourteam\" }\n format.xml { render :xml => @sim_team.errors, :status => :unprocessable_entity }\n else\n @sim_team = SimTeam.new\n format.html # new.html.erb\n format.xml { render :xml => @sim_team }\n end\n end\n end",
"def check_auth\r\n if current_user == nil || @user.id != current_user.id\r\n redirect_to root_path , alert: \"Can't Access A Game That Does not belong to you.\"\r\n end\r\n end",
"def authenticate_admin\n if !current_user\n redirect_to \"/auth/google_oauth2\", :id => \"sign_in\" and return\n elsif !Player.exists?(mtu_id: current_user.mtu_id, committee: true)\n if @player\n redirect_to player_path(@player), notice: \"The signed in user account cannot access this resource\" and return\n else\n redirect_to players_path, notice: \"The signed in user account cannot access this resource\" and return\n end\n end\n end",
"def correct_user\n redirect_to(root_url) unless @user == current_user\n end",
"def edit\n redirect_back_or_default(\"/\") if\n !@user&.admin && session[:real_user_id].blank?\n end",
"def show\n authorize @team\n\n add_breadcrumb \"#{@event.code}\", :admin_event_path\n add_breadcrumb \"Equipes\", :admin_event_teams_path\n add_breadcrumb \"#{@team.name}\", :admin_event_team_path\n @team_users = TeamUser.where(team: @team)\n\n end",
"def create\n # Getting the user by mail\n user = User.find_by(email: params[:session][:email].downcase)\n \n # check if we got a user first and then the password is correct\n if user && user.authenticate(params[:session][:password])\n \n # call helper method log_in (se helpers/seesionhelper)\n log_in user\n # Log the user in and redirect to the page with all teams (/teams)\n redirect_to teams_path\n else\n # Create an error message.\n #flash.now is for rendering (lives for the cycle)\n # danger is mapped in the view against bootstraps classes\n flash.now[:danger] = 'Invalid email/password combination'\n # render the layout with the form\n render 'new'\n end\n end",
"def correct_user\n #to define the correct user and omit it when edit and update\n @user=User.find(params[:id])\n redirect_to(root_path) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id])\n # redirect_to(root_url) unless @user == current_user\n redirect_to(root_url) unless current_user?(@user)\n end",
"def logged_in_employer\n\t unless logged_employer_in?\n\t flash[:danger] = \"Proszę się zalogować.\"\n\t redirect_to url_for(controller: 'employers', action: 'create')\n\t end\n\tend",
"def edit_user\n redirect_to(root_url) unless current_user.edit?\n end",
"def corrent_user\n\t@user = User.find(params[:id])\n\tredirect_to(root_url) unless @user == current_user\n\t\t\n\tend",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\nend",
"def correct_user\n @user = User.find(params[:id])\n\n if @user != current_user\n redirect_to(root_path)\n else\n # nothing to do\n end\n end",
"def correct_user\n @user=User.find(params[:id])\n #return to root if user !=current user\n redirect_to(root_url) unless current_user?(@user)\n end",
"def set_team\n @team = Team.find(params[:id])\n unless @logged_in and @logged_in.update_site?\n @team.readonly!\n end\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user # sauf si\n end",
"def correct_user\n \n redirect_to(login_path) unless current_user?(@user)\n end",
"def logged_in_employee\n unless employee_logged_in?\n flash[:danger] = \"You do not have Access\"\n redirect_to employee_login_url\n end\n end",
"def correct_user\n @user = User.find(params[:id])\n #redirect_to root_url unless @user == current_user\n redirect_to root_url unless current_user?(@user)\n end",
"def check_auth\n if current_user.company_id != @company.id && !current_user.manager? && !current_user.admin?\n redirect_to projects_path, :alert => \"Access denied.\" and return\n end\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to '/' unless @user == current_user || current_user.isadmin?\n end",
"def teams\n redirect_to navigation_teams_path\n end",
"def correct_user\n @admin = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@admin)\n end",
"def edit\n if current_user.access == 2\n redirect_to \"/users/indexU\"\n end\n end",
"def correct_user\n @user=User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n \n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id]) if User.exists?(params[:id])\n redirect_to(edit_user_path(current_user)) unless current_user == @user\n end",
"def correct_user\n @person = Person.find(params[:id])\n redirect_to(root_url) unless current_user?(@person)\n end",
"def correct_user\n @user = User.find(params[:id])\n #render :json => { :updated? => false, :status => 200, :message => \"You are not allowed edit other users.\" } unless @user == current_user\n redirect_to(root_url) unless @user == current_user\n end",
"def check_if_user_is_team_leader?\n render json: [\"Only the Team Lead can edit this team\"], status: 422 unless current_user.id == this_team.user_id;\n end",
"def edit\n return redirect_to(@user) if @user != current_user\n end",
"def show\n self.current_user\n \n if not @current_user\n redirect_to login_path\n else\n render :action => 'edit'\n end\n end",
"def check_use\r\n if !(params[:id]).nil?\r\n if !((Team.find_by_id(TodoList.find_by_id(params[:id]).team_id).users).include?(current_user))\r\n redirect_to frontend_root_path,\r\n notice: \"You cannot see Todo List\"\r\n end\r\n end\r\n end",
"def correct_user\n @grouping = Grouping.find(params[:id])\n redirect_to(root_url) unless current_user == @grouping.user\n end",
"def admin\n if user_signed_in?\n \t redirect_to members_url\n \telse\n \t redirect_to new_user_session_path\n \t end\n \n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n \n end",
"def accept\n if @user_request.user_on_team?\n redirect_back(fallback_location: user_root_path, alert: I18n.t('requests.accepted_another'))\n elsif @user_request.accept\n redirect_to user_root_path, notice: I18n.t('requests.accepted_successful')\n else\n redirect_back(fallback_location: user_root_path, alert: I18n.t('requests.too_many_players'))\n end\n end",
"def correct_user\n\t\t\tif !current_user?(@user) && !current_user.orgadmin?\n\t\t\t\tredirect_to(users_path)\n\t\t\tend\n\t\tend",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def set_idea\n if user_signed_in?\n @idea = Idea.find(params[:id])\n if !@idea.blank?\n if @idea.user_id != @current_user.id\n redirect_to inicio_path, alert: 'acceso denegado para este user'\n end \n else \n redirect_to inicio_path, alert: 'pagina no encontrada'\n end \n else\n redirect_to registrar_path, alert: 'Primero debe estar registrado'\n end \n end",
"def team\n @team = :true\n render '/home/landing'\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def verify_team\n set_team_from_team_id\n unless ( @team )\n flash[:error] = I18n.t(:invalid_action_request) + ' - ' + I18n.t('meeting.errors.missing_team_id')\n redirect_to( meetings_current_path() ) and return\n end\n end",
"def correct_user\n\t\t@project = Project.find(params[:id])\n\t\tredirect_to(root_url) unless current_user.id === @project.owner_id || current_user.admin?\n\trescue ActiveRecord::RecordNotFound\n\t\tredirect_to projects_path\n\tend",
"def correct_user\n @user = User.find_by(id: params[:id])\n redirect_to(root_url) unless @user == current_user\n end",
"def authenticate_correct_user\n redirect_unauthorized unless current_user? @run.user_id\n end",
"def correct_user\n @user = User.find(session[:user_id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def switch\n authorize!(:manage, :all)\n user = User.find_by(login: params[:login].upcase)\n if user\n session[:original_user_id] = session[:user_id]\n session[:user_id] = user.id\n redirect_to root_url, notice: \"Sie sind nun der Nutzer mit dem Login #{user.login}.\"\n else\n redirect_to root_url, notice: \"Der Nutzer existiert nicht im System.\"\n end\n end",
"def login(auth)\n if student = Student.find_by(linkedin_uid: auth.uid)\n login_as(student)\n redirect_to team_path\n else\n redirect_to login_path, notice: \"You haven't joined a competition yet. Please follow the link your professor gave you to join.\"\n end\n end",
"def user\n\t\tif current_user.account_type != Account.roles[:user]\n\t\t\tredirect_to root_url\n\t\tend\n\tend",
"def correct_user\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_url) unless current_user?(@user)\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(root_path) unless (current_user.id == @user.id)\n end",
"def teamowner_information \n team = Team.find_by_event_id(params[:event_id])\n if team != nil\n @teamowner = Team.find_teamowner(team.id)\n @initial_level = team.initial_level\n else\n flash[:notice] = \"Create a team to be an owner!\"\n flash.now\n redirect_to :controller => 'teams', :action => 'teamowner_information', :notice => \"Create a team to be an owner!\"\n end\n\n end",
"def correct_user\n @user = User.find(params[:id])\n redirect_to(user_root_path,:notice => 'You cannot access this page') unless current_user == @user\n end",
"def index\n\n Planout.instance.info()\n\n @user = User.authenticate('alex', 'wja0DjFEGd9D')\n # if @user = User.authenticate('alex', 'wja0DjFEGd9D')\n # if @user = User.authenticate('kriztean', 'strewersk62S?')\n session[:user_id] = @user.id\n # else\n # puts \"Invalid username/password.\"\n # end\n\n redirect_to new_participant_path\n\n end",
"def loged?\n @user = current_user\n if not @user\n redirect_to welcome_index_path\n end\n end",
"def set_user\n @user = User.find_by_id(params[:id])\n require_same_user\n #redirect_to signin_path unless @user #for a route that does not exist redirect it back to home page\n end",
"def correct_user\n\t\t\t@user = User.find(params[:id])\n\t\t\tredirect_to(root_url) unless @user == current_user\n\t\tend"
] |
[
"0.7867253",
"0.7324328",
"0.7126531",
"0.7037571",
"0.6980072",
"0.69788986",
"0.6948538",
"0.68844736",
"0.6879058",
"0.6777168",
"0.6645534",
"0.65735555",
"0.65341973",
"0.6511264",
"0.64719826",
"0.64637256",
"0.64619684",
"0.6449182",
"0.64353603",
"0.6433088",
"0.6420037",
"0.64110297",
"0.64108557",
"0.637596",
"0.6365272",
"0.6365025",
"0.6332244",
"0.6330185",
"0.6326866",
"0.6323087",
"0.63088864",
"0.6294828",
"0.62812084",
"0.6279677",
"0.6275352",
"0.6239084",
"0.6227567",
"0.6224511",
"0.62245005",
"0.6210702",
"0.62068546",
"0.62064433",
"0.6205413",
"0.6203907",
"0.6199083",
"0.6194822",
"0.61922145",
"0.6185177",
"0.6181065",
"0.6178761",
"0.61778235",
"0.6177813",
"0.6175173",
"0.6174231",
"0.6173911",
"0.61673796",
"0.6167287",
"0.61660975",
"0.6160648",
"0.615916",
"0.61497235",
"0.6147561",
"0.6146213",
"0.6139667",
"0.61377805",
"0.6137603",
"0.61344135",
"0.6134336",
"0.6130766",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.6130593",
"0.61288387",
"0.61288387",
"0.61266387",
"0.61235934",
"0.61211973",
"0.61205095",
"0.6119544",
"0.6117155",
"0.6112325",
"0.61120373",
"0.61108714",
"0.6110275",
"0.6107256",
"0.61038727",
"0.6100761",
"0.60996115",
"0.60971534",
"0.60938895",
"0.6091429",
"0.607986",
"0.6076743",
"0.6071917",
"0.6069241"
] |
0.0
|
-1
|
POST: create a new user
|
def create
@user = User.new(params[:user])
if @user.valid?
@user.save
flash[:notice] = "Successfully created new member!"
redirect_to :action => :show, :id => @user.id
else
flash[:alert] = "There was an error in validating the new member"
render :action => :new
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def create_user(body)\n post 'create_user', body\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_user(options = {})\n post \"/users\", options\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 = 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 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 if @user.save\n redirect_to users_path\n else\n redirect_to new_user_path\n end\n end",
"def create\n @user = User.new(user_params)\n\n # save was requested by either current_user or else must be a new registration\n if @user.save(current_user)\n redirect_to users_path\n else\n render('new', status: :unprocessable_entity)\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 @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\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 create\n\t\t\t\t@user = User.create!(create_user_params)\n\t\t\tend",
"def create\n raise\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'Usuário foi inserido com sucesso' }\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 \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.create(user_params)\n render json: user, message: 'user succefully create', status: 200\n end",
"def create\n @new_user = NewUser.new(new_user_params)\n\n respond_to do |format|\n if @new_user.save\n format.html { redirect_to @new_user, notice: 'New user was successfully created.' }\n format.json { render :show, status: :created, location: @new_user }\n else\n format.html { render :new }\n format.json { render json: @new_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n redirect_to @user, notice: 'Se creo un usuario exitosamente.'\n else\n render :new\n end\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",
"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.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 @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 \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(params:)\n parse(JSON.parse(connection.post(\"users\", params.to_json).body))\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)\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(params[:user])\n\t\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\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(user_params)\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 }\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_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_user\n fake_password = Faker::Internet.password\n params = {\n user: {\n username: Faker::Internet.user_name,\n email: Faker::Internet.email,\n password: fake_password,\n password_confirmation: fake_password\n }\n }\n post signup_post_url, { params: params }\n params[:user]\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 user = User.new(user_params)\n msg = if user.save\n 'User has successfully created.'\n else\n set_error(:unprocessable_entity, user)\n end\n common_response(msg, user: user)\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(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.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\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\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 @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to root_url, notice: 'Usuário criado com sucesso.' }\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(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 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.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to root_path, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :created}\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 # TODO: かっこをつけたい\n @user = User.new user_params\n\n # TODO: !をつけたらraiseでこけるのでは\n unless @user.save\n # TODO: locale見当たらない\n render json: { error: t(\"user_create_error\") }, status: 400\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n redirect_to users_path, notice: \"ユーザが保存されました\"\n else\n render :new\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 @user, 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 logger.debug(\"user create\")\n @user = User.new(params[:user])\n respond_to do |format|\n if @user.save\n format.html { redirect_to home_path, 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 #o usuário está sendo criado no devise registration.\n\t\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\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 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(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(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_user\n @user = User.new(params[:user])\n @user.save\n \n redirect_to :action => :users\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(params[:user])\n\n if @user.save\n flash[:notice] = t('users.create.notice')\n redirect_to users_path\n else\n render :action => \"new\"\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 @user }\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 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 name = params[:name]\n email = params[:email]\n password = params[:password]\n new_user = User.create!(\n name: name,\n email: email,\n password: password,\n )\n\n response = \"Hey #{name}, You are registered successfully!\"\n render plain: response\n end",
"def create\n @user = User.new(user_params)\n # Senha padrao = matricula\n @user.password = @user.matricula\n @user.password_confirmation = @user.matricula\n @user.admin = false\n\n # Usuario comum so pode criar usuarios em sua propria unidade\n unless current_user.admin?\n @user.unidade_id = current_user.unidade_id\n end\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'Usuário criado com sucesso.' }\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 if @user.save\n redirect_to user_path(@user)\n else\n render :new\n end\n end",
"def create\n @user = User.new(user_attributes)\n if @user.save\n created(@user)\n else\n validation_errors(@user)\n end\n end",
"def create\n @user_user = User::User.new(user_user_params)\n\n respond_to do |format|\n if @user_user.save\n format.html { redirect_to @user_user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user_user }\n else\n format.html { render :new }\n format.json { render json: @user_user.errors, status: :unprocessable_entity }\n end\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.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)\n\n if @user.save\n render :show, status: :created\n else\n render json: { errors: @user.errors }, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(params[:user])\n if @user.save\n redirect_to users_path, notice: t('users.update.updated')\n else\n @page_title = t(\"actions.new_user\")\n render action: 'new'\n end\n end",
"def create\n\t\t@user = User.new(user_params)\n\t\t\n\t\tif @user.save\n\t\t\tredirect_to users_path\n\t\telse\n\t\t\trender 'new'\n\t\tend\n\tend",
"def create\n\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\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to edit_user_url(@user), notice: 'User was successfully created.' }\n format.json { render :edit, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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 @user, 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"
] |
[
"0.81716645",
"0.81304353",
"0.80620456",
"0.799887",
"0.79771715",
"0.7946712",
"0.7925822",
"0.79162335",
"0.78986996",
"0.78957283",
"0.7887921",
"0.7886165",
"0.78803355",
"0.7870509",
"0.7867123",
"0.78627205",
"0.78584355",
"0.7851147",
"0.78419894",
"0.7840443",
"0.7840048",
"0.7836735",
"0.783346",
"0.7830048",
"0.78275466",
"0.7826966",
"0.7823957",
"0.7821881",
"0.78197736",
"0.7817345",
"0.78157353",
"0.78133625",
"0.781332",
"0.78093654",
"0.78078175",
"0.78014505",
"0.78007114",
"0.77923095",
"0.7791616",
"0.7790095",
"0.7787328",
"0.7785195",
"0.77793527",
"0.77685726",
"0.7767342",
"0.77672553",
"0.77670443",
"0.77667916",
"0.7758885",
"0.7756382",
"0.7752386",
"0.7749224",
"0.77451783",
"0.77418965",
"0.77418965",
"0.77418965",
"0.77413195",
"0.773864",
"0.77380824",
"0.773409",
"0.77310956",
"0.7730006",
"0.7730006",
"0.7729377",
"0.77275944",
"0.77260834",
"0.7725219",
"0.7721976",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518",
"0.7718518"
] |
0.0
|
-1
|
Show member of specific id
|
def show
@user = User.find_by_id(params[:id])
respond_to do |format|
format.html
format.json { render json: @user.to_json(:methods => [:avatar_url]) }
end
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def show_member\n @member = Member.find(params[:id])\n end",
"def show\n #@member= Member.find(params[:member_id])\n end",
"def show\n #@member= Member.find(params[:member_id])\n end",
"def show\n #@member= Member.find(params[:member_id])\n end",
"def show\n \t@member= Member.find(params[:member_id])\n\tend",
"def find_member\n @member = Member.find(params[:id])\n end",
"def index\n @member = Member.find(params[:member_id])\n end",
"def member(id)\n space_memberships.find_by(user_id: id)\n end",
"def member(member_id, &block)\n get \"/member/#{member_id}/\", nil, &block\n end",
"def show\n @member = Member.find_by_url(params[:id])\n @member = Member.find_by_url_or_id(params[:id]) if @member.nil?\n end",
"def find_member_by_id(id)\n @board.members.find { |m| m.id == id }\n end",
"def set_member\n @member = @account.members.find(params[:id])\n end",
"def show\n redirect_to useradmin_members_path(params[:id])\n end",
"def set_member\n @member = Member.friendly.find(params[:id])\n end",
"def set_member\n @member = @space.members.friendly.find(params[:id])\n end",
"def set_member\n @member = User.find(params[:id])\n end",
"def set_member\n @member = User.find(params[:id])\n end",
"def show\n\t\t@member = Member.find(params[:id])\n\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml\t{ render :xml => @member }\n\t\tend\n\tend",
"def set_member\n @member = Member.find(params[:id])\n end",
"def show\n @member = Member.find(params[:id])\n raise CanCan::AccessDenied if cannot? :show, @member\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @member }\n end\n end",
"def set_member\n member_id = params[:id]\n @member = Member.find(member_id)\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def set_member\n @member = Member.find(params[:id])\n end",
"def show\n @who_member = WhoMember.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @who_member }\n end\n end",
"def set_member\n\t\t\t\t@member = Member.find(params[:id])\n\t\t\tend",
"def get_member(id)\n is_admin? ? ::Refinery::Memberships::Member.find(id) : current_refinery_user\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @member }\n end\n end",
"def member\n Member.find(id) if auth == 'customer'\n end",
"def set_member\n @member = @current_enterprise.members.find(params[:id])\n end",
"def show\n @member = Member.find(params[:id])\n\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @member.to_xml }\n end\n end",
"def show\n @member = Member.find(params[:id])\n @title = \"#{@member.last_name} #{@member.given_names}\"\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def show\n @aiit_member = AiitMember.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @aiit_member }\n end\n end",
"def set_member\n @member = Member.find(params[:member_id])\n end",
"def show\n # GET /gym_members/:id\n @gym_member = GymMember.find(params[:id])\n render :show\n end",
"def get_members_by_id\n return filter_by_id(get_members) \n end",
"def show\n @group_member = GroupMember.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @group_member }\n end\n end",
"def show\n @group_member = GroupMember.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @group_member }\n end\n end",
"def set_member\n if current_member \n @member = Member.find(current_member.id)\n else \n @member = Member.find(params[:id])\n end\n end",
"def show\n\tif !checklogin? then return end\n\t\n\t@me = me?\n @member = Member.find(params[:id])\n\n\tfrs = Friend.where(:member_id => params[:id].to_i)\n\tfrlist = '('\n\tfrs.each do |fr|\n\t\tfrlist += fr.friend_id.to_s + ','\n\tend\n\tfrlist += '0)'\n\n\tquery = \"select * from members where id in \" + frlist\n\t@friends = Member.find_by_sql(query)\n\n\t@isFr = Friend.where(:member_id => session[:login].id, :friend_id => params[:id].to_i).count > 0\n\t@isFded = Friend.where(:friend_id => session[:login].id, :member_id => params[:id].to_i).count > 0\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member }\n end\n end",
"def member\n Member.find(@member.name)\n end",
"def show(id)\n response = request(:get, \"/users/#{id}.json\")\n response.first[1]\n end",
"def show\n @member = Member.find(params[:id])\n #@members = Member.paginate(:page => params[:page])\n @title = @member.last_name\n #respond_to do |format|\n # format.html # show.html.erb\n # format.xml { render :xml => @member }\n #end\n end",
"def show\n @membership = Membership.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @membership }\n end\n end",
"def show\n @clnmember = Clnmember.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clnmember }\n end\n end",
"def show\n @member_info = MemberInfo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @member_info }\n end\n end",
"def team_members(id)\n get \"/teams/#{id}/members\"\n end",
"def show\n @member = Member.find(params[:id])\n @warband = @member.warband\n @user = @warband.user\n @items = @member.items\n @title = @member.name\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @member }\n end\n end",
"def show\n\t\tthe_user_id = params[\"id\"]\n \t@user = User.find_by :id => the_user_id\n\tend",
"def has_member(id)\n return get_members_by_id.include? id\n end",
"def show\n\t\t@membership = Membership.find(params[:id])\n\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml\t{ render :xml => @membership }\n\t\tend\n\tend",
"def edit\n @member = TeamMember.find(params[:id])\n end",
"def set_user_member\n @user_member = User::Member.find(params[:id])\n end",
"def show\n @membership = Membership.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @membership }\n end\n end",
"def show\n @family_member = FamilyMember.find(params[:id])\n \n unless @current_family.member?(@family_member)\n flash[:warning] = \"Requested family member is not a member of your family\"\n redirect_to show_family_members\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @family_member }\n end\n end",
"def show\n @beer_club = BeerClub.find(params[:id])\n if(not current_user.nil?)\n memberships=Membership.where(user_id: current_user.id, beer_club_id: params[:id])\n @membership=(memberships.empty? ? nil : memberships.first)\n else\n @membershi=nil\n end\n end",
"def show\n @member_type = MemberType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @member_type }\n end\n end"
] |
[
"0.83190507",
"0.8069731",
"0.8069731",
"0.8069731",
"0.80090594",
"0.77733344",
"0.76382697",
"0.7570597",
"0.7547313",
"0.74561846",
"0.74422973",
"0.74326307",
"0.741494",
"0.73638237",
"0.7360886",
"0.7304635",
"0.72994685",
"0.7287684",
"0.7284234",
"0.7277855",
"0.72530353",
"0.72530353",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.724537",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.7229584",
"0.72280055",
"0.72185045",
"0.7206175",
"0.72027427",
"0.72027427",
"0.72027427",
"0.72027427",
"0.72027427",
"0.71681786",
"0.71151084",
"0.7091898",
"0.70830995",
"0.7040639",
"0.70388496",
"0.70324373",
"0.69413453",
"0.6930804",
"0.69171834",
"0.6917176",
"0.6887088",
"0.6873932",
"0.6873932",
"0.6872494",
"0.6868384",
"0.68655646",
"0.68182695",
"0.67896175",
"0.6787808",
"0.67758703",
"0.6768215",
"0.6766868",
"0.6764303",
"0.67559755",
"0.67445403",
"0.6737364",
"0.6723926",
"0.67199624",
"0.669826",
"0.6695217",
"0.66839087",
"0.6680233"
] |
0.0
|
-1
|
return an HTML form for editing a user
|
def edit
@user = User.find_by_id(params[:id])
logged_in_user = session[:user_hash]["username"]
if logged_in_user != @user.sunet and not
User.is_power_user(logged_in_user)
# permission denied
flash[:error] = "Your privileges don't allow you to edit profiles other than your own."
redirect_to "/users#/users/"
end
@photos = Photo.find_all_by_user_id(params[:id])
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def edit\n # return an HTML form for editing a specific user\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n # just show me the form\nend",
"def edit\n @user = User.find(params[:id])\n\t case params[:form]\n\t when \"email\"\n\t render 'email'\n\t when \"password\"\n\t render 'password'\n\t else\n\t render :action => :edit\n\t end\n\tend",
"def edit\n # find the user we want to edit by id\n # this will send the @user to the edit page with a form\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n @form_id = 'edit-form'\n \n respond_to do |fmt|\n fmt.html { render partial: 'form' }\n fmt.json { render json: @user }\n end\n end",
"def edit\n\t@user = User.find(params[:id])\n\t@title = \"Edit user\"\n end",
"def edit\n #similar to the NEW action, but instead of create a empty user, we will find a user by its id and than\n # send its params to the partial form, so the params can be edited. Please note the partial form\n # for details, as the column admin can be edited only buy logged users with admin privileges.\n #@user variable will be used in the partial form, when submitted goes to UPDATE action.\n @user = User.find(params[:id])\n #only admin can edit other users information, so we first check if the user is admin.\n unless current_user.admin?\n #if the user is not admin it can edit only its own information, so we redirect to edit its own information\n unless @user.id == current_user.id\n redirect_to edit_user_path (current_user)\n end\n end\n end",
"def edit\n load_user\n return if (@user.blank?)\n\n respond_to do|format|\n format.html\n end\n end",
"def edit(id)\n @user = flash[:form_data] || User[id]\n\n if @user.nil?\n flash[:error] = 'The specified user is invalid'\n redirect_referrer\n end\n\n @title = \"Edit #{@user.username}\"\n\n render_view(:form)\n end",
"def edit_external_user\n render partial: 'form'\n end",
"def edit\n @page_title = 'Edit user'\n @user = User.find(params[:id])\n end",
"def edit\n set_user\n end",
"def edit\n get_user_for_edit\n end",
"def edit\n # When a http GET request to '/users/1/edit' is received, have it render:\n # a view file with a form with user 1's information in the appropriate input field.\n @id = params[:id]\n @user = User.find(@id)\n end",
"def edit\n \n @user = User.find(params[:id])\n \n end",
"def edit\n @user = current_user\n render 'edit'\n end",
"def edit\n\t\tthe_user_id = params[\"id\"]\n \t@user = User.find_by(:id => the_user_id)\n\tend",
"def edit\n @user = @current_user \n # render :new \n end",
"def edit\n # @user = User.find(params[:id]) -- not needed bc of correct_user\n end",
"def edit\n @user = User.find(params[:id])\n # @user は編集対象のユーザー\n # current_user はログインしているユーザー \n\n end",
"def edit\n # this finds the current user\n @user = User.find params[:id]\n end",
"def edit\r\n @user = current_user\r\n render :layout=>false\r\n end",
"def edit\n @userToEdit = User.find(params[:id])\n end",
"def edit\r\n \t@user = current_user\r\n end",
"def edit\n\t\t@user = User.find(params[:id])\n\tend",
"def edit\n\t\t@user = User.find(params[:id])\n\tend",
"def edit\n\t\t@user = User.find(params[:id])\n\tend",
"def edit\n\t\t@user = User.find(params[:id])\n\tend",
"def edit \t\t\t\t\t\t\t #render user page \n \t@user = User.find(session[:user_id])\n end",
"def edit_form\n\t\toptions = { :disabled => false, :show_all => true, :edit => true}\n\t\tform_template(options)\n\tend",
"def edit_form\n\t\toptions = { :disabled => false, :show_all => true, :edit => true}\n\t\tform_template(options)\n\tend",
"def edit\n @user = current_user\n end",
"def edit\n @title = \"Edit user\"\n @user = User.find(params[:id])\n\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n \t@user = User.find params[:id]\n end",
"def edit\n @user = User.find(params[:user_id])\n end",
"def edit\n @user = User.find(params[:user_id])\n end",
"def edit\n\t@user = User.find(params[:id])\nend",
"def edit\n # Renders the edit form\n end",
"def edit\n # return an HTML form for editing a specific message\n end",
"def edit\n # return an HTML form for editing a specific message\n end",
"def edit\n @user = User.find params[:id]\n end",
"def edit\n # finds user with id of params[:id]\n @user = User.find params[:id]\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit\n\t\t@user = User.find(params(:id))\n\tend",
"def edit\n \t@user = current_user\n end",
"def edit\n require_user\n end",
"def edit_profile\n \t@user = UsersService.findUserById(params[:id])\n \tuser = UsersService.findUserById(params[:id])\n \t@user_profile_form = UserProfileForm.new(UserProfileForm.attributes(user, :edit_profile))\n end",
"def edit\n # return an HTML form for editing a specific message\n end",
"def edit\n # loads user from the database\n @user = User.find(params[:id])\n end",
"def edit\n @user= User.find_by_id(current_user.id)\n end",
"def edit\n @user = User.find(params[:id])\n end",
"def edit_current_user\n end",
"def edit\n @user = User.find(session[:user_id])\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end",
"def edit\n @user = current_user\n end"
] |
[
"0.81796855",
"0.7678685",
"0.75893253",
"0.7582822",
"0.7542097",
"0.743943",
"0.7439329",
"0.7428165",
"0.7335785",
"0.7288829",
"0.7288553",
"0.7265764",
"0.72639525",
"0.72576153",
"0.72407615",
"0.7223522",
"0.7203743",
"0.7183108",
"0.7176013",
"0.716137",
"0.71435434",
"0.7138151",
"0.713651",
"0.71274376",
"0.71031845",
"0.71031845",
"0.71031845",
"0.71031845",
"0.70723134",
"0.7069834",
"0.7069834",
"0.70608014",
"0.70560503",
"0.70463926",
"0.70463926",
"0.70461076",
"0.70425797",
"0.70425797",
"0.7030627",
"0.7028798",
"0.7025167",
"0.7025167",
"0.70220107",
"0.70084536",
"0.69953835",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6981879",
"0.6977992",
"0.6977723",
"0.69419104",
"0.6932288",
"0.69299686",
"0.69273955",
"0.69263816",
"0.69208944",
"0.69189215",
"0.69108844",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316",
"0.69066316"
] |
0.0
|
-1
|
PUT: update a specific user
|
def update
@user = User.find_by_id(params[:id])
if @user.update_attributes(params[:user])
flash[:notice] = "Updated member!"
else
flash[:alert] = "Unable to update member."
end
redirect_to "/users#/users/#{@user.id}"
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def update_user(user, options = {})\n put \"/users/#{user}\", options\n end",
"def modify_user(user)\n query_api_object Model::User, '/rest/user', user.to_hash, 'PUT'\n end",
"def modify_user(user)\n query_api_object User, \"/rest/user\", user.dump(), \"PUT\"\n end",
"def update_user(options)\n patch(\"/user\", options, 3)\n end",
"def updateUser\n options = {\n :body => params.to_json,\n :headers => {\n 'Content-Type' => 'application/json',\n 'Authorization' => request.headers['Authorization']\n }\n }\n results = HTTParty.put(\"http://192.168.99.101:4051/users/\"+@current_user[\"id\"].to_s, options)\n render json: results.parsed_response, status: results.code\n end",
"def update\n @user = current_user\n if @user.update(update_user_params)\n render 'api/v1/users/show'\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n user = find_user\n user.update!(user_params)\n render json: user\n end",
"def update_user(**params)\n params.merge!(id: existing_user.id)\n api_query(query, variables: params)\n end",
"def update_user(id, accountId, model) path = \"/api/v2/accounts/#{accountId}/users/#{id}\"\n put(path, model, {}, AvaTax::VERSION) end",
"def update\n @user = current_org.users.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, 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 edit\n @user = User.find(params[:id])\n @user.update(user_params)\n end",
"def update\n @user = current_api_user\n unless @user.update(user_params)\n render json: { error: @user.errors.full_messages.to_sentence }, status: :not_found\n end\n end",
"def UpdateUser params = {}\n \n APICall(path: 'users.json',method: 'PUT',payload: params.to_json)\n \n end",
"def update\n @user.update(user_params_update)\n json_response(@user)\n end",
"def update\n\t\t@user = User.find(params(:id))\n\t\t@user.update(user_params)\n\tend",
"def put user_id, options={}, headers={}\n @connection.put \"users/#{user_id}.json\", options, headers\n end",
"def update\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: 'user was successfully updated.' }\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_user\n @user = User.find(params[:id])\n if @user.update(user_params)\n head :no_content\n else\n render json: @user.errors, status :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update user_params(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update_user(user_id, attributes)\n put(\"/v1/users/#{user_id}\", attributes)\n end",
"def update\n @user = User.update(params[:user])\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update(user_params(params[:user]))\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n end",
"def update\n if @user.update_attributes(user_params)\n head :ok\n else\n head :internal_server_error\n end\n end",
"def update\n # not_found unless @user\n # @user = User.get(params[:id]) || not_found\n\n respond_to do |format|\n if @user.update(params[:user])\n format.html { redirect_to @user, :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 update\n authorize! if @user != current_user\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @user.update(user_params)\n respond_with(@user, location: users_url, notice: 'User was successfully updated.')\n else\n respond_with(@user)\n end\n end",
"def update\n # find and update a specific user\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User updated'\n redirect_to users_path\n else\n flash[:error] = 'Update error'\n render :action => \"edit\", :id => @user\n end\n end",
"def update\n @user = User.find(params[:id])\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.json { head :ok }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.shod(params[:id])\n if @user.update(user_params)\n flash[:notice] = t('user_update')\n redirect_to user_path(@user)\n else\n render 'edit'\n end\n end",
"def update\n @user = User.update(user_params)\n end",
"def update\n if params[:id]\n @user = User.find(params[:id])\n else\n @user = current_user\n end\n\n respond_to do |format|\n if @user.id == current_user.id and @user.update_attributes(User.from_params(params))\n format.json { head :no_content }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @user.update(user_params)\n redirect_to edit_user_path (@user)\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = find_user(params[:username])\n\n if @user.update(user_params, current_user)\n redirect_to users_path\n else\n render('edit', status: :unprocessable_entity)\n end\n end",
"def update\n @user = User.find(params[:id])\n @user.update_attributes(params[:user])\n respond_with @user\n end",
"def update\n @user = User.find(params[:id])\n @user.update_attributes(params[:user])\n respond_with @user\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update_attributes(params[:user])\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update_user\n user = current_user\n if user.update(update_params)\n render json: { status: { updated: \"Ok\" } }\n else\n render json: user.errors.full_messages\n end\n end",
"def update\n @user = User.find(params[:id]) \n \n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to users_url, notice: 'User #{@user.name} was successfully created.' }\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 authorize @user\n respond_to do |format|\n if @user.update(permitted_attributes(@user))\n format.html { redirect_to edit_user_path(@user), notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_user\n end",
"def update\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: '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 update\n @user = User.find(params[:id])\n\n if @user.update(user_params)\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n \n respond_to do |format|\n if @user.update_attributes(user_params)\n format.html { redirect_to @user, 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 update\n if current_user != @user\n redirect_to users_path\n end\n\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\n format.json { render :show, status: :ok, location: @user }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @user.update(user_params)\n render json: @user, status: :ok, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = get_user(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to root_url, notice: \"User #{@user.login_name} 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 = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\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: 'User was successfully updated.' }\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\n if @user.id == current_api_user.id\n if @user.update(user_params)\n render json: @user.as_json(except: [:updated_at]), status: :ok\n else\n render json: @user.errors, status: :bad_request\n end\n else\n render json: '', status: :forbidden\n end\n end",
"def update\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_path(@user), 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 update\n @user = User.find(current_identity.user_id)\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, 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 update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to edit_user_path(@user), :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 update\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 => 'User was successfully updated.' }\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\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { render action: \"edit\"}\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 \n end",
"def update\n \t@user = User.find params[:id]\n\n \tif @user.update_attributes(user_params)\n \t\tredirect_to users_path, status: 303\n \telse\n \t\trender :edit\n \tend\n end",
"def update_user(user_name:, user:)\n validate_user_name(:user_name, user_name)\n response = wrap_response(@connection.put(user_path(user_name), user))\n\n response.fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n flash[:notice] = \"User #{@user.username} successfully updated!\"\n format.html { redirect_to @user }\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\n # finds user with id of params[:id]\n @user = User.find params[:id]\n\n # updates the attributes of this user to whatever values are stored in\n # params[:user]\n @user.update params[:user]\n\n # redirect to edit action\n redirect_to edit_user_path\n end",
"def update\n @user.update(user_params)\n respond_with @user\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to request.referer, 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 update\n authorize @user\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\n format.json { render json: @user, status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if user.update(user_params)\n render json: user\n else\n render json: {errors: \"Cannot create user\"}, :status => 420\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to \"/users/#{session[:user_id]}\", 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 update\n @user = User.find(params[:id])\n authorize! :update, @user, :message => 'You are not authorized to perform this operation.'\n if @user.update_attributes(params[:user])\n redirect_to user_path(@user), :notice => \"You updated your account successfully. #{undo_link}\"\n else\n redirect_to user_path(@user), :alert => \"Unable to update user.\"\n end\n end",
"def update\n @user = User.find(params[:id])\n if @user.update(user_params(params))\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update(user_params(params))\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n if @user.update(user_params(params))\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = User.find(params[:id])\n\n respond_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 update\n @user = User.find(params[:id])\n if @user.update_attributes(params.require(:user).permit(:username, :email))\n redirect_to users_path\n else\n render 'edit'\n end\n end",
"def update\n @user = current_user\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, 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 update\n @user = User.find(current_user.id)\n if @user.update_attributes(user_params)\n redirect_to account_url, flash: { success: t(:update_user_success) }\n else\n render 'edit'\n end\n end",
"def update\n @user = User.find(params[:id])\n authorize @user\n\n if @user.update(user_params)\n head :no_content\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n @user = selected_user\n if @user.update(users_params)\n render 'api/users/show'\n else\n render json: @user.errors.full_messages, status: 422\n end\n end",
"def update\n if @user.update(user_params)\n render json: @user, status: :ok\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @user.update(user_params)\n render json: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @user.update(user_params)\n render json: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def update\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: 'User was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user, status: :unprocessable_entity }\n end\n end\n end",
"def update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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 update\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: '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"
] |
[
"0.8188249",
"0.79777175",
"0.79269505",
"0.7790269",
"0.7656797",
"0.7623427",
"0.7560168",
"0.75147706",
"0.7496502",
"0.74697775",
"0.7469062",
"0.7466979",
"0.74541116",
"0.74526423",
"0.7443641",
"0.7431003",
"0.74265105",
"0.7415451",
"0.74102616",
"0.74073523",
"0.7396302",
"0.73947006",
"0.73876864",
"0.73852575",
"0.73549217",
"0.7347415",
"0.7344801",
"0.73262274",
"0.732543",
"0.7323021",
"0.7322389",
"0.73199147",
"0.73187804",
"0.7317564",
"0.73172",
"0.73156613",
"0.73156613",
"0.73013574",
"0.73013574",
"0.7283921",
"0.72812855",
"0.7280558",
"0.7278423",
"0.7275118",
"0.72748375",
"0.7273644",
"0.72726196",
"0.72671664",
"0.7259884",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72564536",
"0.72539264",
"0.72536665",
"0.72513175",
"0.7250761",
"0.72505116",
"0.72490865",
"0.7243845",
"0.72418606",
"0.7237818",
"0.7235393",
"0.723317",
"0.72324497",
"0.7231026",
"0.723053",
"0.72287714",
"0.72284794",
"0.72274554",
"0.7222621",
"0.7222621",
"0.72215664",
"0.72212327",
"0.7219394",
"0.72170985",
"0.7216056",
"0.7215739",
"0.72129613",
"0.720902",
"0.720902",
"0.7207529",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656",
"0.7206656"
] |
0.0
|
-1
|
DELETE: delete a specific user
|
def destroy
User.destroy(params[:id])
flash[:notice] = "Deleted member!"
redirect_to :action => :index
end
|
{
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
[
"def delete_user\n client.delete(user)\n end",
"def delete_user\n end",
"def delete_user(user)\n delete user_path(user)\n end",
"def delete(user_id)\n self.class.delete(\"/#{@api_ver}/users/#{user_id}\", default_options_to_merge_with)\n end",
"def delete_user(id)\n get_user_byid(id).destroy\n end",
"def delete_user(id)\n @user = User.destroy(id)\n end",
"def delete user_id, options={}, headers={}\n @connection.delete \"users/#{user_id}.json\", options, headers\n end",
"def delete_user(id)\n elektron_identity.delete(\"users/#{id}\")\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def delete\n @user = User.find(params[:id])\n end",
"def delete_user(user_id:, params:)\n connection.delete(\"users/#{user_id}\", params).body\n end",
"def delete\n @user = User.find(params[:id])\n @user.delete\n redirect_to root_path\n end",
"def delete\n connection.delete_user id\n nil\n end",
"def user_delete(user_id)\n\t\tdelete_call = Curl::Easy.http_delete(\"#{@ip_address}:#{@port_2}/v2.0/users/#{user_id}\"\n\t\t) do |curl|\n\t\t\tcurl.headers['x-auth-token'] = @token\n\t\t\tcurl.headers['userId'] = user_id\n\t\tend\n\t\n\tend",
"def delete_user\n if (@user = find_user(params[:id]))\n do_delete_user(@user)\n flash[:notice] = \"User '#{@user.login}' has been deleted.\"\n end\n redirect_to :action => 'list'\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n record_activity(\"deleted user: \" + @user.email)\n redirect_to users_path, :notice => \"User deleted\"\n end",
"def delete_user(userid) \n $db.execute('DELETE FROM users WHERE userid=?', userid)\n end",
"def delete_user(user_id)\n raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty?\n path = \"#{users_path}/#{user_id}\"\n delete(path)\n end",
"def delete(id)\n begin\n User.filter(:id => id).destroy\n flash[:success] = 'The specified user has been removed'\n rescue => e\n Ramaze::Log.error(e)\n flash[:error] = 'The specified user could not be removed'\n end\n\n redirect_referrer\n end",
"def delete_user(id)\n # accept an id input parameter\n # use the User Model class to remove the User associated with the `id` primary key from the database\n # (no return is required)\n (User.find_by(id: id)).destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.deleted = true\n if @user.save\n redirect_to(users_path, :alert => 'User deleted successfully.')\n end\n end",
"def destroy\n @user = User.shod(params[:id])\n authorize! :delete, @user\n @user.destroy\n flash[:user_delete] = t('user_delete')\n redirect_to users_path\n end",
"def destroy(user)\n unless user.id\n self.class.invalid_object!(\"Cannot save user #{user.username} without a valid id\")\n end\n\n unless execute_sql(:validate, :user) { table.select(:id).filter(:id => user.id).any? }\n raise RecordNotFound, \"Can't delete user #{user.username} because it doesn't exist\"\n end\n\n execute_sql(:delete, :user) { table.filter(:id => user.id).delete }\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n head :no_content\n end",
"def delete_user(id)\n\n db = connect_to_db(\"db/db.db\")\n\n db.execute(\"DELETE FROM posts WHERE user_id = ?\", id)\n \n db.execute(\"DELETE FROM users WHERE id = ?\", id)\n\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path, :notice => \"User deleted.\"\n end",
"def destroy\n @user = User.find(params[:id])\n @user.delete!\n\n redirect_to admin_users_path\n end",
"def destroy\n @user = User.find(params[:id])\n @user.delete!\n\n redirect_to admin_users_path\n end",
"def destroy\n\t\t@user.delete\n\tend",
"def delete_user(user_id)\n Result.new(call(CMD_DEL_USER % user_id))\n end",
"def destroy\n @user.destroy\n redirect_to users_path, notice: (I18n.t :act_delete)\n end",
"def delete\n @user.destroy\n respond_to do |format|\n format.html { redirect_to v1_resources_users_all_path, notice: 'User was deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id]).destroy\n flash[:success] = \"User deleted!\"\n redirect_to users_url\n end",
"def delete_user(uid)\n @client.post(with_path(\"accounts:delete\"), {localId: validate_uid(uid, required: true)})\n end",
"def delete_user\n User.delete(params[:id])\n render :text => \"\"\n end",
"def destroy\n @user = User.find(params[:id])\n @user.delete\n flash[:notice] = t('users.destroyed')\n redirect_to admin_users_url\n end",
"def delete_users\n delete(users_path)\n end",
"def destroy\n @user.destroy\n respond_to do |format|\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n website.add_log(user: current_user, action: \"Deleted user #{@user.name}\")\n end",
"def deleteUser(id) \n user_to_remove = getUserByID(id)\n\n if user_to_remove != nil \n @Users.delete(user_to_remove)\n else\n puts \"No such user.\"\n end \n end",
"def remove_user\n query_api \"/rest/user\", nil, \"DELETE\"\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n redirect_to users_path, :notice => 'User was successfully deleted.'\n end",
"def destroy\n @user = User.find(params[:id])\n \n if admon_user\n flash[:notice] = 'La cuenta ha sido eliminada'\n redirect_to users_path\n else\n flash[:notice] = 'Su cuenta ha sido eliminada'\n redirect_to signup_path\n current_user_session.destroy\n end\n\n @user.destroy\n end",
"def destroy\n userToBeRemoved = User.find(params[:id])\n userToBeRemoved.destroy\n respond_to do |format|\n format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted :(\"\n redirect_to users_url\n end",
"def delete_by_id(user_id)\n Iterable.request(conf, \"/users/byUserId/#{user_id}\").delete\n end",
"def delete_user(user_name:)\n validate_user_name(:user_name, user_name)\n\n wrap_response(@connection.delete(user_path(user_name))).fmap { |r| SftpgoClient::ApiResponse.new(r.body) }\n end",
"def delete\n @user = User.find(params[:id])\n @user.destroy if @user!=nil # TODO maybe set status to 0 as deleted instead of removing entry\n flash[:notice] = \"User '#{@user.username}' deleted successfully.\"\n\n # when admin delete himself\n if session[:user_id]== @user.id\n session[:user_id] = nil\n session[:username] = nil\n end\n redirect_to(:action => 'list')\n end",
"def remove_user\n query_api '/rest/user', nil, 'DELETE'\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:user])\n @user.destroy\n redirect_to users_path\n end",
"def destroy\n authorize! :destroy, @user, :message => 'You are not authorized to perform this operation.'\n user = User.find(params[:id])\n unless user == current_user\n user.destroy\n redirect_to users_path, :notice => \"User deleted. #{undo_link}\"\n else\n redirect_to users_path, :notice => \"Can't delete yourself.\"\n end\n\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to root_path\n end",
"def destroy\n \tuser = User.find params[:id]\n \tuser.destroy\n\n \tredirect_to users_path, status: 303\n end",
"def destroy\n @user.destroy\n head :no_content\n end",
"def destroy\n user.destroy\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to users_url\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to users_url\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n flash[:error] = \"Delete User #{user.userName}\"\n redirect_to '/users'\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to users_url\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to users_url\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to users_url\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to users_url\n end",
"def user_delete(user_id)\n res = http_delete(:uri=>\"/users/#{user_id}\", :fields=>x_cookie)\n return res.code\n end",
"def destroy\n @user = User.find(params[:id])\n User.cascade_delete(@user)\n\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @user = User.find(params[:id])\n if @user.destroy\n flash[:success] = \"User has been deleted!\"\n redirect_to users_url\n end\n end",
"def delete(user_id:)\n path = '/users/{userId}'\n .gsub('{userId}', user_id)\n\n if user_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"userId\"')\n end\n\n params = {\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'DELETE',\n path: path,\n headers: headers,\n params: params,\n )\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted\"\n redirect_to root_url\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to users_url\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to administrators_url, notice: 'User was successfully deleted.' }\n format.json { head :ok }\n end\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted.\"\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n redirect_to(users_url)\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to dm_core.admin_users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find_by_id(params[:id])\n @user.destroy\n end",
"def delete_user(user)\n users = roles\n existing = users[\"cloudant\"]\n \n existing.delete(user) if existing\n update_roles(users)\n end",
"def destroy\n @user = User.find(params[:id]).destroy\n redirect_to users_path\n end",
"def destroy\n @user = get_user(params[:id])\n begin\n @user.destroy\n flash[:notice] = \"User #{@user.login_name} deleted\"\n rescue Exception => e\n flash[:notice] = e.message\n end\n respond_to do |format|\n format.html { redirect_to users_url }\n format.json { head :no_content }\n end\n end",
"def delete\n @linked_user.delete(@uri)\n end",
"def delete_user\n user = User.where(email: user_params[:email]).first\n response = user.destroy\n @api_response[:code] = @response_codes[:success]\n @api_response[:result] = response\n\n rescue Exception => e\n @errors, @api_response = api_exception_handler(e)\n ensure\n send_response(@api_response, @errors)\n end",
"def destroy\r\n\r\n @user.destroy\r\n\r\n save_users_log(current_user.email, 'user_deleted',@user.to_json)\r\n\r\n respond_to do |format|\r\n format.html { redirect_to users_url, notice: 'User was successfully deleted.' }\r\n end\r\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"Пользователь удален\"\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n flash[:notice] = 'User was successfully deleted.'\n format.html { redirect_to(admin_users_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user = User.find params[:id]\n @user.destroy\n redirect_to users_path\n end",
"def destroy\n @user = User.find(params[:user_uuid])\n @user.destroy\n head :ok\n end",
"def destroy\n user = User.find(params[:id])\n user.destroy\n redirect_to root_path, status: 303\n \n end",
"def delete\n CONNECTION.execute(\"DELETE FROM users WHERE id = #{self.id};\")\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n head :no_content\n end",
"def destroy\n User.find(params[:id]).destroy\n flash[:success] = \"User deleted successfully.\"\n redirect_to users_url\n end",
"def destroy\n @user = User.find(params[:id])\n @user.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_users_url }\n format.json { head :ok }\n end\n end"
] |
[
"0.86632615",
"0.8423136",
"0.84053475",
"0.82250786",
"0.8192423",
"0.815359",
"0.8069401",
"0.8058493",
"0.8056387",
"0.8056387",
"0.8041427",
"0.80394095",
"0.8017781",
"0.799115",
"0.7967456",
"0.7952666",
"0.7934495",
"0.79335874",
"0.7903419",
"0.78754306",
"0.786016",
"0.78581274",
"0.78570837",
"0.78405523",
"0.7837808",
"0.78299445",
"0.78234076",
"0.7800457",
"0.7800457",
"0.779314",
"0.7774845",
"0.777276",
"0.77626175",
"0.7760828",
"0.77545726",
"0.7748578",
"0.77485716",
"0.774388",
"0.7742406",
"0.7737612",
"0.7718967",
"0.77100635",
"0.76989836",
"0.76975334",
"0.769726",
"0.769726",
"0.769726",
"0.769726",
"0.7683074",
"0.76812524",
"0.76730543",
"0.7672135",
"0.7670331",
"0.7669611",
"0.7669611",
"0.76665366",
"0.7666323",
"0.76625353",
"0.7662235",
"0.7657482",
"0.765728",
"0.7656848",
"0.7656848",
"0.7655458",
"0.76538086",
"0.76538086",
"0.76538086",
"0.76538086",
"0.7650603",
"0.76487607",
"0.7648041",
"0.7645982",
"0.7644564",
"0.76384836",
"0.76383966",
"0.7637742",
"0.76352805",
"0.76337457",
"0.7628337",
"0.76230294",
"0.76193947",
"0.76153326",
"0.76138186",
"0.76126724",
"0.7612424",
"0.76099885",
"0.7605014",
"0.75996107",
"0.75972104",
"0.75920016",
"0.7590509",
"0.75903594",
"0.7589839",
"0.7589839",
"0.7589839",
"0.7589839",
"0.7589839",
"0.7589839",
"0.7589839",
"0.7589276",
"0.75879294"
] |
0.0
|
-1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.