Search Results

Search found 10804 results on 433 pages for 'attribute keys'.

Page 89/433 | < Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >

  • DataAnnotation attributes buddy class strangeness - ASP.NET MVC

    - by JK
    Given this POCO class that was automatically generated by an EntityFramework T4 template (has not and can not be manually edited in any way): public partial class Customer { [Required] [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")] [DisplayName("Customer Number")] public virtual string CustomerNumber { get;set; } [Required] [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")] [DisplayName("ACNumber")] public virtual string ACNumber{ get;set; } } Note that "ACNumber" is a badly named database field, so the autogenerator is unable to generate the correct display name and error message which should be "Account Number". So we manually create this buddy class to add custom attributes that could not be automatically generated: [MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode] // This line does not work public virtual string CustomerNumber { get;set; } [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")] [DisplayName("Account Number")] public virtual string ACNumber { get;set; } } Where [NumberCode] is a simple regex based attribute that allows only digits and hyphens: [AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } } NOW, when I load the page, the DisplayName attribute works correctly - it shows the display name from the buddy class not the generated class. The StringLength attribute does not work correctly - it shows the error message from the generated class ("ACNumber" instead of "Account Number"). BUT the [NumberCode] attribute in the buddy class does not even get applied to the AccountNumber property: foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) { // This collection correctly contains all the [Required], [StringLength] attributes // BUT does not contain the [NumberCode] attribute ApplyValidation(generator, attrib); } Why does the prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute which inherits ValidationAttribute so it should be there. If I manually move the [NumberCode] attribute to the autogenerated class, then it is included in the prop.Attributes.OfType<ValidationAttribute>() collection. So what I don't understand is why this particular attribute does not work in when in the buddy class, when other attributes in the buddy class do work. And why this attribute works in the autogenerated class, but not in the buddy. Any ideas? Also why does DisplayName get overriden by the buddy, when StringLength does not?

    Read the article

  • Looping through all attributes of a XML element in XSLT

    - by TheGNUGuy
    Hey everyone, I am trying to use <xsl:for-each select="@*"> to grab all the attributes of a given element but when i do that my <xsl:choose> statement doesn't execute. Here is the element that I'm working with: <textBox id="Airfare" value="" label="text 1"/> Here is the XSLT template I'm using: <xsl:template match="textBox"> <div> <xsl:choose> <xsl:when test="@label"> <xsl:value-of select="@label"/> </xsl:when> <xsl:otherwise> <xsl:text>No Label Defined</xsl:text> </xsl:otherwise> </xsl:choose> <xsl:element name="input"> <xsl:attribute name="type">text</xsl:attribute> <xsl:for-each select="@*"> <xsl:choose> <xsl:when test="@id"> <xsl:attribute name="name">form_<xsl:value-of select="@id"/></xsl:attribute> <xsl:attribute name="id">form_<xsl:value-of select="@id"/></xsl:attribute> </xsl:when> <xsl:when test="@label"> </xsl:when> <xsl:otherwise> <xsl:copy-of select="current()"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:element> </div> And when I generate the HTML using PHP I get this: <div>text 1<input type="text" id="Airfare" value="" label="text 1"></div> As you can see it didn't add form_ to the id attribute it didn't generate a name attribute and it didn't skip over the label attribute. Thanks for your help!

    Read the article

  • asking the container to notify your application whenever a session is about to timeout in Java

    - by user136101
    Which method(s) can be used to ask the container to notify your application whenever a session is about to timeout?(choose all that apply) A. HttpSessionListener.sessionDestroyed -- correct B. HttpSessionBindingListener.valueBound C. HttpSessionBindingListener.valueUnbound -- correct this is kind of round-about but if you have an attribute class this is a way to be informed of a timeout D. HttpSessionBindingEvent.sessionDestroyed -- no such method E. HttpSessionAttributeListener.attributeRemoved -- removing an attribute isn’t tightly associated with a session timeout F. HttpSessionActivationListener.sessionWillPassivate -- session passivation is different than timeout I agree with option A. 1) But C is doubtful How can value unbound be tightly coupled with session timeout.It is just the callback method when an attribute gets removed. 2) and if C is correct, E should also be correct. HttpSessionAttributeListener is just a class that wants to know when any type of attribute has been added, removed, or replaced in a session. It is implemented by any class. HttpSessionBindingListener exists so that the attribute itself can find out when it has been added to or removed from a session and the attribute class must implement this interface to achieve it. Any ideas…

    Read the article

  • Cannot Generate ParameterSetMetadata While Programmatically Creating A Parameter Block

    - by Steven Murawski
    I'm trying to programmatically create a parameter block for a function ( along the lines of this blog post ). I'm starting with a CommandMetadata object (from an existing function). I can create the ParameterMetadata object and set things like the ParameterType, the name, as well as some attributes. The problem I'm running into is that when I use the GetParamBlock method of the ProxyCommand class, none of my attributes that I set in the Attributes collection of the ParameterMetadata are generated. The problem this causes is that when the GetParamBlock is called, the new parameter is not annotated with the appropriate Parameter attribute. Example: function test { [CmdletBinding()] param ( [Parameter()] $InitialParameter) Write-Host "I don't matter." } $MetaData = New-Object System.Management.Automation.CommandMetaData (get-command test) $NewParameter = New-Object System.Management.Automation.ParameterMetadata 'NewParameter' $NewParameter.ParameterType = [string[]] $Attribute = New-Object System.Management.Automation.ParameterAttribute $Attribute.Position = 1 $Attribute.Mandatory = $true $Attribute.ValueFromPipeline = $true $NewParameter.Attributes.Add($Attribute) $MetaData.Parameters.Add('NewParameter', $NewParameter) [System.Management.Automation.ProxyCommand]::GetParamBlock($MetaData)

    Read the article

  • Generating a .CSV with Several Columns - Use a Dictionary?

    - by Qanthelas
    I am writing a script that looks through my inventory, compares it with a master list of all possible inventory items, and tells me what items I am missing. My goal is a .csv file where the first column contains a unique key integer and then the remaining several columns would have data related to that key. For example, a three row snippet of my end-goal .csv file might look like this: 100001,apple,fruit,medium,12,red 100002,carrot,vegetable,medium,10,orange 100005,radish,vegetable,small,10,red The data for this is being drawn from a couple sources. 1st, a query to an API server gives me a list of keys for items that are in inventory. 2nd, I read in a .csv file into a dict that matches keys with item name for all possible keys. A snippet of the first 5 rows of this .csv file might look like this: 100001,apple 100002,carrot 100003,pear 100004,banana 100005,radish Note how any key in my list of inventory will be found in this two column .csv file that gives all keys and their corresponding item name and this list minus my inventory on hand yields what I'm looking for (which is the inventory I need to get). So far I can get a .csv file that contains just the keys and item names for the items that I don't have in inventory. Give a list of inventory on hand like this: 100003,100004 A snippet of my resulting .csv file looks like this: 100001,apple 100002,carrot 100005,radish This means that I have pear and banana in inventory (so they are not in this .csv file.) To get this I have a function to get an item name when given an item id that looks like this: def getNames(id_to_name, ids): return [id_to_name[id] for id in ids] Then a function which gives a list of keys as integers from my inventory server API call that returns a list and I've run this function like this: invlist = ServerApiCallFunction(AppropriateInfo) A third function takes this invlist as its input and returns a dict of keys (the item id) and names for the items I don't have. It also writes the information of this dict to a .csv file. I am using the set1 - set2 method to do this. It looks like this: def InventoryNumbers(inventory): with open(csvfile,'w') as c: c.write('InvName' + ',InvID' + '\n') missinginvnames = [] with open("KeyAndItemNameTwoColumns.csv","rb") as fp: reader = csv.reader(fp, skipinitialspace=True) fp.readline() # skip header invidsandnames = {int(id): str.upper(name) for id, name in reader} invids = set(invidsandnames.keys()) invnames = set(invidsandnames.values()) invonhandset = set(inventory) missinginvidsset = invids - invonhandset missinginvids = list(missinginvidsset) missinginvnames = getNames(invidsandnames, missinginvids) missinginvnameswithids = dict(zip(missinginvnames, missinginvids)) print missinginvnameswithids with open(csvfile,'a') as c: for invname, invid in missinginvnameswithids.iteritems(): c.write(invname + ',' + str(invid) + '\n') return missinginvnameswithids Which I then call like this: InventoryNumbers(invlist) With that explanation, now on to my question here. I want to expand the data in this output .csv file by adding in additional columns. The data for this would be drawn from another .csv file, a snippet of which would look like this: 100001,fruit,medium,12,red 100002,vegetable,medium,10,orange 100003,fruit,medium,14,green 100004,fruit,medium,12,yellow 100005,vegetable,small,10,red Note how this does not contain the item name (so I have to pull that from a different .csv file that just has the two columns of key and item name) but it does use the same keys. I am looking for a way to bring in this extra information so that my final .csv file will not just tell me the keys (which are item ids) and item names for the items I don't have in stock but it will also have columns for type, size, number, and color. One option I've looked at is the defaultdict piece from collections, but I'm not sure if this is the best way to go about what I want to do. If I did use this method I'm not sure exactly how I'd call it to achieve my desired result. If some other method would be easier I'm certainly willing to try that, too. How can I take my dict of keys and corresponding item names for items that I don't have in inventory and add to it this extra information in such a way that I could output it all to a .csv file? EDIT: As I typed this up it occurred to me that I might make things easier on myself by creating a new single .csv file that would have date in the form key,item name,type,size,number,color (basically just copying in the column for item name into the .csv that already has the other information for each key.) This way I would only need to draw from one .csv file rather than from two. Even if I did this, though, how would I go about making my desired .csv file based on only those keys for items not in inventory?

    Read the article

  • Selecting dictionary items by key efficiently in Python

    - by user248237
    suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list? for example: # a dictionary mapping strings to stuff mydict = {'quux': ..., 'bar': ..., 'foo': ...} # list of keys to be selected from mydict keys_to_select = ['foo', 'bar', ...] The way I came up with is: filtered_mydict = [mydict[k] for k in mydict.keys() \ if k in keys_to_select] but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. at least one of these can be avoided, I would think. any ideas? I can use scipy/numpy too if needed.

    Read the article

  • Why am I getting a " instance has no attribute '__getitem__' " error?

    - by Kevin Yusko
    Here's the code: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None root = [self.key, self.left, self.right] def getRootVal(root): return root[0] def setRootVal(newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: t = BinaryTree(newNode) t.left = self.left self.left = t def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: t = BinaryTree(newNode) t.right = self.right self.right = t def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in '+-*/)': currentTree.setRootVal(eval(i)) parent = pStack.pop() currentTree = parent elif i in '+-*/': currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: print "error: I don't recognize " + i return eTree def postorder(tree): if tree != None: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print tree.getRootVal() def preorder(self): print self.key if self.left: self.left.preorder() if self.right: self.right.preorder() def inorder(tree): if tree != None: inorder(tree.getLeftChild()) print tree.getRootVal() inorder(tree.getRightChild()) class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def main(): parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " ) tree = buildParseTree(parseData) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + preorder(tree)) print( "The post order is: ", + inorder(tree)) main() And here is the error: Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 ) Traceback (most recent call last): File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in main() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main tree = buildParseTree(parseData) File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree currentTree = currentTree.getLeftChild() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild return root[1] AttributeError: BinaryTree instance has no attribute '__getitem__'

    Read the article

  • WCF service with Factory attribute on .svc is not working on web server (IIS6), but is locally using

    - by Jessica
    I am working on implementing a non web.config approach of WCF services using the factory attribute on the .svc file per Rick Strahl's blog post: Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" Locally, I am running IIS7 in Visual Studio 2008 and have no problem, but when I deploy to my web server (currently running IIS6), I am getting an authentication error in the event log: Exception: System.ServiceModel.ServiceActivationException: The service '/Services/ResourcesService.svc' cannot be activated due to an exception during compilation. The exception message is: IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used.. --- System.InvalidOperationException: IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used. at System.ServiceModel.Web.WebServiceHost.SetBindingCredentialBasedOnHostedEnvironment(ServiceEndpoint serviceEndpoint, AuthenticationSchemes supportedSchemes) at System.ServiceModel.Web.WebServiceHost.AddAutomaticWebHttpBindingEndpoints(ServiceHost host, IDictionary`2 implementedContracts, String multipleContractsErrorMessage) at System.ServiceModel.WebScriptServiceHost.OnOpening() at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open() at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) After doing some Googling, I changed my authentication settings on the .svc folder within my project (on the server) to only anonymous authentication, but it did not work. I still get web service failed on the calls. IIS7 by default only had anonymous. I do not have any entries in my web.config for the services (I stripped them out per this pattern). I am using a nant script to deploy the website to the server and use this also locally to verify the script was not causing the issue. Any known issue with this? IIS 6 not able to handle?

    Read the article

  • Simple way to decrease values without making a new attribute?

    - by Jam
    I'm making a program where you're firing a 'blaster', and I have 5 ammo. I'm blasting an alien who has 5 health. At the end I instantiate the player and make him blast 6 times to check that the program works correctly. But the way I've done it makes it so that the amount won't decrease. Is there an easy fix to this, or do I just have to make a new attribute for ammo and health? Here's what I have: class Player(object): """ A player in a shooter game. """ def blast(self, enemy, ammo=5): if ammo>=1: ammo-=1 print "You have blasted the alien." print "You have", ammo, "ammunition left." enemy.die(5) else: print "You are out of ammunition!" class Alien(object): """ An alien in a shooter game. """ def die(self, health=5): if health>=1: health-=1 print "The alien is wounded. He now has", health, "health left." elif health==0: health-=1 print "The alien gasps and says, 'Oh, this is it. This is the big one. \n" \ "Yes, it's getting dark now. Tell my 1.6 million larvae that I loved them... \n" \ "Good-bye, cruel universe.'" else: print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!" # main print "\t\tDeath of an Alien\n" hero = Player() invader = Alien() hero.blast(invader) hero.blast(invader) hero.blast(invader) hero.blast(invader) hero.blast(invader) hero.blast(invader) raw_input("\n\nPress the enter key to exit.")

    Read the article

  • Getting message in android app: Binary XML file line #2: You must supply a layout_width attribute.

    - by opike
    I'm trying to use a ListView inside of a RelativeLayout but when I run my app I get a runtimeexception with the message: Binary XML file line #2: You must supply a layout_width attribute. I tried putting layout_width attributes in every conceivable place in the xml resource files but so far no luck. I attempt to populate the listview with this line of code: setListAdapter(new ArrayAdapter(this, R.layout.tablerow3, R.id.label, items)); Here's the tablerow3.xml contents: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> android:layout_width="20dp" android:layout_height="5dp" android:id="@+id/tablerow01"> <Label android:id="@+id/label01" android:layout_width="5dp" android:layout_height="5dp" android:textColor="@color/solid_white" android:singleLine="true"/> <Label android:id="@+id/label02" android:layout_width="5dp" android:layout_height="5dp" android:textColor="@color/solid_white" android:singleLine="true"/> </LinearLayout> Here's the xml that contains the RelativeLayout(forex2.xml): <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:text="Static Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:id="@+id/button_id"> </Button> <Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_toRightOf="@id/button_id" android:layout_alignParentTop="true" android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> <ListView android:id="@android:id/list" android:layout_width="5dp" android:layout_height="5dp" android:layout_alignParentBottom="true" /> <!-- android:layout_width="wrap_content" android:layout_height="wrap_content" --> </RelativeLayout>

    Read the article

  • Unexpected end of file while searching for ']' to end attribute selector.

    - by zurna
    I dont understand what would be the problem with the following code. It needs to copy image's id value to another textbox but instead I get an error. Unexpected end of file while searching for ']' to end attribute selector. <script> $(function() { $(".floatLeft").click(function() { var id = $(this).attr("id").replace(/\D/g, ""); $("input[name='photo[" + id + "]'").val(Math.abs($("input[name='photo[" + id + "]'").val() - 1)); }); }); </script> <ul class="thumbs"> <li> <img src="/FLPM/media/news/images/2M9Y1I2K_sm.jpg" alt="Garden" id="28" class="floatLeft" /> <input type="text" name="photo28" value="0" /> <br /> <a href="?Process=&IMAGEID=28" class="thumb"><span class="floatLeft">DELETE</span></a> </li> <li> <img src="/FLPM/media/news/images/2A9L1V2X_sm.jpg" alt="Frangipani Flowers" id="27" class="floatLeft" /> <input type="text" name="photo27" value="0" /> <br /> <a href="?Process=&IMAGEID=27" class="thumb"><span class="floatLeft">DELETE</span></a> </li> </ul>

    Read the article

  • What is the best way to automatically transpose a LilyPond source file into multiple keys?

    - by Michael Steele
    problem I'm using LilyPond to typeset sheet music for a church choir to perform. Depending on who is available on any given week, songs will be played in various keys. We have an amazing pianist who can play anything we throw at her and the guitarists will typically pencil in alternate chords, but I want to make things easier by having beautifully typeset sheet music available in any key we want. So say we're going to sing our ABCs. First I'll take whatever source transcriptions available and enter it into a LilyPond script: melody = \relative c' { c c g g a a g2 f f e e d d c2 } I want the ability to transpose this automatically, so if I want the whole thing in 'G' I wrap the song in a \transpose call like so: melody = \transpose c g \relative c' { c c g g a a g2 f f e e d d c2 } What I really want is to substitute something for the 'g' and generate the output for melody multiple times. Simple LilyPond variables don't seem to work here, and so far I've been unsuccessful in defining a scheme function to do this. What I've resorted to for the moment is taking the above file, call it twinkle.ly and turning it into an M4 script called twinkle.ly.m4, the contents of which look like this: melody = \transpose c _key \relative c' { c c g g a a g2 f f e e d d c2 } I then compile the while thing by executing the following line: > m4 -D _key=g twinkle.ly.m4 > twinkle_g.ly && lilypond twinkle_g.ly I've written a Makefile to do this for me, defining rules for every song I have and every key I'm interested in. question There's got to be a better way of going about this. Given that Lilypond supports embedded scheme, I would prefer to not use a macro preprocessed on it. Has anybody else come up with a solution to this same problem?

    Read the article

  • How do I define a Calculated Measure in MDX based on a Dimension Attribute?

    - by ShaneD
    I would like to create a calculated measure that sums up only a specific subset of records in my fact table based on a dimension attribute. Given: Dimension Date LedgerLineItem {Charge, Payment, Write-Off, Copay, Credit} Measures LedgerAmount Relationships * LedgerLineItem is a degenerate dimension of FactLedger If I break down LedgerAmount by LedgerLineItem.Type I can easily see how much is charged, paid, credit, etc, but when I do not break it down by LedgerLineItem.Type I cannot easily add the credit, paid, credit, etc into a pivot table. I would like to create separate calculated measures that sum only specific type (or multiple types) of ledger facts. An example of the desired output would be: | Year | Charged | Total Paid | Amount - Ledger | | 2008 | $1000 | $600 | -$400 | | 2009 | $2000 | $1500 | -$500 | | Total | $3000 | $2100 | -$900 | I have tried to create the calculated measure a couple of ways and each one works in some circumstances but not in others. Now before anyone says do this in ETL, I have already done it in ETL and it works just fine. What I am trying to do as part of learning to understand MDX better is to figure out how to duplicate what I have done in the ETL in MDX as so far I am unable to do that. Here are two attempts I have made and the problems with them. This works only when ledger type is in the pivot table. It returns the correct amount of the ledger entries (although in this case it is identical to [amount - ledger] but when I try to remove type and just get the sum of all ledger entries it returns unknown. CASE WHEN ([Ledger].[Type].currentMember = [Ledger].[Type].&[Credit]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Paid]) OR ([Ledger].[Type].currentMember = [Ledger].[Type].&[Held Money: Copay]) THEN [Measures].[Amount - ledger] ELSE 0 END This works only when ledger type is not in the pivot table. It always returns the total payment amount, which is incorrect when I am slicing by type as I would only expect to see the credit portion under credit, the paid portion, under paid, $0 under charge, etc. sum({([Ledger].[Type].&[Credit]), ([Ledger].[Type].&[Paid]), ([Ledger].[Type].&[Held Money: Copay])}, [Measures].[Amount - ledger]) Is there any way to make this return the correct numbers regardless of whether Ledger.Type is included in my pivot table or not?

    Read the article

  • How to make TXMLDocument (with the MSXML Implementation) always include the encoding attribute?

    - by Fabricio Araujo
    I have legacy code (I didn't write it) that always included the encoding attribute, but recompiling it to D2010, TXMLDocument doesn't include the enconding anymore. Because the XML data have accented characters both on tags and data, TXMLDocument.LoadFromFile simply throws EDOMParseErros saying that an invalid character is found on the file. Relevant code: Doc := TXMLDocument.Create(nil); try Doc.Active := True; Doc.Encoding := XMLEncoding; RootNode := Doc.CreateElement('Test', ''); Doc.DocumentElement := RootNode; <snip> //Result := Doc.XMl.Text; Doc.SaveToXML(Result); // Both lines gives the same result On older versions of Delphi, the following line is generated: <?xml version="1.0" encoding="ISO-8859-1"?> On D2010, this is generated: <?xml version="1.0"?> If I change manually the line, all works like always worked in the last years. UPDATE: XMLEncoding is a constant and is defined as follow XMLEncoding = 'ISO-8859-1';

    Read the article

  • Is there a Boost (or other common lib) type for matrices with string keys?

    - by mohawkjohn
    I have a dense matrix where the indices correspond to genes. While gene identifiers are often integers, they are not contiguous integers. They could be strings instead, too. I suppose I could use a boost sparse matrix of some sort with integer keys, and it wouldn't matter if they're contiguous. Or would this still occupy a great deal of space, particularly if some genes have identifiers that are nine digits? Further, I am concerned that sparse storage is not appropriate, since this is an all-by-all matrix (there will be a distance in each and every cell, provided the gene exists). I'm unlikely to need to perform any matrix operations (e.g., matrix multiplication). I will need to pull vectors out of the matrix (slices). It seems like the best type of matrix would be keyed by a Boost unordered_map (a hash map), or perhaps even simply an STL map. Am I looking at this the wrong way? Do I really need to roll my own? I thought I saw such a class somewhere before. Thanks!

    Read the article

  • C#: Is it possible to use expressions or functions as keys in a dictionary?

    - by Svish
    Would it work to use Expression<Func<T>> or Func<T> as keys in a dictionary? For example to cache the result of heavy calculations. For example, changing my very basic cache from a different question of mine a bit: public static class Cache<T> { // Alternatively using Expression<Func<T>> instead private static Dictionary<Func<T>, T> cache; static Cache() { cache = new Dictionary<Func<T>, T>(); } public static T GetResult(Func<T> f) { if (cache.ContainsKey(f)) return cache[f]; return cache[f] = f(); } } Would this even work? Edit: After a quick test, it seems like it actually works. But I discovered that it could probably be more generic, since it would now be one cache per return type... not sure how to change it so that wouldn't happen though... hmm Edit 2: Noo, wait... it actually doesn't. Well, for regular methods it does. But not for lambdas. They get various random method names even if they look the same. Oh well c",)

    Read the article

  • How can I lookup an attribute in any scope by name?

    - by Wai Yip Tung
    How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g. >>> def foo(name): ... a=1 ... print globals().get(name), locals().get(name) ... >>> foo('a') None 1 >>> b=1 >>> foo('b') 1 None >>> foo('foo') <function foo at 0x014744B0> None So far so good. However it fails to lookup any built-in names. >>> range <built-in function range> >>> foo('range') None None >>> int <type 'int'> >>> foo('int') None None Any idea on how to lookup built-in attributes?

    Read the article

  • How do I find the .max of an attribute value among a group of different Models?

    - by Angela
    Hi, everyone: I am also open to just straight-up refactoring what I'm finding to be pretty repetitive, but to give a baseline of how it's working.... I have for every contact a Campaign, which has_many of three types of Models: Email, Call, and Letter. When an Email (Call or Letter) has been executed for a specific contact, I have a Contact_Email(_or_Call_or_Letter) which belongs to both the Contact and the Model (Email_or_Call_or_Letter). Each Contact_Email for example pairing has a :date_sent attribute. So does each Contact_Call and Contact_Letter. How do I find the latest of all of them? Here is the code I wrote that can find the latest Email and my finding retyping similar code for Call and Letter, but then stuck on how to do a .max on all of them: def last_email(contact) #get campaign the contact belongs to @campaign = Campaign.find_by_id(contact.campaign_id) @last_email = ContactEmail.find(:last, :conditions => "contact_id = #{contact.id}", :order => "date_sent DESC") @last_call = ContactCall.find(:last, :conditions => "contact_id = #{contact.id}", :order => "date_sent DESC") @last_letter = ContactLetter.find(:last, :conditions => "contact_id = #{contact.id}", :order => "date_sent DESC") # how do I get the latest of all of these to display? if @last_sent_email.nil? return "no email sent" else return @last_sent_email.date_sent end end Question 1: With what I have, how can I find effectively @last_event given I can find the last Email, last Call, and last Letter for every contact? Question 2: How can I remove the repetitive code that I have to write for each Model?

    Read the article

  • ASP:DropDownList in ItemTemplate: Why is SelectedValue attribute allowed?

    - by recursive
    This piece of code <asp:DropDownList runat="server" ID="testdropdown" SelectedValue="2"> <asp:ListItem Text="1" Value="1"></asp:ListItem> <asp:ListItem Text="2" Value="2"></asp:ListItem> <asp:ListItem Text="3" Value="3"></asp:ListItem> </asp:DropDownList> yields this error: The 'SelectedValue' property cannot be set declaratively. Yet, this is a legal and commonly used edit template for databound GridViews. The SelectedValue attribute certainly appears to be declaratively set here. <EditItemTemplate> <asp:DropDownList runat="server" ID="GenreDropDownList" DataSourceID="GenreDataSource" DataValueField="GenreId" DataTextField="Name" SelectedValue='<%# Bind("Genre.GenreId") %>'> </asp:DropDownList> </EditItemTemplate> The question is: what is the difference between the cases when you are allowed to set it declaratively and those in which you are not? The error message implies that it's never allowed.

    Read the article

  • Would like to move MovieClip using onstage buttons, not arrow keys.

    - by Anne
    To move the MC, using arrow keys I used the following and it worked: var timer:Timer; var direct:String; initStage(); function initStage() { stage.addEventListener(KeyboardEvent.KEY_DOWN,startMove); } function startMove(e:KeyboardEvent):void { switch (e.keyCode) { case Keyboard.RIGHT: direct = "right"; break; case Keyboard.LEFT: direct = "left"; break; case Keyboard.DOWN: direct = "down"; break; case Keyboard.UP: direct = "up"; } timer = new Timer(10); timer.addEventListener(TimerEvent.TIMER, moveBox); timer.start(); stage.removeEventListener(KeyboardEvent.KEY_DOWN, startMove); stage.addEventListener(KeyboardEvent.KEY_UP, stopMove); } function stopMove(e:KeyboardEvent):void { timer.stop(); initStage(); } function moveBox(e:TimerEvent):void { switch (direct) { case "right": box.x += 1; break; case "left": box.x -= 1; break; case "up": box.y -= 1; break; case "down": box.y += 1; break; } } I tried to convert this to use my onstage buttons: up_btn, down_btn, left_btn, right_btn to move MC box but couldn't figure it out. Can anyone help me convert this? Thanks in advance for any help you might offer. Annie

    Read the article

  • Why is FBJS dropping my 'onclick' attribute from this input element?

    - by Chris Barnhill
    When I include an 'onClick' attribute in setInnerXTHML() like this: var innerHtml = '<span>Build Track: Select a city where track building should begin'+ '<div id="action-end">'+ '<form>'+ '<input type="button" value="End Track Building" id="next-phase" onClick="moveTrainAuto();" />'+ '</form>'+ '</div></span>'; actionPrompt.setInnerXHTML(innerHtml); var btn = document.getElementById('next-phase'); btn.addEventListener('click', 'moveTrainAuto'); The 'onClick' gets dropped. I know this from inspecting the element with Firebug. This is what it reveals: <input id="app148184604666_next-phase" type="button" value="End Track Building"/> Here is the function called for onClick: function moveTrainAuto(evt) { debugger; ajax = new Ajax(); ajax.responseType = Ajax.JSON; ajax.ondone = function(data) { debugger; if(data.code == 'UNLOAD_CARGO') { unloadCargo(); } else if (data.code == 'MOVE_TRAIN_AUTO') { moveTrainAuto(); } else if (data.code == 'TURN_END') { turnEnd(); } else { /* handle error */ } } ajax.post(baseURL + '/turn/move-trains-auto'); } As you can see, I've tried both 'onClick' and 'addEventListener'. Neither works. Any ideas?

    Read the article

  • PHP Magic faster than simply setting the class attribute?

    - by Marc Trudel
    Well, not exactly that, but here is an example. Can anyone explain the difference between B and C? How can it be faster to use a magic function to dynamically set a value instead of simply setting the value in the attribute definition? Here is some code: [root@vm-202-167-238-17 ~]# cat test.php; for d in A B C; do echo "------"; ./test.php $d; done; #!/usr/bin/php <?php $className = $argv[1]; class A { public function __get($a) { return 5; } } class B { public $a = 5; } class C { public function __get($a) { $this->a = 5; return 5; } } $a = new $className; $start = microtime(true); for ($i=0; $i < 1000000; $i++) $b = $a->a; $end = microtime(true); echo (($end - $start) * 1000) ." msec\n"; ------ 598.90794754028 msec ------ 205.48391342163 msec ------ 189.7759437561 msec

    Read the article

  • google maps api keys to be set webserver-wide, (as env var? inside apache?)

    - by ~knb
    I have a web site with many virtual hosts and each registered with several domain names (ending in .org, .de), site1.mysite.de, site2.mysite.org Then I have different templating systems based on several programming languages (perl and php) in use on the web server. The Google Maps Api requires a unique Google Maps api key for each vhost. I want to have something like a web-server wide variable $goomapkey that I can call from inside my code. In PHP code, Now I have a kludgy case-analysis solution like $domain = substr($_SERVER['SERVER_NAME'], -3); if (".de" == $domain){ //if ("xxxxxx" eq substr($ENV{SERVER_NAME}, 0, 5)){ // $gookey = "ABQIAAA..."; //} else { //site1.de $gookey = "ABQIAAAA1Js..."; //} } elseif ("dev" == substr($_SERVER['SERVER_NAME'], 0, 3)){ //dev.mysite.org $gookey = "ABQIAAAA1JsSb..."; } else { //www.mysite.org $gookey = "ABQIAAAA1JsS..."; //TODO: Add more keys for each virtual host, for my.machinename.de, IP-address based URL, ... } ... inside my php-based CMS. A non-ideal solution, because it is, php-only, and I still have to set it at several html templates inside the CMS, and there are too many cases. I want the google maps api key to be set by the apache web server who examines the request *early in the request loop before any php page template code is constructed and evaluated. is an environment variable a good solution? which technology should be used to set the $goomapkey variable? I'd prefer mod_perl2 Apache request handler, but the documentation is confusing (many API changes in the past ). Which Apache module could I use? Is there a built-in Apache module that does the same thing?

    Read the article

  • PHP-How to choose XML section based on an attribute?

    - by Vincent
    All, I have a config xml file in the following format: <?xml version="1.0"?> <configdata> <development> <siteTitle>You are doing Development</siteTitle> </development> <test extends="development"> <siteTitle>You are doing Testing</siteTitle> </test> <production extends="development"> <siteTitle>You are in Production</siteTitle> </production> </configdata> To read this config file to apply environment settings, currently I am using, the following code in index.php file: $appEnvironment = "production"; $config = new Zend_Config_Xml('/config/settings.xml', $appEnvironment ); To deploy this code on multiple environments, as user has to change index.php file. Instead of doing that, is it possible to maintain an attribute in the xml file, "say active=true". Based on which the Zend_Config_Xml will know which section of the xml file settings to read? Thanks

    Read the article

  • Why do I need to give my options a value attribute in my dropdown? JQuery related.

    - by Alex
    So far in my web developing experiences, I've noticed that almost all web developers/designers choose to give their options in a select a value like so: <select name="foo"> <option value="bar">BarCheese</option> // etc. // etc. </select> Is this because it is best practice to do so? I ask this because I have done a lot of work with jQuery and dropdown's lately, and sometimes I get really annoyed when I have to check something like: $('select[name=foo]').val() == "bar"); To me, many times that seems less clear than just being able to check the val() against BarCheese. So why is it that most web developers/designers specify a value paramater instead of just letting the options actual value be its value? And yes, if the option has a value attribute I know I can do something like this: $('select[name=foo] option:contains("BarCheese")').attr('selected', 'selected'); But I would still really like to know why this is done. Thanks!!

    Read the article

< Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >