Search Results

Search found 27946 results on 1118 pages for 'output buffer empty'.

Page 70/1118 | < Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >

  • Cannot write the output to a text file in cpp program

    - by swapedoc
    I have this input file "https://code.google.com/codejam/contest/351101/dashboard/do/A-large-practice.in?cmd=GetInputFile&problem=374101&input_id=1&filename=A-large-practice.in&redownload_last=1&agent=website&csrfmiddlewaretoken=OWMxNTVmMTUyODBiYjhhN2Q2OTM3ZGJiMTNhNDkwMDF8fDEzNzIxNzI1NTE3ODAzMjA%3D" I tried to read this file :-using freopen("filename.txt",r,stdin); and then I wanted the output written to be written to another text file which I can upload in this codejam practice question for the judge. #include<iostream> #include<cstdio> using namespace std; int main() { int t,k=0,a[2000]; freopen("ab.txt","r",stdin); scanf("%d",&t); while(t--) { freopen("cb.txt","w",stdout); int c; scanf("%d",&c); int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); printf("Case #%d: ",++k); for(int i=0;i<n-1;i++) {for(int j=i+1;j<n;j++) if((a[i]+a[j])==c) {printf("%d %d\n",i+1,j+1); i=n;} } } return 0; } This is my code. Now the problem is the output file cb.txt contains only the last line of the input. I want the the whole of the output to be written to cb.txt,so what should I do.

    Read the article

  • Script tag in ASPX page is written partially (output stopped at random)

    - by Nir
    I have an aspx page where I put a script tag with .net "if" and "else". The problem is that the output gets cut at random points each time. Sometimes it's ok, sometimes I get cropped output. The code itself (Simplified example): <body id="body" runat="server"> <form id="form1" runat="server">some HTML <script type="text/javascript"> window.addEvent('domready', function() { var x = "nothing"; <% if(someCondition){%> x = "2"; <%} else {%> x = "3"; <%}%> }); </script> </form> </body> The cropped output: <body id="body" runat="server"> <form id="form1" runat="server">some HTML <script type="text/javascript"> window.addEvent('domready', function() { var x = "nothi </script> </form> </body> Does anybody have a clue?

    Read the article

  • Technique for selectively formatting data in a PowerShell pipeline and output as HTML

    - by halr9000
    Say that you want to do some fancy formatting of some tabular output from powershell, and the destination is to be html (either for a webserver, or to be sent in an email). Let's say for example that you want certain numeric values to have a different background color. Whatever. I can think of two solid programmatic ways to accomplish this: output XML and transform with XSLT, or output HTML and decorate with CSS. XSLT is probably the harder of the two (I say that because I don't know it), but from what little I recall, it has the benefit of bring able to embed the selection criteria (xpath?) for aforementioned fancy formatting. CSS on the other hand needs a helping hand. If you wanted a certain cell to be treated specially, then you would need to distinguish it from its siblings with a class, id, or something along those lines. PowerShell doesn't really have a way to do that natively, so that would mean parsing the HTML as it leaves convertto-html and adding, for example, a "emphasis" class: <td class="emphasis">32MB</td> I don't like the idea of the required text parsing, especially given that I would rather be able to somehow emphasize what needs emphasizing in Powershell before it hits HTML. Is XSLT the best way? Have suggestions for how to markup the HTML after it leaves convertto-html or ideas of a different way?

    Read the article

  • Why do I get this strange output behavior?

    - by WilliamKF
    I have the following program test.cc: #include <iostream> unsigned char bogus1[] = { // Changing # of periods (0x2e) changes output after periods. 0x2e, 0x2e, 0x2e, 0x2e }; unsigned int bogus2 = 1816; // Changing this value changes output. int main() { std::clog << bogus1; } I build it with: g++ -g -c -o test.o test.cc; g++ -static-libgcc -o test test.o Using g++ version 3.4.6 I run it through valgrind and nothing is reported wrong. However the output has two extra control characters and looks like this: .... Thats a control-X and a control-G at the end. If you change the value of bogus2 you get different control characters. If you change the number of periods in the array the issue goes away or changes. I suspect it is a memory corruption bug in the compiler or iostream package. What is going on here?

    Read the article

  • C++ UTF-8 output with ICU

    - by Isaac
    I'm struggling to get started with the C++ ICU library. I have tried to get the simplest example to work, but even that has failed. I would just like to output a UTF-8 string and then go from there. Here is what I have: #include <unicode/unistr.h> #include <unicode/ustream.h> #include <iostream> int main() { UnicodeString s = UNICODE_STRING_SIMPLE("??????"); std::cout << s << std::endl; return 0; } Here is the output: $ g++ -I/sw/include -licucore -Wall -Werror -o icu_test main.cpp $ ./icu_test пÑÐ¸Ð²ÐµÑ My terminal and font support UTF-8 and I regularly use the terminal with UTF-8. My source code is in UTF-8. I think that perhaps I somehow need to set the output stream to UTF-8 because ICU stores strings as UTF-16, but I'm really not sure and I would have thought that the operators provided by ustream.h would do that anyway. Any help would be appreciated, thank you.

    Read the article

  • IE7 and IE8: Float clearing without adding empty elements

    - by tk-421
    Hello, I'm having a problem similar to the one described here (without a resolution): http://stackoverflow.com/questions/2467745/ie7-float-and-clear-on-the-same-element The following HTML renders as intended in Firefox but not in (both) IE7 and IE8: <html> <head> <style> ul { list-style-type: none; } li { clear: both; padding: 5px; } .left { clear: left; float: left; } .middle { clear: none; float: left; } .right { clear: right; float: left; } </style> </head> <body> <ul> <li>1</li> <li class="left">2</li> <li class="right">3</li> <li class="left">4</li> <li class="middle">5</li> <li class="right">6</li> <li>7</li> </ul> </body> </html> This is a form layout, and in Firefox the results appear like: 1 2 3 4 5 6 7 That's what I'm going for. In IE7 and IE8 however, the results are: 1 2 3 5 6 4 7 [Note: I don't want to float anything to the right because I want the fields on my form to left-align correctly, without a giant space in-between the floated fields to account for the parent container's width.] Apparently I need a full clear, and can probably add an empty list-item element to the list to force clearing, but that seems like a dumb solution and sort of defeats the purpose. Any ideas? I've spent a few hours reading and trying different options without success.

    Read the article

  • how to make the vim plugin "Project" and "Mini Buffer Explorer" work together?

    - by SunLiWei
    As the title says, I need to make these plugins work together well. The mini buffer explorer just automatically opens after I open the second file(press Enter in project plugin window), then Mini Buffer Explorer opens as the third window on the top of my screen. But after I switch back to project plugin window and press Enter to open the third file, a fourth window opened! It seems project plugin can't overwrite the second file's window. Project plugin 1.4.1 Mini Buffer Explorer plugin 6.4.0

    Read the article

  • How to delete empty lines in multi-ranges in Vim

    - by Kev
    I get a text file: <p>...</p> <pre> ... ... ... ... </pre> <p>...</p> <p>...</p> <p>...</p> <pre> ... ... ... </pre> <p>...</p> Notice that: there are some empty lines between [pre]...[/pre]. I want to delete them. But, I want keep those in [ p]...[/p] The text file becomes: <p>...</p> <pre> ... ... ... ... </pre> <p>...</p> <p>...</p> <p>...</p> <pre> ... ... ... </pre> <p>...</p> I use the cmd below to located them: /<pre>\n\zs\_.\{-}\ze\n<\/pre> But I don't know what to do next! I need a one-line-cmd to do this. Any idea? Thanks! The simpler, the better! Edit: Thank you all. I just figure out how to do it with the help of my another question :g/<pre>/,/<\/pre>/s/^$\n//

    Read the article

  • Starting a process synchronously, and "streaming" the output

    - by Benjol
    I'm looking at trying to start a process from F#, wait till it's finished, but also read it's output progressively. Is this the right/best way to do it? (In my case I'm trying to execute git commands, but that is tangential to the question) let gitexecute (logger:string->unit) cmd = let procStartInfo = new ProcessStartInfo(@"C:\Program Files\Git\bin\git.exe", cmd) // Redirect to the Process.StandardOutput StreamReader. procStartInfo.RedirectStandardOutput <- true procStartInfo.UseShellExecute <- false; // Do not create the black window. procStartInfo.CreateNoWindow <- true; // Create a process, assign its ProcessStartInfo and start it let proc = new Process(); proc.StartInfo <- procStartInfo; proc.Start() |> ignore // Get the output into a string while not proc.StandardOutput.EndOfStream do proc.StandardOutput.ReadLine() |> logger What I don't understand is how the proc.Start() can return a boolean and also be asynchronous enough for me to get the output out of the while progressively. Unfortunately, I don't currently have a large enough repository - or slow enough machine, to be able to tell what order things are happening in...

    Read the article

  • clear php empty array

    - by redcoder
    i have the following array and want to get rid/remove the empty array and rearrange it in an order.can anyone help me please. Array ( [ufile] => Array ( [name] => Array ( [0] => chicken soup.jpg [1] => [2] => hot n sour sup.jpg [3] => [4] => [5] => [6] => [7] => [8] => ) [type] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => ) [tmp_name] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => ) [error] => Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 4 [4] => 4 [5] => 4 [6] => 4 [7] => 4 [8] => 4 ) [size] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 ) ) )

    Read the article

  • After mysql_query, no result output

    - by Jerry
    I have a simple mysql_query() update command to update mysql. When a user submits my form, it will jump to an update page to update the data. The problem is that there's supposed to be some data shown after the update, but it comes out blank. My form <form id="form1" method="POST" action="scheduleUpdate.php" > <select name=std1> <option>AA</option> <option>BB</option> <option>CC</option> </select> <select name=std2> <option>DD</option> <option>EE</option> <option>FF</option> </select> .......//more drop down menu but the name is std3..std4..etc... ....... </form> scheduleUpdate.php //$i is the value posted from my main app to tell me how many std we have for($k=0;$k<$i;$k++){ $std=$_POST['std'.$k]; //if i remove the updateQuery, the html will output.I know the query is the problem but i //couldn't fix it.. $updateQuery=mysql_query("UPDATE board SET student='$std' WHERE badStudent='$std' or goodStudent='$std'",$connection); //no output below this line at all if($updateQuery){ DIE('mysql Error:'+mysql_error()); } } // I have bunch of HTML here....but no output at all!!!! MySQL will be updated after I hit submit, but it doesn't shown any HTML.

    Read the article

  • Shell Scripting: Generating output file name in script and then writing to it

    - by NewShellScripter
    Hello, I have a shell script where a user passes different sizes as command line arguments. For each of those sizes, I want to perform some task, then save the output of that task into a .txt file with the size in the name. How can I take the command line passed and make that part of a stringname for the output file? I save the output file in a directory specified by another command line argument. Perhaps an example will clear it up. In the foor lop, the i value represents the command line argument I need to use, but $$i doesnt work. ./runMe arg1 arg2 outputDir [size1 size2 size3...] for ((i=4; i<$#; i++ )) do ping -s $$i google.com >> $outputDir/$$iresults.txt done I need to know how to build the $outputDir/$$iresults.txt string. Also, the ping -s $$i doesnt work. Its like I need two levels of replacement. I need to replace the $[$i] inner $i with the value in the loop, like 4 for ex, making it $4. Then replace $4 with the 4th command line argument! Any help would be greatly appreciated. Thanks!

    Read the article

  • Elegant ways to print out a bunch of instance attributes in python 2.6?

    - by wds
    First some background. I'm parsing a simple file format, and wish to re-use the results in python code later, so I made a very simple class hierarchy and wrote the parser to construct objects from the original records in the text files I'm working from. At the same time I'd like to load the data into a legacy database, the loader files for which take a simple tab-separated format. The most straightforward way would be to just do something like: print "%s\t%s\t....".format(record.id, record.attr1, len(record.attr1), ...) Because there are so many columns to print out though, I thought I'd use the Template class to make it a bit easier to see what's what, i.e.: templ = Template("$id\t$attr1\t$attr1_len\t...") And I figured I could just use the record in place of the map used by a substitute call, with some additional keywords for derived values: print templ.substitute(record, attr1_len=len(record.attr1), ...) Unfortunately this fails, complaining that the record instance does not have an attribute __getitem__. So my question is twofold: do I need to implement __getitem__ and if so how? is there a more elegant way for something like this where you just need to output a bunch of attributes you already know the name for?

    Read the article

  • The Incremental Architect&rsquo;s Napkin - #5 - Design functions for extensibility and readability

    - by Ralf Westphal
    Originally posted on: http://geekswithblogs.net/theArchitectsNapkin/archive/2014/08/24/the-incremental-architectrsquos-napkin---5---design-functions-for.aspx The functionality of programs is entered via Entry Points. So what we´re talking about when designing software is a bunch of functions handling the requests represented by and flowing in through those Entry Points. Designing software thus consists of at least three phases: Analyzing the requirements to find the Entry Points and their signatures Designing the functionality to be executed when those Entry Points get triggered Implementing the functionality according to the design aka coding I presume, you´re familiar with phase 1 in some way. And I guess you´re proficient in implementing functionality in some programming language. But in my experience developers in general are not experienced in going through an explicit phase 2. “Designing functionality? What´s that supposed to mean?” you might already have thought. Here´s my definition: To design functionality (or functional design for short) means thinking about… well, functions. You find a solution for what´s supposed to happen when an Entry Point gets triggered in terms of functions. A conceptual solution that is, because those functions only exist in your head (or on paper) during this phase. But you may have guess that, because it´s “design” not “coding”. And here is, what functional design is not: It´s not about logic. Logic is expressions (e.g. +, -, && etc.) and control statements (e.g. if, switch, for, while etc.). Also I consider calling external APIs as logic. It´s equally basic. It´s what code needs to do in order to deliver some functionality or quality. Logic is what´s doing that needs to be done by software. Transformations are either done through expressions or API-calls. And then there is alternative control flow depending on the result of some expression. Basically it´s just jumps in Assembler, sometimes to go forward (if, switch), sometimes to go backward (for, while, do). But calling your own function is not logic. It´s not necessary to produce any outcome. Functionality is not enhanced by adding functions (subroutine calls) to your code. Nor is quality increased by adding functions. No performance gain, no higher scalability etc. through functions. Functions are not relevant to functionality. Strange, isn´t it. What they are important for is security of investment. By introducing functions into our code we can become more productive (re-use) and can increase evolvability (higher unterstandability, easier to keep code consistent). That´s no small feat, however. Evolvable code can hardly be overestimated. That´s why to me functional design is so important. It´s at the core of software development. To sum this up: Functional design is on a level of abstraction above (!) logical design or algorithmic design. Functional design is only done until you get to a point where each function is so simple you are very confident you can easily code it. Functional design an logical design (which mostly is coding, but can also be done using pseudo code or flow charts) are complementary. Software needs both. If you start coding right away you end up in a tangled mess very quickly. Then you need back out through refactoring. Functional design on the other hand is bloodless without actual code. It´s just a theory with no experiments to prove it. But how to do functional design? An example of functional design Let´s assume a program to de-duplicate strings. The user enters a number of strings separated by commas, e.g. a, b, a, c, d, b, e, c, a. And the program is supposed to clear this list of all doubles, e.g. a, b, c, d, e. There is only one Entry Point to this program: the user triggers the de-duplication by starting the program with the string list on the command line C:\>deduplicate "a, b, a, c, d, b, e, c, a" a, b, c, d, e …or by clicking on a GUI button. This leads to the Entry Point function to get called. It´s the program´s main function in case of the batch version or a button click event handler in the GUI version. That´s the physical Entry Point so to speak. It´s inevitable. What then happens is a three step process: Transform the input data from the user into a request. Call the request handler. Transform the output of the request handler into a tangible result for the user. Or to phrase it a bit more generally: Accept input. Transform input into output. Present output. This does not mean any of these steps requires a lot of effort. Maybe it´s just one line of code to accomplish it. Nevertheless it´s a distinct step in doing the processing behind an Entry Point. Call it an aspect or a responsibility - and you will realize it most likely deserves a function of its own to satisfy the Single Responsibility Principle (SRP). Interestingly the above list of steps is already functional design. There is no logic, but nevertheless the solution is described - albeit on a higher level of abstraction than you might have done yourself. But it´s still on a meta-level. The application to the domain at hand is easy, though: Accept string list from command line De-duplicate Present de-duplicated strings on standard output And this concrete list of processing steps can easily be transformed into code:static void Main(string[] args) { var input = Accept_string_list(args); var output = Deduplicate(input); Present_deduplicated_string_list(output); } Instead of a big problem there are three much smaller problems now. If you think each of those is trivial to implement, then go for it. You can stop the functional design at this point. But maybe, just maybe, you´re not so sure how to go about with the de-duplication for example. Then just implement what´s easy right now, e.g.private static string Accept_string_list(string[] args) { return args[0]; } private static void Present_deduplicated_string_list( string[] output) { var line = string.Join(", ", output); Console.WriteLine(line); } Accept_string_list() contains logic in the form of an API-call. Present_deduplicated_string_list() contains logic in the form of an expression and an API-call. And then repeat the functional design for the remaining processing step. What´s left is the domain logic: de-duplicating a list of strings. How should that be done? Without any logic at our disposal during functional design you´re left with just functions. So which functions could make up the de-duplication? Here´s a suggestion: De-duplicate Parse the input string into a true list of strings. Register each string in a dictionary/map/set. That way duplicates get cast away. Transform the data structure into a list of unique strings. Processing step 2 obviously was the core of the solution. That´s where real creativity was needed. That´s the core of the domain. But now after this refinement the implementation of each step is easy again:private static string[] Parse_string_list(string input) { return input.Split(',') .Select(s => s.Trim()) .ToArray(); } private static Dictionary<string,object> Compile_unique_strings(string[] strings) { return strings.Aggregate( new Dictionary<string, object>(), (agg, s) => { agg[s] = null; return agg; }); } private static string[] Serialize_unique_strings( Dictionary<string,object> dict) { return dict.Keys.ToArray(); } With these three additional functions Main() now looks like this:static void Main(string[] args) { var input = Accept_string_list(args); var strings = Parse_string_list(input); var dict = Compile_unique_strings(strings); var output = Serialize_unique_strings(dict); Present_deduplicated_string_list(output); } I think that´s very understandable code: just read it from top to bottom and you know how the solution to the problem works. It´s a mirror image of the initial design: Accept string list from command line Parse the input string into a true list of strings. Register each string in a dictionary/map/set. That way duplicates get cast away. Transform the data structure into a list of unique strings. Present de-duplicated strings on standard output You can even re-generate the design by just looking at the code. Code and functional design thus are always in sync - if you follow some simple rules. But about that later. And as a bonus: all the functions making up the process are small - which means easy to understand, too. So much for an initial concrete example. Now it´s time for some theory. Because there is method to this madness ;-) The above has only scratched the surface. Introducing Flow Design Functional design starts with a given function, the Entry Point. Its goal is to describe the behavior of the program when the Entry Point is triggered using a process, not an algorithm. An algorithm consists of logic, a process on the other hand consists just of steps or stages. Each processing step transforms input into output or a side effect. Also it might access resources, e.g. a printer, a database, or just memory. Processing steps thus can rely on state of some sort. This is different from Functional Programming, where functions are supposed to not be stateful and not cause side effects.[1] In its simplest form a process can be written as a bullet point list of steps, e.g. Get data from user Output result to user Transform data Parse data Map result for output Such a compilation of steps - possibly on different levels of abstraction - often is the first artifact of functional design. It can be generated by a team in an initial design brainstorming. Next comes ordering the steps. What should happen first, what next etc.? Get data from user Parse data Transform data Map result for output Output result to user That´s great for a start into functional design. It´s better than starting to code right away on a given function using TDD. Please get me right: TDD is a valuable practice. But it can be unnecessarily hard if the scope of a functionn is too large. But how do you know beforehand without investing some thinking? And how to do this thinking in a systematic fashion? My recommendation: For any given function you´re supposed to implement first do a functional design. Then, once you´re confident you know the processing steps - which are pretty small - refine and code them using TDD. You´ll see that´s much, much easier - and leads to cleaner code right away. For more information on this approach I call “Informed TDD” read my book of the same title. Thinking before coding is smart. And writing down the solution as a bunch of functions possibly is the simplest thing you can do, I´d say. It´s more according to the KISS (Keep It Simple, Stupid) principle than returning constants or other trivial stuff TDD development often is started with. So far so good. A simple ordered list of processing steps will do to start with functional design. As shown in the above example such steps can easily be translated into functions. Moving from design to coding thus is simple. However, such a list does not scale. Processing is not always that simple to be captured in a list. And then the list is just text. Again. Like code. That means the design is lacking visuality. Textual representations need more parsing by your brain than visual representations. Plus they are limited in their “dimensionality”: text just has one dimension, it´s sequential. Alternatives and parallelism are hard to encode in text. In addition the functional design using numbered lists lacks data. It´s not visible what´s the input, output, and state of the processing steps. That´s why functional design should be done using a lightweight visual notation. No tool is necessary to draw such designs. Use pen and paper; a flipchart, a whiteboard, or even a napkin is sufficient. Visualizing processes The building block of the functional design notation is a functional unit. I mostly draw it like this: Something is done, it´s clear what goes in, it´s clear what comes out, and it´s clear what the processing step requires in terms of state or hardware. Whenever input flows into a functional unit it gets processed and output is produced and/or a side effect occurs. Flowing data is the driver of something happening. That´s why I call this approach to functional design Flow Design. It´s about data flow instead of control flow. Control flow like in algorithms is of no concern to functional design. Thinking about control flow simply is too low level. Once you start with control flow you easily get bogged down by tons of details. That´s what you want to avoid during design. Design is supposed to be quick, broad brush, abstract. It should give overview. But what about all the details? As Robert C. Martin rightly said: “Programming is abot detail”. Detail is a matter of code. Once you start coding the processing steps you designed you can worry about all the detail you want. Functional design does not eliminate all the nitty gritty. It just postpones tackling them. To me that´s also an example of the SRP. Function design has the responsibility to come up with a solution to a problem posed by a single function (Entry Point). And later coding has the responsibility to implement the solution down to the last detail (i.e. statement, API-call). TDD unfortunately mixes both responsibilities. It´s just coding - and thereby trying to find detailed implementations (green phase) plus getting the design right (refactoring). To me that´s one reason why TDD has failed to deliver on its promise for many developers. Using functional units as building blocks of functional design processes can be depicted very easily. Here´s the initial process for the example problem: For each processing step draw a functional unit and label it. Choose a verb or an “action phrase” as a label, not a noun. Functional design is about activities, not state or structure. Then make the output of an upstream step the input of a downstream step. Finally think about the data that should flow between the functional units. Write the data above the arrows connecting the functional units in the direction of the data flow. Enclose the data description in brackets. That way you can clearly see if all flows have already been specified. Empty brackets mean “no data is flowing”, but nevertheless a signal is sent. A name like “list” or “strings” in brackets describes the data content. Use lower case labels for that purpose. A name starting with an upper case letter like “String” or “Customer” on the other hand signifies a data type. If you like, you also can combine descriptions with data types by separating them with a colon, e.g. (list:string) or (strings:string[]). But these are just suggestions from my practice with Flow Design. You can do it differently, if you like. Just be sure to be consistent. Flows wired-up in this manner I call one-dimensional (1D). Each functional unit just has one input and/or one output. A functional unit without an output is possible. It´s like a black hole sucking up input without producing any output. Instead it produces side effects. A functional unit without an input, though, does make much sense. When should it start to work? What´s the trigger? That´s why in the above process even the first processing step has an input. If you like, view such 1D-flows as pipelines. Data is flowing through them from left to right. But as you can see, it´s not always the same data. It get´s transformed along its passage: (args) becomes a (list) which is turned into (strings). The Principle of Mutual Oblivion A very characteristic trait of flows put together from function units is: no functional units knows another one. They are all completely independent of each other. Functional units don´t know where their input is coming from (or even when it´s gonna arrive). They just specify a range of values they can process. And they promise a certain behavior upon input arriving. Also they don´t know where their output is going. They just produce it in their own time independent of other functional units. That means at least conceptually all functional units work in parallel. Functional units don´t know their “deployment context”. They now nothing about the overall flow they are place in. They are just consuming input from some upstream, and producing output for some downstream. That makes functional units very easy to test. At least as long as they don´t depend on state or resources. I call this the Principle of Mutual Oblivion (PoMO). Functional units are oblivious of others as well as an overall context/purpose. They are just parts of a whole focused on a single responsibility. How the whole is built, how a larger goal is achieved, is of no concern to the single functional units. By building software in such a manner, functional design interestingly follows nature. Nature´s building blocks for organisms also follow the PoMO. The cells forming your body do not know each other. Take a nerve cell “controlling” a muscle cell for example:[2] The nerve cell does not know anything about muscle cells, let alone the specific muscel cell it is “attached to”. Likewise the muscle cell does not know anything about nerve cells, let a lone a specific nerve cell “attached to” it. Saying “the nerve cell is controlling the muscle cell” thus only makes sense when viewing both from the outside. “Control” is a concept of the whole, not of its parts. Control is created by wiring-up parts in a certain way. Both cells are mutually oblivious. Both just follow a contract. One produces Acetylcholine (ACh) as output, the other consumes ACh as input. Where the ACh is going, where it´s coming from neither cell cares about. Million years of evolution have led to this kind of division of labor. And million years of evolution have produced organism designs (DNA) which lead to the production of these different cell types (and many others) and also to their co-location. The result: the overall behavior of an organism. How and why this happened in nature is a mystery. For our software, though, it´s clear: functional and quality requirements needs to be fulfilled. So we as developers have to become “intelligent designers” of “software cells” which we put together to form a “software organism” which responds in satisfying ways to triggers from it´s environment. My bet is: If nature gets complex organisms working by following the PoMO, who are we to not apply this recipe for success to our much simpler “machines”? So my rule is: Wherever there is functionality to be delivered, because there is a clear Entry Point into software, design the functionality like nature would do it. Build it from mutually oblivious functional units. That´s what Flow Design is about. In that way it´s even universal, I´d say. Its notation can also be applied to biology: Never mind labeling the functional units with nouns. That´s ok in Flow Design. You´ll do that occassionally for functional units on a higher level of abstraction or when their purpose is close to hardware. Getting a cockroach to roam your bedroom takes 1,000,000 nerve cells (neurons). Getting the de-duplication program to do its job just takes 5 “software cells” (functional units). Both, though, follow the same basic principle. Translating functional units into code Moving from functional design to code is no rocket science. In fact it´s straightforward. There are two simple rules: Translate an input port to a function. Translate an output port either to a return statement in that function or to a function pointer visible to that function. The simplest translation of a functional unit is a function. That´s what you saw in the above example. Functions are mutually oblivious. That why Functional Programming likes them so much. It makes them composable. Which is the reason, nature works according to the PoMO. Let´s be clear about one thing: There is no dependency injection in nature. For all of an organism´s complexity no DI container is used. Behavior is the result of smooth cooperation between mutually oblivious building blocks. Functions will often be the adequate translation for the functional units in your designs. But not always. Take for example the case, where a processing step should not always produce an output. Maybe the purpose is to filter input. Here the functional unit consumes words and produces words. But it does not pass along every word flowing in. Some words are swallowed. Think of a spell checker. It probably should not check acronyms for correctness. There are too many of them. Or words with no more than two letters. Such words are called “stop words”. In the above picture the optionality of the output is signified by the astrisk outside the brackets. It means: Any number of (word) data items can flow from the functional unit for each input data item. It might be none or one or even more. This I call a stream of data. Such behavior cannot be translated into a function where output is generated with return. Because a function always needs to return a value. So the output port is translated into a function pointer or continuation which gets passed to the subroutine when called:[3]void filter_stop_words( string word, Action<string> onNoStopWord) { if (...check if not a stop word...) onNoStopWord(word); } If you want to be nitpicky you might call such a function pointer parameter an injection. And technically you´re right. Conceptually, though, it´s not an injection. Because the subroutine is not functionally dependent on the continuation. Firstly continuations are procedures, i.e. subroutines without a return type. Remember: Flow Design is about unidirectional data flow. Secondly the name of the formal parameter is chosen in a way as to not assume anything about downstream processing steps. onNoStopWord describes a situation (or event) within the functional unit only. Translating output ports into function pointers helps keeping functional units mutually oblivious in cases where output is optional or produced asynchronically. Either pass the function pointer to the function upon call. Or make it global by putting it on the encompassing class. Then it´s called an event. In C# that´s even an explicit feature.class Filter { public void filter_stop_words( string word) { if (...check if not a stop word...) onNoStopWord(word); } public event Action<string> onNoStopWord; } When to use a continuation and when to use an event dependens on how a functional unit is used in flows and how it´s packed together with others into classes. You´ll see examples further down the Flow Design road. Another example of 1D functional design Let´s see Flow Design once more in action using the visual notation. How about the famous word wrap kata? Robert C. Martin has posted a much cited solution including an extensive reasoning behind his TDD approach. So maybe you want to compare it to Flow Design. The function signature given is:string WordWrap(string text, int maxLineLength) {...} That´s not an Entry Point since we don´t see an application with an environment and users. Nevertheless it´s a function which is supposed to provide a certain functionality. The text passed in has to be reformatted. The input is a single line of arbitrary length consisting of words separated by spaces. The output should consist of one or more lines of a maximum length specified. If a word is longer than a the maximum line length it can be split in multiple parts each fitting in a line. Flow Design Let´s start by brainstorming the process to accomplish the feat of reformatting the text. What´s needed? Words need to be assembled into lines Words need to be extracted from the input text The resulting lines need to be assembled into the output text Words too long to fit in a line need to be split Does sound about right? I guess so. And it shows a kind of priority. Long words are a special case. So maybe there is a hint for an incremental design here. First let´s tackle “average words” (words not longer than a line). Here´s the Flow Design for this increment: The the first three bullet points turned into functional units with explicit data added. As the signature requires a text is transformed into another text. See the input of the first functional unit and the output of the last functional unit. In between no text flows, but words and lines. That´s good to see because thereby the domain is clearly represented in the design. The requirements are talking about words and lines and here they are. But note the asterisk! It´s not outside the brackets but inside. That means it´s not a stream of words or lines, but lists or sequences. For each text a sequence of words is output. For each sequence of words a sequence of lines is produced. The asterisk is used to abstract from the concrete implementation. Like with streams. Whether the list of words gets implemented as an array or an IEnumerable is not important during design. It´s an implementation detail. Does any processing step require further refinement? I don´t think so. They all look pretty “atomic” to me. And if not… I can always backtrack and refine a process step using functional design later once I´ve gained more insight into a sub-problem. Implementation The implementation is straightforward as you can imagine. The processing steps can all be translated into functions. Each can be tested easily and separately. Each has a focused responsibility. And the process flow becomes just a sequence of function calls: Easy to understand. It clearly states how word wrapping works - on a high level of abstraction. And it´s easy to evolve as you´ll see. Flow Design - Increment 2 So far only texts consisting of “average words” are wrapped correctly. Words not fitting in a line will result in lines too long. Wrapping long words is a feature of the requested functionality. Whether it´s there or not makes a difference to the user. To quickly get feedback I decided to first implement a solution without this feature. But now it´s time to add it to deliver the full scope. Fortunately Flow Design automatically leads to code following the Open Closed Principle (OCP). It´s easy to extend it - instead of changing well tested code. How´s that possible? Flow Design allows for extension of functionality by inserting functional units into the flow. That way existing functional units need not be changed. The data flow arrow between functional units is a natural extension point. No need to resort to the Strategy Pattern. No need to think ahead where extions might need to be made in the future. I just “phase in” the remaining processing step: Since neither Extract words nor Reformat know of their environment neither needs to be touched due to the “detour”. The new processing step accepts the output of the existing upstream step and produces data compatible with the existing downstream step. Implementation - Increment 2 A trivial implementation checking the assumption if this works does not do anything to split long words. The input is just passed on: Note how clean WordWrap() stays. The solution is easy to understand. A developer looking at this code sometime in the future, when a new feature needs to be build in, quickly sees how long words are dealt with. Compare this to Robert C. Martin´s solution:[4] How does this solution handle long words? Long words are not even part of the domain language present in the code. At least I need considerable time to understand the approach. Admittedly the Flow Design solution with the full implementation of long word splitting is longer than Robert C. Martin´s. At least it seems. Because his solution does not cover all the “word wrap situations” the Flow Design solution handles. Some lines would need to be added to be on par, I guess. But even then… Is a difference in LOC that important as long as it´s in the same ball park? I value understandability and openness for extension higher than saving on the last line of code. Simplicity is not just less code, it´s also clarity in design. But don´t take my word for it. Try Flow Design on larger problems and compare for yourself. What´s the easier, more straightforward way to clean code? And keep in mind: You ain´t seen all yet ;-) There´s more to Flow Design than described in this chapter. In closing I hope I was able to give you a impression of functional design that makes you hungry for more. To me it´s an inevitable step in software development. Jumping from requirements to code does not scale. And it leads to dirty code all to quickly. Some thought should be invested first. Where there is a clear Entry Point visible, it´s functionality should be designed using data flows. Because with data flows abstraction is possible. For more background on why that´s necessary read my blog article here. For now let me point out to you - if you haven´t already noticed - that Flow Design is a general purpose declarative language. It´s “programming by intention” (Shalloway et al.). Just write down how you think the solution should work on a high level of abstraction. This breaks down a large problem in smaller problems. And by following the PoMO the solutions to those smaller problems are independent of each other. So they are easy to test. Or you could even think about getting them implemented in parallel by different team members. Flow Design not only increases evolvability, but also helps becoming more productive. All team members can participate in functional design. This goes beyon collective code ownership. We´re talking collective design/architecture ownership. Because with Flow Design there is a common visual language to talk about functional design - which is the foundation for all other design activities.   PS: If you like what you read, consider getting my ebook “The Incremental Architekt´s Napkin”. It´s where I compile all the articles in this series for easier reading. I like the strictness of Function Programming - but I also find it quite hard to live by. And it certainly is not what millions of programmers are used to. Also to me it seems, the real world is full of state and side effects. So why give them such a bad image? That´s why functional design takes a more pragmatic approach. State and side effects are ok for processing steps - but be sure to follow the SRP. Don´t put too much of it into a single processing step. ? Image taken from www.physioweb.org ? My code samples are written in C#. C# sports typed function pointers called delegates. Action is such a function pointer type matching functions with signature void someName(T t). Other languages provide similar ways to work with functions as first class citizens - even Java now in version 8. I trust you find a way to map this detail of my translation to your favorite programming language. I know it works for Java, C++, Ruby, JavaScript, Python, Go. And if you´re using a Functional Programming language it´s of course a no brainer. ? Taken from his blog post “The Craftsman 62, The Dark Path”. ?

    Read the article

  • How can I read the verbose output from a Cmdlet in C# using Exchange Powershell

    - by mrkeith
    Environment: Exchange 2007 sp3 (2003 sp2 mixed mode) Visual Studio 2008, .Net 3.5 Hello, I'm working with an Exchange powershell move-mailbox cmdlet and have noted when I do so from the Exchange Management shell (using the Verbose switch) there is a ton of real-time information provided. To provide a little context, I'm attempting to create a UI application that moves mailboxes similarly to the Exchange Management Console but desire to support an input file and specific server/database destinations for each entry (and threading). Here's roughly what I have at present but I'm not sure if there is an event I need to register for or what... And to be clear, I desire to get this information in real-time so I may update my UI to reflect what's occurring in the move sequence for the appropriate user (pretty much like the native functionality offered in the Management Console). And in case you are wondering, the reason why I'm not content with the Management Console functionality is, I have an algorithm which I'm using to balance users depending on storage limit, Blackberry use, journaling, exception mailbox size etc which demands user be mapped to specific locations... and I do not desire to create many/several move groups for each common destination or to hunt for lists of users individually through the management console UI. I can not seem to find any good documentation or examples of how to tie into reading the verbose messages that are provided within the console using C# (I see value in being able to read this kind of information in many different scenarios). I've explored the Invoke and InvokeAsync methods and the StateChanged & DataReady events but none of these seem to provide the information (verbose comments) that I'm after. Any direction or examples that can be provided will be very appreciated! A code sample which is little more than how I would ordinarily call any other powershell command follows: // config to use ExMgmt shell, create runspace and open it RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); PSSnapInException snapInException = null; PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException); if (snapInException != null) throw snapInException; Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig); try { runspace.Open(); // create a pipeline and feed script text Pipeline pipeline = runspace.CreatePipeline(); string targetDatabase = @"myServer\myStorageGroup\myDB"; string mbxOwner = "[email protected]"; Command myMoveMailbox = new Command("Move-Mailbox", false, false); myMoveMailbox.Parameters.Add("Identity", mbxOwner); myMoveMailbox.Parameters.Add("TargetDatabase", targetDatabase); myMoveMailbox.Parameters.Add("Verbose"); myMoveMailbox.Parameters.Add("ValidateOnly"); myMoveMailbox.Parameters.Add("Confirm", false); pipeline.Commands.Add(myMoveMailbox); System.Collections.ObjectModel.Collection output = null; // these next few lines that are commented out are where I've tried // registering for events and calling asynchronously but this doesn't // seem to get me anywhere closer // //pipeline.StateChanged += new EventHandler(pipeline_StateChanged); //pipeline.Output.DataReady += new EventHandler(Output_DataReady); //pipeline.InvokeAsync(); //pipeline.Input.Close(); //return; tried these variations that are commented out but none seem to be useful output = pipeline.Invoke(); // Check for errors in the pipeline and throw an exception if necessary if (pipeline.Error != null && pipeline.Error.Count 0) { StringBuilder pipelineError = new StringBuilder(); pipelineError.AppendFormat("Error calling Test() Cmdlet. "); foreach (object item in pipeline.Error.ReadToEnd()) pipelineError.AppendFormat("{0}\n", item.ToString()); throw new Exception(pipelineError.ToString()); } foreach (PSObject psObject in output) { // blah, blah, blah // this is normally where I would read details about a particular PS command // but really pertains to a command once it finishes and has nothing to do with // the verbose messages that I'm after... since this part of the methods pertains // to the after-effects of a command having run, I'm suspecting I need to look to // the asynch invoke method but am not certain or knowing how. } } finally { runspace.Close(); } Thanks! Keith

    Read the article

  • Corrupt mercurial repository - cannot update

    - by richzilla
    Hi all, i think ive managed to corrupt one of mercurial repositories, is there anyway to recover the damage? the message i get when attempting to update the repo to my default branch is: PS C:\wco\projects\ims\code> hg up -C default abort: data/Trunk/application/models/priority_model.php.i@83dbdfb60981: no match found! when i run hg verify, i get the following report: PS C:\wco\projects\ims\code> hg verify checking changesets checking manifests crosschecking files in changesets and manifests checking files data/.buildpath.i@0: missing revlog! 0: empty or missing .buildpath .buildpath@0: daf15acb5273 in manifests not found data/.project.i@0: missing revlog! 0: empty or missing .project .project@0: e8b25997d6d1 in manifests not found Rawlings IMS/index.html@3: empty or missing copy source revlog index.html:b8b2b36a6eea Rawlings IMS/index.php@3: empty or missing copy source revlog index.php:a5f76bf232e9 Rawlings IMS/index_backup.php@3: empty or missing copy source revlog index_backup.php:a5f76bf232e9 Rawlings IMS/index_this_hold.html@3: empty or missing copy source revlog index_this_hold.html:b8b2b36a6eea Rawlings IMS/testera.php@3: empty or missing copy source revlog testera.php:6e9e3666c1bc Trunk/application/models/priority_model.php@32: 83dbdfb60981 in manifests not found data/index.html.i@0: missing revlog! 0: empty or missing index.html index.html@0: b8b2b36a6eea in manifests not found data/index.php.i@0: missing revlog! 0: empty or missing index.php index.php@0: a5f76bf232e9 in manifests not found data/index_backup.php.i@0: missing revlog! 0: empty or missing index_backup.php index_backup.php@0: a5f76bf232e9 in manifests not found data/index_this_hold.html.i@0: missing revlog! 0: empty or missing index_this_hold.html index_this_hold.html@0: b8b2b36a6eea in manifests not found data/nbproject/project.properties.i@14: missing revlog! 14: empty or missing nbproject/project.properties nbproject/project.properties@14: 1efa3074378b in manifests not found data/nbproject/project.xml.i@14: missing revlog! 14: empty or missing nbproject/project.xml nbproject/project.xml@14: 52689bf2b35a in manifests not found data/rcrawley/.buildpath.i@9: missing revlog! 9: empty or missing rcrawley/.buildpath rcrawley/.buildpath@9: 2c6411d4fcff in manifests not found data/rcrawley/.project.i@9: missing revlog! 9: empty or missing rcrawley/.project rcrawley/.project@9: cb4b1495acab in manifests not found data/rcrawley/assets/images/ajax-loader.gif.i@9: missing revlog! 9: empty or missing rcrawley/assets/images/ajax-loader.gif rcrawley/assets/images/ajax-loader.gif@9: 8ef26516c7da in manifests not found data/rcrawley/index.html.i@9: missing revlog! 9: empty or missing rcrawley/index.html rcrawley/index.html@9: 545246299dee in manifests not found data/rcrawley/index.php.i@9: missing revlog! 9: empty or missing rcrawley/index.php rcrawley/index.php@9: 66eac798ed6d in manifests not found data/rcrawley/index_backup.php.i@9: missing revlog! 9: empty or missing rcrawley/index_backup.php rcrawley/index_backup.php@9: 93971228fbf5 in manifests not found data/rcrawley/system/index.html.i@9: missing revlog! 9: empty or missing rcrawley/system/index.html rcrawley/system/index.html@9: 17360d3b566e in manifests not found data/rcrawley/testera.php.i@9: missing revlog! 9: empty or missing rcrawley/testera.php rcrawley/testera.php@9: 7d9bd5196740 in manifests not found data/testera.php.i@0: missing revlog! 0: empty or missing testera.php testera.php@0: 6e9e3666c1bc in manifests not found 1646 files, 59 changesets, 1897 total revisions 57 integrity errors encountered! (first damaged changeset appears to be 0) since the first damaged changeset is 0, this would appear to be pretty terminal. Is there anyway around this? any help would be appreciated.

    Read the article

  • PHP $_GET and $_POST are returning empty arrays--trying to paginate SQL data

    - by George88
    I have set up the following: Database class ($db) Pagination class ($paginator) I am attempting to write a basic system to let me administrate pages. I have a page "page_manager.php" in which I include both my database class (database.php) and my pagination class (paginate.php). In my pagination class I have a function which echoes my SQL data. I've come up with a way to echo an HTML < select element with the necessary IDs, which allows me to successfully echo the corresponding results (10 per page), based on the value of the < select element. So, "1" will echo the first 10 results in the database, "2" will echo from 11-20, "3" will echo from 21-30, etc., etc.. I have added an onChange event to the < select element which will copy its value (using "this.value") to a hidden form field. I then submit this form using document.getElementById().submit(); This will then add the $_GET variable to the URL, so the URL becomes ".../?pagenumber_form=X". However, when I try to grab this value back from the URL, the $_GET['pagenumber_form'] is empty. Some code: <span style='font-family: tahoma; font-size: 10pt;'>Page #</span> <select id="page_number_selection" onchange='javascript: document.getElementById("pagenumber_form").value = this.value; document.getElementById("pagenumber").submit();'> <?php for($i = 1; $i <= $this->num_pages; $i++) echo"<option id='" . $i . "'>" . $i . "</option>"; ?> </select> <form name="pagenumber" id="pagenumber" action="" method="get"> <input type="text" name="pagenumber_form" id="pagenumber_form" /> </form> So, I've tried using $_POST as well, but the same thing happens. I want to use $_GET, for a couple of reasons: it's easier to see what is happening with my values and the data I'm using doesn't need to be secure. To recap: the $_GET variable is being added to the URL when I change the < select element, and the corresponding value gets added to the URL as: ".../?pagenumber_form=X", but when I try to use the value in PHP, for example... $page_number = $_GET['pagenumber_form']; ... I get a NULL value. :-( Can anybody help me out please? Thank you. EDIT: I've just made a discovery. If I move my print_r($_GET) to my main index page, then the superglobals are returning as expected. My site structure is like this: index.php - JavaScript buttons use AJAX HTTP requests to include the "responseText" as the .innerHTML of my main < div . The "responseText" is the contents the page itself, in this case page_manager.php, which in turn includes pagination.php. So in other words, my site is built from PHP includes, which doesn't seem to be compatible with HTTP superglobals. Any idea how I can get around this problem? Thank you :-).

    Read the article

  • XSL testing empty strings with <xsl:if> and sorting

    - by AdRock
    I am having trouble with a template that has to check 3 different nodes and if they are not empty, print the data I am using for each node then doing the output but it is not printing anything. It is like the test returns zero. I have selected the parent node of each node i want to check the length on as the template match but it still doesn't work. Another thing, how do i sort the list using . I tried using this but i get an error about loading the stylesheet. If i take out the sort it works <xsl:template match="folktask/member"> <xsl:if test="user/account/userlevel='3'"> <xsl:sort select="festival/event/datefrom"/> <div class="userdiv"> <xsl:apply-templates select="user"/> <xsl:apply-templates select="festival"/> </div> </xsl:if> </xsl:template> <xsl:template match="festival"> <xsl:apply-templates select="contact"/> </xsl:template> This should hopefully finish all my stylesheets. This is the template I am calling <xsl:template match="contact"> <xsl:if test="string-length(contelephone)!=0"> <div class="small bold">TELEPHONE:</div> <div class="large"> <xsl:value-of select="contelephone/." /> </div> </xsl:if> <xsl:if test="string-length(conmobile)!=0"> <div class="small bold">MOBILE:</div> <div class="large"> <xsl:value-of select="conmobile/." /> </div> </xsl:if> <xsl:if test="string-length(fax)!=0"> <div class="small bold">FAX:</div> <div class="large"> <xsl:value-of select="fax/." /> </div> </xsl:if> </xsl:template> and a section of my xml. If you need me to edit my post so you can see the full code i will but the rest works fine. <folktask> <member> <user id="4"> <personal> <name>Connor Lawson</name> <sex>Male</sex> <address1>12 Ash Way</address1> <address2></address2> <city>Swindon</city> <county>Wiltshire</county> <postcode>SN3 6GS</postcode> <telephone>01791928119</telephone> <mobile>07338695664</mobile> <email>[email protected]</email> </personal> <account> <username>iTuneStinker</username> <password>3a1f5fda21a07bfff20c41272bae7192</password> <userlevel>3</userlevel> <signupdate>2010-03-26T09:23:50</signupdate> </account> </user> <festival id="1"> <event> <eventname>Oxford Folk Festival</eventname> <url>http://www.oxfordfolkfestival.com/</url> <datefrom>2010-04-07</datefrom> <dateto>2010-04-09</dateto> <location>Oxford</location> <eventpostcode>OX1 9BE</eventpostcode> <coords> <lat>51.735640</lat> <lng>-1.276136</lng> </coords> </event> <contact> <conname>Stuart Vincent</conname> <conaddress1>P.O. Box 642</conaddress1> <conaddress2></conaddress2> <concity>Oxford</concity> <concounty>Bedfordshire</concounty> <conpostcode>OX1 3BY</conpostcode> <contelephone>01865 79073</contelephone> <conmobile></conmobile> <fax></fax> <conemail>[email protected]</conemail> </contact> </festival> </member> </folktask>

    Read the article

  • JTabbedPane: only first tab is drawn, the second is always empty (newbie Q)

    - by paul
    I created a very simple JTabbedPane by first creating an empty JTabbedPane object, then 2 JPanels that I later add. Each JPanel is holding a object that extends JButton and implements MouseListener. Each of these holds a different image loaded from a file; the image is held locally as a buffered image and as an image icon, etc., all of which works great. The point of all that is to allow resizing of the image when the button is resized (using getscaledinstance()), because the panel is resized, because the JTabbedPane is resized, etc., within the JFrame that holds everything. I override paintComponent() to accomplish this in the class that extends JButton. I am using MigLayout Manager, and all is well on that front controlling layout constraints, growing, filling, initial sizes, preferred sizes, etc. The images the buttons hold are of different sizes and proportions, but this caused no trouble before. Up until 2 days ago everything worked fairly well. I made some changes trying to tweak some resizing issues as I was picking up MigLayout manager. At the time I was playing around with setting various min, max, and preferred sizes using the methods provided for by the components, not the layout manager. I also fooled a bit with pack(), validate(), visible(), opaque() etc., and yes I read the article about Swing and AWT painting here: http://java.sun.com/products/jfc/tsc/articles/painting/ , and I switched to relying more and more on MigLayout. On an unrelated note, it appears JFrame's do not honor maxsize? Somehow, today, with and without using any of these methods provided by swing, with or without using MigLayout manager to handle some of these matters instead, I now have a JTabbedPane that correctly displays the FIRST JPanel I add, but NOT THE SECOND JPanel--which, while present as a tab--does not show when selected. I have switched the order of which panel is added first, and this still holds true regardless of which JPanel I add first, telling me the JPanels are ok, and the problem is most likely in the JTabbedPane. I click on the second tab, the JTabbedPane switches, but I have what appears to be a blank button in the JPanel. A few console system-out statements reveal the following: a) that the second panel and its button are constructed b) no mouse events are being captured when I click on where the second panel and button should reside, as if it didn't exist at that point; c) when I switch to the second tab, the overrided paintComponent() method of the button within that second JPanel is never called, so it is in fact never being painted despite the tab in which it resides becoming visible; d) the JTabbpedPane getComponentCount() returns a correct value of 2 after adding the 2nd panel; e) MigLayout manager actually rocks, but I digress... I cannot now revert to my older code, and despite my best efforts to undo whatever changes caused this, I cannot fix my new problem. I've commented out everything but the most essential calls: constructors for each object--with MigLayout; add() for placing the buttons on the panels using string-arguments appropriate for MigLayout; add() for placing the panels on the JTabbedPane, also with MigLayout string arguments; setting the default op on close for the JFrame; and setting the JFrame visible. This means I do not fiddle with optimization settings, double buffering settings, opaque settings, but leave them as default, and still, no fix; the second panel will not show itself. Each panel, I should add, when it is the first to be loaded, works fine, again re-affirming that the panels and buttons are themselves ok. Here is part of what I am doing: //Note: BuildaButton is a class that merely constructs my instances File f = new File("/foo.jpg"); button1 = new BuildaButton().BuildaButton(f).buildfoo1Button(); f = new File("/foo2.jpg"); button2 = new BuildaButton().BuildaButton(f).buildfoo2Button(); MigLayout ml = new MigLayout("wrap 1", "[fill, grow]0[fill, grow]", "[fill, grow]0[fill, grow]"); MigLayout ml2 = new MigLayout("wrap 2", "[fill, grow]5[fill, grow]", "[fill, grow]0[fill, grow]"); foo1panel = new JPanel(ml); foo1panel.add(button1, "w 234:945:, h 200:807:"); foo2panel = new JPanel(ml); foo2panel.add(button2, "w 186:752:, h 200:807:"); tabs.add("foo1", foo1panel); tabs.add("foo2", foo2panel); System.out.println("contents of tabs: " + tabs.getComponentCount() + " elements"); mainframe.setLayout(ml2); mainframe.setMinimumSize(new Dimension(850,800)); mainframe.add(tabs, "w 600:800:, h 780:780:"); //controlpanel is a still blank jpanel that holds nothing--it is a space holder for now & will be utilized mainframe.add(controlpanel, "w 200:200:200, h 780:780:"); mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.setVisible(true); Thank you in advance for any help you can give.

    Read the article

  • SimpleXMLElement empty object

    - by Mike
    Hi, I am trying to parse an xml file using XmlReader but although I am getting a return from the xml file for the (commission) node for some reason I am getting an empty SimpleXMLElement Object returned as well. I don't know if its something to do with while loop,switch or something I missed in the parse setup. This is the xml file I am trying to read from, as you can see there is only 1 result returned: <?xml version="1.0" encoding="UTF-8"?> <cj-api> <commissions total-matched="1"> <commission> <action-status> new </action-status> <action-type> lead </action-type> <aid> 10730981 </aid> <commission-id> 1021015513 </commission-id> <country> </country> <event-date> 2010-05-08T08:08:55-0700 </event-date> <locking-date> 2010-06-10 </locking-date> <order-id> 345007 </order-id> <original> true </original> <original-action-id> 787692438 </original-action-id> <posting-date> 2010-05-08T10:01:22-0700 </posting-date> <website-id> 3201921 </website-id> <cid> 2815954 </cid> <advertiser-name> SPS EurosportBET </advertiser-name> <commission-amount> 0 </commission-amount> <order-discount> 0 </order-discount> <sid> 0 </sid> <sale-amount> 0 </sale-amount> </commission> </commissions> </cj-api> This is my parser: <?php // read $response (xml feed) $file = "datafeed.xml"; $xml = new XMLReader; $xml->open($file); // loop to read in data while ($xml->read()) { switch ($xml->name) { // find the parent node for each commission payment case 'commission': // initalise xml parser $dom = new DomDocument(); $dom_node = $xml ->expand(); $element = $dom->appendChild($dom_node); $dom_string = $dom->saveXML($element); $commission = new SimpleXMLElement($dom_string); // read in data $action_status = $commission->{'action-status'}; $action_type = $commission->{'action-type'}; $aid = $commission->{'aid'}; $commission_id = $commission->{'commission-id'}; $country = $commission->{'country'}; $event_date = $commission->{'event-date'}; $locking_date = $commission->{'locking-date'}; $order_id = $commission->{'order-id'}; $original = $commission->{'original'}; $original_action_id = $commission->{'original_action-id'}; $posting_date = $commission->{'posting-date'}; $website_id = $commission->{'website-id'}; $cid = $commission->{'cid'}; $advertiser_name = $commission->{'advertiser-name'}; $commission_amount = $commission->{'commission-amount'}; $order_discount = $commission->{'order-discount'}; $sid = $commission->{'sid'}; $sale_amount = $commission->{'sale-amount'}; print_r($aid); break; } } ?> The result is : SimpleXMLElement Object ( [0] => 10730981 ) SimpleXMLElement Object ( ) Why is it returning the second object: SimpleXMLElement Object ( ) and what do I need to do correct it? Thanks.

    Read the article

  • XForms and multiple inputs for same model tag

    - by iHeartGreek
    Hi! I apologize ahead of time if I am not asking this properly.. it is hard to put into words what I am asking.. I have XForms model such as: <file> <criteria> <criterion></criterion> </criteria> </file> I want to have multiple input text boxes that create a new criterion tag. user interface such as: <xf:input ref="/file/criteria/criterion" model="select_data"> <xf:label>Select</xf:label> </xf:input> <xf:input ref="/file/criteria/criterion" model="select_data"> <xf:label>Select</xf:label> </xf:input> <xf:input ref="/file/criteria/criterion" model="select_data"> <xf:label>Select</xf:label> </xf:input> And I would like the XML output to look like this (once user has entered in info): <file> <criteria> <criterion>AAA</criterion> <criterion>BBB</criterion> <criterion>CCC</criterion> </criteria> </file> The way I have it doesn't work, as it sees the 3 input fields to be referring all to the same criterion tag. How do I differentiate? Thanks! I hope that made some sense! BEGIN FIRST EDIT Thanks for the responses for the basic text box! However, I now need to do this with a listbox. But for the life of me, I can't figure out how. I read somewhere to use with the xforms:select and deselect events.. but I didn't know where to place them, and the places I tried gave me very weird behaviour. I am currently implementing the following: <xf:select ref="instance('criteria_data')/criteria/criterion" selection="" appearance="compact" > <xf:label>Choose criteria</xf:label> <xf:itemset nodeset="instance('criteria_choices')/choice"> <xf:label ref="@label"></xf:label> <xf:value ref="."></xf:value> </xf:itemset> </xf:select> However when multiple choices are submitted, all selection values are inserted into the same node, separated by spaces. For example: If AAA and BBB and FFF were selected from listbox, it would result in the following XML: <criterion>AAA BBB FFF</criterion> How do I change my code to have each selection be in a separate node? i.e. I want it to look like this: <criterion>AAA</criterion> <criterion>BBB</criterion> <criterion>FFF</criterion> Thanks! END FIRST EDIT BEGIN SECOND EDIT: For the listboxes (ie xf:select appearance="compact") I ended up allowing the spaces to occur in the same node and then just transformed that xml using xsl to generate a properly formatted new xml doc (with separate individual nodes). Unfortunately, I did not find a less cumbersome solution by inserting them originally into separate nodes. The selected answer works very well for text boxes however, hence why I selected it as the answer. END SECOND EDIT

    Read the article

  • WTSQuerySessionInformation returning empty strings

    - by Benj
    I've written a program which should query the Terminal Services API and print out some state information about the sessions running on a terminal services box. I'm using the WTSQuerySessionInformation function to do this and it's returning some data but most of the data seems to be missing... Does anyone know why? Here's my program: void WTSGetString( HANDLE serverHandle, DWORD sessionid, WTS_INFO_CLASS command, wchar_t* commandStr) { DWORD bytesReturned = 0; LPTSTR pData = NULL; if (WTSQuerySessionInformation(serverHandle, sessionid, command, &pData, &bytesReturned)) { wprintf(L"\tWTSQuerySessionInformationW - session %d - %s returned \"%s\"\n", sessionid, commandStr, pData); } else { wprintf(L"\tWTSQuerySessionInformationW - session %d - %s failed - error=%d - ", sessionid, commandStr, GetLastError()); printLastError(NULL, GetLastError()); } WTSFreeMemory(pData); } void ExtractFromWTS( HANDLE serverHandle, DWORD sessionid ) { WTSGetString(serverHandle, sessionid, WTSInitialProgram, L"WTSInitialProgram"); WTSGetString(serverHandle, sessionid, WTSApplicationName, L"WTSApplicationName"); WTSGetString(serverHandle, sessionid, WTSWorkingDirectory, L"WTSWorkingDirectory"); WTSGetString(serverHandle, sessionid, WTSOEMId, L"WTSOEMId"); WTSGetString(serverHandle, sessionid, WTSSessionId, L"WTSSessionId"); WTSGetString(serverHandle, sessionid, WTSUserName, L"WTSUserName"); WTSGetString(serverHandle, sessionid, WTSWinStationName, L"WTSWinStationName"); WTSGetString(serverHandle, sessionid, WTSDomainName, L"WTSDomainName"); WTSGetString(serverHandle, sessionid, WTSConnectState, L"WTSConnectState"); WTSGetString(serverHandle, sessionid, WTSClientBuildNumber, L"WTSClientBuildNumber"); WTSGetString(serverHandle, sessionid, WTSClientName, L"WTSClientName"); WTSGetString(serverHandle, sessionid, WTSClientDirectory, L"WTSClientDirectory"); WTSGetString(serverHandle, sessionid, WTSClientProductId, L"WTSClientProductId"); WTSGetString(serverHandle, sessionid, WTSClientHardwareId, L"WTSClientHardwareId"); WTSGetString(serverHandle, sessionid, WTSClientAddress, L"WTSClientAddress"); WTSGetString(serverHandle, sessionid, WTSClientDisplay, L"WTSClientDisplay"); WTSGetString(serverHandle, sessionid, WTSClientProtocolType, L"WTSClientProtocolType"); } int _tmain(int argc, _TCHAR* argv[]) { PWTS_SESSION_INFOW ppSessionInfo = 0; DWORD pCount; if(!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &ppSessionInfo, &pCount)) { printLastError(L"WTSEnumerateSessions", GetLastError()); return 1; } wprintf(L"%d WTS sessions found on host\n", pCount); for (unsigned int i=0; i<pCount; i++) { wprintf(L"> session=%d, stationName = %s\n", ppSessionInfo[i].SessionId, ppSessionInfo[i].pWinStationName); ExtractFromWTS(WTS_CURRENT_SERVER_HANDLE, ppSessionInfo[i].SessionId); LPWSTR sessionstr = new wchar_t[200]; wsprintf(sessionstr, L"%d", ppSessionInfo[i].SessionId); } return 0; } And here's the output: C:\Users\Administrator\Desktop>ObtainWTSStartShell.exe empserver1 4 WTS sessions found on host > session=0, stationName = Services WTSQuerySessionInformationW - session 0 - WTSInitialProgram failed - error=87 - The paramete r is incorrect. WTSQuerySessionInformationW - session 0 - WTSApplicationName failed - error=87 - The paramet er is incorrect. WTSQuerySessionInformationW - session 0 - WTSWorkingDirectory returned "" WTSQuerySessionInformationW - session 0 - WTSOEMId returned "" WTSQuerySessionInformationW - session 0 - WTSSessionId returned "" WTSQuerySessionInformationW - session 0 - WTSUserName returned "" WTSQuerySessionInformationW - session 0 - WTSWinStationName returned "Services" WTSQuerySessionInformationW - session 0 - WTSDomainName returned "" WTSQuerySessionInformationW - session 0 - WTSConnectState returned "?" WTSQuerySessionInformationW - session 0 - WTSClientBuildNumber returned "" WTSQuerySessionInformationW - session 0 - WTSClientName returned "" WTSQuerySessionInformationW - session 0 - WTSClientDirectory returned "" WTSQuerySessionInformationW - session 0 - WTSClientProductId returned "" WTSQuerySessionInformationW - session 0 - WTSClientHardwareId returned "" WTSQuerySessionInformationW - session 0 - WTSClientAddress returned "" WTSQuerySessionInformationW - session 0 - WTSClientDisplay returned "" WTSQuerySessionInformationW - session 0 - WTSClientProtocolType returned "" GetShellProcessNameFromUserPolicy - Error: Unable to open policy key - returned [2] GetShellProcessName succeseded - explorer.exe > session=1, stationName = Console WTSQuerySessionInformationW - session 1 - WTSInitialProgram returned "" WTSQuerySessionInformationW - session 1 - WTSApplicationName returned "" WTSQuerySessionInformationW - session 1 - WTSWorkingDirectory returned "" WTSQuerySessionInformationW - session 1 - WTSOEMId returned "" WTSQuerySessionInformationW - session 1 - WTSSessionId returned "?" WTSQuerySessionInformationW - session 1 - WTSUserName returned "" WTSQuerySessionInformationW - session 1 - WTSWinStationName returned "Console" WTSQuerySessionInformationW - session 1 - WTSDomainName returned "" WTSQuerySessionInformationW - session 1 - WTSConnectState returned "?" WTSQuerySessionInformationW - session 1 - WTSClientBuildNumber returned "" WTSQuerySessionInformationW - session 1 - WTSClientName returned "" WTSQuerySessionInformationW - session 1 - WTSClientDirectory returned "" WTSQuerySessionInformationW - session 1 - WTSClientProductId returned "" WTSQuerySessionInformationW - session 1 - WTSClientHardwareId returned "" WTSQuerySessionInformationW - session 1 - WTSClientAddress returned "" WTSQuerySessionInformationW - session 1 - WTSClientDisplay returned "?" WTSQuerySessionInformationW - session 1 - WTSClientProtocolType returned "" GetShellProcessNameFromUserPolicy - Error: Unable to open policy key - returned [2] GetShellProcessName succeseded - explorer.exe > session=3, stationName = RDP-Tcp#0 WTSQuerySessionInformationW - session 3 - WTSInitialProgram returned "" WTSQuerySessionInformationW - session 3 - WTSApplicationName returned "" WTSQuerySessionInformationW - session 3 - WTSWorkingDirectory returned "" WTSQuerySessionInformationW - session 3 - WTSOEMId returned "" WTSQuerySessionInformationW - session 3 - WTSSessionId returned "?" WTSQuerySessionInformationW - session 3 - WTSUserName returned "Administrator" WTSQuerySessionInformationW - session 3 - WTSWinStationName returned "RDP-Tcp#0" WTSQuerySessionInformationW - session 3 - WTSDomainName returned "EMPSERVER1" WTSQuerySessionInformationW - session 3 - WTSConnectState returned "" WTSQuerySessionInformationW - session 3 - WTSClientBuildNumber returned "?" WTSQuerySessionInformationW - session 3 - WTSClientName returned "APWADEV03" WTSQuerySessionInformationW - session 3 - WTSClientDirectory returned "C:\Windows\System32\m stscax.dll" WTSQuerySessionInformationW - session 3 - WTSClientProductId returned "?" WTSQuerySessionInformationW - session 3 - WTSClientHardwareId returned "" WTSQuerySessionInformationW - session 3 - WTSClientAddress returned "?" WTSQuerySessionInformationW - session 3 - WTSClientDisplay returned "?" WTSQuerySessionInformationW - session 3 - WTSClientProtocolType returned "?" GetShellProcessNameFromUserPolicy - Error: Unable to open policy key - returned [2] GetShellProcessName succeseded - explorer.exe > session=65536, stationName = RDP-Tcp WTSQuerySessionInformationW - session 65536 - WTSInitialProgram returned "" WTSQuerySessionInformationW - session 65536 - WTSApplicationName returned "" WTSQuerySessionInformationW - session 65536 - WTSWorkingDirectory returned "" WTSQuerySessionInformationW - session 65536 - WTSOEMId returned "" WTSQuerySessionInformationW - session 65536 - WTSSessionId returned "" WTSQuerySessionInformationW - session 65536 - WTSUserName returned "" WTSQuerySessionInformationW - session 65536 - WTSWinStationName returned "RDP-Tcp" WTSQuerySessionInformationW - session 65536 - WTSDomainName returned "" WTSQuerySessionInformationW - session 65536 - WTSConnectState returned "?" WTSQuerySessionInformationW - session 65536 - WTSClientBuildNumber returned "" WTSQuerySessionInformationW - session 65536 - WTSClientName returned "" WTSQuerySessionInformationW - session 65536 - WTSClientDirectory returned "" WTSQuerySessionInformationW - session 65536 - WTSClientProductId returned "" WTSQuerySessionInformationW - session 65536 - WTSClientHardwareId returned "" WTSQuerySessionInformationW - session 65536 - WTSClientAddress returned "" WTSQuerySessionInformationW - session 65536 - WTSClientDisplay returned "" WTSQuerySessionInformationW - session 65536 - WTSClientProtocolType returned "" GetShellProcessNameFromUserPolicy - Error: Unable to open policy key - returned [2] GetShellProcessName succeseded - explorer.exe As you can see, some of the data looks valid, but not all....

    Read the article

< Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >