Search Results

Search found 2030 results on 82 pages for 'params'.

Page 9/82 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Can can I reference extended methods/params without having to cast from the base class object return

    - by Greg
    Hi, Is there away to not have a "cast" the top.First().Value() return to "Node", but rather have it automatically assume this (as opposed to NodeBase), so I then see extended attributes for the class I define in Node? That is is there a way to say: top.Nodes.First().Value.Path; as opposed to now having to go: ((Node)top.Nodes.First().Value).Path) thanks [TestMethod()] public void CreateNoteTest() { var top = new Topology(); Node node = top.CreateNode("a"); node.Path = "testpath"; Assert.AreEqual("testpath", ((Node)top.Nodes.First().Value).Path); // *** HERE *** } class Topology : TopologyBase<string, Node, Relationship> { } class Node : NodeBase<string> { public string Path { get; set; } } public class NodeBase<T> { public T Key { get; set; } public NodeBase() { } public NodeBase(T key) { Key = key; } } public class TopologyBase<TKey, TNode, TRelationship> where TNode : NodeBase<TKey>, new() where TRelationship : RelationshipBase<TKey>, new() { // Properties public Dictionary<TKey, NodeBase<TKey>> Nodes { get; private set; } public List<RelationshipBase<TKey>> Relationships { get; private set; } }

    Read the article

  • Php algorithm - How to achieve that without eval

    - by Marcelo
    I have a class that keeps data stores/access data by using words.separated.by.dots keys and it behaves like the following: $object = new MyArray() $object->setParam('user.name','marcelo'); $object->setParam('user.email','[email protected]'); $object->getParams(); /* array( 'user' => array( 'name' => 'marcelo', 'email' => '[email protected]' ) ); */ It is working, but the method unsetParam() was horribly implemented. That happened because i didn't know how to achieve that without eval() function. Although it is working, I found that it was a really challenging algorithm and that you might find fun trying to achieve that without eval(). class MyArray { /** * @param string $key * @return Mura_Session_Abstract */ public function unsetParam($key) { $params = $this->getParams(); $tmp = $params; $keys = explode('.', $key); foreach ($keys as $key) { if (!isset($tmp[$key])) { return $this; } $tmp = $tmp[$key]; } // bad code! $eval = "unset(\$params['" . implode("']['", $keys) . "']);"; eval($eval); $this->setParams($params); return $this; } } The test method: public function testCanUnsetNestedParam() { $params = array( '1' => array( '1' => array( '1' => array( '1' => 'one', '2' => 'two', '3' => 'three', ), '2' => array( '1' => 'one', '2' => 'two', '3' => 'three', ), ) ), '2' => 'something' ); $session = $this->newSession(); $session->setParams($params); unset($params['1']['1']['1']); $session->unsetParam('1.1.1'); $this->assertEquals($params, $session->getParams()); $this->assertEquals($params['1']['1']['2'], $session->getParam('1.1.2')); }

    Read the article

  • Rails: redirect_to :controller=>'tips', :action => 'show', :id => @tip.permalink

    - by john
    hi, I tried to redirect rails to show action by passing controller, action, and params. However, rails ignores the name of action totally! what I got is http://mysite/controllername/paramId so i have error message.... here is the action code I used: def update @tip = current_user.tips.find(params[:id]) @tip.attributes = params[:tip] @tip.category_ids = params[:categories] @tip.tag_with(params[:tags]) if params[:tags] if @tip.save flash[:notice] = 'Tip was successfully updated.' redirect_to :controller=>'tips', :action => 'show', :id => @tip.permalink else render :action => 'edit' end end

    Read the article

  • Linenumber for Exception thrown in runtime-compiled DotNET code

    - by David Rutten
    Not quite the same as this thread, but pretty close. My program allows people to enter some VB or C# code which gets compiled, loaded and executed at runtime. My CompilerParams are: CompilerParameters params = new CompilerParameters(); params.GenerateExecutable = false; params.GenerateInMemory = true; params.IncludeDebugInformation = false; params.TreatWarningsAsErrors = false; params.WarningLevel = 4; When this code throws an exception I'd like to be able to display a message box that helps users debug their code. The exception message is easy, but the line-number is where I got stuck. I suspect that in order to get at the line number, I may need to drastically change the CompilerParameters and perhaps even the way these dlls get stored/loaded. Does anyone know the least steps needed to get this to work?

    Read the article

  • Help me refactoring this nasty Ruby if/else statement

    - by Suborx
    Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and i need to assigned user to rayon. I have relation n:n through table colporteur_in_rayons witch have attributes since_date and _until_date. I am junior programmer and i know this code is pretty dummy :) I appreciated every suggestion. def update rayon = Rayon.find(params[:id]) if rayon.update_attributes(params[:rayon]) if params[:user_id] != "" unless rayon.users.empty? unless rayon.users.last.id.eql?(params[:user_id]) rayon.colporteur_in_rayons.last.update_attributes(:until_date = Time.now) Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end else Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end end flash[:success] = "Rayon has been successfully updated." return redirect_to rayons_path else flash[:error] = "Rayon has not been updated." return redirect_to :back end end

    Read the article

  • One executable with cmd-line params or just many satellite executables?

    - by Nikos Baxevanis
    I design an application back-end. For now, it is a .NET process (a Console Application) which hosts various communication frameworks such as Agatha and NServiceBus. I need to periodically update my datastore with values (coming from the application while it's running). I found three possible ways: Accept command line arguments, so I can call my console app with -update. On start up a background thread will periodically invoke the update method. Create an updater.exe app which will do the updates, but I will have code duplication since in some way it will need to query the data from the source in order to save it to the datastore. Which one is better?

    Read the article

  • Rails & Twilio: Receiving nil when storing texts received from Twilio

    - by Jon Smooth
    I have set up the request URL in my Twilio account to have it POST to: myurl.com/receivetext. It appears to be successfully posting because when I check the database using the Heroku console I see the following: Post id: 5, body: nil, from: nil, created_at: "2012-06-14 17:28:01", updated_at: "2012-06-14 17:28:01" Why is it receiving nil for the body and from attributes? I can't figure out what I'm doing wrong! The created and updated at are storing successfully but the two attributes that I care about continue to be stored as nil. Here's the Receive Text controller which is receiving the Post request from Twilio: class ReceiveTextController < ApplicationController def index @post=Post.create!(body: params[:Body], from: params[:From]) end end EDIT: When I dump the params I receive the following: "{\"controller\"=\"receive_text\", \"action\"=\"index\"}" I attained this by inserting the following into my ReceiveText controller. @params = Post.create!(body: params.inspect, from: "Dumping Params") and then opening up the Heroku console to find the database entry with from = "Dumping Params". I simulated a Twilio request with a curl with the following command curl -X POST myurl.com/receivetext route -d 'AccountSid=AC123&From=%2B19252411234' I checked the production database again and noticed that the curl request did work when obtaining the FROM atribute. It stored the following: params.inspect returned "{\"AccountSid\"=\"AC123\", \"From\"=\"+19252411234\", \"co..." I received a comment stating: "As long as twilio is hitting the same URL with the same method (GET/POST) it should be filling the params array as well" I have no idea how to make this comment actionable. Any help would be greatly appreciated! I'm very new to rails. Here's my database migration (I have both attributes set to string. I have tried setting it to text and that didn't work either) : class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :body t.string :from t.timestamps end end end Here is my Post model: class Post < ActiveRecord::Base attr_accessible :body, :from end Routes (everything appears to be routing just fine) : MovieApp::Application.routes.draw do get "receive_text/index" get "pages/home" get "send_text/send_text_message" root to: 'pages#home' match '/receivetext', to: 'receive_text#index' match '/pages/home', to: 'pages#home' match '/sendtext', to: 'send_text#send_text_message' end Here's my gemfile (incase it helps) source 'https://rubygems.org' gem 'rails', '3.2.3' gem 'badfruit' gem 'twilio-ruby' gem 'logger' gem 'jquery-rails' group :production do gem 'pg' end group :development, :test do gem 'sqlite3' end group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'uglifier', '>= 1.0.3' end

    Read the article

  • How would I order a table by the number of matching params in the where clause of an sql statement?

    - by Eitan
    I'm writing sql to search a database by a number of parameters. How would I go about ordering the result set by the items that match the most parameters in the where clause. For example: SELECT * FROM users WHERE username = 'eitan' OR email = '[email protected]' OR company = 'eitan' Username | email | company 1) eitan | [email protected] | blah 2) eitan | [email protected] | eitan 3) eitan | [email protected] | blah should be ordered like: 2, 3, 1. Thanks. (ps the query isn't that easy, has a lot of joins and a lot of OR's in the WHERE) Eitan

    Read the article

  • Visual Studio 2008 profiler analysis - missing time

    - by Scott Vercuski
    I ran the Visual Studio 2008 profiler against my ASP.NET application and came up with the following result set. CURRENT FUNCTION TIME (msec) ---------------------------------------------------|-------------- Data.GetItem(params) | 10,158.12 ---------------------------------------------------|-------------- Functions that were called by Data.GetItem(params) TIME (msec) ---------------------------------------------------|-------------- Model.GetSubItem(params) | 0.83 Model.GetSubItem2(params) | 0.77 Model.GetSubItem3(params) | 0.76 etc. The issue I'm facing is that the sum of the Functions called by Data.GetItem(params) do not sum up to the 10,158.12 msec total. This would lead me to believe that the bulk of the time is actually spent executing the code within that method. My question is ... does Visual Studio provide a way to analyze the method itself so I can see which sections of code are taking the longest? if it does not are there any recommended tools to do this? or should I start writing my own timing scripts? Thank you

    Read the article

  • Help me refactor this nasty Ruby if/else statement

    - by Suborx
    Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and I need to assign a user to rayon. I have relation n:n through table colporteur_in_rayons which has attributes since_date and until_date. I am a junior programmer and I know this code is pretty dummy :) I appreciate every suggestion. def update rayon = Rayon.find(params[:id]) if rayon.update_attributes(params[:rayon]) if params[:user_id] != "" unless rayon.users.empty? unless rayon.users.last.id.eql?(params[:user_id]) rayon.colporteur_in_rayons.last.update_attributes(:until_date => Time.now) Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end else Rayon.assign_user(rayon.id,params[:user_id]) flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}." return redirect_to rayons_path end end flash[:success] = "Rayon has been successfully updated." return redirect_to rayons_path else flash[:error] = "Rayon has not been updated." return redirect_to :back end end

    Read the article

  • GET request, iOS

    - by phnmnn
    I need to do this GET request: http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[] In browser I get response: { "Success":true, "Atava":[], "Pending":[], "CallWaiter":false } But in iOS it not work. i try: NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num]; NSURL *url = [NSURL URLWithString:requestedURL]; NSURLResponse *response; NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding]; NSLog(@"Reply: %@", theReply); OR NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num]; OR NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; [params setObject:@"Tax" forKey:@"Name"]; [params setObject:@"2.11" forKey:@"Price"]; [params setObject:@"1" forKey:@"Quantity"]; [params setObject:@"1" forKey:@"SerialID"]; [params setObject:@"" forKey:@"Remarks"]; [params setObject:@"" forKey:@"Toppings"]; NSData *jsonData = nil; NSString *jsonString = nil; if([NSJSONSerialization isValidJSONObject:params]) { jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil]; jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",jsonString); } NSString *get=[NSString stringWithFormat: @"&Items=%@", jsonString]; NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"GET"]; [request setTimeoutInterval:8]; [request setHTTPBody:getData]; [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; nothing doesn't work. How to fix it? Sorry for bad english.

    Read the article

  • How to pass multiple params to function in python?

    - by user1322731
    I am implementing 8bit adder in python. Here is the adder function definition: def add8(a0,a1,a2,a3,a4,a5,a6,a7,b0,b1,b2,b3,b4,b5,b6,b7,c0): All function parameters are boolean. I have implemented function that converts int into binary: def intTObin8(num): bits = [False]*8 i = 7 while num >= 1: if num % 2 == 1: bits[i] = True else: bits[i] = False i = i - 1 num /= 2 print bits return [bits[x] for x in range(0,8)] I want this function to return 8 bits. And to use this two functions as follows: add8(intTObin8(1),intTObin8(1),0) So the question is: How to pass 8 parameters using one function?

    Read the article

  • Any method to denote object assignment?

    - by Droogans
    I've been studying magic methods in Python, and have been wondering if there's a way to outline the specific action of: a = MyClass(*params).method() versus: MyClass(*params).method() In the sense that, perhaps, I may want to return a list that has been split on the '\n' character, versus dumping the raw list into the variable a that keeps the '\n' intact. Is there a way to ask Python if its next action is about to return a value to a variable, and change action, if that's the case? I was thinking: class MyClass(object): def __init__(*params): self.end = self.method(*params) def __asgn__(self): return self.method(*params).split('\n') def __str__(self): """this is the fallback if __asgn__ is not called""" return self.method(*params)

    Read the article

  • When the user first visits the page I want all the checkboxes to be checked in my index page. Below is the code from my controller and index.html.haml

    - by user1760920
    I want the checkbox to be checked when the user visits the page for the first time. -# This file is app/views/movies/index.html.haml %h1 All Movies = form_tag movies_path, :method => :get, :id => 'ratings_form' do Include: - @all_ratings.each do |rating| = rating = check_box_tag "ratings[#{rating}]", "1", @checked_ratings.include?(rating), :id => "ratings_#{rating}", = submit_tag 'Refresh', :id => 'ratings_submit' %table#movies %thead %tr %th{:class => ("hilite" if @sort == "title")}= link_to "Movie Title", movies_path( :sort => "title", :ratings => @checked_ratings), :id => "title_header" %th Rating %th{:class => ("hilite" if @sort == "release_date")}= link_to "Release Date", movies_path( :sort => "release_date", :ratings => @checked_ratings), :id => "release_date_header" %th More Info %tbody - @movies.each do |movie| %tr %td= movie.title %td= movie.rating %td= movie.release_date %td= link_to "More about #{movie.title}", movie_path(movie) = link_to 'Add new movie', new_movie_path #This is my Controller class MoviesController < ApplicationController def show id = params[:id] # retrieve movie ID from URI route @movie = Movie.find(id) # look up movie by unique ID # will render app/views/movies/show.<extension> by default end def index #get all the ratings available @all_ratings = Movie.all_ratings @checked_ratings = (params[:ratings].present? ? params[:ratings] : []) @sort = params[:sort] @movies = Movie.scoped if @sort && Movie.attribute_names.include?(@sort) @movies = @movies.order @sort end id @checked_ratings.empty? @checked_ratings = @all_ratings end unless @checked_ratings.empty? @movies = @movies.where :rating => @checked_ratings.keys end end def new # default: render 'new' template end def create @movie = Movie.create!(params[:movie]) flash[:notice] = "#{@movie.title} was successfully created." redirect_to movies_path end def edit @movie = Movie.find params[:id] end def update @movie = Movie.find params[:id] @movie.update_attributes!(params[:movie]) flash[:notice] = "#{@movie.title} was successfully updated." redirect_to movie_path(@movie) end def destroy @movie = Movie.find(params[:id]) @movie.destroy flash[:notice] = "Movie '#{@movie.title}' deleted." redirect_to movies_path end end In the controller, I set the @checked_rating to be @all_rating if the @checked.rating is empty but it does not do anything. I tried putting :checked = true in the index.html.haml on the check_box_tag but that makes the checkboxes checked everytime the page is refreshed. Everytime I check a particular checkbox and hit refresh button the page loads with all the checkboxes checked. Please help me with this. Thank you in Advance.

    Read the article

  • Teamviewer: cannot control monitor 1, but can control monitor 2

    - by DaveT
    I'm using the web client of Teamviewer from my work computer trying to control my home computer. I have 2 monitors on the remote desktop, but for some reason only have control on the second monitor. When I switch to the main monitor (monitor 1), I cannot do anything and cannot even move the cursor. But I have no issues when I switch over to the second monitor (monitor 2). I used to have no issues with either, but in the past couple of months this has been causing me issues. Anyone have a suggestion? Thanks!! Also... Here is the log from the Teamviewer session. Showing me switching back and forth between the monitors. (just in case this will help). I had to remove the links in order to post the log since I don't have enough reputation points, but they were just teamviewer login weblinks. =============================================================================== 21.08 16:00:41,176: Version: 9.0.15099 21.08 16:00:41,177: Sandbox: remote 21.08 16:00:41,177: SysLanguage: en 21.08 16:00:41,177: VarLanguage: en 21.08 16:00:41,177: Flash Player: PlugIn (WIN 14,0,0,179) 21.08 16:00:41,178: UseLanguage: en 21.08 16:00:41,178: UseLanguage: en 21.08 16:00:41,182: TeamViewer hasPassword: true 21.08 16:00:41,418: ExternalConnect id=910035824 21.08 16:00:41,419: CT connect 910035824 masterURL: , sandbox = remote 21.08 16:00:41,425: MC.requestRoute(910035824) 21.08 16:00:41,426: MC.sendMasterCommand text=F=RequestRoute2&ID1=777&Client=TV& ID2=910035824&SA_AccountID=26641022&SA_PasswordMD5HashBase64Encoded=& SA_SessionSecret=f7H6Z7SYfX5ahQ7SJq/r/K20PBYg9fOZhp+DKLhf5ts=&SA_SessionID=1558929948& V=9.0.15099&OS=Flash 21.08 16:00:41,426: MC wait for ping completion 21.08 16:00:42,064: PS.socket event: [Event type="connect" bubbles=false cancelable=false eventPhase=2] 21.08 16:00:42,182: PingThread: TCP-Ping ok 21.08 16:00:42,183: MC.socket mode = TCP, MasterURL: 21.08 16:00:42,183: MC.connect: 21.08 16:00:43,058: PS.socket event: [Event type="connect" bubbles=false cancelable=false eventPhase=2] 21.08 16:00:43,058: MC.connectHandler: [Event type="connect" bubbles=false cancelable=false eventPhase=2] 21.08 16:00:43,236: MC.requestRouteResponse: [email protected]_10800_128000_762319420_910035824_10000__1_0_16778176_128000_16778176: 128000;2147483647:1280000;4:640000_786297_786297 21.08 16:00:43,239: CT init socket: TCP 21.08 16:00:43,513: PS.socket event: [Event type="connect" bubbles=false cancelable=false eventPhase=2] 21.08 16:00:43,514: CT.connectHandler: [Event type="connect" bubbles=false cancelable=false eventPhase=2] 21.08 16:00:43,519: Browser name: Netscape 21.08 16:00:43,936: CMD_IDENTIFY id=910035824 ver=2.41 21.08 16:00:44,666: CMD_CONFIRMENCRYPTION: encryption confirmed 21.08 16:00:44,667: Started resendrequest timer 21.08 16:00:45,063: Remote Version: TV 009.000 21.08 16:00:45,501: start classic authentication 21.08 16:00:45,502: Login::SendRequestToConsole(): url= 21.08 16:00:45,828: start srp authentication 21.08 16:00:46,983: checkFirstPacket ok, m_LastReceivedPacketID =4 21.08 16:00:47,148: Login::SendRequestToConsole(): url= 21.08 16:00:47,478: start srp authentication 21.08 16:00:48,210: Login::SendRequestToConsole(): url= 21.08 16:00:48,485: checkFirstPacket ok, m_LastReceivedPacketID =7 21.08 16:00:48,780: TVCmdAuthenticate_Authenticated: 1 21.08 16:00:49,321: Connected to 910035824, name=NEWMAN, os=14, version=9.0.31064 21.08 16:00:49,329: ConnectionAccessSettings: RemoteControl: AllowedFileTransfer: AllowedControlRemoteTV: AllowedSwitchSides: DeniedAllowDisableRemoteInput: AllowedAllowVPN: AllowedAllowPartnerViewDesktop: Allowed 21.08 16:00:52,195: unexpected TVCommand.CommandType == 56 21.08 16:00:52,231: CW received display params: 1680x1050x8 monitors: 2 (active:0) 21.08 16:00:52,301: Caching active, version=2 21.08 16:03:47,158: CW received display params: 1680x1050x8 monitors: 2 (active:1) 21.08 16:04:24,447: CW received display params: 1680x1050x8 monitors: 2 (active:0) 21.08 16:04:40,609: CW received display params: 3360x1050x8 monitors: 2 (active:-1) 21.08 16:04:59,802: CW received display params: 1680x1050x8 monitors: 2 (active:1) 21.08 16:04:59,933: CW received display params: 1680x1050x8 monitors: 2 (active:1) 21.08 16:05:58,419: CW received display params: 1680x1050x8 monitors: 2 (active:0) 21.08 16:06:36,824: CW received display params: 1680x1050x8 monitors: 2 (active:1) 21.08 16:07:07,232: CW received display params: 1680x1050x8 monitors: 2 (active:0)

    Read the article

  • Can't mass-assign protected attributes -- unsolved issue

    - by nfriend21
    I have read about 10 different posts here about this problem, and I have tried every single one and the error will not go away. So here goes: I am trying to have a nested form on my users/new page, where it accepts user-attributes and also company-attributes. When you submit the form: Here's what my error message reads: ActiveModel::MassAssignmentSecurity::Error in UsersController#create Can't mass-assign protected attributes: companies app/controllers/users_controller.rb:12:in `create' Here's the code for my form: <%= form_for @user do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= f.fields_for :companies do |c| %> <%= c.label :name, "Company Name"%> <%= c.text_field :name %> <% end %> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %> <%= f.label :password %> <%= f.password_field :password %> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation %> <br> <% if current_page?(signup_path) %> <%= f.submit "Sign Up", class: "btn btn-large btn-primary" %> Or, <%= link_to "Login", login_path %> <% else %> <%= f.submit "Update User", class: "btn btn-large btn-primary" %> <% end %> <% end %> Users Controller: class UsersController < ApplicationController def index @user = User.all end def new @user = User.new end def create @user = User.create(params[:user]) if @user.save session[:user_id] = @user.id #once user account has been created, a session is not automatically created. This fixes that by setting their session id. This could be put into Controller action to clean up duplication. flash[:success] = "Your account has been created!" redirect_to tasks_path else render 'new' end end def show @user = User.find(params[:id]) @tasks = @user.tasks end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) flash[:success] = @user.name.possessive + " profile has been updated" redirect_to @user else render 'edit' end #if @task.update_attributes params[:task] #redirect_to users_path #flash[:success] = "User was successfully updated." #end end def destroy @user = User.find(params[:id]) unless current_user == @user @user.destroy flash[:success] = "The User has been deleted." end redirect_to users_path flash[:error] = "Error. You can't delete yourself!" end end Company Controller class CompaniesController < ApplicationController def index @companies = Company.all end def new @company = Company.new end def edit @company = Company.find(params[:id]) end def create @company = Company.create(params[:company]) #if @company.save #session[:user_id] = @user.id #once user account has been created, a session is not automatically created. This fixes that by setting their session id. This could be put into Controller action to clean up duplication. #flash[:success] = "Your account has been created!" #redirect_to tasks_path #else #render 'new' #end end def show @comnpany = Company.find(params[:id]) end end User model class User < ActiveRecord::Base has_secure_password attr_accessible :name, :email, :password, :password_confirmation has_many :tasks, dependent: :destroy belongs_to :company accepts_nested_attributes_for :company validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :password, length: { minimum: 6 } #below not needed anymore, due to has_secure_password #validates :password_confirmation, presence: true end Company Model class Company < ActiveRecord::Base attr_accessible :name has_and_belongs_to_many :users end Thanks for your help!!

    Read the article

  • Trying to create an image list based on what is defined as the order, and loosing

    - by user1691463
    I have a custom created module for Joomla 2.5 and within the params of the module, and have a loop that is not outputting as expected. I have the following parameters (fields) int he module: Order Thumb image Image Title Full-size image Now there are 10 sets of these group of 4 params. What I am trying to do is loop through each of the object sets, 10 of them, and on each iteration, build an HTML image list structure. The if statement is building the HTML structure for the sets that have an order value that is greater than 0, and the else is creating the html for those sets that do not have a value greater that 0. The goal is to create two variables and then concatenate the the strings together; the leading set are the sets that have an order defined. This is not happening and every thrid loop seems like it is missing. Here is the order as it is set in the 10 sets Set 1 = 0 Set 2 = 4 Set 3 = 1 Set 4 = 0 Set 5 = 5 Set 6 = 0 Set 7 = 0 Set 8 = 6 Set 9 = 3 Set 10 = 9 However, the outcomes is: 9 5 1 4 6 7 10 Instead of the expected: 3 9 2 5 8 1 (below here are those sets that were not greater than 0 in order of appearance) 4 6 7 whats wrong here that I can not see <?php for ($i = 1; $i <= 10; $i++) { $order = $params->get('order'.$i);#get order for main loop of 10 $active = ""; if ($order > 0) {#Check if greater than 0 for ($n = 1; $n <= 10; $n++) {#loop through all order fields looking and build html lowest to highest; $ordercheck =$params->get('order'.$n); if ($ordercheck == $i) { $img = $params->get('image'.$n); $fimage = $params->get('image'.$n.'fullimage'); $title = $params->get('image'.$n.'alttext'); $active = ""; $active = $active . '<li>'; $active = $active . '<a href="'.$fimage.'" rel="prettyPhoto[gallery1]" title="'.$title.'">'; $active = $active . '<img src="'.$img.'" alt="'.$title.'" />'; $active = $active . '</a>'; $active = $active . '</li>'; $leading = $leading . $active; } } } else { #if the itteration $order was not greater than 0, build in order of accourance $img = $params->get('image'.$i); $fimage = $params->get('image'.$i.'fullimage'); $title = $params->get('image'.$i.'alttext'); $active = $active . '<li>'; $active = $active . '<a href="'.$fimage.'" rel="prettyPhoto[gallery1]" title="'.$title.'">'; $active = $active . '<img src="'.$img.'" alt="'.$title.'" />'; $active = $active . '</a></li>'; $unordered = $unordered . $active; } $imagesList = $leading . $unordered; } ?>

    Read the article

  • How do I make java wait for boolean to run funciton

    - by TWeeKeD
    I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step. ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help. b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(!uploadMsgPic.equalsIgnoreCase("")){ Log.v("response","Pic in storage"); sendPicMsg(); sendMessage(); }else{ sendMessage(); } 1st Method public void sendPicMsg(){ Log.v("response", "sendPicMsg Loaded"); if(!uploadMsgPic.equalsIgnoreCase("")){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); AsyncHttpClient client3 = new AsyncHttpClient(); RequestParams params3 = new RequestParams(); File file = new File(uploadMsgPic); try { File f = new File(uploadMsgPic.replace(".", "1.")); f.createNewFile(); //Convert bitmap to byte array Bitmap bitmap = decodeFile(file,400); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); params3.put("file", f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } params3.put("email", preferences.getString("loggedin_user", "")); params3.put("webversion", "1"); client3.post("http://peekatu.com/apiweb/msgPic_upload.php",params3, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { Log.v("response", "Upload Complete"); refreshChat(); //responseString = response; Log.v("response","msgPic has been uploaded"+response); //parseChatMessages(response); response=picurl; uploadMsgPic = ""; if(picurl!=null){ Log.v("response","picurl is set"); } if(picurl==null){ Log.v("response", "picurl no ready"); }; } }); sendMessage(); } } 2nd Method public void sendMessage(){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); if(preferences.getString("Username", "").length()<=0){ editText1.setText(""); Toast.makeText(this.getActivity(), "Please Login to send messages.", 2); return; } AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); if(type.equalsIgnoreCase("3")){ params.put("toid",user); params.put("action", "sendprivate"); }else{ params.put("room", preferences.getString("selected_room", "Adult Lobby")); params.put("action", "insert"); } Log.v("response", "Sending message "+editText1.getText().toString()); params.put("message",editText1.getText().toString() ); params.put("media", picurl); params.put("email", preferences.getString("loggedin_user", "")); params.put("webversion", "1"); client.post("http://peekatu.com/apiweb/messagetest.php",params, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { refreshChat(); //responseString = response; Log.v("response", response); //parseChatMessages(response); if(picurl!=null) Log.v("response", picurl); } }); editText1.setText(""); lv.setSelection(adapter.getCount() - 1); }

    Read the article

  • Extjs Dynamic Grid

    - by rkenshin
    Hi, I'm trying to create a dynamic grid using Extjs. The grid is built and displayed when a click event is fired then an ajax request is sent to the server to fetch the columns, records and records definition a.k.a Store Fields. Each node could have different grid structure and that depends on the level of the node in the tree. The only way i came up with so far is function showGrid(response, request) { var jsonData = Ext.util.JSON.decode(response.responseText); var grid = Ext.getCmp('contentGrid'+request.params.owner); if(grid) { grid.destroy(); } var store = new Ext.data.ArrayStore({ id : 'arrayStore', fields : jsonData.recordFields, autoDestroy : true }); grid = new Ext.grid.GridPanel({ defaults: {sortable:true}, id:'contentGrid'+request.params.owner, store: store, columns: jsonData.columns, //width:540, //height:200, loadMask: true }); store.loadData(jsonData.records); if(Ext.getCmp('tab-'+request.params.owner)) { Ext.getCmp('tab-'+request.params.owner).show(); } else { grid.render('grid-div'); Ext.getCmp('card-tabs-panel').add({ id:'tab-'+request.params.owner, title: request.params.text, iconCls:'silk-tab', html:Ext.getDom('grid-div').innerHTML, closable:true }).show(); } } The function above is called when a click event is fired 'click': function(node) { Ext.Ajax.request({ url: 'showCtn', success: function(response, request) { alert('Success'); showGrid(response,request); }, failure: function(results, request) { alert('Error'); }, params: Ext.urlDecode(node.attributes.options); } The problem i'm getting with this code is that a new grid is displayed each time the showGrid function is called. The end user sees the old grids and the new one. To mitigate this problem, I tried destroying the grid and also removing the grid element on each request, and that seems to solve the problem only that records never get displayed this time. if(grid) { grid.destroy(true); } The behavior i'm looking for is to display the result of a grid within a tab and if that tab exists replaced the old grid. Any help is appreciated. Thank you

    Read the article

  • DBExpress connecting SQL 2008 at runtime with Delphi 2009

    - by Pascal
    Hi, I'm trying to connect at runtime with SQL Server 2008 with Delphi 2009 using DBExpress, it it's not working. When I set all the properties at design time, it works great, but at RunTime, I'm getting "unknown driver: mssql". Below is the code: scnConexao := TSQLConnection.Create(nil); scnConexao.DriverName := 'MSSQL'; scnConexao.ConnectionName := 'MSSQLConnection'; scnConexao.GetDriverFunc := 'getSQLDriverMSSQL'; scnConexao.LibraryName := 'dbxmss.dll'; scnConexao.VendorLib := 'oledb'; scnConexao.LoginPrompt := False; scnConexao.Params.Add('SchemaOverride=sa.dbo'); scnConexao.Params.Add('HostName=DESKTOP'); scnConexao.Params.Add('DataBase=DBNAME'); scnConexao.Params.Add('OS Authentication=False'); scnConexao.Params.Add('User_Name=UserName'); scnConexao.Params.Add('Password=Password'); scnConexao.Params.Add('MSSQL TransIsolation=ReadCommited'); scnConexao.Open; I have included the dbxmss.dll in the same directory as my app, but to no avail. Any help would be greatly appreciated. Tks

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >