Search Results

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

Page 18/29 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Big Data Appliance

    - by David Dorf
    Today Oracle announced the next release of it's Big Data Appliance, an engineered system composed of hardware and software targeting the efficient processing of big data.  The solution leverages 288 Intel cores running Cloudera's distribution of Apache Hadoop in 1.1 TB of main memory.  This monster helps companies acquire, organize, and analyze large volumes of structured and un-structured data. Additionally a new versions of the Oracle Big Data Connectors and Oracle NoSQL Database were released. Why is this important to retailers?  As the infographic below conveys, mobile and social have added even more data to the already huge collections of POS transactions and e-commerce weblogs.  Retailers know that mining that data will help them make better decisions that lead to increased sales, better customer service, and ultimately a successful retail business. Monetate

    Read the article

  • How to efficiently map tokens to code in a script interpreter?

    - by lithander
    I'm writing an interpreter for a simple scripting language where each line is a complete, executable command. (Like the instructions in assembler) When parsing a line I have to map the requested command to actual code. My current solution looks like this: std::string op, param1, param2; //parse line, identify op, param1, param2 ... //call command specific code if(op == "MOV") ExecuteMov(AsNumber(param1)); else if(op == "ROT") ExecuteRot(AsNumber(param1)); else if(op == "SZE") ExecuteSze(AsNumber(param1)); else if(op == "POS") ExecutePos((AsNumber(param1), AsNumber(param2)); else if(op == "DIR") ExecuteDir((AsNumber(param1), AsNumber(param2)); else if(op == "SET") ExecuteSet(param1, AsNumber(param2)); else if(op == "EVL") ... The more commands are supported the more string comparisions I'll have to do to identify and call the associated method. Can you point me to a more efficient implementation in the described scenario?

    Read the article

  • Wall avoidance steering

    - by Vodemki
    I making a small steering simulator using the reynolds boid algorythm. Now I want to add a wall avoidance feature. My walls are in 3D and defined using two points like that: ---------. P2 | | P1 .--------- My agents have a velocity, a position, etc... Could you tell me how to make avoidance with my agents ? Vector2D ReynoldsSteeringModel::repulsionFromWalls() { Vector2D force; vector<Wall *> wallsList = walls(); Point2D pos = self()->position(); Vector2D velocity = self()->velocity(); for (unsigned i=0; i<wallsList.size(); i++) { //TODO } return force; } Then I use all the forces returned by my boid functions and I apply it to my agent. I just need to know how to do that with my walls ? Thanks for your help.

    Read the article

  • S&OP best practices that can help your organization be more responsive and effective

    - by user717691
    If you want to increase revenue by quickly responding to market changes or want to ensure that your operating plans drive towards corporate financial goals, you need real-time sales and operations planning.Watch the replay of our recent Webcast to hear Christopher Neff from NCR Corporation discuss how NCR Corporation is leveraging Oracle's Real-Time Sales and Operations Planning solutions. Learn best practices that can help your organization be more responsive and effective. Discover how Oracle's comprehensive suite of best-in-class capabilities can: Synchronize plans and actions across the extended enterprise Maximize profits with the ability to sense, influence, and fulfill demand with industry leading demand management and real-time sales & operations Drive tactical decisions into operational planning and execution, while monitoring performance Profitably balance supply, demand, and budgets Move planning processes from periodic and reactive to real-time, iterative and proactive Register now for the on demand Webcast! http://www.oracle.com/webapps/dialogue/ns/dlgwelcome.jsp?p_ext=Y&p_dlg_id=8664804&src=6811174&Act=99NCR Corporation is a leader in Self Service Solution such as POS Solutions, Payment and Imaging Systems.

    Read the article

  • How can I build this payment receipt/booking application?

    - by Festus
    I'm planning to build a payment receipt/booking application for a media company with several branches in different locations. The application should be able to move data across the network/internet to a central database where the administrator/accountant in a different location will be able to see the result of the entire job for the day from each branch. Application will run on windows environment. Will be able to send result of the booking to a Point Of Sales printer for print output. Now, I'm confused about choosing the right programming language to accomplish this task. I'm between beginner/intermediate level in PHP, I know HTML/CSS and JavaScript. I have tried to do this in PHP but, I'm face with several challenges and I fear for the POS part since PHP application run on the web browser. I don't know if python will be best suited for this and how long will it take someone with my experience level to pick up python. Any suggestion will be highly appreciated.

    Read the article

  • Moving two objects proportionally

    - by SSL
    I'm trying to move two objects away from each other at a proportional distance, but on different scales. I'm not quite sure how to do this. Object A can go from position 0.1 to 1. Object B has no limits. If object B is decreasing, then Object A should be decreasing at rate R. Likewise, if Object B is increasing, then Object A increases at rate R. How can I tie these two Object positions together so that in an update loop, they automatically update their positions? I tried using: ObjA.Pos += 0.001f * ObjB.VelocityY; //0.001f is the rate This works but there's an error each time it runs. ObjA starts off at its max position 1 but then the next time it will stop at 0.97, 0.94, 0.91 etc.. This is due to the 0.001f rate I put in. Is there a way to control the rate, yet not end up with the rounding error?

    Read the article

  • Jqzoom not working on safari

    - by Vladimir gatev
    Hello I am using jqzoom and it is working fine on all browser except safari there is an error "TypeError: Result of expression 'smallimagedata.pos' [undefined] is not an object." Please if somebody can help the page is http://www.legzskin.com/products.php?product=CHARMED when u mouseover the 3 images it should appear zoom window over the flash on the left

    Read the article

  • AutoIt scripts runs without error but I can't see archive?

    - by Scott
    #include <File.au3> #include <Zip.au3> ; bad file extensions Local $extData="ade|adp|app|asa|ashx|asp|bas|bat|cdx|cer|chm|class|cmd|com|cpl|crt|csh|der|exe|fxp|gadget|hlp|hta|htr|htw|ida|idc|idq|ins|isp|its|jse|ksh|lnk|mad|maf|mag|mam|maq|mar|mas|mat|mau|mav|maw|mda|mdb|mde|mdt|mdw|mdz|msc|msh|msh1|msh1xml|msh2|msh2xml|mshxml|msi|msp|mst|ops|pcd|pif|prf|prg|printer|pst|reg|rem|scf|scr|sct|shb|shs|shtm|shtml|soap|stm|url|vb|vbe|vbs|ws|wsc|wsf|wsh" Local $extensions = StringSplit($extData, "|") ; What is the root directory? $rootDirectory = InputBox("Root Directory", "Please enter the root directory...") archiveDir($rootDirectory) Func archiveDir($dir) $goDirs = True $goFiles = True ; Get all the files under the current dir $allOfDir = _FileListToArray($dir) Local $countDirs = 0 Local $countFiles = 0 $imax = UBound($allOfDir) For $i = 0 to $imax - 1 If StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]),"D") Then $countDirs = $countDirs + 1 ElseIf StringInStr(($allOfDir[$i]),".") Then $countFiles = $countFiles + 1 EndIf Next MsgBox(0, "Value of $countDirs in " & $dir, $countDirs) MsgBox(0, "Value of $countFiles in " & $dir, $countFiles) If ($countDirs > 0) Then Local $allDirs[$countDirs] $goDirs = True Else $goDirs = False EndIf If ($countFiles > 0) Then Local $allFiles[$countFiles] $goFiles = True Else $goFiles = False EndIf $dirCount = 0 $fileCount = 0 For $i = 0 to $imax - 1 If (StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]),"D")) And ($goDirs == True) Then $allDirs[$dirCount] = $allOfDir[$i] $dirCount = $dirCount + 1 ElseIf (StringInStr(($allOfDir[$i]),".")) And ($goFiles == True) Then $allFiles[$fileCount] = $allOfDir[$i] $fileCount = $fileCount + 1 EndIf Next ; Zip them if need be in current spot using 'ext_zip.zip' as file name, loop through each file ext. If ($goFiles == True) Then $emax = UBound($extensions) $fmax = UBound($allFiles) For $e = 0 to $emax - 1 For $f = 0 to $fmax - 1 $currentExt = getExt($allFiles[$f]) If ($currentExt == $extensions[$e]) Then $zip = _Zip_Create($dir & "\" & $currentExt & "_zip.zip") _Zip_AddFile($zip, $allFiles[$f]) EndIf Next Next EndIf ; Get all dirs under current DirCopy ; For each dir, recursive call from step 2 If ($goDirs == True) Then $dmax = UBound($allDirs) $rootDirectory = $rootDirectory & "\" For $d = 0 to $dmax - 1 archiveDir($rootDirectory & $allDirs[$d]) Next EndIf EndFunc Func getExt($filename) $pos = StringInStr($filename, ".") $retval = StringTrimLeft($filename, $pos + 1) Return $retval EndFunc This should output the .zip archives in the directories it finds the files that it needs to zip but it doesn't. Is there something I have to do after I create and add files to the archive within the code to put this created archive in the directory?

    Read the article

  • AutoIt scripts runs without error but I can't see archive? - UPDATE

    - by Scott
    #include <File.au3> #include <Zip.au3> #include <Array.au3> ; bad file extensions Local $extData="ade|adp|app|asa|ashx|asp|bas|bat|cdx|cer|chm|class|cmd|com|cpl|crt|csh|der|exe|fxp|gadget|hlp|hta|htr|htw|ida|idc|idq|ins|isp|its|jse|ksh|lnk|mad|maf|mag|mam|maq|mar|mas|mat|mau|mav|maw|mda|mdb|mde|mdt|mdw|mdz|msc|msh|msh1|msh1xml|msh2|msh2xml|mshxml|msi|msp|mst|ops|pcd|pif|prf|prg|printer|pst|reg|rem|scf|scr|sct|shb|shs|shtm|shtml|soap|stm|url|vb|vbe|vbs|ws|wsc|wsf|wsh" Local $extensions = StringSplit($extData, "|") ; What is the root directory? $rootDirectory = InputBox("Root Directory", "Please enter the root directory...") archiveDir($rootDirectory) Func archiveDir($dir) $goDirs = True $goFiles = True ; Get all the files under the current dir $allOfDir = _FileListToArray($dir) $tmax = UBound($allOfDir) For $t = 0 to $tmax - 1 Next Local $countDirs = 0 Local $countFiles = 0 $imax = UBound($allOfDir) For $i = 0 to $imax - 1 If StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]),"D") Then $countDirs = $countDirs + 1 ElseIf StringInStr(($allOfDir[$i]),".") Then $countFiles = $countFiles + 1 EndIf Next If ($countDirs > 0) Then Local $allDirs[$countDirs] $goDirs = True Else $goDirs = False EndIf If ($countFiles > 0) Then Local $allFiles[$countFiles] $goFiles = True Else $goFiles = False EndIf $dirCount = 0 $fileCount = 0 For $i = 0 to $imax - 1 If (StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]),"D")) And ($goDirs == True) Then $allDirs[$dirCount] = $allOfDir[$i] $dirCount = $dirCount + 1 ElseIf (StringInStr(($allOfDir[$i]),".")) And ($goFiles == True) Then $allFiles[$fileCount] = $allOfDir[$i] $fileCount = $fileCount + 1 EndIf Next ; Zip them if need be in current spot using 'ext_zip.zip' as file name, loop through each file ext. If ($goFiles == True) Then $fmax = UBound($allFiles) For $f = 0 to $fmax - 1 $currentExt = getExt($allFiles[$f]) $position = _ArraySearch($extensions, $currentExt) If @error Then MsgBox(0, "Not Found", "Not Found") Else $zip = _Zip_Create($dir & "\" & $currentExt & "_zip.zip") _Zip_AddFile($zip, $dir & "\" & $allFiles[$f]) EndIf Next EndIf ; Get all dirs under current DirCopy ; For each dir, recursive call from step 2 If ($goDirs == True) Then $dmax = UBound($allDirs) $rootDirectory = $rootDirectory & "\" For $d = 0 to $dmax - 1 archiveDir($rootDirectory & $allDirs[$d]) Next EndIf EndFunc Func getExt($filename) $pos = StringInStr($filename, ".") $retval = StringTrimLeft($filename, $pos - 1) Return $retval EndFunc Updated, fixed a lot of bugs. Still not working. Like I said I have a list of 'bad' file extensions, this script should go through a directory of files (and subdirectories), and zip up (in separate zip files for each bad extension), all files WITH those bad extensions in the directories it finds them. What is wrong???

    Read the article

  • How to get selected item of a singlechoice Alert Dialog?

    - by Pentium10
    I have this code to show a dialog with singlechoice(radio) options. AlertDialog ad = new AlertDialog.Builder(this) .setCancelable(false) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.choose_one) .setSingleChoiceItems(seq, pos,null) .setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton) { // dialog dismissed } }).create(); How do I get the choice that has been selected?

    Read the article

  • Move to next item or position in List view on button click

    - by praveenb
    Hi, im new to Android programing I build a listview showing station names, that grabs its data from a URL. I used ArrayAdapter to accomplish listview with data. I need to navigate through station names in listview, using previous, next buttons click. I google for this task and tried in different ways to workout bt im not able to solve. shall any one pls help me out for this issue. Thanks in advance...... I tried like this ` private ListView stationList; . . public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.playscreen); // move up event handler preButton= (ImageButton) findViewById(R.id.prevButton); preButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { movePre(); } }); // move down event handler nxtButton= (ImageButton) findViewById(R.id.nextButton); nxtButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { moveNxt(); } }); stationList.setAdapter(new StationAdapter(this, android.R.layout.simple_list_item_1, _stationList)); } else { Log.d(TAG, "No Stations"); } } private void movePre(){ stationList.setSelection(stationList.getSelectedItemPosition() + 1); } // Move selected item "down" in the ViewList. private void moveNxt(){ stationList.setSelection(stationList.getSelectedItemPosition() + 1); } private class StationAdapter extends ArrayAdapter { private Vector<Station> items; public StationAdapter(Context context, int textViewResourceId, Vector<Station> items) { super(context, textViewResourceId, items); this.items = items; } public void setSelectedPosition(int pos){ selectedPos = pos; // inform the view of this change notifyDataSetChanged(); } public int getSelectedPosition(){ return selectedPos; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.row, null); } Station st = items.get(position); if (st != null) { TextView tt = (TextView) v.findViewById(R.id.toptext); TextView bt = (TextView) v.findViewById(R.id.bottomtext); if (tt != null) { tt.setText(st.getStationName()); } if (bt != null) { bt.setText(st.getCT()); } } return v; } } `

    Read the article

  • velocity vector

    - by wanderer
    Hi, I am trying to simulate a collision. The collision is shown here http://www.freeimagehosting.net/image.php?c5ae01b476.jpg A particle falls down on a sphere and a collision between sphere and particle takes place. The sphere always remain stationary and the collision itself is not elastic. So if the particle falls directly n top of sphere, the velocity of particle will become zero. I was trying to set the velocity of particle to be zero after the collision. But that does not give good simulation when the collision does not occur on top of sphere but along the side of sphere. So now after the collision i need to make sure that the particle has a velocity which is orthogonal to the vector of the point of collision from the center of sphere. The velocity along the vector from center of sphere to point of collision should become zero. How do i do that? I am a bit mathematically challenged but i think it has something to do with dot product of vectors. Or maybe i am wrong :) I have the initial velocity vector and 'radiusvector' say :- 1)velocity <-1.03054, -1.56563, 1.33341e-016 2) radius vector <2.04406, 2.19587, 1.0514 Pseudo code for the problem is: foreach( particle particle in particlesCollections) { //sphere.x, sphere.y sphere.z give the center of the sphere dist = particle.pos-vector(sphere.x,sphere.y,sphere.z); //detect if a collision has taken place. if (dist.mag < sphere.radius) { rVector=dist/dist.mag*sphere.radius; particle.pos=vector(sphere.x,sphere.y,sphere.z) + rVector; //particle.Velocity gives the velocity vector of the particle at the time of collision //i need to modify particle.Velocity so that the component of velocity that runs along // with the rvector becomes zero as i have a non elsatic collision. The remaining //velocity that the particle will have is the one which runs along with tangent to the //rVector. The sphere remains stationary. //example values: particle.Velocity == <-1.03054, -1.56563, .006> //and rVector = <2.04406, 2.19587, 1.0514> } } Thanks

    Read the article

  • Passing XML markers to Google Map

    - by djmadscribbler
    I've been creating a V3 Google map based on this example from Mike Williams http://www.geocodezip.com/v3_MW_example_map3.html I've run into a bit of a problem though. If I have no parameters in my URL then I get the error "id is undefined idmarkers [id.toLowerCase()] = marker;" in Firebug and only one marker will show up. If I have a parameter (?id=105 for example) then all the sidebar links say 105 (or whatever the parameter in the URL was) instead of their respective label as listed in the XML file and a random infowindow will be opened instead of the window for the id in the URL. Here is my javascript: var map = null; var lastmarker = null; // ========== Read paramaters that have been passed in ========== // Before we go looking for the passed parameters, set some defaults // in case there are no parameters var id; var index = -1; // these set the initial center, zoom and maptype for the map // if it is not specified in the query string var lat = 42.194741; var lng = -121.700301; var zoom = 18; var maptype = google.maps.MapTypeId.HYBRID; function MapTypeId2UrlValue(maptype) { var urlValue = 'm'; switch (maptype) { case google.maps.MapTypeId.HYBRID: urlValue = 'h'; break; case google.maps.MapTypeId.SATELLITE: urlValue = 'k'; break; case google.maps.MapTypeId.TERRAIN: urlValue = 't'; break; default: case google.maps.MapTypeId.ROADMAP: urlValue = 'm'; break; } return urlValue; } // If there are any parameters at eh end of the URL, they will be in location.search // looking something like "?marker=3" // skip the first character, we are not interested in the "?" var query = location.search.substring(1); // split the rest at each "&" character to give a list of "argname=value" pairs var pairs = query.split("&"); for (var i = 0; i < pairs.length; i++) { // break each pair at the first "=" to obtain the argname and value var pos = pairs[i].indexOf("="); var argname = pairs[i].substring(0, pos).toLowerCase(); var value = pairs[i].substring(pos + 1).toLowerCase(); // process each possible argname - use unescape() if theres any chance of spaces if (argname == "id") { id = unescape(value); } if (argname == "marker") { index = parseFloat(value); } if (argname == "lat") { lat = parseFloat(value); } if (argname == "lng") { lng = parseFloat(value); } if (argname == "zoom") { zoom = parseInt(value); } if (argname == "type") { // from the v3 documentation 8/24/2010 // HYBRID This map type displays a transparent layer of major streets on satellite images. // ROADMAP This map type displays a normal street map. // SATELLITE This map type displays satellite images. // TERRAIN This map type displays maps with physical features such as terrain and vegetation. if (value == "m") { maptype = google.maps.MapTypeId.ROADMAP; } if (value == "k") { maptype = google.maps.MapTypeId.SATELLITE; } if (value == "h") { maptype = google.maps.MapTypeId.HYBRID; } if (value == "t") { maptype = google.maps.MapTypeId.TERRAIN; } } } // this variable will collect the html which will eventually be placed in the side_bar var side_bar_html = ""; // arrays to hold copies of the markers and html used by the side_bar // because the function closure trick doesnt work there var gmarkers = []; var idmarkers = []; // global "map" variable var map = null; // A function to create the marker and set up the event window function function createMarker(point, icon, label, html) { var contentString = html; var marker = new google.maps.Marker({ position: point, map: map, title: label, icon: icon, zIndex: Math.round(point.lat() * -100000) << 5 }); marker.id = id; marker.index = gmarkers.length; google.maps.event.addListener(marker, 'click', function () { lastmarker = new Object; lastmarker.id = marker.id; lastmarker.index = marker.index; infowindow.setContent(contentString); infowindow.open(map, marker); }); // save the info we need to use later for the side_bar gmarkers.push(marker); idmarkers[id.toLowerCase()] = marker; // add a line to the side_bar html side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + id + '<\/a><br>'; } // This function picks up the click and opens the corresponding info window function myclick(i) { google.maps.event.trigger(gmarkers[i], "click"); } function makeLink() { var mapinfo = "lat=" + map.getCenter().lat().toFixed(6) + "&lng=" + map.getCenter().lng().toFixed(6) + "&zoom=" + map.getZoom() + "&type=" + MapTypeId2UrlValue(map.getMapTypeId()); if (lastmarker) { var a = "/about/map/default.aspx?id=" + lastmarker.id + "&" + mapinfo; var b = "/about/map/default.aspx?marker=" + lastmarker.index + "&" + mapinfo; } else { var a = "/about/map/default.aspx?" + mapinfo; var b = a; } document.getElementById("idlink").innerHTML = '<a href="' + a + '" id=url target=_new>- Link directly to this page by id</a> (id in xml file also entry &quot;name&quot; in sidebar menu)'; document.getElementById("indexlink").innerHTML = '<a href="' + b + '" id=url target=_new>- Link directly to this page by index</a> (position in gmarkers array)'; } function initialize() { // create the map var myOptions = { zoom: zoom, center: new google.maps.LatLng(lat, lng), mapTypeId: maptype, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, navigationControl: true, mapTypeId: google.maps.MapTypeId.HYBRID }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var stylesarray = [ { featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] }, { featureType: "landscape.man_made", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; var options = map.setOptions({ styles: stylesarray }); // Make the link the first time when the page opens makeLink(); // Make the link again whenever the map changes google.maps.event.addListener(map, 'maptypeid_changed', makeLink); google.maps.event.addListener(map, 'center_changed', makeLink); google.maps.event.addListener(map, 'bounds_changed', makeLink); google.maps.event.addListener(map, 'zoom_changed', makeLink); google.maps.event.addListener(map, 'click', function () { lastmarker = null; makeLink(); infowindow.close(); }); // Read the data from example.xml downloadUrl("example.xml", function (doc) { var xmlDoc = xmlParse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("lat")); var lng = parseFloat(markers[i].getAttribute("lng")); var point = new google.maps.LatLng(lat, lng); var html = markers[i].getAttribute("html"); var label = markers[i].getAttribute("label"); var icon = markers[i].getAttribute("icon"); // create the marker var marker = createMarker(point, icon, label, html); } // put the assembled side_bar_html contents into the side_bar div document.getElementById("side_bar").innerHTML = side_bar_html; // ========= If a parameter was passed, open the info window ========== if (id) { if (idmarkers[id]) { google.maps.event.trigger(idmarkers[id], "click"); } else { alert("id " + id + " does not match any marker"); } } if (index > -1) { if (index < gmarkers.length) { google.maps.event.trigger(gmarkers[index], "click"); } else { alert("marker " + index + " does not exist"); } } }); } var infowindow = new google.maps.InfoWindow( { size: new google.maps.Size(150, 50) }); google.maps.event.addDomListener(window, "load", initialize); And here is an example of my XML formatting <marker lat="42.196175" lng="-121.699224" html="This is the information about 104" iconimage="/about/map/images/104.png" label="104" />

    Read the article

  • Turtle Graphics as a Haskell Monad

    - by iliis
    I'm trying to implement turtle graphis in Haskell. The goal is to be able to write a function like this: draw_something = do fordward 100 right 90 forward 100 ... and then have it produce a list of points (maybe with additional properties): > draw_something (0,0) 0 -- start at (0,0) facing east (0 degrees) [(0,0), (0,100), (-100,100), ...] I have all this working in a 'normal' way, but I fail to implement it as a Haskell Monad and use the do-notation. The basic code: data State a = State (a, a) a -- (x,y), angle deriving (Show, Eq) initstate :: State Float initstate = State (0.0,0.0) 0.0 -- constrain angles to 0 to 2*pi fmod :: Float -> Float fmod a | a >= 2*pi = fmod (a-2*pi) | a < 0 = fmod (a+2*pi) | otherwise = a forward :: Float -> State Float -> [State Float] forward d (State (x,y) angle) = [State (x + d * (sin angle), y + d * (cos angle)) angle] right :: Float -> State Float -> [State Float] right d (State pos angle) = [State pos (fmod (angle+d))] bind :: [State a] -> (State a -> [State a]) -> [State a] bind xs f = xs ++ (f (head $ reverse xs)) ret :: State a -> [State a] ret x = [x] With this I can now write > [initstate] `bind` (forward 100) `bind` (right (pi/2)) `bind` (forward 100) [State (0.0,0.0) 0.0,State (0.0,100.0) 0.0,State (0.0,100.0) 1.5707964,State (100.0,99.99999) 1.5707964] And get the expected result. However I fail to implement this as an instance of Monad. instance Monad [State] where ... results in `State' is not applied to enough type arguments Expected kind `*', but `State' has kind `* -> *' In the instance declaration for `Monad [State]' And if I wrap the list in a new object data StateList a = StateList [State a] instance Monad StateList where return x = StateList [x] I get Couldn't match type `a' with `State a' `a' is a rigid type variable bound by the type signature for return :: a -> StateList a at logo.hs:38:9 In the expression: x In the first argument of `StateList', namely `[x]' In the expression: StateList [x] I tried various other versions but I never got it to run as I'd like to. What am I doing wrong? What do I understand incorrectly?

    Read the article

  • Downloading all ctrl alt del webcomics using terminal.

    - by Conner
    I've tried using the following commands to download the ctrl alt del comics. $ for filename in $(seq 20021023 20100503); do wget http://www.ctrlaltdel-online.com/comics/"$filename".jpg; done I get the following error code, "bash: syntax error near unexpected token 'do'" I've also tried using cURL, using this command, curl http://ctrlaltdel-online.com/comics[20021023..20100503].jpg I get the following error code, "curl: (3) [globbing] error: bad range specification after pos 37" Any help would be great.

    Read the article

  • Python - wxPython What's wrong?

    - by Wallter
    I am trying to write a simple custom button in wx.Python. My code is as follows,(As a side note: I am relatively new to python having come from C++ and C# any help on syntax and function of the code would be great! - knowing that, it could be a simple error. thanks!) Error Traceback (most recent call last): File "D:\Documents\Python2\Button\src\Custom_Button.py", line 10, in <module> class Custom_Button(wx.PyControl): File "D:\Documents\Python2\Button\src\Custom_Button.py", line 13, in Custom_Button Mouse_over_bmp = wx.Bitmap(0) # When the mouse is over File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 561, in __init__ _gdi_.Bitmap_swiginit(self,_gdi_.new_Bitmap(*args, **kwargs)) TypeError: String or Unicode type required Main.py 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) self.Button1 = Custom_Button(self, parent, -1, "D:/Documents/Python/Normal.bmp", "D:/Documents/Python/Clicked.bmp", "D:/Documents/Python/Over.bmp", "None", wx.Point(200,200), wx.Size(300,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() Custom Button import wx from wxPython.wx import * class Custom_Button(wx.PyControl): ############################################ ##THE ERROR IS BEING THROWN SOME WHERE IN HERE ## ############################################ # The BMP's Mouse_over_bmp = wx.Bitmap(0) # When the mouse is over Norm_bmp = wx.Bitmap(0) # The normal BMP Push_bmp = wx.Bitmap(0) # The down BMP Pos_bmp = wx.Point(0,0) # The posisition of the button def __init__(self, parent, NORM_BMP, PUSH_BMP, MOUSE_OVER_BMP, pos, size, text="", id=-1, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # Set the BMP's to the ones given in the constructor self.Mouse_over_bmp = wx.Bitmap(MOUSE_OVER_BMP) self.Norm_bmp = wx.Bitmap(NORM_BMP) self.Push_bmp = wx.Bitmap(PUSH_BMP) self.Pos_bmp = pos ############################################ ##THE ERROR IS BEING THROWN SOME WHERE IN HERE ## ############################################ 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._mouseIn = 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 _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # 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, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False)

    Read the article

  • Need Help Customizing a Grammar Checking Replace Rule in Java

    - by user567785
    Hello, I am currently adding the Khmer (Cambodian) language to LanguageTool, an opensource grammar checker for OpenOffice (http://www.languagetool.org). I don't know enough Java to customize one of the scripts and wanted to make a request here asking if anyone would be willing to customize it for me (I can put link to your website at http://www.sbbic.org/lang/en-us/volunteer/ if you help). Here is the script that needs customization KhmerWordCoherencyRule.java: /* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.danielnaber.languagetool.rules.km; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import de.danielnaber.languagetool.AnalyzedSentence; import de.danielnaber.languagetool.AnalyzedToken; import de.danielnaber.languagetool.AnalyzedTokenReadings; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.tools.StringTools; import de.danielnaber.languagetool.rules.Category; import de.danielnaber.languagetool.rules.RuleMatch; /** * A Khmer rule that matches words or phrases which should not be used and suggests * correct ones instead. Loads the relevant words from * <code>rules/km/coherency.txt</code>, where km is a code of the language. * * @author Andriy Rysin */ public abstract class KhmerWordCoherencyRule extends KhmerRule { private static final String FILE_ENCODING = "utf-8"; private Map<String, String> wrongWords; // e.g. "????? -> "?????" private static final String FILE_NAME = "/km/coherency.txt"; public abstract String getFileName(); public String getEncoding() { return FILE_ENCODING; } /** * Indicates if the rule is case-sensitive. Default value is <code>true</code>. * @return true if the rule is case-sensitive, false otherwise. */ //in Khmer there is no case public boolean isCaseSensitive() { return false; } /** * @return the locale used for case conversion when {@link #isCaseSensitive()} is set to <code>false</code>. */ public Locale getLocale() { return Locale.getDefault(); } public KhmerWordCoherencyRule(final ResourceBundle messages) throws IOException { if (messages != null) { super.setCategory(new Category(messages.getString("category_misc"))); } wrongWords = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream(getFileName())); } public String getId() { return "KM_WORD_COHERENCY"; } public String getDescription() { return "Checks for wrong words/phrases"; } public String getSuggestion() { return " does not match your previous spelling of the word, use "; } public String getShort() { return "Use a consistant spelling throughout"; } public final RuleMatch[] match(final AnalyzedSentence text) { final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>(); final AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace(); for (int i = 1; i < tokens.length; i++) { final String token = tokens[i].getToken(); final String origToken = token; final String replacement = isCaseSensitive()?wrongWords.get(token):wrongWords.get(token.toLowerCase(getLocale())); if (replacement != null) { final String msg = token + getSuggestion() + replacement; final int pos = tokens[i].getStartPos(); final RuleMatch potentialRuleMatch = new RuleMatch(this, pos, pos + origToken.length(), msg, getShort()); if (!isCaseSensitive() && StringTools.startsWithUppercase(token)) { potentialRuleMatch.setSuggestedReplacement(StringTools.uppercaseFirstChar(replacement)); } else { potentialRuleMatch.setSuggestedReplacement(replacement); } ruleMatches.add(potentialRuleMatch); } } return toRuleMatchArray(ruleMatches); } private Map<String, String> loadWords(final InputStream file) throws IOException { final Map<String, String> map = new HashMap<String, String>(); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(file, getEncoding()); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() < 1) { continue; } if (line.charAt(0) == '#') { // ignore comments continue; } final String[] parts = line.split(";"); if (parts.length != 2) { throw new IOException("Format error in file " + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(getFileName()) + ", line: " + line); } map.put(parts[0], parts[1]); } } finally { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } return map; } public void reset() { } } Here is what I need the SimpleReplaceRule.java to do: 1 - Be able to have more than two spelling variations in the coherency.txt file (right now it can only be Word1;Word2). 2 - Find the first use of ANY of the spelling variations in a document that are found in coherency.txt and then make sure only that spelling is used throughout the document (ex. in the coherency.txt I have Word1;Word2;Word3 then in my document on the first line I write Word2. then on next line I write Word1 and Word 3 - then the grammar checker will flag Word1 and Word3 saying that I should use the spelling "Word2" instead...etc.). If anyone can help I would be grateful! Thanks for your time, Nathan

    Read the article

  • HowTo stick QDialog to Screen Borders like Skype do?

    - by mosg
    Hello. A long time ago I tried to find method how to stick QDialog window to screen borders for my small projects like Skype windows do it, but I failed. May be I was looking this code not in the right place, so now I'm looking the solution here, on stack! :) So, does any one have a deal with some kind of such code, links, samples? In my opinion, we have to reimplement QDialog moveEvent function, like below, but that code does not working: void CDialog::moveEvent(QMoveEvent * event) { QRect wndRect; int leftTaskbar = 0, rightTaskbar = 0, topTaskbar = 0, bottomTaskbar = 0; // int top = 0, left = 0, right = 0, bottom = 0; wndRect = this->frameGeometry(); // Screen resolution int screenWidth = QApplication::desktop()->width(); int screenHeight = QApplication::desktop()->height(); int wndWidth = wndRect.right() - wndRect.left(); int wndHeight = wndRect.bottom() - wndRect.top(); int posX = event->pos().x(); int posY = event->pos().y(); // Snap to screen border // Left border if (posX >= -m_nXOffset + leftTaskbar && posX <= leftTaskbar + m_nXOffset) { //left = leftTaskbar; this->move(leftTaskbar, posY); return; } // Top border if (posY >= -m_nYOffset && posY <= topTaskbar + m_nYOffset) { //top = topTaskbar; this->move(posX, topTaskbar); return; } // Right border if (posX + wndWidth <= screenWidth - rightTaskbar + m_nXOffset && posX + wndWidth >= screenWidth - rightTaskbar - m_nXOffset) { //right = screenWidth - rightTaskbar - wndWidth; this->move(screenWidth - rightTaskbar - wndWidth, posY); return; } // Bottom border if (posY + wndHeight <= screenHeight - bottomTaskbar + m_nYOffset && posY + wndHeight >= screenHeight - bottomTaskbar - m_nYOffset) { //bottom = screenHeight - bottomTaskbar - wndHeight; this->move(posX, screenHeight - bottomTaskbar - wndHeight); return; } QDialog::moveEvent(event); } Thanks.

    Read the article

  • Python - Polymorphism in wxPython, What's wrong?

    - by Wallter
    I am trying to wright a simple custom button in wx.Python. My code is as follows, an error is thrown on line 19 of my "Custom_Button.py" - What is going on? I can find no help online for this error and have a suspicion that it has to do with the Polymorphism. (As a side note: I am relatively new to python having come from C++ and C# any help on syntax and function of the code would be great! - knowing that, it could be a simple error. thanks!) Error def __init__(self, parent, id=-1, NORM_BMP, PUSH_BMP, MOUSE_OVER_BMP, **kwargs): SyntaxError: non-default argument follows default argument Main.py 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) self.Button1 = Custom_Button(self, parent, -1, "D:/Documents/Python/Normal.bmp", "D:/Documents/Python/Clicked.bmp", "D:/Documents/Python/Over.bmp", "None", wx.Point(200,200), wx.Size(300,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() Custom Button import wx from wxPython.wx import * class Custom_Button(wx.PyControl): ############################################ ##THE ERROR IS BEING THROWN SOME WHERE IN HERE ## ############################################ # The BMP's Mouse_over_bmp = wx.Bitmap(0) # When the mouse is over Norm_bmp = wx.Bitmap(0) # The normal BMP Push_bmp = wx.Bitmap(0) # The down BMP Pos_bmp = wx.Point(0,0) # The posisition of the button def __init__(self, parent, id=-1, NORM_BMP, PUSH_BMP, MOUSE_OVER_BMP, text="", pos, size, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) # Set the BMP's to the ones given in the constructor self.Mouse_over_bmp = wx.Bitmap(MOUSE_OVER_BMP) self.Norm_bmp = wx.Bitmap(NORM_BMP) self.Push_bmp = wx.Bitmap(PUSH_BMP) self.Pos_bmp = pos ############################################ ##THE ERROR IS BEING THROWN SOME WHERE IN HERE ## ############################################ 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._mouseIn = 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 _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() dc.DrawBitmap(self.Norm_bmp) # 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, self.Mouse_over_bmp, self.Pos_bmp, useMask=False) if self._mouseDown: # If the Mouse clicks the button dc.DrawBitmap(self, self.Push_bmp, self.Pos_bmp, useMask=False)

    Read the article

  • SQL Server query replace for MySQL Instruction

    - by pojomx
    Hi, I'm new to SQL Server, and used mysql for a while now... SELECT A.acol, IF(A.acol<0,"Neg","Pos") as Column2 From Table I want to do something like that on SQL Server, but there doesn't exist the IF instruction. How do I replace that if, in a SQL Server 2008 Query?

    Read the article

  • ggplot2 pdf import in Adobe Illustrator missing font AdobePiStd

    - by Sander
    I created several simple ggplot2 plots and saved them to PDF files using the following commands: p <- ggplot(plotobject, aes(x=Pos, y=Pval),res=300) ggsave(plot=p,height=6,width=6,dpi=200, filename="~/example.pdf") If I now open this example.pdf in Adobe Illustrator I get the following error: The font AdobePiStd is missing. Affected text will be displayed using a substitute font. Is there a way in ggplot2 to specify a font (I presume this is for the dots/points) that Adobe will understand or otherwise is there a way to get this font working in Adobe?

    Read the article

  • Determining credit/debit card type

    - by ct2k7
    Hi, I'm writing a POS application for the iPhone/iPod combination, using the same exact hardware used in Apple Stores:: EasyPay. Ok, my hurdle is this: how do I identify which credit card type is being used as text is entered in the uitextfield? I assume I've to use textField:shouldChangeCharactersInRange:replacementString:? However, I've got ideas floating around, but I simple cannot put them together to form code :/ Any help is appreciated! Thanks in advanced :D

    Read the article

  • JPA 2.0 @OrderColumn annotation in Hibernate 3.5

    - by peperg
    I'm trynig to use @OrderColumn annotation with Hibernate 3.5 @OneToMany(mappedBy = "parent",fetch=FetchType.EAGER, cascade=CascadeType.ALL) @OrderColumn(name = "pos") private List<Children> childrenCollection; When retrieving data everyting works fine. But I can't make it to reorded elements in List and save new order to database.

    Read the article

  • How to move a kinect skeleton to another position

    - by Ewerton
    I am working on a extension method to move one skeleton to a desired position in the kinect field os view. My code receives a skeleton to be moved and the destiny position, i calculate the distance between the received skeleton hip center and the destiny position to find how much to move, then a iterate in the joint applying this factor. My code, actualy looks like this. public static Skeleton MoveTo(this Skeleton skToBeMoved, Vector4 destiny) { Joint newJoint = new Joint(); ///Based on the HipCenter (i dont know if it is reliable, seems it is.) float howMuchMoveToX = Math.Abs(skToBeMoved.Joints[JointType.HipCenter].Position.X - destiny.X); float howMuchMoveToY = Math.Abs(skToBeMoved.Joints[JointType.HipCenter].Position.Y - destiny.Y); float howMuchMoveToZ = Math.Abs(skToBeMoved.Joints[JointType.HipCenter].Position.Z - destiny.Z); float howMuchToMultiply = 1; // Iterate in the 20 Joints foreach (JointType item in Enum.GetValues(typeof(JointType))) { newJoint = skToBeMoved.Joints[item]; // This adjust, try to keeps the skToBeMoved in the desired position if (newJoint.Position.X < 0) howMuchToMultiply = 1; // if the point is in a negative position, carry it to a "more positive" position else howMuchToMultiply = -1; // if the point is in a positive position, carry it to a "more negative" position // applying the new values to the joint SkeletonPoint pos = new SkeletonPoint() { X = newJoint.Position.X + (howMuchMoveToX * howMuchToMultiply), Y = newJoint.Position.Y, // * (float)whatToMultiplyY, Z = newJoint.Position.Z, // * (float)whatToMultiplyZ }; newJoint.Position = pos; skToBeMoved.Joints[item] = newJoint; //if (skToBeMoved.Joints[JointType.HipCenter].Position.X < 0) //{ // if (item == JointType.HandLeft) // { // if (skToBeMoved.Joints[item].Position.X > 0) // { // } // } //} } return skToBeMoved; } Actualy, only X position is considered. Now, THE PROBLEM: If i stand in a negative position, and move my hand to a positive position, a have a strange behavior, look this image To reproduce this behaviour you could use this code using (SkeletonFrame frame = e.OpenSkeletonFrame()) { if (frame == null) return new Skeleton(); if (skeletons == null || skeletons.Length != frame.SkeletonArrayLength) { skeletons = new Skeleton[frame.SkeletonArrayLength]; } frame.CopySkeletonDataTo(skeletons); Skeleton skeletonToTest = skeletons.Where(s => s.TrackingState == SkeletonTrackingState.Tracked).FirstOrDefault(); Vector4 newPosition = new Vector4(); newPosition.X = -0.03412333f; newPosition.Y = 0.0407479f; newPosition.Z = 1.927342f; newPosition.W = 0; // ignored skeletonToTest.MoveTo(newPosition); } I know, this is simple math, but i cant figure it out why this is happen. Any help will be apreciated.

    Read the article

  • Azure Diagnostics wrt Custom Logs and honoring scheduledTransferPeriod

    - by kjsteuer
    I have implemented my own TraceListener similar to http://blogs.technet.com/b/meamcs/archive/2013/05/23/diagnostics-of-cloud-services-custom-trace-listener.aspx . One thing I noticed is that that logs show up immediately in My Azure Table Storage. I wonder if this is expected with Custom Trace Listeners or because I am in a development environment. My diagnosics.wadcfg <?xml version="1.0" encoding="utf-8"?> <DiagnosticMonitorConfiguration configurationChangePollInterval="PT1M""overallQuotaInMB="4096" xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration"> <DiagnosticInfrastructureLogs scheduledTransferLogLevelFilter="Information" /> <Directories scheduledTransferPeriod="PT1M"> <IISLogs container="wad-iis-logfiles" /> <CrashDumps container="wad-crash-dumps" /> </Directories> <Logs bufferQuotaInMB="0" scheduledTransferPeriod="PT30M" scheduledTransferLogLevelFilter="Information" /> </DiagnosticMonitorConfiguration> I have changed my approach a bit. Now I am defining in the web config of my webrole. I notice when I set autoflush to true in the webconfig, every thing works but scheduledTransferPeriod is not honored because the flush method pushes to the table storage. I would like to have scheduleTransferPeriod trigger the flush or trigger flush after a certain number of log entries like the buffer is full. Then I can also flush on server shutdown. Is there any method or event on the CustomTraceListener where I can listen to the scheduleTransferPeriod? <system.diagnostics> <!--http://msdn.microsoft.com/en-us/library/sk36c28t(v=vs.110).aspx By default autoflush is false. By default useGlobalLock is true. While we try to be threadsafe, we keep this default for now. Later if we would like to increase performance we can remove this. see http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.usegloballock(v=vs.110).aspx --> <trace> <listeners> <add name="TableTraceListener" type="Pos.Services.Implementation.TableTraceListener, Pos.Services.Implementation" /> <remove name="Default" /> </listeners> </trace> </system.diagnostics> I have modified the custom trace listener to the following: namespace Pos.Services.Implementation { class TableTraceListener : TraceListener { #region Fields //connection string for azure storage readonly string _connectionString; //Custom sql storage table for logs. //TODO put in config readonly string _diagnosticsTable; [ThreadStatic] static StringBuilder _messageBuffer; readonly object _initializationSection = new object(); bool _isInitialized; CloudTableClient _tableStorage; readonly object _traceLogAccess = new object(); readonly List<LogEntry> _traceLog = new List<LogEntry>(); #endregion #region Constructors public TableTraceListener() : base("TableTraceListener") { _connectionString = RoleEnvironment.GetConfigurationSettingValue("DiagConnection"); _diagnosticsTable = RoleEnvironment.GetConfigurationSettingValue("DiagTableName"); } #endregion #region Methods /// <summary> /// Flushes the entries to the storage table /// </summary> public override void Flush() { if (!_isInitialized) { lock (_initializationSection) { if (!_isInitialized) { Initialize(); } } } var context = _tableStorage.GetTableServiceContext(); context.MergeOption = MergeOption.AppendOnly; lock (_traceLogAccess) { _traceLog.ForEach(entry => context.AddObject(_diagnosticsTable, entry)); _traceLog.Clear(); } if (context.Entities.Count > 0) { context.BeginSaveChangesWithRetries(SaveChangesOptions.None, (ar) => context.EndSaveChangesWithRetries(ar), null); } } /// <summary> /// Creates the storage table object. This class does not need to be locked because the caller is locked. /// </summary> private void Initialize() { var account = CloudStorageAccount.Parse(_connectionString); _tableStorage = account.CreateCloudTableClient(); _tableStorage.GetTableReference(_diagnosticsTable).CreateIfNotExists(); _isInitialized = true; } public override bool IsThreadSafe { get { return true; } } #region Trace and Write Methods /// <summary> /// Writes the message to a string buffer /// </summary> /// <param name="message">the Message</param> public override void Write(string message) { if (_messageBuffer == null) _messageBuffer = new StringBuilder(); _messageBuffer.Append(message); } /// <summary> /// Writes the message with a line breaker to a string buffer /// </summary> /// <param name="message"></param> public override void WriteLine(string message) { if (_messageBuffer == null) _messageBuffer = new StringBuilder(); _messageBuffer.AppendLine(message); } /// <summary> /// Appends the trace information and message /// </summary> /// <param name="eventCache">the Event Cache</param> /// <param name="source">the Source</param> /// <param name="eventType">the Event Type</param> /// <param name="id">the Id</param> /// <param name="message">the Message</param> public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { base.TraceEvent(eventCache, source, eventType, id, message); AppendEntry(id, eventType, eventCache); } /// <summary> /// Adds the trace information to a collection of LogEntry objects /// </summary> /// <param name="id">the Id</param> /// <param name="eventType">the Event Type</param> /// <param name="eventCache">the EventCache</param> private void AppendEntry(int id, TraceEventType eventType, TraceEventCache eventCache) { if (_messageBuffer == null) _messageBuffer = new StringBuilder(); var message = _messageBuffer.ToString(); _messageBuffer.Length = 0; if (message.EndsWith(Environment.NewLine)) message = message.Substring(0, message.Length - Environment.NewLine.Length); if (message.Length == 0) return; var entry = new LogEntry() { PartitionKey = string.Format("{0:D10}", eventCache.Timestamp >> 30), RowKey = string.Format("{0:D19}", eventCache.Timestamp), EventTickCount = eventCache.Timestamp, Level = (int)eventType, EventId = id, Pid = eventCache.ProcessId, Tid = eventCache.ThreadId, Message = message }; lock (_traceLogAccess) _traceLog.Add(entry); } #endregion #endregion } }

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >