Search Results

Search found 711 results on 29 pages for 'pos'.

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

  • jQuery 1.4 Opacity and IE Filters

    - by Rick Strahl
    Ran into a small problem today with my client side jQuery library after switching to jQuery 1.4. I ran into a problem with a shadow plugin that I use to provide drop shadows for absolute elements – for Mozilla WebKit browsers the –moz-box-shadow and –webkit-box-shadow CSS attributes are used but for IE a manual element is created to provide the shadow that underlays the original element along with a blur filter to provide the fuzziness in the shadow. Some of the key pieces are: var vis = el.is(":visible"); if (!vis) el.show(); // must be visible to get .position var pos = el.position(); if (typeof shEl.style.filter == "string") sh.css("filter", 'progid:DXImageTransform.Microsoft.Blur(makeShadow=true, pixelradius=3, shadowOpacity=' + opt.opacity.toString() + ')'); sh.show() .css({ position: "absolute", width: el.outerWidth(), height: el.outerHeight(), opacity: opt.opacity, background: opt.color, left: pos.left + opt.offset, top: pos.top + opt.offset }); This has always worked in previous versions of jQuery, but with 1.4 the original filter no longer works. It appears that applying the opacity after the original filter wipes out the original filter. IOW, the opacity filter is not applied incrementally, but absolutely which is a real bummer. Luckily the workaround is relatively easy by just switching the order in which the opacity and filter are applied. If I apply the blur after the opacity I get my correct behavior back with both opacity: sh.show() .css({ position: "absolute", width: el.outerWidth(), height: el.outerHeight(), opacity: opt.opacity, background: opt.color, left: pos.left + opt.offset, top: pos.top + opt.offset }); if (typeof shEl.style.filter == "string") sh.css("filter", 'progid:DXImageTransform.Microsoft.Blur(makeShadow=true, pixelradius=3, shadowOpacity=' + opt.opacity.toString() + ')'); While this works this still causes problems in other areas where opacity is implicitly set in code such as for fade operations or in the case of my shadow component the style/property watcher that keeps the shadow and main object linked. Both of these may set the opacity explicitly and that is still broken as it will effectively kill the blur filter. This seems like a really strange design decision by the jQuery team, since clearly the jquery css function does the right thing for setting filters. Internally however, the opacity setting doesn’t use .css instead hardcoding the filter which given jQuery’s usual flexibility and smart code seems really inappropriate. The following is from jQuery.js 1.4: var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } You can see here that the style is explicitly set in code rather than relying on $.css() to assign the value resulting in the old filter getting wiped out. jQuery 1.32 looks a little different: // IE uses filters for opacity if ( !jQuery.support.opacity && name == "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level elem.zoom = 1; // Set the alpha filter to set the opacity elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) + (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"); } return elem.filter && elem.filter.indexOf("opacity=") >= 0 ? (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '': ""; } Offhand I’m not sure why the latter works better since it too is assigning the filter. However, when checking with the IE script debugger I can see that there are actually a couple of filter tags assigned when using jQuery 1.32 but only one when I use jQuery 1.4. Note also that the jQuery 1.3 compatibility plugin for jQUery 1.4 doesn’t address this issue either. Resources ww.jquery.js (shadow plug-in $.fn.shadow) © Rick Strahl, West Wind Technologies, 2005-2010Posted in jQuery  

    Read the article

  • Finding all the shortest paths between two nodes in unweighted directed graphs using BFS algorithm

    - by andra-isan
    Hi All, I am working on a problem that I need to find all the shortest path between two nodes in a given directed unweighted graph. I have used BFS algorithm to do the job, but unfortunately I can only print one shortest path not all of them, for example if they are 4 paths having lenght 3, my algorithm only prints the first one but I would like it to print all the four shortest paths. I was wondering in the following code, how should I change it so that all the shortest paths between two nodes could be printed out? class graphNode{ public: int id; string name; bool status; double weight;}; map<int, map<int,graphNode>* > graph; int Graph::BFS(graphNode &v, graphNode &w){ queue <int> q; map <int, int> map1; // this is to check if the node has been visited or not. std::string str= ""; map<int,int> inQ; // just to check that we do not insert the same iterm twice in the queue map <int, map<int, graphNode>* >::iterator pos; pos = graph.find(v.id); if(pos == graph.end()) { cout << v.id << " does not exists in the graph " <<endl; return 1; } int parents[graph.size()+1]; // this vector keeps track of the parents for the node parents[v.id] = -1; // there is a direct path between these two words, simply print that path as the shortest path if (findDirectEdge(v.id,w.id) == 1 ){ cout << " Shortest Path: " << v.id << " -> " << w.id << endl; return 1; } //if else{ int gn; map <int, map<int, graphNode>* >::iterator pos; q.push(v.id); inQ.insert(make_pair(v.id, v.id)); while (!q.empty()){ gn = q.front(); q.pop(); map<int, int>::iterator it; cout << " Popping: " << gn <<endl; map1.insert(make_pair(gn,gn)); //backtracing to print all the nodes if gn is the same as our target node such as w.id if (gn == w.id){ int current = w.id; cout << current << " - > "; while (current!=v.id){ current = parents[current]; cout << current << " -> "; } cout <<endl; } if ((pos = graph.find(gn)) == graph.end()) { cout << " pos is empty " <<endl; continue; } map<int, graphNode>* pn = pos->second; map<int, graphNode>::iterator p = pn->begin(); while(p != pn->end()) { map<int, int>::iterator it; //map1 keeps track of the visited nodes it = map1.find(p->first); graphNode gn1= p->second; if (it== map1.end()) { map<int, int>::iterator it1; //if the node already exits in the inQ, we do not insert it twice it1 = inQ.find(p->first); if (it1== inQ.end()){ parents[p->first] = gn; cout << " inserting " << p->first << " into the queue " <<endl; q.push(p->first); // add it to the queue } //if } //if p++; } //while } //while } I do appreciate all your great help Thanks, Andra

    Read the article

  • google link for the RGBA library?

    - by Navruk
    I want google link for the RGBA library <script type='text/javascript' src='jquery.color-RGBa-patch.js'></script> This file contains /* * jQuery Color Animations */ (function(jQuery){ // We override the animation for all of these color styles jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ jQuery.fx.step[attr] = function(fx){ if ( fx.colorFunction == undefined || fx.state == 0 ) { fx.start = getColor( fx.elem, attr ); fx.end = getRGB( fx.end ); if ( fx.start == undefined ) { fx.start = [ 255,255,255,0 ]; } else { if ( fx.start[3] == undefined ) // if alpha channel is not spotted fx.start[3] = 1; // assume it is fully opaque if ( fx.start[3] == 0 ) // if alpha is present and fully transparent fx.start[0] = fx.start[1] = fx.start[2] = 255; // assume starting with white } if ( fx.end[3] == undefined ) // if alpha channel is not spotted fx.end[3] = 1; // assume it is fully opaque fx.colorFunction = ( fx.start[3] == 1 && fx.end[3] == 1 ? calcRGB : calcRGBa ); } fx.elem.style[attr] = fx.colorFunction(); } }); var calcRGB = function() { return 'rgb(' + Math.max(Math.min( parseInt((this.pos * (this.end[0] - this.start[0])) + this.start[0]), 255), 0) + ',' + Math.max(Math.min( parseInt((this.pos * (this.end[1] - this.start[1])) + this.start[1]), 255), 0) + ',' + Math.max(Math.min( parseInt((this.pos * (this.end[2] - this.start[2])) + this.start[2]), 255), 0) + ')'; }; var calcRGBa = function() { return 'rgba(' + Math.max(Math.min( parseInt((this.pos * (this.end[0] - this.start[0])) + this.start[0]), 255), 0) + ',' + Math.max(Math.min( parseInt((this.pos * (this.end[1] - this.start[1])) + this.start[1]), 255), 0) + ',' + Math.max(Math.min( parseInt((this.pos * (this.end[2] - this.start[2])) + this.start[2]), 255), 0) + ',' + Math.max(Math.min( parseFloat((this.pos * (this.end[3] - this.start[3])) + this.start[3]), 1), 0) + ')'; }; // Color Conversion functions from highlightFade // By Blair Mitchelmore // http://jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [255,255,255] function getRGB(color) { var result; // Check if we're already dealing with an array of colors if ( color && color.constructor == Array && color.length >= 3 ) return color; // Look for rgb(num,num,num) if (result = /rgba?\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,?\s*((?:[0-9](?:\.[0-9]+)?)?)\s*\)/.exec(color)) return [ parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), parseFloat(result[4]||1) ]; // Look for rgb(num%,num%,num%) if (result = /rgba?\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,?\s*((?:[0-9](?:\.[0-9]+)?)?)\s*\)/.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]||1)]; // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Otherwise, we're most likely dealing with a named color var colorName = jQuery.trim(color).toLowerCase(); if ( colors[colorName] != undefined ) return colors[colorName]; return [ 255, 255, 255, 0 ]; } function getColor(elem, attr) { var color; do { color = jQuery.curCSS(elem, attr); // Keep going until we find an element that has color, or we hit the body if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") ) break; attr = "backgroundColor"; } while ( elem = elem.parentNode ); return getRGB(color); }; // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ var colors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0] }; })(jQuery);

    Read the article

  • Ruby: implementing alpha-beta pruning for tic-tac-toe

    - by DerNalia
    So, alpha-beta pruning seems to be the most efficient algorithm out there aside from hard coding (for tic tac toe). However, I'm having problems converting the algorithm from the C++ example given in the link: http://www.webkinesia.com/games/gametree.php #based off http://www.webkinesia.com/games/gametree.php # (converted from C++ code from the alpha - beta pruning section) # returns 0 if draw LOSS = -1 DRAW = 0 WIN = 1 @next_move = 0 def calculate_ai_next_move score = self.get_best_move(COMPUTER, WIN, LOSS) return @next_move end def get_best_move(player, alpha, beta) best_score = nil score = nil if not self.has_available_moves? return false elsif self.has_this_player_won?(player) return WIN elsif self.has_this_player_won?(1 - player) return LOSS else best_score = alpha NUM_SQUARES.times do |square| if best_score >= beta break end if self.state[square].nil? self.make_move_with_index(square, player) # set to negative of opponent's best move; we only need the returned score; # the returned move is irrelevant. score = -get_best_move(1-player, -beta, -alpha) if (score > bestScore) @next_move = square best_score = score end undo_move(square) end end end return best_score end the problem is that this is returning nil. some support methods that are used above: WAYS_TO_WIN = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],[0, 4, 8], [2, 4, 6]] def has_this_player_won?(player) result = false WAYS_TO_WIN.each {|solution| result = self.state[solution[0]] if contains_win?(solution) } return (result == player) end def contains_win?(ttt_win_state) ttt_win_state.each do |pos| return false if self.state[pos] != self.state[ttt_win_state[0]] or self.state[pos].nil? end return true end def make_move(x, y, player) self.set_square(x,y, player) end

    Read the article

  • Project Euler Problem 14

    - by MarkPearl
    The Problem The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. The Solution   public static long NextResultOdd(long n) { return (3 * n) + 1; } public static long NextResultEven(long n) { return n / 2; } public static long TraverseSequence(long n) { long x = n; long count = 1; while (x > 1) { if (x % 2 == 0) x = NextResultEven(x); else x = NextResultOdd(x); count++; } return count; } static void Main(string[] args) { long largest = 0; long pos = 0; for (long i = 1000000; i > 1; i--) { long temp = TraverseSequence(i); if (temp > largest) { largest = temp; pos = i; } } Console.WriteLine("{0} - {1}", pos, largest); Console.ReadLine(); }

    Read the article

  • Branding/Restricting a Software by License/Serial

    - by Sid
    I have made a POS System for a client of mine using MS Access Server-Client approach. He asked me to brand his software to allow only a certain "number" of users (cashiers) to access the POS System, and must be determined to the license his client will buy. EX: 10 User License = 10 Cashiers ( not necessarily 10 users, it can be 30 users, shifting) = it means 10 PCs will be installed with the client software I made. How and where do I put the logic that will determine if it is licensed or not. What I have done: I have created a serial key generator using Name. Problem is it can be duplicated once you give than name+serial combination, it would still work. I am counting the number of users logged at a time. This could be problematic as I am using MSAccess and not MSSQL. I have scrapped this idea, He also asked me if I could just put serial+mac address combination. That I could do but he will have a hard time implementing it and selling it if he needs the mac address of every computers to be installed with my POS. I am at lost on what can I do. Would like to ask for tips and suggestions. Thank you.

    Read the article

  • Using texture() in combination with JBox2D

    - by Valentino Ru
    I'm getting some trouble using the texture() method inside beginShape()/endShape() clause. In the display()-method of my class TowerElement (a bar which is DYNAMIC), I draw the object like following: void display(){ Vec2 pos = level.getLevel().getBodyPixelCoord(body); float a = body.getAngle(); // needed for rotation pushMatrix(); translate(pos.x, pos.y); rotate(-a); fill(temp); // temp is a color defined in the constructor stroke(0); beginShape(); vertex(-w/2,-h/2); vertex(w/2,-h/2); vertex(w/2,h-h/2); vertex(-w/2,h-h/2); endShape(CLOSE); popMatrix(); } Now, according to the API, I can use the texture() method inside the shape definition. Now when I remove the fill(temp) and put texture(img) (img is a PImage defined in the constructor), the stroke gets drawn, but the bar isn't filled and I get the warning texture() is not available with this renderer What can I do in order to use textures anyway? I don't even understand the error message, since I do not know much about different renderers.

    Read the article

  • Vim: Custom Folding for special doc

    - by Matthias Guenther
    Here is the code: package localhost import scala.tools.nsc.reporters._ import scala.tools.nsc.util.Position class MyReporter extends Reporter { /** <p> * Give message of an rejected program * </p> */ def info0(pos: Position, msg: String, severity: Severity, force: Boolean) = { severity match { case INFO => case WARNING => case ERROR => println("error on pos: " +pos+" message: "+msg) } } } So I want to to fold /** <p> * Give message of an rejected program * </p> */ to something like: /** */ How is this possible? Thanks for your help.

    Read the article

  • Hit Detection When rotating the camera

    - by SD1990
    This bug/feature has been plaguing me for a while and i want to know the best way to fix it. I'm testing simple hit detection with a wall, like: if (Forward button) if(Inv.w.z < -49 || Inv.w.z > 49) pos.z = 0.0f; else if(Inv.w.x < -49 || Inv.w.x > 49) pos.z = 0.0f; else pos.z = +1.0f; where Inv.w. is the camera positions. Now obviously when i now hit that certain point i can no longer move away from the wall or anywhere in fact. How can i change this code to allow for the camera to be turned away from the wall so therefore i should be allowed to move? for example, the player hits the wall and i cant move until i turn around or to the side? I know its something to do with velocity but im pretty new to this so please bare with me if this is easy.

    Read the article

  • What could cause a sudden stop in Box2D?

    - by alexanderpine
    I'm using Box2d for a game, and I have a bug that's driving me nuts. I've simplified the situation down to a square player sliding back and forth frictionlessly on top of a floor composed of a series of square tiles, driven by the left and right keys (which apply a horizontal force). Works great, sliding back and forth across the whole floor. Except... Every once in a while, the player will suddenly stick at the edge of one of the tiles as if it is hitting a (nonexistent) wall. Further pushes in the same direction it was traveling will fail, but as soon as I push backwards once in the opposite direction, I can push forwards past the sticking point again. The sticking point seems to be random, except for being on the edge of a tile. Happens while going left or right. For debugging purposes, I keep the Positions/velocity values for the previous two update ticks and print them out when this stop occurs. As an example, here you see the player moving right, decelerating slightly; pos2 should be about 8.7, but it stops dead instead. tick0: pos= 8.4636 vel= 7.1875 tick1: pos= 8.5816 vel= 7.0833 tick2: pos= 8.5816 vel= 0.0000 So, as the player is 0.8 and the tiles 1.0 wide, the player is stopping just as it is about to cross onto the next tile (8.5816 + 0.8/2 = 8.9816). In fact, I get a collision message (which I ignore except noting that it happened). It only seems to happen at x.5816 (or -x.4184) while moving right, and x.4167 (or -x.5833) while moving left I said that it's like hitting a wall, but in fact, when it hits a wall, the numbers look more like: tick0: pos0= 12.4131 vel2= 8.4375 tick1: pos1= 12.5555 vel1= 8.5417 tick2: pos2= 12.5850 vel0= 0.0000 so it moves further right on the last tick, which puts it in contact with the wall. Anyone seen anything like this. Any suggestion on how I could be causing this behavior.

    Read the article

  • moving in the wrong direction

    - by Will
    Solution: To move a unit forward: forward = Quaternion(0,0,0,1) rotation.normalize() # ocassionally ... pos += ((rotation * forward) * rotation.conjugated()).xyz().normalized() * speed I think the trouble stemmed from how the Euclid math library was doing Quaternion*Vector3 multiplication, although I can't see it. I have a vec3 position, a quaternion for rotation and a speed. I compute the player position like this: rot *= Quaternion().rotate_euler(0.,roll_speed,pitch_speed) rot.normalize() pos += rot.conjugated() * Vector3(0.,0.,-speed) However, printing the pos to console, I can see that I only ever seem to travel on the x-axis. When I draw the scene using the rot quaternion to rotate my camera, it shows a proper orientation. What am I doing wrong? Here's an example: You start off with rotation being an identity quaternion: w=1,x=0,y=0,z=0 You move forward; the code correctly decrements the Z You then pitch right over to face the other way; if you spin only 175deg it'll go in right direction; you have to spin past 180deg. It doesn't matter which direction you spin in, up or down, though Your quaternion can then be something like: w=0.1,x=0.1,y=0,z=0 And moving forward, you actually move backward?! (I am using the euclid Python module, but its the same as every other conjulate) The code can be tried online at http://williame.github.com/ludum_dare_24_evolution/ The only key that adjusts the speed is W and S. The arrow keys only adjust the pitch/roll. At first you can fly ok, but after a bit of weaving around you end up getting sucked towards one of the sides. The code is https://github.com/williame/ludum_dare_24_evolution/blob/cbacf61a7159d2c83a2187af5f2015b2dde28687/tiny1web.py#L102

    Read the article

  • Python - Bitmap won't draw/display

    - by Wallter
    I have been working on this project for some time now - it was originally supposed to be a test to see if, using wxPython, I could build a button 'from scratch.' From scratch means: that i would have full control over all the aspects of the button (i.e. controlling the BMP's that are displayed... what the event handlers did... etc.) I have run into several problems (as this is my first major python project.) Now, when the all the code is working for the life of me I can't get an image to display. Basic code - not working dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100) self.Refresh() self.Update() Full Main.py import wx from Custom_Button import Custom_Button from wxPython.wx import * ID_ABOUT = 101 ID_EXIT = 102 class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(400, 400)) self.CreateStatusBar() self.SetStatusText("Program testing custom button overlays") menu = wxMenu() menu.Append(ID_ABOUT, "&About", "More information about this program") menu.AppendSeparator() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menuBar = wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) # The call for the 'Experiential button' self.Button1 = Custom_Button(parent, -1, wx.Point(100, 100), wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), wx.Bitmap("/home/wallter/Desktop/Normal.bmp"), wx.Bitmap("/home/wallter/Desktop/Click.bmp")) # The following three lines of code are in place to try to get the # Button1 to display (trying to trigger the Paint event (the _onPaint.) # Because that is where the 'draw' functions are. self.Button1.Show(true) self.Refresh() self.Update() # Because the Above three lines of code did not work, I added the # following four lines to trigger the 'draw' functions to test if the # '_onPaint' method actually worked. # These lines do not work. dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.TimeToQuit) def OnAbout(self, event): dlg = wxMessageDialog(self, "Testing the functions of custom " "buttons using pyDev and wxPython", "About", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def TimeToQuit(self, event): self.Close(true) class MyApp(wx.App): def OnInit(self): frame = MyFrame(NULL, -1, "wxPython | Buttons") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() Full CustomButton.py import wx from wxPython.wx import * class Custom_Button(wx.PyControl): def __init__(self, parent, id, Pos, Over_BMP, Norm_BMP, Push_BMP, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self.pos = Pos self.Over_bmp = Over_BMP self.Norm_bmp = Norm_BMP self.Push_bmp = Push_BMP self._mouseIn = False self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def Iz(self): dc = wx.BufferedPaintDC(self) dc.DrawBitmap(self.Norm_bmp, 100, 100) def _onPaint(self, event): # The printing functions, they should work... but don't. dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # This never printed... I don't know if that means if the EVT # is triggering or what. print '_onPaint' # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: # If the Mouse is over the button dc.DrawBitmap(self.Over_bmp, self.pos) else: # Since the mouse isn't over it Print the normal one # This is adding on the above code to draw the bmp # in an attempt to get the bmp to display; to no avail. dc.DrawBitmap(self.Norm_bmp, self.pos) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self.Push_bmp, self.pos) This code won't work? I get no BMP displayed why? How do i get one? I've gotten the staticBitmap(...) to display one, but it won't move, resize, or anything for that matter... - it's only in the top left corner of the frame? Note: the frame is 400pxl X 400pxl - and the "/home/wallter/Desktop/Mouseover.bmp"

    Read the article

  • Table Name is null in the sqlite database in android device

    - by Mahe
    I am building a simple app which stores some contacts and retrieves contacts in android phone device. I have created my own database and a table and inserting the values to the table in phone. My phone is not rooted. So I cannot access the files, but I see that values are stored in the table. And tested on a emulator also. Till here it is fine. Display all the contacts in a list by fetching data from table. This is also fine. But the problem is When I am trying to delete the record, it shows the table name is null in the logcat(not an exception), and the data is not deleted. But in emulator the data is getting deleted from table. I am not able to achieve this through phone. This is my code for deleting, public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item .getMenuInfo(); int menuItemIndex = item.getItemId(); String[] menuItems = getResources().getStringArray(R.array.menu); String menuItemName = menuItems[menuItemIndex]; String listItemName = Customers[info.position]; if (item.getTitle().toString().equalsIgnoreCase("Delete")) { Toast.makeText( context, "Selected List item is: " + listItemName + "MenuItem is: " + menuItemName, Toast.LENGTH_LONG).show(); DB = context.openOrCreateDatabase("CustomerDetails.db", MODE_PRIVATE, null); try { int pos = info.position; pos = pos + 1; Log.d("", "customers[pos]: " + Customers[info.position]); Cursor c = DB .rawQuery( "Select customer_id,first_name,last_name from CustomerInfo", null); int rowCount = c.getCount(); DB.delete(Table_name, "customer_id" + "=" + String.valueOf(pos), null); DB.close(); Log.d("", "" + String.valueOf(pos)); Toast.makeText(context, "Deleted Customer", Toast.LENGTH_LONG) .show(); // Customers[info.position]=null; getCustomers(); } catch (Exception e) { Toast.makeText(context, "Delete unsuccessfull", Toast.LENGTH_LONG).show(); } } this is my logcat, 07-02 10:12:42.976: D/Cursor(1560): Database path: CustomerDetails.db 07-02 10:12:42.976: D/Cursor(1560): Table name : null 07-02 10:12:42.984: D/Cursor(1560): Database path: CustomerDetails.db 07-02 10:12:42.984: D/Cursor(1560): Table name : null Don't know the reason why data is not being deleted. Data exists in the table. This is the specification I have given for creating the table public static String customer_id="customer_id"; public static String site_id="site_id"; public static String last_name="last_name"; public static String first_name="first_name"; public static String phone_number="phone_number"; public static String address="address"; public static String city="city"; public static String state="state"; public static String zip="zip"; public static String email_address="email_address"; public static String custlat="custlat"; public static String custlng="custlng"; public static String Table_name="CustomerInfo"; final SQLiteDatabase DB = context.openOrCreateDatabase( "CustomerDetails.db", MODE_PRIVATE, null); final String CREATE_TABLE = "create table if not exists " + Table_name + " (" + customer_id + " integer primary key autoincrement, " + first_name + " text not null, " + last_name + " text not null, " + phone_number+ " integer not null, " + address+ " text not null, " + city+ " text not null, " + state+ " text not null, " + zip+ " integer not null, " + email_address+ " text not null, " + custlat+ " double, " + custlng+ " double " +" );"; DB.execSQL(CREATE_TABLE); DB.close(); Please correct my code. I am struggling from two days. Any help is appreciated!!

    Read the article

  • Finding the closest object in proxmity to the mouse Coordinates

    - by Cam
    Hey there, i've been working on a problem for a while now, which involves targeting the closest movieClip in relation to the x y coords of the mouse, I've attached a nice little acompanying graphic. Each mc added to the stage has it's own sub-class (HotSpots) which uses Pythag to measure distance from mouse. At this stage i can determine the closest value from my Main class but can't figure out how to reference it back to the movieclip... hope this makes sense. Below are the two Classes. My Main Class which attachs the mcs, and monitors mouse movement and traces closest value package { import flash.display.*; import flash.text.*; import flash.events.*; public class Main extends MovieClip { var pos:Number = 50; var nodeArray:Array; public function Main(){ nodeArray = []; for(var i:int = 0; i < 4; i++) { var hotSpot_mc:HotSpots = new HotSpots; hotSpot_mc.x += pos; hotSpot_mc.y += pos; addChild(hotSpot_mc); nodeArray.push(hotSpot_mc); // set some pos pos += 70; } stage.addEventListener(MouseEvent.MOUSE_MOVE,updateProxmity) } public function updateProxmity(e:MouseEvent):void { var tempArray:Array = new Array(); for(var i:int = 0; i < 4; i++) { this['tf'+[i]].text = String(nodeArray[i].dist); tempArray.push(nodeArray[i].dist); } tempArray.sort(Array.NUMERIC); var minValue:int = tempArray[0]; trace(minValue) } } } My HotSpots Class package { import flash.display.MovieClip; import flash.events.Event; import flash.text.TextField; public class HotSpots extends MovieClip { public var XSide:Number; public var YSide:Number; public var dist:Number = 0; public function HotSpots() { addEventListener(Event.ENTER_FRAME, textUp); } public function textUp(event:Event):void { XSide = this.x - MovieClip(root).mouseX; YSide = this.y - MovieClip(root).mouseY; dist = Math.round((Math.sqrt(XSide*XSide + YSide*YSide))); } } } thanks in advance

    Read the article

  • Unmanaged Code calling leads to heavy memory leak!!

    - by konnychen
    Maybe I need change the title as "Unmanaged Code calling leads to heavy memory leak!" The leak is around 30M/hour I think maybe I need complete my code here because the memory leak maybe not from a static string whereas my real code derive this string from external device (see new code attached). so I handle also unmanaged code. Could it be possible the leak comes from unmanaged code? But I freed the resouce by Marshal.FreeCoTaskMem(pos); oThread2 = new Thread(new ThreadStart(Cyclic_Call)); oThread2.Start(); delegate void SetText_lab_Statubar(string text); private void m_SetText_lab_Statubar(string text) { if (this.lab_Statubar.InvokeRequired) { SetText_lab_Statubar d = new SetText_lab_Statubar(m_SetText_lab_Statubar); this.Invoke(d, new object[] { text }); } else { this.lab_Statubar.Text = text; } } private void Cyclic_Call() { do { //... ... ReadMatrixCode(Station6, 0, str_Code); this.m_SetText_lab_Statubar(str_Code[4]); Thread.Sleep(100); } while (!b_AbortThraed); } private void ReadMatrixCode(Station st, int ItemNr, string[] str_Code) { IntPtr pItemStates = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; int NumItems = itemServerHandles.Length; m_SyncIO.Read(DataSrc, NumItems, itemServerHandles, out pItemStates, out pErrors); // This calls external dll which has some of "out IntPtr" errors = new int[NumItems]; Marshal.Copy(pErrors, errors, 0, NumItems); IntPtr pos = pItemStates; // Now get the read values and check errors for (int dwCount = 0; dwCount < NumItems; dwCount++) { result[dwCount] = (ITEMSTATE)Marshal.PtrToStructure(pos, typeof(ITEMSTATE)); pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(ITEMSTATE))); } // Free allocated COM-ressouces Marshal.FreeCoTaskMem(pItemStates); Marshal.FreeCoTaskMem(pErrors); pItemStates = IntPtr.Zero; pErrors = IntPtr.Zero; } m_syncIO is a class and finally it will call COM component which is defined below [Guid("39C12B52-011E-11D0-9675-1020AFD8ADB3")] [InterfaceType(1)] [ComConversionLoss] public interface ISyncIO { void Read(DATASOURCE dwSource, int dwCount, int[] phServer, out IntPtr ppItemValues, out IntPtr ppErrors); void Write(int dwCount, int[] phServer, object[] pItemValues, out IntPtr ppErrors); }

    Read the article

  • elisp: posn-at-point returns nil after goto-char. How to update the display before posn-at-point?

    - by Cheeso
    In emacs lisp, posn-at-point is documented as: posn-at-point is a built-in function in C source code. (posn-at-point &optional POS WINDOW) . Return position information for buffer POS in WINDOW. POS defaults to point in WINDOW; WINDOW defaults to the selected window. . Return nil if position is not visible in window. Otherwise, the return value is similar to that returned by event-start for a mouse click at the upper left corner of the glyph corresponding to the given buffer position: (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW) IMAGE (DX . DY) (WIDTH . HEIGHT)) The posn- functions access elements of such lists. ok, now I've got a function that looks something like this: (defun my-move-and-popup-menu () "move the point, then pop up a menu." (goto-char xxxx) (setq p (posn-at-point)) (my-popup-menu p ...) ) Basically, move the point, then retrieve the screen position at that point, and then popup a menu at that screen position. But I am finding that posn-at-point returns non-nil, only if the xxxx character position (the after position) is visible in the window, before the call to goto-char. It seems that the position is not actually updated until exit from the function. If goto-char goes a long way, more than one screenful, then the retrieved position is always nil, and my code doesn't know where to popup the menu. The reason I suggest that the position is not actually updated until exit from the function - when the menu successfully pops up, the cursor is clearly visible in its previous location while the popup menu is being displayed. When I dismiss the menu, the cursor moves to where I expected it to move, after the goto-char call. How can I get the position to be really updated, between goto-char and posn-at-point, so that posn-at-point will not return nil? In a Windows Forms application I would call Form.Update() or something similar to update the display in the middle of an event handler. What's the emacs version of that?

    Read the article

  • FBX Importer - Texture Name

    - by CmasterG
    I have a problem with the FBX SDK. I read in the data for the vertex position and the uv coordinates. It works fine, but now I want to read for each polygon to which texture it belongs, so that I can have models with multiple textures. Can anyone tell me how I can get the texture name (file name) for my polygon. My code to read in vertex position and uv coordinates is the following: int i, j, lPolygonCount = pMesh->GetPolygonCount(); FbxVector4* lControlPoints = pMesh->GetControlPoints(); int vertexId = 0; for (i = 0; i < lPolygonCount; i++) { int lPolygonSize = pMesh->GetPolygonSize(i); for (j = 0; j < lPolygonSize; j++) { int lControlPointIndex = pMesh->GetPolygonVertex(i, j); FbxVector4 pos = lControlPoints[lControlPointIndex]; current_model[vertex_index].x = pos.mData[0] - pivot_offset[0]; current_model[vertex_index].y = pos.mData[1] - pivot_offset[1]; current_model[vertex_index].z = pos.mData[2]- pivot_offset[2]; FbxVector4 vertex_normal; pMesh->GetPolygonVertexNormal(i,j, vertex_normal); current_model[vertex_index].nx = vertex_normal.mData[0]; current_model[vertex_index].ny = vertex_normal.mData[1]; current_model[vertex_index].nz = vertex_normal.mData[2]; //read in UV data FbxStringList lUVSetNameList; pMesh->GetUVSetNames(lUVSetNameList); //get lUVSetIndex-th uv set const char* lUVSetName = lUVSetNameList.GetStringAt(0); const FbxGeometryElementUV* lUVElement = pMesh->GetElementUV(lUVSetName); if(!lUVElement) continue; // only support mapping mode eByPolygonVertex and eByControlPoint if( lUVElement->GetMappingMode() != FbxGeometryElement::eByPolygonVertex && lUVElement->GetMappingMode() != FbxGeometryElement::eByControlPoint ) return; //index array, where holds the index referenced to the uv data const bool lUseIndex = lUVElement->GetReferenceMode() != FbxGeometryElement::eDirect; const int lIndexCount= (lUseIndex) ? lUVElement->GetIndexArray().GetCount() : 0; FbxVector2 lUVValue; //get the index of the current vertex in control points array int lPolyVertIndex = pMesh->GetPolygonVertex(i,j); //the UV index depends on the reference mode //int lUVIndex = lUseIndex ? lUVElement->GetIndexArray().GetAt(lPolyVertIndex) : lPolyVertIndex; int lUVIndex = pMesh->GetTextureUVIndex(i, j); lUVValue = lUVElement->GetDirectArray().GetAt(lUVIndex); current_model[vertex_index].tu = (float)lUVValue.mData[0]; current_model[vertex_index].tv = (float)lUVValue.mData[1]; vertex_index ++; } } float v1[3], v2[3], v3[3]; v1[0] = current_model[vertex_index - 3].x; v1[1] = current_model[vertex_index - 3].y; v1[2] = current_model[vertex_index - 3].z; v2[0] = current_model[vertex_index - 2].x; v2[1] = current_model[vertex_index - 2].y; v2[2] = current_model[vertex_index - 2].z; v3[0] = current_model[vertex_index - 1].x; v3[1] = current_model[vertex_index - 1].y; v3[2] = current_model[vertex_index - 1].z; collision_model->addTriangle(v1,v2,v3);

    Read the article

  • How to update a QPixmap in a QGraphicsView with PyQt

    - by pops
    I am trying to paint on a QPixmap inside a QGraphicsView. The painting works fine, but the QGraphicsView doesn't update it. Here is some working code: #!/usr/bin/env python from PyQt4 import QtCore from PyQt4 import QtGui class Canvas(QtGui.QPixmap): """ Canvas for drawing""" def __init__(self, parent=None): QtGui.QPixmap.__init__(self, 64, 64) self.parent = parent self.imH = 64 self.imW = 64 self.fill(QtGui.QColor(0, 255, 255)) self.color = QtGui.QColor(0, 0, 0) def paintEvent(self, point=False): if point: p = QtGui.QPainter(self) p.setPen(QtGui.QPen(self.color, 1, QtCore.Qt.SolidLine)) p.drawPoints(point) def clic(self, mouseX, mouseY): self.paintEvent(QtCore.QPoint(mouseX, mouseY)) class GraphWidget(QtGui.QGraphicsView): """ Display, zoom, pan...""" def __init__(self): QtGui.QGraphicsView.__init__(self) self.im = Canvas(self) self.imH = self.im.height() self.imW = self.im.width() self.zoomN = 1 self.scene = QtGui.QGraphicsScene(self) self.scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) self.scene.setSceneRect(0, 0, self.imW, self.imH) self.scene.addPixmap(self.im) self.setScene(self.scene) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter) self.setMinimumSize(400, 400) self.setWindowTitle("pix") def mousePressEvent(self, event): if event.buttons() == QtCore.Qt.LeftButton: pos = self.mapToScene(event.pos()) self.im.clic(pos.x(), pos.y()) #~ self.scene.update(0,0,64,64) #~ self.updateScene([QtCore.QRectF(0,0,64,64)]) self.scene.addPixmap(self.im) print('items') print(self.scene.items()) else: return QtGui.QGraphicsView.mousePressEvent(self, event) def wheelEvent(self, event): if event.delta() > 0: self.scaleView(2) elif event.delta() < 0: self.scaleView(0.5) def scaleView(self, factor): n = self.zoomN * factor if n < 1 or n > 16: return self.zoomN = n self.scale(factor, factor) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) widget = GraphWidget() widget.show() sys.exit(app.exec_()) The mousePressEvent does some painting on the QPixmap. But the only solution I have found to update the display is to make a new instance (which is not a good solution). How do I just update it?

    Read the article

  • Getting an Error Trying to Create an Object in Python

    - by Nick Rogers
    I am trying to create an object from a class in python but I am getting an Error, "e_tank = EnemyTank() TypeError: 'Group' object is not callable" I am not sure what this means, I have tried Google but I couldn't get a clear answer on what is causing this error. Does anyone understand why I am unable to create an object from my EnemyTank Class? Here is my code: #Image Variables bg = 'bg.jpg' bunk = 'bunker.png' enemytank = 'enemy-tank.png' #Import Pygame Modules import pygame, sys from pygame.locals import * #Initializing the Screen pygame.init() screen = pygame.display.set_mode((640,360), 0, 32) background = pygame.image.load(bg).convert() bunker_x, bunker_y = (160,0) class EnemyTank(pygame.sprite.Sprite): e_tank = pygame.image.load(enemytank).convert_alpha() def __init__(self, startpos): pygame.sprite.Sprite.__init__(self, self.groups) self.pos = startpos self.image = EnemyTank.image self.rect = self.image.get_rect() def update(self): self.rect.center = self.pos class Bunker(pygame.sprite.Sprite): bunker = pygame.image.load(bunk).convert_alpha() def __init__(self, startpos): pygame.spriter.Sprite.__init__(self, self.groups) self.pos = startpos self.image = Bunker.image self.rect = self.image.get_rect() def getCollisionObjects(self, EnemyTank): if (EnemyTank not in self._allgroup, False): return False self._allgroup.remove(EnemyTank) result = pygame.sprite.spritecollide(EnemyTank, self._allgroup, False) self._allgroup.add(EnemyTank) def update(self): self.rect.center = self.pos #Setting Up The Animation x = 0 clock = pygame.time.Clock() speed = 250 allgroup = pygame.sprite.Group() EnemyTank = allgroup Bunker = allgroup e_tank = EnemyTank() bunker = Bunker()5 #Main Loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() screen.blit(background, (0,0)) screen.blit(bunker, (bunker_x, bunker_y)) screen.blit(e_tank, (x, 0)) pygame.display.flip() #Animation milli = clock.tick() seconds = milli/1000. dm = seconds*speed x += dm if x>640: x=0 #Update the Screen pygame.display.update()

    Read the article

  • How to optimize this algorithm?

    - by Bakhtiyor
    I have two sets of arrays like this for example. $Arr1['uid'][]='user 1'; $Arr1['weight'][]=1; $Arr1['uid'][]='user 2'; $Arr1['weight'][]=10; $Arr1['uid'][]='user 3'; $Arr1['weight'][]=5; $Arr2['uid'][]='user 1'; $Arr2['weight'][]=3; $Arr2['uid'][]='user 4'; $Arr2['weight'][]=20; $Arr2['uid'][]='user 5'; $Arr2['weight'][]=15; $Arr2['uid'][]='user 2'; $Arr2['weight'][]=2; The size of two arrays could be different of course. $Arr1 has coefficient of 0.7 and $Arr2 has coefficient of 0.3. I need to calculate following formula $result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$index]*$Arr2Coeff; where $Arr1['uid']=$Arr2['uid']. So when $Arr1['uid'] doesn't exists in $Arr2 then we need to omit $Arr2 and vice versa. And, here is an algorithm I am using now. foreach($Arr1['uid'] as $index=>$arr1_uid){ $pos=array_search($arr1_uid, $Arr2['uid']); if ($pos===false){ $result=$Arr1['weight'][$index]*$Arr1Coeff; echo "<br>$arr1_uid has not found and RES=".$result; }else{ $result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$pos]*$Arr2Coeff; echo "<br>$arr1_uid has found on $pos and RES=".$result; } } foreach($Arr2['uid'] as $index=>$arr2_uid){ if (!in_array($arr2_uid, $Arr1['uid'])){ $result=$Arr2['weight'][$index]*$Arr2Coeff; echo "<br>$arr2_uid has not found and RES=".$result; }else{ echo "<br>$arr2_uid has found somewhere"; } } The question is how can I optimize this algorithm? Can you offer other better solution for this problem? Thank you.

    Read the article

  • How to change one Button background in a gridview? -- Android

    - by Tstop Studios
    I have a GridView with 16 ImageView buttons. My program makes a random number and when the user clicks a button in the gridview, i want it to take the random number (0-15) and set the background of the tile with the same position as the random number (0-15) to a different image. How can I just change one of the buttons background? Here's my code so far: public class ButtonHider extends Activity { Random random = new Random(); int pos; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.button_hider); pos = random.nextInt(15); GridView gridview = (GridView) findViewById(R.id.gvBH); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { pos = random.nextInt(16); if (position == pos) { Toast.makeText(ButtonHider.this, "Found Me!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ButtonHider.this, "Try Again!!", Toast.LENGTH_SHORT).show(); } } }); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return 16; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some // attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(15, 15, 15, 15); } else { imageView = (ImageView) convertView; } imageView.setImageResource(R.drawable.bh_b); return imageView; } } }

    Read the article

  • BlackBerry:Reduce space between 2 buttons in HorizontalFieldManager

    - by user469999
    hi In blackberry i have created a horizontal field managar and added some buttons of small size to it to display toolbar at the bottom of the screen.But my problem is there is too much space between the 2 buttons.I have to reduce this space between 2 buttons so that i can manage to place atleast 6 buttons at the bottom of the screen.I am using the BFmsg.setMargin(305,0,0,40) statement. can anyone please help me on this. Following is my code : BFcontacts = new ButtonField("Cnt") { protected void paint(Graphics graphics) { //Bitmap contactsbitmap = Bitmap.getBitmapResource("contacts.jpg"); //graphics.drawBitmap(0, 0, contactsbitmap.getWidth(), contactsbitmap.getHeight(), contactsbitmap, 0, 0); graphics.setColor(Color.WHITE); graphics.drawText("Cnt",0,0); } }; BFcontacts.setMargin(305,0,0,10);//vertical pos,0,0,horizontal pos HFM.add(BFcontacts); BFmsg = new ButtonField("Msgs") { protected void paint(Graphics graphics) { //Bitmap msgsbitmap = Bitmap.getBitmapResource("messages.jpg"); //graphics.drawBitmap(0, 0, msgsbitmap.getWidth(), msgsbitmap.getHeight(), msgsbitmap, 0, 0); graphics.setColor(Color.WHITE); graphics.drawText("Msgs",0,0); } }; BFmsg.setMargin(305,0,0,40);//vertical pos,0,0,horizontal pos : original HFM.add(BFmsg); add(HFM) Thanks in advance

    Read the article

  • Does query plan optimizer works well with joined/filtered table-valued functions?

    - by smoothdeveloper
    In SQLSERVER 2005, I'm using table-valued function as a convenient way to perform arbitrary aggregation on subset data from large table (passing date range or such parameters). I'm using theses inside larger queries as joined computations and I'm wondering if the query plan optimizer work well with them in every condition or if I'm better to unnest such computation in my larger queries. Does query plan optimizer unnest table-valued functions if it make sense? If it doesn't, what do you recommend to avoid code duplication that would occur by manually unnesting them? If it does, how do you identify that from the execution plan? code sample: create table dbo.customers ( [key] uniqueidentifier , constraint pk_dbo_customers primary key ([key]) ) go /* assume large amount of data */ create table dbo.point_of_sales ( [key] uniqueidentifier , customer_key uniqueidentifier , constraint pk_dbo_point_of_sales primary key ([key]) ) go create table dbo.product_ranges ( [key] uniqueidentifier , constraint pk_dbo_product_ranges primary key ([key]) ) go create table dbo.products ( [key] uniqueidentifier , product_range_key uniqueidentifier , release_date datetime , constraint pk_dbo_products primary key ([key]) , constraint fk_dbo_products_product_range_key foreign key (product_range_key) references dbo.product_ranges ([key]) ) go . /* assume large amount of data */ create table dbo.sales_history ( [key] uniqueidentifier , product_key uniqueidentifier , point_of_sale_key uniqueidentifier , accounting_date datetime , amount money , quantity int , constraint pk_dbo_sales_history primary key ([key]) , constraint fk_dbo_sales_history_product_key foreign key (product_key) references dbo.products ([key]) , constraint fk_dbo_sales_history_point_of_sale_key foreign key (point_of_sale_key) references dbo.point_of_sales ([key]) ) go create function dbo.f_sales_history_..snip.._date_range ( @accountingdatelowerbound datetime, @accountingdateupperbound datetime ) returns table as return ( select pos.customer_key , sh.product_key , sum(sh.amount) amount , sum(sh.quantity) quantity from dbo.point_of_sales pos inner join dbo.sales_history sh on sh.point_of_sale_key = pos.[key] where sh.accounting_date between @accountingdatelowerbound and @accountingdateupperbound group by pos.customer_key , sh.product_key ) go -- TODO: insert some data -- this is a table containing a selection of product ranges declare @selectedproductranges table([key] uniqueidentifier) -- this is a table containing a selection of customers declare @selectedcustomers table([key] uniqueidentifier) declare @low datetime , @up datetime -- TODO: set top query parameters . select saleshistory.customer_key , saleshistory.product_key , saleshistory.amount , saleshistory.quantity from dbo.products p inner join @selectedproductranges productrangeselection on p.product_range_key = productrangeselection.[key] inner join @selectedcustomers customerselection on 1 = 1 inner join dbo.f_sales_history_..snip.._date_range(@low, @up) saleshistory on saleshistory.product_key = p.[key] and saleshistory.customer_key = customerselection.[key] I hope the sample makes sense. Much thanks for your help!

    Read the article

  • speed string search in PHP

    - by Marc
    Hi! I have a 1.2GB file that contains a one line string. What I need is to search the entire file to find the position of an another string (currently I have a list of strings to search). The way what I'm doing it now is opening the big file and move a pointer throught 4Kb blocks, then moving the pointer X positions back in the file and get 4Kb more. My problem is that a bigger string to search, a bigger time he take to got it. Can you give me some ideas to optimize the script to get better search times? this is my implementation: function busca($inici){ $limit = 4096; $big_one = fopen('big_one.txt','r'); $options = fopen('options.txt','r'); while(!feof($options)){ $search = trim(fgets($options)); $retro = strlen($search);//maybe setting this position absolute? (like 12 or 15) $punter = 0; while(!feof($big_one)){ $ara = fgets($big_one,$limit); $pos = strpos($ara,$search); $ok_pos = $pos + $punter; if($pos !== false){ echo "$pos - $punter - $search : $ok_pos <br>"; break; } $punter += $limit - $retro; fseek($big_one,$punter); } fseek($big_one,0); } } Thanks in advance!

    Read the article

  • python add two list and createing a new list

    - by Adam G.
    lst1 = ['company1,AAA,7381.0 ', 'company1,BBB,-8333.0 ', 'company1,CCC, 3079.999 ', 'company1,DDD,5699.0 ', 'company1,EEE,1640.0 ', 'company1,FFF,-600.0 ', 'company1,GGG,3822.0 ', 'company1,HHH,-600.0 ', 'company1,JJJ,-4631.0 ', 'company1,KKK,-400.0 '] lst2 =['company1,AAA,-4805.0 ', 'company1,ZZZ,-2576.0 ', 'company1,BBB,1674.0 ', 'company1,CCC,3600.0 ', 'company1,DDD,1743.998 '] output I need == ['company1,AAA,2576.0','company1,ZZZ,-2576.0 ','company1,KKK,-400.0 ' etc etc] I need to add it similar product number in each list and move it to a new list. I also need any symbol not being added together to be added to that new list. I am having problems with moving through each list. This is what I have: h = [] z = [] a = [] for g in hhl: spl1 = g.split(",") h.append(spl1[1]) for j in c_hhl: spl2 = j.split(",") **if spl2[1] in h: converted_num =(float(spl2[2]) +float(spl1[2])) pos=('{0},{1},{2}'.format(spl2[0],spl2[1],converted_num)) z.append(pos)** else: pos=('{0},{1},{2}'.format(spl2[0],spl2[1],spl2[2])) z.append(pos) for f in z: spl3 = f.split(",") a.append(spl3[1]) for n in hhl[:]: spl4 = n.split(",") if spl4[1] in a: got = (spl4[0],spl4[1],spl4[2]) hhl.remove(n) smash = hhl+z #for i in smash: for i in smash: print(i) I am having problem iterating through the list to make sure I get all of the simliar product to a new list,(bold) and any product not in list 1 but in lst2 to the new list and vice versa. I am sure there is a much easier way.

    Read the article

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