Search Results

Search found 5819 results on 233 pages for 'compiler theory'.

Page 12/233 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • box stacking in graph theory

    - by mozhdeh
    Please help me find a good solution for this problem. We have n boxes with 3 dimensions. We can orient them and we want to put them on top of another to have a maximun height. We can put a box on top of an other box, if 2 dimensions (width and lenght) are lower than the dimensions of the box below. For exapmle we have 3 dimensions w*D*h, we can show it in to (h*d,d*h,w*d,d*W,h*w,w*h) please help me to solve it in graph theory.

    Read the article

  • How to make php-closure compiler output to a predefined file name? (Updated)

    - by Mohammad
    Php-closure compiler (linked to source code) currently writes the compiled code to a md5 encoded filename. How can I make it so it write the compiled code to a predefined name like compiled_code.js? . . I think it has to do with the write() function on Line 164. It gets the filename via the _getCacheFileName() function (Line 272). function _getCacheFileName() { return $this->_cache_dir . $this->_getHash() . ".js"; } I've tried altering it to this: function _getCacheFileName() { //return $this->_cache_dir . $this->_getHash() . ".js"; return 'copiled_code.js'; } without any results. Thanks to all of you in advance!

    Read the article

  • Theory of computation - Using the pumping lemma for context free languages

    - by Tony
    I'm reviewing my notes for my course on theory of computation and I'm having trouble understanding how to complete a certain proof. Here is the question: A = {0^n 1^m 0^n | n>=1, m>=1} Prove that A is not regular. It's pretty obvious that the pumping lemma has to be used for this. So, we have |vy| = 1 |vxy| <= p (p being the pumping length, = 1) uv^ixy^iz exists in A for all i = 0 Trying to think of the correct string to choose seems a bit iffy for this. I was thinking 0^p 1^q 0^p, but I don't know if I can obscurely make a q, and since there is no bound on u, this could make things unruly.. So, how would one go about this?

    Read the article

  • Java generics: What is the compiler's issue here? ("no unique maximal instance")

    - by Epaga
    I have the following methods: public <T> T fromJson( Reader jsonData, Class<T> clazz ) { return fromJson( jsonData, (Type)clazz ); } public <T> T fromJson( Reader jsonData, Type clazz ) { ... } The compiler is saying about the first method: type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object return fromJson( jsonData, (Type)clazz ); ^ What is the problem?

    Read the article

  • How to generate a compiler error based on an attribute being missing in C#?

    - by RodH257
    I create a number of add-ins for the Revit Structure API. Each tool has to habe a class which implements the interface IExternalCommand. In the latest version of Revit, for your tool to work you need to have two attributes on the class that implements that interface: [Regeneration(RegenerationOption.Manual)] [Transaction(TransactionMode.Automatic)] The values in brackets can change, but there must be something there. Often I am finding myself forgetting to put the attributes on, then when it comes to runtime it crashes. Is there any way in Visual Studio 2010 to add a compiler warning or error saying that if your class implements that interface it must have those 2 attributes? I have resharper if that helps. Can anyone point me into the right direction?

    Read the article

  • How do you control what your C compiler Optimizes?

    - by Jordan S
    I am writing the firmware for an embedded device in C using the Silicon Labs IDE and the SDCC compiler. The device architecture is based on the 8051 family. The function in question is shown below. The function is used to set the ports on my MCU to drive a stepper motor. It gets called in by an interrupt handler. The big switch statement just sets the ports to the proper value for the next motor step. The bottom part of the function looks at an input from a hall effect sensor and a number of steps moved in order to detect if the motor has stalled. The problem is, for some reason the second IF statement that looks like this if (StallDetector > (GapSize + 20)) { HandleStallEvent(); } always seems to get optimized out. If I try to put a breakpoint at the HandleStallEvent() call the IDE gives me a message saying "No Address Correlation to this line number". I am not really good enough at reading assembly to tell what it is doing but I have pasted a snippet from the asm output below. Any help would be much appreciated. void OperateStepper(void) { //static bit LastHomeMagState = HomeSensor; static bit LastPosMagState = PosSensor; if(PulseMotor) { if(MoveDirection == 1) // Go clockwise { switch(STEPPER_POSITION) { case 'A': STEPPER_POSITION = 'B'; P1 = 0xFD; break; case 'B': STEPPER_POSITION = 'C'; P1 = 0xFF; break; case 'C': STEPPER_POSITION = 'D'; P1 = 0xFE; break; case 'D': STEPPER_POSITION = 'A'; P1 = 0xFC; break; default: STEPPER_POSITION = 'A'; P1 = 0xFC; } //end switch } else // Go CounterClockwise { switch(STEPPER_POSITION) { case 'A': STEPPER_POSITION = 'D'; P1 = 0xFE; break; case 'B': STEPPER_POSITION = 'A'; P1 = 0xFC; break; case 'C': STEPPER_POSITION = 'B'; P1 = 0xFD; break; case 'D': STEPPER_POSITION = 'C'; P1 = 0xFF; break; default: STEPPER_POSITION = 'A'; P1 = 0xFE; } //end switch } //end else MotorSteps++; StallDetector++; if(PosSensor != LastPosMagState) { StallDetector = 0; LastPosMagState = PosSensor; } else { if (PosSensor == ON) { if (StallDetector > (MagnetSize + 20)) { HandleStallEvent(); } } else if (PosSensor == OFF) { if (StallDetector > (GapSize + 20)) { HandleStallEvent(); } } } } //end if PulseMotor } ... and the asm output for the the bottom part of this function... ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:653: if(PosSensor != LastPosMagState) mov c,_P1_4 jb _OperateStepper_LastPosMagState_1_1,00158$ cpl c 00158$: jc 00126$ C$MotionControl.c$655$3$7 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:655: StallDetector = 0; clr a mov _StallDetector,a mov (_StallDetector + 1),a C$MotionControl.c$657$3$7 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:657: LastPosMagState = PosSensor; mov c,_P1_4 mov _OperateStepper_LastPosMagState_1_1,c ret 00126$: C$MotionControl.c$661$2$8 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:661: if (PosSensor == ON) jb _P1_4,00123$ C$MotionControl.c$663$4$9 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:663: if (StallDetector > (MagnetSize + 20)) mov a,_MagnetSize mov r2,a rlc a subb a,acc mov r3,a mov a,#0x14 add a,r2 mov r2,a clr a addc a,r3 mov r3,a clr c mov a,r2 subb a,_StallDetector mov a,r3 subb a,(_StallDetector + 1) jnc 00130$ C$MotionControl.c$665$5$10 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:665: HandleStallEvent(); ljmp _HandleStallEvent 00123$: C$MotionControl.c$668$2$8 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:668: else if (PosSensor == OFF) jnb _P1_4,00130$ C$MotionControl.c$670$4$11 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:670: if (StallDetector > (GapSize + 20)) mov a,#0x14 add a,_GapSize mov r2,a clr a addc a,(_GapSize + 1) mov r3,a clr c mov a,r2 subb a,_StallDetector mov a,r3 subb a,(_StallDetector + 1) jnc 00130$ C$MotionControl.c$672$5$12 ==. ; C:\SiLabs\Optec Programs\HSFW_HID_SDCC_2\MotionControl.c:672: HandleStallEvent(); C$MotionControl.c$678$2$1 ==. XG$OperateStepper$0$0 ==. ljmp _HandleStallEvent 00130$: ret It looks to me like the compiler is NOT optimizing out this second if statement from the looks of the asm but if that is the case why does the IDE not allow me so set a breakpoint there? Maybe it's just a dumb IDE!

    Read the article

  • Real life usage of the projective plane theory

    - by Elazar Leibovich
    I'm learning about the theory of the projective plane. Very generally speaking, it is an extension of the plane, which includes additional points which are defined as the intersection points of two parallel lines. In the projective plane, every two lines have an interesection point. Whether they're parallel or not. Every point in the projective plane can be represented by three numbers (you actually need less than that, but nevemind now). Is there any real life application which uses the projective plane? I can think that, for instance, a software which needs to find the intersections of a line, can benefit from always having an intersection point which might lead to simpler code, but is it really used?

    Read the article

  • Theory of computation - Using the pumping lemma for CFLs

    - by Tony
    I'm reviewing my notes for my course on theory of computation and I'm having trouble understanding how to complete a certain proof. Here is the question: A = {0^n 1^m 0^n | n>=1, m>=1} Prove that A is not regular. It's pretty obvious that the pumping lemma has to be used for this. So, we have |vy| = 1 |vxy| <= p (p being the pumping length, = 1) uv^ixy^iz exists in A for all i = 0 Trying to think of the correct string to choose seems a bit iffy for this. I was thinking 0^p 1^q 0^p, but I don't know if I can obscurely make a q, and since there is no bound on u, this could make things unruly.. So, how would one go about this?

    Read the article

  • Should you correct compiler warnings about type conversions using explicit typecasts?

    - by BastiBechtold
    In my current project, the compiler shows hundreds of warnings about type conversions. There is a lot of code like this iVar = fVar1*fVar2/fVar3; // or even iVar = fVar1*fVar2/fVar3+.5f; which intentionally assign float values to int. Of course, I could fix these warnings using iVar = int(...); but that looks kind of ugly. Would you rather live with the ugliness or live with the warnings? Or is there even a clean solution?

    Read the article

  • Explicitly typing variables causes compiler to think an instance of a builtin type doesn't have a pr

    - by wallacoloo
    I narrowed the causes of an AS3 compiler error 1119 down to code that looks similar to this: var test_inst:Number = 2.953; trace(test_inst); trace(test_inst.constructor); I get the error "1119: Access of possibly undefined property constructor through a reference with static type Number." Now if I omit the variable's type, I don't get that error: var test_inst = 2.953; trace(test_inst); trace(test_inst.constructor); it produces the expected output: 2.953 [class Number] So what's the deal? I like explicitly typing variables, so is there any way to solve this error other than not providing the variable's type?

    Read the article

  • Where does the compiler store methods for C++ classes?

    - by Mashmagar
    This is more a curiosity than anything else... Suppose I have a C++ class Kitty as follows: class Kitty { void Meow() { //Do stuff } } Does the compiler place the code for Meow() in every instance of Kitty? Obviously repeating the same code everywhere requires more memory. But on the other hand, branching to a relative location in nearby memory requires fewer assembly instructions than branching to an absolute location in memory on modern processors, so this is potentially faster. I suppose this is an implementation detail, so different compilers may perform differently. Keep in mind, I'm not considering static or virtual methods here.

    Read the article

  • Is C# compiler not reporting all errors at once at each compile?

    - by Joan Venge
    When I am compiling this project, it show like 400+ errors in the Error List window, then I go to error sites, fix some, and the number goes to say 120+ errors, and then after fixing some more, the next compile reports like 400+ again. I can see that different files are coming in in the Error List window, so I am thinking the compiler aborts after a certain number of errors? If so, what's the reason for this? Is it not supposed to gather all the errors that are present in the project even if they are over 10K+?

    Read the article

  • How can I make sense of the word "Functor" from a semantic standpoint?

    - by guillaume31
    When facing new programming jargon words, I first try to reason about them from an semantic and etymological standpoint when possible (that is, when they aren't obscure acronyms). For instance, you can get the beginning of a hint of what things like Polymorphism or even Monad are about with the help of a little Greek/Latin. At the very least, once you've learned the concept, the word itself appears to go along with it well. I guess that's part of why we name things names, to make mental representations and associations more fluent. I found Functor to be a tougher nut to crack. Not so much the C++ meaning -- an object that acts (-or) as a function (funct-), but the various functional meanings (in ML, Haskell) definitely left me puzzled. From the (mathematics) Functor Wikipedia article, it seems the word was borrowed from linguistics. I think I get what a "function word" or "functor" means in that context - a word that "makes function" as opposed to a word that "makes sense". But I can't really relate that to the notion of Functor in category theory, let alone functional programming. I imagined a Functor to be something that creates functions, or behaves like a function, or short for "functional constructor", but none of those seems to fit... How do experienced functional programmers reason about this ? Do they just need any label to put in front of a concept and be fine with it ? Generally speaking, isn't it partly why advanced functional programming is hard to grasp for mere mortals compared to, say, OO -- very abstract in that you can't relate it to anything familiar ? Note that I don't need a definition of Functor, only an explanation that would allow me to relate it to something more tangible, if there is any.

    Read the article

  • Minimizing data sent over a webservice call on expensive connection

    - by aceinthehole
    I am working on a system that has many remote laptops all connected to the internet through cellular data connections. The application will synchronize periodically to a central database. The problem is, due to factors outside our control, the cost to move data across the cellular networks are spectacularly expensive. Currently the we are sending a compressed XML file across the wire where it is being processed and various things are done with (mainly stuffing it into a database). My first couple of thoughts were to convert that XML doc to json, just prior to transmission and convert back to XML just after receipt on the other end, and get some extra compression for free without changing much. Another thought was to test various other compression algorithms to determine the smallest one possible. Although, I am not entirely sure how much difference json vs xml would make once it is compressed. I thought that their must be resources available that address this problem from an information theory perspective. Does anyone know of any such resources or suggestions on what direction to go in. This developed on the MS .net stack on windows for reference.

    Read the article

  • Japanese Multiplication simulation - is a program actually capable of improving calculation speed?

    - by jt0dd
    On SuperUser, I asked a (possibly silly) question about processors using mathematical shortcuts and would like to have a look at the possibility at the software application of that concept. I'd like to write a simulation of Japanese Multiplication to get benchmarks on large calculations utilizing the shortcut vs traditional CPU multiplication. I'm curious as to whether it makes sense to try this. My Question: I'd like to know whether or not a software math shortcut, as described above is actually a shortcut at all. This is a question of programming concept. By utilizing the simulation of Japanese Multiplication, is a program actually capable of improving calculation speed? Or am I doomed from the start? The answer to this question isn't required to determine whether or not the experiment will succeed, but rather whether or not it's logically possible for such a thing to occur in any program, using this concept as an example. My theory is that since addition is computed faster than multiplication, a simulation of Japanese multiplication may actually allow a program to multiply (large) numbers faster than the CPU arithmetic unit can. I think this would be a very interesting finding, if it proves to be true. If, in the multiplication of numbers of any immense size, the shortcut were to calculate the result via less instructions (or faster) than traditional ALU multiplication, I would consider the experiment a success.

    Read the article

  • org.apache.jasper.JasperException .... Unterminated &lt;%@ page tag

    - by Ankur
    I get org.apache.jasper.JasperException: /index.jsp(2,1) Unterminated <%@ page tag The page tags look like this: <%@ page import="java.util.*" %> <%@ page import="au.edu.uwa.peb.autoextractor.model.ScanResultItem"; %> This seems to indicate to me that a < does not have a corresponding tag ... is this so ... my IDE does not highlight any errors so how can I find this unterminated tag. Is there a JSP validation tool that I can use, perhaps online? The stack trace looks like this: org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407) org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:132) org.apache.jasper.compiler.Parser.parseDirective(Parser.java:520) org.apache.jasper.compiler.Parser.parseTagFileDirectives(Parser.java:1784) org.apache.jasper.compiler.Parser.parse(Parser.java:127) org.apache.jasper.compiler.ParserController.doParse(ParserController.java:255) org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:120) org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:165) org.apache.jasper.compiler.Compiler.compile(Compiler.java:332) org.apache.jasper.compiler.Compiler.compile(Compiler.java:312) org.apache.jasper.compiler.Compiler.compile(Compiler.java:299) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

    Read the article

  • Is the C++ compiler optimizer allowed to break my destructor ability to be called multiple times?

    - by sharptooth
    We once had an interview with a very experienced C++ developer who couldn't answer the following question: is it necessary to call the base class destructor from the derived class destructor in C++? Obviously the answer is no, C++ will call the base class destructor automagically anyway. But what if we attempt to do the call? As I see it the result will depend on whether the base class destructor can be called twice without invoking erroneous behavior. For example in this case: class BaseSafe { public: ~BaseSafe() { } private: int data; }; class DerivedSafe { public: ~DerivedSafe() { BaseSafe::~BaseSafe(); } }; everything will be fine - the BaseSafe destructor can be called twice safely and the program will run allright. But in this case: class BaseUnsafe { public: BaseUnsafe() { buffer = new char[100]; } ~BaseUnsafe () { delete[] buffer; } private: char* buffer; }; class DerivedUnsafe { public: ~DerivedUnsafe () { BaseUnsafe::~BaseUnsafe(); } }; the explicic call will run fine, but then the implicit (automagic) call to the destructor will trigger double-delete and undefined behavior. Looks like it is easy to avoid the UB in the second case. Just set buffer to null pointer after delete[]. But will this help? I mean the destructor is expected to only be run once on a fully constructed object, so the optimizer could decide that setting buffer to null pointer makes no sense and eliminate that code exposing the program to double-delete. Is the compiler allowed to do that?

    Read the article

  • Can a conforming C# compiler optimize away a local (but unused) variable if it is the only strong re

    - by stakx
    The title says it all, but let me explain: void Case_1() { var weakRef = new WeakReference(new object()); GC.Collect(); // <-- doesn't have to be an explicit call; just assume that // garbage collection would occur at this point. if (weakRef.IsAlive) ... } In this code example, I obviously have to plan for the possibility that the new'ed object is reclaimed by the garbage collector; therefore the if statement. (Note that I'm using weakRef for the sole purpose of checking if the new'ed object is still around.) void Case_2() { var unusedLocalVar = new object(); var weakRef = new WeakReference(unusedLocalVar); GC.Collect(); // <-- doesn't have to be an explicit call; just assume that // garbage collection would occur at this point. Debug.Assert(weakReferenceToUseless.IsAlive); } The main change in this code example from the previous one is that the new'ed object is strongly referenced by a local variable (unusedLocalVar). However, this variable is never used again after the weak reference (weakRef) has been created. Question: Is a conforming C# compiler allowed to optimize the first two lines of Case_2 into those of Case_1 if it sees that unusedLocalVar is only used in one place, namely as an argument to the WeakReference constructor? i.e. is there any possibility that the assertion in Case_2 could ever fail?

    Read the article

  • Array Multiplication and Division

    - by Narfanator
    I came across a question that (eventually) landed me wondering about array arithmetic. I'm thinking specifically in Ruby, but I think the concepts are language independent. So, addition and subtraction are defined, in Ruby, as such: [1,6,8,3,6] + [5,6,7] == [1,6,8,3,6,5,6,7] # All the elements of the first, then all the elements of the second [1,6,8,3,6] - [5,6,7] == [1,8,3] # From the first, remove anything found in the second and array * scalar is defined: [1,2,3] * 2 == [1,2,3,1,2,3] But What, conceptually, should the following be? None of these are (as far as I can find) defined: Array x Array: [1,2,3] * [1,2,3] #=> ? Array / Scalar: [1,2,3,4,5] / 2 #=> ? Array / Scalar: [1,2,3,4,5] % 2 #=> ? Array / Array: [1,2,3,4,5] / [1,2] #=> ? Array / Array: [1,2,3,4,5] % [1,2] #=> ? I've found some mathematical descriptions of these operations for set theory, but I couldn't really follow them, and sets don't have duplicates (arrays do). Edit: Note, I do not mean vector (matrix) arithmetic, which is completely defined. Edit2: If this is the wrong stack exchange, tell me which is the right one and I'll move it. Edit 3: Add mod operators to the list. Edit 4: I figure array / scalar is derivable from array * scalar: a * b = c => a = b / c [1,2,3] * 3 = [1,2,3]+[1,2,3]+[1,2,3] = [1,2,3,1,2,3,1,2,3] => [1,2,3] = [1,2,3,1,2,3,1,2,3] / 3 Which, given that programmer's division ignore the remained and has modulus: [1,2,3,4,5] / 2 = [[1,2], [3,4]] [1,2,3,4,5] % 2 = [5] Except that these are pretty clearly non-reversible operations (not that modulus ever is), which is non-ideal. Edit: I asked a question over on Math that led me to Multisets. I think maybe extensible arrays are "multisets", but I'm not sure yet.

    Read the article

  • Java NIO (Netty): How does Encryption or GZIPping work in theory (with filters)

    - by Tom
    Hello Experts, i would be very thankfull if you can explain to me, how in theory the "Interceptor/Filter" Pattern in ByteStreams (over Sockets/Channels) work (in Asynchronous IO with netty) in regard to encryption or compression of data. Given I have a Filter that does GZIPPING. How is this internally implemented? Does the Filter "collect" so many bytes form the channel, that this is a usefull number of bytes that can then be en/decoded? What is in general the minimal "blocksize(data to encode/decode in a chunk)" of socket based gzipping? Does this "blocksize" have to be negotiated in advance between server and client? What happens if the client does not send enough data to "fill" the blocksize (due to a network conquestion) but does not close the connection. Does this mean the other side will simply wait until it gets enough bytes to decode or until a timeout occoures...How is the Filter pattern the applied? The compression filter will de/compress the blocksize of bytes and then store them again in the same buffer would (in the case of netty) i normally be using the ChannelHanlderContext to pass the de/encoded data to the next filter?... Any explanations/links/tutorials (for beginners;-) will be very much appreciated to help me understand how for example encryption/compressing are implemented in socket based communication with filters/interceptor pattern. thank you very much tom

    Read the article

  • Java Compiler Creation Help..Please

    - by Brian
    I need some help with my code here...What we are trying to do is make a compiler that will read a file containing Machine Code and converting it to 100 lines of 4 bits example: this code is the machine code being converting to opcode and operands. I need some help please.. thanks 799 798 198 499 1008 1108 899 909 898 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Everything compiles but when I go and run my Test.java I get the following OutPut: Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1516) at Compiler.FirstPass(Compiler.java:22) at Compiler.compile(Compiler.java:11) at Test.main(Test.java:5) Here is my class Compiler: import java.io.*; import java.io.DataOutputStream; import java.util.NoSuchElementException; import java.util.Scanner; class Compiler{ private int lc = 0; private int dc = 99; public void compile(String filename) { SymbolList symbolTable = FirstPass(filename); SecondPass(symbolTable, filename); } public SymbolList FirstPass(String filename) { File file = new File(filename); SymbolList temp = new SymbolList(); int dc = 99; int lc = 0; try{ Scanner scan = new Scanner(file); String line = scan.nextLine(); String[] linearray = line.split(" "); while(line!=null){ if(!linearray[0].equals("REM")){ if(!this.isInstruction(linearray[0])){ linearray[0]=removeColon(linearray[0]); if(this.isInstruction(linearray[1])){ temp.add(new Symbol(linearray[0], lc, null)); lc++; } else { temp.add(new Symbol(linearray[0], dc, Integer.valueOf((linearr\ ay[2])))); dc--; } } else { if(!linearray[0].equals("REM")) lc++; } } try{ line = scan.nextLine(); } catch(NoSuchElementException e){ line=null; break; } linearray = line.split(" "); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return temp; } public String makeFilename(String filename) { return filename + ".ex"; } public String removeColon(String str) { if(str.charAt(str.length()-1) == ':'){ return str.substring(0, str.length()-1); } else { return str; } } public void SecondPass(SymbolList symbolTable, String filename){ try { int dc = 99; //Open file for reading File file = new File(filename); Scanner scan = new Scanner(file); //Make filename of new executable file String newfile = makeFilename(filename); //Open Output Stream for writing new file. FileOutputStream os = new FileOutputStream(filename); DataOutputStream dos = new DataOutputStream(os); //Read First line. Split line by Spaces into linearray. String line = scan.nextLine(); String[] linearray = line.split(" "); while(scan.hasNextLine()){ if(!linearray[0].equals("REM")){ int inst=0, opcode, loc; if(isInstruction(linearray[0])){ opcode = getOpcode(linearray[0]); loc = symbolTable.searchName(linearray[1]).getMemloc(); inst = (opcode*100)+loc; } else if(!isInstruction(linearray[0])){ if(isInstruction(linearray[1])){ opcode = getOpcode(linearray[1]); if(linearray[1].equals("STOP")) inst=0000; else { loc = symbolTable.searchName(linearray[2]).getMemloc(); inst = (opcode*100)+loc; } } if(linearray[1].equals("DC")) dc--; } System.out.println(inst); dos.writeInt(inst); linearray = line.split(" "); } if(scan.hasNextLine()) { line = scan.nextLine(); } } scan.close(); for(int i = lc; i <= dc; i++) { dos.writeInt(0); } for(int i = dc+1; i<100; i++){ dos.writeInt(symbolTable.searchLocation(i).getValue()); if(i!=99) dos.writeInt(0); } dos.close(); os.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int getOpcode(String inst){ int toreturn = -1; if(isInstruction(inst)){ if(inst.equals("STOP")) toreturn=0; if(inst.equals("LD")) toreturn=1; if(inst.equals("STO")) toreturn=2; if(inst.equals("ADD")) toreturn=3; if(inst.equals("SUB")) toreturn=4; if(inst.equals("MPY")) toreturn=5; if(inst.equals("DIV")) toreturn=6; if(inst.equals("IN")) toreturn=7; if(inst.equals("OUT")) toreturn=8; if(inst.equals("B")) toreturn=9; if(inst.equals("BGTR")) toreturn=10; if(inst.equals("BZ")) toreturn=11; return toreturn; } else { return -1; } } public boolean isInstruction(String totest){ boolean toreturn = false; String[] labels = {"IN", "LD", "SUB", "BGTR", "BZ", "OUT", "B", "STO", "STOP", "AD\ D", "MTY", "DIV"}; for(int i = 0; i < 12; i++){ if(totest.equals(labels[i])) toreturn = true; } return toreturn; } } And here is my class Computer: import java.io.*; import java.util.NoSuchElementException; import java.util.Scanner; class Computer{ private Cpu cpu; private Input in; private OutPut out; private Memory mem; public Computer() throws IOException { Memory mem = new Memory(100); Input in = new Input(); OutPut out = new OutPut(); Cpu cpu = new Cpu(); System.out.println(in.getInt()); } public void run() throws IOException { cpu.reset(); cpu.setMDR(mem.read(cpu.getMAR())); cpu.fetch2(); while (!cpu.stop()) { cpu.decode(); if (cpu.OutFlag()) OutPut.display(mem.read(cpu.getMAR())); if (cpu.InFlag()) mem.write(cpu.getMDR(),in.getInt()); if (cpu.StoreFlag()) { mem.write(cpu.getMAR(),in.getInt()); cpu.getMDR(); } else { cpu.setMDR(mem.read(cpu.getMAR())); cpu.execute(); cpu.fetch(); cpu.setMDR(mem.read(cpu.getMAR())); cpu.fetch2(); } } } public void load() { mem.loadMemory(); } } Here is my Memory class: import java.io.*; import java.util.NoSuchElementException; import java.util.Scanner; class Memory{ private MemEl[] memArray; private int size; private int[] mem; public Memory(int s) {size = s; memArray = new MemEl[s]; for(int i = 0; i < s; i++) memArray[i] = new MemEl(); } public void write (int loc,int val) {if (loc >=0 && loc < size) memArray[loc].write(val); else System.out.println("Index Not in Domain"); } public int read (int loc) {return memArray[loc].read(); } public void dump() { for(int i = 0; i < size; i++) if(i%1 == 0) System.out.println(memArray[i].read()); else System.out.print(memArray[i].read()); } public void writeTo(int location, int value) { mem[location] = value; } public int readFrom(int location) { return mem[location]; } public int size() { return mem.length; } public void loadMemory() { this.write(0, 799); this.write(1, 798); this.write(2, 198); this.write(3, 499); this.write(4, 1008); this.write(5, 1108); this.write(6, 899); this.write(7, 909); this.write(8, 898); this.write(9, 0000); } public void loadFromFile(String filename){ try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); String read=null; int towrite=0; int l=0; do{ try{ read=br.readLine(); towrite = Integer.parseInt(read); }catch(Exception e){ } this.write(l, towrite); l++; }while(l<100); }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Here is my Test class: public class Test{ public static void main(String[] args) throws java.io.IOException { Compiler compiler = new Compiler(); compiler.compile("program.txt"); } }

    Read the article

  • How can I make the C# compiler infer these type parameters automatically?

    - by John Feminella
    I have some code that looks like the following. First I have some domain classes and some special comparators for them. public class Fruit { public int Calories { get; set; } public string Name { get; set; } } public class FruitEqualityComparer : IEqualityComparer<Fruit> { // ... } public class BasketEqualityComparer : IEqualityComparer<IEnumerable<Fruit>> { // ... } Next, I have a helper class called ConstraintChecker. It has a simple BaseEquals method that makes sure some simple base cases are considered: public static class ConstraintChecker { public static bool BaseEquals(T lhs, T rhs) { bool sameObject = l == r; bool leftNull = l == null; bool rightNull = r == null; return sameObject && !leftNull && !rightNull; } There's also a SemanticEquals method which is just a BaseEquals check and a comparator function that you specify. public static bool SemanticEquals<T>(T lhs, T rhs, Func<T, T, bool> f) { return BaseEquals(lhs, rhs) && f(lhs, rhs); } And finally there's a SemanticSequenceEquals method which accepts two IEnumerable<T> instances to compare, and an IEqualityComparer instance that will get called on each pair of elements in the list via Enumerable.SequenceEquals. public static bool SemanticSequenceEquals<T, U, V>(U lhs, U rhs, V comparator) where U : IEnumerable<T> where V : IEqualityComparer<T> { return SemanticEquals(lhs, rhs, (l, r) => lhs.SequenceEqual(rhs, comparator)); } } // end of ConstraintChecker The point of SemanticSequenceEquals is that you don't have to define two comparators whenever you want to compare both IEnumerable<T> and T instances; now you can just specify an IEqualityComparer<T> and it will also handle lists when you invoke SemanticSequenceEquals. So I could get rid of the BasketEqualityComparer class, which would be nice. But there's a problem. The C# compiler can't figure out the types involved when you invoke SemanticSequenceEquals: return ConstraintChecker.SemanticSequenceEquals(lhs, rhs, new FruitEqualityComparer()); If I specify them explicitly, it works: return ConstraintChecker.SemanticSequenceEquals< Fruit, IEnumerable<Fruit>, IEqualityComparer<Fruit> > (lhs, rhs, new FruitEqualityComparer()); What can I change here so that I don't have to write the type parameters explicitly?

    Read the article

  • What do I need to know to design a language and write a interpreter for it?

    - by alFReD NSH
    I know this question has been asked and even there are thousands of books and articles about it. But the problem is that there are too many, and I don't know are they good enough, I have to design a language and write a interpreter for it. The base language is javascript (using nodejs) but it's ok if the compiler was written in another language that I can use from node. I had done a research about compiler compilers in JS, there is jison (Bison implementaion in JS), waxeye, peg.js. I decided to give jison a try, due to the popularity and its being used by coffee script, so it should be able to cover my language too. The grammar definition syntax is similar to bison. But when I tried read the bison manual it seemed very hard to understand for me. And I think it's because I don't know a lot of things about what I'm doing. Like I don't what is formal language theory. I am experienced in Javascript (I'm more talented in JS than most average programmers). And also know basic C and C++ (not much experience but can write a working code for basic things). I haven't had any formal education, so I may not be familiar with some software engineering and computer science principles. Though everyday I try to grasp a lot of articles and improve. So I'm asking if you know any good book or article that can help me. Please also write why the resource you're suggesting is good. --update-- The language I'm trying to create, is not really complicated. All it has is expressions (with or without units), comparisons and logical operators. There are no functions, loops, ... The goal is to create a language that non-programmers can easily learn. And to write customized validations and calculations.

    Read the article

  • Configuring gcc compiler switches in Qt / QtCreator / QMake

    - by andand
    I recently tried to use Qt Creator 1.3.2 / Qt 4.6.2 / gcc 4.4.0 (32-bit version) on Windows 7 (64-bit) to compile an application using some of the experimental C++0x extensions and encountered the following (fatal) error: This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options. In my search for a solution, I came across this thread, and added the following to the .pro file: CXXFLAGS += -std=c++0x but that didn't seem to make a difference. So, I expect there's some tag I need to add to the .pro (project) file, but I've never messed with the gcc compiler switches in Qt / QMake / QtCreator before, and am uncertain about the proper invokation / incantation. So, my question is how do you set gcc compiler switches when using QtCreator / QMake / Qt?

    Read the article

  • How to use xcode compiler warnings to determine minimum IOS deployment target

    - by Martin Bayly
    I'm building an iOS app using Xcode 3.2.5 with the Base SDK set to iOS 4.2 I know I've used some api's from 4.0 and 4.1 but not sure about whether I actually require 4.2. According to the iOS Development Guide, "Xcode displays build warnings when it detects that your application is using a feature that’s not available in the target OS release". So I was hoping to use the compiler warnings to derive my minimum OS requirement. However, even when I set my iOS Deployment Target to iOS 3.0, I still don't get any compiler warnings. I must be doing something wrong, but not sure what? Can anyone confirm that they get compiler warnings when the iOS deployment target is less than the base SDK and the code uses base SDK functions? Or do the compiler warnings only show if you link a framework that didn't exist in the iOS deployment target version?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >