Search Results

Search found 1033 results on 42 pages for 'destroy'.

Page 31/42 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Using fields from an association (has_many) model with formtastic in rails

    - by pduersteler
    I searched and tried a lot, but I can't accomplish it as I want.. so here's my problem. class Moving < ActiveRecord::Base has_many :movingresources, :dependent => :destroy has_many :resources, :through => :movingresources end class Movingresource < ActiveRecord::Base belongs_to :moving belongs_to :resource end class Resource < ActiveRecord::Base has_many :movingresources has_many :movings, :through => :movingresources end Movingresources contains additional fields, like "quantity". We're working on the views for 'bill'. Thanks to formtastic to simplify the whole relationship thing by just writing <%= form.input :workers, :as => :check_boxes %> and i get a real nice checkbox list. But what I haven't found out so far is: How can i use the additional fields from 'movingresource', next or under each checkbox my desired fields from that model? I saw different approaches, mainly with manually looping through an array of objects and creating the appropriate forms, using :for in a form.inputs part, or not. But none of those solutions were clean (e.g. worked for the edit view but not for new because the required objects were not built or generated and generating them caused a mess). I want to know your solutions for this! :-)

    Read the article

  • Rails nested models and data separation by scope

    - by jobrahms
    I have Teacher, Student, and Parent models that all belong to User. This is so that a Teacher can create Students and Parents that can or cannot log into the app depending on the teacher's preference. Student and Parent both accept nested attributes for User so a Student and User object can be created in the same form. All four models also belong to Studio so I can do data separation by scope. The current studio is set in application_controller.rb by looking up the current subdomain. In my students controller (all of my controllers, actually) I'm using @studio.students.new instead of Student.new, etc, to scope the new student to the correct studio, and therefore the correct subdomain. However, the nested User does not pick up the studio from its parent - it gets set to nil. I was thinking that I could do something like params[:student][:user_attributes][:studio_id] = @student.studio.id in the controller, but that would require doing attr_accessible :studio_id in User, which would be bad. How can I make sure that the nested User picks up the same scope that the Student model gets when it's created? student.rb class Student < ActiveRecord::Base belongs_to :studio belongs_to :user, :dependent => :destroy attr_accessible :user_attributes accepts_nested_attributes_for :user, :reject_if => :all_blank end students_controller.rb def create @student = @studio.students.new @student.attributes = params[:student] if @student.save redirect_to @student, :notice => "Successfully created student." else render :action => 'new' end end user.rb class User < ActiveRecord::Base belongs_to :studio accepts_nested_attributes_for :studio attr_accessible :email, :password, :password_confirmation, :remember_me, :studio_attributes devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable end

    Read the article

  • Rails - Seeking a Dry authorization method compatible with various nested resources

    - by adam
    Consensus is you shouldn't nest resources deeper than 1 level. So if I have 3 models like this (below is just a hypothetical situation) User has_many Houses has_many Tenants and to abide by the above i do map.resources :users, :has_many => :houses map.resorces :houses, :has_many => :tenants Now I want the user to be able edit both their houses and their tenants details but I want to prevent them from trying to edit another users houses and tenants by forging the user_id part of the urls. So I create a before_filter like this def prevent_user_acting_as_other_user if User.find_by_id(params[:user_id]) != current_user() @current_user_session.destroy flash[:error] = "Stop screwing around wiseguy" redirect_to login_url() return end end for houses that's easy because the user_id is passed via edit_user_house_path(@user, @house) but in the tenents case tenant house_tenent_path(@house) no user id is passed. But I can get the user id by doing @house.user.id but then id have to change the code above to this. def prevent_user_acting_as_other_user if params[:user_id] @user = User.find(params[:user_id] elsif params[:house_id] @user = House.find(params[:house_id]).user end if @user != current_user() #kick em out end end It does the job, but I'm wondering if there is a more elegant way. Every time I add a new resource that needs protecting from user forgery Ill have to keep adding conditionals. I don't think there will be many cases but would like to know a better approach if one exists.

    Read the article

  • PropertyPlaceholderConfigurer vs Filters -- Spring Beans

    - by John
    Hi there. I've got a question regarding the difference between PropertyPlaceholderConfigurer (org.springframework.beans.factory.config.PropertyPlaceholderConfigurer) and normal filters defined in my pom.xml. I've been looking at examples, and it seems that even though filters are defined and marked to be active by default in the pom.xml they still make use of PropertyPlaceholderConfigurer in Spring's applicationContext.xml. This means that the pom.xml has a reference to a filter-LOCAL.properties while applicationContext.xml has a reference to application.properties and they both contain the same settings. Why is that? Is that how it is supposed to be done? I'm able to run the goal mvn jetty:run without the application.properties present, but if I add settings to the application.properties that differ from the filter-LOCAL.properties they don't seem to override. Here's an example of what I mean: pom.xml <profiles <profile <idLOCAL <activation <activeByDefaulttrue </activation <properties <envLOCAL </properties </profile </profiles applicationContext.xml <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" <property name="locations" <list <valueclasspath:application.properties </list </property <property name="ignoreResourceNotFound" value="true"/ </bean <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" <property name="driverClassName" value="${jdbc.driver}"/ <property name="url" value="${jdbc.url}"/ <property name="username" value="${jdbc.username}"/ <property name="password" value="${jdbc.password}"/ </bean an example of the content of application.properties and filters-LOCAL.properties jdbc.driver=org.postgresql.Driver jdbc.url=jdbc:postgresql://localhost/shoutbox_dev jdbc.username=tester jdbc.password=tester Can I remove the propertyConfigurer from the applicationContext, create a PROD filter and disregard the application.properties file, or will that give me issues when deploying to the production server?

    Read the article

  • Change an Image while using JCrop

    - by Bathan
    Hi guys! Im working on a new feature in my site and I got stucked really bad. Im using JCrop obviously to crop an Image on my website. The new feature that I've been asked to Implement is to allow the user to change the colors of the Image being cropped. I have now 3 images , Color, GrayScale and Sepia. I can change the source of the image tag using javascript so the image gets changed without reload but I cannot do this once the JCrop has been enabled because it replaces the original Image for a new one. I thought I could disable JCrop, Replace the Image and then Re-Enable, but i couldnt do such thing. The example I found where the JCrop gets destroyed (example5 in Demo zip) uses an object : jcrop_api = $.Jcrop('#cropbox'); But Im enabling JCrop in a different manner,more like Example 3 : jQuery('#cropbox').Jcrop({ onChange: showPreview, onSelect: showPreview, aspectRatio: 1 }); How can I destroy JCrop so I can replace te Image? Is there another way to do this? Please help! I Could easily reload the page each time the user changes de color of the image but we all know that's not cool. Any comments will be apreciated. Thanks

    Read the article

  • rails2 and aws-simple (simpledb): data cannot be deleted from amazon simpledb?

    - by z3cko
    i am developing a ruby on rails (2.3.8) application with data storage amazon simpledb. i am using the aws-sdb gem in the version aws-sdb (0.3.1) there are a few bugs, but the problems are outlined in the comments of this tutorial from amazon: http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1242 i am wondering if it is a bug of the gem or maybe a proxy issue, but i cannot delete any data from simpledb. anyone else experienced this or has a clue? >> t=Team.find(:first) => #<Team:0x329f718 @prefix_options={}, @attributes={"updated_at"=>Fri May 28 16:33:17 UTC 2010, "id"=>0}> >> t.destroy => #<Net::HTTPOK 200 OK readbody=true> >> t=Team.find(:first) => #<Team:0x321ad38 @prefix_options={}, @attributes={"updated_at"=>Fri May 28 16:33:17 UTC 2010, "id"=>0}> the team model is a normal ActiveResource Model, according to said tutorial. class Team < ActiveResource::Base self.site = "http://localhost:8888" # Proxy host + port self.prefix = "/fb2010_dev/" # SDB domain end

    Read the article

  • rspec and ruby 1.9.1: problem with dummy controller and routes

    - by giorgian
    I want to test a module that basically executes some verify statements, to ensure that actions are invoked with the correct method. # /lib/rest_verification.rb module RestVerification def self.included(base) # :nodoc: base.extend(ClassMethods) end module ClassMethods def verify_rest_actions verify :method => :post, :only => [:create], :redirect_to => { :action => :new } ... end end end I tried this: describe RestVerification do class FooController < ActionController::Base include RestVerification verify_rest_actions def new ; end def index ; end def create ; end def edit ; end def update ; end def destroy ; end end # controller_name 'foo' # this only works with ruby 1.8.7 : 1.9.1 says "uninitialized constant FooController" tests FooController # this works with both before(:each) do ActionController::Routing::Routes.draw do |map| map.resources :foo end end after(:each) do ActionController::Routing::Routes.reload! end it ':create should redirect to :new if invoked with wrong verb' do [:get, :put, :delete].each do |verb| send verb, :create response.should redirect_to(new_foo_url) end end ... end When testing: $ ruby -v ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux] $ rake RestVerification :create should redirect to :new if invoked with wrong verb Finished in 0.175586 seconds $ rvm use 1.9.1 Using ruby 1.9.1 p378 $ rake RestVerification :create should redirect to :new if invoked with wrong verb (FAILED - 1) 1) 'RestVerification :create should redirect to :new if invoked with wrong verb' FAILED expected redirect to "http://test.host/foo/new", got redirect to "http://test.host/spec/rails/example/controller_example_group/subclass_1/foo/new" Is this a known issue? Is there a workaround?

    Read the article

  • help me with function resize , not working with png

    - by user304828
    it not work with png created a thumb png but haven't data , like null data :D with jpg , jpeg still working without error why ? function thumbnail($pathtoFile,$thumWidth,$pathtoThumb) { //infor of image $infor = pathinfo($pathtoFile); // Setting the resize parameters list($width, $height) = getimagesize($pathtoFile); $modwidth = $thumWidth; $modheight = floor( $height * ( $modwidth / $width )); // Resizing the Image $thumb = imagecreatetruecolor($modwidth, $modheight); switch(strtolower($infor['extension'])) { case 'jpeg': case 'jpg': $image = imagecreatefromjpeg($pathtoFile); break; case 'gif': $image = imagecreatefromgif($pathtoFile); break; case 'png': $image = imagecreatefrompng($pathtoFile); break; } imagecopyresampled($thumb, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); switch(strtolower($infor['extension'])) { case 'jpeg': case 'jpg': imagejpeg($thumb,$pathtoThumb, 70); break; case 'gif': imagegif($thumb,$pathtoThumb, 70); break; case 'png': imagepng($thumb,$pathtoThumb, 70); break; } //destroy tmp imagedestroy($thumb); }

    Read the article

  • What can I read from the iPad Camera Connection Kit?

    - by HELVETICADE
    I'm building a small controller device that I'd like to partner with a computer. I've settled on using OSC out from my custom built hardware and am pretty satisfied with what I can get from WOscLib. Two goals I'd like to achieve are portability and a very ratio between battery:computing power, and this has lured me towards using iPhoneOS to accomplish my goals. I think the iPad would suit my needs perfectly, except that using wifi to broadcast OSC out from my device requires a third device and would destroy the goal of portability, whilst also introducing potential latency and stability headaches. My question is pretty simple: Can I push my OSC-out FROM my controller TO an iPad via USB and the Camera Connection Kit? If I could accomplish this, the two major goals of my project would be fulfilled very nicely. This seems like it should be a simple little question, but researching this obsessively over the past few weeks has left me more almost more uncertain than if I had done no research at all. I'd really like some more confidence before I go down this route, and it seems like it should be possible. Any insight would be very, very appreciated.

    Read the article

  • wxPython - ListCrtl and SQLite3

    - by Dunwitch
    I'm trying to get a SQLite3 DB to populate a wx.ListCrtl. I can get it to print to stdout/stderr without any problem. I just can't seem to figure out how to display the data in the DataWindow/DataList? I'm sure I've made some code mistakes, so any help is appreciated. Main.py import wx import wx.lib.mixins.listctrl as listmix from database import * import sys class DataWindow(wx.Frame): def __init__(self, parent = None): wx.Frame.__init__(self, parent, -1, 'DataList', size=(640,480)) self.win = DataList(self) self.Center() self.Show(True) class DataList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin): def __init__(self, parent = DataWindow): wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES) #building the columns self.InsertColumn(0, "Location") self.InsertColumn(1, "Address") self.InsertColumn(2, "Subnet") self.InsertColumn(3, "Gateway") self.SetColumnWidth(0, 100) self.SetColumnWidth(1, 150) self.SetColumnWidth(2, 150) self.SetColumnWidth(3, 150) class MainWindow(wx.Frame): def __init__(self, parent = None, id = -1, title = "MainWindow"): wx.Frame.__init__(self, parent, id, title, size = (800,600), style = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER)) # StatusBar self.CreateStatusBar() # Filemenu filemenu = wx.Menu() # Filemenu - About menuitem = filemenu.Append(-1, "&About", "Information about this application") self.Bind(wx.EVT_MENU, self.onAbout, menuitem) #Filemenu - Data menuitem = filemenu.Append(-1, "&Data", "Get data") self.Bind(wx.EVT_MENU, self.onData, menuitem) # Filemenu - Seperator filemenu.AppendSeparator() #Filemenu - Exit menuitem = filemenu.Append(-1, "&Exit", "Exit the application") self.Bind(wx.EVT_MENU, self.onExit, menuitem) # Menubar menubar = wx.MenuBar() menubar.Append(filemenu, "&File") self.SetMenuBar(menubar) # Show self.Show(True) self.Center() def onAbout(self, event): pass def onData(self, event): DataWindow(self) callDb = Database() sql = "SELECT rowid, address, subnet, gateway FROM pod1" records = callDb.select(sql) for v in records: print "How do I get the records on the DataList?" #print "%s%s%s" % (v[1],v[2],v[3]) #for v in records: #DataList.InsertStringItem("%s") % (v[0], v[1], v[2]) def onExit(self, event): self.Close() self.Destroy() def onSave(self, event): pass if __name__ == '__main__': app = wx.App() frame = MainWindow(None, -1) frame.Show() app.MainLoop() database.py import os import sqlite3 class Database(object): def __init__(self, db_file="data/data.sqlite"): database_allready_exists = os.path.exists(db_file) self.db = sqlite3.connect(db_file) if not database_allready_exists: self.setupDefaultData() def select(self,sql): cursor = self.db.cursor() cursor.execute(sql) records = cursor.fetchall() cursor.close return records def insert(self,sql): newID = 0 cursor = self.db.cursor() cursor.execute(sql) newID = cursor.lastrowid self.db.commit() cursor.close() return newID def save(self,sql): cursor = self.db.cursor() cursor.execute(sql) self.db.commit() cursor.close() def setupDefaultData(self): pass

    Read the article

  • OpenGLES - Rendering a background image only once and not wiping it

    - by chaosbeaker
    Hello, first time asking a question here but been watching others answers for a while. My own question is one for improving the performance of my program. Currently I'm wiping the viewFrameBuffer on each pass through my program and then rendering the background image first followed by the rest of my scene. I was wondering how I go about rendering the background image once, and only wiping the rest of the scene for updating/re-rendering. I tried using a seperate buffer but I'm not sure how to present this new buffer to the render buffer. // Set the current EAGLContext and bind to the framebuffer. This will direct all OGL commands to the // framebuffer and the associated renderbuffer attachment which is where our scene will be rendered [EAGLContext setCurrentContext:context]; glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); // Define the viewport. Changing the settings for the viewport can allow you to scale the viewport // as well as the dimensions etc and so I'm setting it for each frame in case we want to change i glViewport(0, 0, screenBounds.size.width , screenBounds.size.height); // Clear the screen. If we are going to draw a background image then this clear is not necessary // as drawing the background image will destroy the previous image glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Setup how the images are to be blended when rendered. This could be changed at different points during your // render process if you wanted to apply different effects glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); switch (currentViewInt) { case 1: { [background render:CGPointMake(240, 0) fromTopLeftBottomRightCenter:@"Bottom"]; // Other Rendering Code }} // Bind to the renderbuffer and then present this image to the current context glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; Hopefully by solving this I'll also be able to implement another buffer just for rendering particles as I can set them to always use a black background as their alpha source. Any help is greatly appreciated

    Read the article

  • Gtk, Trying to set bg to GtkEventBox but it fails.

    - by PP
    I am trying to set bg image to an event box but i am getting error as window GDK_IS_WINDOW (window)' failed what am i doing wrong in it? int main() { GtkWidget *g_winMain; GError *error = NULL; gtk_init(&argc, &argv); g_winMain = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_set_size_request(g_winMain, 300, 300); g_signal_connect(G_OBJECT(g_winMain), "destroy", G_CALLBACK(gtk_main_quit), NULL); GtkWidget *event_box; event_box = gtk_event_box_new(); gtk_event_box_set_visible_window( GTK_EVENT_BOX(event_box), TRUE ); GtkWidget *image; GdkPixmap *pixmap; GdkPixbuf *pixbuf; GdkBitmap *bitmap; pixbuf = gdk_pixbuf_new_from_file("test.jpg", &error); gdk_pixbuf_render_pixmap_and_mask(pixbuf, &pixmap, &bitmap, 0); gdk_window_set_back_pixmap( event_box->window, pixmap, true); //Error On this Line******** gtk_container_add( GTK_CONTAINER(g_winMain), event_box); gtk_widget_show(g_winMain); gtk_main(); }

    Read the article

  • Extjs 4.1 How to call controller action method from form

    - by Omar Faruq
    Extjs 4.1 How to call controller action method from form which is already use in a button action but i want this method reuse from a form field but do not how i can do? // here is my controller code init: function() { this.control({ 'itemsgrid': { removeitem: this.removeUser }, 'salewindow button[action=resetAll]': { click: this.resertform }, 'salewindow button[action=saveOrder]' : { click : this.onsaveOrder }, 'salewindow button[action=PDF]' : { click : this. pdfreport } }); }, resertform : function(button){ var store = Ext.data.StoreManager.get('Items'); store.destroy(); var vatstore = Ext.data.StoreManager.get('Vats'); vatstore.reload(); var rebatestore = Ext.data.StoreManager.get('Rebates'); rebatestore.reload(); Ext.getCmp('calculation-form').getForm().reset(); Ext.getCmp('itemform2').getForm().reset(); Ext.getCmp('itemsgrid').subtotalquantity(p=0); store.reload(); var co=store.getCount(); console.log(co); Ext.getCmp('customerID').setValue('0'); var a = Ext.getCmp('customerID').getValue(); Ext.getCmp('itemform2').customerinfo(a); } //and here is my from field listener { xtype : 'textfield', name : 'BranchId', fieldLabel : 'Branch Id', allowNegative : false, id : 'branchid', value : '1', onBlur: function(){ restoreItem();// i want call this method from here whis is stay in controller } }

    Read the article

  • Is it possible to send OSC commands to an iPad via the Camera Connection Kit?

    - by HELVETICADE
    I'm building a small controller device that I'd like to partner with a computer. I've settled on using OSC out from my custom built hardware and am pretty satisfied with what I can get from WOscLib. Two goals I'd like to achieve are portability and a very nice ratio between battery:computing power, and this has lured me towards using iPhoneOS to accomplish my goals. I think the iPad would suit my needs perfectly, except that using wifi to broadcast OSC out from my device requires that device to be connected to a third device with a wifi chip, and this would destroy the goal of portability, whilst also introducing potential latency and stability headaches. My question is pretty simple: Can I push OSC commands FROM my controller TO an iPad via USB and the Camera Connection Kit? If I could accomplish this, the two major goals of my project would be fulfilled very nicely. This seems like it should be a simple little question, but researching this obsessively over the past few weeks has left me more almost more uncertain than if I had done no research at all. I'd really like some more confidence before I go down this route, and it seems like it should be possible. Any insight would be very, very appreciated.

    Read the article

  • wxPython: How to handle event binding and Show() properly.

    - by Gopal
    Hi all, I'm just starting out with wxPython and this is what I would like to do: a) Show a Frame (with Panel inside it) and a button on that panel. b) When I press the button, a dialog box pops up (where I can select from a choice). c) When I press ok on dialog box, the dialog box should disappear (destroyed), but the original Frame+Panel+button are still there. d) If I press that button again, the dialog box will reappear. My code is given below. Unfortunately, I get the reverse effect. That is, a) The Selection-Dialog box shows up first (i.e., without clicking on any button since the TopLevelframe+button is never shown). b) When I click ok on dialog box, then the frame with button appears. c) Clicking on button again has no effect (i.e., dialog box does not show up again). What am I doing wrong ? It seems that as soon as the frame is initialized (even before the .Show() is called), the dialog box is initialized and shown automatically. I am doing this using Eclipse+Pydev on WindowsXP with Python 2.6 ============File:MainFile.py=============== import wx import MyDialog #This is implemented in another file: MyDialog.py class TopLevelFrame(wx.Frame): def __init__(self,parent,id): wx.Frame.__init__(self,parent,id,"Test",size=(300,200)) panel=wx.Panel(self) button=wx.Button(panel, label='Show Dialog', pos=(130,20), size=(60,20)) # Bind EVENTS --> HANDLERS. button.Bind(wx.EVT_BUTTON, MyDialog.start(self)) # Run the main loop to start program. if __name__=='__main__': app=wx.PySimpleApp() TopLevelFrame(parent=None, id=-1).Show() app.MainLoop() ============File:MyDialog.py=============== import wx def start(parent): inputbox = wx.SingleChoiceDialog(None,'Choose Fruit', 'Selection Title', ['apple','banana','orange','papaya']) if inputbox.ShowModal()==wx.ID_OK: answer = inputbox.GetStringSelection() inputbox.Destroy()

    Read the article

  • rails delete_all exception

    - by Sergei
    Hello, guys! I have some User model, Role model and Assignment model to manage role-based user system. Just like here . So, here some kind of code, to include roles into users form: <% for role in Role.all %> <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %> <%=h role.name %><br /> <% end %> And all's working fine for new records and for editing records. But I just want to make possible to restrict deleting Assigment with id=1, cause this Assignment for default root user from migration, who must be admin anyway. Otherwise, I can lose my last admin. So I've tryed to add before_destroy to Assignment.rb model, but it doesn't work. I've noticed, that when I'm editing user and trying to remove his admin role(assignment), the server makes a delete_all method, not destroy method. So, does anybody know how to catch the deleting of Assignment with id=1 through this kind of code? Thanks in advance!

    Read the article

  • C two functions in one with casts

    - by Favolas
    I have two functions that do the exact same thing but in two different types of struct and this two types of struct are very similar. Imagine I have this two structs. typedef struct nodeOne{ Date *date; struct nodeOne *next; struct nodeOne *prev; }NodeOne; typedef struct nodeTwo{ Date *date; struct nodeTwo *next; struct nodeTwo *prev; }NodeTwo; Since my function to destroy each of the list is almost the same (Just the type of the arguments are different) I would like to make just one function to make the two thins. I have this two functions void destroyListOne(NodeOne **head, NodeOne **tail){ NodeOne *aux; while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } and this one: void destroyListTwo(NodeTwo **head, NodeTwo **tail){ NodeTwo *aux; while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } Since they are very similar I thought making something like this: void destroyList(void **ini, void **end, int listType){ if (listType == 0) { NodeOne *aux; NodeOne head = (NodeOne) ini; NodeOne tail = (NodeOne) ed; } else { NodeTwo *aux; NodeTwo head = (NodeTwo) ini; NodeTwo tail = (NodeTwo) ed; } while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } As you may now this is not working but I want to know if this is possible to achieve. I must maintain both of the structs as they are.

    Read the article

  • Why is my simple python gtk+cairo program running so slowly/stutteringly?

    - by synapz
    My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help! #!/usr/bin/python import gtk import gtk.gdk as gdk import math import random import gobject # The number of circles and the window size. num = 128 size = 512 # Initialize circle coordinates and velocities. x = [] y = [] xv = [] yv = [] for i in range(num): x.append(random.randint(0, size)) y.append(random.randint(0, size)) xv.append(random.randint(-4, 4)) yv.append(random.randint(-4, 4)) # Draw the circles and update their positions. def expose(*args): cr = darea.window.cairo_create() cr.set_line_width(4) for i in range(num): cr.set_source_rgb(1, 0, 0) cr.arc(x[i], y[i], 8, 0, 2 * math.pi) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.fill() x[i] += xv[i] y[i] += yv[i] if x[i] > size or x[i] < 0: xv[i] = -xv[i] if y[i] > size or y[i] < 0: yv[i] = -yv[i] # Self-evident? def timeout(): darea.queue_draw() return True # Initialize the window. window = gtk.Window() window.resize(size, size) window.connect("destroy", gtk.main_quit) darea = gtk.DrawingArea() darea.connect("expose-event", expose) window.add(darea) window.show_all() # Self-evident? gobject.idle_add(timeout) gtk.main()

    Read the article

  • Loading .dll/.exe from file into temporary AppDomain throws Exception

    Hi Gang, I am trying to make a Visual Studio AddIn that removes unused references from the projects in the current solution (I know this can be done, Resharper does it, but my client doesn't want to pay for 300 licences). Anyhoo, I use DTE to loop through the projects, compile their assemblies, then reflect over those assemblies to get their referenced assemblies and cross-examine the .csproj file. Problem: since the .dll/.exe I loaded up with Reflection doesn't unload until the app domian unloads, it is now locked and the projects can't be built again because VS tries to re-create the files (all standard stuff). I have tried creating temporary files, then reflecting over them...no worky, still have locked original files (I totally don’t understand that BTW). Now I am now going down the path of creating a temporary AppDomain to load the files into and then destroy. I am having problems loading the files though: The way I understand AddDomain.Load is that I should create and send a byte array of the assembly to it. I do that: FileStream fs = new FileStream(assemblyFile, FileMode.Open); byte[] assemblyFileBuffer = new byte[(int)fs.Length]; fs.Read(assemblyFileBuffer, 0, assemblyFileBuffer.Length); fs.Close(); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ApplicationBase = assemblyFileInfo.Directory.FullName; AppDomain tempAppDomain = AppDomain.CreateDomain("TempAppDomain", null, domainSetup); Assembly projectAssembly = tempAppDomain.Load(assemblyFileBuffer); The last line throws an exception: "Could not load file or assembly 'WindowsFormsApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.":"WindowsFormsApplication3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}" Any help or thoughts would be greatly appreciated. My head is lopsided from beating it against the wall... Thanks, Dan

    Read the article

  • A simple way to put a UIImage in a UIButton

    - by Alice
    I have a UIButton in my iPhone app. I set its size to 100x100. I have an image that is 400x200 that I wish to display in the button. The button STILL needs to stay at 100x100... and I want the image to downsize to fit... but keep the correct aspect ratio. I thought that's what "Aspect Fit" was used for. Do I include my image with setImage, or setBackgroundImage? Do I set AspectFit for the button? or the image? or the background image? (I need the smaller images to INCREASE in size. While larger images should DESCREASE in size. Always keeping the button at 100x100.) I've tried countless combinations of all of the above... and I just can't seem to get everything to work at the same time: Don't change the button's size of 100x100. Don't destroy the image's aspect ratio. Always increase small images to fit the button. Always decrease large images to fit the button. Never clip any of the image edges. Never require the "put UIButtons over all your UIimages" hack. Don't require everyone to upgrade to v4.2.1 just to use new framework methods. I see so many apps, with so many fully-working image-buttons... that I can't believe I can't figure out this very simple, very common thing. Ugh.

    Read the article

  • HTML5 audio object doesn't play on iPad (when called from a setTimeout)

    - by Dan Halliday
    I have a page with a hidden <audio> object which is being started and stopped using a custom button via javascript. (The reason being I want to customise the button, and that drawing an audio player seems to destroy rendering performance on iPad anyway). A simplified example (in coffeescript): // Works fine on all browsers constructor: (@_button, @_audio) -> @_button.on 'click', @_play // Bind button's click event with jQuery _play: (e) => @_audio[0].play() // Call play() on audio element The audio plays fine when triggered from a function bound to a click event, but I actually want an animation to complete before the file plays so I put .play() inside a setTimeout. However I just can't get this to work: // Will not play on iPad constructor: (@_button, @_audio) -> @_button.on 'click', @_play // Bind button's click event with jQuery _play: (e) => setTimeout (=> // Declare a 300ms timeout @_audio[0].play() // Call play() on audio element ), 300 I've checked that @_audio (this._audio) is in scope and that its play() method exists. Why doesn't this work on iPad?

    Read the article

  • tomcat resource missing, servlet not running

    - by user2837260
    import javax.servlet.*; import java.io.*; public class MyServlet implements Servlet { public void init(ServletConfig con) {} public void service(ServletRequest req, ServletResponse res) throws IOException,ServletException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); String s="blah"; String s1="blah"; out.println("<html><body>"); if((s.equals(req.getParameter("firstname")))&&(s1.equals(req.getParameter("pwd")))) out.println("passwords match"); else out.println("password and name combo does not match"); out.println("</body></html>"); } public void destroy() {} public ServletConfig getServletConfig() { return null;} public String getServletInfo() { return null;} } this is my java file with the servlet class.its saved with the name MyServlet.java and so is the class file. and here is the xml file: <web-app> <servlet> <servlet-name>demoo</servlet-name> <servlet-class>MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>demoo</servlet-name> <url-pattern>/demo</url-pattern> </servlet-mapping> </web-app> i have made the folder as WEB-INF and then classes... WEB-INF also contains the .xml file but when i try to run the servlet , it says resource not found ps- i am already looking for the servlet with the name :demo localhost:8081/s1/demo* s1 is the war file * a html file in the war file seems to run fine on the server though. *

    Read the article

  • Getting list of states/events from a model that AASM's

    - by Jason Nerer
    Hi, I successfully integrated the most recent AASM gem into an application, using it for the creation of a wizard. In my case I have a model order class Order < ActiveRecord::Base belongs_to :user has_one :billing_plan, :dependent => :destroy named_scope :with_user, ..... <snip> include AASM aasm_column :aasm_state aasm_initial_state :unauthenticated_user aasm_state :unauthenticated_user, :after_exit => [:set_state_completed] aasm_state : <snip> <and following the event definitions> end Now I would like to give an administrator the possibility to create his own graphs through the AASM states. Therefore I created two additional models called OrderFlow and Transition where there order_flow has many transitions and order belongs_to order_flow. No problem so far. Now I would like to give my admin the possibility to dynamically add existing transitions / events to an order_flow graph. The problem now is, that I do not find any possibility to get a list of all events / transitions out of my order model. aasm_states_for_select seems to be the correct candidate, but I cannot call it on my order model. Can anyone help? Thx in advance. J.

    Read the article

  • Update multiple progress bar with gtk c++

    - by Yadira Suazo
    I need to output the i progress bars and update them all. But only the last one updates i times. This is the code: static void calculaPi (GtkButton * boton, Datos * dDatos){ const char * threads; GtkWidget * barra, *bot2, *button, *progress, *vbox; threads = gtk_entry_get_text(GTK_ENTRY(dDatos->dthreads )); gint ithreads = 1; ithreads = atoi(threads); barra = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title((GtkWindow *) barra, "Loteria de Threads"); gtk_window_set_default_size(GTK_WINDOW(barra), 300, ithreads*30); gtk_window_set_position(GTK_WINDOW(barra), GTK_WIN_POS_CENTER); button = gtk_button_new_with_label ("Click me!"); vbox = gtk_vbox_new (FALSE, 5); gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 5); gtk_container_add (GTK_CONTAINER (barra), vbox); for (gint i = 1 ; i <= ithreads; i++) { progress = gtk_progress_bar_new (); gtk_box_pack_start (GTK_BOX (vbox), progress, FALSE, FALSE, 5); g_object_set_data (G_OBJECT (barra), "pbar", (gpointer) progress); g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (button_clicked), (gpointer) barra); } bot2 = gtk_button_new_with_label("Salir"); gtk_box_pack_start (GTK_BOX (vbox), bot2, FALSE, FALSE, 5); gtk_widget_set_size_request(bot2, 100, 35); g_signal_connect (G_OBJECT (bot2), "clicked", G_CALLBACK (destroy), G_OBJECT (barra)); gtk_widget_show_all(barra); gtk_main(); } static void button_clicked (GtkButton *button, GtkWidget *barra) { GtkProgressBar *progress; gdouble percent = 0.0; gtk_widget_set_sensitive (GTK_WIDGET (button), FALSE); progress = GTK_PROGRESS_BAR (g_object_get_data (G_OBJECT (barra), "pbar")); while (percent <= 100.0) { gchar *message = g_strdup_printf ("%.0f%% Complete", percent); gtk_progress_bar_set_fraction (progress, percent / 100.0); gtk_progress_bar_set_text (progress, message); while (gtk_events_pending ()) gtk_main_iteration (); g_usleep (500000); percent += 5.0; } }

    Read the article

  • Rails Association Problem

    - by looloobs
    I am having trouble with this association. I need to get an array of the primaries that belong to the soldiers in a platoon. So once I get all the soldiers in a platoon: @company = Company.find_by_id(1) @platoons = @company.platoons <% @platoons.each do |p| %> <%= p.soldiers.primaries.find(:all,:conditions => ["relationship = ? AND contacted = ?", 'Spouse', 'Yes'])) %> <% end %> * So there is no method for primaries, I assume this is because I am trying to call an association on an array. Soldiers have a platoon_id but primaries do not, they only have the association to soldiers in that platoon. How do I do this? I need it to return an array of Primaries. Thanks in advance! class Soldier < ActiveRecord::Base belongs_to :company belongs_to :platoon has_many :primaries, :dependent => :destroy end class Platoon < ActiveRecord::Base belongs_to :company belongs_to :battalion has_many :soldiers end class Primary < ActiveRecord::Base belongs_to :soldier belongs_to :company end

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >