text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Normal 0 21 false false false X-NONE X-NONE I heard several times that high test coverage ratio, and ultimately 100% test coverage, is an illusion of quality. The underlying reason is that when a portion of code is executed by tests, it doesn’t mean that the validity of the results produced by this portion of code is verified by tests. In other words, some code can be covered by tests and still contains bugs. I totally agree with this assertion. However, I don’t agree when one claims that high test coverage ratio is an illusion of quality. I can see several major benefits resulting from high test coverage ratio. Contract + High Test Coverage Ratio = Correctness checked anyway If you apply correctly Design by Contract (DbC) high test coverage pays off. DbC means that your code contains side-effect free code whose only purpose is to check the states correctness at runtime as often as possible. If the state correctness is violated, a contract fails abruptly. To implement the DbC principle, we (the team working on NDepend) used so far my good old friend System.Diagnostics.Debug.Assert(…) and we are in the process of switching to the System.Contract API. The trick is that if contract validity verifications are performed during tests execution, then tests are failing when a contract is broken. And the higher the test coverage ratio, the more contracts are verified at test-time. By extension, one can actually consider test code dedicated to verification (I mean lines in your test like Assert.IsTrue(…)) as contracts residing outside the code itself. Also, on NDepend development, we observe that regression bugs are discovered much more often thanks to broken contracts, than thanks to broken test. It is because contracts actually live in the code, they are much more close to what code is doing than test themselves. Also contracts are more often verified than tests (imagine a contract in a loop vs. a test verification outside the loop). One technical detail is that TestDriven.NET discards Debug.Assert(…) failure windows by default and I explain here how to activate this behavior (thanks to Jamie Cansdale for the tip). Bug discovered in covered code = Easier fix When a bug is discovered in a portion of code, fixing it is easier if the potion of code is already covered by tests. Indeed, if the buggy code is already covered by at least one test, often one just needs to copy/paste this test and tweak its input to reproduce the conditions where the bug appear. This extra test is then useful both for: - Reproducing the bug at whim, to understand its conditions and fix it - Keeping verification that in the future will check that the bug won’t re-appear. Having high test coverage ratio increases the chance that most of the bug reside actually in code covered. Ultimately, 100% test coverage means that if the code contains some bugs, they are necessarily covered anyway by some tests. High coverage leads to relevant investigation Numerous times, while climbing the full coverage mountain, I stumbled on dead code or better said dead condition. Imagine that in the code below, despite plenty of tests the return statement is never covered, meaning that obj is never InAParticularState. If(obj.IsInAParticularState) { return; } It is a good hint to investigate. Very often in such situation, the investigation will lead to the fact that for some reasons, obj cannot be InAParticularState at that point. The best thing to do is then to turn the test condition into a contract. This contract asserts that obj cannot indeed be InAParticularState. Debug.Assert(!obj.IsInAParticularState, “document the reason why object cannot be InAParticularState here”); As a result: you eliminated dead code, the contract is covered by tests (and then verified at test time), the contract constitutes a documentation for future developers for something that was not obvious at first glance and that required investigations. 100% Test Coverage protects from Coverage Erosion 100% coverage ratio doesn’t happen by chance. Writing a few tests can often cover up to 80% of the tested code. However developers often have to struggle hard to reach the 100% coverage goal. By struggling hard, I mean that developers need to write non-trivial tests to cover non-mainstream scenarios. The 80/20 rule regularly applies here: these extra 20% of code to cover can require up to 80% of the time spent in writing tests. So when a class or a namespace is 100% covered it means one thing: developers worked hard to reach this 100% value. 100% coverage then becomes a requirement for future evolutions and refactoring: because the code refactored is originally 100% covered, one has to make sure that the new version of the code is also 100% covered. In other words, when code is 100% covered it is easier to prevent what I usually name coverage erosion. The phenomenon of coverage erosion happens when code gets refactored with poor care for writing new tests. Unfortunately, in real-world development shop where turn-over and urgent evolutions are the rules, coverage erosion is often a reality. It is what Jeff Atwood presented as The theory of the broken window. Basically if one develops in a clean environment, then one will struggle to keep the environment clean and avoid erosion. if one develops in a dirty environment, then one won’t even try to make the environment cleaner and the overall entropy will increase.
http://codebetter.com/patricksmacchia/2009/06/07/high-test-coverage-ratio-is-a-good-thing-anyway/
crawl-003
refinedweb
916
52.29
Hello and welcome everything, in this article we are going to make a React Native Video Player Tutorial. Simple and Easy by exploring the native Video API. In this article we won’t be using any customized controllers, However; I am leaving that Part for a later detailed guide. This one is rather a quick 5 mins example. This is how the example look like on IOS And this is how it looks on Android Environment Setup To get started as usual create a new project using Expo or React Native Cli. With both approaches, you will usually get a starting code like this. >>IMAGE', }, }); The Video component we are going to use is provided by Expo.io. And it already has the native default video controllers ready for IOS and android, so we wont be needing any extra setup for controllers. To install it use the expo cli expo install expo-av And now we are ready to get started Getting started We of course need to import the video component we have just installed import { Video } from 'expo-av'; To get a video playing on the video component, we need to add 3 props. The source, with the url or path file to the video we want to play. Plus shouldPlay prop. And style, providing the video player height and width dimensions. If you don’t set it up, you will have the video playing in the background with just the sounds playing. Finally, the shouldPlay prop with a true value, and this props plays the video once it’s ready, if it’s false or not set. The video will show a thumbnail or A poster if you set it up and wont play till you use the play button from the controllers. Notice, if you want to load a local video file from your assets use require, Like this require(‘path/to/file.extention’) To do so, add this code to your toot view <Video source={{ uri: '' }} shouldPlay style={{ width: "100%", height: "50%" }} /> Our screen will look like this As you can see, The video is shown and playing. Adding Video Player Native Controllers To add the native controllers to show on both android and ios, all we simply need to do is add the prop useNativeControls to our Video component. <Video source={{ uri: '' }} shouldPlay useNativeControls style={{ width: "100%", height: "50%" }} /> Now the Video Player looks like this And on android There you have it a simple React Native Video Player Tutorial. And you can achieve this in less than 5 minutes. That was it for this tutorial, see you in another. Take care and happy coding. I think, you are awsome man! real Life Saver, Simple Solution! 10/10 to you, man!!!
https://reactnativemaster.com/react-native-video-player-tutorial/
CC-MAIN-2020-16
refinedweb
457
78.79
Marshaling and Conversion with P/Invoke If your unmanaged function takes a string, a char*, you can call it from managed C++ by creating a char*, but you can also pass it a String* and let the framework do the conversion for you if you use P/Invoke. It Just Works interop won't convert strings for you. What's more, you can write code of your own to convert a managed type to an unmanaged type and arrange for this conversion code to be wrapped around calls into the DLL. In this column, I'll show you how to control marshaling yourself, and how P/Invoke can be useful to a C++ programmer. When you make a call from managed to unmanaged code, all the parameters you want to send to the unmanaged code are gathered up, rearranged into the right order, possibly copied or converted, possibly pinned to ensure they don't move during the call, and so on. This is called marshaling, and it's supposed to make you think about the beginning of a parade when someone prods and pushes to get all the floats lined up in order before they head out. When you call a legacy library by adding the .lib file to the linker dependencies, you get the default marshaling. If the function only takes and returns so-called blittable types, this is fine. Blittable types have an identical memory representation in managed and unmanaged code. C++ fundamental types such as int are blittable types. Strings are not. LEGACY_API bool Log(char* message, SYSTEMTIME* time) { FILE* logfile = fopen("C:\\log.txt","a"); fprintf(logfile, "%d/%d/%d - %d:%d %s \r\n", time->wYear, time->wMonth, time->wDay, time->wHour, time->wMinute, message); fclose(logfile); return true; } If you want to code along with this column, make a DLL that exposes this method, using the techniques I've shown you earlier for writing a DLL in unmanaged C++. You'll need to include windows.h. Passing a String to a Function in a DLL To call this function from Managed C++, you have two choices: IJW and P/Invoke. If you want to access it with IJW, you would add the import library (.lib) file to the linker dependencies, you would #include a header file that defines the function, and you would make sure that you passed a char* and a SYSTEMTIME* to the function call, like this: #include "windows.h" #include "legacy.h" #using <mscorlib.dll> using namespace System; int _tmain() { SYSTEMTIME st; GetLocalTime(&st); Log("Testing from Managed Code", &st); System::Console::WriteLine(S"log succeeded"); return 0; } (GetLocalTime is an SDK function that fills a SYSTEMTIME structure with the current local time.) This code works, and it's clearly managed code, but it's not using managed types. What if the string you wanted to pass to Log() was already in a System::String variable? To use IJW Interop, you must convert the String* to a char*. Here is one way to do that: String* s = new String("Testing with a heap string"); char* pChar = (char*)Marshal::StringToHGlobalAnsi(s).ToPointer(); Log(pChar, &st); That's hardly pleasant, and it's not an option for types other than strings anyway. If, instead, you use P/Invoke, you can get your strings converted automatically, so that you pass a String* to the function in your code, but a char* actually reaches the functions inside the DLL. Instead of using the header file, legacy.h, to declare the Log() function, you declare it yourself with attributes that control the marshaling. As a side effect, you no longer link to the import library because PInvoke will deal with finding and loading the DLL. The resulting code looks like this: extern "C" { [DllImport("legacy", CharSet=CharSet::Ansi)] bool Log(String* message, SYSTEMTIME* time); } The first parameter on the DllImport attribute, legacy, identifies the DLL in which the function is declared. The second parameter controls the way that strings are marshaled. You can convert the Unicode string in a System::String to an ANSI string, as in this example, or a wchar* if that's what the code in the DLL is expecting. The DllImport attribute is in the InteropServices namespace, so add a using line before the function definition: using namespace System::Runtime::InteropServices; Now you can pass a String* to the Log() function: String* s = new String("Testing with a heap string"); Log(s, &st); System::Console::WriteLine(S"log succeeded"); The DllImport attribute will ensure that s is converted from a String* type of string to a char* type of string at runtime, whenever the Log() function is called. Passing a Non-String, Non-Blittable Type You've seen in previous columns that when you pass a blittable type, such as a double, you don't need to do anything—don't even need to use PInvoke—to handle marshaling and conversion issues. When you pass a string, you add a parameter to the DllImport attribute on your declaration of the function to arrange for appropriate string marshaling behind the scenes. But what about other types, such as the SYSTEMTIME structure that is passed to Log()? Just as you could convert the String* to a char* yourself and pass it along, you can write a function to convert a System::DateTime structure to a SYSTEMTIME structure. Here's one that's really easy to read: SYSTEMTIME MakeSystemTimeFromDateTime(DateTime dt) { SYSTEMTIME st; st.wYear = dt.get_Year(); st.wMonth = dt.get_Month(); st.wDayOfWeek = dt.get_DayOfWeek(); st.wDay = dt.get_Day(); st.wHour = dt.get_Hour(); st.wMinute = dt.get_Minute(); st.wSecond = dt.get_Second(); st.wMilliseconds = dt.get_Millisecond(); return st; } (There are cleverer versions of this in existence. Because both structures actually represent the same thing, a date and time, and because that can be represented by a single number of ticks since a reference date and time, it's possible to convert from one to the other in a single line of code. It's not as readable though, so I'll present it the long-and-simple way in this column.) SYSTEMTIME is defined in winbase.h, but in a managed application you probably don't want to #include that header file. There's nothing stopping you from simply pasting the definition into your own code. It relies on typedefs such as WORD, so you have to poke around a bit and make some substitutions to get a streamlined definition: typedef struct _SYSTEMTIME { short wYear; short wMonth; short wDayOfWeek; short wDay; short wHour; short wMinute; short wSecond; short wMilliseconds; } SYSTEMTIME; Now you can write a managed main that doesn't use GetLocalTime() and that works with a DateTime. After all, your code might be passing a date that came from a DateTimePicker or other control that returns a DateTime structure, so you want to avoid working directly with a SYSTEMTIME structure. Here's the revamped main: extern "C" { [DllImport("legacy", CharSet=CharSet::Ansi)] bool Log(String* message, SYSTEMTIME* time); } int _tmain() { SYSTEMTIME st = MakeSystemTimeFromDateTime(System::DateTime::Now); String* s = new String("Testing with a heap string"); Log(s, &st); System::Console::WriteLine(S"log succeeded"); return 0; } Now the string is being converted automatically, because of the parameter passed to the DllImport attribute, and the DateTime structure is being converted by hand to a SYSTEMTIME structure just before the call. This works, though it's slightly inconvenient. If a function in a DLL is going to be called repeatedly, it's obviously more convenient to add an attribute to the function definition asking the framework to convert a String* to a char* than to expect the programmer to do that conversion before every function call. By the same logic, wouldn't it be great if you could just pass a DateTime to Log() and have the marshaler convert it to a SYSTEMTIME? Well, you can. It's not built in the way string conversions are (everybody does string conversions), but it's not terribly hard to do. I'll show you next column how it's!
http://www.codeguru.com/cpp/cpp/cpp_managed/interop/article.php/c4865/Marshaling-and-Conversion-with-PInvoke.htm
CC-MAIN-2015-40
refinedweb
1,340
57
I’m trying to run a Nengo SPA model so that I can get the same results each time. I understand the following are required: rng Is there anything else I’m missing? Was this comprehensively documented elsewhere? I’m not 100% sure about SPA stuff, but those are all the things that I can think of. That’s all I can think of, but I’ll sometimes be paranoid and set the global numpy seed (and the python random seed if I’m being really paranoid), just to make sure: np.random.seed(seed) random.seed(seed) That said, if either of those seeds actually affects something that isn’t caught by the seeds that you’re already setting, then I’d consider that to be a bug. I have a Nengo model controlling a robot. I do not use any stochastic processes inside Nengo and all the non-Nengo code is deterministic, so to ensure reproducibility, I only set the seed for the top-level network. Indeed, when I run my model using Spyder, this results in the same behavior of the robot across different simulation runs. If I change the seed, the behavior of the robot somewhat changes, because the Nengo controller seems to be very sensitive to the actual choice of encoders and decoders. If, instead of using Spyder, I use the Nengo GUI, again the robot behavior is the same for the same seed across different runs. However, this behavior is different from the behavior exhibited when using Spyder, even though in both cases the seed is exactly the same. Is this expected? How can this be explained? Indeed, models can be sensitive to the actual choice of encoders, intercepts etc. It might be the case that changing the distributions that the parameters are drawn from will make your models more robust. As to the difference between behavior in Spyder and the GUI, I’m not 100% sure, but my guess would be that the Python environment that you’re using in Spyder is different from the one in the GUI. You can verify this by running a script in both environments that has the line import sys print(sys.executable) It will print out the location of the python program that ends up being run. If they’re not the same, then it’s likely that they’re using different installation of NumPy. NumPy is how we generate random numbers; I’m not sure about the details of how it draws random numbers, but it’s possible that you would get different results with the same seed using different versions of NumPy. python My guess is that you are running into the issue documented here. Essentially, there is a bug which can cause the seeds of individual Nengo objects to change in the Nengo GUI even though a top level seed has been set. Thank you for the suggestion. I will definitely consider this.[quote=“tbekolay, post:5, topic:143”] As to the difference between behavior in Spyder and the GUI, I’m not 100% sure, but my guess would be that the Python environment that you’re using in Spyder is different from the one in the GUI. [/quote] I checked that using the suggested script, but I have found that the Python executable in both cases is the same. It seems that @jgosmann guess is correct in this case. Thank you. It looks like you are right. I verified that by removing all sliders and plots from the Nengo GUI and then running the code again using the same seed as before. Now the behavior was the same as when the code was run using Spyder.
https://forum.nengo.ai/t/deterministically-running-nengo-models-by-setting-seeds/143
CC-MAIN-2018-05
refinedweb
614
69.31
Despite the COVID-19 outbreak, our team continues operating at full speed. We are always here to support and answer all your questions. Feel free to reach out by filling this quick form. Hi, I am having this problem when opening dropdown menu in piechart graph (in Flex version!). TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/addChild() at fl.controls::List/drawList()[D:\DEVELOP\test_lib\fl\controls\List.as:531] at com.flexmonster.controls::FMComboBoxList/draw() at fl.core::UIComponent/drawNow()[D:\DEVELOP\test_lib\fl\core\UIComponent.as:1198] at fl.controls::List/scrollToIndex()[D:\DEVELOP\test_lib\fl\controls\List.as:343] at fl.controls::SelectableList/scrollToSelected()[D:\DEVELOP\test_lib\fl\controls\SelectableList.as:989] at com.flexmonster.controls::FMComboBox/open() at com.flexmonster.controls::FMComboBox/onToggleListVisibility() at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.managers::SystemManager/mouseEventHandler()[/Users/justinmclean/Documents/ApacheFlex4.15/frameworks/projects/framework/src/mx/managers/SystemManager.as:2926] Since I have the component only as swc, so I do not see exactly the source codes, causing this problem, I do not know how to fix it. When I build the minimal demo App, with the same report, opening dropbox works just fine, but in our complex app, where there is several levels of encapsulation, I keep on getting this problem (with every dropdown, which is inside of the FlexPivotComponent). The app is modular, so we have many modules building separately and then externally loaded, so sometimes we have to manually include some classes and libraries to be packaged together. I do include the component swc, so the component works fine, but maybe the dropdown uses another external generic library (some parts of fl.*) which is not included in our app. But I do not know which since I can not take a look into the component. Do you have any idea what could be wrong? Or can you share with me the code of FMComboBox and FMComboBoxList, so I can take a look? Thanks Tom Hi Tom, Yes, Flex version of the component uses Flash libraries. Actually, it’s a Flash component with Flex wrapper. Here is the list of dependencies for FMComboBoxList: import fl.controls.List; import fl.controls.ScrollBar; import fl.controls.ScrollPolicy; import fl.controls.listClasses.CellRenderer; import fl.core.InvalidationType; import flash.display.CapsStyle; import flash.display.Shape; Please try to include fl.* libraries into your application and don’t hesitate to ask me if you still have a problem. Regarding source code, please talk to Olena, she will provide you with all necessary information. Thanks, Dmytro Hi Dmytro, the problem is still there. To me it looks like the dropdown is trying to add itself to the stage or into an object, which is converted into another object using as, which results into null. But it is really hard to blind guess what is wrong. I am running out of ideas, any other hints what could go wrong?:) Hi Tomas, Is it possible to send us via email some sample project the shows the issue? It will help us to reproduce and fix the source of the problem. Most probably it’s an incompatibility between your current SDK and core flash libraries that we use to build Flex .swc library. Regards, Dmytro
https://www.flexmonster.com/question/typeerror-when-opening-dropdown/
CC-MAIN-2021-17
refinedweb
551
52.15
Hi, I've a ASP MVC project with _Layout page and -> nested Views, I am using 2 controls _Layout page: 1-> GridViewpage: Grid With Master Details View 2-> GanttwithGridViewPage: Gantt with Grid. (Grid shows but Gantt does not Render, there is a frame, but data source says 0) I am getting errors from the scripts as widgets not defined ej not defined. Or, some of the controls not showing data. I would like to configure the UI side correctly with the page structure. The installs have older versions of JS I have the following questions: 1. Can you tell me what all files should be included in the Head section? of the _Layout 2. What files should be included in the child views? 3. What Order should these files be in? 4. What does Scriptmanager do, how are they helping me? 5. Should I put it after every control? or only once at the end of the page? 6. Should I include both the scripts and script manager or only one. 7. What is the difference between ej.widgets.js and ej.web.all.js; and do we include both 8. In the custom Js script generator, if I choose just grid script, will it include all the dependent JS files, or will I need to include the other dependent files. 9. What does the Grid.render function do, it exists on some help pages and not the other? 10. Should I include core files, if I include all 11. Should I include core files, if I include custom files 12. What is unobtrusive used for? (I have included this as true in web config with the corresponding js file) Unobtrusive Mode In Unobtrusive mode, we can define the ScriptManager in the _Layout page alone and there is no need to define them in partial view. Non-unobtrusive Mode In Unobtrusive mode, provide the @(Html.EJ().ScriptManager()) in the partial view as well as in the _Layout page. Hi Megatron, We can render the Gantt Control with the same reference list and in the same order as we described in the previous update. And we were not able to reproduce any issue while rendering the Gantt with Grid control in the Bootstrap theme. Please find the sample below, Sample: If you still face any issue then please get back to us by modifying the attached sample to reproduce it. Regards, Mahalakshmi K. Hi Megatron, Gantt Control: We have rendered Gantt and Grid in the boostrap container, but still we couldn’t reproduce any issue, can you please share us how you are using third party Boostrap in your project? It will be helpful for us to provide you better solution. Please find the code example for details, If you still facing any issue please get back to us by modifying this sample to reproduce the issue. Schedule Control: We were unable to reproduce the issue “Scrollbars are not shown” at our end and the same have prepared a sample which can be downloaded from the following location, If you still face any issue then please get back to us by modifying the attached sample to reproduce it. Note: We have removed the packages in the above sample kindly restore it before running the sample. Regards, Mahalakshmi K. Hi Taviz, Gantt Control: Query1: but when I try the bigger controls like gant inside any of the other custom bootstrap themes they stops working. The point of Bootstrap was compatibility, and many css namespaces from syncfusion controls are overlapping. Solution: Still we were not able to reproduce the issue in Gantt control rendering when we run the control with other 3rd party bootstrap theme. We have tried with some open source custom bootstrap theme and we can successfully render the Gantt and Grid in the same page. Please find the below screen shot for details. Can you please share us more details about the custom boostrap theme you are using in your project exactly? That will be helpful for us to provide you appropriate solution. Rich Text Editor control: Query:” in your rich text editor there is not way to reset the back ground color to transparent or white” RTE has inbuilt support to Clear formats which is integrated with RTE toolbar . please find the below code snippet to include the clearformat in toolbar. <code> List<String> clear = new List<string>() { "clearFormat", "clearAll" }; ..... @{Html.EJ().RTE("rteSample").ShowHtmlSource(true).Width("100%").ContentTemplate(@<div> <p><b>Description:</b></p> …… </div>).ShowFooter(true).IsResponsive(true).MinWidth("20px").ToolsList(toolsList).Tools(tool =>tool.Clear(clear).FormatStyle(formatStyle).Tables(tables).Links(links).Images(images).Effects(effects).Casing(casing).Font(font).Styles(style).Media(media).Alignment(alignment).Lists(lists).Clipboard(clipboard).DoAction(doAction).Indenting(indenting).View(view)).Render();} </code> Please find the alltools sample in the following link. Query:”And very hard to do ordered list alignments.” We are unable to get the exact problems which you have faced on ordered list from the above shared information. Please use the above sample to reproduce your problem or share us the video or screenshots, so that it would help us to assist you further. Regards, Mahalakshmi K. This post will be permanently deleted. Are you sure you want to continue? Sorry, An error occured while processing your request. Please try again later.
https://www.syncfusion.com/forums/121628/grid-in-nested-layouts-does-not-render-data-which-scripts-do-i-need
CC-MAIN-2018-47
refinedweb
884
64.91
This week Visual Studio 2015 Update 1 was released and with it TypeScript 1.7. To get the update to TypeScript install the update for Visual Studio. Then you can use the following new features: Of course if you are not using Visual Studio to compile your TypeScript feel free to install it from an alternative source, such as npm npm install -g typescript Async/Await for ES6 targets The async keyword is used as a prefix to a function and will designate it as an asynchronous function. You can then use the await keyword when you call the function to stop execution until the async‘s function’s promise is fulfilled. This behavior seems similar how Async/Await works in C# so if you are familiar with that this should be easy. Example Time !"); }); This example was provided by the TypeScript team Of course the glory that is Async/Await does have a drawback. It’s currently only available if you are targeting a platform that supports ES6 generators. That means right now just node.js v4 and up. They are working on bringing it to other targets but there is additional work that the TypeScript team will have to do to make that happen. Polymorphic this Typing TLDR The Polymorphic this typing allows you to create a class that returns this and not mess up the typing’s when the class inherited functions from a parent. An Example Lets say we have a base class called Base and a child class called Child. Before this change if we implemented a fluent style api within these classes a compiler error would occur when Child called a method that was defined on Base. Why? Well the method only understood the type of class it was defined in, in this case Base. Lets look at it: Base class export default class Base { public constructor(protected something:string = '') { } public getCurrentSomething() { return this.something; } public setSomething(newSomething: string) { this.something = newSomething; return this; } } ‘Child’ class import Base from "./Base"; export default class Child extends Base { public constructor(something: string = '') { super(something); } public deleteSomething() { return this; } } Use It import Child from "./Child"; let child = new Child('something') .setSomething('otherThing') .deleteSomething() //ERROR HERE .getCurrentSomething(); On the line that says .deleteSomething() an error would occur because .setSomething() returned a type of Base and there is nor .deleteSomething() defined on Base. This is no longer the case as the this is now considered a special type. They describe is as “the type of the left side of the dot in a method call”. ES6 Module Emitting ES6 was added as an option for Module output. This will allow for more flexibility with module output. ES7 Exponentiation The last this is some sugar for your syntactic sweet tooth. you can now use ** for exponents. let squared = 4 ** 2; // same as: 4 * 4 let cubed = 4 ** 3; // same as: 4 * 4 * 4 let num = 4; num **= 2; // same as: num = num * num; Conclusion Maybe I need to get out more but I think this is some cool stuff. I can’t wait to see what else the TypeScript team puts together, how about you? Let us know what you think by leaving a comment bellow or, if you are feeling shy, send an email to me at brett@wipdeveloper.com.
https://wipdeveloper.com/typescript-whats-new-in-1-7/
CC-MAIN-2019-39
refinedweb
551
72.05
JulianCalendar.IsLeapDay Method (Int32, Int32, Int32, Int32) Determines whether the specified date in the specified era is a leap day. Namespace: System.GlobalizationNamespace: System.Globalization Assembly: mscorlib (in mscorlib.dll) Parameters - year - Type: System.Int32 An integer that represents the year. - month - Type: System.Int32 An integer from 1 to 12 that represents the month. - day - Type: System.Int32 An integer from 1 to 31 that represents the day. - era - Type: System.Int32 An integer that represents the era. Return ValueType: System.Boolean true if the specified day is a leap day; otherwise, false. days. A leap day is a day that occurs only in a leap year. In the Julian calendar, the 29th day of February is the only leap day. The following example calls IsLeapDay for the last day of the second month (February) for five years in each of the eras. using System; using System.Globalization; public class SamplesJulianCalendar { public static void Main() { // Creates and initializes a JulianCalendar. JulianCalendar myCal = new JulianCalendar(); // Creates a holder for the last day of the second month (February). int iLastDay; // Displays the header. Console.Write( "YEAR\t" ); for ( int y = 2001; y <= 2005; y++ ) Console.Write( "\t{0}", y ); Console.WriteLine(); // Checks five years in the current era. Console.Write( "CurrentEra:" ); for ( int y = 2001; y <= 2005; y++ ) { iLastDay = myCal.GetDaysInMonth( y, 2, JulianCalendar.CurrentEra ); Console.Write( "\t{0}", myCal.IsLeapDay( y, 2, iLastDay, JulianCalendar.CurrentEra ) ); } Console.WriteLine(); // Checks five years in each of the eras. for ( int i = 0; i < myCal.Eras.Length; i++ ) { Console.Write( "Era {0}:\t", myCal.Eras[i] ); for ( int y = 2001; y <= 2005; y++ ) { iLastDay = myCal.GetDaysInMonth( y, 2, myCal.Eras[i] ); Console.Write( "\t{0}", myCal.IsLeapDay( y, 2, iLastDay, myCal.Eras[i] ) ); } Console.WriteLine(); } } } /* This code produces the following output. YEAR 2001 2002 2003 2004 2005 CurrentEra: False False False True False Era 1: False False False True False */
https://msdn.microsoft.com/en-us/library/vstudio/tah8fe02.aspx
CC-MAIN-2015-11
refinedweb
316
63.66
DSDP/PMC/PMC Minutes 11Mar10 < DSDP | PMC Revision as of 07:26, 11 March 2010 by Dgaff.eclipse.gmail.com (Talk | contribs) Time Dial-in Info Invited Attendees - Mike Milinkovich - Doug Gaff, PMC Lead - Eric Cloninger, Sequoya - Christian Kurzke, MTJ/Pulsar - Shigeki Moride, NAB - Martin Oberhuber, TM/TCF - Dave Russo, RTSC - Wayne Parrot, Blinki (absent) New Business - History - Wind River stepped down from the Strategic Developer level almost 2 years. - Doug Gaff and his team were still allocated to Wind River’s open source work, so DSDP was effectively still under sponsorship. Then early last year, Doug's management responsibilities at Wind changed significantly, and the official time allocated to DSDP became "whatever he could squeeze in." - Doug took a new job in Dec of last year, and Wind declined to continue their sponsorship of the project. - Doug's new job is unrelated to Eclipse, and he cannot continue to lead the project. The Foundation was unable to find another company or group of companies to devote the necessary time to lead the project. - Where are are now - Doug would like to see DSDP continue if it had good sponsorship, but the seems unlikely. It is more important that the technologies continue to live wherever they can get the most mentoring and exposure. - Some discussion about this on the phone. - Summary is that the PMC really enjoys working together, but no one has enough sponsorship from their respective companies to lead DSDP, and they need to focus on their projects. - Proposal for moving Projects - Blinki - Move to Technology? Needs a reboot, because the project is failing to be open and transparent. - Mike and Wayne from the Foundation will need to meet with Blinki leadership. - Device Debugging - DSF moved to CDT last year and is thriving there. - The repository was left open for folks to remain on a frozen branch until after the CDT transition. The IP-XACT editor is also there, but it's no longer under development. - Decision: Archive - MTJ and Sequoyah - Sequoyah moves to Tools and becomes a container project for mobile - MTJ moves under Sequoyah - RTSC - Move to Technology since they are still incubating. Could move somewhere else when they are ready to exit incubation. Dave really wants the visibility to be high, though. Perhaps a future in CDT? - TM - Move to Tools and eventually have TCF (currently a component) as a separate project. - NAB - Move to Technology. Still in incubation. - Will continue to use the DSDP namespace (org.eclipse.dsdp.nab). Shigeki feels that the DSDP brand is important to maintain (especially in Japan). - Communication and Next Steps - Doug to communicate this meeting on the dsdp-pmc mailing list. - Doug to blog next week. - Rearrange projects AFTER Helios! Wayne, Anne, and Webmaster team will help move. - This PMC will need to meet occasionally to keep things running until Helios. - Participation on planning council - Votes needed from the PMC - Ad-hoc calls as necessary - Words of Thanks from Mike and Doug
http://wiki.eclipse.org/index.php?title=DSDP/PMC/PMC_Minutes_11Mar10&oldid=192062
CC-MAIN-2015-14
refinedweb
494
56.45
This is a schema for XSLT 2.0 stylesheets. It defines all the elements that appear in the XSLT namespace; it also provides hooks that allow the inclusion of user-defined literal result elements, extension instructions, and top-level data elements. The schema is derived (with kind permission) from a schema for XSLT 1.0 stylesheets produced by Asir S Vedamuthu of WebMethods Inc. This schema is available for use under the conditions of the W3C Software License published at The schema is organized as follows: PART A: definitions of complex types and model groups used as the basis for element definitions PART B: definitions of individual XSLT elements PART C: definitions for literal result elements PART D: definitions of simple types used in attribute definitions This schema does not attempt to define all the constraints that apply to a valid XSLT 2.0 stylesheet module. It is the intention that all valid stylesheet modules should conform to this schema; however, the schema is non-normative and in the event of any conflict, the text of the Recommendation takes precedence. This schema does not implement the special rules that apply when a stylesheet has sections that use forwards-compatible-mode. In this mode, setting version="3.0" allows elements from the XSLT namespace to be used that are not defined in XSLT 2.0. Simplified stylesheets (those with a literal result element as the outermost element) will validate against this schema only if validation starts in lax mode. This version is dated 2007-03-16 Authors: Michael H Kay, Saxonica Limited Jeni Tennison, Jeni Tennison Consulting Ltd. 2007-03-15: added xsl:document element revised xsl:sequence element see PART A: definitions of complex types and model groups used as the basis for element definitions PART B: definitions of individual XSLT elements Elements are listed in alphabetical order. PART C: definition of literal result elements There are three ways to define the literal result elements permissible in a stylesheet. (a) do nothing. This allows any element to be used as a literal result element, provided it is not in the XSLT namespace (b) declare all permitted literal result elements as members of the xsl:literal-result-element substitution group (c) redefine the model group xsl:result-elements to accommodate all permitted literal result elements. Literal result elements are allowed to take certain attributes in the XSLT namespace. These are defined in the attribute group literal-result-element-attributes, which can be included in the definition of any literal result element. PART D: definitions of simple types used in stylesheet attributes This type is used for all attributes that allow an attribute value template. The general rules for the syntax of attribute value templates, and the specific rules for each such attribute, are described in the XSLT 2.0 Recommendation. A string containing exactly one character. An XPath 2.0 expression. Describes how type annotations in source documents are handled. The level attribute of xsl:number: one of single, multiple, or any. The mode attribute of xsl:apply-templates: either a QName, or #current, or #default. The mode attribute of xsl:template: either a list, each member being either a QName or #default; or the value #all A list of NameTests, as defined in the XPath 2.0 Recommendation. Each NameTest is either a QName, or "*", or "prefix:*", or "*:localname" The method attribute of xsl:output: Either one of the recognized names "xml", "xhtml", "html", "text", or a QName that must include a prefix. A match pattern as defined in the XSLT 2.0 Recommendation. The syntax for patterns is a restricted form of the syntax for XPath 2.0 expressions. Either a namespace prefix, or #default. Used in the xsl:namespace-alias element. A list of QNames. Used in the [xsl:]use-attribute-sets attribute of various elements, and in the cdata-section-elements attribute of xsl:output A QName. This schema does not use the built-in type xs:QName, but rather defines its own QName type. Although xs:QName would define the correct validation on these attributes, a schema processor would expand unprefixed QNames incorrectly when constructing the PSVI, because (as defined in XML Schema errata) an unprefixed xs:QName is assumed to be in the default namespace, which is not the correct assumption for XSLT. The data type is defined as a restriction of the built-in type Name, restricted so that it can only contain one colon which must not be the first or last character. The description of a data type, conforming to the SequenceType production defined in the XPath 2.0 Recommendation Describes different ways of type-annotating an element or attribute. Describes different ways of type-annotating an element or attribute. One of the values "yes" or "no". One of the values "yes" or "no" or "omit".
http://www.w3.org/2007/11/schema-for-xslt20.xsd
CC-MAIN-2018-13
refinedweb
804
52.8
From: Rene Jager (renej_at_[hidden]) Date: 2001-08-15 16:26:09 Darin Adler wrote: >We're about halfway through the formal review period for Peter Dimov's >Bind library (ends Sunday, August 19th), and so far I've only seen one set >of comments (from Daryle Walker). Please take the time to review the >library this week if you can. > > -- Darin > >Info: Unsubscribe: <mailto:boost-unsubscribe_at_[hidden]> > >Your use of Yahoo! Groups is subject to > > > what can I say, I'm already using it and it works ok (also with home-brewed smart pointers overloading operator->*); I migrated from the binder library to boost.bind; one point maybe is the use of _1, _2. I though I read something on the boost list about indexing from 0 i.o. 1. Another point about the _1, _2, ... _9 free argument variables is that the are in an anonymous namespace, so possible clashes with non-boost stuff... and boost::_1, boost::_2 is long, but safe overall opinion: ACCEPT renej Boost list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/Archives/boost/2001/08/15887.php
CC-MAIN-2013-20
refinedweb
196
75.1
As of release 1.2.10, the source file dbus-sysdeps-util-unix.c will not compile under Mac OS X 10.5, because the function "openlog" is undeclared. On Mac OS X 10.5, "openlog" is declared in the header <syslog.h>. If the line #include <syslog.h> is added in the section of #includes at the top of this file, it compiles and dbus makes normally. I did not include a patch because (a) it's a one-liner, but mostly (b) I have no way of knowing if this header exists on other operating systems, or how in the build system for dbus you would want to go about checking if this #include is necessary. I appreciate it if someone is able to properly tailor the #includes in a future release of dbus. Many thanks, Glen I get the same compilation error on a Fedora core 3 machine, adding the syslog.h include fixes it. commit 510a307da0ce3e63361d0b9b8db4df3f564a1955 Author: Colin Walters <walters@verbum.org> Date: Tue Jan 6 17:34:20 2009 -0500 Bug 19307: Add missing syslog include Use of freedesktop.org services, including Bugzilla, is subject to our Code of Conduct. How we collect and use information is described in our Privacy Policy.
https://bugs.freedesktop.org/show_bug.cgi?id=19307
CC-MAIN-2021-49
refinedweb
207
67.96
Opened 5 years ago Closed 4 years ago #19888 closed Bug (duplicate) MultiValueDictKeyError when saving Inlines without an AutoField Description Saving an Inline that makes use of an autogenerated primary key that is not an AutoField causes a MultiValueDictKeyError. Here is a gist with an admin.py and model.py to reproduce the issue: Steps: create Author save add a Book to Author save add another Book to Author save --> MultiValueDictKeyError Here is an IRC chat log about the issue: [18:22] <gp> I posted a message to the django-dev group earlier about #12235. I need to use a uuid primary key. I've added the solution to my field, but django is trying to populate it with an integer because the suggested solution in the ticket is to imitate an autofield. Is that the right way to fix the issue? [18:22] <ticketbot> [18:23] <gp> I get a ValueError when I try to add the instance because of this [18:23] <akaariai_> gp: sorry for stupid question, but why do you need to mark the field as autofield? [18:24] <akaariai_> and what DB are you using? [18:26] <akaariai_> if mysql I can see the reason, Django will helpfully issue a select last_insert_id() and populate the field using that value... [18:26] <gp> akaariai_: sqlite3 and mysql [18:26] <akaariai_> yeah, likely similar problem on sqlite3 too [18:27] <akaariai_> so, what happens if the field isn't an autofield? [18:27] <gp> akaariai_: MultiValueDict error [18:27] <gp> it has to do with inlines [18:28] <gp> The summary of the ticket was that everyone's UUIDField implementation is wrong. The suggested fix was to mark the field as an AutoField in the contribute_to_class method [18:30] <jacobkm> I have to say I still think it's an implementation problem. I have plenty of models with non-integer primary keys (slug fields, often) and those seem to work fine. [18:30] <jacobkm> Unless there's some reason why a uuid, specifically, causes Django to fail when it doesn't have an autofield primary key I can't really see that this is a bug in Django. [18:31] <gp> jacobkm: are those fields automatically filled in? [18:31] <jacobkm> gp: I'd have to check specifically where, but yeah they kinda have to be. [18:32] <gp> jacobkm: are any of them open? I would like to plug on into my model and see if it works. Would help me narrow the issue down [18:32] <jacobkm> gp: can you reproduce the problem with a field built into Django? i.e. char field or seomthing? [18:33] <jacobkm> gp: if so, then it's certainly a bug in Django. If not, it still might be a bug in Django, but it also implies there's more going on. [18:34] <gp> jacobkm: I will copy over the relavent code to a charfield subclass. The field is basically a charfield on everything but postgres [18:34] <gp> will report back [18:35] <akaariai_> jacobkm: are you setting the field as autofield? [18:35] <jacobkm> akaariai_: I doubt it, that seems wrong to me. [18:36] <akaariai_> agreed [18:36] <gp> jacobkm: the suggested fix to that issue was to use cls._meta.has_auto_field = True and cls._meta.auto_field = self in the fields contribute_to_class method [18:36] <jacobkm> gp: yeah i don't think that should be needed. [18:36] <gp> jacobkm: okay good. [18:53] <gp> here is the field: [18:53] <gp> I still get the MultiValueDictKeyError [18:55] <gp> Have a model and an inline model. Create an instance of the model. Save it. Add one child... save it. Add another child... save = MultiValueDictKeyError [18:56] <jacobkm> gp: beat me to it :) [18:56] <jacobkm> It doesn't actually require a custom field: [18:56] <jacobkm> So yeah, bug. [19:00] <akaariai_> hmmh, so the problem is that the has_auto_field has dual meaning - first, it is used to determine if the field is autogenerated, but also if it is autogenerated in the DB [19:01] <gp> think it is a difficult fix? [19:05] <gp> I would be happy to put it together if someone gave me some guidance on how it should be done [19:06] <gp> akaariai_: I think that is the issue [19:06] <akaariai_> gp: A possible idea is to add field.autogenerated, meaning is that the field's value will be automatically generated on first save, and isn't user editable. [19:07] <akaariai_> then the meta.has_auto_field would point to true AutoFields only. Go through all instances where has_auto_field is used and determine if has_auto_field or field.autogenerated should be used. [19:07] <akaariai_> might work, but I wouldn't be surprised if it doesn't. [19:07] <akaariai_> all instances -> all places in django code... [19:08] <gp> akaariai_: that makes sense [19:10] <gp> Is this something that could get into the 1.5 or will it have to wait? [19:10] <akaariai_> gp: 1.5 is out of the question, release hopefully really soon now. [19:11] <akaariai_> so, no new features [19:11] <gp> I figured so. But if it could I was going to start right now lol [19:12] <gp> Just didn't know if since it was a bug it could sneak in [19:12] <gp> Should I reopen that bug report or create a new one? [19:13] <gp> I mean ticket [19:14] <jacobkm> gp: yeah please do, sorry I meant to do it but I'm getting distracted [19:15] <gp> jacobkm: no problem. which one? reopen or new? [19:15] <jacobkm> gp: um... new one might be better, get rid of the distraction of uuidfield. [19:16] <jacobkm> I got thrown by that and I think everyone else followed along. [19:16] <akaariai_> gp: If it turns out there is a simple bugfix for the inline issue only, then fixing just that might be a good way forward, too. [19:18] <gp> akaariai_: I think the value error issue i've run into is on Model.save_base where the pk is set to the return value of manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) [19:19] <gp> akaariai_: actually I guess that doesn't apply now [19:19] <gp> since imitaiting autofield caused that [19:20] <akaariai_> yes, if you fix that, then users will still need to imitate autofield, and that isn't good. Internal api, and relies on a hack. [19:23] <akaariai_> btw the reason why the autogenerated flag change isn't a good idea to 1.5 even if a perfect patch was available just now is that there are users who surely rely on the has_auto_field hack. [19:24] <akaariai_> and breaking their code just before release isn't a good idea. And then there is of course the possibility of regressions... [19:24] <gp> akaariai_: yep. very true Here is a copy of the field definition I referenced: class UUIDField(CharField): def __init__(self, version=4, node=None, clock_seq=None, namespace=None, name=None, auto=False, *args, **kwargs): # We store UUIDs in hex format, which is fixed at 32 characters. kwargs['max_length'] = 32 self.auto = auto if auto: # Do not let the user edit UUIDs if they are auto-assigned. kwargs['editable'] = False kwargs['blank'] = True kwargs['unique'] = True super(UUIDField, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): """ This is used to ensure that we auto-set values if required. See CharField.pre_save """ value = getattr(model_instance, self.attname, None) if self.auto and add and not value: # Assign a new value for this attribute if required. uuid = uuid4() value = uuid.hex setattr(model_instance, self.attname, value) return value Attachments (2) Change History (7) comment:1 Changed 5 years ago by Changed 5 years ago by comment:2 Changed 5 years ago by Changed 5 years ago by simple test project setup to test issue. uses selenium comment:3 Changed 5 years ago by comment:4 Changed 5 years ago by current patch does not work if the pk field is excluded from the admin It's not clear at this point if this should be categorized as an ORM bug or an admin bug; it seems like it might have its roots in the ORM, but so far the only failing example is in the admin.
https://code.djangoproject.com/ticket/19888
CC-MAIN-2017-39
refinedweb
1,401
71.75
IRC log of ws-ra on 2009-09-01 Timestamps are in UTC. 19:23:29 [RRSAgent] RRSAgent has joined #ws-ra 19:23:29 [RRSAgent] logging to 19:23:31 [trackbot] RRSAgent, make logs public 19:23:31 [Zakim] Zakim has joined #ws-ra 19:23:33 [trackbot] Zakim, this will be WSRA 19:23:33 [Zakim] ok, trackbot; I see WS_WSRA()3:30PM scheduled to start in 7 minutes 19:23:34 [trackbot] Meeting: Web Services Resource Access Working Group Teleconference 19:23:34 [trackbot] Date: 01 September 2009 19:23:38 [Zakim] WS_WSRA()3:30PM has now started 19:23:45 [Zakim] +[IBM] 19:24:18 [Vikas] Vikas has joined #ws-ra 19:25:00 [Zakim] +Bob_Freund 19:26:20 [Paul] Paul has joined #ws-ra 19:26:52 [Tom_Rutt] Tom_Rutt has joined #ws-ra 19:27:41 [Bob] chair: Bob Freund 19:27:48 [Zakim] + +25625669aaaa 19:28:16 [Bob] zakim, aaaa is Paul 19:28:16 [Zakim] +Paul; got it 19:28:29 [Zakim] +Tom_Rutt 19:29:08 [Zakim] +Igor_Sedukhin 19:29:19 [Zakim] +??P9 19:29:25 [li] li has joined #ws-ra 19:29:39 [Zakim] +Vikas 19:30:21 [Zakim] +li 19:30:37 [gpilz] gpilz has joined #ws-ra 19:30:50 [Zakim] +gpilz 19:30:54 [Ashok] Ashok has joined #ws-ra 19:31:14 [DaveS] DaveS has joined #ws-ra 19:31:31 [Zakim] +Yves 19:31:52 [Zakim] +Ashok_Malhotra 19:32:43 [Zakim] +[Microsoft] 19:32:50 [Bob] agenda: 19:33:23 [asir] asir has joined #ws-ra 19:33:26 [Ram] Ram has joined #ws-ra 19:34:19 [Bob] scribe: Vikas Varma 19:34:21 [Tom_Rutt] Tom_Rutt has joined #ws-ra 19:34:28 [Bob] scribenick: Vikas 19:35:05 [Sreed] Sreed has joined #ws-ra 19:35:57 [Bob] Agenda - agreed 19:36:41 [Bob] Resolution: Minutes of 2009-08-25 approved w/o 19:38:06 [Vikas1] Vikas1 has joined #ws-ra 19:38:40 [dug] the term "normal company" could be hard to define 19:39:02 [Vikas1] Bob, can you mark Vikas1 as scribe. 19:39:48 [Bob] scribenick: Vikas1 19:41:07 [Vikas1] Topic: action item review. 19:42:39 [Vikas1] Topic: Progress with initial draft of WS-Frag 19:43:44 [Vikas1] Dug/Ram : Going through internal review 19:44:15 [Vikas1] Dog/Ram : Will try to put the proposal before next call. 19:45:02 [dug] 129.33.49.251 19:45:35 [Vikas] Vikas has joined #ws-ra 19:46:19 [Vikas2] Vikas2 has joined #ws-ra 19:46:39 [Bob] scribenick: Vikas2 19:47:48 [Bob] resolution: Open 7429 w/o 19:47:57 [Vikas] Vikas has joined #ws-ra 19:48:17 [Bob] resolution: issue-7429 resolved with proposal in bugzilla w/o 19:49:01 [Vikas] Vikas has joined #ws-ra 19:49:02 [Yves] dug, hsould be ok now 19:49:21 [dug] yep - works thanks! 19:49:37 [Bob] resolution Issue-7430 opened w/o 19:50:15 [Bob] resolution: Issue 7430 resolved with proposal in bugzilla 19:50:34 [Bob] 19:51:09 [Bob] scribenick: Vikas 19:51:37 [Vikas] yes Bob 19:54:02 [Vikas] resolution: Issue-7478 opened w/o. 19:54:16 [asir] when do we stop opening issues :-) 19:54:46 [dug] 19:55:35 [dug] yves - failing again 19:55:41 [Vikas] ACTION: Gilbert to provide proposal on 7478 19:55:41 [trackbot] Created ACTION-99 - Provide proposal on 7478 [on Gilbert Pilz - due 2009-09-08]. 19:56:06 [gpilz] q+ 19:56:24 [dug] Yves - IP is: 129.33.49.251 19:56:25 [Bob] ack gpi 19:57:21 [gpilz] q+ 19:57:36 [Bob] ack gpi 19:57:51 [asir] q+ 19:57:56 [dug] yves - working again - thanks 19:58:00 [Vikas] Ram: Is it necessary to define a seperate mine-type. 19:58:15 [Bob] asir 19:58:21 [Bob] ack asir 19:59:16 [dug] what does that involve? 19:59:21 [dug] (the process) 19:59:23 [Bob] application 19:59:52 [Vikas] Bob: Is there any objection to define a new mime-type? 20:00:02 [Ashok] I understand that getting a new mime type is a long drawn-out process 20:00:05 [asir] q+ 20:00:12 [Bob] ack asir 20:00:54 [Vikas] Gil: Suggest to drive it as a seperate issue. 20:02:32 [gpilz] q+ 20:02:41 [dug] thanks 20:03:15 [gpilz] q- 20:05:12 [asir] Good! 20:05:20 [Vikas] RESOLUTION: No objection on the latest proposal. 6401 resolved with comment 12. 20:05:42 [li] you're welcome 20:05:53 [Bob] 20:05:56 [Zakim] +JeffM 20:06:18 [Ram] Proposed resolution for 6694: "An endpoint MAY indicate that it supports WS-Eventing, or its features, by including the WS-Eventing Policy assertion(s) within its WSDL. By doing so the endpoint is indicating that the corresponding WS-Eventing operations are supported by that endpoint even they do not explicitly appear in its WSDL”. 20:06:42 [dug] q+ 20:07:14 [Bob] ack dug 20:07:17 [dug] ram - s/even/even though/ right? 20:11:00 [asir] Vow, two big issues out of the way!! 20:11:10 [asir] quite a day! 20:11:10 [Vikas] No objection on the latest proposal. 6694 6401 resolved with comment 7 and 8. 20:11:22 [Vikas] s/6401/ 20:11:29 [asir] s/6401// 20:12:29 [dug] he's just hiding 20:13:26 [Bob] Topic: Infoset 20:14:28 [Ram] q+ 20:14:45 [Bob] ack ram 20:15:09 [DaveS] What issue number are we talking about? 20:15:18 [Ashok] 6700 20:15:29 [Bob] Issue 6700 et alia 20:16:36 [Ram] q+ 20:16:42 [Bob] ack ram 20:17:44 [dug] q+ 20:18:31 [Ram] q+ 20:18:43 [Bob] ack dug 20:18:48 [li] 20:19:01 [dug] This specification is defined in terms of XML 1.0. A mapping from XML to Infoset is straightforward as described below, and it is recommended that this should be used for any non-XML serializations. 20:19:50 [Bob] ack ram 20:20:13 [Bob] ack yves 20:21:09 [dug] This specification is defined in terms of XML 1.0. A mapping from XML to Infoset is straightforward as described in the Infoset specification [http:...], and it is recommended that this should be used for any non-XML serializations. See the Infoset specification for more details. 20:21:20 [li] q+ 20:21:24 [dug] q+ 20:21:28 [Bob] proposal for resolution of 6700, 6701, 6702,6703, and 6704 20:21:37 [Bob] ack li 20:22:08 [Ram] Amended proposal: This specification is defined in terms of XML 1.0. A mapping from XML to Infoset is straightforward as described in the Infoset specification [ ], and it is recommended that this should be used for any non-XML serializations. 20:22:23 [li] 20:22:30 [dug] Ram - add the final sentence (para) 20:22:34 [Ashok] Yves, are you ok with Ram's wording? 20:23:42 [Ram] Doug - I got rid of the last para and merged it into the first para. That is, the ref to Infoset spec is in this first para. 20:23:51 [Yves] not really, it is important to say that the spec is defined in terms on Infoset and not XML1.0 20:24:02 [asir] q+ 20:24:07 [dug] ok - as long as people don't want the "see XXX for more details" 20:24:13 [dug] guess its just noise 20:24:14 [dug] q- 20:24:23 [Bob] ack asir 20:24:27 [Ashok] Yes, that's what I thought ... on second thought I agree with that 20:24:29 [Yves] see and 20:25:17 [Yves] [[A SOAP message is specified as an XML infoset whose comment, element, attribute, namespace and character information items are able to be serialized as XML 1.0.]] 20:25:39 [dug] q+ 20:25:49 [Bob] ack dug 20:26:35 [Tom_Rutt_] Tom_Rutt_ has joined #ws-ra 20:26:43 [asir] q+ 20:26:58 [Bob] ack asir 20:26:58 [Yves] In, if we add a sentence saying that valid infosets for this specification are ones serializable using XML 1.0 should be enough 20:28:04 [Ashok] q+ 20:28:11 [li] yves, that link is broken 20:28:59 [Bob] ashok 20:29:03 [Bob] ack ashok 20:29:51 [Ram] Amended proposal: This specification is defined in terms of XML 1.0. A mapping from XML to Infoset is straightforward as described in the Infoset specification [ ], and it is recommended that this should be used for any non-XML serializations. Valid infosets for this specification are ones serializable using XML 1.0. 20:30:25 [dug] q+ 20:30:40 [Yves] well, that prevents in a way serialization of an infoset into something else, better say that it's an infoset and restricted to serialization in XML1.0 20:32:00 [Yves] proposal: This specification is defined in terms of XML Information Set (Infoset) 20:32:08 [Yves] , even though the specification uses XML 1.0 20:32:09 [Yves] terminology. 20:32:47 [Yves] Valid Infoset for this specification are the one serializable in XML 1.0, hence the use of XML 1.0. 20:33:22 [gpilz] q+ 20:33:45 [asir] q+ 20:33:47 [Bob] ack dug 20:34:17 [Bob] ack yves 20:35:37 [jeffm] jeffm has joined #ws-ra 20:36:52 [Bob] ack gpi 20:37:19 [Ram] Minor amendment to Yves's proposal: This specification is defined in terms of XML Information Set (Infoset) [ ], even though the specification uses XML 1.0 terminology. Valid Infoset for this specification are the one serializable in XML 1.0, hence the use of XML 1.0. 20:38:01 [Ram] q+ 20:38:22 [Bob] ack ram 20:38:24 [Bob] ack asir 20:38:37 [asir] This sounds like the min to close all our infoset issues 20:38:43 [dug] q+ 20:39:36 [asir] I think the third para is already represented in the above proposal 20:39:59 [Bob] ack dug 20:40:37 [asir] Would Doug be okay if we were to say ... 20:40:47 [asir] This spec can be used in terms of .... 20:41:22 [Bob] despite all appearances, this spec is defined (somewhere in a non-disclosed location) in Infoset Notation 20:41:53 [asir] .. 20:41:54 [asir] This specification can be used in terms of XML Information Set (Infoset) [ ], even though the specification uses XML 1.0 terminology. Valid Infoset for this specification are the one serializable in XML 1.0, hence the use of XML 1.0. 20:42:28 [asir] :-) 20:43:05 [asir] Vow .. we closed 8 issues today. 20:43:31 [asir] i stand corrected 10 issues 20:43:50 [DaveS] Can we go home erly? 20:43:58 [dug] end on a high note? 20:45:07 [Bob] cwna for 6424 20:45:10 [li] and i didn't even say a word 20:45:12 [asir] vow .. that is 11 20:45:32 [dug] sure 20:45:58 [Vikas] RESOLUTION: No objection on the latest proposal put forward in the chat room for 6700, 6701, 6702, 6703, and 6704. 20:46:07 [Vikas] RESOLUTION: 6424 closed with no action. 20:46:39 [Yves] 20:48:13 [Vikas] Topic : Issue 6533 20:48:34 [DaveS] q+ 20:49:41 [Bob] ack dave 20:53:20 [asir] Standalone makes sense 20:53:32 [DaveS] +1 to standalone 20:53:39 [asir] Where will we add this para? 20:57:32 [dug] I'm assuming that the non-Get ops in Transfer are non-safe so a ref to (b) should be added - the proposal doesn't actually say that. 20:57:34 [dug] q+ 20:59:19 [Bob] ack dug 21:00:55 [asir] that's a dozen 21:01:02 [asir] do you want to try a bakers dozen? 21:01:09 [DaveS] bye 21:01:25 [Zakim] -??P9 21:01:51 [Zakim] -Yves 21:01:53 [Zakim] -[Microsoft] 21:01:53 [Zakim] -Paul 21:01:53 [Vikas] Vikas has joined #ws-ra 21:01:55 [Zakim] -JeffM 21:01:56 [Zakim] -[IBM] 21:01:58 [Zakim] -Bob_Freund 21:01:58 [Zakim] -Vikas 21:01:58 [Zakim] -gpilz 21:01:58 [Zakim] -Ashok_Malhotra 21:02:05 [Zakim] -li 21:02:14 [Zakim] -Igor_Sedukhin 21:02:33 [Bob] resolution: Issue-6533 resolved with the proposal contained in comment #4 and comment # 6 21:03:09 [Bob] rsagent, generate minutes 21:03:17 [Bob] rrsagent, generate minutes 21:03:17 [RRSAgent] I have made the request to generate Bob 21:07:14 [Zakim] disconnecting the lone participant, Tom_Rutt, in WS_WSRA()3:30PM 21:07:15 [Zakim] WS_WSRA()3:30PM has ended 21:07:17 [Zakim] Attendees were [IBM], Bob_Freund, +25625669aaaa, Paul, Tom_Rutt, Igor_Sedukhin, Vikas, li, gpilz, Yves, Ashok_Malhotra, [Microsoft], JeffM 21:36:57 [gpilz] gpilz has left #ws-ra 21:49:42 [dug] dug has joined #ws-ra
http://www.w3.org/2009/09/01-ws-ra-irc
CC-MAIN-2014-52
refinedweb
2,214
63.83
Search and Replace a Text in a File in Python In this article, we will learn to search and replace a text of a file in Python. We will use some built-in functions and some custom codes as well. We will replace text, or strings within a file using mentioned ways. Python provides multiple built-in functions to perform file handling operations. Instead of creating a new modified file, we will search a text from a file and replace it with some other text in the same file. This modifies the file with new data. This will replace all the matching texts within a file and decreases the overhead of changing each word. Let us discuss some of the mentioned ways to search and replace text. Example: Use replace() to Replace a Text within a File The below example uses replace() function to modify a string within a file. We use the review.txt file to modify the contents. It searches for the string by using for loop and replaces the old string with a new string. open(file,'r') - It opens the review.txt file for reading the contents of the file. strip() - While iterating over the contents of the file, strip() function strips the end-line break. replace(old,new) - It takes an old string and a new string to replace its arguments. file.close() - After concatenating the new string and adding an end-line break, it closes the file. open(file,'w') - It opens the file for writing and overwrites the old file content with new content. reading_file = open("review.txt", "r") new_file_content = "" for line in reading_file: stripped_line = line.strip() new_line = stripped_line.replace("Ghost", "Ghostbusters") new_file_content += new_line +"\n" reading_file.close() writing_file = open("review.txt", "w") writing_file.write(new_file_content) writing_file.close() Output: Example: Replace a Text using Regex Module An alternative method to the above-mentioned methods is to use Python’s regex module. The below example imports regex module. It creates a function and passed a file, an old string, and a new string as arguments. Inside the function, we open the file in both read and write mode and read the contents of the file. compile() - It is used to compile a regular expression pattern and convert it into a regular expression object which can then be used for matching. escape() - It is used to escape special characters in a pattern. sub() - It is used to replace a pattern with a string. #importing the regex module import re #defining the replace method def replace(filePath, text, subs, flags=0): with open(file_path, "r+") as file: #read the file contents file_contents = file.read() text_pattern = re.compile(re.escape(text), flags) file_contents = text_pattern.sub(subs, file_contents) file.seek(0) file.truncate() file.write(file_contents) file_path="review.txt" text="boundation" subs="foundation" #calling the replace method replace(file_path, text, subs) Output: FileInput in: Search and Replace a Text using FileInput and replace() Function The below function replaces a text using replace() function. import fileinput filename = "review.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if("paramal" in line): print(line.replace("paramal","paranormal"), end ='') else: print(line, end ='') Output: Conclusion In this article, we learned to search and replace a text, or a string in a file by using several built-in functions such as replace(), regex and FileInput module. We used some custom codes as well. We saw outputs too to differentiate between the examples. Therefore, to search and replace a string in Python user can load the entire file and then replaces the contents in the same file instead of creating a new file and then overwrite the file.
https://www.studytonight.com/python-howtos/search-and-replace-a-text-in-a-file-in-python
CC-MAIN-2022-21
refinedweb
610
66.84
Wiki SCons / FindTargetSources To generate a Visual Studio project a list of headers and a list of sources are required, but the builtin Find SourceFiles will only find sources, not headers used by those sources. These can be entered manually, or automatically grabbed from the output of a Shared Library/StaticLibrary/Program/Object builder so that they will automatically be updated when the targets change (perhaps by configuration, perhaps by adding new sources to the target). Here is the code to provide such a functionality, and an example on how it can be used: import SCons def FindAllSourceFiles(self, target): def _find_sources(tgt, src, hdr, all): for item in tgt: if SCons.Util.is_List(item): _find_sources(item, src, hdr, all) else: if item.abspath in all: continue all[item.abspath] = True if item.path.endswith('.c'): if not item.exists(): item = item.srcnode() src.append(item.abspath) elif item.path.endswith('.h'): if not item.exists(): item = item.srcnode() hdr.append(item.abspath) else: lst = item.children(scan=1) _find_sources(lst, src, hdr, all) sources = [] headers = [] _find_sources(target, sources, headers, {}) return sources, headers from SCons.Script.SConscript import SConsEnvironment # just do this once SConsEnvironment.FindAllSourceFiles = FindAllSourceFiles env = Environment() prog = env.Program('foo', ['main.c', 'foo.c', 'bar.c']) sources, headers = env.FindAllSourceFiles(prog) env.MSVSProject( ..., ..., srcs = sources, incs = headers, ..., ... ) This version adds .c-files to sources and .h-files to headers, append checks for whatever sources you have ('.cpp', '.cc', '.hpp' for example). Worth noting is that it adds a performance penalty compared to having a static list of headers/sources, but in some cases it makes very much sense in having generated Visual Studio projects. The penalty is of course related to the number of files in the project, how many diffrent file types that should be included, but should be very low for most projects. NOTE: As of SCons snapshot release 20070918 implicit command dependencies are enabled. This will add more nodes (dependencies on the tools) to be processed thus degrading the performance quite a bit. To disable this, do the following: env = Environment(IMPLICIT_COMMAND_DEPENDENCIES = 0) Here is a more general version that accepts a list of file extensions as argument. It's slightly slower than the above version (may have room for improvements) but still much faster than the SCons Find SourceFiles. Failsafe input checks should be added. def FindAllSourceFiles(self, target, *args): def _find_sources(ptrns, tgt, all): for item in tgt: if SCons.Util.is_List(item): _find_sources(ptrns, item, all) else: if item.abspath in all: continue all[item.abspath] = True for pattern, lst in ptrns.items(): if pattern.match(item.path): if not item.exists(): item = item.srcnode() lst.append(item.abspath) break else: lst = item.children(scan=1) _find_sources(ptrns, lst, all) patterns = {} for arg in args: patterns[re.compile('.+\\.('+'|'.join(arg) + ')$', re.IGNORECASE)] = [] _find_sources(patterns, target, {}) return patterns.values() from SCons.Script.SConscript import SConsEnvironment # just do this once SConsEnvironment.FindAllSourceFiles = FindAllSourceFiles env = Environment() prog = env.Program('foo', ['main.c', 'foo.c', 'bar.c', 'baz.s']) sources, headers = env.FindAllSourceFiles(lib, ['c', 's'], ['h']) Updated
https://bitbucket.org/scons/scons/wiki/FindTargetSources
CC-MAIN-2015-48
refinedweb
512
53.07
Dear Community, ich have problems to control my stepper with the TOS-100 shield. I’m using a Arduino Uno, Trinamic TOS-100 and a Nanotec Stepper When I use the example sketch from the TOS the motor is running. Now I tried to write my own. My problem is now that the motor rotates continuously. If I add a delay of 2000ms the motor does not rotate, but is buzzing only. If I add a stop, I have the same problem. The motor should rotate 200 steps, then stop and turn back to 2000ms 200 steps. Maybe you could help me to find my fault. Looking foreward to your answers Kind regards Timm The Code looks like: #include <SPI.h> #include <TMC26XStepper.h> //we have a stepper motor with 200 steps per rotation, CS pin 2, dir pin 6, step pin 7 and a current of 300mA //TMC26XStepper tmc26XStepper = TMC26XStepper(200,2,6,7,900); TMC26XStepper tmc26XStepper = TMC26XStepper(200,2,6,7,900); int curr_step; int speed = 0; int speedDirection = 100; int maxSpeed = 1000; void setup(){ tmc26XStepper.setSpreadCycleChopper(2,24,8,6,0); tmc26XStepper.setRandomOffTime(0); tmc26XStepper.setMicrosteps(32); tmc26XStepper.setStallGuardThreshold(4,0); tmc26XStepper.setSpeed(30); // Motorgeschwindigkeit 30rpm tmc26XStepper.start(); } void loop(){ tmc26XStepper.step(200); tmc26XStepper.move(); //Starte Motor }
https://forum.arduino.cc/t/problems-to-control-the-trinamic-tos-100-motor-shield/192769
CC-MAIN-2021-43
refinedweb
210
58.69
/* * .h 8.3 (Berkeley) 4/4/95 */ #ifndef _SYS_PARAM_H_ #define _SYS_PARAM_H_ #define BSD 199506 /* System version (year & month). */ #define BSD4_3 1 #define BSD4_4 1 #define NeXTBSD 1995064 /* NeXTBSD version (year, month, release) */ #define NeXTBSD4_0 0 /* NeXTBSD 4.0 */ #include <sys/_types.h> #ifndef NULL #define NULL __DARWIN_NULL #endif /* ! NULL */ #ifndef LOCORE #include <sys/types.h> #endif /* * Machine-independent constants (some used in following include files). * Redefined constants are from POSIX 1003.1 limits file. * * MAXCOMLEN should be >= sizeof(ac_comm) (see <acct.h>) * MAXLOGNAME should be >= UT_NAMESIZE (see <utmp.h>) */ #include <sys/syslimits.h> #define MAXCOMLEN 16 /* max command name remembered */ #define MAXINTERP 64 /* max interpreter file name length */ #define MAXLOGNAME 255 /* max login name length */ #define MAXUPRC CHILD_MAX /* max simultaneous processes */ #define NCARGS ARG_MAX /* max bytes for an exec function */ #define NGROUPS NGROUPS_MAX /* max number groups */ #define NOFILE 256 /* default max open files per process */ #define NOGROUP 65535 /* marker for empty group set member */ #define MAXHOSTNAMELEN 256 /* max hostname size */ #define MAXDOMNAMELEN 256 /* maximum domain name length */ /* Machine type dependent parameters. */ #include <machine/param.h> /* More types and definitions used throughout the kernel. */ #ifdef KERNEL #include <machine/limits.h> #include <sys/cdefs.h> #include <sys/errno.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/ucred.h> #include <sys/uio.h> #else #include <limits.h> #endif /* Signals. */ #include <sys/signal.h> /* * Priorities. Note that with 32 run queues, differences less than 4 are * insignificant. */ #define PSWP 0 #define PVM 4 #define PINOD 8 #define PRIBIO 16 #define PVFS 20 #define PZERO 22 /* No longer magic, shouldn't be here. XXX */ #define PSOCK 24 #define PWAIT 32 #define PLOCK 36 #define PPAUSE 40 #define PUSER 50 #define MAXPRI 127 /* Priorities range from 0 through MAXPRI. */ #define PRIMASK 0x0ff #define PCATCH 0x100 /* OR'd with pri for tsleep to check signals */ #define PTTYBLOCK 0x200 /* for tty SIGTTOU and SIGTTIN blocking */ #define PDROP 0x400 /* OR'd with pri to stop re-aquistion of mutex upon wakeup */ #define PSPIN 0x800 /* OR'd with pri to require mutex in spin mode upon wakeup */ #define NBPW sizeof(int) /* number of bytes per word (integer) */ #define CMASK 022 /* default file mask: S_IWGRP|S_IWOTH */ #define NODEV (dev_t)(-1) /* non-existent device */ /* * Clustering of hardware pages on machines with ridiculously small * page sizes is done here. The paging subsystem deals with units of * CLSIZE pte's describing NBPG (from machine/param.h) pages each. */ #define CLBYTES (CLSIZE*NBPG) #define CLOFSET (CLSIZE*NBPG-1) /* for clusters, like PGOFSET */ #define claligned(x) ((((int)(x))&CLOFSET)==0) #define CLOFF CLOFSET #define CLSHIFT (PGSHIFT+CLSIZELOG2) #if CLSIZE==1 #define clbase(i) (i) #define clrnd(i) (i) #else /* Give the base virtual address (first of CLSIZE). */ #define clbase(i) ((i) &~ (CLSIZE-1)) /* Round a number of clicks up to a whole cluster. */ #define clrnd(i) (((i) + (CLSIZE-1)) &~ (CLSIZE-1)) #endif #define CBLOCK 64 /* Clist block size, must be a power of 2. */ #define CBQSIZE (CBLOCK/NBBY) /* Quote bytes/cblock - can do better. */ /* Data chars/clist. */ #define CBSIZE (CBLOCK - sizeof(struct cblock *) - CBQSIZE) #define CROUND (CBLOCK - 1) /* Clist rounding. */ /* * File system parameters and macros. * * The file system is made out of blocks of at most MAXPHYS units, with * smaller units (fragments) only in the last direct block. MAXBSIZE * primarily determines the size of buffers in the buffer pool. It may be * made larger than MAXPHYS without any effect on existing file systems; * however making it smaller may make some file systems unmountable. * We set this to track the value of (MAX_UPL_TRANSFER*PAGE_SIZE) from * osfmk/mach/memory_object_types.h to bound it at the maximum UPL size. */ #define MAXBSIZE (256 * 4096) #define MAXPHYSIO MAXPHYS #define MAXFRAG 8 #define MAXPHYSIO_WIRED (16 * 1024 * 1024) /* * MAXPATHLEN defines the longest permissable path length after expanding * symbolic links. It is used to allocate a temporary buffer from the buffer * pool in which to do the name expansion, hence should be a power of two, * and must be less than or equal to MAXBSIZE. MAXSYMLINKS defines the * maximum number of symbolic links that may be expanded in a path name. * It should be set high enough to allow all legitimate uses, but halt * infinite loops reasonably quickly. */ #define MAXPATHLEN PATH_MAX #define MAXSYMLINKS 32 /* Bit map related macros. */ #define setbit(a,i) (((char *)(a))[(i)/NBBY] |= 1<<((i)%NBBY)) #define clrbit(a,i) (((char *)(a))[(i)/NBBY] &= ~(1<<((i)%NBBY))) #define isset(a,i) (((char *)(a))[(i)/NBBY] & (1<<((i)%NBBY))) #define isclr(a,i) ((((char *)(a))[(i)/NBBY] & (1<<((i)%NBBY))) == 0) /* Macros for counting and rounding. */ #ifndef howmany #define howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) #endif #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) #define powerof2(x) ((((x)-1)&(x))==0) /* Macros for min/max. */ #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif /* MIN */ #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif /* MAX */ /* *) /* * Scale factor for scaled integers used to count %cpu time and load avgs. * * The number of CPU `tick's that map to a unique `%age' can be expressed * by the formula (1 / (2 ^ (FSHIFT - 11))). The maximum load average that * can be calculated (assuming 32 bits) can be closely approximated using * the formula (2 ^ (2 * (16 - FSHIFT))) for (FSHIFT < 15). * * For the scheduler to maintain a 1:1 mapping of CPU `tick' to `%age', * FSHIFT must be at least 11; this gives us a maximum load avg of ~1024. */ #define FSHIFT 11 /* bits to right of fixed binary point */ #define FSCALE (1<<FSHIFT) #endif /* _SYS_PARAM_H_ */
http://opensource.apple.com//source/xnu/xnu-2050.18.24/bsd/sys/param.h
CC-MAIN-2016-44
refinedweb
911
56.55
Mod_Python has a StringField class and psycopg2 can't seem to adapt it correctly. Type(stringfield_string) shows as: <class 'mod_python.util.StringField'> Strings of this class have 3 extra items in dir(stringfield_string) which regular strins don't have: '__dict__', '__module__', 'value' Here's the class definition from mod_python.util: class StringField(str): """ This class is basically a string with a value attribute for compatibility with std lib cgi.py """ def __init__(self, str=""): str.__init__(self, str) self.value = self.__str__() How do I make psycopg2 deal with these correctly? It seems like there's a way to make custom "adapters" but I'm rather clueless here. I just need psycopg2 to run str() on the StringField instance and it'd work great. Cordially, Scott
http://modpython.org/pipermail/mod_python/2005-December/019694.html
CC-MAIN-2018-39
refinedweb
126
67.76
Rename is a refactoring operation that provides an easy way to rename identifiers for code symbols such as fields, local variables, methods, namespaces, properties, and types. Rename can be used to change the names in comments and in strings in addition to the declarations and calls of an identifier. When using Source Control for Visual Studio, get the latest version of sources before attempting to perform Rename refactoring. Rename refactoring is available from the following Visual Studio features: Code Editor In the Code Editor, rename refactoring is available when you position the cursor on the code symbol declaration. When the cursor is in this position, you can invoke the Rename command by typing the keyboard shortcut, or by selecting the Rename menu item from a smart tag, context menu, or the Refactor menu. When you select the Rename menu item, the Rename dialog box appears. For more information, see Rename Dialog Box and How to: Rename Identifiers. Class View When you select an identifier in Class View, rename refactoring is available from the context menu and Refactor menu. Object Browser When you select an identifier in Object Browser, rename refactoring is only available from the Refactor menu. Property Grid of the Windows Forms Designer In the Property Grid of the Windows Forms Designer, changing the name of a control will initiate a rename operation for that control. The Rename dialog box will not appear. Solution Explorer In Solution Explorer, a Rename command is available on the context menu. If the selected source file contains a class whose class name is the same as the file name, then you can use this command to simultaneously rename the source file and execute rename refactoring. For example, if you create a default Windows application and then rename Form1.cs to TestForm.cs, then the source file name Form1.cs will change to TestForm.cs and the class Form1 and all references to that class will be renamed to TestForm. The Undo command (CTRL+Z) will only undo rename refactoring within the code and will not change the file name back to the original name. If the selected source file does not contain a class whose name is the same as the file name, then the Rename command in Solution Explorer will only rename the source file and will not execute rename refactoring. When you execute Rename, the refactoring engine performs a rename operation specific for each code symbol, described in the following table. Field Changes the declaration and usages of the field to the new name. Local variable Changes the declaration and usages of the variable to the new name. Method Changes the name of the method and all references to that method to the new name. Namespace Changes the name of the namespace to the new name in the declaration, all using statements, and fully qualified names. When renaming a namespace, Visual Studio also updates the Default Namespace property on the Application Page of the Project Designer. This property cannot be reset by selecting Undo from the Edit menu. To reset the Default Namespace property value, you must edit the property in the Project Designer. Property Changes the declaration and usages of the property to the new name. Type Changes all declarations and all usages of the type to the new name, including constructors and destructors. For partial types, the rename operation will propagate to all parts. When you Rename a member that either implements/overrides or is implemented/overridden by members in other types, Visual Studio displays a dialog box that says the rename operation will result in cascading updates. If you click continue, the refactoring engine recursively finds and renames all members in base and derived types that have implements/overrides relationship with the member being renamed. The following code example contains members with implements/overrides relationship. interface IBase { void Method(); } public class Base { public void Method() { } public virtual void Method(int i) { } } public class Derived : Base, IBase { public new void Method() { } public override void Method(int i) { } } public class C : IBase { public void Method() { } } In the example above,). When you rename a member that was defined in a referenced assembly, a dialog box explains that renaming will result in build errors.
http://msdn.microsoft.com/en-us/library/6kxxabwd(VS.80).aspx
crawl-002
refinedweb
702
51.99
, We have most of the changes ready and have been waiting for your response to Enio's two comments on 01 MAR 2005 before implementing the rest of them. Would it be OK if we resubmitted the already agreed to changes and do the following for now: Take advantage of the existing --reset and --save options of opcontrol by the following placement of our files:. Modify the --dump option of opcontrol, and possibly --stop and --shutdown, to invoke a standalone program that calls libopjdl.so to create the dummy ELF files. This would eliminate the need to modify opreport. Scott WBI Performance II IBM Corp, Austin, TX Reply to: stjones@... Phone: (512) 838-4758, T/L: 678-4758. -- Philippe Elie Philippe Elie wrote: >. > Great, will get going on the code ... Enio. On Mon, Mar 07, 2005 at 03:13:28PM -0600, Scott T Jones wrote: > John, > > We have most of the changes ready and have been waiting for your response > to Enio's > two comments on 01 MAR 2005 before implementing the rest of them. Sorry for my tardiness, I'm currently net.dead most of the time so haven't been able to look closely at this thread. As a result, please let Phil decide on the best course (and integrate as necessary). Hopefully later I'll take a proper look at these issues and see if we can reach a conclusion to the design issues. (Note I'll be expecting a certain amount of after-care if the patch goes in anyway...) regards john On Thu, Mar 17, 2005 at 01:43:13AM +0100, Philippe Elie wrote: > I need first to release 0.8.2 before applying this patch, probably > this week-end. I'll submit the kernel patch to -mm tree after. Great. Can you remember to do everything on releasechecklist in oprofile-tests? cheers john On Tue, Mar 15, 2005 at 04:39:08PM -0700, Scott T Jones wrote: > The patch changes configure.in and uses libtool to build libopjdl.so and > libopjan.so. Therefore, after applying the patch, you must execute > "libtoolize" to initialize libtool If this is always necessary, then it needs to be part of autogen.sh. I should be able to take a cvs checkout, do autogen.sh, then configure, and make. Your patch is missing documentation. We need a new section in the user guide, and preferably updates to internals.xml. Have you given any thought to using the new code to support summary values for general anonymous regions (non-Java) ? See TODO. Not necessary for now. Missing ChangeLog. The below comments are not comprehensive, but certainly need fixing. diff -prauN oprofile-0.8.1-shiplevel/AUTHORS oprofile-diff/AUTHORS --- oprofile-0.8.1-shiplevel/AUTHORS 1969-12-31 19:00:00.000000000 -0500 +++ oprofile-diff/AUTHORS 2005-02-07 14:29:57.000000000 -0600 @@ -0,0 +1 @@ +Scott T Jones, Enio Pineda, and the OProfile authors Still contains these pointless additional files. Please remove them from the patch. +dnl disable code for Java Address-to-Name support +AC_ARG_ENABLE(opjan, + [ --disable-opjan disable Java Address-to-Name support (default is enabled)], + enable_opjan=$enableval, enable_opjan=yes) Obscure. Please call it '--disable-java' and say "disable Java support". + /usr/lib/libbfd.so \ See pp/Makefile.am for @BFD_LIBS@, we can't use a specific path for libbfd. +/* generate name for anonymous image pseudo-ELF file */ +static char const * get_anon_file_name(pid_t tgid) +{ + char fn[32], buf[256]; + char * name = NULL; + FILE * fd; + + sprintf(fn,"/proc/%d/status",tgid); snprintf, and elsewhere + fd = fopen(fn,"r"); + if (fd) { + while (fgets(buf,256,fd) != NULL) { + if (sscanf(buf, "Name: %s", fn) == 1) { + name = fn; + break; + } + } + fclose(fd); + } + sprintf(buf,"%s%d/anon-",OP_ANON_PATH,tgid); + if (name) { + char *p = name; + /* change '/' in process names to '#' */ + while (*p) { When do we get '/' in process names? + strcat(buf,name); In all code: space after commas. Please follow the coding style. + static char * mangle_filename(struct sfile * last, struct sfile const * sf, int counter, int cg) { @@ -60,7 +97,12 @@ mangle_filename(struct sfile * last, str values.image_name = sf->kernel->name; values.flags |= MANGLE_KERNEL; } else { - values.image_name = find_cookie(sf->cookie); + if (sf->cookie == NO_COOKIE) { + /* anonymous: need to generate name based on pid */ + values.flags |= MANGLE_ANON; + values.image_name = get_anon_file_name(sf->tgid); + } else + values.image_name = find_cookie(sf->cookie); When one clause has braces, all clauses should have them. #include "op_libiberty.h" +#include <op_jdl.h> Why '<>' not '""' ? /* absolute value -> offset */ if (trans->current->kernel) pc -= trans->current->kernel->start; + else { + if (trans->cookie == NO_COOKIE) { + /* anonymous sample - try to convert to offset */ + pc = op_jit_vma_to_offset(trans->tgid, (jitvma_t)pc); + } + } Braces as before (and probably elsewhere). diff -prauN oprofile-0.8.1-shiplevel/libopjan/Makefile.am oprofile-diff/libopjan/Makefile.am --- oprofile-0.8.1-shiplevel/libopjan/Makefile.am 1969-12-31 19:00:00.000000000 -0500 +++ oprofile-diff/libopjan/Makefile.am 2005-02-24 09:52:23.000000000 -0600 @@ -0,0 +1,16 @@ +# IBM JIT Address to Name Remove pointless comment. + * Change History + * ************** + * + * Vers When Who Why + * ---- -------- ---------- ---------------------------------------- + * 1.00 11/30/04 Enio First crack at it + * 1.01 12/04/04 Enio Allow compile with IBM or SUN jvmpi.h + * 1.00 20050201 stjones Renamed OPJAN - OProfile Jit Address-to-Name + * 1.01 20050216 Enio - Remove IBM-only events + * - Free class/method blocks on class unload + * - Don't request compile method unload event + * - Some cleanup Remove this stuff, it's pointless. +/* + * Globals + */ +/* + * Local prototypes: required initialization entry point + */ +/* + * Local prototypes: event handlers + */ +/* + * msg() + */ Ditto (and many other places). Comments should either explain tricky bits, or document an API. The fact that these are local prototypes is plainly obvious. Please go over all your comments and remove those that are simply equivalent to the code below. + (jiface->ProfilerExit)(exitcode); jiface->ProfilerExit(exitcode); please. + /* We never return from ProfilerExit() because the JVM terminates */ + return; Remove the return; - and elsewhere. +/* + * parse_options() + * + * Here as an example, in case we ever want to add options. Please don't introduce dead code. + + * JVM_OnLoad() + * + * Exported entry point called by the JVM when a profiler is specified + * via the -Xrun java command line option. It is an opportunity for us + * to do some initialization and to parse the options passed to the + * profiler. The rest of the initialization will be done when we get + * the JVM_INIT_DONE event. This is an example of a more useful comment :) + /* Get environment and JVMPI Interface pointers from JVM */ + rc = (* jvm)->GetEnv(jvm, (void **)(void*)&jiface, JVMPI_VERSION_1); spacing. + switch(je->event_type) { spacing. + case JVMPI_EVENT_JVM_INIT_DONE: + /* + * Called by the JVM after it finishes initialization + * but before it starts executing java code. + */ Nit - move these comments to above the 'case...' lines, where it makes sense to keep them. + grab_lock(class_hash_lock); + if (class_hash[index] == NULL) { + cn->hash_next = NULL; + } + else { Formatting (and elsewhere). + /* Remove class node from class hash list */ + if (cn->hash_prev == NULL) { + /* Remove first (and possibly only) element in chain */ + int index = hash_function(cn->id, CLASS_HASH_SIZE); + class_hash[index] = cn->hash_next; + if (cn->hash_next) { + cn->hash_next->hash_prev = NULL; + } + } + else if (cn->hash_next == NULL) { + /* Remove last element in chain */ + cn->hash_prev->hash_next = NULL; + } + else { + /* Remove elemement somewhere in the middle of the chain */ + cn->hash_prev->hash_next = cn->hash_next; + cn->hash_next->hash_prev = cn->hash_prev; + } We really don't need so many comments to explain a simple linked list implementation! Never mind that we have op_list.h - why can't you use that? + mname_len = strlen(mn->class->name) + + 1 + + strlen(mn->name) + + strlen(mn->signature) + + 1; Eww... + //msg(stdout, "%05d: 0x%08x %05d %s\n",tgid, (uintptr_t)code_addr, code_size, mname); It drives me mad when people have commented out with no explanation of why. Either remove the dead code or add a comment explaining why it's not live. +/* + * Shared object initialization + * + * In case we ever want to do something at load time. + */ +void __attribute__ ((constructor)) my_init(void) +{ + return; +} + + +/* + * Shared object termination + * + * In case we ever want to do something at unload time. + */ +void __attribute__ ((destructor)) my_fini(void) +{ + return; +} Why? +#ifndef H_OPJAN +#define H_OPJAN This isn't what oprofile header guards look like. +/* read entries file and table up symbols by section */ +static int read_symbols(FILE *entries_fd, msection_info_t ** si) Spacing. + while (fscanf(entries_fd, "%lx %lx %d %s", &symvma, &symlen, &symsec, symname) != EOF) { This line looks too long? + if (sym == NULL) { + return 0; + } Avoid braces for such simple one-line clauses. + unsigned long largest_section; size_t ? + for (i = 0; i < rfd->cnt; i++) { + si[i] = malloc(sizeof(msection_info_t)); + if (si[i] == NULL) { + free(section_data); + return NULL; + } This code leaks on malloc failure? +/* build symbol information needed to write ELF file later */ +static int build_symbols_for_section(int s, msection_info_t ** si, + bfd * abfd, asymbol ** symbols, + int start) See coding style. + syms = (asymbol **)malloc(sizeof(asymbol *) * (sym_cnt + 1)); Don't cast malloc return in C please. + if (syms) { + free(syms); + } just free(syms); unconditionally. +/* check whether file/directory is writable */ +static int is_writable(char * name) +{ + if (access(name, W_OK) == 0) + return 1; + else + return 0; +} + + +/* create directory (if it doesn't exist) */ +int create_dir(char * dn) +{ + if (is_writable(dn)) { + return 0; + } + mkdir(dn, (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); + if (is_writable(dn)) + return 0; + else + return -1; +} Generic stuff should be in libutil. I'm sure we must already have something for creating directories. access() checks are always pointless. + * @remark Copyright 2002, 2003 OProfile authors I suppose the copyrights should have the right date on them if they're there... +#ifndef OP_JDL_H +#define OP_JDL_H Shouldn't we have one header file for use by JITs, and one for oprofile? +#include <op_config.h> "" ? +struct _memory_range { Why the _ prefix? This is already an internal header file? +#if defined(__i386__) + #define X_ARCH bfd_arch_i386 + #define X_MACH bfd_mach_i386_i386 +#elif defined(__x86_64__) + #define X_ARCH bfd_arch_i386 + #define X_MACH bfd_mach_x86_64 +#elif defined(__ia64__) + #define X_ARCH bfd_arch_ia64 + #define X_MACH bfd_mach_ia64_elf64 +#elif defined(__powerpc__) + #define X_ARCH bfd_arch_powerpc + #define X_MACH bfd_mach_ppc +#elif defined(__powerpc64__) + #define X_ARCH bfd_arch_powerpc + #define X_MACH bfd_mach_ppc64 +#elif defined(__s390__) + #define X_ARCH bfd_arch_s390 + #define X_MACH bfd_mach_s390_31 +#elif defined(__s390x__) + #define X_ARCH bfd_arch_s390 + #define X_MACH bfd_mach_s390_64 +#else + #error ***** op_jdl_internal.h: undefined architecture ***** +#endif Do we really have to do this ourselves?? --- oprofile-0.8.1-shiplevel/libpp/locate_images.cpp 2004-07-06 16:43:07.000000000 -0500 +++ oprofile-diff/libpp/locate_images.cpp 2005-02-07 14:29:57.000000000 -0600 @@ -17,6 +17,7 @@ #include <sstream> #include <cstdlib> + Spurious whitespace change using namespace std; @@ -99,6 +100,12 @@ string const find_image_path(string cons image_error & error) { string const image = op_realpath(archive_path + image_name); + int tgid = op_file_is_anon(image); pid_t ? diff -prauN oprofile-0.8.1-shiplevel/libutil/op_file.c oprofile-diff/libutil/op_file.c --- oprofile-0.8.1-shiplevel/libutil/op_file.c 2004-05-29 12:03:01.000000000 -0500 +++ oprofile-diff/libutil/op_file.c 2005-03-11 11:19:04.000000000 -0600 @@ -21,6 +21,45 @@ #include "op_file.h" #include "op_libiberty.h" +#include "op_config.h" +#include <op_jdl.h> + + + +/** + * check if file is in /var/lib/oprofile/samples/current/{anon} directory. + * - If file is a fake ELF image (anon-name.tgid) it returns the tgid. + * - If file is a temporary file (entries or ranges) it returns -1. + * - Anything else it returns 0. + */ +int op_file_is_anon(char const * file) +{ + int tgid = 0; + char * p; + + if (strncmp(file, OP_ANON_PATH, strlen(OP_ANON_PATH)) == 0) { + p = strrchr(file,'.'); + if (p) { + /* looks like a fake ELF image */ + tgid = atoi(++p); + } + else { + /* looks like one of the temporary files */ + tgid = -1; + } + } + return tgid; +} OProfile specific code goes in libop[++], not libutil[++]. diff -prauN oprofile-0.8.1-shiplevel/utils/opcontrol oprofile-diff/utils/opcontrol --- oprofile-0.8.1-shiplevel/utils/opcontrol 2004-07-06 17:20:44.000000000 -0500 +++ oprofile-diff/utils/opcontrol 2005-03-10 17:40:10.000000000 -0600 @@ -1171,6 +1171,7 @@ do_reset() # daemon use {kern} and {root} subdir, it's not a typo to not use ${} move_and_remove $SAMPLES_DIR/current/{kern} move_and_remove $SAMPLES_DIR/current/{root} + move_and_remove $SAMPLES_DIR/current/{anon} What about oparchive? regards john On Thu, Mar 31, 2005 at 10:48:25AM -0800, John, Reeja wrote: >. > I got something similar (in vfprintf, then commenting out the msg() code, I got another crash). Doesn't seem to work too well but I have no idea what the problem is yet... john Ree week. Thanks again for the information. Scott WBI Performance II IBM Corp, Austin, TX Reply to: stjones@... Phone: (512) 838-4758, T/L: 678-4758 oprofile-list-admin@... wrote on 03/31/2005 12:48:25 PM: >. > >@... [mailto:oprofile- > list-admin@...]On Behalf Of Scott T Jones > Sent: Monday, February 07, 2005 4:04 PM > To: oprofile-list@... > Subject: RE: oprofile and jitted code -- proposal 1 > > > This patch adds two new functions to OProfile. First, it adds the ability > to resolve addresses in anonymous processes, by integrating libopjdl.so > into OProfile. This builds upon the patch previously provided by Will > Cohen. Second, it provides a Java profiler, libopjan.so, which resolves > the names of Java jitted methods, when combined with the first feature. > This implements the following proposal on the oprofile-list: > > > >. > > A compatible level of jvmpi.h (IBM or Sun 1.3 or above) must be copied to > the libopjan directory before libopjan.so can be successfully built. The > new configure script will copy this file from $JDKDIR/include if the JDKDIR > environment variable has been set to the directory of the active JDK. > Note that libopjan.so is built using libtool, the presence of which is > tested at configure time. > >@... > Phone: (512) 838-4758, T/L: 678-4758[attachment "hs_err_pid31378. > log" deleted by Scott T Jones/Austin/IBM] 10:04:28AM -0500, Scott T Jones wrote: > #. Ah yes. Though I doubt there's any Java kernel daemons, the code probably makes sense as is. regards john On Wed, Apr 13, 2005 at 09:41:46PM +0100, John Levon wrote: > A straw-man for this liboprofileclient API: Actually, libagent, plus op_agent_id etc. would probably be much better. regards john John, thanks for the heads up... I *am* monitoring this list, but so far I just had no time to do real work on this front. > It's vital that we do this so that we can change the temporary file > approach if we need to. I'm thinking in particular of using shared > memory between the dynamic code library and oprofiled, or other IPC > methods. This would be *very* nice... > It sucks that we require java to be run as root. With another IPC method > we have the ability to have greater control. I'm not sure what much we > can do security wise. Suggestions here are welcome. ...also as a way to fix this requirement to run the VM as root! Running an application as root to be able to profile it is just plain wrong; one of the things I like about oprofile is that it is unobtrusive, you can profile your system "as it usually runs". And not may applications run as root. About the security implications, I would not be so pedantic. Not because security does not matter, but let's look at the whole thing from a high level... we have two "systems": - The profiled VM (be it the JVM or Mono) - oprofile Basically the VM tells oprofile where its methods (executable memory sections) are located in its address space. It is theoretically possible that knowledge of these data could make an exploit of the VM easier, but this exploit should be based on an *existing* VM weakness. So the problem is not that urgent. Moreover, how could a potential attacker get access to those data? Currently, he should be root, and at that point you are lost anyway. Probably, in a cleaner scenario (the VM runs as a regular user, and oprofile still runs as root), the "shared resource" that the VM uses to communicate with oprofile should be created with the right user permissions, and everything would be OK. Since oprofile knows the tgid of the VM, he is in the right position to arrange things in the correct way (I mean create the shared thing with the correct settings, be it a file or a shared memory area). Again, if an attacker is in a position in which he can bypass this kind of permissions, you are lost anyway. Finally, if I got it right, it is anyway a specific user choice to start the VM so that it would communicate with oprofile. By doing so, the user is implicitly trusting the installation of both systems (the VM and oprofile), so tricks like having a modified libopjan are ruled out (and again, at that point you would be lost anyway!). In the end, it seems worse running the whole VM as root than making a simple (somewhat secure) IPC channel from the VM to oprofile, so that the VM can run as a regular user. But I am digressing, this message should have not been about security and running the VM as root. > We really want to make this "tell oprofile about our mappings" to be > fall-over-easy to implement for Mono etc. Of course I second this ;-) In fact, so far I've been following this thread, but I simply could not understand all the details, so I could not understand how I could fit Mono in this scheme. I just thought it was my fault, as I said I'm not devoting much time to this... > A straw-man for this liboprofileclient API: > [simple API snipped] Well, this simple API makes perfect sense to me! If somebody is going to implement this, I could really hack oprofile support into Mono fast, at the very least to check that the approach is working. Honestly, in all the previous mails in this thread I just could not figure out where the borderline between the VM and oprofile lied. >From the JVM point of view it was libopjan, but obviously this is a JVM specific thing. Otherwise the interface seemed to be the temporary file, but (as John is saying) this is just too low level. >). I really, really second this. Please go in this direction ;-) And in any case thanks a lot for all your work! Ciao, Massi On Thu, Apr 14, 2005 at 08:58:56AM +0200, Massimiliano Mantione wrote: > Basically the VM tells oprofile where its methods (executable > memory sections) are located in its address space. > It is theoretically possible that knowledge of these data could > make an exploit of the VM easier, but this exploit should be based > on an *existing* VM weakness. It's not an exploit of the VM that's a worry, you have it upside down. The problem is that the VMs are unprivileged, and oprofiled has no way of knowing who to trust. A naive approach lets anybody sign on as an agent and start telling oprofiled about mappings. This means we'd need to be very careful not to let oprofiled be a DoS victim. And of course, there are race conditions: an unprivileged attacker could claim a tgid before the VM has a chance to, which is an obvious data corruption issue. The best solution I have so far is to traverse the parent-pid tree and ensure that the agent in some way "owns" the PID. This might be good enough. There are still DoS opportunities but with careful limits we might be OK. > Well, this simple API makes perfect sense to me! That's encouraging. > If somebody is going to implement this, I could really hack oprofile > support into Mono fast, at the very least to check that the approach > is working. It's essentially already implemented, it's mostly an issue of code reorganisation. One thing I didn't touch on is debug info: I assume Mono has an interface for that? We'd need some way of telling oprofiled the <mapping-offset> : <filename, line number> tuples. regards john On Thu, 2005-04-14 at 13:26 +0100, John Levon wrote: > It's not an exploit of the VM that's a worry, you have it upside down. Uh oh... sorry, now I get the point. > > If somebody is going to implement this, I could really hack oprofile > > support into Mono fast, at the very least to check that the approach > > is working. > > It's essentially already implemented, it's mostly an issue of code > reorganisation. Well, as things are I just haven't the time to understand that code. But given a library with an interface like the one you described I could start using it without problems. > One thing I didn't touch on is debug info: I assume Mono has an > interface for that? We'd need some way of telling oprofiled the > <mapping-offset> : <filename, line number> tuples. I'm afraid there's no clear external interface I know of. But of course we could provide the mappings... You proposed a function like this: /** *? Would it make sense to pass the debug info to oprofile in this call? In any case, again this is just an issue of having a clear interface. And since the interface must not be Mono specific (or Java specific) any public interface provided by Mono to access debug info should be irrelevant. We should just agree on an interface that oprofile should provide to give debug info for jitted code, then every VM should use that. Ciao, Massi On Thu, Apr 14, 2005 at 05:02:33PM +0200, Massimiliano Mantione wrote: > /** > *? The data for the mapping. Typically, the machine instructions. we don't do it now, but we could then write it to the ELF file and get detailed profiles for each method in terms of instructions. > Would it make sense to pass the debug info to oprofile in this call? Or a op_add_debug_info(op_mapping_id ...) regards john On Tue, Apr 12, 2005 at 06:43:48PM -0600, Scott T Jones wrote: > I am posting this third version of our patch, primarily to fix the problem I'm starting to look at generic anon mapping support, and noticed what appears to be a serious problem with your approach. oprofile's sample files key values are the offset against the binary file at which the instruction can be found. But your code sets the offset for the sample to be the offset against the *mapping*, which has no relation to the location of the symbol's section in the generated ELF file. For example, imagine a sample that's at the very start of the mapping. You're recording the offset as 0 in this case. In terms of file offsets, that's the start of the ELF header! Also: +jitvma_t op_jit_vma_to_offset(pid_t tgid, jitvma_t vma) +{ + int jr; + range_info_t * ri; + + /* find the range information for this tgid */ + ri = find_range_info(tgid); + if (ri == NULL) + return vma; + + /* find range for this vma */ + jr = find_jit_range_for_vma(vma, ri->rfd); + if (jr == -1) + return vma; + + return vma - ri->rfd->range[jr].start; If we have two ranges for the same tgid, then we get an offset value of 0 for two completely distinct VMAs with this code. It's late, but I can't understand how this is possibly working... Unfortunately for us, we can't store raw EIPs into the sample files due to the callgraph files. So we need to rejig things. Me and Phil are currently talking about what changes we need. It's uncomfortable :( regards john I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/oprofile/mailman/oprofile-list/thread/20050219023417.GA22496@compsoc.man.ac.uk/
CC-MAIN-2017-04
refinedweb
3,900
65.93
10-Year History of PPI Inflation: Is There a Case? chart below for the overall PPI annual inflation rates over the last ten years shows a similar pattern: A slight increase in recent months for PPI inflation, but still below the levels in March, April and May, below the 2008-levels, and about the same as the 2004-2005 period. And for the PPI level, 195.5 in February, that's still almost 5% below the peak of 205.5 in July 2008. Q: Based on the data, is there really a strong case for concern about rising PPI inflation? 15 Comments: It could mean slow economic growth instead of inflation. How many more years will it take to reach full employment? You know, we could worry about inflation, dying in a plane crash, getting killed by terrorists, who knows what else hyped up fears. Glenn Beck is carnival-barking about gold, has gold sponsors, so he has inflamed his public of right-wing baboons to screech about inflation. I guess Dallas Fed martinet Richard Fisher is in that particualr troop. Money see-money do. Before we fight inflation, can we please have some old-fashioned prosperity? mark- that is not raw data. is it heavily adjusted. using adjusted data to argue that adjusted data is accurate seems circular. i don't think it proves anything. if we use a non adjusted measure of input inflation over that last 10 years (like the constant commodity index) we see an index that has gone from 180 10 years ago to 635 today, a 252% increase. that annualizes to 13.4% per year. that simply does not square with the heavily manipulated data out of the BLS. look at the most recent PPI number. even using their highly questionable methodology, they cannot mask the blooming inflation.." PPI is up 3.33% in the last 3 months alone. annualize that and you get 14% inflation. you asks if we should be concerned about that? yes. that is 70's style inflation. this result is confirmed by looking at the price data of imports and exports (data which is not manipulated by the BLS) import prices up 1.4% in feb after 1.3% in jan. export prices up 1.2% after 1.3% in jan. these are HUGE numbers and annualize to numbers in the high teens. every objective measure of price is up big and accelerating. how much of this are you willing to ignore to maintain belief in the adjustment process of the BLS? setting your scale to read 20 pounds lighter will not help you fit into your pants. There's little inflation pressure both on the consumption and production sides. On the consumption side, the U.S. still imports more than it exports and domestic demand remains weak. On the production side, productivity is high and input costs remain low (labor is two-thirds of input costs): Output or inflation is a function of technology (or productivity) on labor, capital, raw materials, land, energy, etc.. U.S. Productivity Rose 2.6% In Q4, Labor Costs Fell 0.6% 3/3/2011 Productivity increased by 2.6 percent in the fourth quarter...reflected a modest acceleration from the downwardly revised 2.3 percent increase seen in the third quarter. Unit labor costs fell by 0.6 percent in the fourth quarter...Labor costs were down 0.1 percent year-over-year. Peak Trader- Great numbers. I have been pointing our for two years we have falling unit labor costs. How do you get inflation with falling unit labor costs? Commodities are just not as important as they used to be. We use less and less compared to GDP. Oil use to GDP output has been falling for decades. In the U.S., the future seems to be more natural gas for households and firms to keep the oil flowing for transportation: Oil companies bet future is natural gas November 10, 2010 In the United States and Europe, natural gas is primarily used to heat homes. About three in five American homes use it for heat. And more and more power plants are using it to generate power. Natural gas is used to generate 23percent of electricity in the U.S., up from 16 percent a decade ago. Natural gas is used in small amounts for transportation in the U.S., mostly for city buses and garbage trucks. I don't really care about the price of gold or diamonds going up because I don't use the stuff. substitution is alive and well in the economy All over the world, we have natural gas up our rear ends. There is gobs and gobs of the stuff, thanks to the discovery of shale, and other new sources. You can run cars on methanol (now selling for about $1.28 a gallon) or CNG. The USA has a fantastic opp. to go heavy into natural gas, and radically curtail of involvement in the Middle East. Save hundreds of billions every year on oil imports and military outlays. Oh, why would we do that? peak- productivity numbers are a function of inflation. if you understate inflation, you overstate productivity. you cannot use that figure the way you are trying to. i also question your figure that labor is 2/3 of input costs. that sounds extremely high to me. where are you getting that number? bix- but what about all the other prices? these are the componentsThe Thomson Reuters Equal Weight Continuous Commodity Index is recognized as a major barometer of commodity prices. The index comprises 17 commodity futures that are continuously rebalanced: Cocoa, Coffee ‘C’, Copper, Corn, Cotton, Crude Oil, Gold, Heating Oil, Live Cattle, Live Hogs, Natural Gas, Orange Juice, Platinum, Silver, Soybeans, Sugar No. 11, and Wheat. The index trades on the ICE Futures Exchange. of the constant commodity index: their compound inflation for the last decade has been over 13% a year and that understates the actual inflation as the index gets rebalanced to even %'s each year. surely there are items on that list you care about or do you not eat, drive, or wear clothes? Morganovich, you're making an assumption that's not supported by anything. The quantity and quality of units produced increased with fewer jobs. Here's one example: U.S. Manufacturing: Output vs. Jobs Since 1975 Jan 24, 2011 "Since 1975, manufacturing output has more than doubled, while employment in the sector has decreased by 31%...the average American manufacturer is over three times more productive today than they were in 1975." Also, I may add, after the Creative-Destruction process in the early 2000s, U.S. firms, particularly high-tech firms, produced more output with fewer inputs (e.g. instead of increasing inputs faster than output), which is disinflationary. Labor Productivity and Costs BLS "In the U.S. nonfarm business sector, labor cost represents more than sixty percent of the value of output produced." Over the 1995-00 bubble, inflation averaged 2.5%, and over the 2002-07 bubble, inflation averaged 2.9%. However, in the late '90s, commodity prices fell to low levels (e.g. oil $10 a barrel and gold $250 an ounce). So, there were more powerful factors that influenced the general price level. peak i think it is you who are making unsupported assumptions. the figures you cite are based on nominal output, not units. understate inflation in such a case and it will look like productivity. you then cite a bunch of inflation numbers based on the flawed BLS methodology that was designed to avoid showing inflation. your whole case is based on circular logic. Morganovich, I'm not claiming the aggregate data are wrong and I'm right. The only flaw is incomplete data, e.g. 5% of the puzzle is missing, but that wouldn't significantly change the picture. It's easier to change the pictures of segments of the economy than the picture of the macroeconomy (including the general price level). Links to this post: Create a Link
http://mjperry.blogspot.com/2011/03/10-year-history-of-ppi-inflation-is.html
CC-MAIN-2016-30
refinedweb
1,344
68.47
Technical Support On-Line Manuals CARM User's Guide Discontinued #include <string.h> int strcmp ( const unsigned char *string1, /* first string */ const unsigned char *string2); /* second string */ The strcmp function compares the contents of string1 and string2 and returns a value indicating their relationship. The strcmp function returns the following values to indicate the relationship of string1 to string2: memcmp, strncmp #include <string.h> #include <stdio.h> /* for printf */ void tst_strcmp (void) { unsigned char buf1 [] = "Bill Smith"; unsigned char buf2 [] = "Bill Smithy"; int i; i = strcmp (buf1, buf2); if (i < 0) printf ("buf1 < buf2\n"); else if (i > 0) printf ("buf1 > buf2\n"); else printf ("buf1 == buf.
http://www.keil.com/support/man/docs/ca/ca_strcmp.htm
CC-MAIN-2020-16
refinedweb
107
59.64
don't know where to put this..I'm using MonoDevelop latest stable version on Debian 7. I did try with manualy code mine mainwindow but it seems that this goes completely wrong.. I know there is a graphical box to set the position of the window But I did want to do it manualy. The code I did use: -------------------- using System; using System .Collections .Generic ; using System .Text ; using Gtk; public partial class MainWindow: Gtk.Window { public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); this.button1 .Label = "Use MessageDialog with 1 button"; this .button2 .Label = "Use MessageDialog with 2 buttons"; MainWindow MainWindow =new MainWindow (); MainWindow .SetPosition (WindowPosition .CenterAlways ); } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { Application .Quit (); a.RetVal = true; } protected void OnButton1Clicked (object sender, EventArgs e) { MessageDialog welcome = new MessageDialog (this, DialogFlags .Modal, MessageType.Info, ButtonsType.OkCancel, "The first window you make at Linux with MonoDevelop"); welcome .Title = "Hello Linux..."; ResponseType response = (ResponseType)welcome .Run (); if (response == ResponseType .Ok) { //here we put code when user press OK button welcome .Destroy (); //We want to destroy the message screen welcome } else { //Here you can put code when user press Cancel button. System .Media .SystemSounds .Beep .Play (); //Play system beep sound welcome .Destroy (); //Destroy welcome messagebox } } protected void OnButton2Clicked (object sender, EventArgs e) { MessageDialog welcome = new MessageDialog (this, DialogFlags .Modal, MessageType.Info, ButtonsType .Ok, "The first window you make at Linux with MonoDevelop"); welcome .Title = "Hello Linux..."; welcome .Run (); welcome .Destroy (); } } The code where it goes wrong: MainWindow MainWindow =new MainWindow (); MainWindow .SetPosition (WindowPosition .CenterAlways ); When you try to run this, you have no compiler errors or something like that, but your computer completely FREEZE's.. I think the problem is because I try to use the name MainWindow. The reason why I did try, is because I nowhere can find something to center mine screen, I mean then the MainWindow! I know I can do this graphicaly under the properties from the window,but I want to control it on mine self! How we can do this? Best Regards, Frederik 3.x is outdated - try to build MonoDevelop from master.
https://bugzilla.xamarin.com/12/12852/bug.html
CC-MAIN-2021-39
refinedweb
349
52.05
For back compatability with fltk1.1 Callback is a function pointer to a fltk callback mechanism. It points to any function void foo(Widget*, void*) Function pointer to a callback with only one argument, the widget Function pointer to a callback with a long argument instead of a void argument A pointer to a Callback. Needed for BORLAND fltk::Color is a typedef for a 32-bit integer containing r,g,b bytes and an "index" in the lowest byte (the first byte on a little-endian machine such as an x86). For instance 0xFF008000 is 255 red, zero green, and 128 blue. If rgb are not zero then the low byte is ignored, or may be treated as "alpha" by some code. If the rgb is zero, the N is the color "index". This index is used to look up an fltk::Color in an internal table of 255 colors shown here. All the indexed colors may be changed by using set_color_index(). However fltk uses the ones between 32 and 255 and assummes they are not changed from their default values. (this is not the X colormap used by fltk) A Color of zero (fltk::NO_COLOR) will draw black but is ambiguous. It is returned as an error value or to indicate portions of a Style that should be inherited, and it is also used as the default label color for everything so that changing color zero can be used by the -fg switch. You should use fltk::BLACK (56) to get black. Type of function passed to drawimage(). It must return a pointer to a horizontal row of w pixels, starting with the pixel at x and y (relative to the top-left corner of the image, not to the coordinate space drawimage() is called in). These pixels must be in the format described by type passed to drawimage() and must be the delta apart passed to drawimage(). userdata is the same as the argument passed to drawimage(). This can be used to point at a structure of information about the image. Due to cropping, less than the whole image may be requested. So the callback may get an x greater than zero, the first y passed to it may be greater than zero, and x+w may be less than the width of the image. The passed buffer contains room for at least the number of pixels specified by the width passed to drawimage(). You can use this as temporary storage to construct a row of the image, and return a pointer offset by x into it. Type returned by fltk::Widget::flags() and passed to fltk::Box and many other drawing functions. HelpFunc type - link callback function for files... A Theme is a function called by fltk just before it shows the first window, and also whenever it receives a signal from the operating system that the user's preferences have changed. The Theme's job is to set all the NamedStyle structures to the correct values for the appearance selected by the user and operating system. The return value is ignored but you should return true for future compatability. This pointer is declared as a "C" function to make it easier to load the correct function by name from a plugin, if you would like to write a scheme where the appearance is controlled by plugins. Fltk provides a convienence function to portably load plugins called fltk::load_plugin() that you may want to use if you are writing such a system. Hides whatever the system uses to identify a thread. Used so the "toy" interface is portable. Type of function passed to add_timeout(), add_check(), and add_idle() Numbers passed to Widget::handle() and returned by event(). Values returned by event_key(), passed to event_key_state() and get_key_state(), and used for the low 16 bits of add_shortcut(). The actual values returned are based on X11 keysym values, though fltk always returns "unshifted" values much like Windows does. A given key always returns the same value no matter what shift keys are held down. Use event_text() to see the results of any shift keys. The lowercase letters 'a' through 'z' and the ascii symbols '`', '-', '=', '[', ']', '\', ',', '.', '/', ';', '\'' and space are used to identify the keys in the main keyboard. On X systems unrecognized keys are returned unchanged as their X keysym value. If they have no keysym it uses the scan code or'd with 0x8000, this is what all those blue buttons on a Microsoft keyboard will do. I don't know how to get those buttons on Windows. Flags returned by event_state(), and used as the high 16 bits of Widget::add_shortcut() values (the low 16 bits are all zero, so these may be or'd with key values). The inline function BUTTON(n) will turn n (1-8) into the flag for a mouse button. Device identifier returned by event_device(). This enumeration is useful to get the device type that caused a PUSH, RELEASE, DRAG or MOVE event Values of the bits stored in Widget::layout_damage(). When a widget resized or moved (or when it is initially created), flags are set in Widget::layout_damage() to indicate the layout is damaged. This will cause the virtual function Widget::layout() to be called just before fltk attempts to draw the windows on the screen. This is useful because often calculating the new layout is quite expensive, this expense is now deferred until the user will actually see the new size. Some Group widgets such as fltk::PackedGroup will also use the virtual Widget::layout() function to find out how big a widget should be. A Widget is allowed to change it's own dimensions in layout() (except it is not allowed to change it if called a second time with no changes other than it's x/y position). This allows widgets to resize to fit their contents. The layout bits are turned on by calling Widget::relayout(). Widget::when() values Symbolic names for some of the indexed colors. The 24-entry "gray ramp" is modified by fltk::set_background() so that the color fltk::GRAY75 is the background color, and the others are a nice range from black to a lighter version of the gray. These are used to draw box edges. The gray levels are chosen to be evenly spaced, listed here is the actual 8-bit and decimal gray level assigned by default. Also listed here is the letter used for fltk::FrameBox and the old fltk1.1 names used for these levels. The remiander of the colormap is a 5x8x5 color cube. This cube is used to dither images on 8-bit screens X colormaps to reduce the number of colors used. Values of the bits stored in Widget::damage(). When redrawing your widgets you should look at the damage bits to see what parts of your widget need redrawing. The Widget::handle() method can then set individual damage bits to limit the amount of drawing that needs to be done, and the Widget::draw() method can test these bits to decide what to draw: MyClass::handle(int event) { ... if (change_to_part1) damage(1); if (change_to_part2) damage(2); if (change_to_part3) damage(4); } MyClass::draw() { if (damage() & fltk::DAMAGE_ALL) { ... draw frame/box and other static stuff ... } if (damage() & (fltk::DAMAGE_ALL | 1)) draw_part1(); if (damage() & (fltk::DAMAGE_ALL | 2)) draw_part2(); if (damage() & (fltk::DAMAGE_ALL | 4)) draw_part3(); } Except for DAMAGE_ALL, each widget is allowed to assign any meaning to any of the bits it wants. The enumerations are just to provide suggested meanings. Enumeration describing how colors are stored in an array of bytes that is a pixel. This is used as an argument for fltk::drawimage(), fltk::readimage(), and fltk::Image. Notice that the order of the bytes in memory of ARGB32 or RGB32 is a,r,g,b on a little-endian machine and b,g,r,a on a big-endian machine. Due to the use of these types by Windows, this is often the fastest form of data, if you have a choice. To convert an fltk::Color to RGB32, shift it right by 8 (for ARGB32 shift the alpha left 24 and or it in). More types may be added in the future. The set is as minimal as possible while still covering the types I have actually encountered..: bool state_changed; // anything that changes the display turns this on void check(void*) { if (!state_changed) return; state_changed = false; do_expensive_calculation(); widget->redraw(); } main() { fltk::add_check(1.0,check); return fltk::run(); } Install a function to parse unrecognized events. If FLTK cannot figure out what to do with an event, it calls each of these functions (most recent first) until one of them returns non-zero. If none of them returns non zero then the event is ignored. Currently this is called for these reasons: Add file descriptor fd to listen to. When the fd becomes ready for reading fltk::wait() will call the callback function and then return. The callback is passed the fd and the arbitrary void* argument. The second argument is a bitfield to indicate when the callback should be done. You can or these together to make the callback be called for multiple conditions: Under UNIX any file descriptor can be monitored (files, devices, pipes, sockets, etc.) Due to limitations in Microsoft Windows, WIN32 applications can only monitor sockets (? and is the when value ignored?) Same as add_fd(fd, READ, cb, v);. Add a one-shot timeout callback. The function will be called by fltk::wait() at t seconds after this function is called. The optional void* argument is passed to the callback. Add a series of points to the current path on the arc of an ellipse. The ellipse in inscribed in the l,t,w,h rectangle, and the start and end angles are measured in degrees counter-clockwise from 3 o'clock, 45 points at the upper-right corner of the rectangle. If end is less than start then it draws the arc in a clockwise direction. Add an isolated circular arc to the path. It is inscribed in the rectangle so if it is stroked with the default line width it exactly fills the rectangle (this is slightly smaller than addarc() will draw). If the angles are 0 and 360 a closed circle is added. This tries to take advantage of the primitive calls provided by Xlib and GDI32. Limitations are that you can only draw one, a rotated current transform does not work. Add a series of points on a Bezier spline to the path. The curve ends (and two of the points) are at x,y and x3,y3. The "handles" are at x1,y1 and x2,y2. Add a pie-shaped closed piece to the path, inscribed in the rectangle so if it is stroked with the default line width it exactly fills the rectangle (this is slightly smaller than addarc() will draw). If you want a full circle use addchord(). This tries to take advantage of the primitive calls provided by Xlib and GDI32. Limitations are that you can only draw one per path, that rotated coordinates don't work, and doing anything other than fillpath() will produce unpredictable results. Add a single vertex to the current path. (if the path is empty or a closepath() was done, this is equivalent to a "moveto" in PostScript, otherwise it is equivalent to a "lineto").. Add a whole set of integer vertices to the current path. Add a whole set of vertices to the current path. This is much faster than calling fltk::addvertex once for each point. Adds a whole set of vertcies that have been produced from values returned by fltk::transform(). This is how curve() and arc() are implemented. Same as fltk::message() except for the "!" symbol.. The arguments recognized are listed under args(). The args() argument parser is entirely optional. It was written to make demo programs easy to write, although some minor work was done to make it usable by more complex programs. But there is no requirement that you call it or even acknoledge it's existence, if you prefer to use your own code to parse switches. The second form of fltk::args() is useful if your program does not have command line switches of its own. It parses all the switches, and if any are not recognized it calls fltk::fatal(fltk::help). Consume all switches from argv. To use the switch parser, call fltk::args(argc,argv) may be abbreviated one letter and case is ignored: -iconicWindow::iconize() will be done to the window. -geometryWxH Window is resized to this width & height -geometry+X+Y Initial window position -geometryWxH+X+Y Window is resized and positioned. -displayhost or -displayhost:n.n The X display to use (ignored under WIN32). -namestring will set the Window::label() -bgcolor Call set_background() with the named color. Use "#rrggbb" to set it in hex. -backgroundcolor is the same as -bg color Displays a printf-style message in a pop-up box with an "Yes" and "No" button and waits for the user to hit a button. The return value is 1 if the user hits Yes, 0 if they pick No. The enter key is a shortcut for Yes and ESC is a shortcut for No. If message_window_timeout is used, then -1 will be returned if the timeout expires. A child thread can call this to cause the main thread's call to wait() to return (with the lock locked) even if there are no events ready. The main purpose of this is to get the main thread to redraw the screen, but it will also cause fltk::wait() to return so the program's code can do something. You should call this immediately before fltk::unlock() for best performance. The message argument can be retrieved by the other thread using fltk::thread_message(). Generates a simple beep message You can enable beep on default message dialog (like ask, choice, input, ...) by using this function with true (default is false) You get the state enable beep on default message dialog (like ask, choice, input, ...) by using this function with true (default is false) Get the widget that is below the mouse. This is the last widget to respond to an fltk::ENTER event as long as the mouse is still pointing at it. This is for highlighting buttons and bringing up tooltips. It is not used to send fltk::PUSH or fltk::MOVE directly, for several obscure reasons, but those events typically go to this widget. Change the fltk::belowmouse() widget, the previous one and all parents (that don't contain the new widget) are sent fltk::LEAVE events. Changing this does not send fltk::ENTER to this or any widget, because sending fltk::ENTER is supposed to test if the widget wants the mouse (by it returning non-zero from handle()). Same as fltk::wait(0). Calling this during a big calculation will keep the screen up to date and the interface responsive: while (!calculation_done()) { calculate(); fltk::check(); if (user_hit_abort_button()) break; } Shows the message with three buttons below it marked with the strings b0, b1, and b2. Returns 0, 1, or 2 depending on which button is hit. If one of the strings begins with the special character '*' then the associated button will be the default which is selected when the enter key is pressed. ESC is a shortcut for b2. If message_window_timeout is used, then -1 will be returned if the timeout expires. Replace the top of the clip stack. Remove. Remove the. Similar to drawing another vertex back at the starting point, but fltk knows the path is closed. The next addvertex() will start a new disconnected part of the shape. It is harmless to call fltk::closepath() several times in a row, or to call it before the first point. Sections with less than 3 points in them will not draw anything when filled. Turn a string into a color. If name is null this returns NO_COLOR. Otherwise it returns fltk::parsecolor(name, strlen(name)). fltk:tk::ValueInput. This version takes and returns numbers in the 0-1 range. There is also a class fltk::ColorChooser which you can use to imbed a color chooser into another control panel. Same but user can also select an alpha value. Currently the color chips do not remember or set the alpha! Same but it takes and returns 8-bit numbers for the rgb arguments. Same but with 8-bit alpha chosen by the user. Same but it takes and returns an fltk::Color number. No alpha. Use of this function is very simple. Any text editing widget should call this for each fltk::KEY event. If true is returned, then it has modified the fltk::event_text() and fltk::event_length() to a set of bytes to insert (it may be of zero length!). It will also set the del parameter to the number of bytes to the left of the cursor to delete, this is used to delete the results of the previous call to fltk::compose(). Compose may consume the key, which is indicated by returning true, but both the length and del are set to zero. Compose returns false if it thinks the key is a function key that the widget should handle itself, and not an attempt by the user to insert text. Though the current implementation returns immediately, future versions may take quite awhile, as they may pop up a window or do other user-interface things to allow international characters to be selected. If the user moves the cursor, be sure to call fltk::compose_reset(). The next call to fltk::compose() will start out in an initial state. In particular it will not set "del" to non-zero. This call is very fast so it is ok to call it many times and in many places. Multiply the current transformation by a b 0 c d 0 x y 1 Returns fg if fltk decides it can be seen well when drawn against bg. Otherwise it returns either fltk::BLACK or fltk::WHITE. Change the current selection. The block of text is copied to an internal buffer by FLTK (be careful if doing this in response to an fltk::PASTE as this may be the same buffer returned by event_text()). The block of text may be retrieved (from this program or whatever program last set it) with fltk::paste(). There are actually two buffers. If clipboard is true then the text goes into the user-visible selection that is moved around with cut/copy/paste commands (on X this is the CLIPBOARD selection). If clipboard is false then the text goes into a less-visible buffer used for temporarily selecting text with the mouse and for drag & drop (on X this is the XA_PRIMARY selection). Fork a new thread and make it run f(p). Returns negative number on error, otherwise t is set to the new thread. True if any. Turn a PixelType into the number of bytes needed to hold a pixel.. Drag and drop the data set by the most recent fltk::copy() (with the clipboard argument false). Returns true if the data was dropped on something that accepted it. By default only blocks of text are dragged. You can use system-specific variables to change the type of data. Fltk can draw into any X window or pixmap that uses the fltk::xvisual. This will reset the transformation and clip region and leave the font, color, etc at unpredictable values. The w and h arguments must be the size of the window and are used by fltk::not_clipped(). Before you destroy the window or pixmap you must call fltk::stop_drawing() so that it can destroy any temporary structures that were created by this. Return the last flags passed to setdrawflags(). Same as (drawflags() & f), returns true if any of the flags in f are set. Same except line_delta is set to r.w() times depth(type), indicating the rows are packed together one after another with no gap. Draw a image (a rectangle of pixels) stored in your program's memory. The current transformation (scale, rotate) is applied. The X version of FLTK will abort() if the default visual is one it cannot use for images. To avoid this call fltk::visual(fltk::RGB) at the start of your program. Call the passed function to provide each scan line of the image. This lets you generate the image as it is being drawn, or do arbitrary decompression of stored data (provided it can be decompressed to individual scan lines easily). callback is called with the void* data argument (this can be used to point at a structure of information about the image), the x, y, and number of pixels desired from the image, measured from the upper-left corner of the image. It is also given a buffer of at least w pixels that can be used as temporary storage, for instance to decompress a line read from a file. You can then return a pointer to this buffer, or to somewhere inside it. The callback must return n pixels of the format described by type. The xywh rectangle describes the area to draw. The callback is called with y values between 0 and h-1. Due to cropping not all pixels may be asked for. You can assumme y will be asked for in increasing order. Draw a straight line between the two points. If line_width() is zero, this tries to draw as though a 1x1 square pen is moved between the first centers of pixels to the lower-right of the start and end points. Thus if y==y1 this will fill a rectangle with the corners x,y and x1+1,y+1. This may be 1 wider than you expect, but is necessary for compatability with previous fltk versions (and is due to the original X11 behavior). If line_width() is not zero then the results depend on the back end. It also may not produce consistent results if the ctm is not an integer translation or if the line is not horizontal or vertical. Draw a straight line between the two points. Draw a dot at the given point. If line_width() is zero this is a single pixel to the lower-right of x,y. If line_width() is non-zero this is a dot drawn with the current pen and line caps. Draw a dot at the given point. If line_width() is zero this is the single pixel containing X,Y, or the one to the lower-right if X and Y transform to integers. If line_width() is non-zero this is a dot drawn with the current pen and line caps (currently draws nothing in some api's unless the line_style has CAP_ROUND). Draw using this style. Set drawstyle() to this, drawflags() to flags, calls setcolor() and setbgcolor() with appropriate colors for this style and the given flags, and calls setfont(). This is called by the draw() methods on most fltk widgets. The calling Widget picks what flags to pass to the Symbols so that when they call this they get the correct colors for each part of the widget. Flags that are understood: It then further modifies fg so that it contrasts with the bg. Return the last style sent to drawstyle(s,f). Some drawing functions (such as glyphs) look in this for box types. If this has not been called it is Widget::default_style. Draw a nul-terminated string. Draw the first n bytes (not characters if utf8 is used) starting at the given position. This is the fancy string-drawing function that is used to draw all labels in fltk. The string is formatted and aligned inside the passed rectangle. This also: Provides access to some of the @-string formatting for another graphics API. Most symbols will not work, but you will be able to access the line break and justifications, and commands that change the font, size, and color. I use this to format labels for that are drawn in OpenGL. textfunction is called to draw all text. It's arguments are a pointer to a UTF-8 string, the length in bytes of that string, and two float numbers for the x and y to draw the text at. textfunction may use getfont(), getsize(), and getcolor() to find out the settings and recreate them on the output device. Draw text starting at a point returned by fltk::transform(). This is needed for complex text layout when the current transform may not match the transform being used by the font.(). Returns the most recent event handled, such as fltk::PUSH or fltk::KEY. This is useful so callbacks can find out why they were called. Returns which mouse button was pressed or released by a PUSH or RELEASE event. Returns garbage for other events, so be careful (this actually is the same as event_key(), the buttons have been assigned the key values 1,2,3, etc. Returns the number of extra times the mouse was clicked. For a normal fltk::PUSH this is zero, if the user "double-clicks" this is 1, and it is N-1 for each subsequent click. Setting this value can be used to make callbacks think things were (or were not) double-clicked, and thus act differently. For fltk::MOUSEWHEEL events this is how many clicks the user moved in the x and y directions (currently dx is always zero). Reserved for future use if horizontal mouse wheels (or some kind of joystick on the mouse) becomes popular. Returns true if the current fltk::event_x() and fltk::event_y() put it inside the Rectangle. You should always call this rather than doing your own comparison so you are consistent about edge effects. This is true for a short time after the mouse key is pressed. You test this on the RELEASE events to decide if the user "clicked" or "held" the mouse. It is very useful to do different actions depending on this. This turns off after a timeout (implemented on X only, currently), when the mouse is moved more than 5 pixels, and when the user presses other mouse or keyboard buttons while the mouse is down. On X this is used to decide if a click is a double-click, it is if this is still on during the next mouse press. On Windows and OS/X the system's indication is used for double-click. You can set this to zero with fltk::event_is_click(0), this can be used to prevent the next mouse click from being considered a double click. Only false works, attempts to set this true are ignored. Returns which key on the keyboard was last pushed. Most non-keyboard events set this to values that do not correspond to any keys, so you can test this in callbacks without having to test first if the event really was a keystroke. The values returned are described under fltk::SpaceKey. True if the most recent KEY event was caused by a repeating held-down key on the keyboard. The value increments for each repeat. Note: older versions of fltk reused event_clicks() for this. This made it impossible to design a GUI where the user holds down keyboard keys while clicking the mouse, as well as being pretty hard to understand. So we had to change it for fltk 2. Returns true if the given key was held down (or pressed) during the last event. This is constant until the next event is read from the server. The possible values for the key are listed under fltk::SpaceKey. On Win32 event_key_state(KeypadEnter) does not work. Returns the length of the text in fltk::event_text(). There will always be a nul at this position in the text. However there may be a nul before that if the keystroke translates to a nul character or you paste a nul character. This is a bitfield of what shift states were on and what mouse buttons were held down during the most recent event. The flags to pass are described under fltk::SHIFT. Because Emacs screws up if any key returns the predefined META flag, lots of X servers have really botched up the key assignments trying to make Emacs work. Fltk tries to work around this but you may find that Alt or Meta don't work, since I have seen at least 3 mutually incompatible arrangements. Non-XFree86 machines may also have selected different values so that NUMLOCK, META, and SCROLLLOCK are mixed up. In addition X reports the state before the last key was pressed so the state looks backwards for any shift keys, currently fltk only fixes this bug for the mouse buttons. Same as event_state()&mask, returns true if any of the passed bits were turned on during the last event. So doing event_state(SHIFT) will return true if the shift keys are held down. This is provided to make the calling code easier to read. The flags to pass are described under fltk::SHIFT. Returns the ASCII text (in the future this may be UTF-8) produced by the last fltk::KEY or fltk::PASTE or possibly other event. A zero-length string is returned for any keyboard function keys that do not produce text. This pointer points at a static buffer and is only valid until the next event is processed. Under X this is the result of calling XLookupString(). Returns the distance the mouse is to the right of the left edge of the widget. Widget::send() modifies this as needed before calling the Widget::handle() method. Return the absolute horizontal position of the mouse. Usually this is relative to the left edge of the screen, but multiple Monitor setup may change that. To find the absolute position of the current widget, subtract event_x_root()-event_x(). Returns the distance the mouse is below the top edge of the widget. Widget::send() modifies this as needed before calling the Widget::handle() method. Return the absolute vertical position of the mouse. Zero is at the top. Turns on exit_modal_flag(). This may be used by user callbacks to cancel modal state. See also fltk::Window::make_exec_return(). True if exit_modal() has been called. The flag is also set by the destruction or hiding of the modal widget, and on Windows by other applications taking the focus when grab is on. pops up the file chooser, waits for the user to pick a file or Cancel, and then returns a pointer to that filename or NULL if Cancel is chosen. If use_system_file_chooser() is set to true, a system FileChooser is opened. If the user picks multiple files, these will be separated by a new line. If fname is NULL then the last filename that was choosen is used, unless the pattern changes, in which case only the last directory is used. The first time the file chooser is called this defaults to a blank string. This function is called every time the user navigates to a new file or directory in the file chooser. It can be used to preview the result in the main window. Return the filename from expanded to a full "absolute" path name by prepending the current directory: The return value is the number of bytes this wants to write to output. If this value is greater or equal to length, then you know the output has been truncated, and you can call this again with a buffer of n+1 bytes. Leading "./" sequences in input are removed, and "../" sequences are removed as well as the matching trailing part of the prefixed directory. Technically this is incorrect if symbolic links are used but this matches the behavior of most programs. If the pwd argument is null, this also expands names starting with '~' to the user or another user's HOME directory. To expand a filename starting with ~ in the current directory you must start it with "./~". If input is a zero-length string then the pwd is returned with a slash added to the end. Returns true if the file exists . Returns a pointer to the last period in filename_name(f), or a pointer to the trailing nul if none. Notice that this points at the period, not after it! Returns true if the file exists and is a directory. Returns true if the file exists and is a regular file. Returns true if filename s matches pattern p. The following glob syntax is used by pattern: Returns the modification time of the file as a Unix timestamp (number of seconds since the start of 1970 in GMT). Returns 0 if the file does not exist. Returns a pointer to after the last slash in name. If the name ends with a slash then this returns a pointer to the NUL. If there is no slash this returns a pointer to the start of name. Does the opposite of filename_absolute(). Produces the shortest possible name in output that is relative to the current directory. If the filename does not start with any text that matches the current directory then it is returned unchanged. Return value is the number of characters it wants to write to output. Returns the size of the file in bytes. Returns zero if it does not exist. Does fltk::closepath() and then fill with the current color, and then clear the path. For portability, you should only draw polygons that appear the same whether "even/odd" or "non-zero" winding rules are used to fill them. This mostly means that holes should be drawn in the opposite direction of the outside. Warning: result is somewhat different on X and Win32! Use fillstrokepath() to make matching shapes. In my opinion X is correct, we may change the Win32 version to match in the future, perhaps by making the current pen invisible? Fill the rectangle with the current color. Does fltk::fill(), then sets the current color to linecolor and does fltk::stroke with the same closed path, and then clears the path. This seems to produce very similar results on X and Win32. Also it takes advantage of a single GDI32 call that does this and should be faster. Portably calls the fopen() function for different systems. Note that ALL calls to this function MUST make sure the filename is UTF8 encoded. Portably calls the system's stat() function, to deal with native Unicode filenames. Has the same return values and use as the system's stat. The string passed to fltk_stat must be UTF8 (note that ASCII is a subset of UTF8) write all preferences to disk Get the display up to date. This is done by calling layout() on all Window objects with layout_damage() and then calling draw() on all Window objects with damage(). (actually it calls Window::flush() and that calls draw(), but normally you can ignore this). This will also flush the X i/o buffer, update the cursor shape, update Windows window sizes, and other operations to get the display up to date. wait() calls this before it waits for events. Change fltk::focus() to the given widget, the previous widget and all parents (that don't contain the new widget) are sent fltk::UNFOCUS events, the new widget is sent an fltk::FOCUS event, and all parents of it get fltk::FOCUS_CHANGE events. fltk::focus() is set whether or not the applicaton has the focus or if the widgets accept the focus. You may want to use fltk::Widget::take_focus() instead, it will test first. For back-compatabilty with FLTK1, this turns an integer into one of the built-in fonts. 0 = HELVETICA. Call the handle() method from the passed ShortcutFunctor object for every Widget::shortcut() assignment known. If any return true then this immediately returns that shortcut value, else this returns zero after calling it for the last one. This is most useful for making a display of shortcuts for the user, or implementing a shortcut editor. class ListShortcuts : public ShortcutFunctor { public: bool handle(const Widget* widget, unsigned key) { printf("Widget=%s shortcut=%s\n", widget->label() ? widget->label() : "NULL", key_name(key)); return false; } }; f() { ListShortcuts listShortcuts; fltk::foreachShortcut(listShortcuts); } If widget is not null, only do assignments for that widget, this is much faster than searching the entire list. This is useful for drawing the shortcuts on a widget (though most fltk widgets only draw the first one). Return the rgb form of color. If it is an indexed color that entry is returned. If it is an rgb color it is returned unchanged. Returns the string sent to the most recent set_encoding(). Returns true if the given key is held down now. This is different than event_key_state() as that returns how the key was during the last event. This can also be slower as it requires a round-trip query to the window server. The values to pass are described under fltk::SpaceKey. On Win32 fltk::get_key_state(fltk::KeypadEnter) does not work. Return where the mouse is on the screen by doing a round-trip query to the server. You should use fltk::event_x_root() and fltk::event_y_root() if possible, but this is necessary if you are not sure if a mouse event has been processed recently (such as to position your first window). If the display is not open, this will open it.. Return the distance from the baseline to the top of letters in the current font. Returns the last Color passed to setbgcolor(). To actually draw in the bg color, do this: Color saved = getcolor(); setcolor(getbgcolor()); draw_stuff(); setcolor(saved) Returns the last Color passed to setcolor(). Return an arbitrary HDC which you can use for Win32 functions that need one as an argument. The returned value is short-lived and may be destroyed the next time anything is drawn into a window! Return the distance from the baseline to the bottom of letters in the current font. Uses glDrawPixels to draw an image using the same arguments as drawimage(). If you are in the normal OpenGL coordinate system with 0,0 in the lower-left, the first pixel is memory is the lower-left corner. Draw text at the given point in 3D space transformed to the screen. Draw text at the current glRasterPos in the current font selected with fltk::glsetfont(). You can use glRasterPos2f() or similar calls to set the position before calling this. The string is in UTF-8, although only characters in ISO-8859-1 are drawn correctly, others draw as question marks. Draw the first n bytes of text at the current glRasterPos. Draw the first n bytes of text at the given point in 3D space transformed to the screen. Inline wrapper for glRecti(x,y,x+w,y+h). Set the current OpenGL color to a FLTK color, or as close as possible. Make the current OpenGL font (as used by gldrawtext()) be as similar as possible to an FLTK Font. Currently the font is aliased except on X. Set up an OpenGL context to draw into the current window being drawn by fltk. This will allow you to use OpenGL to update a normal window. The current transformation is reproduced, and the current clipping is simulated with glScissor() calls (which can only do a rectangle). You must use glfinish() to exit this mode before any normal fltk drawing calls are done. You should call glvisual() at program startup if you intend to use this. This may be used to change how windows are created so this call works. I would like this to work reliably, but it is not real good now on any platforms. In particular it does not cooperate with the double-buffering schemes. It does appear to work on X when you turn off double buffering, it also works if OpenGL is entirely software, such as MESA. Do not call glstart()/glfinish() when drawing into a GlWindow! Draw a 1-thick line just inside the given rectangle. Same as fltk::visual(int) except choose a visual that is also capable of drawing OpenGL. On modern X servers this is true by default, but on older ones OpenGL will crash if the visual is not selected with this. mode is the same bitflags accepted by GlWindow::mode(). This causes all windows (and thus glstart()) to have these capabilities. Try to guess the filetype Beware that calling this force you to link in all image types ! Make FLTK act as though it just got the event stored in xevent. You can use this to feed artifical X events to it, or to use your own code to get events from X. Besides feeding events your code should call fltk::flush() periodically so that FLTK redraws its windows. This function will call any widget callbacks from the widget code. It will not return until they complete, for instance if it pops up a modal window with fltk::ask() it will not return until the user clicks yes or no. This is the function called from the system-specific code for all events that can be passed to Widget::handle(). You can call it directly to fake events happening to your widgets. Currently data other than the event number can only be faked by writing to the undocumented fltk::e_* variables, for instance to make event_x() return 5, you should do fltk::e_x = 5. This may change in future versions. This will redirect events to the modal(), pushed(), belowmouse(), or focus() widget depending on those settings and the event type. It will turn MOVE into DRAG if any buttons are down. If the resulting widget returns 0 (or the window or widget is null) then the functions pointed to by add_event_handler() are called. Return true if add_check() has been done with this cb and arg, and remove_check() has not been done. Returns true if the specified idle callback is currently installed. Returns true if the timeout exists and has not been called yet. Returns true if the current thread is the main thread, i.e. the one that called wait() first. Many fltk calls such as wait() will not work correctly if this is not true. This function must be surrounded by lock() and unlock() just like all other fltk functions, the return value is wrong if you don't hold the fltk lock! Warning: in_main_thread() is wrong if the main thread calls fltk::unlock() and another thread calls fltk::lock() (the assumption is that the main thread only calls wait()). Current fix is to do the following unsupported code: fltk::in_main_thread_ = false; fltk::unlock(); wait_for_something_without_calling_fltk_wait(); fltk::lock(); fltk::in_main_thread_ = true; Same as lerp(fg, getbgcolor(), .5). This is for back-compatability only? Same as lerp(fg, bg, .5), it grays out the color. Pops up a window displaying a string, lets the user edit it, and return the new value. The cancel button returns NULL. The returned pointer is only valid until the next time fltk::input() is called. Due to back-compatability, the arguments to any printf commands in the label are after the default value. If message_window_timeout is used, then 0 will be returned if the timeout expires. Intersect a transform()'d rectangle with the current clip region and change it to the smaller rectangle that surrounds (and probably equals) this intersection area. This can be used by device-specific drawing code to limit complex pixel operations (like drawing images) to the smallest rectangle needed to update the visible area. Return values: Turn a string into a fltk::event_key() value or'd with fltk::event_shift() flags. The returned value can be used by by fltk::Widget::add_shortcut(). Any error, or a null or zero-length string, returns 0. Currently this understands prefixes of "Alt+", "Shift+", and "Ctrl+" to turn on fltk::ALT, fltk::SHIFT, and fltk::CTRL. Case is ignored and the '+' can be a '-' instead and the prefixes can be in any order. You can also use '#' instead of "Alt+", '+' instead of "Shift+", and '^' instead of Ctrl+. After the shift prefixes there can either be a single ASCII letter, "Fn" where n is a number to indicate a function key, or "0xnnnn" to get an arbitrary fltk::event_key() enumeration value. The inverse function to turn a number into a string is fltk::key_name(). Currently this function does not parse some strings fltk::key_name() can return, such as the names of arrow keys! Unparse a fltk::Widget::shortcut(), an fltk::event_key(), or an fltk::event_key() or'd with fltk::event_state(). Returns a pointer to a human-readable string like "Alt+N". If hotkey is zero an empty string is returned. The return value points at a static buffer that is overwritten with each call. The opposite function is fltk::key(). Return (1-weight)*color0 + weight*color1. weight is clamped to the 0-1 range before use. Return the last value for dashes sent to line_style(int,width,dashes). Note that the actual pointer is returned, which may not point at legal data if a local array was passed, so this is only useful for checking if it is NULL or not. Return the last value sent to line_style(int,width,dashes), indicating the cap and join types and the built-in dash patterns. Set how to draw lines (the "pen"). If you change this it is your responsibility to set it back to the default with fltk::line_style(0). style is a bitmask in which you , if set then the dash pattern in style is ignored.. The dashes array is ignored on Windows 95/98. Return the last value for width sent to line_style(int,width,dashes). Replace the current transform with the identity transform, which puts 0,0 in the top-left corner of the window and each unit is 1 pixel in size. Call the theme() function if it has not already been called. Normally FLTK calls this just before the first Window::show() is done. You need to call this earlier to execute code such as measuring labels that may depend on the theme. A multi-threaded fltk program must surround all calls to any fltk functions with lock() and unlock() pairs. This is a "recursive lock", a thread can call lock() n times, and it must call unlock() n times before it really is unlocked. If another thread calls lock() while it is locked, it will block (not return from lock()) until the first thread unlocks. The main thread must call lock() once before any call to fltk to initialize the thread system. The X11 version of fltk uses XInitThreads(), XLockDisplay(), and XUnlockDisplay(). This should allow an fltk program to cooperate with other packages updating the display using Xlib calls. This lets you pass your own measurement function to measure the widths of printed text. Also returns floating point sizes. Measure the size of box necessary for drawtext() to draw the given string inside of it. The flags are used to set the alignment, though this should not make a difference except for fltk::ALIGN_WRAP. To correctly measure wrap w must be preset to the width you want to wrap at if fltk::ALIGN_WRAP is on in the flags! w and h are changed to the size of the resulting box.. Restricts events to a certain widget. First thing: much of the time fltk::Window::exec() will do what you want, so try using that. This function sets the passed widget as the "modal widget". All user events are directed to it or a child of it, preventing the user from messing with other widgets. The modal widget does not have to be visible or even a child of an fltk::Window for this to work (but if it not visible, fltk::event_x() and fltk::event_y() are meaningless, use fltk::event_x_root() and fltk::event_y_root()). The calling code is responsible for saving the current value of modal() and grab() and restoring them by calling this after it is done. The code calling this should then loop calling fltk::wait() until fltk::exit_modal_flag() is set or you otherwise decide to get out of the modal state. It is the calling code's responsibility to monitor this flag and restore the modal widget to it's previous value when it turns on. grab indicates that the modal widget should get events from anywhere on the screen. This is done by messing with the window system. If fltk::exit_modal() is called in response to an fltk::PUSH event (rather than waiting for the drag or release event) fltk will "repost" the event so that it is handled after modal state is exited. This may also be done for keystrokes in the future. On both X and WIN32 grab will not work unless you have some visible window because the system interface needs a visible window id. On X be careful that your program does not enter an infinite loop while grab() is on, it will lock up your screen! Returns the current modal widget, or null if there isn't one. It is useful to test these in timeouts and file descriptor callbacks in order to block actions that should not happen while the modal window is up. You also need these in order to save and restore the modal state. Sorts two files based on their modification date. Find an indexed color in the range 56-127 that is closest to this color. If this is an indexed color it is returned unchanged. Clear the current "path". This is normally done by fltk::fillpath() or any other drawing command. You can make fltk "open" a display that has already been opened, perhaps by another GUI library. Calling this will set xdisplay to the passed display and also read information FLTK needs from it. Don't call this if the display is already open! Opens the display. Does nothing if it is already open. You should call this if you wish to do X calls and there is a chance that your code will be called before the first show() of a window. This is called automatically Window::show(). This may call fltk::abort() if there is an error opening the display. Makes FLTK use its own X colormap. This may make FLTK display better and will reduce conflicts with other programs that want lots of colors. However the colors may flash as you move the cursor between windows. This function is pretty much legacy nowadays as all modern systems are full color, on such systems this does nothing. You must call this before you show() any windows. If you call visual(int) you must call this after that. Turn the first n bytes of name into an fltk color. This allows you to parse a color out of the middle of a string. Recognized values are: Same as fltk::input() except an fltk::SecretInput field is used. This is what a widget does when a "paste" command (like Ctrl+V or the middle mouse click) is done to it. Cause an fltk::PASTE event to be sent to the receiver with the contents of the current selection in the fltk::event_text(). The selection can be set by fltk::copy(). There are actually two buffers. If clipboard is true then the text is from the user-visible selection that is moved around with cut/copy/paste commands (on X this is the CLIPBOARD selection). If clipboard is false then the text is from a less-visible buffer used for temporarily selecting text with the mouse and for drag & drop (on X this is the XA_PRIMARY selection). most toolkits require. Restore the previous clip region. You must call fltk::pop_clip() exactly once for every time you call fltk::push_clip(). If you return to FLTK with the clip stack not empty unpredictable results occur. Put the transformation back to the way it was before the last push_matrix(). Calling this without a matching push_matrix will crash! Pushes the intersection of the current region and r onto the clip stack. Same as push_clip(Rectangle(x,y,w,h)) but faster: Same as push_clip(Rectangle(x,y,r,h)) except faster as it avoids the construction of an intermediate rectangle object. Pushes the intersection of the current region and this rectangle onto the clip stack. Save the current transformation on a stack, so you can restore it with pop_matrix(). FLTK provides an arbitrary 2-D affine transformation (rotation, scale, skew, reflections, and translation). This is very similar to PostScript, PDF, SVG, and Cairo. Due to limited graphics capabilities of some systems, not all drawing functions will be correctly transformed, except by the integer portion of the translation. Don't rely on this as we may be fixing this without notice. Pushes an empty clip region on the stack so nothing will be clipped. This lets you draw outside the current clip region. This should only be used to temporarily ignore the clip region to draw into an offscreen area. Get the widget that is being pushed. fltk::DRAG or fltk::RELEASE (and any more fltk::PUSH) events will be sent to this widget. This is null if no mouse button is being held down, or if no widget responded to the fltk::PUSH event. Change the fltk::pushed() widget. This sends no events. Reads a 2-D image off the current drawing destination. The resulting data can be passed to fltk::drawimage() or the 8-bit pixels examined or stored by your program. The return value is either p or NULL if there is some problem (such as an inability to read from the current output surface, or if the rectangle is empty). p points to the location to store the first byte of the upper-left pixel of the image. The caller must allocate this buffer. type can be fltk::RGB or fltk::RGBA (possibly other types will be supported in the future). rectangle indicates the position on the surface in the current transformation to read from and the width and height of the resulting image. What happens when the current transformation is rotated or scaled is undefined. If the rectangle extends outside the current drawing surface, or into areas obscured by overlapping windows, the result in those areas is undefined. linedelta is how much to add to a pointer to advance from one pixel to the one below it. Any bytes skipped over are left with undefined values in them. Negative values can be used to store the image upside-down, however p should point to 1 line before the end of the buffer, as it still points to the top-left pixel. Same except linedelta is set to r.w()*depth(type).(); if (user_hit_abort_button()) break; } } Redraws all widgets. This is a good idea if you have made global changes to the styles. Makes it so SharedImage can identify image files of the types compiled into fltk. These are XPM, PNG, and Jpeg images. Does nothing if load_theme() has not been called yet. If load_theme() has been called, this calls the theme() function again and then call redraw(). If the theme function is written correctly, this should change the display to the new theme. You should call this if you change the theme() or if external information changes such that the result of your theme() function changes. FLTK will call this automatically when it gets a message from the system indicating the user's preferences have changed. Remove all matching check callback, if any exists. You can call this from inside the check callback if you want. Remove all the callbacks (ie for all different when values) for the given file descriptor. It is harmless to call this if there are no callbacks for the file descriptor. If when is given then those bits are removed from each callback for the file descriptor, and the callback removed only if all of the bits turn off. Removes the specified idle callback, if it is installed. Removes all pending timeout callbacks that match the function and arg. Does nothing if there are no matching ones that have not been called yet.: void callback(void*) { printf("TICK\n"); fltk::repeat_timeout(1.0,callback); } main() { fltk::add_timeout(1.0,callback); for (;;) fltk::wait(); } Change the theme to the compiled-in default by calling the revert function of all NamedStyle structures. A theme() function may want to call this to clear the previous settings. Rotate the current transformation counter-clockwise by d degrees (not radians!!). This is done by multiplying the matrix by: cos -sin 0 sin cos 0 0 0 1 Calls fltk::wait() as long as any windows are not closed. When all the windows are hidden or destroyed (checked by seeing if Window::first() is null) this will return with zero. A program can also exit by having a callback call exit() or abort(). Most fltk programs will end main() with return fltk::run();. Scale the current transformation by multiplying it by x 0 0 0 y 0 0 0 1 Scale the current transformation by multiplying it by x 0 0 0 x 0 0 0 1 Move the contents of a rectangle by dx and dy. The area that was previously outside the rectangle or obscured by other windows is then redrawn by calling draw_area for each rectangle. This is a drawing function and can only be called inside the draw() method of a widget. If dx and dy are zero this returns without doing anything. If dx or dy are larger than the rectangle then this just calls draw_area for the entire rectangle. This is also done on systems (Quartz) that do not support copying screen regions. fltk::GRAY75 is replaced with the passed color, and all the other fltk::GRAY* colors are replaced with a color ramp (or sometimes a straight line) so that using them for highlighted edges of raised buttons looks correct. Set one of the indexed colors to the given rgb color. i must be in the range 0-255, and c must be a non-indexed rgb color. Obsolete function to encourage FLTK to choose a 256-glyph font with the given encoding. You must call setfont() after changing this for it to have any effect. Notice that this is obsolete! Only the non-Xft X version actually uses it and that may be eliminated as well. In addition FLTK uses UTF-8 internally, and assummes that any font it prints with is using Unicode encoding (or ISO-8859-1 if there are only 256 characters). The default is "iso10646-1" Set the "background" color. This is not used by the drawing functions, but many box and image types will refer to it by calling getbgcolor(). Set the current "brush" in the DC to match the most recent setcolor() and line_style() calls. This is stupid-expensive on Windows so we defer it until the brush is needed. Set the color for all subsequent drawing operations. Sets the current rgb and alpha to draw in, on rendering systems that allow it. If alpha is not supported this is the same as setcolor(). The color you pass should not premultiplied by the alpha value, that would be a different, nyi, call. Store a set of bit flags that may influence the drawing of some fltk::Symbol subclasses, such as boxes. Generally you must also use setcolor() and setbgcolor() to set the color you expect as not all symbols draw differently depending on the flags. The flags are usually copied from the flags() on a Widget. Some commonly-used flags: Set the current font and font scaling so the size is size pixels. The size is unaffected by the current transformation matrix (you may be able to use fltk::transform() to get the size to get a properly scaled font). The size is given in pixels. Many pieces of software express sizes in "points" (for mysterious reasons, since everything else is measured in pixels!). To convert these point sizes to pixel sizes use the following code: const fltk::Monitor& monitor = fltk::Monitor::all(); float pixels_per_point = monitor.dpi_y()/72.0; float font_pixel_size = font_point_size*pixels_per_point; See the fltk::Font class for a description of what can be passed as a font. For most uses one of the built-in constant fonts like fltk::HELVETICA can be used. Set the current "pen" in the DC to match the most recent setcolor() and line_style() calls. This is stupid-expensive on Windows so we defer it until the pen is needed. Older style of color chooser that only chooses the "indexed" fltk colors. This pops up a panel of the 256 colors you can access with "indexed" fltk::Color values and lets the user pick one of them. If the user clicks on one of them, the new index is returned. If they type Esc or click outside the window, the old index is returned. Set r,g,b to the 8-bit components of this color. If it is an indexed color they are looked up in the table, otherwise they are simply copied out of the color number. Destroy any dc or other objects used to draw into this window. Destroy any "graphics context" structures that point at this window or Pixmap. They will be recreated if you call draw_into() again. Unfortunately some graphics libraries will crash if you don't do this. Even if the graphics context is not used, destroying it after destroying it's target will cause a crash. Sigh. Draw a line between all the points in the path (see fltk::line_style() for ways to set the thicknesss and dot pattern of the line), then clear the path. Draw a line inside this bounding box (currently correct only for 0-thickness lines). Returns the current Theme function. By default this points at fltk_theme(). Change what function fltk should call to set the appearance. If you change this after any windows may have been shown, you should call reload_theme(). Replace x and y transformed into device coordinates. Device-specific code can use this to draw things using the fltk transformation matrix. If the backend is Cairo or another API that does transformations, this may return xy unchagned. Transform the rectangle from into device coordinates and put it into to. This only works correctly for 90 degree rotations, for other transforms this will produce an axis-aligned rectangle with the same area (this is useful for inscribing circles, and is about the best that can be done for device functions that don't handle rotation. Same as transform(Rectangle(X,Y,W,H),to) but replaces XYWH with the transformed rectangle. This may be faster as it avoids the rectangle construction. Replace x and y with the transformed coordinates, rounded to the nearest integer. Replace x and y with the tranformed coordinates, ignoring translation. This transforms a vector which is measuring a distance between two positions, rather than a position.. Translate the current transformation by multiplying it by 1 0 0 0 1 0 x y 1 Try sending the current KEY event as a SHORTCUT event. Normally the focus() gets all keystrokes, and shortcuts are only tested if that widget indicates it is uninterested by returning zero from Widget::handle(). However in some cases the focus wants to use the keystroke only if it is not a shortcut. The most common example is Emacs-style editing keystrokes in text editing widgets, which conflict with Microsoft-compatable menu key bindings, but we want the editing keys to work if there is no conflict. This will send a SHORTCUT event just like the focus returned zero, to every widget in the focus window, and to the add_handler() calls, if any. It will return true if any widgets were found that were interested in it. A handle() method can call this in a KEY event. If it returns true, return 1 immediatly, as the shortcut will have executed and may very well have destroyed your widget. If this returns false, then do what you want the key to do. Releases the lock that was set using the fltk::lock() method. Child threads should call this method as soon as they are finished accessing FLTK. If some other thread is waiting for fltk::lock() to return, it will get control. On Windows this makes file_chooser() call the Win32 file chooser API instead of using the one constructed in fltk. Ignored on other systems. Returns the value of FL_VERSION that FLTK was compiled with. This can be compared to the FL_VERSION macro to see if the shared library of fltk your program linked with is up to date. X-specific crap to allow you to force the "visual" used by fltk to one you like, rather than the "default visual" which in many cases has less capabilities than your machine really has! For instance fltk::visual(fltk::RGB_COLOR) will get you a full color display instead of an 8-bit colormap, if possible. You must call this before you show() any windows. The integer argument is an 'or' of the following: This returns true if the system has the capabilities by default or FLTK suceeded in turing them on. Your program will still work even if this returns false (it just won't look as good). On non-X systems this just returns true or false indicating if the system supports the passed values. Same as fltk::wait(infinity). Call this repeatedly to "run" your program. You can also check what happened each time after this returns, which is quite useful for managing program state.. Change where the mouse is on the screen. Returns true if successful, false on failure (exactly what success and failure means depends on the os). Returns the XID for a window, or zero if show() has not been called on it. Returns the X pixel number used to draw the given FLTK color. If a colormapped visual is being used, this may allocate it, or find the nearest match. 1-pixel thick gray line around rectangle. Obsolete. Draws colored edge and draws nothing inside rectangle. You can change this string to convert fltk to a foreign language. The color picked by the most recent setcolor(Color). The device context that is currently being drawn into. Draws a standard box based on the current theme Diamond shape used to draw Motif-style checkboxes. Raised diamond shape used to draw Motif-style checkboxes. The dnd_* variables allow your fltk program to use the Xdnd protocol to manipulate files and interact with file managers. You can ignore these if you just want to drag & drop blocks of text. I have little information on how to use these, I just tried to clean up the Xlib interface and present the variables nicely. The program can set this variable before returning non-zero for a DND_DRAG event to indicate what it will do to the object. Fltk presets this to XdndActionCopy so that is what is returned if you don't set it. The action the source program wants to perform. Due to oddities in the Xdnd design this variable is not set on the fltk::DND_ENTER event, instead it is set on each DND_DRAG event, and it may change each time. To print the string value of the Atom use this code: char* x = XGetAtomName(xdisplay, dnd_source_action); puts(x); XFree(x); You can set this before calling fltk::dnd() to communicate a different action. See dnd_source_types, which you must also set. Zero-terminated list of atoms describing the formats of the source data. This is set on the DND_ENTER event. The following code will print them all as text, a typical value is "text/plain;charset=UTF-8" (gag). for (int i = 0; dnd_source_types[i]; i++) { char* x = XGetAtomName(xdisplay, dnd_source_types[i]); puts(x); XFree(x); } You can set this and dnd_source_action before calling dnd() to change information about the source. You must set both of these, if you don't fltk will default to "text/plain" as the type and XdndActionCopy as the action. To set this change it to point at your own array. Only the first 3 types are sent. Also, FLTK has no support for reporting back what type the target requested, so all your types must use the same block of data. The X id of the window being dragged from. The program can set this when returning non-zero for a DND_RELEASE event to indicate the translation wanted. FLTK presets this to "text/plain" so that is returned if you don't set it (supposedly it should be limited to one of the values in dnd_source_types, but "text/plain" appears to always work). Inset box in fltk's standard theme 2-pixel thick raised line around edge. 2-pixel thick engraved line around edge. fltk will call this when it wants to report a recoverable problem. but in this case the display is so messed up it is unlikely the user can continue. Very little calls this now. The default version on Unix prints a message to stderr, on Windows it pops up a MessageBox, and then both versions call exit(1). You may be able to use longjmp or an exception to get back to your own code. The last timestamp from an X event that reported it (not all do). Many X calls (like cut and paste) need this value. Draws a flat rectangle of getbgcolor(). The single X GC used for all drawing. This is initialized by the first call to Window::make_current(). This may be removed if we use Cairo or XRender only. Most Xlib drawing calls look like this: This is a portion of the string printed by fltk::args() detects an invalid argument on the command-line. You can add this to your own error or help message to show the fltk switches. It's value is (no newline at start or the end): -d[isplay] host:n.n -g[eometry] WxH+X+Y -n[ame] windowname -i[conic] -bg color Draws nothing normally, and as THIN_DOWN_BOX when the mouse pointer points at it or the value of the widget is turned on. Draws nothing normally, and as THIN_UP_BOX when the mouse pointer points at it or the value of the widget is turned on. This dummy 1x1 window is created by fltk::open_display() and is never destroyed. You can use it to communicate with the window manager or other programs. When this is set to true, then (all) message windows will use scrollbars if the given message is too long. The most recent message read by GetMessage() (which is called by fltk::wait(). This may not be the most recent message sent to an FLTK window (because our fun-loving friends at MicroSoft decided that calling the handle procedures directly would be a good idea sometimes...) You can change this string to convert fltk to a foreign language. Draws nothing. Can be used as a box to make the background of a widget invisible. Also some widgets check specifically for this and change their behavior or drawing methods. Ellipse with no border. You can change this string to convert fltk to a foreign language. Ellipse with a black border and gray shadow. Ellipse with a black border. Pushed in version of PLASTIC_UP_BOX Box designed to vaguely resemble a certain fruit-themed operating system. Round-cornered rectangle with no border. Inset oval or circle. Raised oval or circle. Round-cornered rectangle with a black border. Round-cornered rectangle with a black border and gray shadow. 1-pixel-thick inset box. 1-pixel-thick raised box. A up button in fltk's standard theme. fltk will call this when it wants to report a recoverable problem. The display may be messed up but the user can probably keep working. (all X protocol errors call this). The default version on Unix prints a message to stderr, on Windows it pops up a MessageBox. The colormap being used by FLTK. This is needed as an argument for many Xlib calls. You can also set this immediately after open_display() is called to your own colormap. The function own_colormap() can be used to make FLTK create a private one. FLTK uses the same colormap for all windows and there is no way to change that, sorry. The open X display. This is needed as an argument to most Xlib calls. Don't attempt to change it! This is NULL before fltk::open_display() is called. The most recent X event. If non-zero this is the palette alloced by fltk on an 8-bit screen. Hopefully you can ignore this, I'm not even sure it works anymore. Which screen number to use. This is set by fltk::open_display() to the default screen. You can change it by setting this to a different value immediately afterwards. The X visual that FLTK will use for all windows. These are set by fltk::open_display() to the default visual. You can change them before calling Window::show() the first time. Typical code for changing the default visual is: fltk::args(argc, argv); // do this first so $DISPLAY is set fltk::open_display(); fltk::xvisual = find_a_good_visual(fltk::xdisplay, fltk::xscreen); if (!fltk::xvisual) fltk::abort("No good visual"); fltk::xcolormap = make_a_colormap(fltk::xdisplay, fltk::xvisual->visual, fltk::xvisual->depth); // it is now ok to show() windows: window->show(argc, argv); A portable interface to get a TrueColor visual (which is probably the only reason to do this) is to call fltk::visual(int). Set by Window::make_current() and/or draw_into() to the window being drawn into. This may be different than the xid() of the window, as it may be the back buffer which has a different id. You can change this string to convert fltk to a foreign language.
http://www.fltk.org/doc-2.0/html/namespacefltk.html
CC-MAIN-2015-14
refinedweb
12,283
73.07
#include <lvt/Animator.h> Inheritance diagram for Shuttle: A Shuttle moves a portion of a scene graph along a cyclic path specified by two or more waypoints. Default constructor. Constructs a Shuttle with an empty circuit. Destructor. Adds a waypoint to the Shuttle's circuit. [virtual] Moves the shuttle along its circuit. Implements Animator. [inline] Removes all waypoints from the Shuttle's circuit, and stops the Shuttle. -1 Removes a waypoint from the Shuttle's circuit. Removes the nth waypoint from the Shuttle's circuit. If n is -1, the last waypoint in the circuit is removed. If the shuttle is currently heading towards the nth waypoint, it will immediately change course for the n+1th waypoint. Renders the shuttle. As with all Animators, nothing is actually drawn, but the modelview matrix is modified representing movement along the Shuttle's circuit.
http://liblvt.sourceforge.net/doc/ref/class_l_v_t_1_1_shuttle.html
CC-MAIN-2017-17
refinedweb
141
59.19
Java 1.2 Unleashed Java 1.2 Unleashed - 47 - Sun's Java Web Server - What Are the JavaServer Toolkit and Java Web Server? - How Does Java Web Server Work? - Installing Java Web Server - Running Java Web Server - Using Servlets - Writing Servlets - Summary In Chapter 32, "Server Programs," you learned how to write server programs in Java. You saw how easy it is to listen for incoming connections, read requests from the connection's input stream, process the requests, and write responses to the connection's output stream. JavaSoft also realizes that it has a winner in Java when it comes to server development and server-side programming, and has developed the JavaServer Toolkit and Service API. The JavaServer Toolkit is a server framework from which other servers can be developed. One of the servers developed from this framework is the Java Web Server, formerly named Jeeves. Jeeves doesn't stand for anything--it's the name of a butler (and hence a SERVant). One of the key features (among many) of the JavaServer Toolkit is its support for Java server-side programming in the form of servlets. Servlets are the server-side analog to applets. JavaSoft has developed a Servlet API for servlet programming. This API is a standard extension to JDK 1.2. In this chapter, you'll install Java Web Server and learn how it works. You'll learn about servlets, cover the basics of the Servlet API, and develop a few servlets of your own. When you finish this chapter, you'll be able to use Java Web Server and servlets to build advanced Web sites. What Are the JavaServer Toolkit and Java Web Server? The JavaServer Toolkit is a framework for building Internet and intranet servers. It implements the functions that are common to many servers: - It listens on a port (or ports) for connection requests. - It accepts connection requests. - It creates threads to handle the requests. - It hands the connections to the threads for processing. - It manages the threads and connections. Besides providing these basic server functions, the Java Server Toolkit makes it easier to integrate the following advanced capabilities into the servers you develop: - Web-based remote administration - Authentication and access controls - Secure Sockets Layer (SSL) - Servlets support - HTTP 1.0 support - Dynamic Web page generation The JavaServer Toolkit provides a framework for developing Java-based server software. This framework was used to develop Java Web Server. Java Web Server is a top-of-the-line, fully HTTP 1.1-compliant Web server that provides a number of attractive features: - Java servlets can be used to replace CGI programs written in other languages. - Web pages can be dynamically compiled based on server code that is embedded in HTML files. - User connections with the Web server can be tracked and managed as interactive sessions. - Secure Sockets Layer and X.509 digital certificates can be used to provide privacy, integrity, and authentication services. - Templates for the presentation of HTML content are separately managed by the server. Of these features, this chapter will focus on the development of Java servlets. Information on other Java Web Server capabilities is covered in the server documentation. How Does Java Web Server Work? Because Java Web Server is built using the Java Server framework, it follows its basic execution paradigm. An acceptor listens for incoming connection requests on the TCP ports managed by the server. It hands off accepted connections to connection handlers. The connection handlers receive HTTP requests from Web server clients and load and invoke servlets to process the HTTP requests. Figure 47.1 provides an overview of Java Web Server's operation. FIGURE 47.1. How Java Web Server works. What's unique about the Java Server Toolkit, in general, and Java Web Server, in particular, is the use of servlets. Servlets are server extensions that are written in Java and are associated with particular URLs. When a request for the URL of a servlet is received from a Web browser, Java Web Server invokes the servlet to process the request. Java Web Server provides the servlet with all the information it needs to process the request. It also provides a mechanism for the servlet to send response information back to the Web browser. The Servlet API (covered later in this chapter in the section "The Servlet API") is used to develop servlets. Servlets can be preloaded by Java Web Server or loaded on-the-fly as they are needed. Installing Java Web Server In order to run the examples in this chapter, you'll need to download and install Java Web Server. It is available from JavaSoft at. Java Web Server for Windows 95 and NT is distributed as a self-extracting executable file. Run the file and follow the installation instructions to install Java Web Server on your system. Running Java Web Server Java Web Server comes with extensive documentation that describes its features and shows how they work. I'm not going to duplicate the documentation here, but I will give you enough information to get you up and running and to show you how to develop and use servlets. To start Java Web Server, open a DOS window, change to Java Web Server's bin directory, and run httpd, as follows: C:\JavaWebServer1.0.3\bin>httpd NOTE: If you installed Java Web Server as a service under Windows NT, it is automatically started when you reboot your machine. Java Web Server provides Web service on port 8080 as a default. This lets you use Java Web Server without having to stop your current Web server (if any). I've temporarily installed Java Web Server on a host named athome.jaworski.com. Figure 47.2 shows the server's default Web page, located at. FIGURE 47.2. The Java Web Server default Web page. The default Web page provides a link for you to administer your server. Follow this link to the server administration applet, shown in Figure 47.3. Note that server administration takes place on port 9090, as a default. FIGURE 47.3. The Java Web Server administration applet. You can log in to this applet to administer your server. I won't cover server administration in any more detail than you'll need to install a servlet. The Java Web Server documentation explains all aspects of server administration. To stop Java Web Server, just press Ctrl+C from within the DOS window in which it was started. On Windows NT, use the Services applet in the Control Panel to stop the Java Server service. Using Servlets Before I show you how to develop servlets, I'm going to whet your appetite by taking you on a tour of the servlets that come with Java Web Server. Open your Web server to the default Web page (). Next, click on the link to Administer the Web Server. Here you'll find two Health Check servlets, as shown in Figure 47.4. FIGURE 47.4. Links to Health Check Servlets. Click on the link to the Link Checker servlet. This servlet provides a handy tool to check for broken links in your Web documents, as shown in Figure 47.5. Go back to the previous page and click on the link to the Echo Servlet. This servlet echoes the Common Gateway Interface (CGI) parameters that are passed to it, as shown in Figure 47.6. You can use this servlet to debug your URLs. FIGURE 47.5. The Link Checker Servlet. FIGURE 47.6. The Echo Servlet. Now use your browser to open the following URL: Substitute your host name for your.host.name. The Protectedservlet illustrates the use of the access control features of Java Web Server. It prompts you with the login dialog, shown in Figure 47.7. If you fail to log in correctly three times, it displays the notice shown in Figure 47.8. If you do log in correctly (User name=jeeves and Password=jeeves), it displays the Web page shown in Figure 47.9. FIGURE 47.7. The authorization dialog box. FIGURE 47.8. Wrong password! FIGURE 47.9. The protected Web page. Writing Servlets Now that you have a taste for servlets, I'll show you how they work and help you to develop a couple of your own. Servlets are the server-side analog of applets. They are written to the Servlet API (covered in the next section) and are installed on a Web server. Besides Java Web Server, a number of Web servers support servlets and the Servlet API. The following list identifies some of these Web servers. A complete list can be obtained from. - Apache 1.1.3 - Netscape FastTrack 2.0, Enterprise 2.0, Enterprise 3.0 - Microsoft IIS 2.0, IIS 3.0 - Weblogic Tengah - Lotus Domino Go Webserver - IBM Internet Connection Server Servlets are located in the servlets directory of the Web server and can be invoked via the following URL:[?arguments] The name of your Web server host (and port number) are substituted for your.host.com:port, and the class name of your servlet is substituted for ServletName.class. The optional arguments are a standard URL-encoded query string. Java Web Server can also be configured to associate servlets with other URLs or to be invoked as the result of processing a particular type of URL. Consult the Java Web Server documentation for information on how to do this. Most likely, the servlets that you'll develop will be similar to CGI programs in the services they provide. The advantages of servlets over CGI programs are that there is minimal server overhead in invoking them, they are provided with direct access to server resources, and they are written in Java. THE SERVLET API The Servlet API is a Standard Extension API, meaning that it is not a part of the core Java Platform. See Chapter 51, "Java Platforms and Extensions," for a description of the Java Platform, the Core API, and the Standard Extension API. The Servlet API packages include the javax.servlet package and the javax.servlet.http package. The javax.servlet Package The javax.servlet package defines the following six interfaces and three classes: - javax.servlet interfaces - Servlet--The Servlet interface must be implemented by all servlets. The init() and destroy() methods are invoked by the server to start and stop a servlet. The getServletConfig() and getServletInfo() methods are over-ridden to return information about a servlet. The service() method is invoked by the server so that a servlet can perform its service. It has two parameters--one of the ServletRequest interface and one of the ServletResponse interface. - ServletRequest--The ServletRequest interface encapsulates a client request for service. It defines a number of methods for obtaining information about the server, requester, and request. The getInputStream() method returns an object of the ServletInputStream class that may be used to read request information sent by the client. - ServletResponse--The ServletResponse interface is used by a servlet to respond to a request by sending information back to the requester. The getOutputStream() method returns an object of the ServletOutputStream class that is used to send response information to the client. The getWriter() method returns a PrintWriter object that is used for client communication. The setContentType() method sets the MIME type of the response information. The setContentLength() method specifies the length of the response in bytes. The getCharacterEncoding() method returns the MIME type associated with the response. - ServletConfig--The ServletConfig interface is used by the server to pass configuration information to a servlet. Its methods are used by the servlet to retrieve this information. - ServletContext--The ServletContext interface defines the environment in which an applet is executed. It provides methods that are used by applets to access environment information. - SingleThreadModel--The SingleThreadModel interface is used to identify servlets that must be thread-safe. If a servlet implements this interface, the Web server will not concurrently execute the service() method of more than one instance of the servlet. - javax.servlet classes - GenericServlet--The GenericServlet class is a convenience class that implements the Servlet interface. You can subclass this class to define your own servlets. - ServletInputStream--The ServletInputStream class is used to access request information supplied by a Web client. An object of this class is returned by the getInputStream() method of the ServletRequest interface. - ServletOutputStream--The ServletOutputStream class is used to send response information to a Web client. An object of this class is returned by the getOutputStream() method of the ServletResponse interface. The javax.servlet.http Package The javax.servlet.http package is used to define HTTP-specific servlets. It defines the following interfaces and classes. - javax.servlet.http interfaces - HttpServletRequest--The HttpServletRequest interface extends the ServletRequest interface and adds methods for accessing the details of an HTTP request. - HttpServletResponse--The HttpServletResponse interface extends the ServletResponse interface and adds constants and methods for returning HTTP-specific responses. - HttpSession--This interface is implemented by servlets to enable them to support browser-server sessions that span multiple HTTP request-response pairs. Since HTTP is a stateless protocol, session state is maintained externally using client-side cookies or URL rewriting. This interface provides methods for reading and writing state values and managing sessions. - HttpSessionBindingListener--This event listening interface is imple-mented by classes whose objects are associated with HTTP sessions. The valueBound() method is used to notify an object that it is bound to an HTTP session, and the valueUnbound() method is used to notify an object that it is unbound from an HTTP session. - HttpSessionContext--This interface is used to represent a collection of HttpSession objects that are associated with session IDs. The getIds() method returns a list of session IDs. The getSession() method returns the HttpSession object associated with a particular session ID. Session IDs are implemented as String objects. - javax.servlet.http classes - Cookie--This class represents an HTTP cookie. Cookies are used to maintain session state over multiple HTTP requests. They are named data values that are created on the Web server and stored on individual browser clients. The Cookie class provides the method for getting and setting cookie values and attributes. - HttpServlet--The HttpServlet class extends the GenericServlet class to use the HttpServletRequest and HttpServletResponse interfaces. - HttpSessionBindingEvent--This class implements the event that is gen-erated when an object is bound to or unbound from an HTTP session. - HttpUtils--The HttpUtils class provides the parseQueryString() method for parsing a query string contained in an HTTP request. The TimeServlet Class The TimeServlet class, shown in Listing 47.1, is a simple servlet that will ease you into servlet programming. Compile the servlet and move the TimeServlet.class file to Java Web Server's servlets directory. Don't worry about the deprecation warning. I'll explain it in the next section. LISTING 47.1. THE TimeServlet CLASS. import javax.servlet.*; import java.util.*; import java.io.*; public class TimeServlet extends GenericServlet { public String getServletInfo() { return "Time Servlet"; } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String date=new Date().toString(); PrintStream outputStream = new PrintStream(response.getOutputStream()); outputStream.println(date); } } Next, you must install the servlet on Java Web Server. To do this, open the URL. Your server's administration applet is loaded and displays the login, shown in Figure 47.10. Log in as admin with the admin password. FIGURE 47.10. The server administration applet. After you log in, the administration main screen is displayed, as shown in Figure 47.11. Highlight the Web service and click on the Manage button to configure the Web service. FIGURE 47.11. The server administration main screen. The Web service administration screen is displayed, as shown in Figure 47.12. Click the Servlets button to add the TimeServlet. FIGURE 47.12. The Web service administration applet. The Servlets configuration screen is displayed, as shown in Figure 47.13. Click on Add in the selection list on the left of the screen to add a servlet to the list of servlets known to Java Web Server. FIGURE 47.13. The Servlet administration applet. An Add a New Servlet dialog appears, as shown in Figure 47.14. Enter TimeServlet for the servlet's name and TimeServlet.class for the servlet's class. Then click the Add button to add the servlet. FIGURE 47.14. The Add a New Servlet dialog. The screen is updated to display information about the servlet. Click the Load at Startup radio button to cause the servlet to be loaded automatically when the server starts. Then click the Save button to save the change. (See Figure 47.15.) FIGURE 47.15. Completing the servlet's configuration. You're finished configuring the servlet. Click the Load button to load the servlet, close the applet window, and then click the Log Out button to log out of the administration applet. Now you're ready to use the TimeServlet servlet. Open the URL. com:8080/servlet/TimeServlet.class to access the servlet. It displays the output shown in Figure 47.16. If that seems like a lot of work just to get the time, hang in there. The next servlet will be more interesting and informative. How TimeServlet Works In order to use servlets, you must import the javax.servlet package, as shown in Listing 47.1. The TimeServlet class extends the GenericServlet class and overrides the getServletInfo() and service() methods. The getServletInfo() method returns a string that provides information about the servlet. The service() method implements the actual servlet request handling and response handling. It is invoked by the Web server when the URL of the servlet is requested. The server passes the ServletRequest and ServletResponse arguments to the servlet. FIGURE 47.16. The TimeServlet's output display. The TimeServlet is pretty simple and does not need any particular information contained in the ServletRequest object to perform its processing. It creates a new Date object, converts it to a String, and stores it using the date variable. It uses the getOutputStream() method of the ServletResponse class to create a ServletOutputStream object for sending response information back to the browser client. The ServletOutputStream object is filtered as a PrintStream. NOTE: When you compile TimeServlet, you get a deprecation warning because you used PrintStream instead of its PrintWriter replacement. Finally, you write the date string to the output stream to send it to the browser client. The EchoRequest Servlet The EchoRequest servlet, shown in Listing 47.2, shows how ServletRequest parameters are processed. Compile EchoRequest.java and copy the EchoRequest.class file to the servlets directory used by Java Web Server. Again, don't worry about the deprecation warning. Configure EchoRequest using the administration applet, as discussed for TimeServlet. Set its name to EchoRequest and its class name to EchoRequest.class. (See Figure 47.17.) LISTING 47.2. THE EchoRequest SERVLET. import javax.servlet.*; import java.util.*; import java.io.*; public class EchoRequest extends GenericServlet { public String getServletInfo() { return "Echo Request Servlet"; } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintStream outputStream = new PrintStream(response.getOutputStream()); outputStream.print("Server: "+request.getServerName()+":"); outputStream.println(request.getServerPort()); outputStream.print("Client: "+request.getRemoteHost()+" "); outputStream.println(request.getRemoteAddr()); outputStream.println("Protocol: "+request.getProtocol()); Enumeration params = request.getParameterNames(); if(params != null) { while(params.hasMoreElements()){ String param = (String) params.nextElement(); String value = request.getParameter(param); outputStream.println(param+" = "+value); } } } } FIGURE 47.17. Configuring the EchoRequest servlet. Open the URL. It displays the IP address and port number of the Java Web Server Web server, and the host name and address of the computer on which your browser resides. It also displays the version of the HTTP protocol being used. (See Figure 47.18.) FIGURE 47.18. Using the EchoRequest servlet. Now open the same URL with the ?n1=v1&n2=v2&n3=v3 query string appended. EchoRequest displays the name value pairs in the query string, as shown in Figure 47.19. You can also use EchoRequest with forms. Copy the formtest.htm file, shown in Listing 47.3, to the public_html directory of your Web server. Open it with the URL. The form shown in Figure 47.20 is displayed. LISTING 47.3. THE formtest.htm FILE. <HTML> <HEAD> <TITLE>Using a form with EchoRequest</TITLE> </HEAD> <BODY> <FORM ACTION="servlet/EchoRequest.class"> Enter text: <INPUT NAME="textField" TYPE="TEXT" SIZE="30"><P> Check this out: <INPUT NAME="checkbox" TYPE="CHECKBOX"><P> Select me: <SELECT NAME="mySelection"> <OPTION>Number one <OPTION>Number two <OPTION>Number three </SELECT><P> <INPUT NAME="Submit" TYPE="SUBMIT"> </FORM> </BODY> </HTML> FIGURE 47.19. Using the EchoRequest servlet with a query string. Enter a value for the text field, check or uncheck the text box, and make a selection from the selection list. Then click the Submit button. The EchoRequest servlet is invoked to process the form. It displays the output shown in Figure 47.21. Note that it correctly identifies the form values that you submitted. FIGURE 47.20. Using the EchoRequest servlet with an HTML form. FIGURE 47.21. EchoRequest displays the data you entered in the form. How EchoRequest Works As you would expect, the overall structure of EchoRequest is the same as TimeServlet. Both servlets extend GenericServlet and override the getServletInfo() and service() methods. The service() method of EchoRequest begins by setting the content type of the response to the text/plain MIME type. We set the MIME type because we'll be generating more than one line of output and we don't want the browser client to mistake it for HTML. Next, service() creates an output stream in the same manner as TimeServlet, using the getOutputStream() method of the ServletResponse interface. It then prints information about the server, client, and protocol that it obtains using the getServerName(), getServerPort(), getRemoteHost(), getRemoteAddr(), and getProtocol() methods of the ServletRequest interface. The service() method invokes the getParameterNames() method of the ServletRequest interface to retrieve an enumeration of the parameter names that are passed in the query string of the HTTP request. It displays each parameter name along with its value. The parameter values are retrieved via the getParameter() method of the ServletRequest interface. Summary In this chapter, you installed Java Server and learned how it works. You learned about servlets and about the basics of the Servlet API. You then developed the TimeServlet and the EchoRequest servlet and learned how servlets can be used to process form data. In the next chapter, you'll learn more about the Servlet API and how to use servlets with other Web servers.
http://www.webbasedprogramming.com/Java-1.2-Unleashed/ch47.htm
crawl-002
refinedweb
3,743
58.38
> -----Original Message----- > From: Simon Nash [mailto:nash@apache.org] > Sent: Monday, November 21, 2011 7:49 PM > To: user@tuscany.apache.org > Subject: Re: Wrong result type in web service operation > > Scott Kurz wrote: > > Sebastian, > > > > Do you have a tool to show you the SOAP request being sent over the > wire? > > > > I don't think we have a lot of Tuscany logging in place, but Axis2 > has > > some logging that could be enabled if we had to. > > > > Scott > > > TCPMon is a convenient way of doing this if you're able to change the > sending or receiving port number. If not, you could use Wireshark > which is an excellent tool. > > Simon Thanks for the pointer to TCPMon. I routed two requests through localhost:9090. The good request is from the wrapped style interaction. The bad one is from the bare style interaction which is the subject of this conversation. The bad request has a non-empty SOAP action and is missing the namespace for the operation in the SOAP body. The latter difference is clearly significant, as pasting this SOAP-XML into a client like SOAP-UI will produce the same fault that I am seeing in Tuscany. BTW, The Axis2 logging can be enabled by placing a log4j.properties file on the classpath, but the logging output is not very helpful, as it mainly traces processing steps without showing the attendant data. --
http://mail-archives.apache.org/mod_mbox/tuscany-user/201111.mbox/%3C32F15738E8E5524DA4F01A0FA4A8E4906C919BF3@hqmbx2.eur.ad.sag%3E
CC-MAIN-2016-26
refinedweb
232
72.56
This post describes how to build an static version of OpenCV for Linux operating systems. I am going to use OpenCV version 3.1.0 and Ubuntu 16.04 64-bit but the process should be more or less the same under CentOS or other flavors of Linux. So let’s start. Following are the requirements for building OpenCV: - OpenCV 3.1.0 for Linux/Mac (can be found here) - CMake (just use Ubuntu Software to get it. I am going to use the CMake GUI to comfortably set all the options but if you feel more like a genius by typing some commands in the terminal then you can go ahead and type “sudo apt-get install cmake” and some similar commands to get it.) Extract OpenCV archive and run CMake. Make sure you set the source and bin folders as seen below. (Of course you should use the folder paths from your own computer and PLEASE don’t use my name, please.) Just make sure build folder is under the source folder. Now hit Configure button. You will be asked to approve creating the binaries folder as seen below. Just press Yes to continue. Next you have to make sure Unix Makefiles are selected in the CMakeSetup dialog as seen here. Press Finish to proceed. And Yes, now you have to wait for the following to appear. Be patient. Go through the options in red and make sure to uncheck BUILD_SHARED_LIBS option. Also change CMAKE_INSTALL_PREFIX to where you want to install your static libraries. I prefer my home folder so I set CMAKE_INSTALL_PREFIX option to “/home/amin/opencv” After setting the above options make sure you press Configure once again. After it’s done, press Generate to create make files. You can safely close CMake and forget it ever existed. Now it’s time to start compiling OpenCV, so open up a terminal window and enter the following commands: cd Downloads/opencv-3.1.0/build sudo make No need to repeat that you have to enter the same folder you did for binary folder in CMake instead of “Downloads/opencv-3.1.0/build” right? Wait for a while until building is finished. Then enter one last command to finish it off. sudo make install Voila, now you have a static build of OpenCV 3.1.0 under the same folder you entered for CMAKE_INSTALL_PREFIX. Mine was “/home/amin/opencv” so if I check that folder you’ll see that I have all required files there. Good job and thank you! 🙂 Can you give a tutorial about how to use the opencv static libraries? Can you tell me exactly what you mean by “How to use OpenCV static Libs”? Are you looking for something like this: (It’s for Qt on Linux but everywhere the answer is more or less the same) I need to use the static libraries of the opencv as libs of a makefile project in eclipse. My makefile: ” INCDIR = ./include LIBDIR = ./lib SRCDIR = ./src OPENCVDIR = /home/spaf94/opencv_static/lib OPENCVINC = /home/spaf94/opencv_static/include CXXFLAGS = -O2 -g -Wall -fmessage-length=0 -I$(INCDIR) -I$(OPENCVINC) -L$(OPENCVDIR) VPATH = $(SRCDIR) OBJS = test20161105.o LIBS += $(OPENCVDIR)/libopencv_highgui.a $(OPENCVDIR)/libopencv_core.a TARGET = test20161105 $(TARGET): $(OBJS) $(CXX) -o $(TARGET) $(OBJS) $(LIBS) all: $(TARGET) clean: rm -f $(OBJS) $(TARGET) ” With this, I create a simple cpp file to show an image: ” #include #include #include using namespace cv; int main(void) { Mat image; image = imread(“/home/spaf94/Imagens/opencv.png”, CV_LOAD_IMAGE_COLOR); return 0; } ” But when I compile, I got errors in the static libraries … “Indefinite reference to [functions name of the opencv]” I don’t have much experience with Eclipse but you should look for a method to add pkgconfig in Eclipse if you want the better option. If you still insist on manually entering all libs, then make sure you add them correctly. Here is an example of how I do it: LIBS += -L[OPENCV_LIBS_DIR] -lopencv_core -lopencv_imgproc -lopencv_imgcodecs -lopencv_videoio -lopencv_objdetect Obviously you should replace [OPENCV_LIBS_DIR] with the correct directory on your system. And one final note, don’t worry about the name of the library being “libopencv_core.a” and so on. “-L” and “-l” options are taking care of that. Ok thank you very much for the help 🙂 Glad to be of help to fellow engineers and researchers 🙂
http://amin-ahmadi.com/2016/09/19/build-opencv-statically-for-linux/
CC-MAIN-2017-04
refinedweb
721
73.37
Introduction to OpenCV save image OpenCV save image() is a method which is present in the OpenCV Public Library that enables the system to save a provided image data, which is in the form of a ndarray data into a file by making use of the imwrite() function present in the OpenCV library available for Python programming language. The OpenCV library is a public domain that has an array of methods that help in performing various operations on the image files, but for operating that it is important that the system can read the image file provided as the source/input and then the various operations can be performed on it and later after the processing is completed this file can be saved and used further by the user. While the user is working with these processed images for various applications, it is generally noted that the user needs to store the resultant intermediate images or the final resultant images while the process of transformation is occurring. For the system being able to save this processed image within the local filing system, the OpenCV save image method (cv2.imwrite()) is most commonly used. Syntax for using OpenCV save image() the following is the syntax that needs to be used for operating on images and saving them in the filing system: cv2.imwrite('/path/to/destination/finalimagename.png,image) Parameter for using OpenCV save image() The following parameters are used within the syntax for the OpenCV save image function, which enables the command to save images within the local filing system: Formats / Extensions that are supported for OpenCV save image() When OpenCV read image function reeds the image that has to be processed for any specific procedure to be performed by the system, it does not generally consider the extension of the image file being processed to determine the format for the image file image. rather it is seen to be deciding the extension for the image to be based upon the format for the file which has been presented in the file data respective to the image. Window bitmaps – (eg: .bmp, .dib); JPEG files – (eg: .jpeg, .jpg, .jpe); Portable Network Graphics – (eg: .png); Portable image format– (eg: .pbm, .ppm .pgm); TIFF files – (eg: .tiff, .tif) Following are the parameters that are being currently supported for the method: - For files with extension .JPEG, the quality can be between 0 – 100. The default value for JPEG files is 95. - For files with extension .PNG, the quality for the compress level can be between 0 -9. The default value for PNG files is 1. - For files with extension PPM, PBM or PGM, there can be a binary format flag with a value of either 0 or 1. The default value for the files with these extensions is 1. Example of OpenCV save image() # command used to import the OpenCV library to utilize OpenCV read image function import cv2 # command used for reading an image from the disk disk, cv2.imread function is used # reading the image as a grey scaled image img1 * = * cv2.imread * (* r * ' * C *:\ * Users * \ * PRIYANKA BANERJEE\ * educba.png', * * * * 1) # saving the image into * * * the * * * filing * * * system status1 * = * cv2.imwrite * (* r * ' * C *: * \ * Users * \ * PRIYANKA BANERJEE * \educba1.jpeg', * * 0, * img1) print("The image file needs to be written to the file-system : ", * status1) cv2.waitKey(0) cv2.destroyAllWindows() Output for Example: Conclusion It is one of the most extensively used commands for processing any image file and executive any function related to image processing and detection in the Python programming language. While the user is working with these processed images for various applications, it is generally noted that the user needs to store the resultant intermediate images or the final resultant images while the process of transformation is occurring. For the system to be able to save this processed image within the local filing system, the OpenCV save image method. Recommended Articles This is a guide to OpenCV save image. Here we discuss the Formats / Extensions that are supported for OpenCV save image() along with the example. You may also have a look at the following articles to learn more –
https://www.educba.com/opencv-save-image/
CC-MAIN-2021-49
refinedweb
688
59.33
Hello - I have a SMX 4 issue where a OSGi bundle that imports javax.xml.namespace isn't able to find javax.xml.namespace.QName at runtime (class not found). The bundle itself loads into SMX 4 just fine, and the manifest definitely imports javax.xml.namespace. I see that SMX 4 isn't exposing the version of the javax.xml.namespace package that comes with Java 1.5/1.6, but is using and Apache reference implementation instead. The Jar is in: org/apache/servicemix/specs/org.apache.servicemix.specs.jaxp-api-1.4/1.2.0.0-fuse I see that this Jar is installed in my SMX 4 instance when I start it up, and it looks like it exports the javax.xml.namespace package, so I'm baffled. Has anyone else come across this? -Oliver I figured this one out. I had loaded an XmlBeans bundle from the Spring OSGi bundle repository, and it didn't have an import for the javax.xml.namespace in the Manifest. So it was that bundle trying to load javax.xml.namespace.QName, not my application bundle. I think the Spring bundle was probably tested in an OSGi container that included the built-in Java 1.5/1.6 javax.xml.namespace package by default (which SMX doesn't - it substitutes an Apache version). So that's why it worked for whoever built it. I guess substituting for JDK packages still has its gotchas, even in an OSGi world! I'm pretty new to OSGi, but it seems like there are quite a few class loading details to be aware of. One thing that would be beneficial is for class loading error messages to print out a bit of information about the bundle that is trying to load the class. That would have been a timesaver in this case since I got faked out and thought it was my App bundle having the problem. -Oliver Good idea about the detailed error message. Feel free to raise a RFE at the JIRA for it:
https://developer.jboss.org/thread/244260
CC-MAIN-2018-09
refinedweb
343
67.96
If else Statement C# if else Statement we presented last time is only good if you want to execute a code when one condition is met. But what would you do if you want execute another set of codes when that condition is not met? The if else statement serves this purpose because it is a double selection conditional statement. It means you can specify another behavior when the specified condition is false. Below is the syntax of an if else statement. if (condition) { code to execute if condition is true; } else { code to execute if condition is false; } The else keyword can’t be used by itself. It must have a matching if statement. The curly braces are optional if you only have one statement to execute for each of the body of if and else. The code inside the else block will only be executed if the condition inside the if statement results to false. I’ll show you an example of using the if else statement. using System; namespace IfElseStatementDemo { public class Program { public static void Main() { int number = 5; //Test the condition if (number < 10) { Console.WriteLine("The number is less than 10."); } else { Console.WriteLine("The number is either greater than or equal to 10."); } //Modify value of number number = 15; //Repeat the test to yield a different result if (number < 10) { Console.WriteLine("The number is less than 10."); } else { Console.WriteLine("The number is either greater than or equal to 10."); } } } } Example 1 – Using the if else Statement The number is less than 10. The number is either greater than or equal to 10. The output shows the functionality of the if else statement. When the value of number is less than 10, it met the condition and executes the code that is inside the if block. When the value of number was modified to have a value which is greater than 10, the condition resulted to false and the code block of else was executed. Do not use the else block if it has no corresponding if block. Like the if statement, do not add a semicolon immediately after the else keyword.
https://compitionpoint.com/if-else-statement/
CC-MAIN-2021-21
refinedweb
360
72.97
- Name same state information. Since the objects which are created are based on a prototype,which is the original object, so this pattern is called Prototype pattern. Following are the uses of the Prototype pattern - This pattern is useful if we want to create a copy of an object which is expensive or resource intensive to create.Suppose if we are creating an object which contains data which is fetched from a database through a web service.Now we need to create many more identical objects of this type.In this case it is better if we can reuse the existing object rather than creating new objects multiple times. - We are not required to explicitly set the same properties on a class.Duplication of code is avoided. Implementation In the Prototype object define a clone() method.There is an interface called ICloneable which specifies this method.Our prototype can implement this ICloneable interface. Example of Prototype Pattern In this example we are taking the example of a School.In a School many students are there and most of the attributes of students are similar.For example students in the same grade will have same subjects.A student has just a few attributes that identifies him.For example student has Name and RollNo which uniquely identifies him. Since details of Students are fetched from a database so retrieving all the students details from the database could be unnecessary and expensive operation.So we can fetch just the necessary information from the database and use the prototype pattern to create copies of these objects. We can then fetch the required information for each student such as name and roll number.Since fetching only the required information from the database is less expensive than fetching all the duplicate information so Prototype pattern is a suitable pattern to use here. abstract class Student { public string Name {get;set;} public string RollNo { get; set; } public string SchoolName { get; set; } public string SchoolAddress { get; set; } public string SchoolStrength { get; set; } public string Principal { get; set; } public abstract Student Clone(); } public class HighSchoolStudent:Student { //Subjects are unique for High School Students public List<Subject> Subjects { get; set; } public override Student Clone() { return this.MemberwiseClone() as Student; } } HighSchoolStudent is a type of student who belongs to HighSchool.All HighSchool students share the same subjects.The attributes which makes them unique are the roll number and name. So we will fetch only a single record for a high school student.Then we fetch only the roll numbers and names of all the students.Finally we clone the single high school student that we fetched and assign the name and roll number to the cloned student. static void Main(string[] args) { StudenService svc=new StudenService(); //GetHighSchoolStudent method will fetch a single record for a high school student Student student = svc.GetHighSchoolStudent(); //GetNamesandRollNo will fetch the names and roll nos of students in high school Dictionary<string, string> nameAndRollNos = svc.GetNamesandRollNo(); foreach(var stud in nameAndRollNos) { Student highSchoolstudent = student.Clone(); highSchoolstudent.RollNo = stud.Key; highSchoolstudent.Name = stud.Value; } } So this pattern is useful when we want to create many new objects based on some blueprint.This blueprint is specified by the prototype object.
https://codecompiled.com/use-and-example-of-prototype-design-pattern
CC-MAIN-2021-49
refinedweb
532
55.64
A computer-aided drawing using conformal mapping and hyperbolic tiling. The title is taken from ancient Greek mythology. I found some old but cool software for numerical conformal mapping: Zipper. It's slightly weird to use, but it seems quite powerful. For my purposes I didn't like the way it skipped output for points that weren't inside the target region, so I patched its FORTRAN 77 code to output nonsense values instead. This makes sure that the Nth line of output corresponds to the Nth line of input. diff -ruw conformal/zipper/inverse.f conformal-new/zipper/inverse.f --- conformal/zipper/inverse.f 2010-10-12 16:51:27.000000000 +0100 +++ conformal-new/zipper/inverse.f 2013-08-17 02:41:54.644940816 +0100 @@ -76,11 +76,8 @@ c a circle to the disk is not 1-1 on the outside. c thus we will just delete these points. if(x*x+y*y.gt.(1.d0+1.d-8))then - write(*,*)' ' - write(*,*)' z(j) outside region, so pullback outside disk,' - write(*,*)' and will be eliminated from output.' - write(*,*)' j=',j,' inverse of z(j)=', z(j) - goto 984 + x=-100 + y=-100 endif write(3,999)x,y 984 continue Zipper's demo csh script provided me with enough clues to write my own driver script in bash: #!/bin/bash # generate raw mipmap data for the source tex.png for d in 1024 512 256 128 64 32 16 8 4 2 1 do convert tex.png -geometry "${d}x${d}" tmp.ppm tail -c "$(( d * d * 3))" tmp.ppm done > texture.rgb # generate the shape to fill with butterflies ./curve > init.dat # massage the shape into zipper input ./zipper/polygon >/dev/null <<-"EOF" init.dat 500 poly.dat EOF # compute the conformal mapping ./zipper/zipper >/dev/null # calculate the pre-images in the unit disk for each pixel rm "preimage.grid" touch "preimage.grid" for j in $(seq 1800) do ./row "${j}" > "grid.dat" ./zipper/inverse >/dev/null <<-"EOF" grid.dat grid.pre EOF cat "grid.pre" >> "preimage.grid" done # fill with a textured hyperbolic tiling ./tile < preimage.grid > tiling.ppm # finally composite with the bottle and stopper in gimp I wanted to generate an image with 2:3 aspect ratio, so I chose the logical coordinates of the image to be in [0,4]x[0,6]. I wanted a reasonable resolution, so the device dimensions are 1200x1800. I generate mipmaps from the base texture for anti-aliasing. Generating the boundary curve is quite easy, as zipper/polygon reads input from a text file with one point per line, with the last point specifying which point inside the simple closed curve formed from the previous points will be mapped to the origin of the unit disk. My curve has a regular octagon at the bottom with the centre of the top edge at (2,1). The edge length is e and the centre of the octagon is at (2,h), with r being the distance from the centre to each vertex. The neck of the bottle has height e/2, and then it extends up and out at 45 degrees to far beyond the page boundaries (to avoid a visible edge within the final image). #include <math.h> #include <stdio.h> const double pi = 3.141592653589793; int main(int argc, char **argv) { double e = 1 / (1.5 + sqrt(2)); double h = e * (1 + sqrt(0.5)); double r = sqrt((e/2)*(e/2) + (h-e/2)*(h-e/2)); double x, y; for (int i = 0; i < 8; ++i) { double t = pi / 2 + pi / 8 + i * pi / 4; x = 2 + r * cos(t); y = h + r * sin(t); printf("%f %f\n", x, y); } y += e/2; printf("%f %f\n", x, y); x += 20; y += 20; printf("%f %f\n", x, y); x -= 20 + e + 20; printf("%f %f\n", x, y); x += 20; y -= 20; printf("%f %f\n", x, y); printf("%f %f\n", 2.0, 1.0); return 0; } Zipper's inverse program has a hardcoded limit on the number of points it can transform, and rather than try and fix it I split my input into smaller batches - one for each row of pixels in the output image. Outputting a row's coordinates to a text file works like this: #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { int j = atoi(argv[1]); double y = j / 1800.0 * 6; for (int i = 1; i <= 1200; ++i) { double x = i / 1200.0 * 4; printf("%f %f\n", x, y); } return 0; } The last step in the driver script takes the transformed coordinates (which are now inside the unit disc, or (-100,-100) for points that were outside the region) and computes the colour for each pixel. First define some constants and global variables (not the best coding style, but it worked for this small program): #include <math.h> #include <stdio.h> const double pi = 3.141592653589793; const double c = -0.5; // cos(2 * pi / 3) const double s = 0.8660254037844387; // sin(2 * pi / 3) const double sqrt3 = 1.7320508075688772; // sqrt(3) static double center, radius; static int lod = 0; Here center and radius will be set to the circle that forms the right hand edge of an equilateral hyperbolic triangle centred at the origin in the Poincaré disk, and lod is used to pass the computed mipmap level of detail from the main loop through to the texture lookup. The texture lookup code is probably the worst code I've written for some time. There's a huge global structure to contain the raw texture data read from disk, and copy/paste coding to grab the right mipmap level's data and send it to stdout. static struct { unsigned char m10[1024][1024][3]; unsigned char m9[512][512][3]; unsigned char m8[256][256][3]; unsigned char m7[128][128][3]; unsigned char m6[64][64][3]; unsigned char m5[32][32][3]; unsigned char m4[16][16][3]; unsigned char m3[8][8][3]; unsigned char m2[4][4][3]; unsigned char m1[2][2][3]; unsigned char m0[1][1][3]; } texture; void texture2D(int j, int i) { i >>= (10 - lod); j >>= (10 - lod); switch (lod) { case 10: putchar(texture.m10[j][i][0]); putchar(texture.m10[j][i][1]); putchar(texture.m10[j][i][2]); break; // ... and so on all the way down to ... case 0: putchar(texture.m0[j][i][0]); putchar(texture.m0[j][i][1]); putchar(texture.m0[j][i][2]); break; } } The hyperbolic tiling is generated by reflections in the sides of the hyperbolic triangle mentioned earlier. Hyperbolic reflection in the Poincaré disk model is circle inversion. There are three sides, so there are three transforms, and each side is rotated about the origin by 2pi/3. The circle inversion is implemented once in transform1(). void rotate(double x, double y, double *x0, double *y0) { *x0 = c * x + s * y; *y0 = -s * x + c * y; } void unrotate(double x, double y, double *x0, double *y0) { *x0 = c * x - s * y; *y0 = s * x + c * y; } void transform1(double x, double y, double *x0, double *y0) { double x1, y1, r1, x2, y2; x1 = (x - center) / radius; y1 = y / radius; r1 = x1*x1+y1*y1; x2 = x1 / r1; y2 = y1 / r1; *x0 = x2 * radius + center; *y0 = y2 * radius; } void transform2(double x, double y, double *x0, double *y0) { double x1, y1, x2, y2; rotate(x, y, &x1, &y1); transform1(x1, y1, &x2, &y2); unrotate(x2, y2, x0, y0); } void transform3(double x, double y, double *x0, double *y0) { double x1, y1, x2, y2; unrotate(x, y, &x1, &y1); transform1(x1, y1, &x2, &y2); rotate(x2, y2, x0, y0); } The process of generating a tiling is by reflecting the original point in all the sides. If the new points are all further away from the origin, then the original point must be in the root triangle, otherwise pick the the new point that is closest to the origin and repeat (giving up if it takes too many steps). Once within the root triangle, reflect in the x-axis if necessary so that there are an even number of reflections in total - this makes the orientation of all the triangles the same. This is particularly important as some tilings might have paths with different numbers of reflections from nearby original points in the same triangle to their final points in the root triangle, which would give an unsightly seam. Once this terminates, if we're in the root triangle then we need to look up the pixel colour from the texture. But a hyperbolic triangle is curved, and a texture is a flat square grid. I used ternary coordinates, computing the distance from each edge in the hyperbolic triangle, and using their ratios to compute a point in a flat triangle embedded in a square. The distance() function here is actually Euclidean distance which is not quite right, but the maths for hyperbolic distance is much more involved, and I'd need to work out how to find the closest point on a given line to a given point in the Poincaré disk model. double distance(double x, double y) { double dx = x - center; double dy = y; return sqrt(dx * dx + dy * dy) - radius; } void colour(double x, double y, double r, int depth) { if (0 < depth && r < 1) { double x1, y1, r1, x2, y2, r2, x3, y3, r3; transform1(x, y, &x1, &y1); r1 = x1*x1+y1*y1; transform2(x, y, &x2, &y2); r2 = x2*x2+y2*y2; transform3(x, y, &x3, &y3); r3 = x3*x3+y3*y3; if (r <= r1 && r <= r2 && r <= r3) { if (depth & 1) { y = -y; } rotate(x, y, &x1, &y1); unrotate(x, y, &x2, &y2); double a = distance(x, y); double b = distance(x1, y1); double c = distance(x2, y2); double k = a + b + c; a /= k; b /= k; c /= k; double u = b + c / 2; double v = sqrt3 * c / 2; int i = fmin(fmax(1024 * u, 0), 1023); int j = fmin(fmax(1024 * v, 0), 1023); texture2D(j, i); } else if (r1 <= r2 && r1 <= r3) { colour(x1, y1, r1, depth - 1); } else if (r2 <= r1 && r2 <= r3) { colour(x2, y2, r2, depth - 1); } else if (r3 <= r1 && r3 <= r2) { colour(x3, y3, r3, depth - 1); } else { putchar(255); putchar(255); putchar(255); } } else { putchar(255); putchar(255); putchar(255); } } The main program computes the generating triangle (here a {3,7} tiling) and reads the raw texture mipmap data. Then it spits out a PPM header, and computes colours for all the input coordinates. The most interesting part is the level of detail computation: h is the hyperbolic distance between two neighbouring pixels, the ratio of this to a base distance h0 determines how much the image has been stretched or shrunk - looking up into an appropriately filtered and downscaled texture for parts that are shrunk is the essence of mipmapping, providing a computationally cheap way to avoid aliasing. int main(int argc, char **argv) { double dh = cos(pi / 7) / sin(pi / 3); double de = sqrt((dh - 1) / (dh + 1)); radius = (1 - de * de) / (2 * de); center = radius + de; FILE *tex = fopen("texture.rgb", "rb"); fread(&texture, sizeof(texture), 1, tex); fclose(tex); printf("P6\n1200 1800\n255\n"); double x, y; double ox = 0, oy = 0; double h0 = acosh(dh) * sqrt3 / 256; while (2 == scanf("%lf %lf\n", &x, &y)) { double h = acosh(1 + 2 * ((x - ox) * (x - ox) + (y - oy) * (y - oy)) / ((1 - x * x - y * y) * (1 - ox * ox - oy * oy))); lod = 10 - log2(h / h0); lod = lod < 0 ? 0 : lod > 10 ? 10 : lod; colour(x, y, x*x+y*y, 32); ox = x; oy = y; } return 0; } There are a few enhancements left to do (mainly interpolation within and between texture mipmap levels for smoother appearance), and it might be fun in the future to make an animation of the stopper being removed, but it's good ennough for now.
http://mathr.co.uk/blog/2013-08-17_elpis.html
CC-MAIN-2017-17
refinedweb
1,997
66.67
Table Of Contents Clock object¶ The removed.¶ New in version max_iteration property: from kivy.clock import Clock Clock.max_iteration = 20 Triggered Events¶ New in version 1.0.5. A triggered event is a way to defer a callback exactly like schedule_once(), but with some added convenience. The callback will only be scheduled once per frame even if you call the trigger twice (or more). This is not the case with Clock.schedule_once(): # will run the callback twice before the next frame Clock.schedule_once(my_callback) Clock.schedule_once(my_callback) # will run the callback once before the next frame t = Clock.create_trigger(my_callback) t() t() Before triggered events, you may have used this approach in a widget: def trigger_callback(self, *largs): Clock.unschedule(self.callback) Clock.schedule_once(self.callback) As soon as you call trigger_callback(), it will correctly schedule the callback once in the next frame. It is more convenient to create and bind to the triggered event than using Clock. Note ClockBase.create_trigger() also has a timeout parameter that behaves exactly like ClockBase.schedule_once(). Threading¶ New in version 1.9.0. Often, other threads are used to schedule callbacks with kivy’s main thread using ClockBase. Therefore, it’s important to know what is thread safe and what isn’t. All the ClockBase and ClockEvent methods are safe with respect to kivy’s thread. That is, it’s always safe to call these methods from a single thread that is not the kivy thread. However, there are no guarantees as to the order in which these callbacks will be executed. Calling a previously created trigger from two different threads (even if one of them is the kivy thread), or calling the trigger and its ClockEvent.cancel() method from two different threads at the same time is not safe. That is, although no exception will be raised, there no guarantees that calling the trigger from two different threads will not result in the callback being executed twice, or not executed at all. Similarly, such issues might arise when calling the trigger and canceling it with ClockBase.unschedule() or ClockEvent.cancel() from two threads simultaneously. Therefore, it is safe to call ClockBase.create_trigger(), ClockBase.schedule_once(), ClockBase.schedule_interval(), or call or cancel a previously created trigger from an external thread. The following code, though, is not safe because it calls or cancels from two threads simultaneously without any locking mechanism: event = Clock.create_trigger(func) # in thread 1 event() # in thread 2 event() # now, the event may be scheduled twice or once # the following is also unsafe # in thread 1 event() # in thread 2 event.cancel() # now, the event may or may not be scheduled and a subsequent call # may schedule it twice Note, in the code above, thread 1 or thread 2 could be the kivy thread, not just an external thread. - class kivy.clock.ClockBase[source]¶ Bases: kivy.clock._ClockBase A clock object with event support. - create_trigger(callback, timeout=0)[source]¶ Create a Trigger event. Check module documentation for more information. New in version 1.0.5. - frames[source]¶ Number of internal frames (not necesseraly drawed) from the start of the clock. New in version 1.8.0. - frametime[source]¶. - max_iteration¶ New in version 1.0.5: When a schedule_once is used with -1, you can add a limit on how iteration will be allowed. That is here to prevent too much relayout. - schedule_interval(callback, timeout)[source]¶ Schedule an event to be called every <timeout> seconds. - schedule_once(callback, timeout=0)[source]¶ Schedule an event in <timeout> seconds. If <timeout> is unspecified or 0, the callback will be called after the next frame is rendered. Changed in version 1.0.5: If the timeout is -1, the callback will be called before the next frame (at tick_draw()). - tick()[source]¶ Advance the clock to the next step. Must be called every frame. The default clock has a tick() function called by the core Kivy framework. - class kivy.clock.ClockEvent(clock, loop, callback, timeout, starttime, cid, trigger=False)[source]¶ Bases: object A class that describes a callback scheduled with kivy’s Clock. This class is never created by the user; instead, kivy creates and returns an instance of this class when scheduling a callback. Warning Most of the methods of this class are internal and can change without notice. The only exception are the cancel() and __call__() methods. - kivy.clock.mainthread(func)[source]¶ Decorator that will schedule the call of the function in the mainthread. It can be useful when you use UrlRequest or when you do Thread programming: you cannot do any OpenGL-related work in a thread. Please note that this method will return directly and no result can be returned: @mainthread def callback(self, *args): print('The request succedded!' 'This callback is call in the main thread') self.req = UrlRequest(url='http://...', on_success=callback) New in version 1.8.0.
http://kivy.org/docs/api-kivy.clock.html
CC-MAIN-2014-42
refinedweb
806
66.94
SSL and TLS Transports Reference The following Mule transports provide access to TCP connections: The TCP Transport, which uses the basic TCP transport. The Secure Sockets Layer (SSL) and Transport Layer Security (TLS) transports use TCP with socket-level security. Other than the type of socket used, these transports all behave quite similarly. The SSL transport allows sending or receiving messages over SSL connections. SSL is a layer over IP and implements many other reliable protocols such as HTTPS and SMTPS. However, you may want to use the SSL transport directly if you require a specific protocol for reading the message payload that is not supported by one of these higher level protocols. This is often the case when communicating with legacy or native system applications that don’t support web services. Namespace and Syntax XML namespace: XML schema location: Connector syntax: Protocol Types PROTOCOL-TYPE defines how messages in Mule are reconstituted from the data packets. The protocol types are: Endpoint syntax: You can define your endpoints 2 different ways: Prefixed endpoint: <ssl:inbound-endpoint Non-prefixed URI: <inbound-endpoint See the sections below for more information. Considerations SSL is one of the standard communication protocols used on the Internet, and supports secure communication both across the internet and within a local area network. The Mule SSL transport uses native Java socket support, adding no communication overhead to the classes in java.net, while allowing many of the advanced features of SSL programming to be specified in the Mule configuration rather than coded in Java. Use this transport when communicating using low-level SSL using. As shown in the examples below, the SSL transport can be used to Create an SSL Server an SSL server Send Messages to an SSL Server messages to an SSL server The use of SSL with Java is described in detail in the JSSE Reference Guide. In particular, it describes the keystores used by SSL, how the certificates they contain are used, and how to create and maintain them. Features The SSL module allows a Mule application both to send and receive messages over SSL connections, and to declaratively customize the following features of SSL SSL endpoints can be used in one of two ways: To create an SSL server that accepts incoming connections, declare an inbound ssl endpoint with an ssl:connector. This creates an SSL server socket that reads requests from and optionally writes responses to client sockets. To write to an SSL server, create an outbound endpoint with an ssl:connector. This creates an SSL client socket that writes requests to and optionally reads responses from a server socket. To use SSL endpoints, follow the following steps: Add the MULE SSL namespace to your configuration: Define the SSL prefix using xmlns:ssl="" Define the schema location with Define one or more connectors for SSL endpoints. Create an SSL Server To act as a server that listens for and accepts SSL connections from clients, create an SSL connector that inbound endpoints use: <ssl:connector Send Messages to an SSL Server To send messages on an SSL connection, create a simple TCP connector that outbound endpoints use: SSL endpoints. Messages are received on inbound endpoints. Messages are sent to outbound endpoints. Both kinds of endpoints are identified by a host name and a port. By default, SSL endpoints use the request-response exchange pattern, but they can be explicitly configured as one-way. The decision should be straightforward: Example Configurations This shows how to create an SSL server in Mule. The connector at ❶ defines that a server socket is created that accepts connections from clients. Complete mule messages are read from the connection (direct protocol) becomes the payload of a Mule message (since payload only is false). The endpoint at ❷ applies these definitions to create a server at port 4444 on the local host. The messages read from there are then sent to a remote ssl endpoint at ❸. The flow version uses the eof protocol (❹), so that every byte sent on the connection is part of the same Mule message. Note that both connectors specify separate keystores to be used by the client (outbound) and server (inbound) endpoints. Configuration Options For more details about creating protocol handlers in Java, see . Configuration Reference SSL Transport Javadoc API Reference Reference the SSL Javadoc for this module. accepts (and you can then log) bytes as they are received.
https://docs.mulesoft.com/mule-user-guide/v/3.7/ssl-and-tls-transports-reference
CC-MAIN-2017-09
refinedweb
736
50.57
On 3/25/13 9:37 PM, Dan Douglas wrote: > Hello, > > $ function f { typeset +x x; typeset x=123; echo "$x"; sh -c 'echo "$x"'; > }; x=abc f > 123 > abc > $ echo "$BASH_VERSION" > 4.2.45(1)-release > > This is inconsistent with a variable defined and exported any other way. > (ksh93/mksh/zsh don't have this issue. Dash doesn't actually export the > variable to the environment in this case, but just "localizes" it, and > requires a separate export.) The question is whether or not variables in the temporary environment passed to a shell function and that function's local variables exist in the same namespace. Bash makes a distinction, to a certain extent, between the two, but it's inconsistent, as you say. I'll take a look at this, and maybe it will be in bash-4.3. Chet -- ``The lyf so short, the craft so long to lerne.'' - Chaucer ``Ars longa, vita brevis'' - Hippocrates Chet Ramey, ITS, CWRU address@hidden
https://lists.gnu.org/archive/html/bug-bash/2013-04/msg00067.html
CC-MAIN-2019-43
refinedweb
163
72.16
Understanding Struts Action Class Understanding Struts Action Class  ...) throws java.lang.Exception Action Class process the specified... the mappings in the struts-config.xml. Our Action Class returns Struts Dispatch Action Example to select the method from the Action class for specific requests. Note... Struts Dispatch Action Example Struts Dispatch Action Struts2.2.1 Action Tag Example class directly from a JSP page. We can call action directly by specifying... the results from the Action. The following Example will shows how to implement... ActionTag .jsp as follows. If the executeResult=?true? is specified in the action tag The password forgot Action is invoked... password action requires user name and passwords same as you had entered during Redirect Action Struts 2 Redirect Action In this section, you will get familiar with struts 2 Redirect action... action to display a page. Redirect Action Result: This redirect pattern Forward Action Example an Action Class Developing the Action Mapping in the struts-config.xml... Struts Forward Action Example  ...-mapping. Note that we do not create any action class Struts Action Class Struts Action Class What happens if we do not write execute() Tag (Data Tag) Example tag that is used to call actions directly from a JSP page by specifying the action... tag is used to call actions directly from a JSP page by specifying the action... the results from the Action. Any result processor defined for this STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS... of Action classes for your project. The latest version of struts provides classes... action. In this article we will see how to achieve this. Struts provides forward select query result to jsp page using struts action class how to forward select query result to jsp page using struts action class how to forward select query result to jsp page using struts action class STRUTS 2 Could not find action or result ;package <action name="fetch" class...STRUTS 2 Could not find action or result hiii..i am new to struts 2... warning and the "menujsp.jsp" page is not opening...its showing the LookupDispatchAction Example Here, Action mapping helps to select the method from the Action class...; Struts LookupDispatch Action... enables a user to collect related functions into a single action class Struts LookupDispatchAction Example Here, Action mapping helps to select the method from the Action class for ...; Struts LookupDispatch Action... enables a user to collect related functions into a single action class Struts MappingDispatchAction Example for each method defined in the action class. Note that the value specified... to collect related functions into a single action class. It needs...; MappingDispatch_Action which is a sub class of  Struts MappingDispatchAction Example in the action class. Note that the value specified with the parameter attribute...; Struts MappingDispatch Action... functions into a single action class. It needs to create multiple Action in Struts 2 Framework , and select the view result page that should send back to the user action class.... Actions are mostly associated with a HTTP request of User. The action class... { return "success"; } } action class does not extend another class and nor getting null value in action from ajax call getting null value in action from ajax call Getting null value from ajax call in action (FirstList.java)... first list is loading correctly. Need...-default"> ... <action name="StudentRegister" No action instance for path ; </action-mappings> </struts-config>... struts@roseindia.net */ /** * Struts File Upload Action Form. * */ public class StrutsUploadAndSaveAction extends Action Calling Action on form load - Struts ... this list is coming from the action which i m calling before the page is being... to direct user directly to this page i m calling an action which is preparing a list...; This action needs no data other than the user's session, which it can get from Developing Login Action Class process. Get the login information from the user Developing Login Action Class... Developing Login Action Class  ... for login action class and database code for validating the user against database Pass value of rasio button from jsp page to action class(not conventional problem) Pass value of rasio button from jsp page to action class(not conventional problem) Hi, I have a jsp page that has code which goes ike this: <... in action class using getter setter and hence corresponding data can be deleted. i the Action Mapping specified the Action Mapping specified How is the Action Mapping specified ActionMapping and is the Action Mapping specified ActionMapping and is the Action Mapping specified What is ActionMapping and is the Action Mapping specified action tag - Struts action tag Is possible to add parameters to a struts 2 action tag? And how can I get them in an Action Class. I mean: xx.jsp Thank you Action classes in struts Action classes in struts how many type action classes are there in struts Hi Friend, There are 8 types of Action classes: 1.ForwardAction class 2.DispatchAction class 3.IncludeAction class 4.LookUpDispatchAction }//execute }//class struts-config.xml <struts...struts <p>hi here is my code in struts i want to validate my...;gt; <html:form <pre> Advance Struts Action Advance Struts2 Action In struts framework Action is responsible for controlling the request coming from the clients. It is a java class class it can... is extended by most of the Action classes is ActionSupport class. The default BeanPage Tag: item from the page context as a bean. This tag retrieve the value of the specified item from the page context for this page, and define it as a scripting... with the value of the specified page context property Page Refresh - Struts Page Refresh Hi How Can we control the page does not go to refersh after its forward again from action class.in my form i have one dropdownlist... in same page and fwd the action to same page How to display Jfreechart from servlet in jsp web page at specified location How to display Jfreechart from servlet in jsp web page at specified... to display the chart in web page. I generated the chart using Jfreechart... in jsp web page . Thank you very much Sir Introduction to Action interface Introduction To Struts Action Interface The Action interface contains the a single method execute(). The business logic of the action is executed within... from user. NONE- If the execution of action is successful but you do not want linking tree heading in javasript into a Jsp file and then jsp to struts action form can we do this ? and also is there any way to directly transfer control from javascript tree link to struts action class...linking tree heading in javasript into a Jsp file and then jsp to struts action singleton class in struts - Java Beginners singleton class in struts hi, This balakrishna, I want to retrive data from database on first hit to home page in struts frame work User Registration Action Class and DAO code User Registration Action Class and DAO code... to write code for action class and code for performing database operations (saving data into database). Developing Action Class Create Action class used in the above class to forward the action to the next page. All...Create Action Class An action is an important portion of web application... an action class you need to extend or import the Action classes or interface Action Listeners Action Listeners Please, could someone help me with how to use action listeners I am creating a gui with four buttons. I will like to know how to apply the action listener to these four buttons. Hello Friend, Try Fetch the data using jsp standard action the data from the database & show in a jsp page using jsp:usebean in MVC model... that retrieves the data from the database through java bean and display it in jsp page... java.util.*; public class EmpBean { public List dataList(){ ArrayList list=new How can i pass the valus from a JSP to the action class??? How can i pass the valus from a JSP to the action class??? hewllo wevryone... can anyone help me with how i can pass the value of menuId in my JSP and pass it in the action class Example of ActionSupport class Example of ActionSupport class Struts ActionSupport class provides the default... of ActionSupport class is given below actionsupport.jsp <%@ page...;action name="actionSupport" class=" struts *; import org.apache.struts.action.*; public class LoginAction extends Action...struts <p>hi here is my code can you please help me to solve...; <p><html> <body></p> <form action="login.do"> Testing Struts Application in the action class code.Intentionally so! The step by step progress gets... Reading: Struts in Action . by Ted Husted ( Manning press/ DreamTech...Testing Struts Application   struts <html:select> - Struts , allowing Struts to figure out the form class from the struts-config.xml file... with the action. For example, the class attribute might be specified...struts i am new to struts.when i execute the following code i Chain Action Result Example ; </action> <action name="doLogin" class="...; <action...Chain Action Example Struts2.2.1 provides the feature to chain many actions Redirect Action Result Example of the ActionMapperFactory for redirecting the URL to the specified action. To redirect the action to the specified location you need to do mapping in the struts.xml as follows <action name="redirectAction" class=" Struts Action Chaining Struts Action Chaining Struts Action Chaining sturts - Struts in action class i m calculating sum of both d no. now i have created another page... execute method of action class to .jsp page. I have tried bean:write bt value...sturts I m new 2 struts..i have made a calculate.jsp with num1 radio button value on edit action ...Problem 'm facing is on edit action 'm not retrieving radio button value..i have... is Payment type. <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <html> < Displaying different portions of a page subsequently on the basis of action Displaying different portions of a page subsequently on the basis of action Suppose in Report.jsp there are two text fields From Date: and To Date: with js calender beside these and a SEARCH Button(When the page initially loads Struts 2 Interceptors Interceptor transfer cookies from action to response... define the Static Parameters while configuring your action class...Struts 2 Interceptors Struts 2 framework relies upon Interceptors to do most retrive data from database using jsp in struts? retrive data from database using jsp in struts? *search.jsp* <...*; import org.apache.struts.action.*; public class SearchAction extends Action... org.apache.struts.validator.DynaValidatorForm; public class SearchFB extends DynaValidatorForm { } SearchDTO.java DispatchAction class? - Struts /understandingstruts_action_class.shtml class? HI, Which is best and why either action class or dispatch class. like that Actionform or Dynactionform . I know usage download file Error in struts2 action class download file Error in struts2 action class Hi, i am using bellow...._jspService(header_jsp.java from :437...(baselayout_jsp.java from :199) at org.apache.jsp.layout.baselayout_jsp java - Struts architecture. * The RequestProcessor selects and invokes an Action class... to this servlet. * There can be one instance of this servlet class, which receives... resource. * The Action classes can manipulate the state of the application's Capturing JSP Content Within My Strut Action Servlet - JSP-Servlet or Struts Action ... */ BufferedHttpResponseWrapper wrapper = new...Capturing JSP Content Within My Strut Action Servlet My end goal is to be able to grab the content from the JSP from within the calling servlet ckeditor <p> and ckeditor and how to prevent ckeditor from adding blank spaces and paregraph in text area What is Action Class? What is Action Class? What is Action Class? Explain with Example login page error login page error How to configure in to config.xml .iam takin to one login form in that form action="/login" .when iam deployee the project following error arise ."The server encountered an internal error (No action instance p access data from mysql through struts access data from mysql through struts I am Pradeep Kundu. I am making a program in struts in which i want to access data from MySQL through struts... , other page open but blanks. These are my action classes code struts validation ; <p class="sep"><label class="small"><bean:message key...; <p class="sep"><label class="small" for="select01">...:text></p> <p class="sep"><label Struts Articles . 4. The UI controller, defined by Struts' action class/form bean... is isolated from the user). Bridge the gap between Struts and Hibernate... built upon Struts and Hibernate can derive benefit from this generic extension Struts 1 Tutorial and example programs to the Struts Action Class This lesson is an introduction to Action Class... struts ActionFrom class and jsp page. Using... Struts Dispatch Action that will help you grasping the concept How To Develop Login Form In Struts ,the following classes will be used-- Action class ActionForm class Action Class: The action class is the link between the Struts framework and your business application logic. The purpose of Action How To Make Executable Jar File For Java P{roject - Java Beginners How To Make Executable Jar File For Java P{roject Hello Sir I want...*; public class CreateJar { public static int buffer = 10240; protected...(file, files); } } Thanks visit this page Validations using Struts 2 Annotations page or in action class, but Struts 2 provides another very easy method... the action class to handle the login request. The Struts 2 framework provides... validation is done in action class and if user enters Admin/Admin in the user
http://www.roseindia.net/tutorialhelp/comment/1029
CC-MAIN-2014-52
refinedweb
2,253
57.87
Is it possible to send two different variables to one definition and then use them separately in that definition? Here’s what I’m trying to do. ============== #item = url #species = pet def exists(item) existingitems = YAML.load(File.open("./#{species}.yaml")) existingitems.each { |exist| if exist == item return false end } return true end pets.each do |pet| files.each do |url| if exists(url) here I want to send both the pet and url variable up to definition puts "Exists" else puts "Nope" end end end ============= I have it all working with just the url, but I need it to know what pet it’s on so it knows what file to open and search in. Anyone have any suggestions? P.S. This code isn’t an exact copy, I took out a lot of fluff and stuff to shorten it for the example; it probably won’t work if you try and test the code. I’m just looking to see if there is a way to send both variables up to the definition and then be able to use them?
https://www.ruby-forum.com/t/two-variables-to-one-definition/151841
CC-MAIN-2018-51
refinedweb
182
78.28
A pure-Python libconfig reader/writer with permissive license Project description libconf is a pure-Python reader/writer for configuration files in libconfig format, which is often used in C/C++ projects. It’s interface is similar to the json module: the four main methods are load(), loads(), dump(), and dumps(). Example usage: import io, libconf >>> with io.open('example.cfg') as f: ... config = libconf.load(f) >>> config {'capabilities': {'can-do-arrays': [3, 'yes', True], 'can-do-lists': (True, 14880, ('sublist',), {'subgroup': 'ok'})}, 'version': 7, 'window': {'position': {'h': 600, 'w': 800, 'x': 375, 'y': 210}, 'title': 'libconfig example'}} >>> config['window']['title'] 'libconfig example' >>> config.window.title 'libconfig example' >>> print(libconf.dumps({'size': [10, 15], 'flag': True})) flag = True; size = [ 10, 15 ]; The data can be accessed either via indexing (['title']) or via attribute access .title. Character encoding and escape sequences The recommended way to use libconf is with Unicode objects (unicode on Python2, str on Python3). Input strings or streams for load() and loads() should be Unicode, as should be all strings contained in data structures passed to dump() and dumps(). In load() and loads(), escape sequences (such as \n, \r, \t, or \xNN) are decoded. Hex escapes (\xNN) are mapped to Unicode characters U+0000 through U+00FF. All other characters are passed though as-is. In dump() and dumps(), unprintable characters below U+0080 are escaped as \n, \r, \t, \f, or \xNN sequences. Characters U+0080 and above are passed through as-is. Writing libconfig files Reading libconfig files is easy. Writing is made harder by two factors: libconfig’s distinction between int and int64: 2 vs. 2L libconfig’s distinction between lists and arrays, and the limitations on arrays The first point concerns writing Python int values. Libconf dumps values that fit within the C/C++ 32bit int range without an “L” suffix. For larger values, an “L” suffix is automatically added. To force the addition of an “L” suffix even for numbers within the 32 bit integer range, wrap the integer in a LibconfInt64 class. Examples: dumps({'value': 2}) # Returns "value = 2;" dumps({'value': 2**32}) # Returns "value = 4294967296L;" dumps({'value': LibconfInt64(2)}) # Explicit int64, returns "value = 2L;" The second complication arises from distinction between lists and arrays in the libconfig language. Lists are enclosed by () parenthesis, and can contain arbitrary values within them. Arrays are enclosed by [] brackets, and have significant limitations: all values must be scalar (int, float, bool, string) and must be of the same type. Libconf uses the following convention: it maps libconfig ()-lists to Python tuples, which also use the () syntax. it maps libconfig []-arrays to Python lists, which also use the [] syntax. This provides nice symmetry between the two languages, but has the drawback that dumping Python lists inherits the limitations of libconfig’s arrays. To explicitly control whether lists or arrays are dumped, wrap the Python list/tuple in a LibconfList or LibconfArray. Examples: # Libconfig lists (=Python tuples) can contain arbitrary complex types: dumps({'libconf_list': (1, True, {})}) # Libconfig arrays (=Python lists) must contain scalars of the same type: dumps({'libconf_array': [1, 2, 3]}) # Equivalent, but more explit by using LibconfList/LibconfArray: dumps({'libconf_list': LibconfList([1, True, {}])}) dumps({'libconf_array': LibconfArray([1, 2, 3])}) Comparison to other Python libconfig libraries Pylibconfig2 is another pure-Python libconfig reader. It’s API is based on the C++ interface, instead of the Python json module. It’s licensed under GPLv3, which makes it unsuitable for use in a large number of projects. Python-libconfig is a library that provides Python bindings for the libconfig++ C++ library. While permissively licensed (BSD), it requires a compilation step upon installation, which can be a drawback. I wrote libconf (this library) because both of the existing libraries didn’t fit my requirements. I had a work-related project which is not open source (ruling out pylibconfig2) and I didn’t want the deployment headache of python-libconfig. Further, I enjoy writing parsers and this seemed like a nice opportunity :-) Release notes 2.0.1, released on 2019-11-21 Allow trailing commas in lists and arrays for improved compatibility with the libconfig C implementation. Thanks to nibua-r for reporting this issue. 2.0.0, released on 2018-11-23 Output validation for dump() and dumps(): raise an exception when dumping data that can not be read by the C libconfig implementation. This change may raise exceptions on code that worked with <2.0.0! Add LibconfList, LibconfArray, LibconfInt64 classes for more fine-grained control of the dump()/dumps() output. Fix deepcopy() of AttrDict classes (thanks AnandTella). 1.0.1, released on 2017-01-06 Drastically improve performance when reading larger files Several smaller improvements and fixes 1.0.0, released on 2016-10-26: Add the ability to write libconf files (dump() and dumps(), thanks clarkli86 and eatsan) Several smaller improvements and fixes 0.9.2, released on 2016-09-09: Fix compatibility with Python versions older than 2.7.6 (thanks AnandTella) Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/libconf/2.0.1/
CC-MAIN-2022-40
refinedweb
850
54.52
Timeline Jan 27, 2010: - 10:12 PM Ticket #3364 (OGRSpatialReference::IsSameGeogCS() is returning true when units don't ...) created by - For OGRSpatialReference, SetAngularUnits?() will write the unit details … - 8:24 PM Changeset [18679] by - pull in upstream fixes for SHPRewind() (#3363) - 8:22 PM Changeset [18678] by - pull in upstream fixes for SHPRewind() (#3363) - 8:21 PM Changeset [18677] by - enable test 34, multipolygon formation (#3363) - 3:27 PM Ticket #3363 ([PATCH - Shapelib] Shapefile driver can write wrong winding order for ...) created by - Frank, this is an issue strictly identical to #3356, but in shpopen.c. … - 3:20 PM Ticket #3356 (OGR unreliability when detecting inner rings from outer rings for ...) closed by - fixed: Ok, this turned out to be a very interesting problem. The way to … - 3:18 PM Changeset [18676] by - OGRLinearRing: use another variant of Green Theorem less sensitive to … - 3:17 PM Changeset [18675] by - Test sensitivity of OGRLinearRing::isClockwise() and … - 3:16 PM Changeset [18674] by - OGRLinearRing: use another variant of Green Theorem less sensitive to … - 2:15 PM Changeset [18673] by - sandbox: prepare modules for GDAL source import from trunk - 11:26 AM Changeset [18672] by - updated version to 1.8.0 - 5:37 AM Ticket #3362 (gcs.override.csv has wrong datum shift for Belge 1972) created by - The file … - 5:24 AM Changeset [18671] by - frmts/jpeg: missing cleanup for .lib binaries - 2:43 AM Changeset [18670] by - Updated doc in GDALDataset comments - 2:41 AM Ticket #3359 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) closed by - duplicate - 2:41 AM Ticket #3360 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) closed by - duplicate - 2:41 AM Ticket #3361 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) closed by - duplicate - 2:40 AM Ticket #3358 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) closed by - duplicate - 2:38 AM Ticket #3361 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) created by - Hello, I'm sorry for my English.... Problem occurs while converting … - 1:38 AM Ticket #3360 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) created by - Hello, I'm sorry for my English.... Problem occurs while converting … - 1:34 AM Ticket #3359 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) created by - Hello, I'm sorry for my English.... Problem occurs while converting … - 1:32 AM Ticket #3358 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) created by - Hello, I'm sorry for my English.... Problem occurs while converting … - 1:26 AM Ticket #3357 (incorrect data for EPSG:3120 in FWTools2.4.2 and 2.4.6) created by - Hello, I'm sorry for my english.... Problem occurs while converting … Jan 26, 2010: - 10:49 PM Ticket #3356 (OGR unreliability when detecting inner rings from outer rings for ...) created by - Recent releases of GDAL/OGR recognize some multipolygons as polygons. … - 6:08 PM Ticket #3354 (gdal_merge.py partly broken in GDAL 1.7.0) closed by - fixed: Fixed in r18668 in trunk and in r18669 in 1.7 branch. - 6:07 PM Changeset [18669] by - Fixed the global variable issue caused by r18412 (#3354). Also adds … - 5:43 PM Changeset [18668] by - Fixed the global variable issue caused by r18412 (#3354). Also adds … - 2:50 PM Ticket #3355 (Fixes to variations on PDS Image pointer and implementation of ...) created by - This patch fixes a couple of bugs in the current PDS implementation, … - 2:15 PM Ticket #3177 (variation on label to image pointer (PDS)) reopened by - The implementation to fix this is actually flawed based on both … - 12:19 PM Ticket #3345 (GDAL JPEG compressed NITF image is not compatible with other NITF viewer) closed by - fixed: Ok, I've backported the whole set of changes in 1.7 branch (r18667). - 12:15 PM Changeset [18667] by - NITF: Improve compliance towards NITF specs (MIL-STD-2500C and … - 11:39 AM Ticket #3354 (gdal_merge.py partly broken in GDAL 1.7.0) created by - Chaitanyah, Yes, as you reported on IRC, I confirm gdal_merge.py in … Jan 25, 2010: - 11:50 PM Changeset [18666] by - convert to unix text format - 7:20 PM Changeset [18665] by - update with 1.7 pointer, and remove FOSS4G 2009 stuff - 7:17 PM NewsAndStatus edited by - add 1.7 (diff) - 7:15 PM Release/1.7.0-News created by - - 7:04 PM WikiStart edited by - point to 1.7 (diff) - 3:42 PM Changeset [18664] by - JPEG in NITF: set the restart interval as required by MIL-STD-188-198 … - 12:30 PM Ticket #3351 (ogrinfo and python bindings segfault on certain shapefile) closed by - duplicate: The .DBF is corrupted. I've backported in r18663 the fix done for #3093. - 12:28 PM Changeset [18663] by - Avoid crashing on corrupted .DBF files (#3351, #3093) - 11:35 AM Changeset [18662] by - JPEG in NITF : Correctly format the version number of the APP6 segment … - 10:57 AM Ticket #3353 (can't have odbc without pgeo) closed by - duplicate: duplicate of #3352 - 10:20 AM Ticket #3353 (can't have odbc without pgeo) created by - It would be useful to have a pgeo switch for ./configure. Currently … - 10:19 AM Ticket #3352 (can't have odbc without pgeo) created by - It would be useful to have a pgeo switch for ./configure. Currently … - 12:59 AM Changeset [18661] by - mass backport of jp2kak driver from trunk for non-persistent upgrade … - 12:26 AM Ticket #3350 (ogrinfo and python bindings segfault on certain shapefile) closed by - duplicate - 12:24 AM Ticket #3351 (ogrinfo and python bindings segfault on certain shapefile) created by - I have a shapefile which makes ogrinfo segfault, python segfaults with … - 12:21 AM Ticket #3350 (ogrinfo and python bindings segfault on certain shapefile) created by - I have a shapefile which makes ogrinfo segfault, python segfaults with … - 12:20 AM Changeset [18660] by - introduce ycc optimization, and fix a problem with overviews in … Jan 24, 2010: - 7:39 PM Changeset [18659] by - updated for new ReadBlock? implementation, slight image result diffs (#3295) - 7:33 PM Changeset [18658] by - major restructuring, all reading now goes through DirectRasterIO (#3295) - 4:21 PM Changeset [18657] by - allow quality as low as 0.01 pre request from Greg - 2:15 PM Changeset [18656] by - Use CXX to compile .cpp - 11:42 AM Ticket #3349 (PG driver does not retrieve column width and precision from a SQL query) closed by - fixed: Fixed in trunk (r18653) and in branches/1.7 (r18655). Tested in r18654. - 11:42 AM Changeset [18655] by - Get width and precision from OGR PG SQL queries (#3349) - 11:41 AM Changeset [18654] by - Test retrieval of width and precision from OGR PG SQL queries (#3349) - 11:40 AM Changeset [18653] by - Get width and precision from OGR PG SQL queries (#3349) - 11:39 AM Ticket #3349 (PG driver does not retrieve column width and precision from a SQL query) created by - Contrary to PG tables, the PG driver does not retrieve column width … - 6:44 AM Changeset [18652] by - Fix ./configure --with-threads fails on FreeBSD 8.0 (#3348) - 6:43 AM Changeset [18651] by - Fix ./configure --with-threads fails on FreeBSD 8.0 (#3348) - 6:42 AM Ticket #3348 (Compilation after ./configure --with-threads fails on FreeBSD 8.0) created by - Neither PTHREAD_MUTEX_RECURSIVE, MUTEX_TYPE_COUNTING_FAST nor … - 5:57 AM Changeset [18650] by - Update makefile.vc for autotest/cpp - 5:38 AM Changeset [18649] by - Use clock() for better portability - 4:57 AM Changeset [18648] by - fix win32 compilation of 8211view.exe and 8211dump.exe - 3:57 AM Ticket #3337 (CADRG data in the polar regions does not display properly.) closed by - fixed: Added a autotest of the polarsteregraphic case with and without PROJ … - 3:54 AM Changeset [18647] by - improve error cleanup/supression/reporting for polar stereographic … - 3:52 AM Changeset [18646] by - Add test of issue #3337 - 3:20 AM Changeset [18645] by - cleanup hfatest.obj so it does not get copied to ../o - 2:51 AM Changeset [18644] by - xcopy doesn't support multi argument sources. - 2:26 AM Changeset [18643] by - ensure gcp to transform is exact (#3337) - 2:26 AM Changeset [18642] by - ensure gcp to transform is exact (#3337) - 2:21 AM Changeset [18641] by - NITF: avoid (false positive) warning emitted by GCC 4.2 - 2:18 AM Changeset [18640] by - NITF: fix leak of pszGCPProjection - 2:08 AM Changeset [18639] by - added logic to return GCPPROJECTIONX metadata when transformer cannot … - 2:04 AM Changeset [18638] by - added logic to return GCPPROJECTIONX metadata when transformer cannot … - 1:54 AM Changeset [18637] by - added logic to return GCPPROJECTIONX metadata when transformer cannot … - 1:53 AM Ticket #3347 (NITF corners can be wrong) closed by - fixed: In r18635 I have modified the code, essentially backing out r7382, and … - 1:38 AM Changeset [18636] by - set svnignore for nitfdump side files - 1:36 AM Changeset [18635] by - ensure that igeolo corners are not messed up if irregular, keep … - 1:35 AM Ticket #3347 (NITF corners can be wrong) created by - While investigating #3337 I have discovered that the conversion of … - 1:32 AM Changeset [18634] by - ensure we embed the manifest in nitfdump.exe Jan 23, 2010: - 8:54 PM Changeset [18633] by - ensure test mainline object not left around to mix into ../o - 8:47 PM Changeset [18632] by - ensure nodata carried into overviews (#2855) - 8:45 PM Changeset [18631] by - ensure nodata carried into overviews (#2855) - 8:43 PM Changeset [18630] by - ensure nodata carried into overviews (#2855) - 8:37 PM Changeset [18629] by - ensure we do not copy test mainline into ../o - 7:32 PM Ticket #2855 (RRD overviews do not preserve the NoData pixels in the base raster dataset) closed by - fixed: I have extended the trunk autotest suite with verification of this new … - 7:30 PM Changeset [18628] by - added testing of overview nodata values (#2855) - 7:12 PM Changeset [18627] by - propogate nodata during createcopy, and overview building (#2855) - 7:09 PM Changeset [18626] by - propogate nodata during createcopy, and overview building (#2855) - 7:05 PM Changeset [18625] by - propogate nodata during createcopy, and overview building (#2855) - 6:54 PM Changeset [18624] by - fix to build on windows - 5:27 PM Ticket #3338 (Missing georeferencing) closed by - fixed: It seems the pixelSize variable in this file uses subfields x and y … - 5:21 PM Changeset [18623] by - fix support for mapinfo with nonstandard pixelSize (#3338) - 5:18 PM Changeset [18622] by - fix support for mapinfo with nonstandard pixelSize (#3338) - 5:18 PM Changeset [18621] by - fix support for mapinfo with nonstandard pixelSize (#3338) - 2:54 PM Changeset [18620] by - Move EPSILON driver detection - 2:53 PM Changeset [18619] by - Add test for EPSILON tiles - 2:34 PM Changeset [18618] by - Fix autotest/cpp Jan 22, 2010: - 8:17 PM Ticket #3338 (Missing georeferencing) reopened by - The cellsize is still missling. It should be 0.6 x 0.6. - 3:43 PM Changeset [18617] by - NITF: Emits an APP6 application data marker in the JPEG stream as … - 1:13 PM Ticket #3346 (Debug build of static library crashes on Windows) created by - It is a … - 7:29 AM Ticket #3345 (GDAL JPEG compressed NITF image is not compatible with other NITF viewer) created by - When I used GDAL to save a compressed NITF image, I was not able to … - 6:56 AM Ticket #3343 (ECW libs configured wrong) closed by - fixed: I have corrected this in trunk (r18614,r18616), and 1.7 branch … - 6:54 AM Changeset [18616] by - fix typo in last commit (#3343) - 6:53 AM Changeset [18615] by - fix one case in ecw configuration (#3343) - 6:41 AM Changeset [18614] by - fix one case in ecw configuration (#3343) - 5:00 AM Ticket #3344 (Compiling ECW support on Linux fails) created by - The ECW SDK ecw_jpeg_2000_sdk_3_3_source.zip / libecwj2-3.3 seems to … - 4:55 AM Ticket #3343 (ECW libs configured wrong) created by - In the file configure.in on line 1402: […] the NCSEcw is duplicated … Jan 21, 2010: - 12:05 PM Ticket #3342 (Compilation problem on Ubuntu 9.10 when ./configure --with-spatialite=/usr) closed by - fixed: Fixed in trunk (r18612) and in branches/1.7 (r18613) - 12:05 PM Changeset [18613] by - Don't add include/spatialite to the include path to avoid compilation … - 12:05 PM Changeset [18612] by - Don't add include/spatialite to the include path to avoid compilation … - 12:03 PM Ticket #3342 (Compilation problem on Ubuntu 9.10 when ./configure --with-spatialite=/usr) created by - Currently, when linking against libspatialite, we add … Jan 20, 2010: - 1:15 PM Ticket #3210 (Default nmake.opt fails to build with Visual C++) closed by - fixed - 1:09 PM Changeset [18611] by - Ticket #3210: Fixed problems with creating bach of libjpeg12 files … - 12:42 PM Ticket #3210 (Default nmake.opt fails to build with Visual C++) reopened by - - 9:54 AM Changeset [18610] by - Fix possible random crash in RasterliteDataset::IBuildOverviews (#3339) - 9:53 AM Changeset [18609] by - Fix possible random crash in RasterliteDataset::IBuildOverviews (#3339) Jan 19, 2010: - 9:21 PM Ticket #3338 (Missing georeferencing) closed by - fixed: I have added this logic in trunk (r18605), 1.6-esri (r18606) and 1.7 … - 9:20 PM Changeset [18608] by - Support Eprj_MapInfo nodes not called Map_Info (#3338) - 9:20 PM Changeset [18607] by - Support Eprj_MapInfo nodes not called Map_Info (#3338) - 9:18 PM Changeset [18606] by - Support Eprj_MapInfo nodes not called Map_Info (#3338) - 9:08 PM Changeset [18605] by - upgrade to 1.8dev versioning - 8:43 PM Ticket #3341 (osr_xml test flawed) created by - In a build of GDAL with the JP2KAK driver, a full run of the autotest … - 8:26 PM Ticket #3340 (ogr_mitab autotest failure) created by - I am seeing a failure in the autotest suite when run as a whole … - 5:16 PM Milestone 1.7.0 completed - Release 1.7 Plan Page - 3:12 PM Ticket #3339 (RasterliteCreateCopy() might crash randomly on 32bit platform) closed by - fixed: Fixed in trunk (r18603) and in branches/1.7 (r18604) - 3:10 PM Changeset [18604] by - Fix random crash in RasterliteCreateCopy?() on 32bit platform (#3339) - 3:10 PM Changeset [18603] by - Fix random crash in RasterliteCreateCopy?() on 32bit platform (#3339) - 3:09 PM Ticket #3339 (RasterliteCreateCopy() might crash randomly on 32bit platform) created by - An invalid use of sprintf(szTmp, "%llu", (GUIntBig)ptr) to print the … - 1:25 PM Changeset [18602] by - NetCDF: prevent CreateCopy? on source dataset that has bands of complex … - 1:25 PM Changeset [18601] by - Avoid buffer overflow when 'GeodeticLatitude?' which is 16 char wide + … - 1:13 PM Changeset [18600] by - NetCDF: prevent CreateCopy? on source dataset that has bands of complex … - 1:10 PM Changeset [18599] by - Avoid buffer overflow when 'GeodeticLatitude?' which is 16 char wide + … - 12:33 PM Changeset [18598] by - prepare release - 12:32 PM Changeset [18597] by - Reissue for pcidsk sdk issue - 12:31 PM Changeset [18596] by - fix up pcidsk sdk step 2 of 2 - 11:52 AM Changeset [18595] by - fix up pcidsk sdk - step 1 of 2 - 11:36 AM Ticket #3338 (Missing georeferencing) created by - The extent values should be in world space (top: 2898846.6, left: … - 11:18 AM Changeset [18594] by - Prepare for 1.7.0 release. - 11:16 AM Changeset [18593] by - replace svn:externals with copy of pcidsk sdk - 11:07 AM Changeset [18592] by - Prepare for 1.7.0. - 11:05 AM Changeset [18591] by - update to 1.7.0 release info - 11:01 AM Changeset [18590] by - refreshed from libgeotiff - 10:54 AM Changeset [18589] by - correct author/credit/blame information - 10:49 AM Changeset [18588] by - add flushing support based on new synchronize method - 8:38 AM Ticket #3337 (CADRG data in the polar regions does not display properly.) created by - Their projection isinterpreted as GCS WGS84. It should be North Pole … - 8:38 AM Changeset [18587] by - reenable complex support - ok in arcgis10 (#3174) - 7:30 AM Ticket #3336 (ODBC Code type mismatch on 64-bit builds) closed by - fixed: I have applied a slight variation on the patch that did not attempt to … - 7:28 AM Changeset [18586] by - correct allocation types for several values to avoid problems on win64 … - 7:22 AM Changeset [18585] by - correct allocation types for several values to avoid problems on win64 … - 3:34 AM Ticket #3336 (ODBC Code type mismatch on 64-bit builds) created by - CPLODBCStatement::CollectResultsInfo?() allocates space for column … Jan 18, 2010: - 8:24 PM Changeset [18584] by - add support for ellipsoid height datums, datum.csv, vd codes - 6:44 PM Changeset [18583] by - improved error handling, and progress reporting (Trent) - 1:46 PM Ticket #3335 (CopyLayer() method should use transactions similar to ogr2ogr) created by - Copying from any data source to SQLite (at least in Python) is … - 12:42 PM PscMotions edited by - (diff) - 12:41 PM PscMotions edited by - (diff) - 12:33 PM Changeset [18582] by - Update with changes from r18510 to r18581 - 12:11 PM Changeset [18581] by - switch to operate on one line at a time, fix two bugs - 11:31 AM Changeset [18580] by - Include appropriate directory for netcdf-3 packaging in RHEL5 - 11:22 AM Changeset [18579] by - Skip if no HTTP driver available - 6:55 AM Ticket #3334 (DXF creation failed.) closed by - invalid: Hmm, I'm not thrilled with how the error is reported so I've made some … - 6:48 AM Changeset [18578] by - Improve error reporting when template files not found (#3334). - 3:20 AM Ticket #3334 (DXF creation failed.) created by - Trying to convert a shapefile to a DXF using the following command on … Jan 17, 2010: - 4:16 PM Ticket #3333 (Add several projections) created by - Added several supported projections: - Aitoff - Winkel_I - Winkel_II - … - 2:32 PM Changeset [18577] by - Avoid crash on jpeg2000_8 with Ubuntu 8.04 LTS version of libjasper - 2:32 PM Changeset [18576] by - Process --config GDAL_SKIP before calling GDALAllRegister - 1:52 PM Changeset [18575] by - OGR GeoJSON: added extra test if datasource consists of real GeoJSON data - 12:28 PM Changeset [18574] by - OGR GeoJSON: added simple test case for writing GeoJSON dataset using … - 12:26 PM Changeset [18573] by - OGR GeoJSON: Ported file operations from VSI layer with VSIF in order … - 8:52 AM Ticket #3322 (Erronous size output for Gtiff using gdalwarp) closed by - fixed: I did try with gdalautotest-1.7b2, the output with COMPRESS=YES is … - 6:21 AM Changeset [18572] by - Correct prototype of OGR_ST_SetParamDbl() in .cpp to match with the … - 5:56 AM Changeset [18571] by - Add missing doxygen for OSRImportFromEPSG and OSRImportFromEPSGA - 5:13 AM Changeset [18570] by - Fix segfault when reading CEOS dataset with nBitsPerPixel != 8; add … - 2:59 AM Changeset [18569] by - Fix segfault on invalid HDF5 dataset and other memory error - Thanks … Jan 16, 2010: - 11:48 PM Ticket #3332 ([PATCH] Add ArcObjects OGR driver to allow reading of GeoDatabase (e.g ...) created by - This driver allows reading of FileGDB FeatureClasses? as long as there … - 8:07 PM Ticket #3327 (Add support to the VRT driver to specify a background color instead of ...) closed by - fixed - 6:49 PM Changeset [18568] by - One more fix in VSIMem debugging infrastructure - 4:37 PM rfc27_supportdata edited by - (diff) - 3:19 PM rfc27_supportdata edited by - (diff) - 3:17 PM rfc27_supportdata created by - - 3:09 PM RfcList edited by - (diff) - 3:09 PM RfcList edited by - added rfc 27. (diff) - 1:42 PM Ticket #3331 (Add support for compressed, and embedded GDAL support data files.) created by - As we distribution more coordinate system dictionaries with GDAL (such … - 1:02 PM Ticket #3330 (Add support for OGC Tiled WMS Specification to WMS Driver) created by - Trent Hare has requested that the WMS driver be extended to support … - 10:02 AM Changeset [18567] by - Fix bug in VSIMem debugging infrastructure... Thanks to … - 8:38 AM Ticket #3329 ([VFK - Patch] Patch to be more robust against corrupted data) closed by - fixed: The patch seems to be OK. Thanks, committed in r18566. - 8:36 AM Changeset [18566] by - [OGR - VFK] Patch to be more robust against corrupted data (thanks to … - 7:57 AM Ticket #3329 ([VFK - Patch] Patch to be more robust against corrupted data) created by - Martin, I've attached to this ticket a patch that add more checks … - 5:47 AM Changeset [18565] by - fix a few memory leaks, essentially in error path - 3:47 AM Changeset [18564] by - gdalwarp: print a warning message when trying to specify multiple … - 1:00 AM Changeset [18563] by - Updated VRT tutorial for #3327 Jan 15, 2010: - 9:57 PM Ticket #3328 (gdalwarp doesn't support producing VRTs containing multiple source files) created by - This is mostly copied from the email list … - 8:56 PM Changeset [18562] by - add backward compatability for original spec codes (libgeotiff #24) - 9:23 AM Changeset [18561] by - Added in gdalbuildvrt feature similar to -init in gdal_merge.py (#3327) - 9:21 AM Ticket #3327 (Add support to the VRT driver to specify a background color instead of ...) created by - As requested by Greg Coats in … - 7:38 AM Changeset [18560] by - OziExplorer? OZF (ozf2, ozfx3) - documentation and samples - 4:06 AM Ticket #3326 (Georaster - files exported to HFA don't open in ArcMap) closed by - fixed - 4:04 AM Changeset [18559] by - Fix #3326 (files exported to HFA error) - 4:02 AM Ticket #3326 (Georaster - files exported to HFA don't open in ArcMap) created by - After running gdal_translate from GeoRaster to HFA the output WKT … Jan 14, 2010: - 7:14 PM Ticket #3174 (Gdal envi driver can no longer read complex dataset) closed by - fixed: I have re-enabled complex support in trunk (r18557) and 1.6 branch … - 7:12 PM Changeset [18558] by - re-enabled complex support (#3174) - 7:11 PM Changeset [18557] by - re-enabled complex support (#3174) - 5:38 PM Changeset [18556] by - Remove svn:executable where inappropriate. - 5:28 PM Changeset [18555] by - Add missing include in pcidsk_read so things build properly with gcc-4.4. - 4:12 PM Changeset [18554] by - Switch from C standard library includes to C++ standard library … - 3:57 PM Changeset [18553] by - sandbox/mloskot: added README as dummy commit - 3:50 PM Changeset [18552] by - Creating private sandbox for myself - 3:40 PM Changeset [18551] by - Compatibility fixes for GCC 3.2.3 (CentOS 3.9) to use isalpha, … - 2:20 PM Changeset [18550] by - Extend inclusive filter so that it contains exclusive filter, … - 2:04 PM Changeset [18549] by - Add test for apt.dat V8.10 - 2:01 PM Changeset [18548] by - XPlane : recognize code 16 and 17 for seplane bases and heliports; add … - 1:38 PM Ticket #3325 (PCIDSK: Creating a tiled image and reopening the tiled image with ...) closed by - fixed: I have introduced a Synchronize() method on the PCIDSK::PCIDSKFile … - 1:31 PM SupportedCompilers edited by - we haven't defined what officially supported compiler means, removing … (diff) - 1:27 PM Changeset [18547] by - added Synchronize() method on file, channel, segment and a test (#3325) - 1:25 PM Changeset [18546] by - GeoJSON: re-route sprintbug() to CPLVASPrintf to re-enable MinGW … - 1:22 PM Changeset [18545] by - GeoJSON : re-apply (bug fix … - 6:55 AM Ticket #3325 (PCIDSK: Creating a tiled image and reopening the tiled image with ...) created by - Whenever creating a tiled PCIDSK image, filling it with some data, … Jan 13, 2010: - 11:01 PM Ticket #3090 (GDAL WCS driver can't open this service) closed by - wontfix: I discovered that OGC:CRS84 was not being interpreted, and I have … - 10:47 PM Changeset [18544] by - added support for OGC:CRS84 and similar srses from wms/wcs spec in … - 8:56 PM Ticket #2903 (Creating a large GIF file will fail and give a generic error message.) closed by - worksforme: Gao, I just tested this on my system and I was able to write a 50000 … - 8:36 PM Ticket #3180 (NITF GEOLOB TRE ignored for precision georeferencing) closed by - fixed - 8:24 PM Ticket #3320 (dxf-reader: rotation angle of MText elements should be exposed in OGR ...) closed by - fixed - 8:07 PM Changeset [18543] by - fix up for altered color table - 12:06 PM Ticket #3320 (dxf-reader: rotation angle of MText elements should be exposed in OGR ...) reopened by - Frank, 2 tests in ogr_dxf.py report now failures and likely need being … - 10:05 AM Changeset [18542] by - minor touch up in copyright message. Jan 12, 2010: - 8:12 PM Changeset [18541] by - Translate direction vector text angle for MTEXT from radians to degrees. - 4:09 PM Changeset [18540] by - Extend test on newer MSC_VER, as VC 7.1 doesn't like it either… - 3:19 PM FAQRaster edited by - palette example and cite source (diff) - 3:01 PM FAQRaster edited by - creating/editing color palettes (diff) - 1:41 PM Ticket #3324 (Add Lambert Conformal Conic single standard parallel support to netCDF ...) created by - NetCDF driver does not support a single standard parallel for lambert … - 11:04 AM Changeset [18539] by - Some compatibility stuff for old-and-broken compiler… - 9:52 AM Changeset [18538] by - A tiny comment related to changes in rawdataset.h 9r18524) - 7:06 AM Ticket #3323 (GRASS driver crash for location without projection) closed by - fixed: It would be definitely good to fix also in GRASS lib but simpler no … - 7:05 AM Changeset [18537] by - fix for #3323, crash if no projection is defined - 6:53 AM Changeset [18536] by - Added missing inclusion guard in rawdataset.h Jan 11, 2010: - 5:40 PM Changeset [18535] by - Treat color 7 as black so as to avoid common problems plotting as white. - 5:07 PM Changeset [18534] by - OGR GeoJSON: Fixed JSON-C issue with undefined strncasecmp when … - 4:55 PM Changeset [18533] by - OGR GeoJSON: missing include file; open std namespace … - 4:49 PM Changeset [18532] by - OGR GeoJSON: updated JSON-C library from version 0.7 to 0.9 - part 2. - 4:47 PM Changeset [18531] by - OGR GeoJSON: updated JSON-C library from version 0.7 to 0.9. JSON-C … - 4:43 PM Changeset [18530] by - Added solution and project files for Visual Studio 2010 (Visual C++ 10.0) - 4:25 PM Ticket #3320 (dxf-reader: rotation angle of MText elements should be exposed in OGR ...) closed by - fixed: I believe this is fixed in trunk now (r18529 and 18528). - 4:10 PM Changeset [18529] by - Fixed use of svn:keyword Id in VFK driver. - 4:05 PM Changeset [18528] by - Fix arguments to atan2() (#3320). - 3:58 PM Changeset [18527] by - Process text direction for MTEXT (#3320). - 3:57 PM Changeset [18526] by - Updated svn:ignore patterns in VFK drivers - 3:54 PM Changeset [18525] by - Refined RawDataset? comment related to change introduced in r18524 - 3:43 PM Changeset [18524] by - Declare destructor of RawDataset? class as pure virtual function to … - 12:40 PM Ticket #3323 (GRASS driver crash for location without projection) created by - QGIS bug It is just stupid bug … - 10:12 AM Changeset [18523] by - Added missing svn:keywords property to some files gdal/alg - 10:07 AM Changeset [18522] by - Fixed EOL - 5:01 AM Ticket #3322 (Erronous size output for Gtiff using gdalwarp) created by - Hi, I'm encountering a tiff's output size issue with gdalwarp when … - 2:42 AM Ticket #3321 (dxf-reader: detection of dashed lines) created by - In the example "fuaggeobau.dxf" (available to Frank), the detection of … - 2:18 AM Ticket #3320 (dxf-reader: rotation angle of MText elements should be exposed in OGR ...) created by - For an AcDbMText-Element the text rotation angle should be exposed in … Jan 10, 2010: - 8:03 PM Changeset [18521] by - Update for beta2. - 8:00 PM Ticket #3301 (patch to fix OGR support with cygwin) closed by - fixed: I'm not completely convinced that proj.4 is always (or even by default … - 7:59 PM Changeset [18520] by - assume proj dll is named cygproj-0.dll on cygwin builds (#3301) - 7:44 PM Ticket #3319 (self intersection issue with polygonize routine.) created by - The attached zip file contains a small ascii grid file which produces … - 7:34 PM Ticket #3318 (Ingres : missing parenthesis in logical test ?) closed by - fixed: I agree, fixed in trunk (r18519). The fix could be backported, but I … - 7:33 PM Changeset [18519] by - Correct precidence issue when writing ILSEG/LSEG geometries (#3318). - 7:25 PM Changeset [18518] by - update to utilize the new OGC based ingres capabilities (#3159) - 3:42 PM Epsilon edited by - (diff) - 3:42 PM BuildHints edited by - (diff) - 3:40 PM Epsilon created by - - 3:11 PM Changeset [18517] by - Add support to link against epsilon in configure - 3:10 PM Changeset [18516] by - Fix inverted variables in ax_lib_sqlite3.m4 - 2:31 PM FAQRaster edited by - (diff) - 2:31 PM FAQRaster edited by - Updated how to make GeoTIFF from non-geospatial raster (diff) - 1:43 PM Ticket #2673 (Make '--with-hide-internal-symbols=yes' default option) closed by - wontfix: I close because --with-hide-internal-symbols doesn't really help when … - 12:17 PM Ticket #3317 (Patch enabling copy operations for VFKProperty class) closed by - fixed - 12:00 PM Ticket #3105 (gdal does not build with libdap 3.9.x) closed by - fixed: r18515 /trunk/gdal/ (7 files in 3 dirs): Fix trunk compilation against … - 11:59 AM Changeset [18515] by - Fix trunk compilation against libdap 3.9.X (#3105) - 11:56 AM Changeset [18514] by - Avoid test to hang forever - 8:31 AM GdalOgrInJava edited by - (diff) - 7:48 AM Changeset [18513] by - A few compatibility fixes - 7:32 AM Changeset [18512] by - Update NEWS - 7:16 AM SoftwareUsingGdal edited by - Updated Cadcorp SIS info (diff) - 7:12 AM Changeset [18511] by - Test gdaldem color-relief -of VRT - 7:12 AM Changeset [18510] by - gdaldem : support VRT as output format of color-relief mode by using … - 6:18 AM Changeset [18509] by - [OGR-VFK] Patch enabling copy operations for VFKProperty class applied … - 5:23 AM SoftwareUsingGdal edited by - add GMT that optionnaly uses GDAL since GMT 4.5.1 (diff) - 5:13 AM Changeset [18508] by - Use VSIF*L API for ramp text file - 5:09 AM Changeset [18507] by - Remove unused function - 3:00 AM Ticket #3318 (Ingres : missing parenthesis in logical test ?) created by - In ogringrestablelayer.cpp, line 547, there's the following code : … Jan 9, 2010: - 3:02 PM AutotestStatus edited by - (diff) - 12:51 PM Changeset [18506] by - Introduce a gdaltest.unzip() and use it - 12:12 PM Changeset [18505] by - Make it work for Windows too - 11:51 AM Changeset [18504] by - test_ogrsf: Write test : restore initial order of 2nd and 5th features … - 11:45 AM AutotestStatus edited by - OGR OGDI driver tested + new VFK driver (diff) - 11:43 AM Changeset [18503] by - Add test for OGR OGDI driver - 11:38 AM Changeset [18502] by - OGR OGDI : force ResetReading?() when changing current layer - 10:43 AM Changeset [18501] by - Documented GDALRasterBlock constructor arguments. Experimenting … - 10:23 AM Changeset [18500] by - Replaced remaining C-style casts with static_cast in C API wrappers of … - 10:15 AM Changeset [18499] by - OGR OGDI: avoid that a spatial filter set on a layer gets implicitely … - 9:04 AM Changeset [18498] by - configure : fix dummy content added to EXTRA_INCLUDES when system libz … - 8:14 AM Changeset [18497] by - Replace print statement by print() function for py3 compat - 8:13 AM Changeset [18496] by - [autotest] replaced deprecated import of gdal with osgeo.gdal convention - 8:00 AM Changeset [18495] by - [autotest] Prefer print() instead of print - 7:55 AM Changeset [18494] by - Validate pData pointer in RasterIO methods of GDALDataset and … - 7:50 AM Changeset [18493] by - [autotest] added support of basic arguments handling to run_all.py: -h … - 7:48 AM JasPer edited by - (diff) - 7:22 AM JasPer edited by - (diff) - 7:03 AM Changeset [18492] by - [autotest] replaced deprecated import of gdal with new convention - 1:34 AM Changeset [18491] by - Python bindings of SpatiaReference?.str : don't use delete[] to … Jan 8, 2010: - 9:44 PM Changeset [18490] by - implement support for reading and writing vertical datum info from geotiff - 9:10 PM Changeset [18489] by - fixed COMPD_CS handling in IsGeographic?() - 7:27 PM Changeset [18488] by - [OGR VFK] Fixed naming convention in VFKProperty class. - 7:13 PM Ticket #3317 (Patch enabling copy operations for VFKProperty class) created by - This patch implements copy constructor and assignment operator for … - 6:38 PM Changeset [18487] by - [OGR VFK] Assert pointer to data passed to VFKFeature ctor is not null - 5:26 PM Changeset [18486] by - Added VFK source files to makegdal80.vcproj - 5:08 PM Changeset [18485] by - [OGR VFK] Replaced manual memory management for string property with … - 4:10 PM Changeset [18484] by - [OGR VFK] Declare VFKProperty constructors as explicit. - 3:59 PM Changeset [18483] by - [OGR VFK] Refactoring applying coding and style guidelines, small … - 3:22 PM Changeset [18482] by - Added missing header in gdal_grid.cpp and cleaned compilation warning - 3:09 PM Changeset [18481] by - Correctly pair free() with malloc() - 2:36 PM Changeset [18480] by - Test OGRFeature::Equal() - 2:35 PM Changeset [18479] by - Implement test for equality of fields value in OGRFeature::Equal() - 9:12 AM Ticket #3316 (Crash and geolocation array extraction problems with HDF4 LISOTD_HRAC ...) created by - Several problems with specific HDF dataset: Dataset source: … - 8:25 AM Ticket #3303 (gdal-translate does not understand my .IMG files) closed by - worksforme: I did: […] and I see: […] so it appears the source image … - 6:32 AM Changeset [18478] by - update VFK html file - 6:14 AM Changeset [18477] by - Updated default value (0) in comment of GDALRasterBand::RasterIO method. - 4:21 AM Changeset [18476] by - Updated default value (0) in comment of GDALDataset::RasterIO method. - 2:17 AM Changeset [18475] by - VFK: fix some errors reported by test_ogrsf utility (trac #3315) Jan 7, 2010: - 3:41 PM Changeset [18474] by - Test CreateFeature?() and SetFeature?() on a dataset that has only a … - 3:40 PM Changeset [18473] by - Shapefile driver : fix CreateFeature?() and SetFeature?() on a dataset … - 3:36 PM Changeset [18472] by - Pedantic cleanups. This changeset fixes build issues on more pedantic … - 2:25 PM Ticket #3315 (VFK : errors reported by test_ogrsf utility) created by - To check it : go in apps, and 'make test_ogrsf' then run test_ogrsf on … - 2:17 PM Changeset [18471] by - OGRFeature::Equal() : fix crash when the geometry of second feature is … - 1:50 PM Ticket #3314 (VFK driver : memory leak and memory use errors) closed by - fixed: Martin, yep with r18470, valgrind is now happy. Thanks for being so … - 1:41 PM Changeset [18470] by - VFK: fix typo in variable name - 1:35 PM Changeset [18469] by - VFK: more memory leaks fixed (trac #3314) - 1:16 PM Changeset [18468] by - VFK: fix freeing memory - 1:02 PM Changeset [18467] by - VFK: some memory leak fixed (trac #3314) - 12:40 PM Changeset [18466] by - Unix VFK support : change logic to enable it by default. --disable-vfk … - 12:39 PM Changeset [18465] by - Added 'maintainer wanted' note to Windows CE port manual page. - 12:08 PM Changeset [18464] by - Revert r18448 to use again rename : why ? well, no idea really apart … - 11:52 AM Changeset [18463] by - regenerated with reference autoconf - 11:34 AM Ticket #3314 (VFK driver : memory leak and memory use errors) created by - Martin, I'm attaching the output of "valgrind --leak-check=full … - 11:31 AM Changeset [18462] by - Revert unwanted debug trace - 11:28 AM Changeset [18461] by - Add missing stuff for win32 VFK support - 11:00 AM Changeset [18460] by - Add missing file to makefiles - 10:43 AM Changeset [18459] by - Remove 2 object files from target rules as the source have been removed - 10:34 AM Changeset [18458] by - Avoid errors when driver is not compiled - 10:01 AM Changeset [18457] by - add newline at end of file - 9:12 AM Changeset [18456] by - Get a last missed file in the cleanup. - 9:07 AM Changeset [18455] by - Various cleanups -- remove code that won't be used outside of PCI. Add … - 8:40 AM Changeset [18454] by - vfk added - 8:34 AM Changeset [18453] by - fix type (.o -> .obj) - 7:18 AM Changeset [18452] by - VFK: don't print warning for KATUZE block & happy new year - 3:47 AM Ticket #3313 (GRASS driver crash after MAPSET unset) created by - The bug was first reported in qgis: … - 2:58 AM Changeset [18451] by - set svn properties - 2:45 AM Changeset [18450] by - autotest for VFK driver added - 1:09 AM Changeset [18449] by - VFK driver added Jan 6, 2010: - 5:02 PM ECW edited by - add pointer to another useful patch for libecwj. (diff) - 12:02 PM Changeset [18448] by - Use ren instead of rename to fix build with MSVC under Cygwin shell … - 9:38 AM Ticket #3210 (Default nmake.opt fails to build with Visual C++) closed by - wontfix: Mateusz, Thanks for tracing this down. I find it hard to imagine … Jan 5, 2010: - 2:46 PM Changeset [18447] by - VRT tutorial : better nesting of the presentation of the elements to … - 1:48 PM Changeset [18446] by - Try to improve the description of what the -addalpha option of … - 12:18 PM Changeset [18445] by - Unix: avoid compiling INGR et NITF drivers against internal libtiff … - 11:51 AM Changeset [18444] by - Win32 : avoid compiling MrSID driver against internal libgeotiff … - 11:33 AM Changeset [18443] by - The E in AXIS["E",EAST] needs quoting - 10:55 AM Changeset [18442] by - modest ability to ingest and operate on COMPD_CS coordinate systems - 6:42 AM Ticket #3312 (Add support for new metadata item "coordinate system string" to ENVI driver) created by - ENVI 4.7 adds a new metadata item called "coordinate system string" … - 12:10 AM Ticket #3311 (Use of gdalwarp projecting to Michigan Oblique Mercator) created by - Is anyone aware of the use of gdalwarp on gtiff files; projecting from … Jan 4, 2010: - 7:46 PM Changeset [18441] by - new - 6:41 PM Changeset [18440] by - remove gcp flipping logic from ESRI merge as it seems to break some … - 2:09 PM Changeset [18439] by - avoid running cleanup when the utility is unavailable - 2:06 PM Changeset [18438] by - Add a test for gdal_rasterize utility - 1:35 PM Ticket #3310 (Segmentation fault in gdal_rasterize with shapefiles with empty geometries) closed by - fixed: Already fixed in trunk in r17037 r18437 … - 1:33 PM Changeset [18437] by - Be more careful about features with null geometries (backport of … - 12:52 PM Changeset [18436] by - Avoid memory errors when dealing with a too short filename (complement … - 12:45 PM Ticket #3310 (Segmentation fault in gdal_rasterize with shapefiles with empty geometries) created by - I am trying to rasterize a shapefile of the Canary Islands … - 10:40 AM Changeset [18435] by - highly restructured to support .LBL labelled compressed files - 10:39 AM Changeset [18434] by - added compressed PDS support - 9:47 AM Ticket #1743 (Const correctness in cpl_http module) closed by - wontfix: No feedback, no interest, giving up. - 9:44 AM Ticket #2106 (Add GML validation option to ./configure) closed by - wontfix: There has been no interest and I hardly remember what was the idea in … - 9:43 AM Ticket #3153 (Define OGRErr as enumerated type) closed by - wontfix: Giving up. - 9:42 AM Ticket #3194 (SRP shall support Main Raster Image (MRI) that contain multiple zone ...) closed by - fixed: Alan Stratford reports the patch works ok for him. I have no … - 9:39 AM Changeset [18433] by - Support multiple zone images (#3194) Jan 3, 2010: - 3:17 PM Changeset [18432] by - refresh internal libgeotiff from upstream - 3:06 PM Ticket #3309 (Change in libgeotiff broke MrSID support) closed by - fixed: r18431 /trunk/gdal/NEWS: Add a warning about incompatibility between … - 3:05 PM Changeset [18431] by - Add a warning about incompatibility between MrSID GeoDSDK and … - 3:01 PM MrSID edited by - Add note for MrSID and ABI incompatibilities with libgeotiff 1.3.0 or … (diff) - 1:15 PM Ticket #3309 (Change in libgeotiff broke MrSID support) created by - I have fought the whole day long trying to understand why I got … - 7:10 AM Changeset [18430] by - Add missing include - 5:44 AM Changeset [18429] by - Fix crash when running autotest/alg/polygonize.cpp with GDAL compiled … Jan 2, 2010: - 3:39 PM Changeset [18428] by - update portuguese main page - 2:20 PM Changeset [18427] by - Add rules to build testcopywords and testperfcopywords - 12:07 PM Changeset [18426] by - Update NEWS - 12:00 PM Changeset [18425] by - XPlane: discard invalid geometries so that ogr2ogr to postgis works … - 10:52 AM Changeset [18424] by - Test for stopway layer - 10:51 AM Changeset [18423] by - XPlane : add a new layer 'Stopway' that contains a polygon with the … - 2:29 AM Changeset [18422] by - Don't make a 3D linearring - 1:11 AM Ticket #3308 (GDAL Georaster Use the Compression type import raster can't build pyramid!) created by - I use GDAL Georaster component import raster data into Oracle … Jan 1, 2010: - 12:54 PM Changeset [18421] by - Simplify PrepareEjection?(): no need for temporary array to reverse an … - 12:16 PM AutotestStatus edited by - NWT_GRC and NWT_GRD tested now (diff) - 10:49 AM MaintenanceReportsByChaitanya edited by - Oct 28, 2009 to Jan 1, 2010 (diff) - 9:53 AM Ticket #3129 (Contour orientation) closed by - fixed: Added a test and documentation in r18420 in trunk. - 9:53 AM Changeset [18420] by - Added a test to check contour orientation and the related … Dec 31, 2009: - 12:38 PM Changeset [18419] by - added -unscale commandline option - 12:28 PM Changeset [18418] by - Generate contours with correct orientation. (#3129) Dec 30, 2009: - 7:32 PM Ticket #3307 (FAST files with 7 bands not missing one band) closed by - fixed: Regression test added in trunk (r18416). The demonstration file is … - 7:32 PM Changeset [18417] by - support a 7th band (#3307) - 7:26 PM Ticket #3306 (FAST files without SENSOR not working) closed by - fixed: Regression test added in trunk (r18416). The demonstration file is … - 7:24 PM Changeset [18416] by - added RevB tests (#3306, #3307) - 3:56 PM Changeset [18415] by - preliminary extension to support seven bands (#3307) - 3:55 PM Ticket #3307 (FAST files with 7 bands not missing one band) created by - For reasons that are not clear to me, a client's EOSAT FAST FORMAT … - 3:35 PM Changeset [18414] by - fix regression (r16396) that caused SENSOR name to be required (#3306) - 3:27 PM Ticket #3306 (FAST files without SENSOR not working) created by - I have a RevB fast format file from a client with no SENSOR keyword. … - 8:20 AM Changeset [18413] by - Handle the .shp file length limits more gracefully. (#3236) - 7:16 AM Ticket #3305 (Cannot open file in SRTMHGT format) closed by - wontfix: Unfortunately the file starts with the byte sequence 0xffd8ff and this … - 6:44 AM Ticket #3305 (Cannot open file in SRTMHGT format) created by - When trying to read a file in SRTM3 .hgt format, I get the following … - 4:54 AM Ticket #3161 (Enhancements proposal for gdal_merge.py) closed by - fixed: Applied the patch in trunk (r18412) - 4:53 AM Changeset [18412] by - Make gdal_merge into a module. Add a global version variable. (#3161) Dec 29, 2009: - 11:35 PM Ticket #3237 (Northwood/VerticalMapper Driver Contribution) closed by - fixed: Added tests in trunk in r18411. - 11:32 PM Changeset [18411] by - Add tests for Northwood/VerticalMapper? driver. (#3237) Dec 28, 2009: - 5:41 PM Changeset [18410] by - make fixed arrays dynamic - 5:10 PM Changeset [18409] by - added spline support - 8:16 AM Changeset [18408] by - Update tests for ADRG (#3302) - 8:15 AM Changeset [18407] by - ADRG: rework to support subdatasets; implement GetFileList?() (#3302) - 6:46 AM Ticket #3247 (Shapefile driver truncated field names, sometimes causing duplicates) closed by - fixed: r18406 in trunk will test that the data goes into the correct field. - 6:44 AM Changeset [18406] by - Test that data goes into the right fields with ogr2ogr (#3247) - 3:39 AM Ticket #3304 (Crash on histogram computation) closed by - fixed: r18403 /trunk/gdal/ (3 files in 3 dirs): Fix crash of Python bindings … - 3:39 AM Changeset [18405] by - Test GetDefaultHistogram?( force = 0 ) (#3304) - 3:38 AM Changeset [18404] by - Fix crash of Python bindings when … - 3:37 AM Changeset [18403] by - Fix crash of Python bindings when … - 1:20 AM Ticket #3304 (Crash on histogram computation) created by - The python interpreter crashes when I try to get the default histogram … Note: See TracTimeline for information about the timeline view.
http://trac.osgeo.org/gdal/timeline?from=2010-01-27T22%3A12%3A07-0800&precision=second
CC-MAIN-2016-40
refinedweb
7,432
50.2
In this shot, we will learn how to test your code in Go. Go has built-in support for testing using the testing package. Package testing provides support for automated testing of Go code. It intended to be used with the go test command that automates the execution of any function of the following form: func TestXxx(*testing.T) Where Xxxdoes not start with a lowercase letter and the function name identifies the test routine. Within these functions, use Error, Fail, or related methods to signal failure. Create a file that contains the TestXxx functions described above and whose name ends with _test.go to write a new test suite and place it in the same package as the one being tested. A typical unit test will look something like this: import "testing" func TestAbc(t *testing.T) { t.Error() // indicate test failed } The test file will be included when the go testcommand is run. For more details, run go help testand go help testflag. Let’s write a simple unit test using the testing package. We will test an add function to check if it correctly adds two integers. package main import ( "testing" ) // testing add function func TestAdd(t *testing.T) { // using two positive numbers if add(1, 2) != 3 { t.Errorf("Failed with positive numbers.") } // using two negative numbers if add(-1, -2) != -3 { t.Errorf("Failed with negative numbers.") } } RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/what-is-built-in-testing-support-in-go
CC-MAIN-2022-33
refinedweb
238
68.06
class QueueHandler(logging.Handler): """ This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. This code is new in Python 3.2, but this class can be copy pasted into user code for use with earlier Python versions. """ def __init__(self, queue): """ Initialise an instance, using the passed queue. """ logging.Handler.__init__(self) self.queue = queue def enqueue(self, record): """ Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue implementations. """ self.queue.put_nowait(record) def emit(self, record): """ Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. """ try: # self.enqueue(record) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) This code is perfectly usable in earlier Python versions, including 2.x - just copy and paste it into your own code. In addition to usage with queues from the queue and multiprocessing modules (as described in this earlier post), the QueueHandler makes it easy to support other queue-like objects, such as ZeroMQ sockets. In the example below, a PUBLISH socket is created separately and passed to the handler (as its ‘queue’):() To test this out, put this together into a little test script (imports not shown, but you can get the working script here): def main(): print('Enter messages to send:') h = ZeroMQSocketHandler('tcp://*:5556') logger = logging.getLogger() logger.addHandler(h) try: while True: s = raw_input('> ') logger.warning(s) finally: logger.removeHandler(h) h.close() For the receiving end, you can use a simple script like this: import json import pprint import zmq URI = 'tcp://localhost:5556' def main(): print('Receiving on a SUB socket: %s' % URI) ctx = zmq.Context() sock = zmq.Socket(ctx, zmq.SUB) sock.setsockopt(zmq.SUBSCRIBE, '') sock.connect(URI) try: while True: msg = sock.recv() data = json.loads(msg) pprint.pprint(data) print('-'*40) finally: sock.close() if __name__ == '__main__': main() And the output would be something like: Receiving on a SUB socket: tcp://localhost:5556 {u'args': None, u'created': 1284446528.9099669, u'exc_info': None, u'exc_text': None, u'filename': u'zmqlog.py', u'funcName': u'main', u'levelname': u'WARNING', u'levelno': 30, u'lineno': 78, u'message': u"It's easy to log to ZeroMQ!", u'module': u'zmqlog', u'msecs': 909.96694564819336, u'msg': u"It's easy to log to ZeroMQ!", u'name': u'root', u'pathname': u'zmqlog.py', u'process': 13647, u'processName': u'MainProcess', u'relativeCreated': 521204.14185523987, u'thread': -1215568192, u'threadName': u'MainThread'} ---------------------------------------- This is great! I have written my own handler before for writing to a "multiprocessing" queue, but 0MQ has grabbed my attention as a better direction for putting together the pieces of my application. HI, this is nice. Also, pyzmq ships with log handlers for the logging module: Cheers @Brian: Thanks, I'd missed that.
http://plumberjack.blogspot.my/2010/09/queuehandler-and-zeromq-support.html
CC-MAIN-2018-13
refinedweb
502
58.79
Contribution of security selection and contribution of asset allocation Problem 1: Consider the following information regarding the performance of a money manager. The table presents the actual return of each sector of the manager's portfolio in column (1), the fraction of the portfolio allocated to each sector in column (2), the benchmark or neutral sector allocation in column (3), and the returns of the sector indexes in column (4). (12 points) (1) Actual return (2) actual weight (3) Benchmark Weight (4) Index Return Equity 2.5% 0.65 0.6 2.6 (S&P 500) Bonds 1% 0.2 0.3 1.1 (Bond Index) Cash 0.5% 0.15 0.1 0.4 1). What was manager's return in the month? What was the over or underperformance? Show your calculations. 2). What's contribution of security selection to the relative performance? Show your calculations. 3). What was the contribution of asset allocation to the relative performance? Show your calculations. -------------------- Problem 2: Company A's 10 percent coupon rate, quarterly payment, $1,000 par value bond, which matures in 10 years, currently sells at a price of $950. The company's tax rate is 38 percent. Based on the nominal interest rate, what is the firm's cost of debt? Show your calculations. Solution Summary The contribution of security and contributions of assets are examined.
https://brainmass.com/business/interest-rates/contribution-security-selection-contribution-asset-325030
CC-MAIN-2017-43
refinedweb
227
50.63
Explorer Data Provider Sample Demonstrates how to implement a Shell namespace extension, including context menu behavior and custom tasks in the browser. This topic contains the following sections. Requirements Downloading the Sample Building the Sample To build the sample from the command prompt: - Open the command prompt window and navigate to the ExplorerDataProvider project directory. - Enter msbuild ExplorerDataProvider.sln. To build the sample using Microsoft Visual Studio (preferred): - Open Windows Explorer and navigate to the ExplorerDataProvider project directory. - Double-click the icon for the ExplorerDataProvider.sln file to open the project in Visual Studio. - From the Build menu, select Build Solution. The DLL will be built in the default \Debug or \Release directory. Note In the version of this sample included in the Windows SDK, the configuration for the 64-bit Release build does not include the ExplorerDataProvider.def file in the linker's Module Definition File option. You must specify that file yourself before building in a 64-bit environment. Add the line ModuleDefinitionFile="ExplorerDataProvider.def" to the VCLinkerTool section (begins at line 329) of the ExplorerDataProvider.vcproj file as shown here: The version of this sample downloadable from Code Gallery has been corrected for this issue and no extra action is required on your part. Running the Sample Navigate to the directory that contains the new .dll and .propdesc file, using the command prompt or Windows Explorer. At the command line, type regsvr32.exe. Note If you run this command from an elevated command prompt, the self-registration will also register the .propdesc file automatically. If it is run from a non-elevated command prompt then the namespace extension will work, but without custom property functionality. Open the My Computer folder and browse the new namespace extension present there.
https://docs.microsoft.com/en-us/windows/win32/shell/samples-explorerdataprovider
CC-MAIN-2021-17
refinedweb
291
50.23
A while ago we had the need to grab the App window variable (exposed by CefSharp) and we were extending the Window interface to do that. There seems to be a better way to get variables that are define in the Window environment. I learned this from this link An advanced guide on how to setup a React and PHP. If you are defining a variable or object you want to read from React (like in CefSharp, o directly in the HTML like in the screenshot) // inside of your app entry HTML file's header <script> var myApp = { user: "Name", logged: true } </script> You can do a declare module 'myApp' in index.d.ts, then add the myApp variable as a external library in Webpack's config file externals: { myApp: `myApp`, }, Then you can import as if it was a module in TypeScript (or JavaScript files) with React import myApp from 'myApp'; And you can even use TypeScript destructuring technique to get internal properties directly const { user: { name, email}, logged } = myApp; If you found this useful, you might want to join my newsletter; or take a look at other posts about code, TypeScript, and React.
https://nono.ma/says/use-window-variables-in-redux-via-webpack
CC-MAIN-2019-43
refinedweb
195
58.08
I recently bought a 16 bit I2C A/D converter based on the TI ADS1115 chip. it's pretty well priced in my opinion for being a complete break-out module and seems to have very good specs. uint8_t count = 0; Wire.beginTransmission(devAddr); Wire.send(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, length); // request length bytes from device unsigned long readStart = millis(); do { if(Wire.available() >= length ) { for (; Wire.available(); count++) { data[count] = Wire.receive(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); Serial.print(" "); #endif } } } while(millis() - readStart < timeout); //wait up to timeout period reading Wire.endTransmission(); Thanks Jeff, that would be great. I've had the device for over a week now but just not the time to try and cobble something together. I'm a hardware type and software comes slow and gradual to me. The built in A/D pins on a arduino are useful but sadly fall far short of instrumentation quality. I thoough this would be a nice improvement to have avalible. one suggestion is to add a timeout property to the library so calls want hang if the I2C device does not respond. ... You would want to inform the caller of a timeout, for example return 0 if the code times out. I suppose you library doesn't think of itself as a slave device, but can you implement that for inter-Arduino talks. Jeff, Very nice professional work! Thanks for the effort. I'll be following... The timeout is set to a default of 250ms (defined in I2Cdev.h). Read operations that time out return -1, while 0 indicates instant failure and 1 or more indicates success. A timeout length of zero disables timeout detection. #define ADS1115_ADDRESS_ADDR_GND 0x90 // address pin low (GND)#define ADS1115_ADDRESS_ADDR_VDD 0x91 // address pin high (VCC)#define ADS1115_ADDRESS_ADDR_SDA 0x92 // address pin tied to SDA pin#define ADS1115_ADDRESS_ADDR_SCL 0x93 // address pin tied to SCL pin#define ADS1115_DEFAULT_ADDRESS ADS1115_ADDRESS_ADDR_GND #define ADS1115_ADDRESS_ADDR_GND 0x48 // address pin low (GND)#define ADS1115_ADDRESS_ADDR_VDD 0x49 // address pin high (VCC)#define ADS1115_ADDRESS_ADDR_SDA 0x4A // address pin tied to SDA pin#define ADS1115_ADDRESS_ADDR_SCL 0x4B // address pin tied to SCL pin#define ADS1115_DEFAULT_ADDRESS ADS1115_ADDRESS_ADDR_GND Hardware for this design includes: one ADS1113/4/5 configured with an I2C address of 1001000; I think that 250ms is too short for some precision I2C devices that have long sample times.I suggest at least doubling the default value to avoid false errors with those devices. Thank you very much for your quick work on this ADS1115 device. I will try and check it out with the module this weekend. One possible question I have on a quick read through, are you sure about the I2C device addresses this device would use? ... From the datasheet (QuickStart Guide, page 11) the 7 bit address is show as [1001000]. ... My understanding with using the Wire library calls, that one uses the 7 bit address for the calls and the Wire library adds the internal R/W bit to form the full 8 bit I2C address? ... As a compromise, I've left the default at 250ms and added an optional "timeout" argument to the tail end of each read* method, so that for those specific actions that might legitimately take a long time, it's easy to specify a longer timeout. You could already have just modified the I2C::readTimeout variable before calling the desired read* method, but that's not very convenient or pretty. This is much better, and I probably should have done it that way in the first place. Yay for helpful ideas from other people! The Arduino MasterReader example Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=68210.0
CC-MAIN-2016-40
refinedweb
632
63.9
Just wanted to share this indicator I've been working on in case anyone sees any value. The basic idea is to determine trend while reducing the false positives in moving averages. So instead of caring about whether a price is above or below a MA, it looks at the relationship between the mean of the price for n periods vs the mean of the MA for the same period. def get_bias(ma,pc,context): ma = ma[-context.bias_lookback:]# array of moving average values pc = pc[-context.bias_lookback:]# array of price close values ma_mean = np.mean(ma)# mean of moving averages pc_mean = np.mean(pc)# mean of price values if ma_mean > pc_mean:# determines down bias and gets strength strength = ma_mean - pc_mean return 2,strength #short if pc_mean > ma_mean:# determines up bias and gets strength strength = pc_mean - ma_mean return 1,strength #long By returning the strength of the bias (up or down), we can place long and short trades for the given bias and adjust the shares according to the strength. So if the long bias is low, then we only risk a few shares and vice versa for a strong bias.
https://www.quantopian.com/posts/market-bias-indicator
CC-MAIN-2018-30
refinedweb
191
68.4
I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet. Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wondering why that is? For example: The following code is taken from a file called ApplicationCreator.java. I noticed that the public class ApplicationCreator essentially instantiates itself twice, or am I missing something here? public class ApplicationCreator<MR> implements IResourceObjectCreator<BinaryRuleSet<MR>> { private String type; public ApplicationCreator() { this("rule.application"); } public ApplicationCreator(String type) { this.type = type; } 1) Why would the class instantiate itself inside the class? The class is not calling itself, it is proving a way for others to instantiate its object. Read about constructor. 2) Why would it do so twice? Or is this a way to set certain parameters of the ApplicationCreator class to new values? As I said, it is a way to create object. 1st one will assign default value to type. And 2nd will give others an option to assign a value. Read about constructor overloading. this in the constructor will call another constructor of the same class depending upon argument type passed to this.
https://codedump.io/share/zTQBzKqtLmHf/1/why-specify-a-method-twice---java
CC-MAIN-2017-39
refinedweb
219
51.14
torrent arcade games, nick arcade games, free enternet arcade games, q bert arcade game, lease commercial arcade games. espn arcade games, wwf arcade game, early penney arcade games, games coming to xbox live arcade, classic arcade games playstation 2. pin-up art arcade game, pinball arcade game rentals milwaukee wi, free mad caps arcade games, vbulletin arcade games, used arcade game gravity hill. used arcade game gravity hill, arcade games net roids, download xbox arcade games to dvd, flash arcade games galaga, top video arcade games, free dowload arcade games. arcade game repair manuals, megaman arcade game, all reflexive arcade games v3.0, cyberball arcade game for sale, ms. pacman arcade game. joystick arcade games, downlodable arcade games, free arcade fishing games, resturaunt games arcade, arcade game repair manuals. import arcade games, top video arcade games, 1990 arcade games online, all reflexive arcade games v3.0, arcade game t shirts. espn arcade games, download 80's arcade games, all reflexive arcade games, austin texas arcade restaurant games pool, nbc arcade games. video arcade game music download 80s, restaurants with arcade games, wrestlemania the arcade game genesis fatalities, school arcade games, war fighter arcade game. arcade style fighting games, used pacman arcade game, downloadable casino arcade games for mac, espn arcade games, crime fighters arcade game. arcade games dallas fort worth, reflexive arcade games build, top arcade racing games, atari arcade games, arcade game hire sydney. video arcade games archives, golden t 2007 arcade game, free arcade games online color sudoku, austin texas arcade restaurant games pool, arcade game rentals winnipeg. Categories - Iphone arcade games - arcade game hire sydney arcade games for businesses arcade games top referrers best arcade games of the 90's cannon arcade game arcade games at home robotron 2084 game in a bottle arcade lounge games like arcade and dress up arcade games on ds free action arcade puzzle games iron horse arcade game water squirting arcade games - stoner arcade games - free retro arcade games - arcade games in pa - tmnt the arcade game - free arcade game penguin freeze - ninja kiwi games arcade power pool - nick arcade games - arcade games gate - old arcade space games - gatlinburg cabins with arcade games
http://manashitrad.ame-zaiku.com/926-reflexive-arcade-games.html
CC-MAIN-2019-04
refinedweb
362
57.3
Hi, I'm writing a new "FAT Python" project to try to implement optimizations in CPython (inlining, constant folding, move invariants out of loops, etc.) using a "static" optimizer (not a JIT). For the background, see the thread on python-ideas: See also the documentation: I implemented the most basic optimization to test my code: replace calls to builtin functions (with constant arguments) with the result. For example, len("abc") is replaced with 3. I reached the second milestone: it's now possible to run the full Python test suite with these optimizations enabled. It confirms that the optimizations don't break the Python semantic. Example: --- >>> def func(): ... return len("abc") ... >>> import dis >>> dis.dis(func) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_CONST 1 ('abc') 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 9 RETURN_VALUE >>> len(func.get_specialized()) 1 >>> specialized=func.get_specialized()[0] >>> dis.dis(specialized['code']) 2 0 LOAD_CONST 1 (3) 3 RETURN_VALUE >>> len(specialized['guards']) 2 >>> func() 3 >>> len=lambda obj: "mock" >>> func() 'mock' >>> func.get_specialized() [] --- The function func() has specialized bytecode which returns directly 3 instead of calling len("abc"). The specialized bytecode has two guards dictionary keys: builtins.__dict__['len'] and globals()['len']. If one of these keys is modified, the specialized bytecode is simply removed (when the function is called) and the original bytecode is executed. You cannot expect any speedup at this milestone, it's just to validate the implementation. You can only get speedup if you implement *manually* optimizations. See for example posixpath.isabs() which inlines manually the call to the _get_sep() function. More optimizations will be implemented in the third milestone. I don't know yet if I will be able to implement constant folding, function inlining and/or moving invariants out of loops. Download, compile and test FAT Python with: hg clone ./configure && make && ./python -m test test_astoptimizer test_fat Currently, only 24 functions are specialized in the standard library. Calling a builtin function with constant arguments in not common (it was expected, it's only the first step for my optimizer). But 161 functions are specialized in tests. To be honest, I had to modify some tests to make them pass in FAT mode. But most changes are related to the .pyc filename, or to the exact size in bytes of dictionary objects. FAT Python is still experimental. Currently, the main bug is that the AST optimizer can optimize a call to a function which is not the expected builtin function. I already started to implement code to understand namespaces (detect global and local variables), but it's not enough yet to detect when a builtin is overriden. See TODO.rst for known bugs and limitations. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-dev/2015-November/142113.html
CC-MAIN-2017-39
refinedweb
454
58.48
Introduction. This is a tutorial for getting the date and time and displaying it or working on it. This is very useful tutorial. So Lets Learn it… Program for Getting the date & time in java. //import Date as we require it. import java.util.Date; // the name of our class its public public class DateExample { //void main public static void main (String[] args) { //declare Date Date d = new Date(); //print the Date System.out.println("Its Now:-"); System.out.println(d.toString()); } } Output Its Now:- Tue Nov 19 18:28:52 IST 2013 How does it work - Nothing to input the date and time is directly printed. Extending it The program can be extended. This is a basic concept of java programming and has lots of applications. Explanation. - Import the Date. - Declare the class as public - Add the void main function - Declare Date object. - Add system.out.println() function to print the date and time. At the end. You learnt creating the Java program for Getting Date and Time. So now enjoy the program. Please comment on the post and share it.
https://techtopz.com/java-programming-getting-the-date-time-tutorial-and-example/
CC-MAIN-2019-43
refinedweb
182
69.18
Import is a keyword . Import keyword is used built in or user defined packages into java source code file. When use package in our source file then access the package class with import keyword declaration. The compiler can access any class in the java.lang package without needing an import statement. import mypackage.*; import mypackage.extrapackage.*; import java.applet.*; Indicate that classes can be found in the mypackage and mypackage.extrapackage packages and also that the Applet class can be found in the java.applet package. The first import statement gives the full package path name for the Applet class in the packages included with the standard JVM, then when the compiler sees just Applet in the class definition title, it will know where to find it. In the next two import statements, we see the "*" wildcard character used for the classes in the mypackage and mypackage. extrapackage packages. This indicates that these packages hold multiple classes and the compiler should look here if it cannot find a class in the core packages. import java.util.Scanner; public class ScannerTest { public static void main(String arg[]) { // scanner gets its input from the console. Scanner sc = new Scanner(System.in); String name = ""; System.out.print("Your name "); // Get the user's name. name = sc.next(); System.out.println(); // Print their name in a a message. System.out.println("Welcome, " + name + " to Javaland!"); } } In this program uses Scanner class Method is use This class is pre defined class is define java itself and this class method uses in our class , to use import keyword and acess the class. java is a package and util is a sub package and this package inside the class Scanner. import java.util.*; The * is a "regular expression operator" that will match any combination of characters. Therefore, this import statement will import everything in java.util. If we need multiple classes from different packages, we use an import statement for each package from which we need to import classes (or interfaces, or any other part of that package we need.) import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing
http://r4r.co.in/java/corejava/java_basic_tutorial/import_statement_in_java.shtml
CC-MAIN-2021-39
refinedweb
359
55.44
C++ comes with a number of standard libraries.Some libraries are commercial & limited to perticular compiler while some are included in every compiler.These libraries place their definitions inside namespace.So we’ll discuss what namespace is,but before moving onto namespace let’s clear few things about libraries. Libraries In C++,you came across so many built-in libraries.You can use these libraries in your program with the help of include directive.An include directive for a standard library has the form: #include<iostream> You’ve already used the iostream library in your program.Include directive is preprocessor directive that add the information from library file.Here,library name is the name of header file that includes all the definition of items in the library. Note: Most older compilers like Turbo C++ 3.0 do not confirm to the current namespace standard.So your usage of the standard library is restricted with these old compilers.With these compilers you’ve to write the library filename extention as .h,and you do not need the using directive. Namespace Namespace is simply a collection of name definitions,like class and variable declarations.With namespace you can reuse the names of classes,functions, and other items by qualifying the names to indicate different uses.This allows your code to be modular & reusable.You can have more than one namespace in your program.But it is manadatory to write using directive,if you’ve used any namespace in program.For example,if you’re writing standard I/O program then you must include these lines in your program. #include <iostream> using namespace std;If you want to make specific part of namespace available to your program like std::cin or std::cout then you can modify the using directives as shown below. using std::cin; using std::cout; using std::endl; This can be helpful if you’re using multiple namespace. Creating Namespace You place a name definition in a namespace by placing it in a namespace grouping.You just have to palce your code inside the namespace which in turn will be available as part of the namespace throughout the program.This way namespace can be helpfull in larger programs. namespace Name_Space_Name {//functions etc Or any other code goes here.} You can even nest your namespace or can have two different namespace in your program.As well as you can have unnamed namespace which makes name definition local to a compilation unit. There are three ways you can use the namespace in your program: 1. by making all the names in the namespace available with a using directive. 2. by making the single name available with a using declaration for the one name. 3. by qualifying the name with the name of the namespace and the scope resolution operator. To use this namespace all you’ve to do is use the using directive.For example: using namespace Name_Space_Name; You can easily test this if you use modern IDE’s like Dev-C++,Visual C++ express and Turbo explorer.Again if you’re using older compilers like TC3 & VS5.0 which do not supprort namespaces,above information doesn’t apply to them. I hope the information helped.If you have any questions or comments, please don’t hesitate to post them here.Please note:I will not entertain source code & project requests.
https://onecore.net/libraries-and-namespaces.htm
CC-MAIN-2018-34
refinedweb
560
58.38
The Whiz of Silver Bullets 244 ChelleChelle writes "In an entertaining yet well thought-out article, software architect Alex E. Bell of The Boeing Company lashes out at the so-called 'Silver Bullets' and those who rely on them to solve all their software development difficulties. From the article: 'the desperate, the pressured, and the ignorant are among those who continue to worship the silver-bullet gods and plead for continuance of silver-fueled delusions that are keeping many of their projects alive.'" The Real Silver Bullet (Score:4, Funny) Re:The Real Silver Bullet (Score:3, Funny) Re:The Real Silver Bullet (Score:2) Re:The Real Silver Bullet (Score:2) Silver bullet, or dum-dum bullet? Re:The Real Silver Bullet (Score:2) Seriously though, people need to learn that software is a tool. For example, houses would never get built without hammers, but you still need skilled workers putting in the hours to get it done. Silver Bullet in a Concealed-Carry Revolver (Score:4, Funny). If you are over 18 years of age, you need to weigh the situation carefully. If you kill your boss, then you will definitely be tried for 1st degree murder. You may be eligible to submit a plea of insanity. Most states allow such a plea. Check with your lawyer before you start shooting. Re:Silver Bullet in a Concealed-Carry Revolver (Score:2) How many software firms hire 16-17 year-olds? Re:Silver Bullet in a Concealed-Carry Revolver (Score:2) Why did you choose to insult my abilities as a software developer? Re:Silver Bullet in a Concealed-Carry Revolver (Score:2) Re:Silver Bullet in a Concealed-Carry Revolver (Score:3, Informative) ." You don't live in the US, do you? In the US, persons under the age of 18 are tried, convicted and executed [ncadp.org] on a Re:Silver Bullet in a Concealed-Carry Revolver (Score:2, Interesting) I am still waiting to see occ Well... (Score:5, Insightful) Re:Well... (Score:4, Insightful) And this is what has to change. Saying that techs should make all the decisions is of course unrealistic, but in a sane company the management lets them evaluate the solutions before deciding. Re:Well... (Score:5, Insightful) Why ? Think about it from the management's point of view. The choices they face are: Which one should a sane manager choose ? Getting fired or getting a bonus ? Re:Well... (Score:3, Insightful) IMarv Re:Well... (Score:3, Interesting) Actually, it would only stop if potential customers would stop believing in silver-bullets. I work in the specialty chemical industry. You would not believe how many times I have been asked for a 'silver bullet', even when I explain that said bullet is impossible because it violates one or more laws of nature. Vendors offer them because customers want them, reality be damned. Here around (Score:2) Stop the BLAME GAME! (Score:5, Interesting) The problem here is that everybody has their own silver bullets, and if you don't happen agree then you think the other person is a bone head. So let's stop the blame game shall we. Re:Stop the BLAME GAME! (Score:5, Insightful) Re:Stop the BLAME GAME! (Score:2) But worse, has he opened his eyes?? Is he so *blinkered* that he does not see that Silver Bullets exist in all spheres of human activity? Failing Football Team? just add Wayne Rooney Global Warming? just change your lightbulbs to savers Middle East Crisis? just send in Condaleeza Rice Endemic Crime? everyone would be fine if there was Education, Education, Education. This guy needs to get out more. Re:Stop the BLAME GAME! (Score:5, Funny) Re:Stop the BLAME GAME! (Score:5, Funny) In our shop, it's Java that accelerates software development, and I don't mean the programming language. Re:Stop the BLAME GAME! (Score:2) Re:Stop the BLAME GAME! (Score:3) People need to understand that good tools do not replace the craftsman. It is possible to write a good program in Visual Basic, Perl, forth, c, or even 6502 assembly. All good tools do, is make the work go faster. But there is a limit to even that. It takes time to care. I do think that some programing languages are better than others. I hated Forth, and I refuse to lean any language that is tied to one operating system. Those are my likes and choices. Unlike a lot of people I like UML and managers (Score:5, Funny) Manager: "This new project should be done with new project management methods, like UML" Senior: "Uuh, you do know that UML is a notation for diagrams?" Manager (irritated): "Yeah, of course I know that. You know what I mean!" Re:UML and managers (Score:2) Re:UML and managers (Score:2) Re:UML and managers (Score:2) Re:UML and managers (Score:2) Re:UML and managers (Score:3, Interesting) Re:UML and managers (Score:3, Interesting) I've been on many projects (and managed quite a few myself) that successfully used UML in requirements gathering (use cases---so business folks can sign off on them; leading to less problems later on), object modeling (database schema generation, php, c#, java, etc., code generation, ado Re:UML and managers (Score:3, Funny) Sorry, no sale :p (Score:4, Interesting) Sorry, I LIVE in a pretty small town in Transylvania (used to live in a slightly larger one), and software developers around here are all BUT immune to (the lure of such) silver bullets... ever heard of Cluj-Napoca or Baia Mare (or any of the software microbehemoths that start springing to life there) ? Re:Sorry, no sale :p (Score:3, Insightful) See, this is the problem with offshoring. It's not the quality of the foreign coders, it's the lack of a shared cultural context in which to collaborate. For instance, no American software company would put "Cluj" in its name. Re:Sorry, no sale :p (Score:2, Funny) Silver Bullets works just fine (Score:2, Insightful) Re:Silver Bullets works just fine (Score:2) GVIM [vim.org] works pretty well for me. I also use NVU for RAD prototyping. Oh and I auctually wrote a useful webservice in C# using SharpDevelop so that counts as well. The sad part is vim sucks the least of these three, although SharpDevelop is starting to support the ASP.NET thing pretty well. Re:Silver Bullets works just fine (Score:4, Insightful) Bullets don't kill people... (Score:5, Insightful) The problem with Silver Bullets is not the bullet itself - but the idiot behind the trigger. Most of these Silver Bullets are great ideas, but give them to some moron who half knows how they work (and yet claims to be an expert) and they do the exact opposite of what they were intended to do, and because some PHB reads about in the industry pages, they just keep hanging in there like a millstone around our respective necks. For any technology you can see outstanding implementations. But for every one of those there are ten other complete disasters. And as the other saying goes - if you don't know who the moron is..... Re:Bullets don't kill people... (Score:3, Insightful) As a manager you are tasked with developing software quickly and cheaply. I liken it to being a farmer. You can till the soil, plant the seeds Re:Bullets don't kill people... (Score:3, Insightful) (ie. "we'll build a steel buidling, because steel is good - and we'll fasten the steel beams together with nails, because our carpenters know how to use nails.") Then when it comes time to implement - the implementor starts the project already painted into a corner by the architect, and has to jump through all kinds of Untried bullets (Score:4, Interesting) My own experience of some of these bullets (UML, agile methods, etc.) within an organisation is that they get a small enthusiastic following who push it so far, implement maybe 20% of the technique then lose interest or regress under deadline pressure. They don't follow the bullet far enough to draw proper conclusions. I'm cynical about most bullets, but some catch the imagination. I'd just like to see one of them, just once, properly implemented. Incidentally, this isn't just an engineering article. Management suffers from the same tendency towards managerial silver bullets (and the same poor application). I guess many professions do. Re:Untried bullets (Score:3, Insightful) Webservices are todays silver bullets (Score:3, Insightful) And every body knows that XML itself is no longer a silver bullet. It is too natural and integrated to not use XML where it fits in. What I worry about is the huge stack of technologies that are currently being built on top of it. Webservices being the biggest of those and worse the stuff that goes on top of that: XML Schemas, WS-YouNameIt, BPMN, BPEL4WS It reminds me of a few years ago when choosing java for an enterprise project meant that you had to use EVERY component in the J2EE stack, so that every single class was a EJB and every single call was a remote call. Now most projects has learnt to stay away from the "classic J2EE" approach, but are instead falling for the next silver bullet which invites to make the excact same mistake using Web Services Webservices are great and has their uses, but I have seen projects that subscribe to the idea that every single component in the project should be a webservice and orchestrated by BPEL. Good luck. Re:Webservices are todays silver bullets (Score:2) You are not from the future, right? Re:Webservices are todays silver bullets (Score:4, Interesting) Web services are probably being overtouted as a silver bullet, but the fact is that they serve a very useful purpose. I maintain a legacy app which uses ad-hoc XML over HTTPS. Since I have no idea what the format of the request and response is, I must constantly refer to the code to figure it out. I must also invent my own error responses if the format is incorrect. Web services mean I could just define the interface in WSDL (using WTP in Eclipse for example) and more or less forget about it. I can even use Axis or .NET's wsdl.exe to auto generate the stubs that make the call and just concentrate on the business logic. Bad calls throw a soap fault which is turned into an exception or whatnot by the client lib that makes the call. It doesn't make all my problems disappear, but it does mean I can be looking at the functionality of the app rather than wasting time rolling my own XML format. And even the ad-hoc XML over HTTPS is quite an improvement over what came before. Then you'd be talking about opening a port and defining the whole handshake and transfer of data using messages, complete with all the bugs and security issues that go with that. Standards are a great thing even if they initially seem confusing. Certainly any standard is open to abuse. I expect that anyone who has to deal with Microsoft's new Office format over XML will be in a world of hurt. But you have Microsoft to blame for that, not the standard. Re:Webservices are todays silver bullets (Score:2, Interesting) Yes sure, it works. It is an easy solution to various simple data-interchange-like problems. However, it is also bulky, inefficient and overly complex. Bulky - needs no explanation. Inefficient - parsing it isn't that trivial, and also applying schemas is expensive and complicated. Multiple levels of namespaces, and so on can lead to complex heirarchical data structures that need a load of work to make sense of. Why 'silver bullets'? (Score:2) So, what's a 'silver bullet' supposed to be good for? Killing werewolves, right? (Or wererats or warehouses or werecanaries.) Given that it's really only good for one extremely limited function, why in the world does a 'silver bullet' represent a solution to a wide range of problems? Re:Why 'silver bullets'? (Score:3, Informative) Sheesh [berkeley.edu] Kids today. Re:Why 'silver bullets'? (Score:2) I remember seeing the explanation of this in an old Lone Ranger movie: Because a silver bullet is so expensive, you don't fire them off in volleys like people do with lead bullets. You take careful aim before you pull the trigger. Unfortunately, the usual management approach with silver software bullets is to supply them to the entire staff, and demand that they be fired at every target at every opportunity. There's a TFA is shallow hogwash (Score:4, Interesting) For one: 'utterance_in_a_state_of_speechlessness' should be 'utterance state="speechlessness"' And further: Using sophisticated design techniques doesn't replace the work, but it can help a piece of software reach it's maximum potential. On the inside of every shop there is a silver bullet: It's called education. A model doesn't replace programming and somewhere beyond the ususal CRUD there's allways work to be done on procedural details - that's where part of the fun in sw developement is. Every developer worth his money knows this. If he where ranting at academics, I'd understand, but as far as I'm conserned he's preaching to the choir. TFA is definitely not 'well-thought-out'. In fact it's a tad pointless. Re:TFA is shallow hogwash (Score:2) Yes, it is yet another article that can be summed up by "Some technologies are overhyped and used inappropriately". Re:TFA is shallow hogwash (Score:2) Fred Brooks original silver bullet paper (Score:5, Informative) *sigh* (Score:2) The root problem is people using tools they never bother to even vaguely understand. If you aren't going to bother to understand the technology, ple Re:*sigh* (Score:2) The problem here is that it's very cultural - the manager doesn't want to know the details, and refuses to accept that squirting ink on a piece of paper is not something you can compare developing web applications to - I'm building a site for his other company at the moment, and one of the "specifications" is that all content fo Technoluddite? (Score:5, Insightful) As he snarkily pooh-pooh's the distribution of realtime stock and financial data as a web service, it's probably the latter. I used to work for a company who ran their own ticker plant and had software on the desks of almost every stock broker, investment banker and forex trader on the planet. The client/server requirments of the system were immense. The client had to be maintained on Windows, Sun, Mac and was being slooooowly ported to linux, was fragile as hell and a pain to install and upgrade. The server was a farm of eight midrange Sun or AS/400 boxes, fed by redundant T1's from the ticker plant, and this would only accomodate two or three hundred users. Then we went to a web-based client, sort of like AJAX before people started calling it AJAX, and all the headache went away. It's not a small or trivial thing, and it radically changed the way business was done, and for the better. Just because it's new and has a buzzword doesn't mean it's a flash in the pan. The moral of the story is to use your judgement, and avoid formulas. Even tried-and-true ones. Silver bullets may not exist, but technology doesn't stand still, no matter how many hours you've sunk into learning emacs and gdb. SoupIsGood Food Re:Technoluddite? (Score:5, Insightful) How did "objects and IDEs don't solve every problem" turn into "objects and IDEs have little or no value"? Re:Technoluddite? (Score:2) "Objects and IDEs don't solve every problem" is a self-evident truth "Marketers over-hype things" is also pretty widely understood. So what is he saying that is actually interesting? It would be much more productive to write an article on the appropriate limits of the use of particular technologies than to spew truisms as if they were deep wisdom. Re:Technoluddite? (Score:3, Interesting) Silver Bullet != !(Flash in the Pan). It doesn't look like the essay defines "silver bullet" and I don't have the original in front of me, but a Silver Bullet is a single methodology or technology change that by itself always results in an order-of-magnitude improvement, thus seeming to "slay" previously immortal beasts of problems. Fred Brooks never claimed there wouldn't be improvements, and there have been. But they always seem Software development is a pathological case (Score:5, Insightful) "Hope springs eternal in the human breast" - indeed, in business (and especially sales) optimism is highly thought of, and realism often denounced as "cynicism" or "negative thinking". This is all very well in activities involving human beings, who can easily be manipulated through their emotions. However, it fails utterly when confronted with the cold, hard facts of the physical world. When someone seems to be unrealistically hopeful, we speak of "getting a reality check". In other words, finding our noses hard up against the brick wall of ineluctable, unarguable facts. The problem with most software development projects is that the ultimate decision-makers - those who have the gold and, therefore, make the rules - are very rarely able to get a reality check until the project runs out of time, money, or both. They are hopelessly ill-equipped to make reasoned, educated judgments based on the arguments presented by vendors, analysts, and their own technical staff. So it's hardly surprising that over-optimism tends to creep in. I have been giving talks about software engineering for about 20 years now, and I usually stress the fact that "there are no silver bullets". This warning is always greeted by vigorous nodding, knowledgeable smiles, and sometimes applause. Afterwards, I sadly feel, the people who have just agreed that there are no silver bullets go out into the exhibition hall or open their magazines, and resume... looking for silver bullets. Ultimately, I see just two ways out of this dead end. Either decision-makers take the time, trouble, and mental effort to learn the necessary basics about software development and maintenance. Or they start choosing technical managers and architects who really know their stuff - and trust them implicitly. As time goes by, I hope that both these things will happen more and more. I've been in the business for nigh on 1/4 century (Score:5, Interesting) There is one thing that seems constant: The mix of successful, marginally successful, and just plain failed projects feels the same as ever, even though I'm positively sure that our knowledge of how to create software is much greater than it was. The glass half full aspect of this of course is that the sytems we are developing are far more powerful and complex than what we worked on in the early 80s. Back then many projects were just collections of utility programs that were invoked from the OS command line and ran top to bottom. Structure those programs, and the problem of how to create software is solved, see??? That's why structured programming was the silver bullet of the 70s and early 80s. Now, it's not uncommon for a "lowly" application programmer to have to deal with things like aynchronous processes, something that was the province of the lordly systems programmer back in the day. Ordinary applicaitons are as or more complex today than major systems were back then. The other thing that is constant is that some people get it, some sort of get it, and some don't get it a all. But the common shibboleths of our profession are freely available to all, level of englightment not withstanding. The difference is the lower the level of enlightenment, the more those things take on the role of totems and fetishes. I've been looking at jobs listings recently, and curiously they never seem to be looking for charactersistics that would demonstrate that somebody "gets it". I've seen things like "Must have three to five years of programming with Struts." Now I have nothing against Struts, but I can see nothing about Struts that would indicate you need three years of hard labor to be able to work productively with it. After all, the point of all these frameworks is to make things easier. I can see "must have thre years working with distributed transactional systems", or "must have three years of experience with security on web applications", or "must have three years of experience with designing user interfaces." I'd rather call things like the XML or web services craze "technology fetishes" than "silver bullets". A fetish is "An object that is believed to have magical or spiritual powers, especially such an object associated with animistic or shamanistic religious practices." Religious or technological, fetishes are for some aids on a difficult but rewarding journey, for others they're the promise of relief from hard work, thinking and risk. Re:I've been in the business for nigh on 1/4 centu (Score:3, Insightful) You are right on target. I have confused users with my creations for 2+ decades. I know over 10 languages, have been taught 15 or so, am currently conversant with about 3 (not counting markup constructions like HTML, XML, Heck, when I worked for "HAL" we had a week long course on methodology. If fully implemented with all the requesite documents at each stage, all you would have is a CD full of documents and no product (no time). I agree wit Re:I've been in the business for nigh on 1/4 centu (Score:5, Insightful) Actually, I remember the TQM craze well. However instead of learning about it from the trade rags, I decided to read Kaoru Ishikawa's book, "What Is Total Quality Control?: The Japanese Way". Dr. Ishikawa is the creator of the infamous "fish-bone" diagram. The interesting thing about Ishikawa's book is that if you had to boil it down, it wasn't about tricks that would magically give your products "quality". Oh, there are some chapters on how to understand what customers' real requirements are (thus the fishbone diagram). But they aren't the heart of the book. What the book really is, is a primer on character. And according to the book the bedrock characteristic of a quality producing organization is integrity. It does no good to understand customer requirements if you don't understand your own products and processes; and you will never understand those if you fear the truth and you discourage its spread. So the first thing you need to do is eliminate the culture of fear: fear of failure,mistakes, and plain old bad news. Once fear is eliminated from the organization, useful information begins to flow. In Ishikawa's vision of the quality organiation, fear of the truth is the greatest enemy: victory in competition goes to the organization that discovers and rectifies its faults the quickest. Which is why it is foolish to motivate with praise, particularly undeserved praise. I've never met an engineer worth his salt who really enjoys getting personal praise on more than a occasional basis. The good ones are more motivated with the prospect of becoming better. Praise has its uses; mainly to help maintain a realistically balanced view in the painful process of self improvement. Manufacturing is different than software development. But it is true that the integrity and fear play a huge part in determining software quality. Some day I will write a book: Why Good Engineers Write Bad Software. The number one reason has to be this: not facing reality. This leads to the number two reason: not doing what you know you should be doing. Both of these proceed from fear. A software development organization that eliminates fear eliminates the number one barrier to achieving its potential. In the end, the personal qualities of courage, compassion, and integrity that we bring to our work matter much more than any methodology. Re:I've been in the business for nigh on 1/4 centu (Score:4, Insightful) It is no longer a fetish. How exactly would you phrase that in a job listing? "Only people who 'get it' need apply"? Determining whether somebody does in fact "get it" is clearly best left for interview. For examples, see my original posting. Let me give you an example of why the way job listing are usually written are broken. Suppose you use WebWork in your application. So you say, "Must have three years of experience with WebWork". Now you have three engineers. Engineer A has worked on a WebWork based application for three years, although he has mostly been coding business logic POJOs. Engineer B has five years of Struts experience, and in the last six months has converted an application from Struts to WebWorks in anticipation of WebWork becoming Struts 2. Engineer C has been programming Java MVC applications for the web for ten years. He lead the development of an in house MVC framework in 1998, and has periodically done evaluations of Struts and WebWork, but neither has enough of and advantage to convert from the in house framework. Under the criteria you have the job, only the least qualified candidate is going to get an interview. Splendid stuff! (Score:4, Funny) Silver bullet effect (Score:2, Insightful) It's People (Score:4, Insightful) Silver Bullet Response Template (Score:3, Insightful) If that doesn't work move on to: $BULLET won't help you BECAUSE your programmers are retarded. If that still doesn't have any effect... $BULLET won't help you because your managers are retarded. For BULLET in "Structured programming techinques" "Top down design" "Bottom up design" "Object oriented programming" C++ java XML "six sigma" "agile (or extreme) programming" scrum The old saying (Score:2) Alternatives to silver bullets (Score:3, Funny) 1) Stake thru the heart 2) Garlic worn around the neck 3) Holy water 4) Crucifix 5) Sunlight Two unspoken words: agile and extreme (Score:5, Insightful) Before we start a religious war on whether XP/agile are silver bullets or not, let's step back and ask whether we're talking about different things. I think there is no silver bullet that will kill a software monster created by Big Up Front Design (BUFD). It's a good thing to put serious, deep thought into what must be done before one starts work. You have to do your homework and you have to write down everything you know for certain up front. Trouble happens because after some point up-front design becomes mere speculation. You have to somehow confirm early design decisions made when you're ignorant. In the old days before computers, Engineers built prototypes to do that. Nowadays, Engineeers (or the pointy-haired bosses who lead them) are addicted to the notion of "shipping the prototype." I personally favor the notion of capturing "user stories" because stories have a way of separating "what" from "how" and stories are an effective way to communicate pertinent details between customer and developer while skipping over one's ignorance. A trouble with BUFD is that it becomes a "proclamation" about software from the developer (or customer, depending upon the power-relationship). If we were gods, that would not be a problem, but we have limited knowledge and we have sort our our ignorance. But we're not and I think a "conversation" between the two is a more effective way to sort out what's wanted and what's possible. In a "conversation" the software monster never grows so big that the ammunition in our clip (UML, agile/xp methods, high-level languages, today's microsoft buzzword) can't kill it. Inability to deal with complexity (Score:3, Informative) Hence the common practice (in some countries) of selling impossible deadlines to customers and then using overwork to (try and) achieve those deadlines (via the "tired developers make more bugs" and the "low morale" negative feedback loops, overwork usually leads to LONGER development times and a longer tail of bugfixing before the software is accepted for production). The same theory would also help explain the recurring reliance by some managers on the next "silver bullet" to solve all our problems - silver bullets are always sold as solving everything and having no downsides (thus no tradeoffs) and no side-effects (and thus no negative feedback loops). Don't forget "Meta" Silver Bullets !!! (Score:3, Insightful) Solutions vs Tools (Score:3, Insightful) I think a lot of this comes down to the 'solutions mindset' vs the 'tools mindset'. A 'Solution' is self-contained, operates itself, and requires little thought. A 'Tool', on the other hand, requires a wielder (or operator), may need other tools to be effective, and requires thought and skill to use. The problem is that computer technology, by and large, is much more a tool than it is a solution, while management tends to gravitate towards 'solutions'. Most 'silver bullets' are in fact useful tools, if treated as such. When treated as a solution, they always come up short, because no tool, by itself, is a full-blown solution. The result is that management ends up using and discarding one silver bullet after another, rather than concentrating on gathering a useful set of tools and a group of people capable of using them skillfully. Re:Bullets? (Score:2, Insightful) At least XML works. Instead of technologies, I'd be much more critical of development techniques that are pitched as silver bullets, like Extreme Programming. Remember that? All the rage a few years ago, with even level-headed publishers like O'Reilly getting in on the action --they even released a pocket guide [amazon.com], come on, what is this, devotion on the level of Mao's little red book? -- it was supposed to solve bottlenecks in development and result in cleaner, more easily maintainable code. Instead, all it di Re:Bullets? (Score:5, Insightful) XML works? Huh? XML is a data representation. It works? How does it work? By representing data? What else could work? S-Expressions? SGML? ASN.1? Flat text file? The data representation isn't solving the problem. XML, Extreme Programming, technique / technology of the week all are trying to do the same thing: help us manage complexity. Fred Brooks had a lot to say there. My favorite quote from the 'No Silver Bullet' essay: Re:Bullets? (Score:5, Insightful) That works, until you notice that it's not as easy as it seems. How do you represent arrays of data, or trees?? I've seen all sorts of horrible tricks to deal with those problems, like "key=value" where the value is encoded in hex or base64. XML is nice for that: The designers thought of all that already, designed it to be able to deal with all of them, and made parsers that work. Re:Bullets? (Score:3, Interesting) XML says little of the semantics. This isn't evil in and of itself. The way it was marketed as a silver bullet, even though the semantic holes|canyons|abysses stretch wide, explains the backlash. What's good about XML, and I used to go to some government working groups about it, is that by calling everything "human readable text", there was much participation from people who otherwise wouldn't budge. The bad news, in the government case, is that homo bureaucratus realiz Re:Bullets? (Score:5, Insightful) I think you've essentially hit the nail on the head there. XML is excellent at what it does. However what it does is not "everything", and the "silver bullet" marketing (Java + XML = "Enterprise"!) surrounding it causes people to get upset, because that's not what it is. Marketing is, in general, really good at turning people against perfectly good technologies, because those in the know will always see through the lies, exaggerations and half-truths, but will then have a hard time conveying these to superiors or other colleagues who have had a little less experience and a glossy leaflet to gaze on. Re:Bullets? (Score:2) "Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp." Using XML as a programming language is the prime example of this. It is basically lisp with a different (but vastly more verbose) syntax and the more advanced concepts removed. Re:Bullets? (Score:2) Well, yes, XML is a data interchange format more than anything. On the other hand, it can be a useful representation of (simple) logical structures, which could be considered almost "progamming in XML". But no, in general, that's neither what it's for nor something it is useful for. Re:Bullets? (Score:2) Yeah, that's kinda a problem with the complexity of the subject. People just buy what's best presented ("ooh, that's shiny!") because they're often completely incapable of purchasing things on the merits of the presented systems. This is something I've encountered a lot myself, and I've only actually been in this in Re:Bullets? (Score:2, Insightful)? Observe that all these things are problems that only arise if you have humans generating the data. If a program generates it, then you n Re:Bullets? (Score:2, Insightful) Ah Ha! My chance to get modded into oblivion by those who don't know anything! XML is a tagging system. It may be useful for the transmission of data between dissimilar systems but even there it is a crappy methodology. It bloats the data with massive tags, if you parse it in anything but a linear fashion, it becomes a recursive method to make processes take forever and isn't worth anything more than a flat file with a table at the top to tell you where things are. XML only handles ASCII and doesn't do t Re:Bullets? (Score:3, Interesting) coming from an other world, where 2400 baud modems were a luxory, I always get bothered while dealing with XML, and seeing that in most transactions, over 50% is the tags. Then people deal with the magic SOAP transactions, where they send 90%+ tags, and 2-3 short strings as the actual data On the other hand, implement a payment processing using a. SOAP requests b. some proprietary crap than you will thank God for XML I also have to mention that while XML seems like a bandwidth hog, there is Re:Bullets? (Score:3, Informative) Here you have a bit of code that ver Re:Bullets? (Score:3, Interesting) Your "~~~" idea doesn't even come close to solving the problem. It still won't help with new Re:Bullets? (Score:2) Re:Bullets? (Score:2) Re:Bullets? (Score:5, Interesting) For him, XML was sort of a religion. The ultimate "technology" (we were not talking about all the technos that comes with XML like XSLT, Talking about XML as a "tool" was a blasphemy. I "learned" that the savior XML: - Saved us from the interoperability problem by allowing us to transfer data from and to any system transparently. Sure, you only have to transform the output of one application into the input of the second system. - Reduce coding problem ( using for example, the function "XML DoSomething(XML params)", so you can change the params without changing the interface and the doc (duh!) ) - Reduce database problem ( storing XML as blob in the DB - no need to call the DBA when you change the data format ) - Solve configuration problem ( now configuration file are in XML that means it is easy to understand ) Thanks XML. Re:Bullets? (Score:3, Informative) Here are three choices I've gotten to work: JSON [json.org] XML CSV Have you ever seen nested CSV files? They're truely bizzare to see, but if you have a sufficiently powerful parser, they can be read. New Line characters are to be record separators only when they are fully outside of quotes. Commas are to be used as field separators, only when they are fully outside of quotes. Quotes are to be used as content descriminators only when not doubled up. The closest thing to a CSV spec t [shaftek.org] Re:Bullets? (Score:5, Insightful) Re:Bullets? (Score:3, Funny) Re:Bullets? (Score:2) Yes, if those are just slimy fucking walrus-looking pieces of shit Re:Bullets? (Score:2) Re:Bullets? (Score:3, Insightful) By using XML instead of something simpler, the size of each network message being passed is increased tremendously, and the amount of processing required to create and decode the message is increase considerably compared to a simpler format. Yes, the size can be decreased via compression, b More than just XML (Score:2) Re:strangly this whole thing (Score:2) Fortunately, /. has non-validating moderators. Re:Current silver bullets (Score:3, Informative)
https://slashdot.org/story/06/07/26/0356237/the-whiz-of-silver-bullets
CC-MAIN-2018-13
refinedweb
6,218
62.38
Last updated 5 September 2008. The most recent version of this tutorial is at. Table of Contents:. If you only want access to Python's normal AST, which includes line numbers and byte position for the code fragements, you should use the _ast module. Back long time ago I had a class assignment to develop a GUI interface using drawpoint and drawtext primitives only. Everything - buttons, text displays, even the mouse pointer itself - was built on those primitives. It gave the strange feeling of knowing that GUIs are completely and utterly fake. There's no there there, and it's only through a lot of effort that it feels real. Those that aren't as old and grizzled as I am might get the same feeling with modern web GUIs. Those fancy sliders and cool UI effects are built on divs and spans and CSS and a lot of hard work. They aren't really there. This package gives you the same feeling about Python. It contains a Python grammar definition for the PLY parser. The file python_lex.py is the tokenizer, along with some code to synthesize the INDENT, DEDENT and ENDMARKER tags. The file python_yacc.py is the parser. The result is an AST compatible with that from the compiler module, which you can use to generate Python byte code (".pyc" files). There's also a python_grammer.py file which makes a nearly useless concrete syntax tree. This parser was created by grammar_to_ply.py, which converts the Python "Grammar" definition into a form that PLY can more easily understand. I keep it around to make sure that the rules in python_yacc.py stay correct. You might also find it useful if you want to port the grammar directly to yacc or some similar parser system. What this means is this package gives you, if you put work into it, the ability to create a Python variant that works on the Python VM, or if you put a lot of work into it (like the Jython, PyPy, and IronPython developers), a first step into making your own Python implementation. If you think this sounds like a great idea, you're probably wrong. Down this path lies madness. Making a new language isn't just a matter of adding a new feature. The parts go together in subtle ways, and if you tweak the language and someone else tweaks the language a different way, then you quickly stop being able to talk to each other. Lisp programmers are probably thinking now that this is just a half-formed macro system for Python. They are right. Once you have an AST you can manipulate it in all sorts of ways. But many experienced Lisp programmers will caution against the siren call of macros. Don't make a new language unless you know what dangerous waters you can get into. On the other hand, it's a lot fun. Someone has to make the new cool langauge for the future so you've got to practice somewhere. And there are a few times when changing things at the AST or code generation levels might make good sense. Steve Yegge is right when he wrote "When you write a compiler, you lose your innocence." I'll start with the simple thing, to make sure everything works. Create the file "owe_me.py" with the following: # owe_me.py amount = 10000000 print "You owe me", amount, "dollars"To bytecompile it use the provided "compile.py" file. This is similar to "py_compile.py" from the standard library. % python compile.py owe_me.py Compiling 'owe_me.py' % ls -l owe_me.pyc -rw-r--r-- 1 dalke staff 165 Feb 17 19:21 owe_me.pyc %Running this is a bit tricky because the .pyc file is only used when the file is imported as a module. The easiest way around that is to import the module via a comment-line call. % python -c 'import owe_me' You owe me 10000000 dollars %(I thought it would be best to use the '-m' option but that seems to import the .py file before the .pyc file. Hmm, I should check into that some more.) If you want to prove that it's using the .pyc generated by this "compile.py", try renaming the file % rm owe_me.pyc % python compile.py owe_me.py Compiling 'owe_me.py' % mv owe_me.pyc you_owe_me.pyc % python -c 'import you_owe_me' You owe me 10000000 dollars %The compile module also supports a '-e' mode, which executes the file after byte compiling it, instead of saving the byte compiled form to a file. % python compile.py -e owe_me.py You owe me 10000000 dollars % Reading "10000000" is tricky, at least for humans. Is that 1 million or 10 million? You might be envious of Perl, which supports using "_" as a separator in a number % perl $amount = 10_000_000; print "You owe me $amount\n"; ^D You owe me 10000000 % You can change the python4ply grammar to support that. The tokenization pattern for base-10 numbers is in python_lex.py in the function "t_DEC_NUMBER": def t_DEC_NUMBER(t): r'[1-9][0-9]*[lL]?' t.type = "NUMBER" value = t.value if value[-1] in "lL": value = value[:-1] f = long else: f = int t.value = (f(value, 10), t.value) return t Why do I return the 2-tuple of (integer value, original string) in t.value? The python_yacc.py code contains commented out code where I'm experimenting with keeping track of the start and end character positions for each token and expression. PLY by default only tracks the start position, so I use the string length to get the end position. I'm also theorizing that it will prove useful for those doing round-trip conversions and want to keep the number in its original presentation. Okay, so change the pattern to allow "_" as a character after the first digit, like this: r'[1-9][0-9_]*[lL]?'then modify the action to remove the underscore character. The new definition is: def t_DEC_NUMBER(t): r"[1-9][0-9_]*[lL]?" t.type = "NUMBER" value = t.value.replace("_", "") if value[-1] in "lL": value = value[:-1] f = long else: f = int t.value = (f(value, 10), t.value) return t To see if it worked I changed owe_me.py to use underscores, and I changed the value to prove that I'm using the new file instead of some copy of the old # owe_me.py amount = 20_000_000 print "You owe me", amount, "dollars" % python compile.py -e owe_me.py You owe me 20000000 dollars % Python 3.0 will introduce a way to represent numbers in binary using the prefix "0b" or "0B", just like hex numbers now can be expressed with a leading "0x" or "0X". For example, "0b1100" will be 12. This is purely a lexer change and is easy to add to python4ply. It's not quite trivially easy. The token starts with a "0" which will match the octal pattern for numbers, and then "b1100" will match the pattern for variable names. That is, >>> import tokenize >>> tokenize.tokenize(StringIO.StringIO("0b1100").readline) 1,0-1,1: NUMBER '0' 1,1-1,6: NAME 'b1100' 2,0-2,0: ENDMARKER '' >>> In PLY the token patterns are tested in the order they occur in the lexer file, which is python_lex.py. (It's a bit more complex; read the documentation for details.) The solution is to put the new binary token definition before the octal definition. def t_BIN_NUMBER(t): r"0[bB][01_]+" t.type = "NUMBER" value = t.value[2:].replace("_", "") # Treat values like '0b__' as an error if not value: raise_syntax_error("base-2 number must contain a digit", t) t.value = (int(value, 2), t.value) return t def t_OCT_NUMBER(t): r"0[0-7]*[lL]?" t.type = "NUMBER" ...I think the code is pretty obvious but I wrote the thing so I'm biased. You can see I support and ignore any "_" characters in the number. Binary numbers are long and it quickly gets hard to read and having the "_" helps with grouping. Save that, tweak the "owe_me.py" so it uses a binary number, and use a slightly different number to help verify that the code you're going to run is the code you think you're going to run. # owe_me.py amount = 0b1_0011_0001_0010_1101_0000_0001 print "You owe me", amount, "dollars"And ... % python compile.py -e owe_me.py You owe me 20000001 dollars %it works! Homework assignment: Ned Batchelder blogged about __FILE__ and __LINE__ in Python by looking at the stack trace. Modify python4ply so those variable name tokens are true literals; literally the string name and the integer number.("0.0") >> % Only a dozen or so lines of code to add syntax-level support for a decimal type, and the generated bytecode is compatible with existing Python byte code. % python compile.py div.py Compiling 'div.py' % python Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import div float 0.1 decimal 0.0 >>> If you've read this far then you're probably also thinking "this is really cool! I can add X and Y and Z to my Python code and life would be so much better." Mark my words young Jedi - this is the path to the dark side. On the other hand, what does not kill you make you strong. And I like traffic lights, but only when they're green. Kidding aside, it is really cool, but bear in mind the many problems of making any new language like less tool support, few people using it, higher support costs, and subtle interaction errors between features. If you deploy this internally for other developers you'll probably waste days or weeks of work as people run the wrong Python on a piece of code. Regular expressions are fun. The first contact I had with them was through DOS globbing, where "*.*" matched all files with an extension. Then I started using Unix, and started using Archie, which supported regular expressions. Hmm, that was in 1990. I read the documentation for regexps but I didn't understand them. Instead I mentally translated the glob "?" to "." and the glob "*" to ".*". Luckily for me I was in college and I took a theory of automata course. I loved that course. It taught me a lot about how to think about computers as what they are - glorified state machines. Other programmers also really like regular expressions, and languages like Perl, Ruby, and Javascript consider them so important that are given syntax level support. Python is not one of those languages, and someone coming from Ruby, where you can do # lines.rb File.open("python_yacc.py").each do |line| if line =~ /def (\w+)/ puts "#{$1}\n" end endwill probably find the corresponding Python both tedious and (because of the separation between the pattern definition and use) harder to read: # lines.py import re pattern = re.compile(r"def (\w+)") for line in open("python_yacc.py"): m = pattern.match(line) if m is not None: print m.group(1)This code is generally considered the best practice for Python. It could be made a bit shorter by using re.match instead of the precompiled pattern, but at the cost of some performance. The original regular expression library in Python was called 'regex'. It was based on Emacs regular expressions and made obsolete with Python 1.5. It was replaced by the 're' module (in various incarnations) with perl5-compatible syntax. One advantage in Python not having special syntax for regular expressions was the ability to change regular expression libaries gracefully. On the other hand, over the last about 15 years the Perl5 regular expression syntax has pretty much become the dominate regular expression syntax. I don't think there's a need to make major changes now. I'll give Perl5 regular expressions (as implemented by the 're' module) first-class syntax support for creating patterns. That will shorten the code by getting rid of the "import re" and the "re.compile()" call. Here's how I want the pattern creation to look like pattern = m/def (\w+)/This new syntax is vaguely modelled after Perl's. It must start with a "m/" and end with a "/" on the same line. I do not allow any "/" characters inside the pattern. If you need it, use the octal escape \057 or figure out and implement your own escape mechanism. Note that my new syntax might break existing code because m=12 a=3 i=2 print m/a/iis already valid. The first step is to add a new token name and definition to "python_lex.py". Here I've removed the DECIMAL token I talked about earlier. You don't need to, but I figure it's less confusing for those starting with a fresh install. tokens = tuple(python_tokens.tokens) + ( "NEWLINE", "NUMBER", "PATTERN", # The new token type name "NAME", "WS", ... The new token definition goes before the t_NAME definition, to prevent the NAME from matching first. This token returns a 2-ple of the regular expression pattern as a string, and the flags to pass to re.compile. I need to pass it back as basic types and not a pattern object because the bytecode generation only understands the basic Python types. import re _re_flags = { "i": re.IGNORECASE, "l": re.LOCALE, "m": re.MULTILINE, "s": re.DOTALL, #"x": re.VERBOSE, # not useful in this context "u": re.UNICODE, } def t_PATTERN(t): r"m/[^/]*/[a-z]*" m, pattern, opts = t.value.split("/") flags = 0 for c in opts: flag = _re_flags.get(c, None) if flag is None: # I could pin this down to the specific character position raise_syntax_error( "unsupported pattern modifier %r" % (c,), t) flags |= flag # test compile to make sure that it's a valid pattern try: re.compile(pattern, flags) except re.error, err: # Sadly, re.error doesn't include the error position raise_syntax_error(err.message, t) t.value = (pattern, flags) return t # This goes after the strings otherwise r"" is seen as the NAME("r") def t_NAME(t): r"[a-zA-Z_][a-zA-Z0-9_]*" t.type = RESERVED.get(t.value, "NAME") return t This PATTERN will be a new "atom" at the grammar level, which will correspond to a call to re.compile("pattern", options). The AST needs to look like >>> from compiler import parse >>> parse("compile('pattern', 10)") Module(None, Stmt([Discard(CallFunc(Name('compile'), [Const('pattern'), Const(10)], None, None))])) >>> The python_yacc.py by default contains 11 p_atom_* patterns. I used p_atom_12 for the earlier DECIMAL support so to prevent accidental confusion I'll label this as p_atom_13. The name doesn't make much difference so long as it starts with "p_" and is different from the other function names. def p_atom_13(p): 'atom : PATTERN' pattern, flags = p[1] p[0] = ast.CallFunc(ast.Name("_$re_compile"), [ast.Const(pattern), ast.Const(flags)]) locate(p[0], p.lineno(1)) See how I'm using the impossible variable name '_$re_compile'? That's going to be "re.compile" and I'll use the same trick I did with the DECIMAL support and insert the AST corresponding to from re import compile as _$compileat the start of the module definition,("re", [("compile", "_$re_compile")], 0)) p[0] = ast.Module(docstring, stmt) locate(p[0], 1)#, (None, None)) I'll test this with a simple program # pattern_test.py data = "name: Andrew Dalke country: Kingdom of Sweden " pattern = m/Name: *(\w.*?) *Country: *(\w.*?) *$/i m = pattern.match(data) if m: print repr(m.group(1)), "lives in", repr(m.group(2)) else: print "unknown" % python compile.py -e pattern_test.py 'Andrew Dalke' lives in 'Kingdom of Sweden' %and to see that it generates byte code % python compile.py pattern_test.py Compiling 'pattern_test.py' % rm pattern_test.py % python -c 'import pattern_test' 'Andrew Dalke' lives in 'Kingdom of Sweden' % Go ahead. See what happens when you give it a bad pattern or an unknown modifier flag. If you actually use this, or think about what's going on, you'll see there's going to be a usability problem. (Usability is hard. Writing new languages is easy. Writing usable new languages is .. well, you get the point.) What's the problem? People will write patterns like: # m/(ATOM |HETATM)/.match(line): count += 1 print count, "atoms in", time.time()-t1, "seconds" BTW, this shows my history in molecular modeling. A "PDB" file describes the position of atoms in a molecule, amoung other things. This file contains the histone octamer along with some DNA double helix wrapped around it. But that's not important right now. When I run that program I get timing values like % python compile.py -e count_atoms.py 11843 atoms in 0.04518699646 seconds % This main loop calls re.compile("(ATOM |HETATM)") for each line, instead of computing it once outside the loop. Translating the code into normal Python it looks like from re import compile as re_compile for line in open("nucleosome.pdb"): if re_compile("(ATOM |HETATM)").match(line): count += 1This means re.compile is called for every line in the file. The re module does cache the most recent patterns so it's not all that bad, but it takes time to check that cache. On the other hand, in my Python variant with a special pattern symbol I know that the pattern cannot be changed. It could be created once during module import and reused. That corresponds to from re import compile as re_compile pattern = re_compile("(ATOM |HETATM)") for line in open("nucleosome.pdb"): if pattern.match(line): count += 1 There are many ways to implement this. I'll describe just one. When I build the AST I'll create and use a new variable name for each and remember the name and its two parameters. Then at the very end when I'm making the module I'll add all of the re.compile definitions to the top-level of the module. When I imported decimal.Decimal and assigned it to the variable name "_$Decimal" I chose the name manually. After all, I only needed one name and I knew there weren't going to be conflicts. In this case I'll need an indefinite number of new names; one for each pattern. This is traditionally done through a function named "gensym" for "generate new symbol"; and who am I to break with tradition? import itertools counter = itertools.count() def gensym(prefix="gensym-"): return prefix + str(counter.next()) >>> gensym() 'gensym-0' >>> gensym() 'gensym-1' >>> gensym("hello") 'hello2' >>> gensym("_$re") '_$re3' >>> I'll need a place to store the data. The PLY way seems to be to store that in the lexer or the parser instance, which makes it single threaded. Well, unless you use a threading.local(). Anyhoo, here I'll store the data in the parser as a "patterns" list. This will have 3-tuples of (variable name, pattern, flags). def parse(source, filename="<string>"): # There is a bug in PLY 2.3; it doesn't like the empty string. # Bug reported and will be fixed for 2.4. # if not source: source = "\n" lexer = python_lex.lexer parser.patterns = [] # info for new pattern definition goes here try: parse_tree = parser.parse(source, lexer=lexer) except SyntaxError, err: ... The atom rule for "PATTERN" is easier. I reach into the parser object and append the 3-tuple, and the AST node only does a Name lookup of the new symbol. def p_atom_13(p): 'atom : PATTERN' sym = gensym("_$re-") pattern, flags = p[1] p.parser.patterns.append( (sym, pattern, flags) ) p[0] = ast.Name(sym) locate(p[0], p.lineno(1)) Finally, I need to change the "p_file_input_2" so if there are any pattern objects then I import the re.compile function and create the pattern definitions. Here's what the underlying AST will look like >>> from compiler import parse >>> parse("x = re_compile('pattern', 8)") Module(None, Stmt([Assign([AssName('x', 'OP_ASSIGN')], CallFunc(Name('re_compile'), [Const('pattern'), Const(8)], None, None))])) >>>and here's the new function def p_file_input_2(p): "file_input : file_input_star ENDMARKER" stmt = ast.Stmt(p[1]) locate(stmt, p[1][0].lineno)#, bounds(p[1][0], p[1][-1])) docstring, stmt = extract_docstring(stmt) # If there are any syntax-level defined patterns if p.parser.patterns: # from re import compile as _$re_compile new_nodes = [ast.From("re", [("compile", "_$re_compile")], 0)] for (sym, pattern, flags) in p.parser.patterns: # symbol = _$re_compile(pattern, flags) node = ast.Assign( [ast.AssName(sym, 'OP_ASSIGN')], ast.CallFunc(ast.Name('_$re_compile'), [ast.Const(pattern), ast.Const(flags)], None, None)) new_nodes.append(node) stmt.nodes[:0] = new_nodes p[0] = ast.Module(docstring, stmt) locate(p[0], 1)#, (None, None)) % python compile.py -e count_atoms.py 11843 atoms in 0.0161190032959 seconds %The time went from 0.045 to 0.016 seconds, which is 64% faster. (That's 1/2.8, which I find easier to understand.) The Perl runtime is optimized for that language and likely implements other ways to make this type of pattern matching fast. For example, I stored the patterns as variables in the normal module namespace, though in a way that does not override normal Python variables. Module lookup is a dictionary lookup but since the patterns won't change one optimization is to have a special patterns list and look up the patterns by index. By the way, the above precomputed-pattern code has a subtle error. The following would be legal according to the Python grammar m/a/ = 9because the m/a/ gets turned into a Python NAME, which is allowed on the left-hand-side of the assignment, which gets turned into an assignment via the function expr_to_assign. It should not be possible to assign to the pattern name. That's easy to fix. The conversion between a normal expression and an assignment expression is in "expr_to_assign". I'll have it raise an exception if an ast.Name node contains the name that used for a special pattern def expr_to_assign(term): if isinstance(term, ast.Name): x = ast.AssName(term.name, 'OP_ASSIGN') if term.name == "None": raise_syntax_error("assignment to None", term) elif term.name.startswith("_$re"): raise_syntax_error("cannot assign to a regular expression", term) locate(x, term.lineno)#, term.span) return x elif isinstance(term, ast.Tuple): ... These changes make it easier to define a pattern, but not to use it. As another example of (fake?) Perl envy. I'm going to support its "=~" match syntax so that the following is valid: # line =~ m/(ATOM |HETATM)/: count += 1 print count, "atoms in", time.time()-t1, "seconds" This turned out to be very simple. I need a new token for "=~". Most of the simple tokens are defined in "python_tokens.py". I added "EQUALMATCH" in the list of tokens in the place shown here ... PERCENTEQUAL %= AMPEREQUAL &= CIRCUMFLEXEQUAL ^= EQUALMATCH =~ COLON : COMMA , ... Note that this will break legal existing code, like >>> a=~2 >>> a -3 >>>The lexer doesn't need anything else because I've already defined a PATTERN token. I need to decide the precedence level of =~. Is it as strong as "**" or as weak as "or", or some place in between? I decided to make it as weak as "or", which is defined by the "test" definition. Here's my new "p_test_4" function: def p_test_4(p): 'test : or_test EQUALMATCH PATTERN' # pattern.search(or_test) sym = gensym("_$re-") pattern, flags = p[3] p.parser.patterns.append((sym, pattern, flags)) p[0] = ast.Compare( ast.CallFunc(ast.Getattr(ast.Name(sym), 'search'), [p[1]], None, None), [("is not", ast.Name("None"))]) locate(p[0], p.lineno(2)) I got the AST definition by looking at >>> from compiler import parse >>> parse("pat.search(line) is not None") Module(None, Stmt([Discard(Compare(CallFunc(Getattr(Name('pat'), 'search'), [Name('line')], None, None), [('is not', Name('None'))]))])) >>> And that's it! Well, I could add an optimization in this case and move the ".search" outside the loop, but that's an exercise left for the student. Now I'll put a toe into evil, just to see how cold it is. I'm going to add support for # get_function_names.py for line in open("python_yacc.py"): if line =~ m/def (\w+)/: print repr($1)That is, if the =~ matches then $1, $2, ... will match group 1, 2. Oh, and while I'm at it, if there's a named group then $name will retrieve it. And '$' will mean to get the match object itself. To make it work I need some way to do assignment in the expression. Python doesn't really support that, except for a hack around how variables leak inside list comprehensions. >>> y = 5 >>> if [x for x in [y]][0] == 5: ... print "y is 5" ... y is 5 >>> x 5 >>>That's an ugly, complicated hack and I don't want to use it. Instead I created a new AST node called "AssignExpr" which is like an "Assign" node except that it can be used in an expression. The compiler module doesn't know about it and it's hard to change the code through subclassing, so I patch the compiler and its bytecode generation code so it understands the new node type. These changes are in "compiler_patches.py" and the patches are done when the module is imported. Take a look at the module if you want to see what it does. It doesn't escape my notice that with AssignExpr there's only a handful of lines needed for support assignment in an expression, like if line = readline(): print repr(line)Before you do that yourself, read the Python FAQ for why Python doesn't support this. To support the new pattern match syntax I need to make two changes to python_yacc.py. The first is to import the monkeypatch module: import compiler_patchesthen make the changes to the p_test_4 function to save the match object to the variable "$". def p_test_4(p): 'test : or_test EQUALMATCH PATTERN' # pattern.search(or_test) sym = gensym("_$re-") pattern, flags = p[3] p.parser.patterns.append((sym, pattern, flags)) p[0] = ast.Compare( ast.AssignExpr([ast.AssName("$", "OP_ASSIGN")], ast.CallFunc(ast.Getattr(ast.Name(sym), 'search'), [p[1]], None, None)), [("is not", ast.Name("None"))]) locate(p[0], p.lineno(2)) Does it work? Try this program, which is based on the Ruby code I started with at the start of this tutorial section, oh so long ago. # get_function_names.py for line in open("python_yacc.py"): if line =~ m/def (\w+)/: # I don't yet have syntax support to get to the special '$' # variable so I have to get it from the globals dictionary. print repr(globals()["$"].group(1)) % python compile.py -e get_function_names.py 'gensym' 'raise_syntax_error' 'locate' 'bounds' 'text_bounds' 'extract_docstring' '__init__' '__init__' 'add_arg' 'add_star_arg' 'p_file_input_1' 'p_file_input_2' 'p_file_input_star_1' 'p_file_input_star_2' 'p_file_input_star_3' ... Sweet! def t_MATCH(t): r"\$[0-9a-zA-Z_]*" # This can be "$" or "$1" or "$name" value = t.value if value == "$": # Get the object itself t.value = None else: name = value[1:] if name.isdigit(): # Lookup by number t.value = int(name, 10) else: # Lookup by name t.value = name return tDon't forget to add "MATCH" to the list of token names! Here's the only change to the python_yacc.py file def p_atom_14(p): 'atom : MATCH' m = p[1] if m is None: p[0] = ast.Name("$") else: p[0] = ast.CallFunc(ast.Getattr(ast.Name("$"), "group"), [ast.Const(m)], None, None) Does it work? # get_function_names.py for line in open("python_yacc.py"): if line =~ m/def (?P<name>\w+)/: print repr($1), repr($name) % python compile.py -e get_function_names.py 'gensym' 'gensym' 'raise_syntax_error' 'raise_syntax_error' 'locate' 'locate' 'bounds' 'bounds' 'text_bounds' 'text_bounds' 'extract_docstring' 'extract_docstring' '__init__' '__init__' '__init__' '__init__' 'add_arg' 'add_arg' 'add_star_arg' 'add_star_arg' ...or the bit more complicated variation to show that $name also works, although it assumes the formal parameter list fits on one line: # get_function_names.py for line in open("python_yacc.py"): if line =~ m/def (?P<name>\w+) *(?P<args>\(.*\)) *:/: print repr($1), repr($args) % python compile.py -e get_function_names.py 'gensym' '(prefix="gensym-")' 'raise_syntax_error' '(message, node=None, lineno=None)' 'locate' '(node, lineno):#, (span_start, span_end))' 'bounds' '(x, y)' 'text_bounds' '(p, arg1, arg2=None)' 'extract_docstring' '(stmt)' '__init__' '(self, argnames, defaults, flags)' '__init__' '(self, args=None, star_args=None, dstar_args=None)' 'add_arg' '(self, arg)' 'add_star_arg' '(self, star_args, dstar_args)' .. I'm going to leave the ability to assign to '$'. In this case it seems useful to be able to reset '$' or assign it to some other match object. But then again assigning to '$' then using '$1' assumes that the assigned object has a .group(1). See how hard it is to catch all the nuances in making even a simple change to a language? Speaking of simple changes, adding support for variable names with terminal "?" and "!" also seems simple. It's mostly a matter of changing the t_NAME definition and the PVM handles it without a problem, but parts of the standard library and third-party code won't know about the new variable name syntax, so you'll end up with small breakage. What's wrong with the following made-up example? assert 0 not in results, "problem in: %r" % dataMost likely the variable name "data" was changed to the slightly better "results" but not changed everywhere. If this case is truly impossible then the unittests can't ever get to the diagnostic statement and it's very hard to check. But perhaps there is a way, and in that case the raised exception will be NameError: name 'data' is not definedand not an AssertionError. If you want to check that the failure side of the assert always works then one solution is to rewrite the AST so that the failure is always created, then stored to a temporary variable and used if the test fails. That is, to rewrite the AST so that assert X, Ybecomes something like _$assert = Y assert X, _$assert It's not hard, but a bit harder than it should be. That assert statement is handled by p_assert_stmt_2 def p_assert_stmt_2(p): 'assert_stmt : ASSERT test COMMA test' node = ast.Assert(p[2], p[4]) locate(node, p.lineno(1))#, bounds(text_bounds(p, 1), p[4])) p[0] = [node] The easiest solution is to have it return two statement lines def p_assert_stmt_2(p): 'assert_stmt : ASSERT test COMMA test' assign = ast.Assign([ast.AssName("_$assert", "OP_ASSIGN")], p[4]) assert_ = ast.Assert(p[2], p[4]) locate(assign, p.lineno(1)) locate(assert_, p.lineno(1)) p[0] = [assign, assert_] (I'll draw back the covers a bit - the reason is this is easy is because I modified the code while writing this to make it easier. Before the change it assumed that each statement corresponded to one and only node in the AST.) I'll try it out with this simple program # assert.py assert 1, s % python assert.py % python compile.py -e assert.py Traceback (most recent call last): File "compile.py", line 76, in <module> execfile(args[0]) File "compile.py", line 48, in execfile exec code in mod.__dict__ File "assert.py", line 1, in <module> assert 1, s NameError: name 's' is not defined % This transformation of the Python code does have some performance impact because it's always doing extra code, and the new code doesn't obey the "-O" setting to disable assert statement. There's also going to be some cases where the fail code can't properly be executed unless the test condition fails. I can imagine embedded directives that enable or disable certain features, perhaps through special tags in the comments or new token types. None stand out as being obvious and without a good driving example I won't show how. If you're going to try something out, remember that the tokenizer can easily be changed to store each comment and its line number. What about code and branch coverage? There are already some tools for code coverage, most notably Ned Batchelder's "coverage". That page links to a few other tools. They generally work by using the Python standard library to parse Python and find line numbers for executable code, then use the sys.settrace hook to get runtime callbacks with information about which lines are being executed. There are limitations with this approach, nicely listed at I have control over the entire AST and even some of the byte code generation so there are tricks I can do that they can't. I can instrument every piece of executable code to report the line number, instead of calling settrace. I'll start with the basics and call the function def trace(lineno): print "line", linenobefore executing any new statement. All statements are listed in an ast.Stmt node so this should be easy but there are a couple of complications that make it hard to generate these calls while building the AST. I can't add code before the docstring because the bit of code which extracts the docstring (called "extract_docstring") gets it from the first statement, if it's of the correct form. Inserting the trace call means the first statement will always be a trace. I also can't add trace calls before "from __future__ import" calls, which must occur before any other code. While I could make it work while building the AST, it was easier to create the AST as-is then transform it to include the trace calls. def parse(source, filename="<string>"): # There is a bug in PLY 2.3; it doesn't like the empty string. # Bug reported and will be fixed for 2.4. # if not source: source = "\n" lexer = python_lex.lexer try: parse_tree = parser.parse(source, lexer=lexer) except SyntaxError, err: # Insert the missing data and reraise assert hasattr(err, "lineno"), "SytaxError is missing lineno" geek_lineno = err.lineno - 1 start_of_line = lexer.lexer.line_offsets[geek_lineno] end_of_line = lexer.lexer.line_offsets[geek_lineno+1]-1 text = source[start_of_line:end_of_line] err.filename = filename err.text = text raise add_trace(parse_tree.node, 1) misc.set_filename(filename, parse_tree) syntax.check(parse_tree) return parse_tree The new add_trace function is a recursive function that takes two parameters: an ast node (for simplicity the top-level one must be the module's ast.Stmt node) and the flag "is_module" which is True if the node is the top-level ast.Stmt). The top-level ast.Stmt is important because it's the one which contains the "from __future__" statements.' function # def trace(lineno): # print "line", lineno def_node = ast.Function( None, 'trace', ['lineno'], [], 0, None, ast.Stmt([ast.Printnl([ast.Const('line'), ast.Name('lineno')], None)])) new_nodes.append(def_node)) There's nothing particularly hard about the code and I think the comments suffice. It calls the "after_import_future" helper function which finds the index after the last "from __future__ ..." statement. def after_import_future(nodes): for i, node in enumerate(nodes): if not (isinstance(node, ast.From) and node.modname == "__future__"): return i else: # all elements are 'from __future__ import ..' statements return len(nodes) return 0 # empty listAnd again, that's it. What to see it work? I figured you would. Here's an implementation of the popular "fizzbuzz" program # fizzbuzz.py for i in range(1, 10): if i % 15 == 0: print i, "fizzbuzz" elif i % 5 == 0: print i, "buzz" elif i % 3 == 0: print i, "fizz" else: print iand its output % python compile.py -e fizzbuzz.py line 2 line 3 line 10 1 line 3 line 10 2 line 3 line 8 3 fizz line 3 line 10 4 line 3 line 6 5 buzz line 3 line 8 6 fizz line 3 line 10 7 line 3 line 10 8 line 3 line 8 9 fizz % If you stare at it for a while you'll see that that line 4 is never called because i is never a multiple of 15. Stare at it longer and you'll see that it only reports the line of the 'for' statement once and only the 'if' of the 'if/elif/else' lines. That's not so useful. Are you interested in seeing what you get from sys.settrace? If you do the obvious thing and define a callback and call settrace before running the fizzbuzz code, like this # This does not work like you might expect import sys def report(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return report sys.settrace(report) for i in range(1, 10): if i % 15 == 0: print i, "fizzbuzz" elif i % 5 == 0: print i, "buzz" elif i % 3 == 0: print i, "fizz" else: print i To quote from the documentation The global trace function is invoked (with event set to 'call') whenever a new local scope is entered; it should return a reference to the local trace function to be used that scope, or None if the scope shouldn't be traced. In this case there is no new local scope, so you'll get no output. You need to structure it like this. import sys def report(frame, event, arg): if event == "line": lineno = frame.f_lineno print "line", lineno return report sys.settrace(report) def main(): for i in range(1, 10): if i % 15 == 0: print i, "fizzbuzz" elif i % 5 == 0: print i, "buzz" elif i % 3 == 0: print i, "fizz" else: print i main() Once you do that the trace output is line 12 line 13 line 15 line 17 line 20 1 line 12 line 13 line 15 line 17 line 20 2 line 12 line 13 line 15 line 17 line 18 3 fizz line 12 line 13 line 15 line 17 line 20 4 line 12 line 13 line 15 line 16 5 buzz line 12 line 13 line 15 line 17 line 18 6 fizz line 12 line 13 line 15 line 17 line 20 7 line 12 line 13 line 15 line 17 line 20 8 line 12 line 13 line 15 line 17 line 18 9 fizz line 12It's obviously more detailed because it reports the elif statements, and perhaps better because it shows that its' going back to the for statement for each loop. How do I get the same effect given the AST? One solution is to also instrument the "if" and "for" statements, so it's effectively like: def trace(lineno): print "line", lineno def trace_iter(lineno, it): for x in it: yield x print "loop", lineno # fizzbuzz.py trace(2) for i in trace_iter(2, range(1, 10)): if trace(3) or (i % 15 == 0): trace(4); print i, "fizzbuzz" elif trace(5) or (i % 5 == 0): trace(5); print i, "buzz" elif trace(7) or (i % 3 == 0): trace(6); print i, "fizz" else: trace(7); print i Doing this calls for a few changes in the add_trace code. As you've seen, defining the AST directly is verbose and harder to read than Python code so to make things easier I'll use compiler.parse to turn Python code into an AST, then add that AST into the main program's AST. Add the following to python_yacc.py, which creates a module-level variable called _header_ast: _header_ast = compiler.parse(""" def trace(lineno): print "line", lineno def trace_iter(lineno, it): for x in it: yield x print "loop", lineno """).node.nodes This is only proof-of-concept code. If you do this for real you should put all of the tracing code into its own module instead of inserting into each byte-compiled module. I would probably use a class, instantiated with the module name, a checksum of some sort, and a way to register which line numbers are present. The actual details will depend highly on what you want from it. Here's the new add_trace. The new bits are how I integrate the new _header_ast and the two parts at the end where I handle ast.For and ast.If nodes. The comments should be descriptive enough.) elif isinstance(node, ast.If): # Add "trace" calls for each elif; [0] is the if test # Result looks like # if original_test_0: suite_0 # elif lineno(2) or (original_test_1): suite_1 # elif lineno(3) or (original_test_2): suite_2 # ... # else: else_suite for i in range(1, len(node.tests)): if_test, code = node.tests[i] node.tests[i] = ( ast.Or([ast.CallFunc(ast.Name("trace"), [ast.Const(if_test.lineno)], None, None), if_test]), code) Does it work? % python compile.py -e fizzbuzz.py line 2 line 3 line 5 line 7 line 10 1 loop 2 line 3 line 5 line 7 line 10 2 loop 2 line 3 line 5 line 7 line 8 3 fizz loop 2 line 3 line 5 line 7 line 10 4 loop 2 line 3 line 5 line 6 5 buzz loop 2 line 3 line 5 line 7 line 8 6 fizz loop 2 line 3 line 5 line 7 line 10 7 loop 2 line 3 line 5 line 7 line 10 8 loop 2 line 3 line 5 line 7 line 8 9 fizz loop 2Definitely more verbose, and it looks like it's reporting everything correctly. With a bit more work I think I could instrument all of the statements to report full coverage, but I've not done that. Yet. Do you want to? Please? It would save me a lot of work. The output is still missing coverage for line 4. I had to check that by eye. It would be better to have the instrumentation tell me what's missing. The following shows one way to do it, which might be a sketch for a larger more robust system. I know which lines can be covered when I added the instrumentation so every time I add new instrumentation I'll also keep track of its line number in the "seen_linenos" set. Once I know all the line numbers I can use them to initialize a dictionary in the AST called "lineno_counts", which maps the line number to number of times the instrumentation for it occured. When the program is over, which I get from registering a callback via "atexit.register", I'll go through the lineno_counts for each line I'll display the line number and either "********" if the corresponding count is 0, or the count itself. _header_ast = compiler.parse(""" def trace(lineno): lineno_counts[lineno] += 1 def trace_iter(lineno, it): for x in it: yield x lineno_counts[lineno] += 1 def report_coverage(): print " === line coverage ===" for (lineno, count) in sorted(lineno_counts.items()): if count == 0: print lineno, "********" else: print lineno, count import atexit atexit.register(report_coverage) """).node.nodes def add_trace(node, is_module, seen_linenos): # count_ast is identical to: # lineno_counts = dict.fromkeys([], 0) count_ast = compiler.parse( "lineno_counts = dict.fromkeys([], 0)").node.nodes[0] new_nodes.append(count_ast))) seen_linenos.add(lineno) locate(trace, lineno) new_nodes.append(trace) # add the call to the AST new_nodes.append(child) # and then do the old code add_trace(child, 0, seen_linenos) node.nodes[:] = new_nodes # replace the old list of ast nodes if is_module: # Insert the possible line numbers into the initialization # for the 'lineno_counts' dictionary. data_nodes = count_ast.expr.args[0].nodes = [] for lineno in seen_linenos: data_nodes.append(ast.Const(lineno)) else: # Recursively descend through all nodes to find ast.Stmt nodes # "getChildNodes" is part of the compiler.ast node API for child in node.getChildNodes(): add_trace(child, 0, seen_linenos) #) seen_linenos.add(node.lineno) elif isinstance(node, ast.If): # Add "trace" calls for each elif; [0] is the if test # Result looks like # if original_test_0: suite_0 # elif lineno(2) and (original_test_1): suite_1 # elif lineno(3) and (original_test_2): suite_2 # ... # else: else_suite for i in range(1, len(node.tests)): if_test, code = node.tests[i] node.tests[i] = ( ast.Or([ast.CallFunc(ast.Name("trace"), [ast.Const(if_test.lineno)], None, None), if_test]), code) seen_linenos.add(if_test.lineno) This also means changing the "add_trace" call in the parse function, to def parse(source, filename="<string>"): ... err.text = text raise add_trace(parse_tree.node, 1, set()) misc.set_filename(filename, parse_tree) syntax.check(parse_tree) return parse_treeThe result? % python compile.py -e x.py 1 2 3 fizz 4 5 buzz 6 fizz 7 8 9 fizz === line coverage === 2 10 3 9 4 ******** 5 9 6 1 7 8 8 3 10 5 Hmm. What else is there to do? Quite a bit. My original purpose in doing this was to instrument Python code for branch coverage. You can see I'm at the point where I can do that now, but it's more than I'm going to cover in a tutorial. Or perhaps you'll work on it and save me the effort? Python 3 is in early alpha. It's incompatible with the Python 2 series, the last of which will be Python 2.6. The currently suggested upgrade path is to make your code 2.6 compatible then use the 2to3 converter to turn it into Python 3 code. The converter does only static analysis of the structure, without any inferencing. It can't check everything. What about adding run-time instrumentation that can, for example, check that the result of .keys() is never used as a list? Then run the unittests and see if there are any problems. But bear in mind that I don't trust this code for mission critical work, at least not without a lot of testing. The compiler module has known bugs, and will be removed for 3.0. I've not put everything through its paces. So at this point use python4ply for experiementational work and be prepared to dig into code to figure out what's going on. Because the compiler module will be removed, the best thing for the future is to rewrite the AST generation so it uses the same AST nodes as in the _ast module. That is, so it uses Python's own AST structure and AST -> bytecode generation. I'm not looking forward to that, and it will prevent cool bytecode hacks like my monkeypatched AssignExpr. Perhaps you can to write a pure Python bytecode generation engine? A more general program could also support __future__ statements correctly, so 'with' and 'as' aren't keywords when parsing old Python files. It should also handle inline encoding declarations. Again, don't look at me ... unless you've got money?
http://dalkescientific.com/Python/python4ply-tutorial.html
CC-MAIN-2017-26
refinedweb
7,712
67.25
- Type: Bug - Status: Closed (View Workflow) - Priority: Major - Resolution: Done - Affects Version/s: 7.1.1.Final - Fix Version/s: EAP 6.1.0.Alpha (7.2.0.Final) - Component/s: JPA / Hibernate - Labels:None Prerequisites: 1. A JPA entity A with a reference to a different JPA entity B. FetchType is FetchType.LAZY, e.g. @Entity public class A @Entity public class B { } 2. A remote interface with methods passing an instance of A, .e.g. @Remote public interface ITest 3. A process calling test1() and then test2() on the remote interface like this: @EJB(lookup = "...") private ITest iTest; public void ITest(){ final A a = iTest.test1(); iTest.test2(a); } } Error description: When calling test1() an instance of A is returned. This instance is valid and works as expected. The reference to B is a proxy (something like B_$$_javassist_2), which was expected because B was loaded lazily and was never accessed in the remote process before. When passing the instance of A back by calling test2(a) an exception of this type is raised: java.lang.ClassNotFoundException: B_$$_javassist_2 from [Module "deployment.x.ear.y_ejb.jar:main" from Service Module Loader] at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(Concurrent ClassLoader.java:468) It looks as if the proxy cannot be serialized or deserialized. The behavior is reproducible with different applications on different platforms. As soon as a Hibernate javassist proxy, which was received via a remote call, is passed back as an argument in another remote call (the remote process is the same in all calls) the exception is raised. The classloader settings are the standard JBoss settings.
https://issues.redhat.com/browse/AS7-5496
CC-MAIN-2020-45
refinedweb
278
51.75
This is the ninth and the last part of my Spring Data JPA tutorial. Now it is time to take a look of what we have learned, and how we should use it to build better software. Table of Contents The contents of my Spring Data JPA tutorial is given in following: - Part One: Configuration - Part Two: CRUD - Part Three: Custom Queries with Query Methods - Part Four: JPA Criteria Queries - Part Five: Querydsl - Part Six: Sorting - Part Seven: Pagination - Part Eight: Adding Functionality to a Repository - Part Nine: Conclusions The next step is to take a look of the advantages provided by Spring Data JPA and learn how we can use it in effective manner. Promises Kept The goal of the Spring Data JPA project is stated:. This is a lot to promise. The question is, has Spring Data JPA achieved its goal. As you have learned from my tutorial, Spring Data JPA has following advantages over the "old school" method of building JPA repositories: - It provides CRUD capabilities to any domain object without the need of any boilerplate code. - It minimizes the amount of source code needed to write custom queries. - It offers simple abstractions for performing common tasks like sorting an pagination. The thing is that implementing these functions have forced the developers to write a lot of boilerplate code in the past. Spring Data JPA changes all this. It minimizes the amount of code needed for implementing repositories. Making It Work for You I hate the term best practices because it has a negative effect on continuous improvement. However, I still feel that it is my responsibility to give you some guidance concerning the usage of Spring Data JPA. Here are my five cents about this matter: Creating Queries Your goal should be to use the Spring Data JPA to reduce the amount of code you have to write. With this goal in mind, I will you give some guidelines for creating queries with Spring Data JPA: - If the query can be build by using the query generation from method name strategy, I think you should use it. However, if the method name will become long and messy, I would consider using the @Query annotation in order to make the source code more readable. - Your second option for creating queries should be the @Query annotation and JPQL. This approach ensures that the you will not have to write more code than it is necessary. - Use JPA Criteria API or Querydsl only when you have no other options. Remember to extract the query generation logic into separate classes which creates Specification or Predicate objects (Depending on your technology selection). JPA Criteria API Versus Querydsl This is a question which should be asked by each developer. The usage of JPA Criteria API has been argued by claiming that you can use it to build type safe queries. Even though this is true, you can achieve the same goal by using the Querydsl. The first round ends in a draw, and we need to look for the answer from a bit deeper. I will compare these two options in following categories: readability and testability. Readability Programs must be written for people to read, and only incidentally for machines to execute - Abelson and Sussman on Programming. With this guideline in mind, lets take a look of the implementations, which I created for my previous blog entries. The requirements of the search function are following: - It must be possible to search persons by using their last name as a search criteria. - The search function must return only such persons whose last name begins with the given search term. - The search must be case insensitive. First, lets take a look of the implementation which is using the JPA Criteria API. The source code of my static meta model is given in following: @StaticMetamodel(Person.class) public class Person_ { public static volatile SingularAttribute<Person, String> lastName; } The source code of my specification builder class is given in following: public class PersonSpecifications { /** * Creates a specification used to find persons whose last name begins with * the given search term. This search is case insensitive. * @param searchTerm * @return */(); } }; } } Second, the source code of the implementations which uses Querydsl is given in following: public class PersonPredicates { public static Predicate lastNameIsLike(final String searchTerm) { QPerson person = QPerson.person; return person.lastName.startsWithIgnoreCase(searchTerm); } } This use case is pretty simple but it can still be used for demonstrating the differences of the JPA Criteria API and the Querydsl. The source code written by using Querydsl is clearly more readable than the one using the JPA Criteria API. Also, when the queries become more complex, the difference will be much bigger. I would say that this round goes to Querydsl. Testability Software testability is the degree to which a software artifact (i.e. a software system, software module, requirements or design document) supports testing in a given context. In other words, the testability of your code defines the amount and quality of tests you can write at the same cost. If the testability of your code is high, you can write more tests with better quality than in a situation where the testability of your code is low. Lets keep this measurement in mind when we will compare the unit tests written for implementations which were presented earlier. First, lets check out the unit test for the implementation which uses the JPA Criteria API:); } } Second, the unit test for the implementation using Querydsl is given in following:); } } After seeing the unit tests for both implementations, it should be obvious that writing unit tests for Querydsl is much easier than writing unit tests for the JPA Criteria API. Also, the unit test written to test the Querydsl predicate builder is much easier to understand. This is valuable because unit tests should also be used to document the behavior of the system. At this point it should be clear that the winner of this round is Querydsl PS. I am aware that unit tests do no ensure that the results returned by the created query are correct. However, I believe that they are still valuable because running unit tests is typically dramatically faster than running integration tests. It is still good to understand that in the context of integration testing, the testability of both implementations is equal. Conclusions The question is: Should I use the JPA Criteria API or Querydsl? It depends. If you are starting from scratch and you have a total control over your technology selections, you should at least consider using Querydsl. It makes your code easier to write and read. It also means that writing unit tests for your code is simpler and faster. On the other hand, if you are modifying an existing system to use Spring Data JPA, and the existing code is using the JPA Criteria API, you might want to continue using it for the sake of consistency. The fact is that there is no right answer for this question. The answer depends always from external requirements. The only thing you can do, is to ensure that you are aware of the different options, which are available to you. Only then you can choose the right tool for the task in hand. There is Still More to Learn The truth is that I have only scratched the surface of implementing JPA based repositories. I hope that the recommendations given in this blog entry will help you to take the first step, but I have to admit that there is a lot more to learn. I hope that the following resources will help you in your journey: Reference Documentation JPA Criteria API 2.0 - Dynamic, Typesafe Query in JPA 2.0 - JPA Criteria API by Samples Part I and Part II - Using the Criteria API to Create Queries - The Java EE 6 Tutorial This has been awesome stuff. Thanks for sharing. Especially the github projects are really valuable. Antti, Thanks for the feedback. It is great to hear that you have find this tutorial useful. Nice blog post again. One other benefit of Querydsl compared to the JPA 2 Criteria API in the Spring Data context is that it is also available for some other backends, at the moment MongoDB and JDBC. Timo, thanks for your comment. The support for MongoDB and JDBC is indeed a strong benefit of Querydsl. However, I feel that there might be some work to be done in order improve the general awareness about Querydsl. does querydsl support postgres Yes. However, nowadays I am using jOOQ because it has a better API (in my opinion). After some days googling I couldn't find a better Spring JPA tutorial than this one, Spring data team should hire you to write some documentation and working examples for them, I read their Spring JPA doc and it is vague compared to this one, very well done. Guido, Thanks for your comment. I am happy to hear that you found this tutorial useful. Some parts of this tutorial contain a bit outdated information since the tutorial is based on 1.0.2 version of Spring Data JPA. However, I have written a book called Spring Data Standard Guide that is an extended edition of this tutorial. This book covers the usage of Spring Data JPA 1.2.0 and Spring Data Redis 1.0.1. Very nice, I'll get the book ASAP, I was about to ask questions but a book should answer most, I have though one question of a matter of opinion, JPA reporsitories are nice, but what if you need to build your query base on optional parameters? Let's say, you have a table of events, and you want a list of events between a time frame (findByTimeBetween signature)? Answering the question myself, it seems to me that the best builder pattern like usable for this is the Criteria API (Passing a null to a Between signature method raises an exception), which I like it more soft than hard typed (metamodel), any thoughts on this? Or, does the book cover stuff like that? Hi Guido, You have two options (you already figured the first one out): The book covers both of these situations. Also, the book has 11 different implementations of a simple contact manager application that use Spring Data JPA. 7 of those applications demonstrate the different query creation techniques (1 technique per application) and 4 demonstrate other concepts. These applications makes it easy to start experimenting right away (it can be frustrating to start building application from scratch if you are not sure how things work). Also, if you have more questions, I will be happy to answer them. Hi Petri, I just overview the whole book, it is very nice, I do feel it is missing one or two chapters with some corner cases scenario, not that I wanted one specific scenario in it, but it would help to shed some light/ideas. There is still the scenario that I described to you before about dynamic queries with JPA 2 Criteria API, our project is kind of overloaded already and for the use cases we have I don't think we are going to into any specific complex scenario, for such cases I would just use standard JPQL queries. To complete my puzzle I need just one idea, I don't want to go thru the hassle of creating my own custom Pageable by using .count(...), so I was thinking if there is a way to link Criteria API with Spring Pageable interface or PageRequest class. I know, in the worst scenario I will just create a Generic method where I pass a Predicate, a Sort and a Page request to manually execute two queries (one to count and another which will actually do the job) base on the passed Predicate. Here is a working example, but it is missing the link between Pageble and Criteria, we use this with JPA interceptor (new code in progress) which has every object backed by Riak (Think of it Redis like with consistency and availability in our case, fast KV): @Repository public class UpdateChunkServiceImpl implements UpdateChunkService { @PersistenceContext private EntityManager entityManager; @Override public List<UpdateChunk> findByChunkTypeAndTimeBetween(final UpdateChunkType chunkType, final DateTime fromDate, final DateTime toDate, int pageIndex) { final CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder(); CriteriaQuery<UpdateChunk> criteriaQuery=criteriaBuilder.createQuery(UpdateChunk.class); final Root<UpdateChunk> root=criteriaQuery.from(UpdateChunk.class); final Path<DateTime> timePath=root.get("time"); final Path<Integer> chunkTypePath=root.get("chunkType"); Predicate predicate=null; if(chunkType != null){ predicate=addAndPredicate(criteriaBuilder, predicate, criteriaBuilder.and(criteriaBuilder.equal(chunkTypePath, chunkType.getTypeId()))); } if(fromDate != null){ predicate=addAndPredicate(criteriaBuilder, predicate, criteriaBuilder.and(criteriaBuilder.greaterThanOrEqualTo(timePath, fromDate))); } if(toDate != null){ predicate=addAndPredicate(criteriaBuilder, predicate, criteriaBuilder.and(criteriaBuilder.lessThanOrEqualTo(timePath, toDate))); } if(predicate != null){ criteriaQuery=criteriaQuery.where(predicate); } criteriaQuery=criteriaQuery.orderBy(criteriaBuilder.desc(timePath)); return entityManager.createQuery(criteriaQuery).getResultList(); } private Predicate addAndPredicate(final CriteriaBuilder criteriaBuilder, final Predicate oldPredicate, final Predicate newPredicate) { return oldPredicate != null ? criteriaBuilder.and(oldPredicate, newPredicate) : newPredicate; } } Thanks for taking a look at my book! I agree that it lacks "advanced" concepts but I was under a strict page count limit given by the publisher which made it practically impossible to add these concepts to the book. We were originally planning to add a chapter about Spring Data Hadoop as well but the page count limit made it impossible. I ended up publishing that chapter in my blog. About your problem: Are you trying to figure out a way to implement this piece code with Spring Data JPA or just use parts of it in your implementation? If you want to use Spring Data JPA, you have to follow the steps described in the seventh part of my Spring Data JPA tutorial. If you want to use only parts of it and build your own pagination logic, you could find some answers from the source code of the SimpleJpaRepository class. Check the private readPage(TypedQuery<T> query, Pageable pageable, Specification<T> spec) method that is used to read the objects belonging to the requested page from the database. My plans are to use strictly Spring Data JPA wired with Hibernate 3.6.10.Final because version 4 has no support yet for Joda time and few other things, using Spring data repositories for the simple scenarios and Criteria API for more complex scenarios, then by using Hibernate interceptor manage the backed Riak data, think of it as a JPA hybrid JPA where you can do SQL for filtering and KV for fetching, of course, storing data will still do its part in SQL for very few fields, like ID, time, some categories, but the raw data will only be stored in NoSQL, we want to follow a simple standard like the combination of Spring Data + JPA 2, simplicity of proxying injection and at the same time the complexity of our other layer (NoSQL) So are objects have Jackson annotations AND JPA annotations which with the aid of Hibernate interceptors will do both with the same @Persistent @Json instance. So basically you want to: Is there some reason why you prefer using Hibernate interceptors instead of simply getting the raw data from Riak after you have received the ids? I have not personally used Hibernate interceptors so I am kind of shooting blind here. However, I took a quick look of the Javadoc and you might be able to use them if you: @Transientannotation. UpdateChunkclass as a "normal" entity, and build the query executed against the relational database by following the approach described in my Spring Data JPA tutorial that talks about pagination. This is getting interesting. I definitely want to know if this works. UpdateChunk as you guessed (you basically read my mind), has several annotations per method, for example, if a field will be ONLY stored at Riak, then it is @Transient, if it is a pseudo property then it is annotated with @Transient and @JsonIgnore, so basically I have a hybrid ORM, except that my relational part is very minimal, the idea behind SQL is only to provide a set of indexes for search and filtering purpuses, you could manuall fetch with multiget using the IDs, but I have used Hibernate interceptors before and they are ... lets say they are faster than doing the job manually OR using AOP. Lets say, List findBy... will do the whole job, hybridly speaking, my only draw back, which it is a matter of taste, is that I don't like Query DSL, at advanced applications you usually do either of the following things: 1) Standard JPA repo for most queries (which supports pagination) 2) Use custom queries either using entity manager and building your own query. 3) Typesafe using criteria, I like more the Type safe idea because the mapping is resolved, specially if your project has custom mapping like joda time, which by just adding a jar works: @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime") I have another layer for Riak, which will be called by Hibernate interceptor, with mutation and all that Riak implies, with its own caching (Using Google's Guava 13.0.1 framework) so doing the multiget will kind of have its own 2nd level cache so it will be fast. But as you know, Redis, Memcache, CouchDB, and most KV NoSQL DBs tend to have poor indexing/search like API, so we have to have a Hybrid model, we even have Solr 4 which we use for other type of Docs searching. Thanks for explaining the "theory" behind the decision to use the "hybrid" model. It was interesting and I definitely agree that index and search APIs of NoSQL databases tend to be poor (At least when you compare them with relational databases). Hi Guido, You'd have some direction on how I could inject a JPA repository into an Hibernate interceptor ? I would like to log in a table Hibernate operations using an AuditLogRepository but it is not seen by Hibernate. Cheers, Hi Stephane, I noticed that you asked you the same question here: Spring managed Hibernate interceptor in JPA. This gave me an idea. Maybe you can do something like this: @Configurationclass or add it as a method parameter to the @Beanmethod that creates the Hibernate interceptor object. @Beanmethod by creating the Hibernate interceptor. Remember to pass the JPA repository to it. Naturally I haven't tried this myself, but it could work. Our idea is to use POJO which will be convert back and forth to JSON, stored in Riak NoSQL fully and only few of their properties stay in SQL for query/indexing purposes, so our focus in JPA is just for filtering, paging and stuff, using JPA/Hibernate to update objects and interceptors to populate to Riak, most Objects will just in Riak with few in SQL. Yes, you are right, the source code pointer you sent answers my questions, thanks a million. Now my puzzle is completed, to be honest, it seems like Spring Data is bigger than what I thought, you need another 200 pages from your publisher and an Advanced Spring Data book. Hey, good to know that you found the answer you were looking for! Now I am wondering if my lucky shot described above works. I am wondering if I should test it myself ;) As for the Hibernate interceptor, it is easier to use than what you think, explained on this reference: Thanks for the learning experience. It is always nice to learn new things! I have successfully implemented what I called phase 1, I couldn't do it in Hibernate, I had to switch to EclipseLink 2.4.1 which to be honest for JPA 2+ I think it will have a better future, when you annotate a property with @Transient, no interceptor in the world see the value and hence it is lost for Riak (@PostInsert and @PostSave) So EclipseLink as this @CloneCopyPolicy which allows you to specify a method which will create a of your Entity including its transient properties, so this method which I called cloneThis basically creates a BeanWrapper instance and copy each not null property to a new instance. To resume, the Entities backed with NoSQL require two additional annotations: @CloneCopyPolicy and @EntityListeners, then magic happens, the entity listener also have methods for @PostLoad and @PostRemove. Where can I post or send you my @Configuration class for EclipseLink?, It is almost the same as the one of your tutorial, it requires for a better performance the ReflectiveLoadTimeWeaver which has to be configured at bootstrap at the application servers (Had to google so much) BTW, I finished today most of our new API, finally, I went for EntityListener called JPA2RiakListener, since I don't mind annotating the POJO with the listener class, and it will remove the overhead of calling the listener when an Entity is backed by Riak. It was really hard to create a JPAQueryUtil for count and pagination because of some stupid error with CriteriaQuery and generatedAlias, I meant, making a Generic type like Pageable method where it accept a CriteriaQuery and Order, I had to mix some class and generate the alias by myself, I'll post the code when I give a better form to the code (clean up and stuff) Hi, after I read your book and and make de tutorials that you brote, we take de desicion to make a project for about 150 enttities, Already finish the construcction of the backend... but in the construccion of the front-end I feel that the team spent too much time. it seems to elaboraiting to much boilerplate. so de question is in sense to suggest me a set of frameworks to acelerate de work?. what do you think about Spring Roo with Spring Data? First, I would like to thank you for reading my book and tutorials. I hope that they were worth your time. Could you describe what were the biggest reasons of writing boilerplate code? This would help me to give a better answer to your question. However, one very common task that requires boilerplate code is transforming DTO objects into model objects and vice versa. There are several libraries which help you to reduce the amount of required code: I have no experience from Spring Roo (I have not used it) so I have no idea if it is useful. The problem of code generation (in general) is that I want to be in control of my code base because this way I know that the code is good enough. Code generators can help you to create the skeleton of the application but naturally they cannot write the actual logic for you (except maybe in simple cases). This being said, I think that it might be worth to give Spring Roo a shot. You should never judge something which you haven't used yourself. There are a couple of "related" Spring projects which you might find useful as well: I hope that my answer was useful to you. If you can shed more light on the reasons of writing boilerplate code, I am more than happy to continue this discussion! I am searching for general benchmarks for performance of SPRING DATA. Is there some blog or articles on performance of Spring Data JPA vs just OpenJPA? I am not aware of such blog post or benchmark :( This is a shame because it would be interesting to know the overhead caused By Spring Data. If you happen to find such a benchmark, it would be nice if you could let me know about it. Hello Petri, Thank you very much for your articles .... If we use spring data JPA , what would be the best UI frame work you would recommend to integrate with this ? We are looking for some thing that can help faster development and also less experienced developers should be able to learn fast. JSF/wicket/struts/spring mvc ........ like this a list is being proposed ... Regards MRV Hi, Have you considered using Grails? Although I have no experience from it, it seems to get a lot love from SpringSource right now. Another interesting project is Spring Boot which simplifies the development of Spring powered applications. It is kind of hard to say what is the best UI framework because it depends from many factors. For example, if most of your team members already know JSF and have no experience from Spring MVC, it probably makes no sense to use Spring MVC in your project (unless you want to learn something new). One suggestion though: I wouldn't consider using Struts because it doesn't offer anything which isn't found from Spring MVC. Petri, Basically we are looking for some thing like SPRING REST, SPRING DATA JPA stack ... but looks like JSF is not a good candidate for the above stack . I may be wrong but. Grails looks like( yii php frame work) but couldn't find good tutorials that give enough confidence .. Vikas, Maybe you could build your applications by using the "full" Spring stack. In my previous job I did use another web framework (Wicket) with the Spring stack. It seemed to be the right thing to do at the time but now I think that perhaps the "full" Spring stack would have been a better choice. Petri, Do you have any experience on Play frame work ? any idea how good it is when comparing to grails ? Regards Vikas Hi Vikas, I have created a "Hello World" application with Play and Scale so I have no real experience from it. However, I remembered that zeroturnaround.com has published a few rather good articles about Java web application frameworks: Maybe these will answer to your question. Petri, Planning to try Vaadin... thank you very much for your directions. Will update you if any road blocks.... just for sharing experience.....:-) Regards Vikas Hi Vikas, I am very interested to hear your opinion about Vaadin. I have an opinion too but I am not going to reveal it yet. :) Petri, As per one of our brain trusts opinion we decided to try vaadin for only admin modules. As it is state full and consumes more memory due to all built-in widgets/components ...We fear whether it may scale to eCommerce kind off apps where traffic is more ...we are now more to the original plan ... Some thing like Spring data jpa rest mvc + Jquery ... Or Play + Jquery Regards Vikas Hello Petrik, I am very new to the world of Spring and all programming stuff. We use Spring data in our project. I have a simple query as follows "select * from USERS". I also use Pageable to enable pagination. This query may have optional predicates based on the given parameters being null or not. For example if "code" parameter is given and not null, then the query becomes "select * from USERS where code = :code"; As far as I know I cannot implement this using @Query annotation. I can implement a custom repository and use EntityManager to create a dynamic query. However, I am not sure how I can integrate "Pageable" with that to get back paginated results. How can I achieve this? If you need to build dynamic queries, you can use either JPA Criteria API or Querydsl. Both of these techniques support pagination so it shouldn't be a problem. Hi Petrik, Thanks for the reply, This is how i created my query. Can you please tell me how i can use pagination with the same ? I need to return Page instead of collection. public List findCustomers( final String firstName, final String surname) { StringBuilder queryBuilder = new StringBuilder( "select c from Customer where "); List paramList = new ArrayList();.createQuery( queryBuilder.toString()); List resultList = (List)query.getResultList(); // iterate, cast, populate and return a list } Return a page instead of collection / list, can you please help me with that? You cannot use pagination provided by Spring Data JPA if you use entity manager. Let's assume that you can to create the query by using Spring Data JPA and JPA Criteria API. You can do this by following these steps JpaSpecificationExecutor<T>interface (See my Spring Data JPA + Criteria API tutorial for more details about this.) Specification<Customer>objects (See my Spring Data JPA + Criteria API tutorial for more details about this). findAll(Specification specification, Pageable pageable)method of the JpaSpecificationExecutor<T>interface (See my Spring Data JPA + pagination tutorial for more details about this). I hope that this answered to your question.
https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-nine-conclusions/
CC-MAIN-2022-40
refinedweb
4,745
60.14
Analysis Software If you would like access to the software on this page we ask that you adhere to a few basic conditions: - You don't share it further than your group, but direct any additional requests to us - We will answer simple questions and try to add requested features and especially fix bugs, but we can't "support" the software as if it were a commercially available package, we also will not answer basic Igor questions. - If eventually your group makes improvements, we'd like to have those shared back and ideally keep a master version. All files on this page require proper credentials for download. Please contact us if you would like access to the files or to report any bugs with the software: password request Contents - 1 ICARTT - 2 How to read NetCDF v3 into Igor - 3 Mie Code - 4 Picarro G2401 - 5 Real Time AMS Igor Display - 6 SMPS - 7 KinSim ICARTT ICARTT Igor Software ICARTT Igor Software Notes - These functions create and load data files in the ICARTT format, a widely used, text based format for atmospheric data, particularly for aircraft data. The latest ICARTT specification is linked above. ICARTT is based on the Haines-Hipskind NASA Ames Format, and has undergone several revisions since its inception in 2004. Functions and macros herein are not appropriate for all data generated by ICARTT users; assumptions are outlined below. - This code can write and read data in a 1D timeseries format, which is the by and large most used ICARTT format ("Fileformat 1001", see below). The ICARTT specification also includes several additional file formats for posting multidimensional data (Fileformats 2110 and 2310), but these are currently not supported by this software. - There are 2 main versions of the ICARTT specification, v1.1 and v2, the latter being in use since 2017. The specification linked above refers to v2.0. Importantly, the code provided here is able to read most standard-compliant v1 and v2 ICARTTs, but it will only write out v2 compliant code. - Functions in this file use functions in the 2019 GeneralMacros igor procedure file (a collection of NOAA CSL supported Igor Tools). Users should have both files open in an igor experiment. - Whenever a user loads or creates a ICARTT format file, an igor data folder called ICARTTFileFormat gets created in the experiment and most of the work is done here. If something goes awry, the user can reset the data folder to root (most everyone's default) by inserting the text below (less the //) into the command line SetDataFolder root: - Some parameters are calculated; some have simple default values. The later are: - FileFormatType = 1001 // this value is assumed for reading and creating files. - FileVolumeNumber = 1 // this value is assumed for reading and creating files. - TotalVolumeNumber = 1 // this value is assumed for reading and creating files. - ScaleFactor = 1 // this value is assumed for creating files, but reading files with non-unity scaling factors is supported - MissingDataIndicator = -9999 // NOTE - This is adjusted depending on the significant digits of the datastream - None of the original waves in the experiment are modified in any way. Waves selected to be saved are duplicated in the ICARTTFileFormat data folder. The UTC timewave (the independent parameter) and any dependent parameters formatted with a "t" (from the create panel) will have the starting date subtracted from it (in the created file) and will be formatted with one digit after the decimal. - When loading an icartt file into an experiment, the missing value as reported in the header will be used to convert missing values in the incoming waves to nans. The independent variable (time) will have the UTC date (as indicated in the header) added to it. - When loading data from the LoadDataOnly menu item, almost no format checking is done and missing data isn't changed to nans. - The name of the wave in the experiment will be the name given to the dependent and independent parameters, with the exception of matricies, where column names much as mymatrix0, mymatrix1, etc are used. - If anything is named in the experiment in a 'liberal' fashion (i.e. wave names with spaces), all bets are off. - Users should be aware that there are operating system differences for end of line designations. Mac uses carriage return (CR), Unix uses line feed (LF), and Windows use carriage return + line feed (CRLF) For icartt, the preferred end of line designation is CRLF (which correspondes to \r\n in the code). Other Igor ICARTT Software The first tool was written by James Allan (U Manachester) and uses one ipf: ICARTT Matlab Software The following software was written by Glenn Wolfe (NASA GDFL), who also maintains it, please contact him for support. It provides a generic reader and a specific/example writer procedure: ICARTT R Software The following ICARTT reader was written by Steve Wofsy (Harvard), who also maintains it, please contact him for support. ICARTT Python Software Provided by Christoph Knote (being updated as of 2022) - Project page at Pypi Python Package - Project page at U Augsburg ICARTT Python Package and Discussion Provided by: Barron Henderson barronh@gmail.com (21-Aug-2013) # In a python script from PseudoNetCDF.icarttfiles import ffi1001 f = ffi1001('pathtofile') var = f.variables['HO2_pptv'] print var[:].mean(), var.units # From command line: dump CDF (like ncdump) python -m PseudoNetCDF.pncdump -f ffi1001 pathtofile # From command line: make a NetCDF file (like ncdump file1 | ncgen file2) python -m PseudoNetCDF.pncgen -f ffi1001 pathtofile pathtonetcdfoutput.nc How to read NetCDF v3 into Igor - Provided by Pedro Campuzano-Jost, with credit to Pengfei Yu. - This applies to working with instrument/model output that is formatted in netcdf v3 (1997 release). - Reading netcdf3 files in Igor is extremely painful. There is a 2004, 32-bit compatible XOP from a Japanese group buried in the depths of IgorExchange, with no hope of an update, as well as some code on top of that XOP from both the Manchester guys and Donna. But regardless, it requires you to open a 32-bit version of Igor just to load the file, and the handling of 2D waves and wave attributes is...less than ideal. - On the other hand, netcdf v4 is very easy to deal with since the data structure conforms to the hdf5 format (used by Aerodyne and Tofwerk instruments and many other applications). But despite the fact that v4 is 10 years old (v 4.0.0 of the netcdf library was released in 2008), many scripts used by atmospheric chemist still use v3 (including about 80% of global modelers). The fix is actually surprisingly easy: - Download the netcdf 4.6 for windows library/utility pack: (NCAR, for unknown reasons does not advertise the windows version on their main software page, so if you want to stay up to date check this webpage:) - Install the package and MAKE SURE you add the library to your System/DOS path (installing for all users is probably the best/easiest option) - Open a command prompt and cd yourself into the directory where your netcdf v3 file lives (if this sounds scary, just put your file in your personal folder, above "Documents", and you won't need to cd at all) - Run "nccopy -4 MyNetCDFv3File.nc MyNetCDFv3File.h5" - The new file you created, MyNetCDFv3File.h5 is now a netcdf4/h5 file and can be perused at will with the hdf5browser in Igor (warning, it is likely quite a bit bigger than the old one). Mie Code - The Igor IPF below contains the J-Group Scattering/Extinction calculator, based on the code provided in the book by C. F. Bohren and D. R. Huffman, Absorption and Scattering of Light by Small Particles. - Our group uses this function frequently to independently check the quantification of the AMS, by e.g. comparing the mass scattering efficiency (MSE) calculated from AMS mass divided by dry PM1 scattering, to the MSE calculated from measured size distributions (e.g. from an SMPS) and this Mie code. For an example see Figure 2d in DeCarlo et al., 2008 - The original version of the Mie subroutine was translated from Fortran into Igor by Charles Brock, NOAA ESRL, and it is provided "as is" (few comments). For interpretation of what that subroutine is doing see the B&H book and also e.g. this link that provided Fortran code with more detailed comments. - The wrapper code was written by Ed Dunlea, Mike Cubison and Pedro Campuzano Jost. - Contact Pedro.CampuzanoJost-1@colorado.edu and jose.jimenez@colorado.edu for feedback or bug reports. - You can download the code from this link. Picarro G2401 Picarro Software Picarro Software Notes - Picarro Panel v1.0 (MJL 02/05/2013) - Recursively loads all .DAT Picarro acquisition files or a specified date range of files in a given directory (best to point the loading directory to DataLog_User and leave the sub directories in their original configuration) - Plots: - Picarro measurement time series - CO is the fully corrected measurement which corrects for CO2 and H2O spectroscopic interferences, as well as H2O dilution. - CO2_dry is corrected for H2O spectroscopic interference & dilution effect of H2O - CO2 is not corrected for anything (probably never use) - CH4_dry is only corrected for H2O spectroscopic interference & dilution effect of H2O - CH4 is not corrected for anything (probably never use) - H2O - Picarro diagnostic time series - Das Temperature - Etalon Temperature - Warm Box Temperature - Cavity Temperature - Cavity Pressure Software Output Measurement Timeseries Diagnostic Timeseries Real Time AMS Igor Display Real Time Software Real Time Notes - THIS FUNCTION WILL NOT COMPILE WITHOUT APPROPRIATE XOP! - An XOP (external operation) is a modular chunk of code that adds features to Igor One needs the file called VDT2.xop or a shortcut to this file to be placed in the directory Wavemetrics:Igor Pro Folder:Igor Extensions: The VDT2.xop is normally found in the folder called Wavemetrics:Igor Pro Folder:More Extensions:Data Acquisition - Real Time (RT) and Serial Feed (SF) ipf - This code is for use with the ToF AMS data acquisition program. In the daq one has the option of outputting a limited set of parameters to one text file (TimeTrace.txt)many individual text files (RT_xxxxx.txt) and/or serial output (No file name, just a an old fashioned serial RS232 output. Most will only work with only the RT_xxx.txt files - The functions in this ipf are intended to run in an Igor experiment concurrently with the DAQ. The RT_xxxx.txt files generated by the DAQ are intended to be read into an Igor experiment on the DAQ computer. Absolutely nothing in this ipf should change anything that happens in the DAQ - Usage Instructions: - Aircraft / Ground Plot will bring up a plot of predetermined parameters focused on Aircraft / Ground data - Delete Real Time Files checkbox when unchecked files are read into igor and then the file is moved to the processed folder. When checked file is not moved to the process folder, but instead is deleted. - The "Clear.." button will clear existing waves - will set them to zero points. "Pause.." will resume appending values to existing waves. - The "Process MS itx files" checkbox causes the itx mass spectra files to be loaded and appended to a 2D m/z vs time wave (assuming they have been selected to be saved in the DAQ menu). No plotting or further averaging is done in the DAQ_QuickView ipf posted here. - The TimeTrace.txt nd the serial feed functions are intended to more specialized purposes. - The TimeTrace.txt file is intended to be read into an Igor experiment as one file, and no special code is needed (beyond that of creating an igor-friendly time wave). In this case, just create the Real Time panel and press the begin button. - The serial feed functions are intended to work on a computer that has a serial stream connection to the daq. In this case, just create the Serial Feed panel and press the begin button. In either case, a standard graph of values will be plotted. Users may make new plots or change the existing one to suit their needs. Software Output SMPS SMPS Software The SMPS Software is generally not shared at this point, except with close collaborators of our group, as we don't have time to support it. SMPS Software Notes JG_SMPS_V4.46 (dd 8/06/14) - Loads and Concatenates SMPS data collected with TSI AIM (built on Mike C's BEARPEX/CalNex JG_SMPS_v3.ipf and used ToolsMJC_v1a.ipf and Tools_20100221.ipf) - As of V4.46 uses DS_GenTools.ipf for general functions (previous to then, used JG_GenTools or DougTools.ipf)) - Input should be .txt files created as ouput in TSI AIM software (row-formatted) and dNdLogDp and in named in format: 2010_12_13_1522_SMPS.txt (yyyy_mm_dd_hhmm_SMPS.txt) - If starting with .ipf (rather than .pxt, .pxp); - 0) Compile - 1) Run function "PopulateSMPSpanel()" (which populates the panel with default input values in "root:Temporary") - 2)"SMPS Plotting Panel" from "SMPS" menu dropdown - 3) If using a mask wave, a) customize "AssignFlags()" function and run; b) load mask and time waves in "Masterlogger folder" - "Load-Concatenate" button prompts user to select folderpath for text files to load and also promps user to input assign "project" name to files loaded (will put all data in folder names as such) - Choose the version of TSI AIM used to export text files (diagnostic columns vary) - User can chose number of Dp bins to regrid dNdLogDp to at the loading step only. This is useful for when file of different Dp ranges are loaded together. (when plotting later can chose to use these or the native bins). Warning, uses a linear interpolation, not binning, so if much fewer bins than in original data is chosen,not all data points are used in regridding so statistics may be degraded. Thus best to chose similar Dp number to original data and use raw data for final workups, instrument comparison, etc. - Image Time Series Plots plots either number or volume distributions - Optional inputs for: - Dp smoothing - Max percentile of data assigned to hottest color in image (help use full color range) - Interpolation across data gaps (of user-specified duration) - Choosing whether to use regridded or raw dXdLogDp (native scaling) - Integrated # and Mass Concentration Plot (Number or Mass) - Optional inputs: Max/Min Dp over which to integrate total concentration Additional Notes: - Best to reselect "Data Folder to Plot" to be sure that datafolder is set to proper project folder (should be reset after all plotting, so only really needed if user changes datafolders). However, must select before first plot. - Panel inputs stored in root:Temporary (DO NOT DELETE this folder) - can delete all other folders - Scaled dXdlogDp waves: Currently, these are not used anywhere in the code. To avoid make large "scaled waves" (interpolated to new/fixed timestamp) see the line near the top of the main ipf: "Variable offset = date2secs(2010,12,13), delta=60 //DD". As written (in the posted version) this would make a scaled size distribution from Dec, 13, 2010 with a point every 60 seconds up until YOUR last scan time. To avoid make this long, unused, mostly empty wave, change the date to the day before you collected your data and maybe change the delta to something bigger, like 300+. Then those waves will be small. Will code with more elegant solution in future version. - There are several auxillary functions at the bottom that may be useful for QC, exporting data. Use "CutBadDat()" function to "manually" enter bad periods that thereafter will be cut when using panel buttons. - Version update notes at top of .ipf Next Version Steps: - Several. See top of ipf. Feel free to send suggestions to Doug. Software Output Panel v4.44 dNdlogDp Size Distribution dMdlogDp Size Distribution dN Total Concentration dM Total Concentration KinSim KinSim Software KinSim Software Notes KinSim_v2.1.ipf (ZP 11/10/14) - Version 1 (by Harald Stark): mechanism generation and integration of rate equations. - Version 2: functions in v1 and - P- and T-dependent rate constants - Advanced input of initial concentrations - compatible to direct input of numbers (for concentrations in molec/cm3), and mixing ratios in "%", "ppth", "ppm", "ppb", "ppt", and "ppq" - Optimized parameters for the integrator - to handle stiff problems - Version 2.1: update of help notes and fix of minor bugs - General usage: compile the procedure then select "Display_help" from the "KinSim" menu. After the dialog box is prompted, select "Basic version" if only the functions in v1 are needed, else select "Version 2". Follow the help notes. KinSim_v3.75.ipf (ZP 5/31/18) - Version 3: switch from menu control to user-friedly panel control, substantial function reorganization, and - Automatic input check (for basic parameters and mechanism) - Species concentration constrain - Special treatment for photolysis, emissions, and dilutions (user-defined dilution air composition) - Times series plots of species concentrations and reaction rates - Version 3.75: fix of bugs, conversion of some macros to functions, and - Mechanism export and import - Preclusion of species from dilution - Mechanism input in both JPL and IUPAC formats - Possibility of enabling/disabling reactions in the mechanism - Fractional product stoichiometric coefficients - Option of simple rate-coefficient input table - Translation table to build time-dependence table - Real-time T & P change - Gas-particle partitioning calculations - General usage: see here Input Mechanisms - Basic OFR mechanism (v1.00 ZP 9/10/14) - Including photolytic, Ox, HOx, NOx, and SO2 reactions in OFRs - A few reactions have special rate constant expressions. Refer to the "Notes" column for more details. - Link: Basic_OFR_mechanism.pxp - Mechanism of CH4 full oxidation in OFRs (v1.00 ZP 9/10/14) - Should be used along with the basic OFR mechanism - Link: CH4_OFR-oxidation_mechanism.pxp - Mechanism for 2014 NO3-Terpene Chamber Studies (v1.00 DD, 6 Jan, 2015) - Link: NO3_Terpene_mechanism.pxp - Should work with latest KinSim versions, however see here for ipfs pre-version control, including additional post-processing/plotting functions and example plots images. - Mechanism for IEPOX-SOA (v1.00 DJ, 17 Nov, 2017) - IEPOX-SOA mechanism based on Marais et al. (2016) - Link: IEPOX_SOA_mechanism.pxp Other Utilities - List/post other utilities here
https://cires1.colorado.edu/jimenez-group/wiki/index.php/Analysis_Software
CC-MAIN-2022-33
refinedweb
3,001
51.28
During Christmas holidays, I read about Microsoft Windows Workflow Foundation (WWF) for the first time and realized that I was too late in learning this new technology. "Better late than never" - so I decided to get my hands wet on this framework. WWF is an extensible framework from Microsoft to implement workflow based solutions. In simple terms, a workflow is a collection of activities. To read more on WWF, please visit the MSDN site. At least once in a day, all of us open a web browser to do some search in Google, open our email account to check emails, and so on. This is an example of a human workflow, and in this article, I am going to show how to express this workflow in WWF. For doing a Google search, one has to perform the following activities: For checking emails in a Hotmail account, one has to perform the following activities: In the above scenarios, we are filling a form in a web page and posting it. To accomplish this workflow, I did a very minimal abstraction and came up with the three activities below: Microsoft has made WWF application development very easy by providing the Visual Studio� 2005 Extensions for WWF. A separate project template is available for developing the Activity library. To implement a custom activity, all we have to do is derive from the Activity class and override the Execute method. public class MyActivity : Activity { protected override Status Execute(ActivityExecutionContext context) { . . } } I added additional properties for the VisitPage, InputData, and Click activities. See the attached code for details. Visual Studio has full designer support to model a workflow and even allows us to define breakpoints in the designer itself for debugging. Workflows can be defined in XML format also (XOML - XML workflow markup). Figure 1 is Hotmail account login workflow in designer view, and figure 2 is a Google search workflow in text view. Figure 4 - Hotmail Login Figure 5 - Google Search There are so many automated web filing systems available today for a variety of services. I am sure that they are proprietary solutions very hard to develop, maintain, and to train new people. Now, we have got a very good generic, extensible framework from Microsoft with a full suite of developer tools to develop workflow based solutions. With the designer support, even a business analyst can complete a workflow without any help from a developer. I strongly believe that re-engineering web filing systems using WWF will deliver true ROIs. The sample application was developed using Microsoft Pre-Release Software WinFX Runtime Components - December Community Technology Preview (CTP). Microsoft internet controls were used for the IE browser functionalities. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/dotnet/WWF.aspx
crawl-002
refinedweb
452
53.21
glasser: > Tue Jun 5 10:14:33 EDT 2007 glasser at mit.edu > * Wrap log output in a configurable type. Content-Description: A darcs patch for your repository! > > New patches: > > [Wrap log output in a configurable type. > glasser at mit.edu**20070605141433] { > hunk ./Config.hs 109 > +-- > +-- If logging is enabled, xmonad prints out 'logWindowSet' applied to > +-- the current window set. By default this is the identity; however, > +-- if you'd like to be able to send other kinds of messages over > +-- stdout, you can make this something else (perhaps something like > +-- 'Either WindowSet CustomStatusBarCommand'). Note that you will > +-- also need to adjust the LogRecord declaration in Config.hs-boot. > + > +type LogRecord = WindowSet > +logWindowSet :: WindowSet -> LogRecord > +logWindowSet = id > + > hunk ./Config.hs-boot 5 > +type LogRecord = WindowSet > +logWindowSet:: WindowSet -> LogRecord How about we just set the logging function itself in Config.hs? logging :: WindowSet -> X () logging s = return () -- no logging logging s = hPrint stdout -- normal logging s = do e <- grabsomethingfun from XMonadContrib hPrint in my own format (e,s) ? -- Don
http://www.haskell.org/pipermail/xmonad/2007-June/000601.html
CC-MAIN-2014-15
refinedweb
168
57.27
GCC Bugzilla – Bug 17829 [3.4 Regression] wrong error: call of overloaded function is ambiguous Last modified: 2004-10-09 14:38:24 UTC With snapshot gcc-4.0-20041003 I get an error (see below): "call of overloaded is ambiguous" while only one function definition is present. With gcc33, gcc34 and the previous snapshot gcc-4.0-20040926 this program compiles without error. Michael Cieslinski src.ii: In static member function `static QFontEngine* QFontDatabase::findFont (QFont::Script, const QFontPrivate*, const QFontDef&, int)': src.ii:48587: error: call of overloaded `parseFontName(const QString&, QString&, QString&)' is ambiguous src.ii:28700: note: candidates are: static void QFontDatabase::parseFontName (const QString&, QString&, QString&) src.ii:48571: note: void parseFontName(const QString&, QString&, QString&) g++40 -c -O2 -o out.o src.ii -v Reading specs from /usr/local/gcc40/lib/gcc/powerpc-unknown-linux- gnu/4.0.0/specs Configured with: ../gcc40/configure --prefix=/usr/local/gcc40 --program- suffix=40 --with-cpu=G5 --enable-altivec --enable-languages=c,c++ --enable- checking Thread model: posix gcc version 4.0.0 20041003 (experimental) /usr/local/gcc40/libexec/gcc/powerpc-unknown-linux-gnu/4.0.0/cc1plus - fpreprocessed src.ii -quiet -dumpbase src.ii -mcpu=G5 -auxbase-strip out.o -O2 - version -o /tmp/ccd0gsRe.s GNU C++ version 4.0.0 20041003 (experimental) (powerpc-unknown-linux-gnu) compiled by GNU C version 4.0.0 20041003 (experimental). GGC heuristics: --param ggc-min-expand=30 --param ggc-min-heapsize=4096 as -mpower4 -maltivec -many -V -Qy -o out.o /tmp/ccd0gsRe.s GNU assembler version 2.15.90 (ppc-redhat-linux) using BFD version 2.15.90 20040225 Created attachment 7277 [details] preprocessed source Reduced to: class QString {}; class QFontDatabase { static void findFont(); static void parseFontName(const QString &name, QString &foundry, QString &family); }; static void parseFontName(const QString &name, QString &foundry, QString &family){} void QFontDatabase::findFont( ) { QString family_name, foundry_name, family; parseFontName( family, foundry_name, family_name ); } : Search converges between 2004-09-27-014001-trunk (#563) and 2004-09-27-161002-trunk (#564). Note if I change QString to be just an int, we accept the code. Confirmed, we should find the class version as we do with changing QString to be an int. Related to bug 17801 which was caused by the same patch. Doesn't koenig lookup apply? That'll pull in ::parseFontName because of ::QString I don't know but Comeau C++ online tester accepts the code. ah, [3.4.2]/2a says koenig is not done when regular lookup finds a member fn. Forgot that bit. Confirmed indeed. Here's a testcase in our usual style: --------------------- struct A {}; struct B { static void foo(); static void bar(const A &); }; void bar(const A &){} void B::foo () { A a; bar (a); } ------------------------------ g/x> /home/bangerth/bin/gcc-3.3*/bin/c++ -c x.cc g/x> /home/bangerth/bin/gcc-3.4*/bin/c++ -c x.cc x.cc: In static member function `static void B::foo()': x.cc:12: error: call of overloaded `bar(A&)' is ambiguous x.cc:5: note: candidates are: static void B::bar(const A&) x.cc:8: note: void bar(const A&) Koenig lookup should definitely _not_ find the static member since it only looks up in the _namespace_ of an argument, but shouldn't consider class scopes of arguments. W. Why shouldn't unqualified (not koenig) lookup find both versions of bar(), then? Well, yea, Nathan got me on the wrong track when mentioning Koenig. Koenig has nothing to do at all with the present problem. I simply forgot to realize that the call is from within a member function, not a global function. I don't have the right section of the standard ready, but all my instincts tell me that the call in the example is not ambiguous, but should quite unambiguously find the member function only. Note that the standard specifically says that the search for candidates ends if one or several are found in one scope from within the hierarchy of scopes that are searched sequentially. I would guess that the class scope is the first one to look at. W. 2004-10-05 Nathan Sidwell <nathan@codesourcery.com> PR c++/17829 * parser.c (cp_parser_postfix_expression): Inhibit Koenig when unqualified lookup finds a member function. we were doing koenig lookup when we shouldn't have been. Which is why changing the arg type from ::Qstring to int made it work -- that changed the set of associated namespaces from (::) to (). Subject: Bug 17829 CVSROOT: /cvs/gcc Module name: gcc Changes by: nathan@gcc.gnu.org 2004-10-05 16:08: *** Bug 17801 has been marked as a duplicate of this bug. *** Nathan, are you going to apply this to gcc-3_4-branch as well? It doesn't apply cleanly because of whitespace changes, but that's it. I've bootstrapped/regtested it on {i386,ppc,ppc64,s390,s390x}-redhat-linux, no regressions. Subject: Bug 17829 CVSROOT: /cvs/gcc Module name: gcc Branch: gcc-3_4-branch Changes by: nathan@gcc.gnu.org 2004-10-08 15:19: Fixed in GCC 3.4.3 and GCC 4.0.0. *** Bug 17904 has been marked as a duplicate of this bug. ***
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=17829
CC-MAIN-2015-18
refinedweb
861
60.21
Embedded Systems Programming Hello World for ARM - 2017 A toolchain is a collection of programming tools. It consists of a compiler, linker, assembler, and a debugger. The GNU toolchain is a programming tools produced by the GNU Project. The GNU toolchain plays a vital role in development of software for embedded systems. It can be ported to Microsoft Windows (via Cygwin and MinGW/MSYS). Quite often, the toolchain used for embedded development is a cross toolchain (cross compiler). In other words, when the host and target architectures are different, the toolchain is called a cross compiler (e.g. if we develop a code on a Linux machine based on the x64 architecture, but we're compiling for an ARM target, then we need Linux-based ARM-targeting cross compiler). This is the typical way of building embedded software. Picture source: Toolchains Before we do any cross compilation, we need to clarify the terminology. (source: - Toolchains) When talking about toolchains, one must distinguish three different machines: - the build machine, on which the toolchain is built - the host machine, on which the toolchain is executed - the target machine, for which the toolchain generates code Picture source: Programming Embedded Systems, 2nd Edition With C and GNU Development Tools By Michael Barr, Anthony Massa From these three different machines, we distinguish 3 (ARM, MIPS, or PowerPC) -. Toolchain has a name convention:arch[-vendor][-os]-abi - arch - architecture arm, mips, x86, i686, etc. - vendor - tool chain supplier - os - operating system linux, none (bare metal) - abi - application binary interface eabi, gnueabi, gnueabihf Samples: - that can be installed in Debian-based systems using a package manager like apt (the package is called gcc-arm-linux-gnueabi). This toolchain targets the ARM architecture, has no vendor, creates binaries that run on the Linux operating system, and uses the GNU EABI. In other words, it is used to target ARM-based Linux systems. - arm-linux-gcc This is actually binary for gcc which produces objects for ARM architecture to be run on Linux with default configuration (abi) provided by toolchain. - i686-unknown-linux-gnu 32-bit GNU/linux - This example is based on the code from Programming Embedded Systems, 2nd Edition With C and GNU Development Tools By Michael Barr, Anthony Massa. This is an Embedded version of Hello World. However, since in the embedded world, the display for the string "Hello World" is not easily available, we will just replace the string output with the blinking LED. #include "led.h" int main(void) { /* Configure the green LED control pin. */ ledInit( ); while (1) { /* Change the state of the green LED. */ ledToggle( ); /* Pause for 500 milliseconds. */ delay_ms(500); } return 0; } Before anything else, let's see how it works. We'll make executable first. Then, we'll sit back and check the details later. I used gcc toolchain on Ubuntu 13 and Fedora 18 targeting ARM processor. Here is the makefile. # Fedora 18 #XCC = arm-linux-gnu-gcc #LD = arm-linux-gnu-ld # Ubuntu 13 XCC = arm-linux-gnueabi-gcc LD = arm-linux-gnueabi-ld CFLAGS = -g -c -Wall -I./include LDFLAGS = -Map blink.map -T viperlite.ld -N all: blink.exe led.o: led.c led.h $(XCC) $(CFLAGS) led.c blink.o: blink.c led.h $(XCC) $(CFLAGS) blink.c blink.exe: blink.o led.o viperlite.ld $(LD) $(LDFLAGS) -o $@ led.o blink.o clean: -rm -f blink.exe *.o blink.map The files used in this example: "Embed.tar.gz": "makefile", "blink.c", "blink.map", "blink.hex", "led.c", "led.h", "viperlite.ld" and "include" where other .h files are located. Here we used arm-linux-gnu-gcc on Fedora 18 and arm-linux-gnueabi-gcc on Ubuntu 13 instead of arm-elf-gcc. They seem to be the same according to my research. (see Toolchain - Name Convention). This Blinking LED example consists of two source modules: "led.c" and "blink.c". After we made the two object files ("led.o" and "blink.o"), the GNU linker performs the linking and locating of the object files. For locating, there is a linker script file named "viperlite.ld" that we input to ld in order to establish the location of each section in the Arcom board's memory. The actual command for linking and locating is: $ arm-linux-gnu-ld -Map blink.map -T viperlite.ld -N -o blink.exe led.o blink.o If we break up the parts: - -Map blink.map To generate a map file and use the given filename Programming Embedded Systems Second Edition - -T viperlite.ld To read the linker script - -N To set the text and data sections to be readable and writable - -o blink.exe To set the output filename (if this option is not included, ld will use the default output file name a.out) The two object files ("led.o" and (blink.o") are the last arguments on the command line for linking. The linker script file, "viperlite.ld", is also passed in for locating the data and code in the our target's (Arcom board's) memory. The result of this command is the creation of two files ("blink.map" and "blink.exe") in the working directory. The ".map" file gives a complete listing of all code and data addresses for the final software image. In some cases, we might need to format the image from the build procedure for our specific target platform.One tool included with the GNU toolset that can assist with formatting images is the strip utility, which is part of the binary utilities package called binutils. The strip utility can remove particular sections from an object file. The basic command structure for the strip utility is: arm-elf-strip [options] input-file ... [-o output-file] The command used to strip symbol information is: $ arm-elf-strip --remove-section=.comment blinkdbg.exe -o blink.exe This removes the section named ".comment" from the image "blinkdbg.exe" and creates the new output file "blink.exe". There might be another time when we need an image file that can be burned into ROM or flash. The GNU toolset has just what you need for this task. The utility objcopy is able to copy the contents of one object file into another object file. The basic structure for the objcopy utility is: arm-elf-objcopy [options] input-file [output-file] Suppose we want to convert our program from ELF format into an Intel Hex Format file. The command line we use for this is: $ arm-elf-objcopy -O ihex blink.exe blink.hex This command uses the "-O" ihex option to generate an Intel Hex Format file. The input file is "blink.exe" (the objcopy utility determines the input file type). Finally, the output file is named "blink.hex". Picture source : My current embedded project's main processor - Embedded Market Study, 2013 Picture source : Which of the following 32-bit chip families would you consider for your next embedded project? - Embedded Market Study, 2013 -
http://www.bogotobogo.com/cplusplus/embeddedSystemsProgramming_gnu_toolchain_ARM_cross_compiler.php
CC-MAIN-2017-34
refinedweb
1,158
67.55
Andrew SiemerEnterprise Web Applications, ASP.NET, C#, SQL Server, Architecture, & Writing Server2009-11-11T21:49:00ZBuilding Distributed Applications in ASP.NET MVC at MvcConf 2010 on 7/22/2010<p></p> <p>Next week Thursday I will be speaking at <a href="">MvcConf</a>.  This is a virtual, free conference that has attracted some very heavy hitters MVC hitters to come and chat about their voodoo.  This should be interest sting.</p> <p><a href=""></a></p> <p>Below is the abstract and TOC for my presentation.  If you think I missed something or am watering down the presentation please feel free to contact me to give me your suggestions.</p> <h3>Abstract</h3> <p.</p> <p.</p> <h3>The map from start to finish</h3> <ol> <li>Standard MVC demo application <ol> <li>All code in a controller/action, or the view <ol> <li>Domain model </li> <li>Business logic </li> <li>Data access (LINQ to SQL) </li> </ol> </li> <li>b. Why is this bad? <ol> <li>Causes code duplication and increased complexity </li> <li>Tight coupling results in less flexible code </li> <li>No abstractions and/or leaky abstractions cause unforeseen ripple effects </li> <li>Not easily testable </li> <li>Refactoring is more difficult </li> <li>Deployment options are fairly fixed </li> <li>Versioning specific parts of the application is not easy </li> <li>Not compose-able </li> <li>Not easily distributable </li> </ol> </li> </ol> </li> <li>Separating our concerns <ol> <li>Putting code into small singularly focused classes </li> <li>Why is this better? <ol> <li>More testable </li> <li>Easier to manage </li> <li>More reusable </li> <li>Refactoring gets better </li> </ol> </li> </ol> </li> <li>Logical separation (layers) <ol> <li>Moving classes to appropriate namespaces </li> <li>Why is this better? <ol> <li>Easier to manage </li> <li>A required step to getting closer to tiers </li> </ol> </li> </ol> </li> <li>Physical separation (tiers) <ol> <li>Moving classes into appropriate physical assemblies </li> <li>Why is this better? <ol> <li>Deployment options become more flexible </li> </ol> </li> </ol> </li> <li>Refactoring for dependency injection <ol> <li>Achieving loose coupling with interfaces and constructor injection </li> <li>Why is this better <ol> <li>Loosely coupled </li> <li>More compose-able </li> <li>Easiest to test </li> </ol> </li> </ol> </li> <li>Using an IoC container for flexible composition <ol> <li>Implementing an inversion of control (IoC) container – StructureMap </li> <li>Why is this better? <ol> <li>Dynamically compose-able. </li> <li>Ultimate flexibility for the developer </li> <li>Easy to seamlessly slip in new functionality </li> <li>Capable of <i>supporting</i> distributed processing </li> </ol> </li> </ol> </li> <li>Adding a WCF service client and services to support seamless application distribution <ol> <li>Why is this better? <ol> <li>Ability to distribute specific pieces of our applications to other servers </li> <li>Supporting horizontal scalability gets easier </li> <li>Vertical scalability can be applied to areas of your application rather than being forced to beef up the entire application </li> </ol> </li> </ol> </li> </ol><img src="" width="1" height="1">asiemer MVC Cookbook – public review<p>I <a href="">Packt Publishing cookbook series</a>.  An example recipe in this book might be how to consume JSON, creating a master /details page, jquery modal popups, custom ActionResults, etc.  Basically anything recipe oriented around the topic of ASP.NET MVC might be acceptable.  </p> <p>If you are interested in helping out with the review process you can join the “ASP.NET MVC 2 Cookbook-review” group on Google here: <a title="" href=""></a></p> <p>Currently the suggested TOC for the project is listed.  Also, chapters 1, 2, and most of 8 are posted.  Chapter 5 should be available tonight or tomorrow.</p> <p).</p> <p>Thank you!</p><img src="" width="1" height="1">asiemer off C# in Depth 2nd Edition<p>If you like C# at all then you know that Jon Skeet (<a href="">writings</a>, <a href="">blog</a>, <a href="">StackOverflow</a>) is the man when it comes to this language.  Just look at his StackOverflow flair!!!  He is the top dude by a long shot in C# and has been for a long time.</p> <p><a href=""><img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="" width="229" height="75" /></a> </p> <p>His latest book “C# in Depth 2nd edition” is currently available in the Manning Early Access Program (MEAP) and ready for you to get your hands on!  </p> <p>$15 off C# in Depth 2nd edition: use code dotd0217 at checkout. <a href=""></a></p><img src="" width="1" height="1">asiemer not found: 'Void System.Web.Mvc.ViewContext..ctor(System.Web.Mvc.ControllerContext, System.Web.Mvc.IView, System.Web.Mvc.ViewDataDictionary, System.Web.Mvc.TempDataDictionary)'<p>I am finding that there are several complaints about getting Spark View Engine to work with ASP.NET MVC.  I had to tweak the Spark View Engine code base to get things running again.</p> <p>I had to download the spark view engine source code (<a href=""></a>). ): </p> <p>    public void Render(ViewContext viewContext, TextWriter writer) <br />    { <br />        var wrappedHttpContext = new HttpContextWrapper(viewContext.HttpContext, this); <br />        var wrappedViewContext = new ViewContext( <br />            new ControllerContext(wrappedHttpContext, viewContext.RouteData, viewContext.Controller), <br />            viewContext.View, <br />            viewContext.ViewData, <br />            viewContext.TempData, <br />            writer); //  <-- add the writer to the end of the list of parameters <br />        ... <br />    } </p> <p. </p><img src="" width="1" height="1">asiemer you help me formulate a TOC for an ASP.NET MVC Cookbook<p>Hey there everyone.  I was recently tasked to pitch a book to my publisher.  As a first step I need to come up with an outline for the Table of Contents.  This book is the standard cookbook style with an added focus on the MVC side of ASP.NET.  I have been poking about at other similarly styled books to get some ideas.  I think comparing ASP.NET Web Forms to ASP.NET MVC would provide some folks with a good reference point when looking at the two ways of doing things.  </p> <p>(Thanks to my friend James Shaw for this idea…made my life easier)</p> <p>Below is what I have some up with so far.  Can you please take a quick look to make sure I haven’t missed anything?  Perhaps more important than missing a topic…am I including too much?  Feel free to contact me directly with any comments at <a href="mailto:asiemer@hotmail.com">asiemer@hotmail.com</a> or leave a comment below. </p> <p>Thanks!</p> <p>1. <strong>Working with the View</strong></p> <blockquote> <p>1. Discovering the problems of a non-strongly typed view</p> </blockquote> <blockquote> <p>2. Creating a strongly typed view</p> </blockquote> <blockquote> <p>3. Working with a ViewModel</p> </blockquote> <blockquote> <p>4. How to use strongly typed input builders</p> </blockquote> <blockquote> <p>5. Create a custom input builder</p> </blockquote> <blockquote> <p>6. Consolidating view code into a partial view</p> </blockquote> <blockquote> <p>7. Using the Spark view engine</p> </blockquote> <blockquote> <p>8. Using the FubuMVC view engine</p> </blockquote> <blockquote> <p>9. Exposing a view that returns an image</p> </blockquote> <blockquote> <p>10. Creating a JSON result</p> </blockquote> <blockquote> <p>11. Consuming a JSON view</p> </blockquote> <blockquote> <p>12. Exposing a view that returns a PDF</p> </blockquote> <p>2. <strong>Actions</strong></p> <p>3. <strong>Controllers</strong></p> <p>4. <strong>Routes</strong></p> <p>5. <strong>Master Pages</strong></p> <blockquote> <p>1. How to create a master page</p> </blockquote> <blockquote> <p>2. Controlling which master page is used with a custom base page</p> </blockquote> <blockquote> <p>3. Working with Spark View Engine master pages</p> </blockquote> <p>6. <strong>Working with data in the view</strong></p> <blockquote> <p>1. Reintroducing for and foreach</p> </blockquote> <blockquote> <p>2. Displaying data from an xml file</p> </blockquote> <blockquote> <p>3. Displaying an array as a group of check boxes</p> </blockquote> <blockquote> <p>4. Displaying an array as a group of radio buttons</p> </blockquote> <blockquote> <p>5. Creating a page-able set of data</p> </blockquote> <blockquote> <p>6. How to sort data </p> </blockquote> <blockquote> <p>7. Navigating to a specific page of data</p> </blockquote> <blockquote> <p>8. Deleting a record from a data set</p> </blockquote> <blockquote> <p>9. Adding a javascript delete confirmation pop-up </p> </blockquote> <blockquote> <p>10. Adding a modal window delete confirmation pop-up</p> </blockquote> <blockquote> <p>11. Displaying a modal window to show a records details</p> </blockquote> <blockquote> <p>12. Adding a totals row to the bottom of a set of data</p> </blockquote> <blockquote> <p>13. Using the free telerik grid</p> </blockquote> <p>7. <strong>Working with Forms</strong></p> <blockquote> <p>1. Posting a form to the appropriate action</p> </blockquote> <blockquote> <p>2. Setting the field tab order</p> </blockquote> <blockquote> <p>3. Setting a default button</p> </blockquote> <p>8. <strong>MVC and templating</strong></p> <blockquote> <p>1. Plugging in a new skin from the template gallery</p> </blockquote> <blockquote> <p>2. Using T4 to create strongly typed helpers</p> </blockquote> <blockquote> <p>3. Using T4MVC to destroy magic strings</p> </blockquote> <blockquote> <p>4. Creating a view template</p> </blockquote> <p>9. <strong>Validation Recipes</strong></p> <blockquote> <p>1. Validating with Data Annotation Validators</p> </blockquote> <blockquote> <p>2. Reporting validation errors with ViewData.ModelState</p> </blockquote> <blockquote> <p>3. Using Html.ValidationMessage to display validation errors</p> </blockquote> <blockquote> <p>4. Summarizing validation errors with Html.ValidationSummary</p> </blockquote> <blockquote> <p>5. Using the xVal validation framework</p> </blockquote> <blockquote> <p>6. Using Castle Validator for validation</p> </blockquote> <blockquote> <p>7. Client side validation with JQuery Validation</p> </blockquote> <blockquote> <p>8. Making a required field</p> </blockquote> <blockquote> <p>9. Setting an acceptable range</p> </blockquote> <blockquote> <p>10. Requiring the password and password verification fields to match</p> </blockquote> <blockquote> <p>11. Using a regex pattern to validate data</p> </blockquote> <blockquote> <p>12. Forcing a choice to be made in a drop down menu</p> </blockquote> <p>10. <strong>Managing large applications with Areas</strong></p> <blockquote> <p>1. Creating a separate project as an area</p> </blockquote> <blockquote> <p>2. Creating an area in the same project</p> </blockquote> <blockquote> <p>3. Using areas to manage segments of your site</p> </blockquote> <blockquote> <p>4. Creating portable areas to compartmentalize functionality</p> </blockquote> <p>11.<strong> Maintaining state</strong></p> <blockquote> <p>1. Working with application wide information</p> </blockquote> <blockquote> <p>2. Maintaining a user’s information during their session</p> </blockquote> <blockquote> <p>3. Using cookies to remember a user</p> </blockquote> <blockquote> <p>4. Managing state in a web farm scenario using SQL Server</p> </blockquote> <p>12. <strong>Error Handling</strong></p> <blockquote> <p>1. Handling errors in your code</p> </blockquote> <blockquote> <p>2. Handling errors for a view</p> </blockquote> <blockquote> <p>3. Handling errors in your application</p> </blockquote> <blockquote> <p>4. Showing friendly error information</p> </blockquote> <blockquote> <p>5. Using Error Logging Modules and Handlers (ELMAH) to deal with unhandled exceptions</p> </blockquote> <blockquote> <p>6. Reporting caught exceptions to ELMAH</p> </blockquote> <p>13.<strong> Security</strong></p> <blockquote> <p>1. Using membership and roles to manage users</p> </blockquote> <blockquote> <p>2. Using windows authentication</p> </blockquote> <blockquote> <p>3. Restricting access to all pages</p> </blockquote> <blockquote> <p>4. Restricting access to selected pages</p> </blockquote> <blockquote> <p>5. Restricting access to pages by role</p> </blockquote> <blockquote> <p>6. Restricting access to a controller</p> </blockquote> <blockquote> <p>7. Restricting access to a selected area</p> </blockquote> <p>14. <strong>Profiles and Themes</strong></p> <blockquote> <p>1. Using profiles</p> </blockquote> <blockquote> <p>2. Inheriting a profile</p> </blockquote> <blockquote> <p>3. Using an migrating anonymous profiles</p> </blockquote> <blockquote> <p>4. Managing user profiles</p> </blockquote> <blockquote> <p>5. Using themes</p> </blockquote> <blockquote> <p>6. User personalized themes</p> </blockquote> <p>15. <strong>Configuration</strong></p> <blockquote> <p>1. Adding custom application settings in web.config</p> </blockquote> <blockquote> <p>2. Displaying custom error messages</p> </blockquote> <blockquote> <p>3. Maintaining session state across multiple web servers</p> </blockquote> <blockquote> <p>4. Accessing other web.config configuration elements</p> </blockquote> <blockquote> <p>5. Adding your own configuration elements to web.config</p> </blockquote> <blockquote> <p>6. Encrypting web.config sections</p> </blockquote> <p>16. <strong>Tracing and Debugging</strong></p> <blockquote> <p>1. Uncovering page level problems</p> </blockquote> <blockquote> <p>2. Uncovering application wide problems</p> </blockquote> <blockquote> <p>3. Writing trace data to the event log</p> </blockquote> <blockquote> <p>4. Sending trace data via email</p> </blockquote> <blockquote> <p>5. Using a breakpoint to stop execution of an application when a condition is met</p> </blockquote> <p>17. <strong>Caching</strong></p> <blockquote> <p>1. Caching a whole page</p> </blockquote> <blockquote> <p>2. Caching pages based on route details</p> </blockquote> <blockquote> <p>3. Caching pages based on browser type and version</p> </blockquote> <blockquote> <p>4. Caching pages based on developer defined custom strings</p> </blockquote> <blockquote> <p>5. Caching partial pages</p> </blockquote> <blockquote> <p>6. Caching application data</p> </blockquote> <blockquote> <p>7. Caching object data</p> </blockquote> <blockquote> <p>8. Installing MemCached Win32 as an alternate cache provider</p> </blockquote> <blockquote> <p>9. Using the MemCached Enyim client to cache application data</p> </blockquote> <blockquote> <p>10. Installing Microsoft Velocity</p> </blockquote> <blockquote> <p>11. Using Velocity to cache application data</p> </blockquote> <p>18. <strong>Localizing your application</strong></p> <blockquote> <p>1. Providing multiple language support</p> </blockquote> <blockquote> <p>2. Using resource files to manage display data</p> </blockquote> <blockquote> <p>3. Managing currency display based on selected language</p> </blockquote> <p>19. <strong>HTTP Handlers and Modules</strong></p> <blockquote> <p>1. Tracking access to your resources with an HTTP Handler</p> </blockquote> <blockquote> <p>2. Create a file download HTTP Handler</p> </blockquote> <blockquote> <p>3. Control leeching of your resources with an HTTP Module</p> </blockquote> <p>20. <strong>Making ASP.NET even more powerful</strong></p> <blockquote> <p>1. Making controllers testable by implementing a ControllerFactory</p> </blockquote> <blockquote> <p>2. Implementing inversion of control with StructureMap</p> </blockquote> <blockquote> <p>3. Install MVC Turbine and write less code</p> </blockquote> <blockquote> <p>4. Creating testable views</p> </blockquote> <blockquote> <p>5. Creating testable controllers</p></blockquote><img src="" width="1" height="1">asiemer a virtual .net users group<p>Hey all!  I am finally going to put my full steam into setting up my <a href="">VirtualDNUG</a> users group.  With the help of the good folks over at <a href="">ineta</a> .</p> <p>If you are interested in attending our initial meetings, would like to present, or have a topic that you would like to be covered, please contact me directly at <a href="mailto:asiemer@hotmail.com">asiemer@hotmail.com</a>.</p><img src="" width="1" height="1">asiemer MVC 2 in Action conducting a public review<p>Since I enjoyed the first edition of the ASP.NET MVC in Action book I figured I would jump on this second edition of this book and framework as quickly as I could.  I just read this post from Jeffrey Palermo:</p> <p><a href=""></a></p> <p>Which basically states that they are actively working on the next edition of the book.  More importantly, the chapters that they have completed so far are in a publicly viewable location: <a href=""></a></p> <p><strong>Here is a re-post of Jeffrey’s original post:</strong></p> <p>If you’d like to get an early glimpse of ASP.NET MVC 2 in Action, you can participate on the public email list at<a href=""></a>.  The first bit of the manuscript is ready to review, and it consists of <a href="">chapter 23, Data Access with NHibernate</a>.  You can also access every bit of code, text, and image at the book’s <a href="">GitHub repository</a>.  With the first book, <a href="">ASP.NET MVC in Action</a>, Manning conducted an Early Access Program (MEAP).  Manning will still conduct it, but our program is a early, early access program.  In other words, you can have access to the unedited, perhaps dirty, manuscript and help as it drives forward to polish and completion.</p> <p.</p> <p>Our hope is that this book serves the .Net community that is working ASP.NET MVC 1 and ASP.NET MVC 2 applications.</p> <p>The author team consists of:</p> <ul> <li><a href="">Jeffrey Palermo</a> </li> <li><a href="">Ben Scheirman</a> </li> <li><a href="">Jimmy Bogard</a> </li> <li><a href="">Eric Hexter</a> </li> <li><a href="">Matt Hinze</a> </li> </ul> <p>If this book project interests you, and if you know people who should be involved, please blog, tweet, and otherwise post a link to this announcement.</p><img src="" width="1" height="1">asiemer article just submitted to DotNetSlackers.com<p>I.  </p> <p.</p><img src="" width="1" height="1">asiemer on a Page<p>Some!</p> <p><a href=""><img title="image" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="388" alt="image" src="" width="500" border="0" /></a></p> <p>Scrum on a Page describes most of the really important details about Scrum, who is involved, the meetings, and what the process is.  This is a good doc to have if you are just now learning Scrum.  Please feel free to make suggestions if you like.</p><img src="" width="1" height="1">asiemer review: Brownfield Application Development in .NET<p>The first question you may have in reading the title to this post is what is a Brownfield application?  The book opens up a discussion on this topic with this opening line:</p> <blockquote style="width:381px;height:5.04%;"> <p>“An industrial Brownfield is a commercial site contaminated by hazardous waste that has the potential to be reused once it’s cleaned up.  To a software developer, a Brownfield Application is an existing project, or codebase, that may be contaminated by poor practices, structure, and design but which has the potential to be revived through comprehensive and directed refactoring.”</p> </blockquote> <p>I was able to review the book “<a target="_blank">Brownfield Application Development in .NET</a>” very early on in it’s creation.  I am now the technical reviewer for the final stretch of this project.  </p> <p>I have to say up front that I never considered myself a Brownfield application enthusiast in the least!  I didn’t really even know that a Brownfield application as defined above actually had a name other than FUBAR.  And to be quite honest the whole concept of a Brownfield applications is something that I have always tried to avoid.  However, after having read this book a few times I must say that while I don’t consider myself a Brownfield developer I think we all come across them and interact with them more often than we might think.  While not wanting to identify with the Brownfield developer myself…I have to swallow the lump at the back of my throat and admit that we are all Brownfield developers from time to time during our careers.</p> <p>We have all heard the expression that code not under test is legacy code and have all worked on code bases without tests.  </p> <p>We have all probably been to a dev shop that didn’t have proper source control.</p> <p>We have all seen deployment processes that require all hands to be on deck in the wee hours of the night to push and pull and tweak the code through to production.</p> <p>If any of these statements ring a bell with you (and probably many other examples as well) then you have been involved with a so-called Brownfield project.  </p> <p>If you are anything like me, you probably show up to the first day of work at a new contract and find at least one “are you serious?” feature of your new work environment in the first 30 minutes to an hour…with many more that follow closely behind.  If you are anything like me you see problems…sure…but you also know that there is a better solution or an industry standard way of dealing with each and every one of those problems.</p> <p>This book does a great job of not only laying out a road map for locating each of the various types of pain points offered by a Brownfield application but it also does a great job of suggesting how to deal with each of those pain points.  And while the book is entitled “Brownfield Application Development in .NET”, don’t think that this book only deals with the technical side of this problem.  It does a great job of covering all the aspects of these sorts of problematic applications and the culture and company that is ultimately responsible for allowing them to be created in the first place.  </p> <p>This book offers up ways to deal with some of the political aspects of fixing this type of application.  It provides suggestions for how to deal with the people on these types of projects.  Rules around broken builds are provided.  A definition of what a “check in dance” is and how it changes when an additional feature is added to the big picture.  And of course many of the tools that are out there to deal with these sorts of problems are covered too.</p> <p>Here is a great blurb from the book:</p> <blockquote style="width:381px;height:0%;"> <p>“Maintenance of the application does not begin once it has been released into production.  From a developer’s perspective, each line of code you write enters maintenance mode immediately after it is written.”</p> </blockquote> <p>And then you have lines such as this:</p> <blockquote style="width:381px;height:0%;"> <p>“Then words like “spaghetti” and “minefield” start to enter the project’s lexicon.”</p> </blockquote> <p>Whether this topic is old hat to you, or something that you have never thought of I find that this book is very easy to read and quite clear when making it’s points.  I will share more as I read more.  I really can’t wait for this book to be published.  I think that this is going to be one of those books that every developer and software shop should own.  It clearly defines what should be required by our industry…but rarely is.</p><img src="" width="1" height="1">asiemer Lozano’s interview for DotNetRadio is now available!<p>Hey all.  Just wanted to let you know that the interview that I did with <a href="" target="_blank">Javier Lozano</a> (lozanotek.com) is now available on <a href="" target="_blank">DotNetRadio</a>!  This was a pretty hefty interview so I had to cut it in half.  In the first half of the interview we discussed the following points.</p> <li>How and why was ASP.NET MVC created? </li> <li>What are the pain points of ASP.NET Webforms? </li> <li>What can a WebForms developer expect when moving to ASP.NET MVC? </li> <li>MVC is like BizTalk – it can do anything – it just can’t do anything out of the box! </li> <li>What did ASP.NET MVC get right…what did it get wrong? </li> <li>What are the differences between WebForms and MVC with regards to saving state and workflow? </li> <li>What sort of validation is provided with MVC 1 or MVC2? </li> <li>What is a strongly typed view and how does that work? </li> <li>Creating strongly typed views and why that is important </li> <li>What is the difference between a Model and a ViewModel and why would a developer want to use that? </li> <li>What does the term “magic string” mean and why is that bad? </li> <li>How do magic strings relate to MVC 1, MVC 2, and what tools are provided by MVC Contrib to help remove magic strings from an MVC application? </li> <li>What are MVC Contrib Input Builders and how do those work? </li> <li>How would you use templating in ASP.NET MVC? </li> <li>How does Dynamic Data work in ASP.NET MVC? </li> <li>How do you create inject-able controllers via an MVC Contrib Controller Factory? </li> <li>Using inversion of control containers in the MVC framework </li> <li>What is painful about the WebForms view engine used in ASP.NET MVC? </li> <li>Why are there so many view engines available for MVC? </li> <li>How does nVelocity make working in the View easier? </li> <li>Why are code behind files the ultimate evil? </li> <li>How is the workflow different in the WebForms view engine compared to other MVC view engines such as SPARK or nVelocity? <p><a href="" target="_blank">Subscribe to the podcast!</a></p> <p>Please feel free to let me know if you have any feedback.  In the next post I will put up the second half of Javier Lozano’s.  And after that I will post the <a href="" target="_blank">Sara Chipps</a> interview!</p> <p>Upcoming interviews will include include Jeffrey Palermo, Ayende Rahien, Gil Zilberfeld, Bill Pringle, Patrick Smacchia, Scott Belware, and many more!  Stay tuned.</p> <p>Follow me on Twitter at <a href="" target="_blank">@asiemer</a> and follow the show at <a href="" target="_blank">@dnetradio</a>.</p> <p></p> <p></p> </li><img src="" width="1" height="1">asiemer in questions for upcoming guests and get DotNetRadio SWAG<p><strong>Gil Zilberfeld from TypeMock:</strong> As you may know by now (from my tweeting or by looking on the <a href="" target="_blank">DotNetRadio</a>! </p> <p><strong>Jeffrey Palermo from Headspring Systems:</strong> What you may not know is that I am scheduling an interview (possibly tomorrow) with Jeffrey Palermo from Headspring Systems (creator of <a href="" target="_blank">MVC Contrib</a> and author of ASP.NET MVC in Action).  We will be discussing MVC Contrib and application architecture using that project.  Send your questions for him soon as that interview may be taking place as early as tomorrow evening if things work out.</p> <p><strong>Feedback:</strong> In addition to sending in questions, please also send in your feedback.  As this is a new podcast I am testing out the show format, music, ad spaces, etc.  If you have any feedback, good or bad, please send it to me at <a href="mailto:podcast@dotnetradio.com">podcast@dotnetradio.com</a>.</p> <p><strong>Guest Ideas?</strong>  <a href="mailto:podcast@dotnetradio.com">podcast@dotnetradio.com</a>! </p><img src="" width="1" height="1">asiemer - Podcast #2 – interview with Atif Aziz creator of ELMAH<p><span style="font-size:medium;font-family:'Times New Roman';"></span> <div style="font-size:85%;margin:10px;color:#000000;font-family:arial, helvetica, sans-serif;background-color:#ffffff;-webkit-background-clip:initial;-webkit-background-origin:initial;"> <p><span style="font-size:medium;font-family:'Times New Roman';"></span> <div style="font-size:85%;margin:10px;color:#000000;font-family:arial, helvetica, sans-serif;background-color:#ffffff;-webkit-background-clip:initial;-webkit-background-origin:initial;"> <p <a href="">through his web site</a>. You can find out more about Atif Aziz by visiting his web site <a href=""></a>.</p> <ul> <li><a href="">Raboof.com</a> = FooBar!! </li> <li>Atif describes to us what <a href="">ELMAH</a> is and the history behind it. He then goes into detail as to how to get ELMAH installed and running. Atif then outlines the types of storage that are supported and how to implement a custom storage provider. Next we get into how ELMAH handles exceptions, how it works with the .NET runtime, and what the appropriate way to handle exceptions with ELMAH is. He then gets into the details of how to signal ELMAH about exceptions that occur as the filtering that ELMAH provides. </li> <li><a href="">OrbitOne ASP.NET Exception Reporting</a> (based on ELMAH) – a good example of centralized exception logging and extending ELMAH </li> <li><a href="">ELMAH has earned Veracode Application Security rating</a> and has earned OWASP top 10 and SANS-CWE top 25 placements </li> <li>What is <a href="">Fizzler</a>? A .NET based CSS selector built on top of HTML Agility Pack to parse nodes of HTML by CSS selector. Using LINQ with Fizzler. How does jQuery (client side selector) compare to Fizzler? How is Fizzler able to select out nodes, make changes, and put those changes back? Fizzler and <a href="">HTML Agility Pack</a> is very powerful when paired together for parsing and modifying HTML nodes </li> <li>How does <a href="">Jayrock</a> fit into a web developers world? Jayrock is an easy to use way for JavaScript to communicate with back end web services using JSON as the wire format and JSON-RPC as the procedure invocation protocol. Jayrock can generate the client code that is needed for you. Jayrock works with .NET 1.0!! Jayrock is considerably easier to use compared with WCF. Jayrock follows the Duct Tape Programmer mentality of simple and easy to use with rock solid stability </li> <li><a href="">BackLINQ</a> "was a pretty bad start" ...but a good story </li> <li><a href="">LINQBridge</a> provides LINQ capabilities to .NET 2.0 framework </li> <li>Unit testing is awesome…but not worth updating older codebases that are based on infrastructure </li> <li><a href="">MoreLINQ</a>, by <a href="">Jon Skeet, StackOverflow super star</a>, and author of <a href="">C# in Depth</a>. MoreLINQ provides 22 additional really useful LINQ methods such as Zip(), ToDelimitedString(), TakeLast(), etc. </li> <li>Open Source works when everyone contributes little bits, be it code, documentation, writing blog posts and articles, etc. </li> </ul> <p><b>Send me your questions and comments!</b>  <br />If you would like to submit a question to be answered in the next show, please record an audio file and email it to podcast@dotnetradio.com. All you need is a telephone! Call (646) 200-0000, talk, then navigate to<a href=""></a> to retrieve your recording. Then send it my way.</p> <p></p> </div></p><img src="" width="1" height="1">asiemer has been more fun than I had anticipated<p>Going.</p> <p>So far I have interviewed <a href="" target="_blank">Ben Schierman</a>, <a href="" target="_blank">Javier Lozano</a>, <a href="" target="_blank">Atif Aziz</a>, and <a href="" target="_blank">Sara Chipps</a> (in that order).  </p> <p>Ben’s interview, which largely discussed ASP.NET MVC and surrounding technologies, <a href="" target="_blank">is already posted</a>.  </p> <p>I just finished the rough edit of Atif’s interview which was fantastic (he is reviewing that now).  He has a wealth of untapped knowledge that would take several interviews to get out of him.  We discussed some of his open source projects which touched <a href="" target="_blank">ELMAH</a>, <a href="" target="_blank">Fizzler</a>, <a href="" target="_blank">Jayrock</a>, <a href="" target="_blank">LINQBridge</a>, <a href="" target="_blank">BackLINQ</a>, and <a href="" target="_blank">MoreLINQ</a> among many other interesting things. </p> <p>The next interview I will be posting will be the interview I had with Javier Lozano.   That interview took us through quite a few details of the ASP.NET MVC framework.  We discussed the existing MVC framework, new features of <a href="" target="_blank">ASP.NET MVC 2 (preview 2)</a>, the <a href="" target="_blank">MVC Contrib</a>, Javier’s <a href="" target="_blank">MVC Turbine</a> project (which is awesome),  the MVC controls provider by such vendors as as <a href="" target="_blank">Telerik</a> and <a href="" target="_blank">Syncfusion</a>, followed by a quick discussion of the Community for MVC (<a href="" target="_blank">C4MVC</a>) which I personally attended this last time around and loved!  C4MVC is a must for any MVC developer.  </p> <p>Then earlier this week I had a chance to speak with Sara Chipps from GirlDeveloper.com.  Sara covered ideas about how to make personal projects a reality.  We discussed her personal project <a href="" target="_blank">bundl.it< <a href="" target="_blank">tinychat.com<!</p> <p>If you are waiting for the next interview, watch for my tweet from <a href="" target="_blank">@dnetradio</a> tonight.  I will be posting Atif Aziz’s interview later this evening.</p><img src="" width="1" height="1">asiemer Sara J Chipps 11 Nov 2009 (tomorrow) at 7am<div style="float:right;"> </div> <div>Hey all. I wanted to let you know that I am going to be interviewing Sara J Chipps (of <a href=""></a>) tomorrow at 7am. We will be discussing all sorts of programmer goodness from making your personal projects a reality (such as Sara’s <a href=""></a> project), agile development, commenting your code, and your responsibility as a developer to the next person reading your code. We will also be looking at jQuery, asynchronous processes, and architecting for speed and scalability. And of course, being that we are talking with a …or “THE”… girl developer we will also touch upon what it is like to be a lady working in mostly male dominated industry.</div> <p><strong>Send in your questions and comments!</strong></p> <p>If you have any questions for Sara prior to the interview or during it please twitter your question my way and include #DNetRadio in your post. </p> <p>You can also record an audio file and email it to <a href="mailto:podcast@dotnetradio.com">podcast@dotnetradio.com</a>. All you need is a telephone! Call (646) 200-0000, talk, then navigate to <a href=""></a> to retrieve your recording. Then send it my way!</p> <p> </p> <p> </p> <div style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:a2ffe593-6fb6-46e8-ba46-355b3b3c7cbf" class="wlWriterEditableSmartContent">Technorati Tags: <a rel="tag" href="">Sara J Chipps</a></div><img src="" width="1" height="1">asiemer
http://dotnetslackers.com/Community/blogs/asiemer/atom.aspx
crawl-003
refinedweb
5,828
57.67
. C# Generics Declaration To define a class or method as generic, then we need to use a type parameter as a placeholder with an angle (<>) brackets. public class GenericClass<T> { public T message; public void genericMethod(T studentname, T Address) { Console.WriteLine("{0}", message); Console.WriteLine("Name: {0}", studentname); Console.WriteLine("Location: {0}", Address); } } If you see above class, we created a class (GenericClass) with one parameter (message) and method (genericMethod) using type parameter (T) as placeholder with an angle (<>) brackets. Here, the angle (<>) brackets will indicate a GenericClass is generic and type parameter (T) is used to accept a requested type. The type parameter name can be anything like X or U or etc. based on our requirements. Generally, while creating an instance of class we need to specify an actual type, then the compiler will replace all the type parameters such as T or U or X, etc. with specified actual type. In c#, following is the example of creating an instance of generic class. GenericClass<string> generic= new GenericClass<string>(); generic.message = "Generic in C#"; generic.genericMethod("Code Hunger", "India");
https://blog.codehunger.in/generic-in-c/
CC-MAIN-2021-43
refinedweb
183
50.73
martin 99/12/01 12:55:08 Modified: src CHANGES src/main util.c Log: EBCDIC: Escaped characters in c2x() were encoding the EBCDIC representation of the special characters, not the latin1 representation. This would result in invalid URI references for, e.g., filenames generated by mod_autoindex.c (when they had special chars in them) Revision Changes Path 1.1467 +5 -0 apache-1.3/src/CHANGES Index: CHANGES =================================================================== RCS file: /export/home/cvs/apache-1.3/src/CHANGES,v retrieving revision 1.1466 retrieving revision 1.1467 diff -u -r1.1466 -r1.1467 --- CHANGES 1999/12/01 20:45:29 1.1466 +++ CHANGES 1999/12/01 20:54:55 1.1467 @@ -1,5 +1,10 @@ Changes with Apache 1.3.10 + *) EBCDIC: Escaped characters were encoding the ebcdic representation + of the special characters, not the latin1 representation. This + would result in invalid URI's for, e.g., filenames (with special chars) + in mod_autoindex.c [Martin Kraemer] + *) EBCDIC: Fix Byte Ranges for EBCDIC platforms. The necessary switch between implied conversion for protocol parts and configured conversion for document data was missing. The effect of this was that 1.175 +3 -0 apache-1.3/src/main/util.c Index: util.c =================================================================== RCS file: /export/home/cvs/apache-1.3/src/main/util.c,v retrieving revision 1.174 retrieving revision 1.175 diff -u -r1.174 -r1.175 --- util.c 1999/11/26 20:21:18 1.174 +++ util.c 1999/12/01 20:55:03 1.175 @@ -1481,6 +1481,9 @@ static ap_inline unsigned char *c2x(unsigned what, unsigned char *where) { +#ifdef CHARSET_EBCDIC + what = os_toascii[what]; +#endif /*CHARSET_EBCDIC*/ *where++ = '%'; *where++ = c2x_table[what >> 4]; *where++ = c2x_table[what & 0xf];
http://mail-archives.apache.org/mod_mbox/httpd-cvs/199912.mbox/%3C19991201205509.14052.qmail@hyperreal.org%3E
CC-MAIN-2017-04
refinedweb
278
55.91
Recently, I have been experimenting with different approaches for building vanilla JavaScript apps. And I got the idea to recreate basic React functionality in order to get a similar workflow as in React. This would enable me to keep the benefits of vanilla JavaScript while having the structure of React apps. It would also make it easy to migrate code into React if the app grows. By the end of this post, I will show you how to make a counter component with code that looks almost identical to React code, without using any React. As can be seen here:; You can find the repository here. Setup The first thing that I did was that I installed webpack and typescript. The main reason why I'm using typescript is because it makes it easy to use jsx, otherwise it's not mandatory. The same could likely be done with babel as well. After a standard webpack and typescript installation, I installed typed-html npm install --save typed-html. This is a package that lets us use jsx inside of typescript tsx files. After it was installed, I added the following lines into the typescript config file. { "compilerOptions": { "jsx": "react", "jsxFactory": "elements.createElement", } } This factory comes with some limitations. <foo></foo>; // => Error: Property 'foo' does not exist on type 'JSX.IntrinsicElements'. <a foo="bar"></a>; // => Error: Property 'foo' does not exist on type 'HtmlAnchorTag' We can't use props and components like we usually would in React, instead, a component will be a function call and the function arguments will be props. Now, what does the jsx factory even do? It transpiles the jsx into a string. That works for me, because I wanted to do the rending with a simple .innerHTML. But if you want to get some other kind of output, you could use some other factory or even make your own. You could also avoid using jsx and just use template literals instead. Before I started coding I also had to create an index.html file. /public/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <title>App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="bundle.js"></script> </body> </html> Rendering Now that everything was set up, it was time to dive into JavaScript. First I made a file called notReact.ts and put it inside of the /src folder. This file is where all of the rendering and state logic was located in. First I made a function closure and put two functions inside of it. One for initialization and one for rendering. export const notReact = (function() { let _root: Element; let _templateCallback: ITemplateCallback; function init(rootElement: Element, templateCallback: ITemplateCallback) { _root = rootElement; _templateCallback = templateCallback; render(); } function render() { _root.innerHTML = _templateCallback(); } return {init, render}; })(); type ITemplateCallback = { (): string; } init() has two arguments, a root element that will be used as a template container and a callback function that returns a string, containing all of the html. The render() function calls the template callback and assigns it to the .innerHTML of the root element. Next, I made the index.ts and the App.tsx file and put both of them inside of the /src folder. Then I initialized the rendering and called the App component inside of the index.ts file. import App from "./App"; import { notReact } from "./notReact"; const render = () => { const root = document.getElementById('root'); notReact.init(root, App); } window.addEventListener("DOMContentLoaded", () => render()); Inside of the App component I wrote a simple "Hello world". import * as elements from 'typed-html'; const App = () => { return ( <h1> Hello world; </h1> ); } export default App; State and event listeners Now that the rendering was done, it was time to write the useState hook, while also creating a basic counter application to test it out. First I created another component called Counter.tsx and put it inside of the components folder. I wrote it the same way it would be written in regular React, with the exception of the onClick event that I omitted for now. import * as elements from 'typed-html'; import { notReact } from '../notReact'; const Counter = () => { const [count, setCount] = notReact.useState(0); const increaseCounter = () => { setCount(count+1); } return ( <div> <h1>Counter: {count}</h1> <button>Increase count</button> </div> ); } export default Counter; After that, I had to change the App component: import * as elements from 'typed-html'; import Counter from './components/Counter'; const App = () => { return ( <div> {Counter()} </div> ); } export default App; With everything being ready, it was time to write the useState hook. export const notReact = (function() { let hooks: Array<any> = []; let idx: number = 0; function useState(initValue: any) { let state; state = hooks[idx] !== undefined ? hooks[idx] : initValue; const _idx = idx; const setState = (newValue: any) => { hooks[_idx] = newValue; render(); } idx++; return [state, setState]; } function render() { idx=0; //resets on rerender ... } return {useState, init, render}; })(); There are two local variables. An array variable called hooks that contains all of the state values. And the idx variable which is the index used to iterate over the hooks array. Inside of the useState() function, a state value together with a setter function get returned for each useState() call. Now we have a working useState hook, but we can't test it out yet. We need to add an onclick event listener to the button first. The problem here is that if we add it directly into the jsx, the function will be undefined because of the way the html is being rendered here. To fix this, I had to update the notReact.ts file again. export const notReact = (function() { const _eventArray: IEventArray = []; function render() { _eventArray.length = 0; //the array gets emptied on rerender ... document.addEventListener('click', (e) => handleEventListeners(e)); function handleEventListeners(e: any) { _eventArray.forEach((target: any) => { if (e.target.id === target.id) { e.preventDefault(); target.callback(); } }); } function addOnClick(id: string, callback: any) { _eventArray.push({id, callback}); } return {useState, useEffect, init, render, addOnClick}; })(); type IEventArray = [{id: string, callback: any}] | Array<any>; I made a local variable named eventArray. It's an array of objects, containing all elements that have an onclick event, together with a callback function for each of those events. The document has an onclick event listener. On each click it checks if the target element is equal to one of the event array elements. If it is, it fires it's callback function. Now let's update the Counter component so that the button has an onclick event: const Counter = () => { ... notReact.addOnClick("increaseCount", increaseCounter); ... return ( <div> <h1>Counter: {count}</h1> <button id="increaseCount">Increase count</button> </div> ); } Here is the result so far: Side effects The last thing that I added was the useEffect hook. Here is the code: export const notReact = (function() { let hooks: Array<any> = []; let idx: number = 0; function useEffect(callback: any, dependancyArray: Array<any>) { const oldDependancies = hooks[idx]; let hasChanged = true; if (oldDependancies) { hasChanged = dependancyArray.some((dep, i) => !Object.is(dep, oldDependancies[i])); } hooks[idx] = dependancyArray; idx++; if (hasChanged) callback(); } return {useState, useEffect, init, render, addOnClick}; })(); It saves dependancies from the last render and checks if they changed. If they did change the callback function gets called. Lets try it in action! I added a message bellow the button that changes if the counter gets higher than 5. Here is the final counter Component code:; Conclusion This is it! The component is looking a lot like actual React now. Changing it for React would be trivial, the only thing that would need to be changed is the onclick event and the imports. If you enjoy working in React, an approach like this might be worth trying out. Just keep in mind that this code is proof of concept, it isn't very tested and there are definitely a lot of bugs, especially when there are a lot of different states. The code has a lot of room for improvement and expansion. It's not a lot of code though, so it would be easy to change it based on your project requirements. For a more serious application, you would most likely have to implement some sort of event loop that would synchronize the state changes. I didn't go very in depth about my implementation of the useState and useEffect hooks. But if you want more details, you can check out this talk, it's what inspired my implementation. Again, all of the code can be found in this repository. Thank you for reading! 😁 Discussion (0)
https://dev.to/maturc/recreating-the-react-workflow-in-vanilla-javascript-449c
CC-MAIN-2022-21
refinedweb
1,417
56.86
Version: (using KDE KDE 3.3.91) Installed from: Slackware Packages I use a lot the drag'n drop between konqueror and konsole, especially the "cd" option but with the new media:/ io-slave the path dropped on konsole of course is not a valid unix pathname, but that media:/ url correspond to a real pathname so it wouldn't be possible to convert the url into the corresponding pathname when dropped on apps that doesn't know about kio? SVN commit 418162 by hindenburg: Use mostLocalURL on dropped URLs, helpful for media:/. BUG: 98879 M +2 -1 TEWidget.cpp --- trunk/KDE/kdebase/konsole/konsole/TEWidget.cpp #418161:418162 @@ -73,6 +73,7 @@ #include <kglobalsettings.h> #include <kshortcut.h> #include <kurldrag.h> +#include <kio/netaccess.h> #include <qlabel.h> #include <qtimer.h> @@ -2148,7 +2149,7 @@ dropText += " "; m_drop->setItemEnabled(cd,false); } - KURL url = *it; + KURL url = KIO::NetAccess::mostLocalURL( *it, 0 ); QString tmp; if (url.isLocalFile()) { tmp = url.path(); // local URL : remove protocol. This helps "ln" & "cd" and doesn't harm the others In kde 3.4.1 debian, it isn't resolved. It fails, and not paste the correct path. It paste " kfmclient copy 'media:/hdd' . " and if you use F4 key in konqueror to open a konsole in a media:/ path, it open your HOME directory because it doesn't know media:/ path The fix isn't in KDE 3.4.1. KIO::NetAccess::mostLocalURL was added for KDE 3.5. Hence this can't be back-ported to 3.4.x. Kurt: you can KIO::stat and check if a UDS_LOCAL_PATH (= 72 | UDS_STRING) was returned. You won't have the constant, though, so you'll have to go with the value.
https://bugs.kde.org/show_bug.cgi?id=98879
CC-MAIN-2022-27
refinedweb
284
69.18
QComboBox and HeaderItem Dear all, I have a QComboBox with a QStandardItemModel, which contains a single item named "One". I want the QComboBox to have an header (I'm not sure this is the correct technical term ...) which will always be the same. [1] To be more precise, running the code below leads to the following output: "One" (as the header) + "One" (with a checkbox). [2] What I'm looking for is as follows: "Header" (as the header) + "One" (with a checkbox). I tried the function "model.setHorizontalHeaderItem()" but it leads to the same as [1] above. Please, help me. @#include <QApplication> #include <QComboBox> #include <QStandardItemModel> int main( int argc, char **argv ) { QApplication app( argc, argv ); QComboBox* comboBox = new QComboBox(); QStandardItemModel model( 1, 1 ); QStandardItem *item = new QStandardItem( QString("One") ); item->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled ); item->setData ( Qt::Unchecked, Qt::CheckStateRole ); model.setItem(0, 0, item); model.setHorizontalHeaderItem( 0, new QStandardItem( "Header" ) ); comboBox->setModel( &model ); comboBox->show(); return app.exec(); }@ See QComboBox::setView , QComboBox uses QListWidget as view by default and there's no header. Set QTreeWidget as QComboBox view and there you can set header.
https://forum.qt.io/topic/47368/qcombobox-and-headeritem
CC-MAIN-2017-34
refinedweb
187
58.28
An implicit question to newcomers to Scala seems to be: where does the compiler look for implicits? I mean implicit because the question never seems to get fully formed, as if there weren’t words for it. :-) For example, where do the values for integral below come from? scala> import scala.math._ import scala.math._ scala> def foo[T](t: T)(implicit integral: Integral[T]) {println(integral)} foo: [T](t: T)(implicit integral: scala.math.Integral[T])Unit scala> foo(0) scala.math.Numeric$IntIsIntegral$@3dbea611 scala> foo(0L) scala.math.Numeric$LongIsIntegral$@48c610af Another question that does follow up to those who decide to learn the answer to the first question is how does the compiler choose which implicit to use, in certain situations of apparent ambiguity (but that compile anyway)? For instance, scala.Predef defines two conversions from String: one to WrappedString and another to StringOps. Both classes, however, share a lot of methods, so why doesn’t Scala complain about ambiguity when, say, calling map? Note: this question was inspired by this other question on Stack Overflow, but stating the problem in more general terms. The example was copied from there, because it is referred to in the answer. Implicits in Scala refers to either a value that can be passed “automatically”, so to speak, or a conversion from one type to another that is made automatically. Speaking very briefly about the latter type, if one (see implicit def augmentString on Predef). The other kind of implicit is the implicit parameter. These are passed to method calls like any other parameter, but the compiler tries to fill them in automatically. If it can’t, it will complain. One can pass these parameters explicitly, which is how one uses breakOut, for example (see question about breakOut, on a day you are feeling up for a challenge). In this case, one has to declare the need for an implicit, such as the foo method declaration: def foo[T](t: T)(implicit integral: Integral[T]) {println(integral)} There’s one situation where an implicit is both an implicit conversion and an implicit parameter. For example: def getIndex[T, CC](seq: CC, value: T)(implicit conv: CC => Seq[T]) = seq.indexOf(value) getIndex("abc", 'a') The method getIndex can receive any object, as long as there is an implicit conversion available from its class to Seq[T]. Because of that, I can pass a String to getIndex, and it will work. Behind the scenes, the compile changes seq.IndexOf(value) to conv(seq).indexOf(value). Another common pattern in implicit parameters is the type class pattern. This pattern enables the provision of common interfaces to classes which did not declare them. It can both serve as a bridge pattern – gaining separation of concerns – and as an adapter pattern. The Integral class you mentioned is a classic example of type class pattern. Another example on Scala’s standard library is Ordering. There’s a library that makes heavy use of this pattern, called Scalaz. This is an example of its use: def sum[T](list: List[T])(implicit integral: Integral[T]): T = { import integral._ // get the implicits in question into scope list.foldLeft(integral.zero)(_ + _) } There is also a syntactic sugar for it, called a context bound, which is made less useful by the need to refer to the implicit. A straight conversion of that method looks like this: def sum[T : Integral](list: List[T]): T = { val integral = implicitly[Integral[T]] import integral._ // get the implicits in question into scope list.foldLeft(integral.zero)(_ + _) } Context bounds are more useful when you just need to pass them to other methods that use them. For example, the method sorted on Seq needs an implicit Ordering. To create a method reverseSort, one could write: def reverseSort[T : Ordering](seq: Seq[T]) = seq.reverse.sorted Because Ordering[T] was implicitly passed to reverseSort, it can then pass it implicitly to sorted. When the compiler sees the need for an implicit, either because you are calling a method which does not exist on the object’s class, or because you are calling a method that requires an implicit parameter, it will search for an implicit that will fit the need. This search obey certain rules that define which implicits are visible and which are not. The following table showing where the compiler will search for implicits was taken from an excellent presentation about implicits by Josh Suereth, which I heartily recommend to anyone wanting to improve their Scala knowledge. It has been complemented since then with feedback and updates. The implicits available under number 1 below has precedence over the ones under number 2. Other than that, if there are several eligible arguments which match the implicit parameter’s type, a most specific one will be chosen using the rules of static overloading resolution (see Scala Specification §6.26.3). Let’s give examples for them. implicit val n: Int = 5 def add(x: Int)(implicit y: Int) = x + y add(5) // takes n from the current scope import scala.collection.JavaConversions.mapAsScalaMap def env = System.getenv() // Java map val term = env("TERM") // implicit conversion from Java Map to Scala Map def sum[T : Integral](list: List[T]): T = { val integral = implicitly[Integral[T]] import integral._ // get the implicits in question into scope list.foldLeft(integral.zero)(_ + _) } Edit: It seems this does not have a different precedence. If you have some example that demonstrates a precedence distinction, please make a comment. Otherwise, don’t rely on this one. This is like the first example, but assuming the implicit definition is in a different file than its usage. See also how package objects might be used in to bring in implicits. There are two object companions of note here. First, the object companion of the “source” type is looked into. For instance, inside the object Option there is an implicit conversion to Iterable, so one can call Iterable methods on Option, or pass Option to something expecting an Iterable. For example: for { x <- List(1, 2, 3) y <- Some('x') } yield, (x, y) That expression is translated by the compile into List(1, 2, 3).flatMap(x => Some('x').map(y => (x, y))) However, List.flatMap expects a TraversableOnce, which Option is not. The compiler then looks inside Option’s object companion and finds the conversion to Iterable, which is a TraversableOnce, making this expression correct. Second, the companion object of the expected type: List(1, 2, 3).sorted The method sorted takes an implicit Ordering. In this case, it looks inside the object Ordering, companion to the class Ordering, and finds an implicit Ordering[Int] there. Note that companion objects of super classes are also looked into. For example: class A(val n: Int) object A { implicit def str(a: A) = "A: %d" format a.n } class B(val x: Int, y: Int) extends A(y) val b = new B(5, 2) val s: String = b // s == "A: 2" This is how Scala found the implicit Numeric[Int] and Numeric[Long] in your question, by the way, as they are found inside Numeric, not Integral. If you have a method with an argument type A, then the implicit scope of type A will also be considered. By “implicit scope” I mean that all these rules will be applied recursively – for example, the companion object of A will be searched for implicits, as per the rule above. Note that this does not mean the implicit scope of A will be searched for conversions of that parameter, but of the whole expression. For example: class A(val n: Int) { def +(other: A) = new A(n + other.n) } object A { implicit def fromInt(n: Int) = new A(n) } // This becomes possible: 1 + new A(1) // because it is converted into this: A.fromInt(1) + new A(1) This available only since Scala 2.9.1. This is required to make the type class pattern really work. Consider Ordering, for instance… it comes with some implicits in its companion object, but you can’t add stuff to it. So how can you make an Ordering for your own class that is automatically found? Let’s start with the implementation: class A(val n: Int) object A { implicit val ord = new Ordering[A] { def compare(x: A, y: A) = implicitly[Ordering[Int]].compare(x.n, y.n) } } So, consider what happens when you call List(new A(5), new A(2)).sorted As we saw, the method sorted expects an Ordering[A] (actually, it expects an Ordering[B], where B >: A). There isn’t any such thing inside Ordering, and there is no “source” type on which to look. Obviously, it is finding it inside A, which is a type argument of Ordering. This is also how various collection methods expecting CanBuildFrom work: the implicits are found inside companion objects to the type parameters of CanBuildFrom. Note: Ordering is defined as trait Ordering[T], where T is a type parameter. Previously, I said that Scala looked inside type parameters, which doesn’t make much sense. The implicit looked for above is Ordering[A], where A is an actual type, not type parameter: it is a type argument to Ordering. See section 7.2 of the Scala Specification. This available only since Scala 2.8.0. I haven’t actually seen examples of this. I’d be grateful if someone could share one. The principle is simple: class A(val n: Int) { class B(val m: Int) { require(m < n) } } object A { implicit def bToString(b: A#B) = "B: %d" format b.m } val a = new A(5) val b = new a.B(3) val s: String = b // s == "B: 3" I’m pretty sure this was a joke, but this answer might not be up-to-date. So don’t take this question as being the final arbiter of what is happening, and if you do noticed it has gotten out-of-date, do open a ticket about it, or, if you know how to correct it, please fix it. It’s a wiki after all. EDIT Related questions of interest: This question and answer were originally submitted on Stack Overflow.blog comments powered by Disqus Contents
http://docs.scala-lang.org/tutorials/FAQ/finding-implicits
CC-MAIN-2017-04
refinedweb
1,717
55.84
? batch rename images sequentially. complete noob here. curious if this is even possible before I slog through it. I'd like to select multiple images and rename them sequentially. I found a watermark app but it doesn't have a tool to do sequential numbering but it will rename per filename possibly with a prompt to enter a "start from" number. any help would be appreciated. thanks in advance. You would like to select multiple images from the iOS camera roll, local file system, dropbox, etc.? You would like to store the resulting images where? If reading and writing to the local file system, then something like this should work... import os # create four dummy files in_file_names = ['in_file_number_{}.txt'.format(i) for i in xrange(7, 11)] print(in_file_names) for file_name in in_file_names: if not os.path.isfile(file_name): with open(file_name, 'w') as out_file: out_file.write('This file was only created for a demo.\n\tYou can safely delete this file.') # The real app starts here... def rename_files(in_file_names, out_file_fmt = '', starting_number = 1): out_file_fmt = out_file_fmt or 'freshly_watermarked_file_{:0>3}.txt' for in_file_name in in_file_names: out_file_name = out_file_fmt.format(starting_number) assert not os.path.isfile(out_file_name), 'File already exists: ' + out_file_name os.rename(in_file_name, out_file_name) starting_number += 1 rename_files(in_file_names) something simple would be awesome, just a camera roll multi-select and saving back to camera roll using the sequences. That would be better so it would be closer to my skill level for learning. my wish was worded a little off i just noticed. the prompt for a start number would let you add images to a sequence. thank you for the reply! It's currently not possible to set the file name when saving an image to the camera roll. Do images in the camera roll even have names? They do of course when you plug your device into a computer and access it via the Windows Explorer or iPhoto, but who knows if those names are real. Old-fashioned audio CDs also don't have any files or file names, yet most operating systems show the individual tracks as named/numbered files. @dgelessus: Yes. Images of the iOS camera roll do have file names. The output of: import photos print(photos.pick_image(include_metadata=True)) Contains: u'filename': u'IMG_0921.PNG' If you cancel the image picker, the code above throws an exception which I believe is a bug! well, that's a bummer. good news for me, the dev of the watermark app () replied to my suggestion and worked it in for the next weeks update. bad news for you guys, I might have wasted your time ;-) ccc that is going in my reference library though! thank you for that.
https://forum.omz-software.com/topic/1418/batch-rename-images-sequentially
CC-MAIN-2018-05
refinedweb
449
60.21
The BufferedReader class of the java.io package can be used with other readers to read data (in characters) more efficiently. It extends the abstract class Reader. Working of BufferedReader The BufferedReader maintains an internal buffer of 8192 characters. During the read operation in BufferedReader, a chunk of characters is read from the disk and stored in the internal buffer. And from the internal buffer characters are read individually. Hence, the number of communication to the disk is reduced. This is why reading characters is faster using BufferedReader. Create a BufferedReader In order to create a BufferedReader, we must import the java.io.BuferedReader package first. Once we import the package, here is how we can create the reader. // Creates a FileReader FileReader file = new FileReader(String file); // Creates a BufferedReader BufferedReader buffer = new BufferedReader(file); In the above example, we have created a BufferedReader named buffer with the FileReader named file. Here, the internal buffer of the BufferedReader has the default size of 8192 characters. However, we can specify the size of the internal buffer as well. // Creates a BufferdReader with specified size internal buffer BufferedReader buffer = new BufferedReader(file, int size); The buffer will help to read characters from the files more quickly. Methods of BufferedReader The BufferedReader class provides implementations for different methods present in Reader. read() Method read()- reads a single character from the internal buffer BufferedReader. import java.io.FileReader; import java.io.BufferedReader; class Main { public static void main(String[] args) { // Creates an array of character char[] array = new char[100]; try { // Creates a FileReader FileReader file = new FileReader("input.txt"); // Creates a BufferedReader BufferedReader input = new BufferedReader(file); // buffered reader named input. The buffered reader is linked with the input.txt file. FileReader file = new FileReader("input.txt"); BufferedReader input = new BufferedReader(file); Here, we have used the read() method to read an array of characters from the internal buffer of the buffered reader. skip() Method To discard and skip the specified number of characters, we can use the skip() method. For example, import java.io.FileReader; import java.io.BufferedReader; public class Main { public static void main(String args[]) { // Creates an array of characters char[] array = new char[100]; try { // Suppose, the input.txt file contains the following text // This is a line of text inside the file. FileReader file = new FileReader("input.txt"); // Creates a BufferedReader BufferedReader input = new BufferedReader(file); // Skips the 5 characters input.skip(5); // Reads the characters input.read(array); System.out.println("Data after skipping 5 characters:"); System.out.println(array); // closes the reader input.close(); } catch (Exception e) { e.getStackTrace(); } } } Output Data after skipping 5 characters: is a line of text inside the file. In the above example, we have used the skip() method to skip 5 characters from the file reader. Hence, the characters 'T', 'h', 'i', 's' and ' ' are skipped from the original file. close() Method To close the buffered reader, we can use the close() method. Once the close() method is called, we cannot use the reader to read the data. Other Methods of BufferedReader To learn more, visit Java BufferedReader (official Java documentation).
https://www.programiz.com/java-programming/bufferedreader
CC-MAIN-2021-04
refinedweb
522
50.84
How to approve App ID from account representative? Errors : Your Application ID is not authorized It is unclear what you are asking here. Where are you seeing this error? Can you provide a code snippet? Where are you looking for approval? What API endpoint are you attempting to use? from requests_oauthlib import OAuth1 auth = OAuth1(“api key”, “api secret key”, “access token”, “access token secret”) request = requests.post( url, auth = auth, headers = header, data = json.dumps(data)) request.text Output={“errors”:[“Your Application ID is not authorized.”]} I am trying to extract engagement metrics(likes, favorites, replies) using /totals endpoint. But POST request is giving 403. Does your application have access to the Engagement API? Have you got an enterprise account? See the documentation here. This is an enterprise API available within our managed access levels only. To use this API, you must first set up an account with our enterprise sales team Not yet. I had requested for enterprise access since a week. But no reply from Enterprise Sales team. How long does it take for getting enterprise access? I can’t comment on times on that, however this is a commercial API with an annual contract. This is the reason your API call is failing, you need to.wait to have access. Sure, will wait for access. Thank you for your help.
https://twittercommunity.com/t/errors-your-application-id-is-not-authorized/116957
CC-MAIN-2018-51
refinedweb
224
70.9
Components t:dataModel and t:dataScroller work together nicely to allow a user to "page" through a set of a few dozen to a few hundred records. However the implementation does assume that the entire set of available records are in memory and wrapped up inside a ListDataModel or ArrayDataModel. When the available dataset is quite large, and the application can have many users, this can lead to memory usage problems. This page contains discussions on how to handle this scenario. On-demand loading A custom DataModel can be used to allow data to be loaded "on demand". First, a class needs to be defined which your "business methods" (eg EJBs) can use to pass "pages" of data back to the UI. This class needs to be defined in your project, as the "business" level shouldn't be extending MyFaces classes: package example; import java.util.List; /** * A simple class that represents a "page" of data out of a longer set, ie * a list of objects together with info to indicate the starting row and * the full size of the dataset. EJBs can return instances of this type * when returning subsets of available data. */ public class DataPage<T> { private int datasetSize; private int startRow; private List<T> data; /** * Create an object representing a sublist of a dataset. * * @param datasetSize is the total number of matching rows * available. * * @param startRow is the index within the complete dataset * of the first element in the data list. * * @param data is a list of consecutive objects from the * dataset. */ public DataPage(int datasetSize, int startRow, List<T> data) { this.datasetSize = datasetSize; this.startRow = startRow; this.data = data; } /** * Return the number of items in the full dataset. */ public int getDatasetSize() { return datasetSize; } /** * Return the offset within the full dataset of the first * element in the list held by this object. */ public int getStartRow() { return startRow; } /** * Return the list of objects held by this object, which * is a continuous subset of the full dataset. */ public List<T> getData() { return data; } } Now a custom DataModel can use this DataPage stuff. Again, it is recommended that you copy this code into your project and change the package name appropriately. This class can't go in the MyFaces libraries as it depends on DataPage, and as noted above, DataPage is accessed by your business level code so it really can't be in the MyFaces libs: package example; import javax.faces.model.DataModel; import example.DataPage; /** * A special type of JSF DataModel to allow a datatable and datascroller * to page through a large set of data without having to hold the entire * set of data in memory at once. * <p> * Any time a managed bean wants to avoid holding an entire dataset, * the managed bean should declare an inner class which extends this * class and implements the fetchData method. This method is called * as needed when the table requires data that isn't available in the * current data page held by this object. * <p> * This does require the managed bean (and in general the business * method that the managed bean uses) to provide the data wrapped in * a DataPage object that provides info on the full size of the dataset. */ public abstract class PagedListDataModel<T> extends DataModel { int pageSize; int rowIndex; DataPage<T> page; /* * Create a datamodel that pages through the data showing the specified * number of rows on each page. */ public PagedListDataModel(int pageSize) { super(); this.pageSize = pageSize; this.rowIndex = -1; this.page = null; } /** * Not used in this class; data is fetched via a callback to the * fetchData method rather than by explicitly assigning a list. */ @Override public void setWrappedData(Object o) { throw new UnsupportedOperationException("setWrappedData"); } @Override public int getRowIndex() { return rowIndex; } /** * Specify what the "current row" within the dataset is. Note that * the UIData component will repeatedly call this method followed * by getRowData to obtain the objects to render in the table. */ @Override public void setRowIndex(int index) { rowIndex = index; } /** * Return the total number of rows of data available (not just the * number of rows in the current page!). */ @Override public int getRowCount() { return getPage().getDatasetSize(); } /** * Return a DataPage object; if one is not currently available then * fetch one. Note that this doesn't ensure that the datapage * returned includes the current rowIndex row; see getRowData. */ private DataPage<T> getPage() { if (page != null) return page; int rowIndex = getRowIndex(); int startRow = rowIndex; if (rowIndex == -1) { // even when no row is selected, we still need a page // object so that we know the amount of data available. startRow = 0; } // invoke method on enclosing class page = fetchPage(startRow, pageSize); return page; } /** * Return the object corresponding to the current rowIndex. * If the DataPage object currently cached doesn't include that * index then fetchPage is called to retrieve the appropriate page. */ @Override public Object getRowData(){ if (rowIndex < 0) { throw new IllegalArgumentException( "Invalid rowIndex for PagedListDataModel; not within page"); } // ensure page exists; if rowIndex is beyond dataset size, then // we should still get back a DataPage object with the dataset size // in it... if (page == null) { page = fetchPage(rowIndex, pageSize); } // Check if rowIndex is equal to startRow, // useful for dynamic sorting on pages if (rowIndex == page.getStartRow()){ page = fetchPage(rowIndex, pageSize); } int datasetSize = page.getDatasetSize(); int startRow = page.getStartRow(); int nRows = page.getData().size(); int endRow = startRow + nRows; if (rowIndex >= datasetSize) { throw new IllegalArgumentException("Invalid rowIndex"); } if (rowIndex < startRow) { page = fetchPage(rowIndex, pageSize); startRow = page.getStartRow(); } else if (rowIndex >= endRow) { page = fetchPage(rowIndex, pageSize); startRow = page.getStartRow(); } return page.getData().get(rowIndex - startRow); } @Override public Object getWrappedData() { return page.getData(); } /** * Return true if the rowIndex value is currently set to a * value that matches some element in the dataset. Note that * it may match a row that is not in the currently cached * DataPage; if so then when getRowData is called the * required DataPage will be fetched by calling fetchData. */ @Override public boolean isRowAvailable() { DataPage<T> page = getPage(); if (page == null) return false; int rowIndex = getRowIndex(); if (rowIndex < 0) { return false; } else if (rowIndex >= page.getDatasetSize()) { return false; } else { return true; } } /** * Method which must be implemented in cooperation with the * managed bean class to fetch data on demand. */ public abstract DataPage<T> fetchPage(int startRow, int pageSize); } Finally, the managed bean needs to provide a simple inner class that provides the fetchPage implementation: public SomeManagedBean { .... private DataPage<SomeRowObject> getDataPage(int startRow, int pageSize) { // access database here, or call EJB to do so } public DataModel getDataModel() { if (dataModel == null) { dataModel = new LocalDataModel(getRowsPerPage()); } return dataModel; } private class LocalDataModel extends PagedListDataModel { public LocalDataModel(int pageSize) { super(pageSize); } public DataPage<SomeRowObject> fetchPage(int startRow, int pageSize) { // call enclosing managed bean method to fetch the data return getDataPage(startRow, pageSize); } } The jsp pages are then trivial; by default the t:dataScroller will update the t:dataTable's "first" property, and that's all that is needed because when the table asks the custom DataModel for the necessary rows callbacks to fetchPage will be made which will fetch exactly the data required. No event listeners, action methods, or anything else is required as glue. Other approaches In an email thread on this topic, an alternative was decribed: So was this: And another example with the DataModel approach And a sortable and scrollable demo with 1.1.1 jars included: Paging large data sets with a LazyList Paged datatable with a GenericDataTableHandler:
http://wiki.apache.org/myfaces/WorkingWithLargeTables
crawl-002
refinedweb
1,213
52.09
Hello, I have to do an assignment for school. I have to write a code for a program that calculates the average of to double numbers. I wrote this is NetBeans and it gives me the following errors: the variables first and second may have not been initialized cannot find symbol sc public class DecimalAveShifat { public static void main(String args []){ double first; double second; double mean1; double meanf; mean1 = first + second; meanf = mean1 / 2; System.out.println ("First Decimal Number: "); first = sc.nextDouble (); System.out.println ("Second Decimal Number: "); second = sc.nextDouble (); System.out.println ("The avarage of the two is " + meanf) ; } } I am just a beginner. It has only been a week since I started computer science class at school. If anyone could tell me what is wrong, and the fix for it, it would be wonderful. Thanks in advance. Shifat Taushif shifat.tk
http://www.javaprogrammingforums.com/whats-wrong-my-code/13894-finding-average-two-double-digits.html
CC-MAIN-2018-05
refinedweb
146
66.13
cryptohash collection of crypto hashes, fast, pure and practical See all snapshots cryptohash appears in cryptohash-0.11.9@sha256:59d9494ba0cc9eef087ecba2e12e4d3e2d3b0327dd1542af552e3dca0e7de70d,4230: - MD2, MD4, MD5 - RIPEMD160 - SHA1 - SHA-2 family: 224, 256, 384, 512 and the newer 512t - SHA-3 (aka Keccak) - Skein: 256, 512 - Tiger - Whirlpool You can easily import any hash with the following: import qualified Crypto.Hash.<HASH> as <Hash> We recommend using import qualified because the APIs are similar and many of the modules reuse the same names. However, if you are ony using one module, there is no need to qualify the names. Incremental API it’s based on 4 different functions, similar to the lowlevel operations of a typical hash: - init: create a new hash context - update: update non-destructively a new hash context with a strict bytestring - updates: same as update, except that it takes a list of strict bytestring - finalize: finalize the context and returns a digest bytestring. all those operations are completely pure, and instead of changing the context as usual in others language, it re-allocates a new context each time. One Pass API The one pass API use the incremental API under the hood, but expose common operations to create digests out of a bytestring and lazy bytestring. - hash: create a digest (init+update+finalize) from a strict bytestring - hashlazy: create a digest (init+update+finalize) from a lazy bytestring More Type safety A more type safe API is also available from Crypto.Hash. The API provides all the supported hashes in the same namespace, through unified functions. It introduces 2 new types, the Context type and the Digest type. Both those types are parametrized with the HashAlgorithm used. The API is very similar to each single hash module, except the types are slightly different. import Crypto.Hash -- use the incremental API to hash the byte [1,2,3] with SHA1 -- and print the hexadecimal digest. example1 = do let ctx = hashInit ctx' = hashUpdates ctx [ Data.ByteString.pack [1,2,3] ] dgt = hashFinalize ctx' :: Digest SHA1 putStrLn $ show dgt -- use the one-pass API to hash the byte 1,2,3 with SHA3_512 -- and print the hexadecimal digest. example2 = do let dgt = hash (Data.ByteString.pack [1,2,3]) :: Digest SHA3_512 putStrLn $ show dgt Performance Cryptohash uses C implementations to provide maximum performance. see the cbits directory for more information
https://www.stackage.org/lts-7.24/package/cryptohash-0.11.9
CC-MAIN-2022-21
refinedweb
390
51.28
I read somewhere that one of the developers/contributors would like to see an IDE developed in Enigma; this implies to me that it would be possible, and if it's possible, I would love to get involved. Don't take this the wrong way, but I actually do not agree with the complaints about LateralGM on Windows because of this. Sure LGM may not be designed well for a good plugin, but its problems almost always crop up when used with the ENIGMA plugin on Windows. LateralGM by itself rarely if ever (I've never seen it) segfault on its own all by itself, it's always the ENIGMA plugin crashing it. And this is not just because of LGM's poor plugin architecture it's the generally bad design of the ENIGMA plugin itself. Robert, I see that you have basically remade LGM 5x over the past few years and it would have been awesome if you actually managed to finish one. CLI is the easiest way to make a custom IDE compile a game with ENIGMA. That is why I encourage finishing it, because then HitCoder and other people who want to make an IDE wouldn't have to waste time somehow interfacing with ENIGMA. They would just need to make a writer for EGM which is a trivial format. 1) Change room data into XML. 2) Make a format that is basically extracted EGM. It doesn't really matter what crashes. When the user opens LGM and it segfaults then of course the only thing he can blame is LGM. On my laptop my plugin fixes made crashes almost non-existent (about 1 crash every 3 hours or so). I am doing this release to fix the JoshEdit problems so that egofree is able to build LGM again and people can continue to develop it. Yes it certainly does make it easier to get started, but ideally in a perfect world you still need compileEGMf to pass resources that have been opened but not saved in the IDE. This is the problem GM Studio's IDE has, it always forces you to save your changes before running, which 99% of the time nobody wants to do, Especially me, you make small changes just to test them. I was going to do that, but clearly if that's all you want then there is GMX. XML is a bloated markup language and Josh already proposed an EYAML format to replace the binary room blobs. Anyway, I don't have time to do it, that's a substantial amount of work. The breaking change is fine though because I have backed up every old plugin and LateralGM version in multiple locations and they aren't hidden either, you can find them easily on the Wiki and I've linked it multiple times. So if you'd like to make the changes to the plugin, knock yourself out it needs done but nobody has time right now. EGM is actually supposed to support this, it was never finished and I never had the interest in doing it. Also note the above comments regarding LGM still loading the entire project instead of just the resource you are currently editing. Irrelevant So push the changes to GitHub. That is really not a problem as you can just write to a temporary.. And we did have posts with Josh talking about rooms in a non-binary mode. In it I showed how XML is actually not bloated if used correctly. Yet has more features than EYAML proposed. But I honestly don't care in which format it is. What you said irrelevant. I don't see how that is a lot of work. Again, if you have EGM loading then this should be trivial. It should be even easier, as you must SKIP a step. Just don't open the .zip and instead read the folder structure. This significantly complicates the overall process of passing the resources by requiring them to be loaded into the IDE, written to the disk, then read back from the disk on the other end before being passed from the CLI to compileEGMf. functionThatSavesInEGM(randomlyGeneratedFileInTemp);system(cliPath+" -egm "+randomlyGeneratedFileInTemp); Rusky has pointed out to me that XML supports namespaces and some other features I see, so excuse me for being naive originally. I was not aware of this but I think it is still debatable about how verbose XML can be, and I clearly tend to agree that it is. However, XML apparently does have some good data processing and querying features (which I was already aware of), but why exactly does ENIGMA need them? YAML is clearly/technically/colloquially not a markup language and really good for just plain old data, which our rooms basically are. So I would like to know if you had some ideas for utilizing the XML processing/querying features or not, because that is something to consider before making a decision. I don't know what you want me to say. LGM has taken all of the necessary precautions to make sure the errors are properly reported, and so has the plugin framework. Even a native IDE would require a plugin framework so that it's not limited to only ENIGMA, it's a simple separation of duty. Are we still not able to debug these compile errors you're having with the plugin or what? It doesn't complicate anything as the IDE must be able to save EGM anyway and the CLI needs to be able to load it. functionThatSavesInEGM(randomlyGeneratedFileInTemp);system(cliPath+" -egm "+randomlyGeneratedFileInTemp);nativeCodeThatReadsEGM();cliPassesDataToCompileEGMf();compileParseLinkAndStuffs(); pluginTellsCompileEGMfWhereToFindTheRemainingResources();pluginPassesDataToCompileEGMf();compileEGMfFindsResourcesTheIDEDidNotHaveLoaded();compileParseLinkAndStuffs(); I do agree that XML is more verbose than some alternatives, that is for sure. I just meant that the excuses like "Plugin is crashing, not LGM" is futile here. Removing one .ey entry can trow a segfault. But internally, throughout the whole process, it turns into this... I don't know, reading the XML is useful when a corruption occurs, that's why we don't want binary blobs. I wouldn't say XML is hard to read, I did HTML programming in junior high school. I don't know how I would have been towards YAML when I was younger. When I first saw it a few years ago in ENIGMA I wasn't sure I understood it, but it wasn't difficult even though it looked foreign. Now that I am older, I definitely prefer it just because it's easier on my eyes. That said, GMX is basically the XML format, we've done YAML in every other part of EGM. So that is basically why I don't support the room format being XML because that is inconsistent. Using YAML makes the EGM format unique from the others, and I really don't think we should do another format just because we want XML. There's not really a good argument at all here especially considering we already have the suitable YAML infrastructure. The plugin gets a lot of these because it makes a lot of use of threads and tries to do GUI stuff from those threads. Well maybe making it only use one thread is solution then?
https://enigma-dev.org/forums/index.php?PHPSESSID=bqdk6rsimloh8kasi9sfpqac60&topic=2599.0
CC-MAIN-2021-21
refinedweb
1,207
61.06
SECOND EDITION FRIDAY, NOVEMBER 11, 2016 | Kartik 27, 1423, Safar 10, 1438 | Regd No DA 6238, Vol 4, No 194 | | 32 pages plus 24-page Weekend supplement | Price: Tk10 Betrayed and deceived, Santals lose everything › 2 Tractor tramples atrocity evidence › 3 Supreme Court verdict on arrest and remand › 4 BD NGO wins Energy Globe Award at COP22 › 5 Police against revealing details of death in crossfire › 32 2 FRIDAY, NOVEMBER 11, 2016 DT News ATTACKS ON MADARPUR COMMUNITY Betrayed and deceived, Santals lose • Nure Alam Durjoy and Tajul Islam Reza from Gaibandha Before being elected chairman of Sapmara union, he was involved in a popular movement advocating for the local indigenous Santal community’s claims over a land now controlled by a government sugar mill. On Sunday, the same man stood by and watched as police fired at the community and his followers set fire to their homes. The betrayed community is in shock after this 180-degree turnaround by the man they helped put in office. Shakil Ahmed Bulbul, the president of upazila Chhatra League and newly-elected Sapmara UP chairman in Gobindaganj upzila under Gaibandha district. The land in question was acquired by the then-East Pakistan government in 1962 for the mill. In 2014, some found that the contract for acquisition had been violated by the mill authority and a committee was formed to get the land back on that ground. Bulbul was named the president of this Shahebganj-Bagda Farm Bhumi Uddhar Songram [land recovery movement] Committee. Santals who have now fled to neighbouring villages, told the Dhaka Tribune that it was at the urging of Bulbul four months ago that they, along with some Bangalis, took to a 100 acre piece of the 1842.3 acre sugarcane farm and built 600 new homes. Not only the UP chairman, but local lawmaker Abul Kalam Azad too, gave them assurance that they would be stay beside the community in their struggle for land, some claimed. The burnt remains of those ‘Attack on Santals was planned’ • Syed Samiul Basher Anik The recent attack on a Santal community in Gobindaganj, Gaibandha was planned to evict them from their land, a citizens body said yesterday. After visiting the affected areas of Shahebganj-Bagda farm in Gobindaganj on Tuesday, members of Shahebganj-Bagda farm Bhumi Uddhar Sanghati Committee said Santals were victims of a joint attack carried out by ruling party leaders, local administration and police aiming to evict them from their land. The eight-member committee made the comment at a A man shows empty shells of the bullets fired by police on local Santal and Bangali people of Gobindaganj upazila, Gaibandha when they resisted an eviction drive. The photo was taken yesterday MEHEDI HASAN shanties have now been flattened down with a tractor machine. It began on Sunday with an attack, where Bulbul and Azad’s men press conference held at Dhaka Reporters’ Unity in the capital. “Although two Santal men – Shyamol Hembron and Mongol Madri – were killed in the illegal eviction drive led by police, they are refusing take the responsibility,” said Jyotirmoy Barua, convener of the committee. Three Santal men remain missing after police opened fire on the people on Sunday, he added. Local union parishad Chairman Shakil Akhand Bulbul and his musclemen, along with police and sugar mill manager Abdul Awal, attacked the Santals and Bangalis in a planned way under the guise of mill staff, according to the committee. “Prior to the attack, Bulbul instructed his goons to rob all the houses and spare no one,” Jyotirmoy claimed. The evicted Santal families are now living under the open sky while the government has yet to extend a helping hand, he added. took part, the Santals said. Police stood by as the men set fire to the homes. Later they also locked in a battle with the com- Shahebganj Bhumi Uddhar Sanghati Committee holds a press briefing at the Reporters Unity in Dhaka protesting the attacks on Santal Community in Gaibandha DHAKA TRIBUNE The committee called upon the government to launch a judicial probe into the incident. • News 3 FRIDAY, NOVEMBER 11, 2016 DT everything munity, which allegedly shot with bows and arrows at police and got shot at in return. Three men from the village have died so far from gunshot wounds. How the tables turned Bulbul contested the chairman position for Sapmara union parishad in March. The community says that it was after his polls victory that he turned against the Santals. In a UP with about 18,000 voters, the nearly 1,500 adults from the community were a certain vote bank for the aspiring politician. Even recently, in a rally at Shahebganj Bazar, MP Abul Kalam Azad gave assurance to the community that he would stand by their demands. But both the men were present to look on as the community was violently thrown out, not even given the chance to take their belongings. Rumila Kisku, one of the victims, told the Dhaka Tribune how she had lost her home and all her belongings in the fire. She has two children; one is in class nine and the other one in class two. “Did we not vote for them? How did they become chairman, MP? Are we not citizens of this country? Why does not the government look after us?” she exclaimed at one point. ‘Take what you can’ Victims alleged that the goons of MP Azad and Bulbul led the attack on the village. Those who spoke to the journalists were mostly women. Among Tractor tramples atrocity evidence • Nure Alam Durjoy from Gaibandha When the tractor finally stopped growling, its driver glancing back at the well-tilled patch of land; it would be hard for anyone to guess that this stretch of Madarpur village was teeming with people just five days ago. More than 2,000 people, mostly Santals, living in about 600 shanties in the remote village under Gaibandha’s Gobindaganj upazila. They were displaced after their houses were set afire on Sunday and Monday, allegedly by men loyal to local MP Abul Kalam Azad and Sapmara Union Chairman Shakil Ahmed Bulbul, in presence of police. Two Santal men were killed and three others were injured in clashes on Sunday when the residents No home, and now no education • Nure Alam Durjoy and Tajul Islam Reza from Gaibandha them were Taran Murmu, Mikai Murmu, Ajiran Begum and Rumana Begum, former residents of the village. “Police have filed a case against many of our men. They have run away for fear of arrest,” one of them said. They claimed that during Sunday’s attack there had been at least 4,000 people from nearby villages, policemen, sugar mill’s guards and goons working for the two politicians. They also named several people from Kothiabari, Rampura and Goalpara villages. Some said immediately before the attack, there was an announcement on a megaphone. “‘Take what you can,’ they said over the mike,” said Sri Ezekiel, one of the victims. The goons launched into the shanties looting everything they could. “There was nothing we could do when we saw a giant flame reaching out to the sky,” he said. Responding to the Dhaka Tribune’s queries, Bulbul admitted that he stood over the eviction of the villagers but denied any wrongdoing. “I resigned from the land recovery committee in January,” he said. “There is this man named Shahjahan Ali, who is the general secretary of that committee. He is the one who told the Santals to build homes in that land,” he added. “Besides, some organisations and leftist groups also had a hand in this,” Bulbul alleged. Abul Kalam Azad MP could not be reached for comments. • The future seems dark for young Santals of Madarpur. Driven out of their village by the police and local thugs, at least 60-70 children and youth from the community have stopped going to school for fear of assault. They also lost all their textbooks and study materials in the arson that burned all their homes to ground. Following a violent eviction carried out by local thugs watched over by policemen, which began on Sunday and continued intermittently till Monday, some 1,000 Santal families have run away from their homes and taken shelter in nearby villages. Children from the community are saying they fear they might be beaten up on their way to the school, or even in the schools. In a nearby village, one of our correspondents found Santal families sitting around in the yards of people who had given them shelter. Children were also there sitting by their elders. “We cannot go to school. We tried to go. They said: You are Santals. Why are you here? If we go to school they will beat us,” said Magdulina, a class-six student. “Our books were burnt there in the village. We do not even have anything to eat. Our parents are unfed too,” she said. There are 60-70 students in the community, most of whom go to the Sahebganj Farm Government Primary School. Some are college and university-level students. Workers of a sugar mill in Madarpur village under Gobindapur upazila, Gaibandha run a tractor on the land which, before Sunday, was home to several Santal families to trample the burnt remains of their houses to the ground. The photo was taken yesterday MEHEDI HASAN Archana, a class four student, said she wanted dearly to get back The picture shows a school attendance register of students. The school was not even spared from the wrath of men of lawmaker and chairman MEHEDI HASAN to school but could not because of the fear of violence. fought pitched battles with police, sugar mill staff, and men loyal to the MP and chairman. Victims said the tractor was brought in on Monday evening after their houses were set on fire to erase evidence that they lived there. On Wednesday noon, this correspondent saw a tractor – which, according to people supervising the operation, belonged to the Mahimaganj Sugar Mill – levelling the patch of land where the charred houses stood but left the surrounding area untouched. When asked why they were ploughing the area, the supervisors claimed that the land had been lying barren for a long time and declined to speak further. Several date and banana trees bore signs of the arson. Ansel Hembrom, one of the Santals who lived there, said the tractor had begun work in presence of police on Monday night. A barbed-wire fence was being put up to cut off the place. It was from here that the Pakistani government evicted 25 families in 1962 for setting up a sugar mill. Those evicted went on to settle in other parts of the country. A 1962 deal between Pakistan’s central and provincial governments had a clause that the land would be handed over to the previous owners if it was used for other purposes. The sugar mill stopped production in 2004 but the land was leased allegedly to local politicians and affluent people. Some of those families returned to lay claim to the land. They built makeshift houses there in July. • Medi Soren, a honors second year student, said he could not imagine that this sort of torture would descend upon him and his neighbours. An SSC candidate said: “I have exams soon and I am wondering whether I will be able to sit for the exam. I have no home now, where am I going to study?” Sahebganj Farm school’s Headmaster Abdul Baki said none of his Santal students had been to the school since the incident. He said he had spoken to some of the parents and heard that the students were afraid to come to the school. Five days ago, the community was living in a long line of shanties, nearly 600, built four months ago. Now the place is a flat piece of land, darkened with ash. • 4 FRIDAY, NOVEMBER 11, 2016 DT News Supreme Court verdict on arrest and remand • Ashif Islam Shaon The Bangladesh Supreme Court has issued guidelines for the law enforcement agencies and magistrates over sections 54 and 167 of the Code of Criminal Procedure (CrPC). Section 54 empowers the police to detain any person under suspicion while Section 167 empowers them to question an accused in remand. In its full verdict the Appellate Division has issued 10 guidelines for the law enforcers about detaining anyone on suspicion and nine guidelines for magistrates, judges and tribunals to deal with an accused. A four-member Appellate Division bench headed by Chief Justice Surendra Kumar Sinha had passed the order on May 24 this year, upholding the High Court’s 2003 verdict in a writ petition filed by Bangladesh Legal Aid and Services Trust (BLAST). The petition had sought implementation of a judicial committee recommendations which investigated a private university BIGSTOCK student’s death after arrest under Section 54. In its verdict the High Court had asked the government to amend the sections within two months in line with instructions given by the court. The apex court has, however, made some changes and issued the final guidelines. The Appellate Division yesterday said that the court has formulated some basic responsibilities for the law enforcement agencies to maintain at all level. The Supreme Court has directed magistrates, tribunals, courts and judges – who have the power to take cognisance of an offence as a court of original jurisdiction – to ensure observance of these guidelines. The court also directed the inspector general of police and the director general of Rapid Action Battalion (RAB) to circulate the guidelines to all police stations for compliance. It asked the registrar general to circulate it for compliance by the magistrates. Guidelines for law enforcement agencies (i) (ii) (iii) (iv) (v) A law enforcement officer making the arrest of any person shall prepare a memorandum of arrest immediately after the arrest and obtain the signature of the arrestee with the date and time of arrest in the memorandum. The law enforcement officer must inform a nearest relative of the arrestee – or, in the absence of such relative – a friend suggested by the arrestee of the arrest and the place of custody as soon as possible but not later than 12 hours. The ground of arrest; name and address of the complainant; the name and address of the relative or friend to whom information about the arrest is given; and particulars of the law enforcement officer in whose custody the arrestee is staying must be registered. Registration of a case against the arrested person is a must for seeking detention either in law enforcement officer’s custody or in judicial custody under Section 167(2). No law enforcement officer shall arrest a person under Section 54 for the purpose of detaining him under Section 3 of the Special Powers Act 1974 (for detention or deportation). (vi) A law enforcement officer shall disclose his identity and if demanded, shall show his identity card to the person arrested and to those present at the time of arrest. (vii) If the law enforcement officer finds any marks of injury on the person arrested, he must record the reasons for such injury and take the person to the nearest hospital for treatment and obtain a certificate from the attending doctor. (viii) If the person is not arrested from his residence or place of business, the officer must inform the nearest relative of the arrestee in writing within 12 hours of bringing the arrestee to the police station. (ix) (x) The law enforcement officer shall allow the person arrested to consult a lawyer of his choice if he so desires or to meet any of his nearest relation. If an arrestee needs to be kept in custody for more than 24 hours, the law enforcement officer must state in the forwarding letter to a magistrate why the investigation cannot be completed within 24 hours and why he considers that the accusations against the person are well founded. He shall also provide the magistrate with a copy of the case diary. Guidelines for magistrates, judges and tribunals (i) If a person is produced for detention in custody without a copy of the case diary, the magistrate or the court or the tribunal must release the person upon taking a bond. (ii) A magistrate/court/tribunal must not allow showing an arrestee arrested in another case unless a copy of the case diary for that case is produced or if the ground of the prayer is found not well founded or baseless. (iii) On fulfilment of the above conditions, if the investigation of the case cannot be concluded within 15 days of detention and if the case is exclusively triable by a court of Sessions or Tribunal, a magistrate may send the accused on remand for a term not exceeding 15 days at a time. (iv) If the magistrate is satisfied that the accusation or the information about the arrestee is well founded and that his detention is justified, the magistrate shall pass an order for further detention in such custody as he deems fit and proper, until legislative measure is taken as mentioned above. (v) If a magistrate realises that a prayer aims at preventive detention, then the magistrate shall not make an order of detention of a person in the judicial custody. (vi) It shall be the duty of the magistrate/tribunal, before whom the accused person is produced, to satisfy that these requirements have been complied with before making any order under section 167 of the CrPC. (vii) If the magistrate has reasons to believe that a law enforcement officer who has legal authority to commit a person in confinement has acted contrary to law, the magistrate shall proceed against such officer under Section 220 of the Penal Code. (viii) Whenever a law enforcement officer takes an accused person in his custody on remand, it is his responsibility to produce that person in court upon expiry of the remand period; and if it is found that the arrested person is dead, the magistrate shall direct for the examination of the victim by a medical board; and in the event of burial of the victim, he shall direct exhumation of the dead body for fresh medical examination; and if the report of the board reveals that the death was homicidal in nature, the magistrate shall take cognisance of the offence punishable under Section 15 of the Hefajate Mrittu (Nibaran) Ain 2013 against the officer concerned and the officer-in-charge of the police station concerned or the commanding officer of such officer in whose custody the death of the accused took place. (ix) If there are materials or information to a magistrate that a person has been subjected to torture or died in custody within the meaning of Section 2 of the Nirjatan and Hefajate Mrittu (Nibaran) Ain 2013, the magistrate shall refer the victim to the nearest doctor in case of torture and to a medical board in case of death for ascertaining the injury or the cause of death; and if the medical evidence reveals that the person detained has been tortured or died due to torture, the magistrate shall take cognisance of the offence on his own under Section 190(1)(c) of the CrPC and proceed in accordance with law. News 5 FRIDAY, NOVEMBER 11, 2016 CLIMATE CHANGE CONFERENCE COP22 Emitters’ proposal on $100 billion road-map unclear • Abu Siddique The climate finance road-map proposed by the developed countries in Conference of Parties (COP22) to fix the modality and sources of the funds has failed to give sufficient directions for the future funding. This road-map couldn’t clearly clarify that “how far the adaptation finance will be adequately scaled-up; which portion of claimed climate finance will be actually grants or grant equivalent; how the most climate vulnerable countries will get priority in funding considering the institutional challenges,” said M Zakir Hossain Khan, Climate Finance Governance Analyst, who works for the BD NGO wins Energy Globe Award at COP22 • Abu Siddique Bangladeshi NGO Tahzingdong has won the Energy Globe Award in Earth category at COP22 this year for its community-based forest conservation project in Rowangchhari, Bandarban. The award was declared yesterday at COP22 in Marrakech, Morocco. The two other finalists for the award were the Inga Foundation of Honduras for its project named “Land for Life” and AMSED of Morocco for its project named “Waste water treatment for agricultural use with minimal Greenhouse Gaz Emission in Asselda Village.” The Energy Globe Award was founded in 1999 by the Austrian energy pioneer Wolfgang Neumann and is one of the most prestigious environmental awards today. The goal of this award is to present successful sustainable projects to a broad audience as many of today’s environmental problems already have good, feasible solutions. Projects which conserve and protect resources or that employ renewable energy can participate. With a global call for participation, Energy Globe invites outstanding sustainable best practice projects to participate in the annual competition. From all over the world, some 800 projects and initiatives are submitted annually to compete for the award. With the goal of restoration and conservation of the community managed forest resources in the Transparency International Bangladesh. It also could not clarify that the most vulnerable countries which have not submitted any emission reduction target whether they would be considered for committed climate finance or not, he added. He also said that the role of Multilateral Development Banks in climate finance is not clear in the proposal. The document reads that the pledges made in 2015 alone will boost public finance from an average of US$41 billion over 2013-14 to US$67 billion in 2020 – an increase of US$26 billion. This projection is based on the significant pledges and announcements made by many developed countries Bandarban hill district of Bangladesh, Tahzingdong has been implementing its project supported by Arannayk Foundation of Bangladesh since 2009. The project covers 12,919.64 hectares of nine community conserved areas which are commonly called village common forests, and it includes more than 1,000 indigenous forest dependent families. Tahzingdong has built two community houses as part of institutional capacity building and Motivated by Tahzingdong’s reforestation programme, a man plants a sapling in his neighbourhood in Rowangchhari to increase forest area ENERGY GLOBE installed two water supply technologies that capture more than 387,000 litres of clean water in a month from the forests using a gravitational flow system, said Aung Shwe Shing, executive director of Tahzingdong. • and Multilateral Development Banks (MDBs), as well as reasonable assumptions about trends of climate finance from other countries. It should be considered a conservative, indicative aggregation of public climate finance levels in 2020, rather than a firm prediction, it also said. The proposal came from 39 developed countries as per the Paris Agreement which stated that the developed countries will meet the $100 billion per annum target by 2020 and extend it until 2025 in the context of meaningful mitigation actions and transparency on implementation. It also said that prior to 2025, the COP 22 will set a new collective quantified goal from a floor of $100 billion per year, taking into account the needs and priorities of developing countries. He raised question that the most importantly “Road-map doesn’t include direction on whether the future finance against the claim for loss and damages would be over and above this $100 billion dollars”. This road-map sets out the range of actions which are to fulfill the pledges of developed country parties and make further efforts to scale-up climate finance, and significantly increase finance for adaptation, in line with the priorities expressed by developing countries. It will also help developing countries to develop and implement ambitious mitigation contributions and adaptation plans that are essential to attract investment, according to the proposed road-map. Zakir Hossain Khan also emphasized that developing country parties should use the COP22 negotiations to determine the concrete definition of climate finance that recognise only grants for adaptation and also a common, clear strong modalities, procedures and guidelines (MPG) for climate finance accounting to be developed under Article 13 of Paris Agreement that proposed a broad based Transparency Framework”. However, the last year’s OECD/CPI report claimed that these countries had delivered $62 billion in climate finance in 2014. • Hope and despair of vulnerable countries • Rezaul Karim Chowdhury DT Following the discussion on insurance mechanism in the loss and damage issue in Paris agreement adopted last year, the Least Developed Countries and Most Vulnerable Countries (MVC)s are raising several questions in this year’s climate conference in Marrakech. Firstly, they want to know about the premium of the insurance. They demanded that the developed countries should pay the premium of the insurance as they are responsible for global warming. There are strong lobby from insurance companies of developed countries in this regard for pushing the insurance under the loss and damages mechanism though they are not telling who will pay for that. Another issue which is coming from the vulnerable nations is the inclusion of climate induce displacement in the process of Warsaw Institutional Mechanism under which the discussion of loss and damages is being taken. Regarding financing, developed countries’ position is not to go beyond what they are contributing to Green Climate Fund (GCF) and do not want separate allocation for loss and damages, while the developing countries opted for new and additional sources of fundings. • TEMPERATURE FORECAST FOR TODAY DRY WEATHER LIKELY FRIDAY, NOVEMBER 11 Dhaka 30 19 Chittagong 29 24 Rajshahi 30 19 Rangpur 30 20 Khulna 30 18 Barisal 30 18 Sylhet 31 18 DHAKA TODAY TOMORROW SUN SETS 5:14PM SUN RISES 6:12AM YESTERDAY’S HIGH AND LOW 32.2ºC 17ºC Sylhet Chuadanga Source: Accuweather/UNB PRAYER TIMES Cox’s Bazar 29 22 Fajr: 5:35am | Jumma: 1:15pm Asr: 4:00pm | Magrib: 5:30pm Esha: 7:30pm Source: Islamic Foundation 6 FRIDAY, NOVEMBER 11, 2016 DT News 39th death anniversary of Enamul Haque observed • Tribune Desk The 39th death anniversary of country’s first ever posthumous eye-donor ARM Enamul Haque was observed yesterday. Haque, a veteran social worker and prominent engineer, died in 2005 He had donated his eye before three years of his death. Later, his corneas were transplanted to Shahadat Chowdhury, editor of Saptahik 2000, and one Ramzan Ali. On the occasion, social workers of different organisations, groups, individuals, family members and journalists paid homages to his grave. A Milad and Doa mahfil was also arranged. Enamul Haque was born in Rajkhola area, Haora district, West Bengal on October 1, 1921. He had started his career in teaching profession in 1946. He was one of the founders of Dhanmondi Club. He was a linguist and was fluent in four languages. • A cargo laden covered-van turns turtle in Digraj area on the Khunla-Mongla Highway. Locals, drivers and port authorities alleged that the highway has become rundown, as big potholes had developed at several points of the roads. The photo was taken recently DHAKA TRIBUNE Rundown road makes Mongla’s goods transportation difficult • Hedait Hossain Molla, Khulna Nearly six kilometres of Khulna-Mongla Highway are in very bad condition and became unfit for vehicular movement, as big potholes have developed at many points of the road due to lack of repairs and maintenance. Goods transportation and other works of Mongla sea port and Mongla export processing zone are hampering due to the bad condition of the roads, said authorities. Of the 60 kilometres, six kilometres of Khulna-Mongla Highway became unfit for vehicular movement, said locals. During a visit to the roads, this correspondent found that a number of big potholes have developed on the roads making it risky for commuters but Road and Highway Department authorities do not take any initiatives to repair the roads yet. Locals alleged that Mongla is the second largest seaport of the country and the Khulna-Mongla Highway is the only road which connected Mongla with Khulna and Barisal. In 2013, Road and Highway Department had repaired the highway. After three years of repairing, this road has ruined and six kilometres from Digraj area to Belai on the highway are in very bad condition and became unfit for vehicular movement. As the road has become unfit for vehicular movement, thousands of trucks, lorries and passenger buses plying on the highway were stuck up on the road for hours, alleged locals. Officials of Mongla sea port, members of Navy and tourists who came in the area to visit world’s largest mangrove forest Sundarbans were also sufferings a lot due to bad condition of the road. Mongla Port Authority Chairman Rear Admiral Reaz Uddin Ahmed said: “This highway is very much important and we had tried to repair the road for several times in past with our own accord. We also requested Road and Highway Department to repair the road and they assured us that they will repair the road as soon as possible.” When contacted Mahmud Hasan, general manager of Mongla Export Processing Zone (EPZ), said: “We are suffering huge due to bad condition of Khulna-Mongla highway. Foreign investors also suffer when they came here in aiming to invest which discontent them to invest.” Mizanur Rahman, a fish trader of Mongla, said: “We need to use the road everyday to carry our fish to Khulna as most of the fish processing factories situated in Khulna. But due to dilapidated condition of Khulna-Mongla highway we have to spend at least 3 hours instead of 30 minutes to reach Khulna from Mongla.” Abdul Jalil, a bus driver on the route, said: “Due to big potholes in one side of the road, drivers use only one lane of the two lane road which is causing huge traffic jam.” Anisuzzaman Masud, executive engineer of Bagerhat Roads and Hoghways, said: “We have already called for tender to repair the road and hope we will able to start repair works very soon.” • News 7 FRIDAY, NOVEMBER 11, 2016 DT Post office still bearing name of Pakistani governor • Md Wali Newaz, Faridpur After forty four years of independence, a sub-post office at Titumir Bazaar in Faridpur town still carries the name of the then East-Pakistan’s governor Azam Khan. Lieutenant general Mohammad Azam Khan inaugurated the market while he was the governor of East Pakistan, present Bangladesh, from 1960-62. 5 rescued while being trafficked to Iraq illegally • FM Mizanur Rahaman, Chittagong The market, which was known as new market that time, was renamed Azam Khan Market and the post office was named Azam Market Town Sub-post Office. Though after the independence, the market was named Titumir Bazaar, the name of the subpost office remained unchanged. Md Khalilur Rahman, deputy commander of the district Muktijoddha Sangsad, an association of freedom fighters, and also a businessman of the market, said: “It is very shameful that after so many years of independence, a government organisation has been carrying the name of a Pakistani governor.” He said he had informed the district post office of the fact verbally, but they did not take any step. Mohammad Mohosin Uddin, postmaster of the district post office, told the Dhaka Tribune that he did not know about it. He, however, assured that he would take steps to change the name as soon as possible. Post-Master of Faridpur Post Office Mohammad Mohsin Uddin told the Dhaka Tribune that he was not aware of the matter. He also assured the correspondent that he would request higher authorities to rename the post office. • Two-day Lalon festival begins • Kudrote Khoda Sobuj, Kushtia A two-day Lalon Festival began yesterday at the Lalon Akhrah in Kushtia. Bangladesh Shilpakala Academy, Kushtia organised the festival. The festival will see many events such as musical events, discussions on Lalon’s philosophy, Lalon’s fair and so on. Organisers arranged a seminar titled at Lalon Academy auditorium where Bangladesh Shilpakala Academy, Kushtia, Director General Liaquat Ali Lucky, Additional Deputy Commissioner Mujib-ul-Ferdous, Islamic University, Kushtia VC Dr Abul Ahsan Choudhury were present. • The Rapid Action Battalion (RAB 7) rescued five fortune seekers from Chittagong Shah Amanat International Airport on Wednesday while they were being sent to war-torn Iraq illegally. “The five victims were rescued from the waiting room of Immigration of Chittagong Shah Amanat International Airport while they were waiting to board on a Qatar-bound Air Arabia flight”, said Senior Assistant Superintendent of Police (ASP), RAB 7 Md Sohel Mahmud. “They were handed over to Patenga police station and a case was filed in this connection”, said ASP Sohel Mahmud. On October 12, RAB personnel rescued 39 fortune seekers from the airport. • KUNIO HOSHI MURDER Court for appointing lawyer for accused at government’s cost • Liakat Ali Badal, Rangpur A Rangpur court yesterday gave directive to the government to appoint a lawyer for members of the banned Islamic outfit Jama’atul Mujahideen of Bangaldesh (JMB), who are accused in Japanese citizen Kunio Hoshi murder, at its own cost. Special Judge Nareah Chandra Sarkar passed the order after he came to know that no lawyer has been recruited for them. Five members of the JMB were produced before the court. The court A human chain was formed on Rajshahi University campus yesterday, protesting attacks in minority people across Bangladesh also fixed November 15 for the next hearing. On August 7, a court accepted the charge sheet pressed against eight members of the JMB in the killing case. The Court of Senior Judicial Magistrate Arifur Rahman also excluded five people, including BNP leader Rashedun Nabi Khan Biplab, from the case, as their involvement in the killing was not found during the investigation. Knunio Hoshi, 65, was shot in Kachu Alutari area on October 3, 2015. • AZAHAR UDDIN Bholaganj Land Customs Station counting losses as limestone import from India suspended • Mahammad Sirajul Islam, Sylhet Limestone import from India through Bholaganj Land Customs Station in Sylhet has remained suspended since Monday, causing an economic loss to the country. The forest department of the India village Majai, located in the taluk of Shella Bholaganj in Meghalaya, from where the limestone was imported through the land customs station, had not been giving car passes for limestone export to Bangladesh for several days, said Mujibur Rahman Mintu, secretary to limestone importers group of Bholaganj. The forest department was doing it, as Indian High Court had imposed a ban on extracting limestone from mines by machines on August 2015, said Mujibur. Due to the ban, limestone import through other land customs stations of Bangladesh had been decreased significantly, as the Indian exporters were now supplying limestone from their stocks, added Mujibur. Every day around three to four thousand metric tones of limestone were imported through Bholaganj, yielding about Tk1.1 to 1.2 millions revenue, said Abul Hossain, superintendent of the land customs station. Bashir Ahmed, former general secretary of limestone importers group of Bholaganj, said the sudden suspension of the import would affect the cement industry of Bangladesh, as limestone is the main raw material for producing cement. The price of cement might rise for this reason, he added. Besides, around 200 people, who worked in stone crusher mills in Bholaganj, have lost their earning sources, as the mills were dependent on limestone. • DT 8 World FRIDAY, NOVEMBER 11, 2016 SOUTH ASIA Pakistan: Trump may favour India Donald Trump’s surprise election as US president has Pakistanis wary that he may accelerate what they see as a shift in American policy to favour arch-foe India analysts said on Wednesday. Trump’s anti-Muslim rhetoric - he once proposed banning Muslims entering the US - and business ties to India are signs that his administration could shift further toward New Delhi REUTERS INDIA India SC orders Punjab to share river water India’s top court ordered authorities in northern Punjab state Thursday to share river water supplies with neighbouring Haryana state. The Supreme Court said the Punjab government’s decision to terminate the agreement via a state legislation was unconstitutional and defied the court’s own earlier orders calling for the canal’s completion. AFP CHINA China home to 9m ‘leftbehind’ children More than 9m children have been “left behind” in China’s countryside by parents who have moved to its towns and cities to find work, Beijing said Thursday. The plight of such children, who are usually looked after by grandparents but sometimes have no guardians at all, is one of the most emotive consequences of China’s decades-long economic boom. AFP ASIA PACIFIC Australia ratifies climate pact amid Trump fears Australia ratified the Paris climate agreement on Thursday, amid fears US president-elect Donald Trump could follow through on his pledge to cancel the landmark pact. Australia’s approval of the binding deal was delayed by national elections in July and its announcement Thursday came ahead of the departure of the country’s foreign and environment ministers for UN climate talks in Marrakesh. AFP MIDDLE EAST Coalition strike kills 20. AFP ANALYSIS How pollsters missed a Trump victory • Reuters, New York/London Two days ago, pollsters and statisticians gave Hillary Clinton odds of between 75 and 99% HOW THE POLLS MOSTLY GOT IT WRONG US presidential vote polling before the November 8 vote unrelated to one another as a series of 51 coin tosses.. In 2000, when Republican George W Bush beat Democrat Al Gore, for example, the turnout was about 60%, according to the US Percentage points favoring... Hillary Clinton Donald Trump +6 +5 +4 +3 +2 +1 Monmouth University NBC News/ Wall Street Journal Real Clear Politics (RCP, collated) Investor’s Business Daily/ TIPP* Tracking Economist/YouGov LA Times/ USC* Tracking Selected major polls/forecasts Nov 1 - Nov 7 Reuters/Ipsos Fox News ABC/Washington Post Tracking CBS News Final result (RCP) Clinton 0.2% ahead of Trump in the overall vote *University of Southern California **TechnoMetrica Market Intelligence Source: RealClearPolitics/LA Times/USC Tracking Supporters celebrate as returns come in for Donald Trump during an election night in Manhattan, New York Bloomberg Census Bureau. Eight years later, turnout was 64% when Democratic nominee Barack Obama won his first presidential election against Republican Arizona Senator John McCain.vember 3, for example, had REUTERSvember 7. That poll put him ahead in the popular vote by two percentage points, which in the end overstated his share by about three points.% of the population but only 10% of the Electoral College votes. Young said both pollsters and journalist described the results of the national polls and predictions with a false precision by presenting the result as near absolutes. • World Farmer suicide, banks call in police as India moves to ditch banknotes • Reuters, New Delhi/Mumbai A farmer in southern India committed suicide fearing she would be left penniless after the government’s shock decision to withdraw high denomination notes from circulation, police said Thursday. Indian banks called in thousands of police on Thursday to manage huge queues outside branches, as people tried to exchange bank notes abruptly pulled out of circulation by Prime Minister Narendra Modi in a crackdown on “black money”. Modi announced the shock move on Tuesday night to ditch Rs500 and RS1,000 notes - worth a combined $256bn - that he said were fuelling corruption, being forged and even paying for attacks by Islamist militants against India. Some people frustrated by the long wait got into arguments at Canara Bank near the parliament building in New Delhi, as people barged into queues that wound through the branch and on to the street outside. $2tn gross domestic product and who have low confidence in banks or plastic cards. Farmer commits suicide A farmer in southern India committed suicide fearing she would be left penniless after the government’s shock decision to withdraw high denomination notes from circulation, police said Thursday. Kandukuri Vinoda, 55, had a large amount of cash at her home in Rs1,000 and Rs500 rupee notes and panicked that her savings had become worthless when she heard Prime Minister Narendra Modi’s surprise announcement on Tuesday. Vinoda from Mahabubabad district, east of Hyderabad city, had sold some land last month and was paid around Rs5.5m for it in cash. She remote areas and to avoid paying taxes. Cash crunch Although a few people were able to exchange their old money for new notes, there were strict caps on account withdrawals and most came away with bundles of lower-denomination bills. People were allowed to make a one-time exchange of 4,000 rupees in cash and one-time account withdrawals of Rs10,000, capped at Rs20,000 per week. Cash dispensers remained closed and were due to reopen on Friday. • Jihadists fray soldiers’ nerves in Mosul battle • Reuters, Baghdad A week after his tank division punched through Islamic State defences on the southeast edge of Mosul, an Iraqi army colonel says the fight to drive the militants out of their urban stronghold is turning into a nightmare. Against a well-drilled, mobile and brutally effective enemy, exploiting the cover of built-up neighbourhoods and the city’s civilian population, his tanks were useless, he said, and his men untrained for the urban warfare they face. His Ninth Armoured Division and elite counter terrorism units fighting nearby seized six of some 60 neighbourhoods last week, the first gains inside Mosul since the October 17 start of a campaign to crush Islamic State in its Iraqi fortress. Even that small foothold is proving hard to maintain, however, with waves of counter attacks by jihadist units including snipers and suicide bombers who use a network of tunnels stretching 4km under the city. An Indian man displays new 2000 rupee notes outside the Reserve Bank of India in Mumbai on Thursday AFP A soldier of the Iraqi army walks on November 7, 2016, past ammunition and a tank confiscated from Islamic State group jihadists, in the town of Qaraqosh, Mosul AFP Toughest urban war border caliphate in Syria and Iraq from the pulpit of a Mosul mosque two years ago, told his fighters last week there could be no retreat in a “total war” with their enemies. Crashing waves Hashemi said government forces were only in full control of two of the districts they entered last week. The army says it has captured five other districts, but fighting continues in all of them and Hashemi said in some neighbourhoods the army had been driven back three or four times - often at night - before reclaiming territory the next day. With its tanks unable to navigate narrow city streets, the Iraqi army has called on US Apache helicopters to target car bombers. The Pentagon said on Monday they would continue to be used “in what we expect will be tough fighting to come”. • 9 FRIDAY, NOVEMBER 11, 2016 DT USA Trump lawyers head to court for upcoming fraud trial Lawyers for president-elect Donald Trump on Thursday will head to court for a hearing pitting the future leader of the US against a group of students who say they were defrauded by one of his businesses. The 2010 lawsuit was filed on behalf of students who say they were lured by false promises to pay up to $35,000 to learn Trump’s real estate investing “secrets” from his “handpicked” instructors. REUTERS THE AMERICAS Mexico won’t pay for Trump wall Mexico said on Wednesday it would work with Donald Trump for the benefit of both nations after his surprise US.election win but reiterated it would not pay for his planned border wall. Trump’s threats to dump the North American Free Trade Agreement agreement with Mexico and Canada, and to tax money sent home by migrants to pay for the controversial wall on the southern border. REUTERS UK Britain rethinks property fund rules British authorities are considering changing the rules governing commercial property funds to prevent a repeat of the investor panic that followed the country’s vote to leave the EU. Big funds worth around $22bn in total were forced to suspend their activities after running out of ready cash when investors who feared property prices would collapse demanded their money. AFP EUROPE Merkel’s conservatives warn of Trump effect German Finance Minister Wolfgang Schaeuble and other conservatives warned on Thursday that populists would pose a problem for Europe unless mainstream politicians responded after Donald Trump’s victory in the US presidential election. Trump’s win has shaken many European lawmakers ahead of elections next year, including in France and Germany. REUTERS AFRICA South Africa’s Zuma faces new no-confidence vote South Africa’s scandal-hit President Jacob Zuma faces a no-confidence vote in parliament on Thursday, but looks certain to survive despite mounting anger within his party. Zuma has fought off a series of damaging controversies during his presidency, and last week came under further pressure after a corruption probe raised fresh allegations of misconduct. AFP 10 FRIDAY, NOVEMBER 11, 2016 DT World INSIGHT US more divided than ever • Reuters, Ellsworth, Maine The 2016 US neighbour against neighbour. In a recent Reuters/Ipsos survey, 15% of respondents said they had stopped talking to a family member or close friend as a result of the election. For Democrats, this shoots up to 23%, compared to 10% for Republicans. And 12% had ended a relationship because of it. There was no comparative polling data from previous elections. But interviews with relationship counsellors. ‘People. Weeks ago, he planted a Clinton% white and 18% black. Interviews with residents suggested its northern areas, mostly affluent and white, would vote for Trump, while its mostly black, lower-income southern section would largely support Clinton. For some, the tensions reach the bedroom. Sam Nail, a Cincinnati marriage counsellor,. WHO VOTED FOR WHO? Based on exit polls November 8 Total national vote By demographic Hillary Donald Clinton Trump 53 Men Income level As of Nov 10, 1300 GMT Below $30,000 $30,000 -50,000 $50,000 -100,000 $100,000 -200,000 $200,000 -250,000 47.7% 47.5% More than $250,000 Source : NYT/Edison Research for the National Election Pool/RealClearPolitics 41 42 51 46 47 46 48 53% Clinton 50 Trump 48 49 48 0 10 % 20 30 40 54 80 90 100 Women White people Black people Hispanic/Latino Under-30s Over-45s City population +50k Small town/rural COULD TRUMP’S VICTORY HERALD POPULIST WAVE? After electoral upsets in U.S. and Britain, frustration with the political status quo – over issues from immigration to inequality – is likely to influence polls across Europe in the coming months Britain: Nigel Farage, acting leader of UK Independence Party and one of architects of Brexit vote, has hailed Trump’s 3 victory as “supersized Brexit” 5 1 Austria – Dec 4 1 Victory of Norbert 4 Hofer of Freedom Party over Green Party candidate 2 Alexander Van der Bellen in presidential elections could bring to power first far-right leader of western Europe since World War II 2 Italy – Dec 4 Failure by Prime Minister Matteo Renzi to win crucial referendum on constitutional reform, could push anti-establishment Five Star Movement of Beppe Grillo closer to reins of power 4 France – May 7, 2017 5 Germany – autumn 2017 Marine Le Pen, leader of far-right National Front, far outpolls President François Hollande ahead of springtime Frauke Petry, whose Alternative for Germany (AfD) has hurt Chancellor Angela Merkel’s conservatives in elections. Fewer people now rule out her chances of victory after Trump upset series of regional elections this year, is climbing in opinion polls ahead of national elections next year Pictures: Getty Images Ellsworth resident at odds with his sisters, witnessed the election’s political vitriol first hand. Foster’s van was one of 20 vehicles spray-painted outside a Trump rally on October 15 in the city of 53 55 58 59 62 65 3 Netherlands – Mar 15, 2017 Geert Wilders, leader of anti-Islam Freedom Party who wants to emulate Britain with “Nexit” vote, running neckand-neck with Prime Minister Mark Rutte’s Liberals (VVD) in polls ahead of parliamentary elections © GRAPHIC NEWS Bangor. And across Ellsworth, pro- Trump yard signs were stolen almost as fast as they were planted, Republican officials say. Foster worries about the divisions ahead. • 88 World 11 FRIDAY, NOVEMBER 11, 2016 DT Al-aqsa mosque ANALYSIS Trump’s win means end of Palestinian state era • AFP,, said last month that he does not believe Trump sees Jewish settlements in the occupied West Bank as illegal, as nearly all the rest of the international community does. Asked whether he believed in the twostate solution, the basis of more than two decades of peace negotiations, Friedman said Trump was “tremendously sceptical”. The Israeli right has welcomed such statements and seized on Trump’s victory to promote its cause – including, for some, a call to bury the two-state solution once and for all.. REUTERS Netanyahu congratulated Trump and pledged to work with him, and the two men spoke by telephone on Wednesday. “The two leaders, who have known each other for many years, had a warm and heartfelt conversation,” a statement from Netanyahu’s office said.mud Abbas congratulated Trump and said he hoped peace could be achieved during his term based on the borders of 1967, the year Israel occupied the West Bank. However, a high-ranking Palestinian official saidbn a year in military aid.• DT 12 Business FRIDAY, NOVEMBER 11, 2016 TOP STORIES Investors exuberant as Donald Trump signals shift from austerity era European stocks rose yesterday following extraordinary gains in Asia and the United States, as exuberance shot through markets and reversed initial dives in reaction to Donald Trump’s US presidential victory. PAGE 13 Japan lawmakers approve TPP despite Trump victory Japan’s lower house of parliament yesterday passed the contentious Trans-Pacific Partnership (TPP) free trade deal, a move largely viewed as an empty gesture due to opposition by US president-elect Donald Trump. PAGE 14 Economists see pain, then gain for India after bank note shock India’s shock move to take larger bank notes out of circulation will hit Asia’s third-largest economy in the short term, but pain will turn to longer-term gains including transparency, higher tax revenues and lower inflation, economists said. PAGE 15 Capital market snapshot: Thursday DSE Broad Index 4,677.1 0.1% ▲ Index 1,122.5 0.1% ▲ 30 Index 1,758.2 0.1% ▲ Turnover in Mn Tk 6,459.6 16.4% ▲ Turnover in Mn Vol 138.6 3.3% ▲ CSE All Share Index 14,387.6 0.1% ▲ 30 Index 12,978.8 0.3% ▲ Selected Index 8,753.0 0.1% ▲ Turnover in Mn Tk 330.0 -19.8% ▼ Turnover in Mn Vol 8.6 -23.0% ▼ Inflation edges up to 5.57% in October • Tribune Business Desk Inflation in Bangladesh rose to 5.57% last month driven by the higher prices of food, government data showed yesterday. It was slightly up from 5.53% read in the previous month. According to Bangladesh Bureau of Statistics (BBS), food inflation, which is more important in developing countries like Bangladesh, where a large amount of household incomes are spent on food, slightly increased to 5.56% in October from 5.10% in September. Non-food inflation, however, decreased to 5.58% from 6.19% during the period. While releasing data at the NEC conference room, Planning Minister AHM Mustafa Kamal said: “Higher food prices, particularly INFLATION RATE FROM APRIL TO OCTOBER THIS YEAR ( IN%) April 5.61 May 5.45 June 5.53 July 5.40 August 5.37 September 5.53 October 5.57 Source: BBS rice, vegetables, salt, oil, sugar and milk, pushed up inflation.” He, however, said food inflation in October last year was a bit higher as it was 6.19%. The government fixed the target to contain inflation at 5.8% for the fiscal year 2016-17. In rural areas, the inflation rate in October was 4.87%, which was 4.63% in September, and in urban areas, it declined to 6.87% from 7.21%. In rural areas, food inflation moved up 4.89% from 4.27%, and in urban areas, it climbed to 7.9% from 7.3% during the period. In case of non-food inflation, it was down 4.23% from 5.31% in rural areas, while it fell 6.63% from 7.42% in urban areas. The point-to-point national wage index witnessed an increasing trend with 6.16% in October, up from 6.09% in September. The average year-on-year rate of inflation from November 2015 to October 2016 also declined to 5.66%, which was 6.21% from November 2014 to October 2015. • Muhith urges businessmen to accept new VAT law Finance Minister AMA Muhith launches Tax Guide at a programme in the ministry auditorium in the city yesterday ASIF SHOWKAT KALLOL • Asif Showkat Kallol Finance Minister AMA Muhith said the country’s value-added tax is “reasonable” and so the businessmen shouldn’t object to it. “The old Dhaka businessmen are against introducing the new VAT law, but I want to tell them that the new uniform VAT rate is reasonable,” he said while launching Tax Guide at the finance ministry’s auditorium yesterday. Muhith, however, said the rate would be reduced if the amount of VAT increased annually. He said Bangladesh is one of the pioneer countries to introduce such a VAT law. Muhith ruled out the possibility of double taxation. “If this happens, this is wrong calculation.” He insisted uniform 15% VAT rate will be good for the business. Earlier this month shop keepers in Dhaka protested against the new VAT law keeping their shops closed and organising rallies. “I was actually disappointed at the strike. They (businessmen) shouldn’t go for it again,” finance minister said. He said the VAT law was first introduced in France and later in the United Kingdom, and the VAT rate varies from 5% to 20% in different countries. Muhith said he would lower the country’s VAT rate if the number of taxpayers become 50,000. “I would promise to lower the rate of VAT. I said the first time we have a uniform rate of 15% but if you want I will change that rate.” At present, the number of registered businessmen taxpayers are 7.7m businessmen, but only 1.1m of them pay VAT. Muhith said the government would procure 20,000 electronic cash register machines from aboard and supply to the businessmen at import price. • Ecnec okays projects worth over Tk9,600cr • Tribune Business Desk Executive Committee of the National Economic Council (Ecnec) yesterday approved 12 projects worth nearly Tk9,664 crore mainly related to river route development, power transmission and road communication works. The approval came at the Ecnec meeting with Prime Minister Sheikh Hasina in the chair at the NEC conference in the city yesterday. Following the meeting, Planning Minister AHM Mustafa Kamal disclosed the meeting outcome. Of the approved project costs, Tk4,255.38 crore will come from public coffer, Tk533.08 crore from the project-related public agencies’ own fund and Tk4,875.53 crore as project assistance. Of the approved 12 projects, nine are new while three are revised ones. Bangladesh Regional Domestic Shipping Transport Project-1 is one of the 12 approved projects, of which the estimated cost is Tk3,200 crore, aiming to ensure safe passenger journey and goods transportation on Ctg-Dhaka-Ashuganj river route. About the project, the minister said Bangladesh river route will be a super corridor for the South Asian region, and considering this, the project was approved. The Ecnec also gave the nod to other projects, including Tk286.75 crore for Jhenaidah-Chuadanga-Meherpur-Mujibnagar Highway Development, Tk97 crore for Police Station and Barrack Construction, Tk70.7 crore for Three Guarder Bridge Construction in Jamalpur-Madaripur Highway, Tk2,982.38 crore for Power Grid Development, Tk910 crore for setting up Compressor Wellhead at Titas gas field, Tk869.71 crore for Land Acquisition, Land Development and Rehabilitation to construct 1,320MW cola-based power plant in Patuakhali. • Business 13 Investors exuberant as Donald Trump signals shift from austerity era • Reuters European stocks rose yesterday following extraordinary gains in Asia and the United States, as exuberance shot through markets and reversed initial dives in reaction to Donald Trump’s US presidential victory. Investors focused on Trump’s priorities - including tax cuts and higher infrastructure and defense spending, along with bank deregulation - and set aside for the moment longer-term worries about whether he will slap punitive tariffs on Chinese and Mexican exports, risking a global trade war. European stocks hit a twoweek high, with the pan-European STOXX 600 index up 1.3% in early dealings, and “safe haven” government bonds sold off after Trump suggested he would spend billions on infrastructure. This marked an abrupt change from the sharp recoil on markets on Wednesday after the Republican candidate’s triumph. Investors saw signs that Trump will ditch the budget austerity policies that Western governments have pursued since the 2008 global financial crisis after he takes over in Jan,” said Craig Erlam, senior market analyst at OANDA. “The stance he takes on trade will likely determine how vulnerable the markets are, but in reality these are very long-term policies and for now, markets are more focused on the prospect of lower taxes, fiscal stimulus and less regulation.” The three major US stock indexes rose on Tuesday and the dollar index against major currencies recovered from a trough of 95.885 plumbed on Wednesday to around 98.778 on Wednesday morning. In a remarkable session for Japanese shares, the Nikkei jumped 7 percent at one point after sinking 5% on Wednesday. Gains in Europe, where markets had already started to recover on Wednesday, were more modest. Britain’s FTSE was up 0.95%, Germany’s DAX rose 1.12% and France’s CAC was up 1.06% by 0415 ET. The moves were led by Wednesday’s sharp rises in US Treasury yields. The 30-year Treasury bond yield gained almost 25 basis points in its sharpest rise in more than five years; yields on the 10-year note climbed 21 basis points to breach the 2% mark for the first time since January. High-rated euro zone bond yields - which had sunk early Wednesday - rose sharply on Thursday, with the region’s benchmark German 10-year bonds up 5 basis points to 0.23%, the highest level since May. End of austerity? Trump’s victory and opening comments have sharpened a debate about the austerity consensus that has prevailed across most of the developed world since the financial crisis. If his actions match his rhetoric, it seems likely that Trump’s administration will test the theory of whether central banks’ cuts in interest rates to ultra-low levels and money printing should be replaced by budget measures to boost the world economy. “It looks like Trump will aim for a more fiscally accommodative policy at a time when they seems to be a shift in major economies towards fiscal policies,” said Investec economist Philip Shaw. “The big unknown is how the rest of the Republican party to react to this, as there are many fiscal hawks among them.” Ratings agency S&P Global on Tuesday affirmed the AA+ credit rating of the United States, but noted uncertainty over the future path of government debt would prevent any upgrade. There were also lingering concerns about Trump’s campaign promises to shield American jobs through possible protectionist trade policies. Among Asia’s trade-reliant economies, China and South Korea are particularly exposed to any hostile U S measures as they run large trade surpluses with the United States, Credit Suisse said in a research note. • IEA may see global market awash with oil in 2017 • Reuters The oil market surplus may run into a third year in 2017 without an output cut from OPEC, while escalating production from exporters around the globe could lead to relentless supply growth, the International Energy Agency said yesterday .. • DT FRIDAY, NOVEMBER 11, 2016 Walton gets good response at Lagos Int’l Trade Fair 2016 • Tribune Business Desk Walton’s electronics and home appliances got huge response from the African consumers at the 30th edition of Lagos International Trade Fair 2016 in Nigeria. A 10-day mega show, which began on November 4 at Tafawa Balewa Square of the Nigerian capital of Lagos, will continue till Sunday Walton, a Bangladesh manufacturer of electronics and home appliance products, has participated at the mega expo in the African country for the first time to show Made in Bangladesh brand, said a press release. Walton displayed its several products including intelligent inverter technology’s refrigerators, air conditioners, LED televisions, blenders, induction cookers, LED bulbs and other electronics and electrical household appliances. “The entrance of Walton products in Nigeria is a good sign for African’s electronics market and I hope there is a big market of electronics products here due to uniqueness and highest standard,”said Nunne David, a Nigerian entrepreneur. David also said: “We are looking forward to witnessing a big boom of Walton product’s sales due to the participation in this largest fair of the African continent.” Besides, the sound acceptability of Walton products will increase the trade relationship between Nigeria and Bangladesh, he added. While visiting Walton pavilion at the fair, Md Aminul Haque, an expatriate Bangladeshi and Managing Director of ASA Microfinance Bank Limited in Nigeria, stated that he is very proud to see the presence of the leading Bangladeshi electronics brand Walton in Nigerian Market. • BRAC Bank organises a Town Hall meeting with the theme “All for One, One for All” in Sylhet to review business performance of 2016 and set business strategy for 2017 and beyond. All employees of Sylhet area took part in the meeting. Selim RF Hussain, managing director & CEO, BRAC Bank Limited, and senior officials of the bank attended the programme BGMEA Vice-President (Finance) Mohammad Nasir, Director Md Monir Hossain, Sociability CEO Ms Elizabeth Boye, Danish Fashion & Textile Project Manager Ms Sofie Pederson and CSR chief Ms Pia Odgaard at an award-giving ceremony in the city yesterday. A total of 11 trainees were given CSR certificates under the Step-Up Programme jointly organised by BGMEA and Danish Fashion and Textile 14 FRIDAY, NOVEMBER 11, 2016 DT Business Japan lawmakers approve TPP despite Trump victory • AFP, Tokyo Japan’s lower house of parliament yesterday passed the contentious Trans-Pacific Partnership (TPP) free trade deal, a move largely viewed as an empty gesture due to opposition by US president-elect Donald Trump. President Barack Obama championed the 12-nation deal saying it would enable the United States to set the global trade agenda in the face of China’s increasing economic clout. But Trump has strongly opposed the deal, casting a huge shadow over its future. percent of the global economy. The TPP is seen as a counterweight to China, as Beijing expands CORPORATE NEWS its sphere of influence and promotes its own way of doing business - seen as often running counter to largely Western-set global standards that emphasise transparency and respect for human rights and the environment. Japanese Prime Minister Shinzo Abe has made the TPP a pillar of his economic platform to revive the nation’s key exports sector. But experts say that with Trump’s election the deal is a non-starter. “Japan’s hopes for the TPP (are) dead and buried,” Marcel Thieliant, economist at Capital Economics, said in a note. • Rupayan Housing Estate Ltd has recently handed over its 65th project named Rupayan Hozaifa, said a press release. The company’s managing director , Captain PJ Ullah (retired) was present on the occasion among others Delta Life Insurance Company Ltd has recently celebrated its 30th anniversary, said a press release. The company’s chairperson, Monzurur Rahman inaugurated the celebration programme Mercantile Bank Limited has recently held its 293rd board meeting, said a press release. The bank’s chairperson, Shahidul Ahsan presided over the meeting Economists see pain, then gain for India after bank note shock Business 15 Smart City Hackathon begins today • Ishtiaq Husain The first-ever Smart City Hackathon begins today at GPHouse, the corporate head office of the Grameenphone. Organized by Preneurlab and White Board, an initiative of Grameenphone, the hackathon aims to find digital solutions for many problems of Dhaka. The capital of Bangladesh is the one of the largest mega cities of the world but scores poorly in habitability scale. Dhaka North City Corporation Mayor Annisul Huq will inaugurate the 36 hours long hackathon to be participated by 30 teams. The winning team will win three months co-working space at White- Board with access to GP’s digital ecosystem. DT FRIDAY, NOVEMBER 11, 2016 White-Board will provide relevant knowledge and asset support to solidify the winning prototype. A special demo day will be arranged through White- Board for commercial presentation. A six-month start-up mentorship support will be provided by Preneur Lab in addition to a 6-month mentorship from IEEE BDS and IPR as well as incubation support from Dnet (Junction). • •. A customer deposits 1000 and 500 Indian rupee banknotes in a cash deposit machine at bank in Mumbai REUTERS than expected, after it lowered it by a quarter percentage point last month. • Stocks post marginal rise • Tribune Business Desk Stocks witnessed a marginal rise yesterday amid upbeat mood. The benchmark index of Dhaka Stock Exchange DSEX inched almost 6 points or 0.2% up to 4,677. The DS30 index, comprising blue chips, rose only over 1 point to 1,758. The DSE Shariah Index DSES gained only over 1 point to 1,122. The Chittagong Stock Exchange Selective Category Index CSCX rallied 11 points to 8,752. As foreign investment in Bangladesh stock markets is insignificant, local stocks gave cold shoulder to the US election, analysts say. The DSE total turnover crossed Tk600 crore level again by the end of the session. Trading was concentrated mainly on power and engineering sectors, which together accounted for more than 30% of the total turnover. On the sectoral front, textile and tannery sectors performed pretty well, rising 0.8% and 0.6% respectively. Conversely, telecommunications and non-banking financial institutions declined 0.7% and 0.6% respectively on profit booking. Of the total 320 issues traded on the DSE, 135 closed positive, 130 negative and 55 remained unchanged. Apex Footwear was the highest traded share with a turnover of about Tk33 crore. • 16 FRIDAY, NOVEMBER 11, 2016 DT Travel Exploring Singapore’s Chinatown •Eliza Binte Elahi I can’t help but think about the bustling markets, narrow streets, and delicious street food, whenever I hear the word ‘Chinatown.’ Singapore has always been one of the most popular business or vacation destinations in Southeast Asia. For the shopaholics in this region, there is no other place better, than the famous Chinatown, especially when it comes to the numerous street markets which are widely popular among locals and tourists alike. From authentic souvenirs and local art/crafts, to the colourful street markets, the mesmerising city of Singapore has a lot to offer to its visitors. Singapore’s historic place, Chinatown is a vibrant mix of both, old and new. Colonial shops and houses, restored and painted in candy hues, are home to the traditional stores and cafes. The streets bustle with tourists looking for cheap but unique souvenirs, as well as locals going about their daily business. You’ll find Buddhist and Hindu temples, markets and mouthwatering street food. Singapore is regarded as one of the cleanest cities in the world. Conveniently accessible from my hotel, Singapore’s Chinatown immediately gave me the impression that it is indeed one of the most cleanest city I have ever seen. Although Chinatown is clean compared to the rest of the places I have visited, there is still some noticeable rubbish here and there, but definitely nothing to fret about. I particularly liked the significant contrast between the historical buildings making up Chinatown, and the super modern high rise buildings that hover in the background. If you have time, I would recommend you to try to capture the transition from the past to the present on camera, if you happen to be in Chinatown. Many of the boutique hotels and guest houses in the district are nicely preserved with charming colour combinations and shutters, to make you feel like you are travelling back in time. After walking around Chinatown for 3-4 hours, I began to take notes of the things I truly adored. One particular thing would be watching the locals. It’s one of those rewarding activities that are absolutely free, yet very interesting. Chinatown in Singapore, is an ideal place to observe how wealthy and budget tourists, local hawkers, stall workers, children and teenagers, together create a truly unique atmosphere. Tourists who appear to have no intention of buying things are suddenly bartering over two dollar key chains and counterfeit t-shirts. Children are seen trying to convince their parents, to get them some tasty street-side snacks. Hawkers trying to sell squid balls to tourists. Yeah, that’s Chinatown. I also couldn’t help but notice the broad array of tiny shops and restaurants, that are somehow jammed into the streets of the district, even the narrowest ones. Many Western cities are unfortunately burdened by so many by-laws and red tape, that it is next to impossible to create such a crammed, energetic ambiance like the one that can be experienced in Singapore’s Chinatown. I remember coming across a striking temple one day, when looking around the shops. Maybe the reason why it remains so memorable is the fact that it is a Hindu Temple located right in the heart of Chinatown? After some research that evening, I found out that it was a Sri Mariamman Temple – the oldest Hindu temple in Singapore. Since it was originally built in 1823, I hope you can imagine the contrast created between the temple and the skyscrapers of Singapore’s central business district looming behind it. I thought its colours were very vivid and the sacred cow sculptures were a strong reminder of Hinduism. The following are the street markets of Chinatown in Singapore that are worth visiting. Pagoda Street Markets After departing from the Chinatown MRT station, the first thing which will remind you that you’ve entered the shopping district, are the stalls that line both sides of the street. traditional Chinatown and Singapore souvenirs. Temple market is located along the left side of Smith Street. It is a street for the pedestrians only (no vehicular traffic allowed even bicycles). On both sides, the street is lined with one food stall after another, selling some of Singapore’s most popular local dishes. Just a word of caution though. The area is geared towards the tourist so it can get a bit pricey at times. Unfortunately, many of the food stalls have shut down over the years. Although it sounds like you have a lot to see and do, most of the Chinatown Food Street area can be covered within a couple of hours. Of course that depends entirely on you and how much time you spend shopping and snacking in this area. Make sure you visit The Chinatown Complex and the Maxwell Food Center. You’ll find lots of colourful souvenir shops and stalls, as well as one of the only places to find a traditional bamboo steamed Indonesian desert, called Putu Piring. It’s a delicious, and not so sweet, coconut cake with a sugary filling. You can easily miss the store as it is not that noticeable, so keep an eye out as it is at the end of Trengganu Street. One thing that I couldn’t help but notice was that the level of restoration work may have been too thorough. In other words, it felt a bit synthetic at times, with some streets covered with artificial ‘rain protectors’ and so forth. This doesn’t take away from the fact that there is still the beautiful architecture and world class temples. It has the scrumptious street food, the atmospheric Chinese lanterns, the beer stalls, and all the tiny trinkets that tourists love to buy. Although, I didn’t buy too much, I can honestly say that Chinatown is definitely a worthwhile site to explore while in Singapore, especially for those who want to see modernity clash with the historic architecture and customs. • The writer is a faculty at School of Business University of South Asia, Dhaka Feature 17 FRIDAY, NOVEMBER 11, 2016 DT ‘I want to challenge myself’ DT catches up with DLF panellist Prabda Yoon • Baizid Haque Joarder Prabda Yoon is a man who wears many hats - the writer, translator, graphic designer, publisher, and filmmaker, is also one of the many panellists to star at the Dhaka Lit Fest. Based in Bangkok, Yoon is considered by many to be the voice of Thai youth. He won the S E A Write Award in 2002, and is responsible for running the publishing house Typhoon Studio. Before journeying to Dhaka for the Dhaka Lit Fest, Yoon gives us a brief glimpse into his life and work. When people think you’re being rebellious or that you’re intentionally opposing the norm they can be hostile towards you Writer, translator, graphic designer, publisher and filmmaker - how does Prabda Yoon manage it all? I don’t do them all at the same time, of course. A lot of what I do involves writing and storytelling, so I would say that my work is in literature and publishing mostly. However, everything I do falls under the “art” umbrella, in my opinion. You are credited with introducing post-modernist techniques into contemporary Thai literature and breaking the rules while at it. What was your inspiration, and what was the journey like? I had no intention to introduce anything into anything, let alone breaking any rules. But I think because I am generally inspired by the so-called “avant-garde” and experimental artistic works, my own work also tends to reflect that. When people think you’re being rebellious or that you’re intentionally opposing the norm they can be hostile towards you, but I understand that. I don’t work to offend. If anything, I want to challenge myself. If my work appears to be different from the majority of works out there, it’s because I want to see if I can do something to impress myself more than to break the rules of others. What is your philosophy behind translations? I want the readers to get close to the feeling of reading the original prose as much as possible. The feeling, not the exact meaning of the words. For example, with Lolita I wanted Humbert Humbert to come across in the Thai text as the original Humbert Humbert, not some imposter that has been modified or transformed by the translator’s strict philosophy of translation. Some people translate beautifully because they’re good with language, but their text is totally different from the original. That’s not my way. I don’t want to show off my own style when I translate. For someone interested in Thai literature, what would you recommend? Where do they start? A lot of what I would recommend has not been translated into English, unfortunately. I would love to suggest something by Rong Wongsawan, but he was never translated. What is your take on the art of film-making? What issues do you wish to highlight in your films? Filmmaking to me is unique in the way that it’s a combination of almost all artistic practices. At least it has everything I’m interested in: storytelling, photography, design, sounds, music, etc. And it terms of production it’s a collaborative work which is something very challenging and rewarding for me. And I think the content of my film is also about challenge. What are you reading at the moment? I am always reading a few books simultaneously. At the moment I am reading When the Word Becomes Flesh by Paolo Virno, and a book on cocktails, by Richard Godwin called Spirits. How do you feel about attending the Dhaka Lit Fest? Very excited, of course. I’ve never been to Bangladesh. I’m always thrilled to be in a new place.• 18 FRIDAY, NOVEMBER 11, 2016 DT Feature CineQ 2016 ends with flying colours •Syed Rasseque Tasin CineQ 2016 has been the talk of the town ever since it was launched by the Enliven Youth Platform and presented by Enliven Cinema Club. The cinema based quiz competition event received tremendous response, especially from the youth. On October 28, the event took place at St. Joseph Higher Secondary School with a participation of almost 500 students from various schools, colleges and universities. It was the first national quiz competition based on movies. Our country has always been able to produce a profound, cultural atmosphere and such events help to nurture the historical and cultural appreciation in the youth. The event started on Friday morning at around 10 am with an opening speech by the Founder of Enliven, Adnan Kabir. The distinguished personality shared some stories about the formation of Enliven Cinema Club and how it started its journey. Later, Asif Yeasin Kabir, Founder of Enliven Youth Platform shared with everyone about how he came up with an event, CineQ 2016 and how to transform “me” to “we” concept and worked with a team of twenty energetic team members. The event was launched within a week of planning and took only 25 days for the total operation. Within this short time frame, the program has successfully registered more than 120 teams from schools, colleges and universities inside and outside Dhaka. Later at around 11 am the participants were asked to go to their respective classes in order to attend the written examination, the first round of the competition. It took about an hour for the exam to end. In the meantime, the judges had already started their work on checking the papers submitted by the participants. Around 3pm, the second round of the event commenced. This one was more intense and competitive than the previous round. Six teams from Round 1 had qualified for this round, and had to pick the right films from visual cues. During the breaks, questions were thrown to the crowd for audience participation, so an atmosphere of sport prevailed. The spot quiz winner received the gift hampers from Solid Style. Many keynote speakers and guests visited the program, including Zakir Hossain Raju [Filmmaker], Khalid Saifullah Mahmud [CEO of Dona Media], Nahid Masud, [Sound expert] and Mir Samsul Alam Baboo [Researcher, Federation of Film Society Bangladesh]. Their short speeches helped to underscore the objective of “cineQ 2016” program: to generate a higher appreciation Our country has always been able to produce a profound, cultural atmosphere and such events help to nurture the historical and cultural appreciation in the youth for film and to nurture the very best of knowledge, inspiration and information among the youth. The top 3 teams from each group received certificates and were given gifts and prizes. The winner of the CineQ 2016 received the crest and prize money worth of 10,000 BDT presented by Meraki from the chief guest of the program, Abdul Aziz, Chairman of Jaaz Multimedia. SJHSS Catechizers, 3 Quarters and Ravenclaw are the three champion teams from three groups respectively. Furthermost, they received a gift from Pathak Samabesh, a premier book store and the gift partner of the event. A short film competition was arranged sidewise and the winning short film Innocent received prizes from amadercinema.com. Although there were some limitations regarding the whole event, the weather and the electricity to name some, the organisers are confident they shall prevail next year when CineQ 2017 returns. Apart from this, Enliven Youth Platform will open the second general member recruitment drive for their next big event. • Biz Info 19 FRIDAY, NOVEMBER 11, 2016 DT | workshop | Innovation project design at BCS Administration Academy The innovation team of Biman Bangladesh Airlines participated in the ‘Innovation project design’ workshop was held November 8-10, at BCS Administration Academy, Shahbag, Dhaka. Biman submitted two projects on ‘online ticketing through mobile banking,’ and ‘on-line check-in service and issuing boarding card,’ at the workshop organised by the cabinet division and access to information project of the Prime Minister’s office. Shakil Meraj, general manager (PR) attended the workshop as the resource person of Biman. • | session | | event | Rise Above All: The Tale of Game Changers Global Brand hosts a glitzy event with Dell partners Every tale of success is built with numerous tales of struggles. To share those tales Don Sumdany Facilitation and Consultancy is organising ‘Sailor presents Rise above all November 18 at KIB Auditorium. This will be the biggest public speaking session of Bangladesh with an estimation of 1000 participants. Renowned experts from the field of business, entertainment, music and so on will be present at the session. They will share their stories of success, failure and inspiration. They will also share how they become what they are now, and what it takes to be extraordinary amidst the ordinary. The speakers of this daylong speaking session are: Tahsan Khan, Singer, Song writer, Actor and Academic; Rubaba Dowla, Ex Chief Communication Officer and Customer Service Officer, Grameen Phone and Airtel Bangladesh; Mostofa Sarwar Farooki, Film Director; Zara Mahbub, Senior Vice President, Head of Communication & Service Quality at BRAC Bank Limited; Ali Reza Iftekhar, Managing Director & CEO at Eastern Bank Limited; G. Sumdany Don, CIO, Don Sumdany Facilitation and Consultancy. Sailor is the title sponsor of the event and it is powered by Cooper’s Bakery. The co-sponsors of the session are Swapno, Symphony, Omicon Group. The payment partner is bKash. Dhaka Tribune is the proud media partner of the event. Other partners are Gtv, bdnews24. com, United News of Bangladesh (UNB), Bangla Tribune, ColorsFM 101.6, EMK Center, Vertical Horizon and Bangladesh Organization of learning and Development (BOLD). For more information: DonSumdany Event Link: D3E53y • Global Brand Pvt Ltd, the distributor of Dell in Bangladesh has organised a program named ‘Dell Partner Meet,’ on November 9, at Emporium Banquet Hall, in Dhaka. In this exclusive program, Global Brand is basically presenting their new Dell laptops, and even communicate with their partners. A K M Dedarul Islam, deputy general manager of Global Brand, discussed about the new line-up of Dell laptops. From now on Inspiron, Vostro, Latitude, and XPS will be available in the market. Atiqur Rahman, country manager of Dell, was present in the program. Moreover, the chairman, Abdul Fattah, managing director, Rafiqul Anwar, and director, Jashim Uddin, were also present along with the authentic Dell partners, at the event. • DT 20 Editorial FRIDAY, NOVEMBER 11, 2016 TODAY The dead end of history Trump may be a successful businessman, but he is short on ideas, never mind an ideology PAGE 21 Billionaire manages stunning upset The arcane system ensured Trump will have access to the country’s nuclear weapons even if he did not get a majority of the votes PAGE 22 A bad day for Planet Earth REUTERS America’s white-lash elects Trump If the Americans consider Donald Trump worthy of their highest elective office, the world should not quibble. This was a contest between rural and urban America. For once, rural America won PAGE 23 Be heard Write to Dhaka Tribune FR Tower, 8/C Panthapath, Shukrabad, Dhaka-1207 Send us your Op-Ed articles: opinion.dt@dhakatribune.com Join our Facebook community: DhakaTribune. The views expressed in Opinion articles are those of the authors alone. They do not purport to be the official view of Dhaka Tribune or its publisher. President Trump is bad news for many reasons, but his stance on climate change has to be the most damaging one. Trump’s first move since being elected president of the United States has been to hire Myron Ebell, a well-known climate change denier, to head his Environmental Protection Agency. This will set America, and the world, back in irrevocable and harmful ways. The move shows that Trump has every intention to bring to fruition his plans for a less environmentally friendly America. Hiring an individual who has called climate change “nothing to worry about” does not bode well for the rest of the world. With COP22 currently in progress in Marrakech, Morocco, it is more important now than ever to ensure that climate change is seen as a real threat, and we do everything in our power to prevent its negative impacts. This is especially important for Bangladesh, one of the countries most vulnerable to climate change and its impacts. Countries such as ours should hold their own at conferences such as the COP22 to ensure that the developed world doesn’t continue to take advantage of our vulnerabilities. Continued investment in renewable energy and cutting down on the use of fossil fuels are crucial if we want to keep global temperature rise to a minimum. For this to happen, the leader of the most powerful country needs to be on board. It is clear that he is not. A president who has repeatedly denied the existence of climate change, going as far as to call it being manufactured by the Chinese government, will mean disaster for all of us. Let us hope, though, that this is not the case. Trump has won, and for better or worse, the world has to deal with it. The world needs to come together in the fight against climate change. We cannot afford to derail this now. A president who has repeatedly denied the existence of climate change, going as far as to call it being manufactured by the Chinese government, will mean disaster for all of us The dead end of history Opinion 21 The 1990s was the decade of hope to end a century of division. We need them again DT FRIDAY, NOVEMBER 11, 2016 political landscape in 2016 has gone viral thanks to a New York real estate tycoon with an ego as grotesque as his bank balance. Trump built the campaign he prefers to call a “movement” around his social media presence and off-the-cuff, rambling speeches. Both suited his swashbuckling style. Twitter, in particular, provided a turret through which he could fire at will, at any time and at anyone. That won’t do now. Trump may be a successful businessman, but he is short on ideas, never mind an ideology. He can still find these, of course, but any resetting of his moral compass in line with his new office may take time the world simply does not have. His inauguration at the end of January 2017 will be followed by bellwether national elections in the Netherlands, France, and Germany. However grand the party held at the Manhattan Hilton on Tuesday night, it could not possibly have matched those thrown by Geert Wilders in The Hague, Marine Le Pen in Paris, or the AfD in Berlin. All three congratulated Trump before he had even congratulated himself. Bitterness, division, acrimony, intolerance Trump may be a successful businessman, but he is short on ideas, never mind an ideology • Phil Humphreys It was “The End of History,” Francis Fukuyama proclaimed in 1992. The Berlin Wall had been brought down and the Iron Curtain forced open. Germany was reunited while the Soviet Union had disintegrated. The American political scientist knew the plates had shifted for good. And who could argue? Capitalism had won. Communism was discredited. The final form of human government had been found and (almost) everyone agreed. In the 10 years that followed, the world came in from the cold. The European community became a union, leading to a single currency and central bank. The World Trade Organisation came into existence and the African Union was conceived. The Oslo Accords gave Israel and Palestine a pathway to coexistence. The Dayton Agreement ended the bitter Bosnian War and the Good Friday Agreement brought peace to Northern Ireland. Apartheid was overthrown in South Africa and a Rainbow Nation was born in its place. Latin American liberal democracies flourished where military dictatorships had ruled. Even Cuba began accepting US aid. It was not all rosy, of course; the Rwandan genocide and Kosovo conflict left deep wounds. But it was overwhelmingly a decade for agreements, accords, unions, and reunifications. And what now? A world turned in on itself REUTERS It seems only bitterness, division, acrimony, and intolerance. A Great Britain under constitutional threat from Brexit forces. Right-wing parties on the rise across a fractured Europe. The Middle East roadmap in tatters. A failed Arab Spring. Syria at war, and IS on the march. Terrorism everywhere. At the same time, China is colonising the developing world via economic stealth, while Russia uses covert military and cyber warfare to intimidate neighbours it can annex, and destabilise opponents it cannot. Even in Bangladesh, houses and temples are being attacked because the people inside follow a different religion. Next door in Myanmar, the Rohingya face a similar strain of persecution. And now we have Trump. Pandemic nationalism They say that if America sneezes, the rest of the world catches a cold. Maybe this time, the pathogen passed the other way. The bitterness, division, acrimony, and intolerance infecting much of the global The struggle for 2017 If this rising tide of hate-filled nationalism is to be stopped, then perhaps only the country which has been fought over, ripped open, and pulled from pillar to post more than most can force back the flood. The country with an act of genocide on its collective conscience; the same country which has thrown open its borders and arms to a million Syrian refugees as the rest of Europe has erected fences in 2016. Helmut Kohl’s Germany led the world out of the Cold War and into a decade of relative reconciliation. Angela Merkel and Europe’s largest electorate can again show the way when it goes to the polls next September. If the 1990s saw a spirit of hope borne out of years of struggle and despair, the elections of this year can leave no doubt that the despair has returned, and that the struggle for 2017 has already begun. Maybe now, as happened then, the hope will follow. In the country with the darkest past, the light will surely be seen. • Phil Humphreys is a British journalist and former Bangladesh development worker now living in Berlin, Germany. 22 FRIDAY, NOVEMBER 11, 2016 DT Opinion Strongman billionaire manages stunning upset A tongue-in-cheek look at how the media may have covered Trump’s win if the US were a thirdworld nation • Rohan Venkataramakrishnan A controversial strongman billionaire with a history of misogyny has managed a stunning upset. A controversial strongman billionaire with questionable connections to the Russian government and a history of misogyny managed a stunning upset over the politician-wife of a former president of the United States of America on Wednesday. Local news outfits in the country officially declared pro- Christian Donald Trump the victor of US elections, after his right-wing nationalist outfit trounced the incumbent party in many of the country’s key provinces. “I’ve spent my entire life in business looking at the untapped potential in projects and people all over the world. That is now what I want to do for our country,” Trump said in his victory speech. “The forgotten men and women of our country will be forgotten no longer.” The result came after a violent 18-month campaign that culminated in decisions made by a little-known group of 538 “electors” who meet every four years to choose the next president of the North American nation. The arcane system, which has its roots in political traditions established by a tiny male elite centuries ago, ensured Trump will have access to the country’s nuclear weapons even if he did not get a majority of the votes. The election campaign was marked by leaks, threats, scandals, and accusations of intervention by foreign governments. The right-wing candidate announced on national television that he would jail his opponent if he won, and promised to dismantle much of the work put in place by his predecessor, Barack Obama, whose victory eight years ago seems to only have papered over the nation’s history of racial strife. Trump’s opponent, the leftwing Hillary Clinton -- whose husband was embroiled in an ugly sex scandal as president in the 1990s -- was widely believed to be the front-runner, despite several corruption scandals that tainted her candidacy. Clinton’s failure Trump has questionable plans The arcane system, which has its roots in political traditions established by a tiny male elite centuries ago, ensured Trump will have access to the country’s nuclear weapons even if he did not get a majority of the votes means the US maintains its record of never having had a female head of state, despite giving women the vote nearly a century ago. Having Trump hold the reins of the nuclear-armed nation is likely to add to the turmoil and uncertainty around the world, in part because the TV star-turnedpolitician himself announced plans to keep out Muslims, begin conflict with China, and upend the global order. He also promised to dismantle America’s free speech laws and attack all those who had criticised him over the course of the campaign. Global markets slumped on the news of the strongman’s victory and it remains to be seen how the added volatility of having a right-wing president ruling over a divided polity in a nuclear-armed state will affect conditions all over the world. Inspired by Slate’s If It Happened There series, which re-imagines coverage of American events in the manner that the US media writes about the rest of the world. • Rohan Venkataramakrishnan is a news editor at scroll.in. This article first appeared on Scroll.in and has been reprinted under special arrangement. REUTERS Opinion 23 DT FRIDAY, NOVEMBER 11, 2016 Rural America’s white-lash elects Trump This is the way democracy dies LETTER FROM AMERICA • Fakhruddin Ahmed America’s 18-month long nightmare has ended with a chronic headache. In a shocking upset, Americans elected their first playboy president. Donald Trump has been in the public eye for 40 years. America knew a lot about him. They learnt more gory details about his private conduct during the presidential campaign; yet, had no qualms about electing him. If the Americans consider Donald Trump worthy of their highest elective office, the world should not quibble. This was a contest between into the cities of another hitherto blue state, which Obama had won twice, Michigan. Trump had frequented it several times, and won by 12,000 votes (0.3%). Clinton spent an inordinate amount of time in iffy North Carolina, (which Obama won in 2008 and lost in 2012), and lost it badly, by 177,000 votes (3.8%). She should have campaigned more in Florida, which Obama won twice narrowly. Clinton lost Florida decisively, by 120,000 votes (1.3%). Last month, Steve Schmidt, John McCain’s strategist for the 2008 campaign, expressed his surprise at Clinton’s strategy as she was attempting to expand her campaign to Arizona, which she was not going to win. Schmidt said that if Clinton only defended her firewall states (Pennsylvania, Wisconsin, Michigan) she would be elected president. Why didn’t Clinton campaign in predominantly white rural America? When all is said and with both the Republicans and Democrats for letting them down, and have found a voice in the “outsider” Donald Trump. And Trump has played them like the Pied Piper. There was a method to Trump’s madness The Trumps have a history of discrimination against blacks. His father Fred was arrested at a Ku Klux Klan rally in 1927 in Queens, New York. The realtor who was renting out Trump’s apartments in New York City in the 1960s said recently that he was told by Fred Trump, in Donald Trump’s presence, not to rent his apartments to blacks. President Nixon’s justice department sued the Trumps in the 1960s and 1970s for housing discrimination against non-whites. A Trump associate told Rolling Stone this June that he heard Trump say: “Black guys counting my money. I hate it. The only kind This is a blot on America’s democracy REUTERS If the Americans consider Donald Trump worthy of their highest elective office, the world should not quibble. This was a contest between rural and urban America. For once, rural America won rural and urban America. For once, rural America won. Born and raised in a millionaire’s family in urban America (New York City), Donald Trump managed to sell himself as the champion of rural America. Raised in a working class household in rural America (Scranton, Pennsylvania), Hillary Clinton failed to connect with her working class roots, and campaigned exclusively in urban America. Inexplicably, Clinton did not campaign in the predominantly white rural areas of three Democratic states, all of which she lost. In her firewall state of Pennsylvania which Obama won twice, Clinton campaigned exclusively in Philadelphia and Pittsburgh, while Trump campaigned in “rural Alabama” that lies between the two cities. Trump won by 68,000 votes (1.2%). Hillary never visited another of her firewall states, Wisconsin, which Obama won twice during the campaign. Trump did, and won by 27,000 votes (1%). Only on the last day of campaigning did Clinton venture done, Trump won 306 Electoral College votes to Clinton’s 232. However, Hillary Clinton has won over 200,000 more popular votes than Trump nationwide (Clinton: 59, 814,018, or 47.7%; Trump: 59, 611, 678, or 47.5%). This will be the second time in the last 16 years that the losing Democratic candidate will have won more popular votes nationwide (Al Gore won 600,000 more votes nationwide than George W Bush in 2000), than the winning Republican candidate. This is a blot on America’s democracy. This is the year of the working class whites In June, JD Vance, a former marine and Yale law school graduate, wrote a sensational memoir about working class whites: “Hillybilly Elegy: A memoir and culture in crisis.” He captured the frustration and hopelessness of poor whites of Scottish and Irish origin living in the Appalachian region of America, who have seen goodpaying local factory jobs disappear or go abroad, and are worried that their children will be worse off than they are. They are furious of people I want counting my money are little short guys that wear Yarmulkes every day.” It is such a mindset that propelled Donald Trump in 2011 to sire the “Birther movement” that accused President Obama of being foreign-born, and forced the president to show his birth certificate. This fabrication ingratiated Trump to the Republican base. Thanks to Trump, over 40% of Republicans still believe that Barack Obama was born in Kenya (therefore, his presidency is illegitimate) and that he is a Muslim (he is a Christian). Before its publication, conservative commentator Ann Coulter sent Trump a copy of her 2015 anti-immigration book: Adios America: The Left’s Plan to Turn Our Country into a Third Hellhole. After reading it, Trump made anti-immigration the main plank of his platform. As he came down the escalator of the Trump Tower in New York, in June 2015, shouting imprecations against Mexicans (“rapists,” criminals,” “drug dealers”), his popularity among the Republican base shot up, never to come down again. Trump then added Muslims to the list of immigrants to be banned. This alarmed other minority groups such as Chinese- Americans, who had suffered discrimination, and Japanese- Americans, who were imprisoned in internment camps during WWII. Trump alienated Native Americans by repeatedly calling Massachusetts Senator Elizabeth Warren (she is part Native American), Pocahontas. In an attempt to please his white base, Trump has repeatedly insulted all minority ethnic groups -- African- Americans, Latinos, Asians, and Native Americans. There are three reasons why Hillary Clinton lost: 1) When Clinton first burst into the national scene in 1992 as the presidential candidate Bill Clinton’s wife, Republicans calculated that she would run for president some day. On radio and Fox News, they have been vilifying her ever since, resulting in Hillary’s undeserved high negatives. 2) The installation of seven servers at home to receive and transmit confidential state department correspondence made Clinton look irresponsible. 3) FBI Director Comey’s letter to Congress saying that more be pertinent (they were not), 11 days before the election, reversed Clinton’s momentum. Many voters mistakenly believed the Republican propaganda that Clinton would be indicted if she was elected. Bottom line Good candidates win, bad candidates lose. Jimmy Carter was a bad candidate and Ronald Reagan an excellent one in 1980. George HW Bush was a good candidate, and Michael Dukakis an awful one in 1988. Bill Clinton was a very good candidate in 1992 and 1996. George W Bush was a better candidate than Al Gore (2000) and John Kerry (2004). Barack Obama was an excellent candidate in 2008 and 2012. Hillary Clinton was a flawed candidate in 2016. Donald Trump was dangerous as a candidate, and could pose a mortal threat to America as president. In a 2012 interview, retired Supreme Court Justice David Souter prophetically predicted the appearance of a Trump-like candidate: He posited that the republic was. • Fakhruddin Ahmed is a Rhodes Scholar. DT 24 Sport FRIDAY, NOVEMBER 11, 2016 TOP STORIES Rooney returns to captain England Wayne Rooney will return to England’s line-up as captain for today’s World Cup qualifier against Scotland as his experience in the tense encounter will be vital for the young squad, interim manager Gareth Southgate said. PAGE 26 BPL 3 finalists Comilla, Barisal lock horns The finalists of the BPL third edition, holders Comilla and Barisal have both lost their opening game in the fourth edition and will look to register their first win when they take on each other at SBNS today. PAGE 26 England post commanding total Century-makers Ben Stokes and Moeen Ali piled on the agony for India’s bowlers yesterday as England posted the highest score by a visiting team in nearly five years on the second day of the first Test. PAGE 27 16 yrs since Test bow, now its time to shine Bangladesh have completed 16 years in Test cricket. The Tigers’ five-day reign began on November 10, 2000 when they played their inaugural Test match against India at Bangabandhu National Stadium. Since then, they have played 95 Tests in these 16 years. PAGE 28 Rangpur thrash sorry Khulna • Tribune Report Khulna Titans were all out for the lowest ever total in the history of the Bangladesh Premier League Twenty20 yesterday as they were skittled out for just 44 in 10.4 overs against Rangpur Riders at Sher-e-Bangla National Stadium. Rangpur faced little trouble in overhauling the target, romping home in only eight overs with nine wickets in hand. This was their second consecutive victory. The previous lowest total belonged to Barisal Bulls, who were bundled out for 58 in 16 overs Rangpur’s Shahid Afridi appeals for a lbw decision against Khulna in the BPL in Mirpur yesterday Lowest total in BPL history Khulna were bundled out for just 44 in 10.4 overs against Rangpur yesterday in Mirpur. This is the lowest ever total in the history of the BPL Twenty20 so far. The previous lowest total belongs to Barisal Bulls who were skittled out for only 58 in 16 overs against Sylhet in the third edition of the tournament last year. Shuvagata Hom’s 12 runs was the only double figure score for the Titans as all the batsmen were dismissed for single digits. against Sylhet Super Stars in the third edition of the tournament last year. Arafat Sunny became the fifth bowler in the history of T20 cricket not to concede a single run off his bowling as he ended up with outstanding figures of 3/0 from his 2.4 overs. Pakistan superstar Shahid Afridi picked up 4/12 from his three overs and apart from Shuvagata Hom, none of the Khulna batsmen were able to reach double figures. After being asked to bat first, Khulna never looked confident and kept losing wickets at regular intervals. They were eventually PLAYS OF THE DAY dismissed with as many as 9.2 overs to spare. In reply, Rangpur reached the target in eight overs with Soumya Sarkar (13*) and Mohammad Mithun (15*) remaining unbeaten. Mohammad Shahzad (13) was the only Rangpur wicket to fall off the bowling of Junaid Khan. Following this humiliating defeat, Khulna will be desperate to return to winning ways but first, they must get their team combination right as they have useful West Indies all-rounder Kevon Cooper and wicket-keeper Andre Fletcher in the dug-out. • DHAKA TRIBUNE Sunny’s three wickets for zero runs Rangpur’s left-arm spinner Arafat Sunny stormed into the record books as he picked up three wickets from his 2.4 overs without giving a single run to register the best ever economy rate in the history of the BPL. He is the fifth bowler in the history of T20 cricket who did not concede a run in an innings. However, Sunny bowled more than an over compared to Suresh Raina, Hasan Raza, Dinuka Hettiarachchi and Udit Patel, who all bowled less than an over to achieve the feat previously. Afridi magic with the ball Pakistan superstar Shahid Afridi was terrific with the ball for Rangpur as he picked up 4/12 from his three overs and was instrumental behind the dismissal of Khulna for just 44. Afridi picked up the wickets of Riki Wessels, Shuvagata, Alok Kapali and Nur Alam. –MAZHAR UDDIN SCORECARD KHULNA TITANS INNINGS R B Mazid run out (Gazi) 6 11 Pooran b Gazi 0 1 Wessels b Afridi 5 10 Mahmudullah lbw b Gleeson 2 3 Shuvagata b Afridi 12 8 Kapali lbw b Afridi 0 1 Ariful lbw b Sunny 7 8 Nur b Afridi 8 11 Junaid c Soumya b Sunny 0 4 Asghar b Sunny 0 5 Shafiul not out 0 2 Extras (lb 4) 4 Total (all out; 10.4 overs) 44 Fall Of Wickets 1-1 (Pooran), 2-10 (Mazid), 3-15 (Mahmudullah), 4-15 (Wessels), 5-15 (Kapali), 6-31 (Shuvagata Hom), 7-40 (Ariful), 8-40 (Junaid), 9-44 (Nur), 10-44 (Asghar) Bowling Gazi 1-0-6-1, Rubel 2-0-8-0, Sunny 2.4-2- 0-3, Gleeson 2-0-14-1, Afridi 3-0-12-4 RANGPUR RIDERS INNINGS R B Shahzad c & b Junaid 13 16 Soumya not out 13 19 Mithun not out 15 15 Extras (w 2, nb 2) 4 Total (1 wicket; 8 overs) 45 Fall Of Wickets 1-16 (Shahzad) Bowling Junaid 2-0-14-1, Asghar 2-0-6-0, Shuvagata 2-0-10-0, Nur 2-0-15-0 The Riders won by nine wickets MoM: Shahid Afridi (RR) Presser from the press box! • Mazhar Uddin An unpleasant incident awaited the sports journalists following the BPL clash between Khulna Titans and Rangpur Riders yesterday in Mirpur as the security officials did not allow the media to enter the field after the game. In accordance with the rules and regulations in international matches, the journalists can enter the field after the match but due to some unknown reasons, the “walkie talkie” security officials denied the correspondents from entering the ground. Consequently, the journalists immediately decided to boycott the mandatory post-match press conference. As a result, Rangpur spinner Arafat Sunny came to the press box upon request from the journalists to give his reaction to the win. He said, “I had no idea about the record but obviously it feels great to be in the record books. I tried to bowl a tight line and length and I would also like to add that the batsmen made some mistakes as well. After changing my bowling action I think I am feeling better and comfortable with my new action. Hopefully, I’ll be able to regain my previous momentum. • Advertisement 25 Dhaka Tribune FRIDAY, NOVEMBER 11, 2016 DT 26 Sport FRIDAY, NOVEMBER 11, 2016 BPL 3 finalists Comilla, Barisal lock horns • Mazhar Uddin The finalists of the Bangladesh Premier League Twenty20’s third edition, reigning champions Comilla Victorians and Barisal Bulls have both lost their opening game in the fourth edition and will look to register their first win when they take on each other at Sher-e-Bangla National Stadium in Mirpur today. Mashrafe bin Mortaza’s Comilla lost to Tamim Iqbal’s Chittagong Vikings by 29 runs where apart from youngster Nazmul Hossain Shanto’s fifty, none of the batsmen were able to score significantly in pursuit of a target of 162. Their bowling department also needs to fire as they bagged only one wicket against the port city outfit. In their first game, Mushfiqur Rahim’s Barisal also suffered a comprehensive eight-wicket loss against Dhaka Dynamites. Even though Mushfiq and Shahriar Nafees struck half-centuries, their overseas players Dilshan Munaweera, Dawid Malan, Thisara Perera and Rayad Emrit all failed to score as they eventually posted 148/6 in their 20 overs. To add to that, Barisal pacer Al Amin Hossain was a let-down in the opening game and will no A file photo of a Comilla Victorians practice session MD MANIK doubt eye a better show today, along with Perera and Munaweera, while Taijul Islam will provide support in the spin department. And according to Mushfiq, the senior players, alongside the foreigners, need to step up and display better cricket. “In this BPL edition, if you notice, all the teams are well-balanced and whoever plays good cricket and commit less mistakes on a given day will win the game. As Comilla and ourselves have lost our first game, it’s very important to seal a win and gain confidence Zamal clinches Professional Golf title for the rest of the tournament. Our main target will be to do our basics right,” Mushfiq told the media yesterday. Meanwhile in the evening game at the same venue, high-flying Dhaka will look to continue their brilliant run after winning their opening game comfortably against a demoralised Rajshahi Kings, who lost their tournament opener against Khulna Titans by just three runs. Opening batsman Mehedi Maruf, who struck a magnificent unbeaten half-century in the last game, will once again look to continue from where he had left off against Barisal while their Lankan legend Kumar Sangakkara, West Indians Dwayne Bravo and Andre Russell and England’s Ravi Bopara can be devastating on any given day. Skipper Shakib al Hasan will marshal his troop and with Nasir Hossain and pacer Mohammad Shahid at his disposal, Rajshahi will have to play their best cricket in order to register their maiden win in the first edition. Rajshahi captain Darren Sammy will have to lead from the front, along with Sabbir Rahman, who was dismissed for only four against Khulna. However, Mominul Haque batted well and smashed a half-century in the first game and will have to play another vital knock at the opening spot. Sabbir is of the opinion that his side should not think about the big names in Dhaka’s dugout. Rather, they should just ensure not repeating their mistakes from the previous game. “Cricket is a team game where the contribution of all the 11 members of the side is required. We are not thinking about our opponent. I think if we play to our potential, we can beat Dhaka,” said Sabbir. • TODAY’S MATCHES Comilla Victorians v Barisal Bulls, 2pm Dhaka Dynamites v Rajshahi Kings, 7pm Both matches will be held at SBNS, Mirpur Rahmatganj stun Sk Jamal • Tribune Report Rahmatganj MFS shocked Sheikh Jamal Dhanmondi Club 1-0 in the second phase of the Bangladesh Premier League at Bangabandhu National Stadium yesterday. Forward Siyo Zunapiyo netted the all-important goal in the 69th minute to take unfancied Rahmatganj to third position in the 12- team points table. With 25 points from 14 matches, Rahmatganj now trail table-toppers Abahani Limited by three four points but the latter have a game in hand. Sheikh Jamal are fourth with 22 points from the same number of points. The corresponding fixture in the first phase ended in a 1-1 draw. • RESULT Rahmatganj 1-0 Sk Jamal Siyo 69 • Tribune Report The four-day long Paragon Professional Golf Competition came to an end yesterday with Zamal Hossain Mollah emerging as the champion at Kurmitola Golf Club. Mollah struck 14-under-par and ran away with the title ahead of second-placed Mohammad Nizam (two-under-par) and Mohammad Zakir Uzzaman and Mohammad Badal Hossain (both one-underpar), who jointly finished third. Mohammad Akbar Hossain, meanwhile, finished highest among the amateur golfers. A total of 70 professional and 10 amateur golfers took part in the Tk 10 lakh event where 45 players missed the cut after round two. Kazi Nabil Ahmed, MP distributed prizes among the winners following the conclusion of the fourth and final round. The second edition of the tournament will be held in the first week of next month at Savar Golf Club. • Chief guest Kazi Nabil Ahmed, MP (CR) poses alongside the winners and special guests of the First Paragon Professional Golf Tournament at Kurmitola Golf Club yesterday MAHMUD HOSSAIN OPU Chittagong Rear Admiral M Shaheen Iqbal (C) inaugurates the inter-forces basketball tournament in the port city yesterday ISPR Rooney returns to captain England • Reuters Striker Wayne Rooney will return to England’s starting line-up as captain for today Mourinho. “Yes, he is,” Southgate told reporters yesterday.” Southgate has two more games to convince the Football Association that he is the right man for the job.• Sport 27 DT FRIDAY, NOVEMBER 11, 2016 Federer can still be a threat, says Edberg • Reuters,.• DAY’S WATCH CRICKET CHANNEL 9, SONY SIX Bangladesh Premier League 2:30 PM Comilla Victorians v Barisal Bulls 7:15 PM Dhaka Dynamites v Rajshahi Kings STAR SPORTS 1, SONY ESPN 10:30PM India v England 1st Test, Day 3 FOOTBALL STAR SPORTS 1 7:20 PM Indian Super League 2016 Goa v North East TEN 3 2:50 PM A-League 2016/17 Adelaide United v Brisbane Roar FC SONY ESPN 1:30 AM FIFA World Cup Qualifiers 2018 France v Sweden SONY ESPN HD 1:30 AM FIFA World Cup Qualifiers 2018 Romania v Poland SONY SIX 10:50 PM FIFA World Cup Qualifiers 2018 Armenia v Montenegro 1:30 AM FIFA World Cup Qualifiers 2018 England v Scotland SONY SIX HD 1:30 AM FIFA World Cup Qualifiers 2018 San Marino v Germany India’s Ajinkya Rahane (L) and Wriddhiman Saha (C) watch as England’s Ben Stokes plays a shot on the second day of their first Test at the Saurashtra Cricket Association stadium in Rajkot yesterday AFP England post commanding total • AFP, Rajkot Century-makers Ben Stokes and Moeen Ali piled on the agony for India’s bowlers yesterday Herath runs through Zim as SL sweep series • Reuters Rangana Herath grabbed Zimbabwe’s final three wickets to return figures of 8-63 as Sri Lanka wasted little time in finishing off the hosts on the final morning of the second Test at the Harare Sports Club yesterday. The home side, teetering on 180 for seven overnight, survived 13 overs before being bowled out for 233 as Sri Lanka won by 257 runs to compete a sweep of the twomatch series. Herath finished with 13 wickets in the match as he fully. exploited a turning surface to dominate the Test with his spin. Craig Ervine, the only home player to provide any significant resistance, was first out yesterday, adding seven runs to his overnight 65 before a sharp catch from Dhananjaya de Silva at slip gave Herath his first wicket of the morning. • BRIEF SCORE ZIMBABWE 272 & 233 in 58 overs (Ervine 72, Williams 45, Herath 8/63) lost to SRI LANKA 504 & 258/9d by 257 runs At least five dropped catches and some sloppy fielding underlined a miserable day for the Indians before their home fans.. Stokes chipped in before Shami broke their 62-run stand with the wicket of Ali who saw his offstump cartwheel away in spectacular fashion after misjudging the line and not playing a shot. England’s total was the highest by a visiting team in India since the West Indies made 590 at Mumbai in November 2011.• 1ST TEST, DAY 2 ENGLAND 1ST INNINGS R B (overnight 311-4; M. Ali 99 not out, B. Stokes 19 not out): M. Ali b Shami 117 213 B. Stokes c Saha b Yadav 128 235 J. Bairstow c Saha b Shami 46 57 C. Woakes c Saha b Jadeja 4 8 A. Rashid c Yadav b Jadeja 5 20 Z. Ansari lbw b Mishra 32 83 S. Broad not out 6 16 Extras (b5, lb4, nb1) 10 Total (all out, 159.3 overs) 537 Fall of wickets 1-47 (Cook), 2-76 (Hameed), 3-102 (Duckett), 4-281 (Root), 5-343 (Ali), 6-442 (Bairstow), 7-451 (Woakes), 8-465 (Rashid), 9-517 (Stokes), 10-537 (Ansari) Bowling Shami 28.1-5-65-2, Yadav 31.5-3-112-2, Ashwin 46-3-167-2, Jadeja 30-4-86-3 (1nb), Mishra 23.3-3-98-1 INDIA 1ST INNINGS R B M. Vijay not out 25 70 G. Gambhir not out 28 68 Extras (b8, lb1, w1) 10 Total (0 wickets; 23 overs) 63 Bowling Broad 5-1-20-0, Woakes 7-2-17-0 (1w), Ali 6-2-6-0, Ansari 3-0-3-0, Rashid 2-0-8-0 DT 28 FRIDAY, NOVEMBER 11, 2016 Sport 16 years since Test debut, now it’s time to shine • Ali Shahriyar Bappa Bangladesh have completed 16 years in Test cricket. The Tigers’ five-day reign began on November 10, 2000 when they played their inaugural Test match against India in Dhaka’s Bangabandhu National Cricket Stadium. Since then, Bangladesh have played 95 Tests in these 16 years. The Tigers have managed to win only eight and draw 15 Tests among these 95. Two of those wins came against a second-string West Indies side in 2009 while five of them came against Zimbabwe. The other win came against England last month which is perhaps Bangladesh’s biggest achievement in their Test history so far. A couple of memorable Tests come to mind on the occasion of the Tigers’ 16th year in five-day cricket. Chief among them is the Multan Test against Pakistan in 2003 while the other one is against Australia in Fatullah 10 years ago. The Tigers fans can also count the first Test against England in Chittagong as a near miss as Bangladesh lost narrowly by a margin of 22 runs chasing a 286-run target on a difficult fourth-innings pitch against the formidable visiting side. However, the Multan and Fatullah Tests feature at the very top of the list of regrets for the Bangladesh supporers. In Multan, Bangladesh set a challenging 261-run target. At one stage, Pakistan were reeling on 164 for 7 and Bangladesh were scenting a famous victory. But Pakistan great Inzamam-ul-Haque played a superb match-winning unbeaten 138 to snatch victory from the jaws of defeat. Meanwhile in Fatullah, Bangladesh were playing against the mighty Aussies in 2006. Bangladesh were on top right from the very beginning, riding on opening batsman Shahriar Nafees’ brilliant 138-run knock. Bangladesh posted 427 in their first innings while Australia were bundled out for 269 in theirs. Bangladesh set the opponents Dutch national defender Virgil van Dijk (C) vies with Eden Hazard (R) of Belgium during a friendly at Amsterdam Arena in Amsterdam on Wednesday AFP The Tigers have completed their 16th year in Test cricket. Now with several performers at their disposal, Bangladesh will look to improve their fortunes in the longer version with important away Tests awaiting them in the coming days MD MANIK a challenging 307-run target and were it not for one of the all-time greats in the shape of Ricky Ponting, the Tigers could well have recorded a historical win of gigantic proportions. However, alongside these near misses, there has also been some world-class performances. Mohammad Ashraful is a case in point. He holds the record of being the youngest centurion in the history of Test cricket at 17 years and 61 days. Ashraful made the record against Sri Lanka in 2001. Sohag Gazi holds the record of scoring a hundred and taking a hattrick in the same Test. He created this record against New Zealand in 2012. Abul Hasan Raju scored a Test century against the West Indies at No 10 in 2012. Two years later, Shakib al Hasan scored a century and took 10 wickets in the same Test match. Only three players in Test history - AK Davidson in 1960, Ian Botham in 1980 and Imran Khan in 1983 – previously achieved the feat. But unfortunately, individual brilliance is not enough to win a Test match and probably that’s why Bangladesh have not won many matches compared to the limited-over formats. In the recent past, Bangladesh’s ODI record has improved significantly. They have established themselves as a competitive ODI unit in the last few years. They reached the quarter-finals of the 2015 World Cup in Australia after eliminating the formidable England side. They have won six consecutive ODI home series against teams like Pakistan, India and South Africa, among others. But Test cricket remains a mystery to the Tigers as the statistics point to a dismal record. In the last two years though, the Tigers have started to improve in the longer version. With that said, most of their recent improvements have come on home soil. Many critics believes that if Bangladesh want to establish their name in world cricket then they have to win Test matches regularly. Probably one reason why Bangladesh are below-par in Tests is because they don’t play five-dayers as much as the established orders. The Tigers recently returned to Test cricket after a 15-month gap whereas England, in the same duration, played 14 matches. So if Bangladesh want to improve, then there are no alternatives to playing more matches regularly. However, this is the right time for the Tigers to prove their mettle as they have quite a few Test matches away from home in the TEST BREAKDOWN Against Match Win Lose Draw Australia 4 0 4 0 England 10 1 9 0 New Zealand 11 0 8 3 Pakistan 10 0 9 1 India 8 0 6 2 South Africa 10 0 8 2 Sri Lanka 16 0 14 2 West Indies 12 2 8 2 Zimbabwe 14 5 6 3 First Test win: against Zimbabwe in Chittagong, 2005 Highest scorer: Tamim Iqbal, 3349 runs with 40.34 average Highest individual score: Tamim against Pakistan in May 2015 Highest number of centuries: Tamim, eight Highest number of half-centuries: Habibul Bashar, 24 Highest wicket-taker: Shakib al Hasan, 159 Highest five-wicket hauls: Shakib al Hasan, 15 Highest dismissals: Mushfiqur Rahim, 92 Highest Test caps: Mohammad Ashraful, 61 coming days. Bangladesh have a stylish opener like Tamim Iqbal, who is the highest Test run-scorer for the country with 3349 runs, including eight Test centuries. Dependable batsmen like Mushfiqur Rahim and Mahmudullah are now solid names in the middle order while they also have Shakib, who is often considered the best all-rounder in the world. The bowling department has the young pace sensation Mustafizur Rahman and the off-spinner Mehedi Hasan Miraz, who took 19 wickets against England recently and surprised the cricket world. Some other young and exciting talents like Sabbir Rahman, Soumya Sarkar and Rubel Hossain have emerged in the last few seasons. So it is high time for the Tigers to lift their game and leave a mark in the longest format of the game, much like the limited-overs. • Netherlands, Belgium share spoils • Reuters, Amsterdam Belgium’s Yannick Carrasco grabbed a late equaliser to secure a 1-1 draw against the Netherlands in a friendly at the Amsterdam Arena on Wednesday..• Downtime 29 FRIDAY, NOVEMBER 11, 2016 DT CROSSWORD CODE-CRACKER ACROSS 1 Very small (6) 5 Greyish brown (3) 7 Nettlerash (5) 8 Fisher (6) 10 Insect trap (3) 12 Pierce with horns (4) 13 First woman (3) 14 Grotto (4) 16 Quote (4) 17 Pale (3) 18 Classify (4) 20 Sporting item (3) 23 Bearlike (6) 24 Weeps (5) 25 Eyelid affliction (3) 26 Time of the year (6) DOWN 1 Honey drink (4) 2 Lump of gold (6) 3 Thither (5) 4 Irish republic (4) 5 Early freshness (3) 6 Employ (3) 9 Fondness (4) 11 Honey maker (3) 14 Vehicles (4) 15 Fantastic tricks (6) 16 Male swan (3) 17 Less well (5) 18 Prosecutes (4) 19 Niggardly (4) 21 Perform (3) 22 Attempt (3) How to solve: Each number in our CODE-CRACKER grid represents a different letter of the alphabet. For example, today 15 represents S so fill S every time the figure 15 appears. You have two letters in the control grid to start you off. Enter them in CALVIN AND HOBBES SUDOKU How to solve: Fill in the blank spaces with the numbers 1 – 9. Every row, column and 3 x 3 box must contain all nine digits with no number repeating. PEANUTS YESTERDAY’S SOLUTIONS CODE-CRACKER CROSSWORD DILBERT SUDOKU 30 FRIDAY, NOVEMBER 11, 2016 DT Showtime Dhaka International Short and Independent Film Festival to open in December • Showtime Desk The 14th edition of Dhaka International Short and Independent Film Festival (DISIFF) is to open its curtains on December 3. The organisers said that the biennial event this time will feature more than 500 films, the highest number of films in its history, which come from 108 participating countries, at a press conference on Wednesday. Nasiruddin Yousuff, the chairman of festival committee, Jakir Hossain Raju, chairman of Bangladesh Short Film Forum, filmmaker Jahidur Rahman Anjan, and Syed Imran Hossain Kimrani, the festival director, among others were present at the conference. Many of the films to show at DISIFF are well-known and screened previously at renowned festivals like Cannes, Busan, Berlin, Locarno, TIFF, and others. Organised by Bangladesh Short Film Forum, the DISIFF’s programme includes Cinema of World, Film in Competition, Retrospective, Independent Film, Alamgir Kabir Memorial Lecture, a seminar, and master classes. Meanwhile, a lifetime achievement award will be given to a film personality for contributions to Bangla cinema. In the retrospective section, five films by Indonesian filmmaker, Garin Nugroho will also be showcased.. Films will be screened at four different venues: Shawkat Osman Memorial Auditorium of Central Public Library, two auditoriums at Bangladesh National Museum, and the Music and Dance Centre of Bangladesh Shilpakala Academy, while inauguration ceremony of the week long event will be held at the Central Public Library in Dhaka. Bangladesh Short Film Forum, country’s one of the organisations comprised of independent filmmakers, has been organising the festival since 1988. • Solo performance of Chanchal Khan at National Museum Taylor Swift throws Lorde a star-studded birthday bash • Showtime Desk Prominent Tagore singer and exponent, Dr Chanchal Khan will perform at the Begum Sufia Kamal Auditorium on Friday, November 11, at 6:30pm. He will recite translations from Gitanjali, which has been a subject of his research and past work related to tracing the history of Gitanjali and its underlying philosophy. Chanchal Khan will sing from Gitanjali, as well as from the array of songs including devotion, love and season, and songs that feature Tagore’s parodies and satirical compositions. An artiste of special grade in Bangladesh Television and Bangladesh Betar, Chanchal has been singing, researching, and teaching Tagore songs over the last three decades. In the US, Nepal, and Australia, he founded music schools and institutions offering lessons to numerous students of both Bengali and other ethnic origins. These include Shurolok in Australia, and Anondolok in Nepal. Largely a self-trained singer with early formal lessons from Chhayanaut, Chanchal is one of the founding members of Rabindra Shangeet Shommilan Parishad in the ‘80s. Chanchal Khan directed Balmiki Protibha, a joint India-Bangladesh endeavour in 2010. In 2011, he directed a documentary Bangladeshey Rabindranath, in association with the Ministry of Cultural Affairs, Bangladesh to commemorate the 150th birth anniversary of Rabindranath Tagore. This was screened in India, and Bangladesh under both government and private auspices during the two nations joint festival. He has released his second documentary titled Timeless Gitanjali, sponsored by the India-Bangladesh Foundation, High Commission of India in 2014, which was screened in India, Australia, USA, and the UK. He was awarded reception by the Chief Minister of Tripura Sri Manik Sarkar, in connection with the screening of this documentary in Agartala. • Showtime Desk When Taylor Swift is in charge of the festivities, it’s no surprise that Lorde’s 20th birthday party on Monday night in the New York City was quite an extravaganza. Taylor hosted a dinner for her friend who goes by the stage name Lorde, born as Ella Yelich-O’Connor, at ZZ’s Clam Bar in Manhattan. Celebrities who attended to celebrate included Lena Dunham, Karlie Kloss, Mae Whitman, Tavi Gevinson, Aziz Ansari, and Lorde’s childhood friends from New Zealand. Taylor decorated the group’s area with gold balloons spelling out “U R 20.” Lorde posted a photo of the set-up, saying, she was the “happiest birthday girl in the world.” Taylor presented Lorde, a candle-festooned chocolate birthday cake. After the party, the Royals singer posted a photo of herself in between Taylor and Karlie, who were kissing her cheeks. The caption read, “Had the best birthday party I’ve ever had tonight surrounded by my nyc family. all organised by tay who is, as she says, ‘a mom with no kids’.” Lorde added, “I am your kid and you love me so hard I could burst. Here’s to our 3 magic years of best friendship and more moments like this, squished between angels.” Earlier in the day, Taylor posted a birthday card she’d painted for Lorde, with the caption, “Thank you for the music you make.” • Showtime Shakib meets Shakib 31 FRIDAY, NOVEMBER 11, 2016 WHAT TO WATCH DT • Showtime Desk This week, Bangladeshi allrounder cricketer, Shakib al Hasan celebrated his daughter, Alayna Hasan Aubrey’s first birthday, with friends and family. The party was held at the Dhaka’s Radisson hotel. It was glamorous and had a star-studded guests list. Siam returns • Showtime Desk For the past one year, young actor and model Siam, has been missing from the entertainment world. He left Bangladesh to pursue his studies in the UK. His hard work and determination finally paid off, as he is back in Dhaka with excellent results. Siam informs that his parents had wanted him to become a barrister for some time now. So this was his opportunity to make his parents happy. He studied for twelve hours a day, which helped Siam secure the top position among other Bangladeshi students of the university. After his comeback, Siam is busy shooting TVCs and TV dramas. He is active in the media with BPL, as he is supporting one of the teams solely. Siam said, “Hopefully, the audience won’t miss me anymore. I am here once again.” • Fans who witnessed the occasion were shocked when Shakib Khan, the superstar actor, showed up to the party. It was arguably the most extravagant birthday celebration in the town, filled with lots of celebrities. Zahid Hasan, Nobel, Bijori Barkatullah, Tamalika Karmakar, Tarin, Deepa Khandaker, Shahed Ali, Runa, Suzana Zafar, and Elita Karim were there to celebrate Aubrey’s birthday. Other than the actors and musicians, many of Shakib’s fellow cricketers were present, most notably, the Sri Lankan legend, Kumar Sangakara.• Martin Shkreli releases Wu-Tang Clan songs • Showtime Desk Last month, ex-CEO of Turing Pharmaceuticals, Martin Shkreli, also vilified as ‘The most hated man in America,’ tweeted, “If Trump wins, my entire unreleased music collection, including unheard Nirvana, Beatles, and of course, Wu-Tang, comes out, for free.” He made headlines in the past for hiking up the price of a life saving drug, buying the single copy of a Wu Tang Clan’s album for $2 million, getting into a fight with Ashton Kutcher, and of course some criminal charges bought against him by the FBI. Last Tuesday night, Shkreli live streamed video.” • Kingsman: The Secretive Service Star Movies 4:28pm A spy organisation recruits an unrefined, but promising street kid into the agency’s ultra-competitive training program, just as a global threat emerges from a twisted tech genius. Cast: Colin Firth, Taron Egerton, Samuel L Jackson Sherlock Holmes: A Game of Shadows HBO 3:30pm Sherlock Holmes and his sidekick Dr. Watson join forces to outwit and bring down their fiercest adversary, Professor Moriarty. Cast: Robert Downey Jr, Jude Law, Jared Harris The Town WB 4:57pm As he plans his next job, a longtime thief tries to balance his feelings for a bank manager connected to one of his earlier heists, as well as the FBI agent looking to bring him and his crew down. Cast: Ben Affleck, Rebecca Hall, Jon Hamm Madagascar Zee Studio 5:45pm Spoiled by their upbringing with no idea what wild life is really like, four animals from New York Central Zoo escape, unwittingly assisted by four absconding penguins, and find themselves in Madagascar, among a bunch of merry lemurs Cast: Chris Rock, Ben Stiller, David Schwimmer 300 Movies Now 5:20pm King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C. Cast: Gerard Butler, Lena Headey, David Wenham 32 FRIDAY, NOVEMBER 11, 2016 DT INFLATION EDGES UP TO 5.57% IN OCTOBER PAGE 12 Back Page THE DEAD END OF HISTORY PAGE 21 SHAKIB MEETS SHAKIB PAGE 31 Police against revealing details of death in crossfire to media • Kamrul Hasan Police are now against revealing the details of cause of death of crossfire victims to the media. The Directorate General of Health Services (DGHS) has instructed its forensic doctors not to provide detailed autopsy report on persons killed in crossfire, after it was requested by the police in a letter. The Dhaka Metropolitan Police (DMP) wrote to the DGHS on September 25, requesting it not to provide detailed autopsy report on persons killed in crossfire or any unnatural death if inquired by the media. DGHS, an associate of the Health Ministry, served a letter in this regard on November 6 to all hospitals with forensic department. Such hospitals include medical college hospitals, 200-bed general hospitals and upazila sadar hospitals. The DMP letter said detailed information of an autopsy report – which is like a secret document – in many cases is used as important evidence during investigation and charge framing. Revealing such information to all during investigation hampers the process, creating confusion among the people about the death. The DMP asked the DGHS not to disclose information about the types of injuries and to provide brief information about cause of death. It claimed that barring such flow of information is not violation of the Right to Information Act 2009. Bangladesh not suing anyone over BB reserve heist • Jebun Nesa Alo Despite being hit with possibly the largest banking heist in history, the top authorities of Bangladesh government have decided not to file a lawsuit against any international organisation connected with the theft. The decision was made at a meeting between Foreign Minister AH Mahmood Ali and Bangladesh Bank Governor Fazle Kabir at the Ministry of Foreign Affairs yesterday, sources told the Dhaka Tribune. Ajmalul Hossain QC, the lawyer who conducted the legal procedure of recovering $81 million laundered from the central bank's reserve account with Federal Reserve Bank of New York, was also present at the meeting. Speaking to the Dhaka Tribune, Ajmal said should Bangladesh government want to, it is required to file the lawsuit within one year of the occurrence of the theft as per the agreement with SWIFT, the global financial messaging network through which the money was stolen. “In that case, the deadline would be February 4 next year. But Bangladesh has decided not to file any lawsuit. We have already traced and recovered $15.25million, and we aim to recover the rest of the money the same way,” he said. However, in case the Bangladesh Article 7 of the Right to Information Act states that information related to cases under investigation, trial, or related to public security would not be disclosed. Professor Sadeka Halim, former commissioner of Information Commission Bangladesh, told the Dhaka Tribune that of the 32 articles of the Right to Information Act, at least six sub-articles under Article 7 bar citizens from getting information related to cases under investigation. But if the killings violate human rights or are results of corruption, then anybody can apply for information and the authorities are compelled to provide the information within 24 hours, she said. Stressing that every family member has the right to know how their dear ones were killed, or what happened to them, Supreme Court lawyer Jyotirmoy Barua said although there is a bar to providing such information, this must be published publicly at a suitable time. Complaining that authorities had been tightening freedom of expression since long, Nur Khan, director of Ain o Salish Kendra, said such attempts would further authorities fails to recover the rest of the money by February 4, they will not have the option to file the case after the deadline, he added. Meanwhile, the New York Fed has admitted to being guilty of executing of money transfer order that led to the heist. “They admit that they were partly responsible for this heist, and are providing support to Bangladesh government in recovering the money by putting pressure on the Philippines,” Ajmal said. “There is no need for us to file any case against the New York Fed or any other organisation, because we will get our money back.” Bangladesh is currently trying to BIGSTOCK prompt unruly police officials to be involved in crimes. Besides, journalists and rights activists would not be able to reveal the truth if any crimes took place. If the authorities succeeded in implementing their desire, it would establish a passive control over the media and gag freedom of expression, he said. Professor Zia Rahman, chairman of Dhaka University criminology department, said: “Whether there is a law protecting police’s desire or not, the only concern should be transparency and accountability in the investigation.” • recover stolen money through the Philippines' Department of Justice, he said. According to sources, $70 million of the heist money was found to have been smuggled to the Philippines, of which $15.25 million has been recovered and will be deposited at Bangladesh Bank's account with the New York Fed by November 24. A team from Bangladesh Bank is working in Manila to complete the process, Ajmal said. The rest of $70 million will be recovered from Solaire casino, money exchange house Philrem and other organisations involved with transferring the money, sources said. Assets of these organisations have already been frozen by the AL leader saves rapist in Tangail • Mohammed Afzal Hossain, Tangail Parents of a physically challenged minor, was allegedly raped, could not take legal action against the rapist as local Awami League leaders forced them to negotiate with the rapist at Chandpur village in Gopalpur upazila in Tangail. Victim’s foster mother said: “Harun Maker, 50, a resident of Kamakkha village in the upazila, told us that he wanted to take our girl to doctor. On September 24 Harun took the girl saying that he was going to doctor’s chamber. But he took the girl to his house instead of going to doctor’s chamber and raped her.” After returning home, the girl told her mother about the incident. After that victim’s parents tried to take legal action against Harun but upazila AL President and Union Chairman Halimuzzaman and others stopped them and pressured to negotiate with the rapist by taking money, locals said wishing anonymity. On October 18, Halimuzzaman and others arranged an arbitration and fined the rapist Harun Tk40,000. Harun paid the fined money on November 5. When contacted, victim’s foster father, said: “We had to negotiate with the rapist as influential people pressured us to solve the problem locally.” Halimuzzaman said: “We tried to solve the problem locally and fined Harun Maker.” Masumur Rahman, upazila nirbahi officer of Gopalpur, said: “We will take actions against the rapist and negotiators.” • Philippine authorities and the Department of Justice is working to get the assets forfeited in order to pay Bangladesh back, Ajmal said. The money that could not be traced will be recovered from Rizal Commercial Banking Corporation (RCBC) of the Philippines as the money was transferred through the bank, Ajmal said. In August this year, Philippine central bank Bangko Sentral ng Pilipinas (BSP) charged the RCBC a fine of one billion pesos ($21 million) as the bank was used by cyber criminals to pull off the heist. Earlier, some $68,000 left with the RCBC bank was sent back to the New York Fed. •:
https://www.yumpu.com/en/document/view/56300567/e-paper-11-november-2016
CC-MAIN-2021-04
refinedweb
23,710
57.1
#define D define #D Y return #D R for #D e while #D I printf #D l int #D W if #D C y=v+111;H(x,v)*y++= *x #D H(a,b)R(a=b+11;a<b+89;a++) #D s(a)t=scanf("%d",&a) #D U Z I #D Z I("123\ 45678\n");H(x,V){putchar(".XO"[*x]);W((x-V)%10==8){x+=2;I("%d\n",(x-V)/10-1);}} l V[1600],u,r[]={-1,-11,-10,-9,1,11,10,9},h[]={11,18,81,88},ih[]={22,27,72,77}, bz,lv=60,*x,*y,m,t;S(d,v,f,_,a,b)l*v;{l c=0,*n=v+100,j=d<u-1?a:-9000,w,z,i,g,q= 3-f;W(d>u){R(w=i=0;i<4;i++)w+=(m=v[h[i]])==f?300:m==q?-300:(t=v[ih[i]])==f?-50: t==q?50:0;Y w;}H(z,0){W(E(v,z,f,100)){c++;w= -S(d+1,n,q,0,-b,-j);W(w>j){g=bz=z; j=w;W(w>=b||w>=8003)Y w;}}}W(!c){g=0;W(_){H(x,v)c+= *x==f?1:*x==3-f?-1:0;Y c>0? 8000+c:c-8000;}C;j= -S(d+1,n,q,1,-b,-j);}bz=g;Y d>=u-1?j+(c<<3):j;}main(){R(;t< 1600;t+=100)R(m=0;m<100;m++)V[t+m]=m<11||m>88||(m+1)%10<2?3:0;I("Level:");V[44] =V[55]=1;V[45]=V[54]=2;s(u);e(lv>0){Z do{I("You:");s(m);}e(!E(V,m,2,0)&&m!=99); W(m!=99)lv--;W(lv<15&&u<10)u+=2;U("Wait\n");I("Value:%d\n",S(0,V,1,0,-9000,9000 ));I("move: %d\n",(lv-=E(V,bz,1,0),bz));}}E(v,z,f,o)l*v;{l*j,q=3-f,g=0,i,w,*k=v +z;W(*k==0)R(i=7;i>=0;i--){j=k+(w=r[i]);e(*j==q)j+=w;W(*j==f&&j-w!=k){W(!g){g=1 ;C;}e(j!=k)*((j-=w)+o)=f;}}Y g;} I have OCX created in VC++ that has many functions. OCX has got some GUI. I want to use those functions in C# web application without loading OCX. i.e. I want to extract only functions from OCX. Can anyone please suggest how this can be done? i have been trying to make create this program, it's kinda hard for me to get help in real life because I'm the only computer science student in my second semester. this is c++. I have to use arrays I have to make a program that shows grades, based on marks. The number of students depends on the user input. grade A >=90 grade B >=80 grade C >=70 grade D >=60 grade F <=59 based on the homework my lecturer has given me, the output has to be like this Enter the number of students: 4 Enter 4 marks: 40 55 70 58 student 0 mark is 40 and grade is C student 1 mark is 55 and grade is B student 2 mark is 70 and grade is A student 3 mark is 58 and grade is B This is my code: #include<iostream> using namespace std; int main(){ int students; int mark; int x; char grade[6]={'A','B','C','D','F','\0'}; cout<<"enter the number of students"<<endl; cin>>students; cout<<"enter "<<students<<" marks "<<endl; for(x=0;x<students;x++){ cin>>mark; if(mark>=90) grade[0]; else if(mark>=80) grade[1]; else if(mark>=70) grade[2]; else if(mark>=60) grade[3]; else grade[4]; cout<<"student "<<students<<" mark is "<<mark<<" and grade is "<<grade[x]; } } I don't know what to do anymore. Help me if(mark>=90) grade[0]; cout<<"student "<<students<<" mark is "<<mark<<" and grade is "<<grade[x]; Quote:I don't know what to do anymore. Help me <br /> NetTcpBinding^ binding = gcnew NetTcpBinding();<br /> binding->Name = "IMyWebService";<br /> EndpointAddress^ address = gcnew EndpointAddress("myUrl");<br /> <ChannelFactory<IMyWebService^>^> factory = gcnew ChannelFactory<IMyWebService^>(binding, address);<br /> How do I increase size of my tooltip control as I need to show image to my tooltip I probably need to increase size of my tooltip control? I tried using Text Renderer Measure Text but it just for increasing size according to text we provide.I want to increase size means height and width of my tool Tip so that my whole image gets displayed. Right now only part of image getting displayed using graphics Draw Image function according default size of tool Tip which is small.I am also providing default size of my image by using Graphics Draw Image function.But since size of my toolTip is small only part of image getting displayed. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Messages/5368643/I-have-OCX-created-in-VCplusplus-that-has-many-fun.aspx
CC-MAIN-2019-22
refinedweb
882
59.64
pymake: 25% faster than msys make pymake news: - Bad news: pymake is still 5x slower than GNU make on Linux/Mac. - Good news: pymake is 25% faster than msys make (GNU make on Windows)! - Best news: there’s a lot of room to make performance better. All measurements are do-nothing depend builds. Full rebuilds aren’t significantly affected because compiler speed overwhelms any time we spend in make. Creating Windows processes is more expensive than creating processes on a unix-like operating system. Creating MSYS processes is hugely more expensive. Windows I/O in general is slow compared to Linux, at least for typical build tasks. Because pymake recurses in a single process, caches parsed makefiles such as rules.mk, and avoids many shell invocations, it can make up for slow parsing times by dramatically reducing time spent elsewhere. How to use pymake on Windows Don’t use pymake with client.mk on Windows, yet. pymake doesn’t understand MSYS-style paths, which is what configure substitutes for @srcdir@ and @topsrcdir@ when using client.mk. This will be fixed by the patches available from this bug tree. Configuring manually isn’t hard: to build Firefox in c:/builds, follow this recipe: $ mkdir /c/builds $ hg clone /c/builds/mozilla-central $ cd /c/builds/mozilla-central $ autoconf-2.13 && (cd js/src && autoconf-2.13) $ mkdir ff-debug $ cd ff-debug $ export MAKE='python -O c:/builds/mozilla-central/build/pymake/make.py' $ ../configure --enable-application=browser --enable-debug --disable-optimize $ python -O ../build/pymake/make.py -j4 How to use pymake on Linux/Mac Configure manually as above, or add the following flags to your mozconfig file: export MAKE="python -O $topsrcdir/build/pymake/make.py" mk_add_options MAKE="python -O @TOPSRCDIR@/build/pymake/make.py" Soon on all platforms this will be as simple as mk_add_options MOZ_ENABLE_PYMAKE=1 Thank you! Special thanks to Arpad Borsos who wrote tests and an implementation of –keep-going for pymake. Next plans Immediate future plans for pymake reduce the process count even further, especially for depend builds: Currently every invocation of nsinstall is a separate process, and we invoke nsinstall even when all its install targets are up to date. Simple tasks like this will instead be implemented as native python commands. Ted implemented a branch to do this, but the current implementation blocks the only thread. I think we’re going to switch and use shared-nothing threads and message passing to parallelize before making this the default behavior. Every time Mozilla processes a makefile the build system combines all the compiler-generated dependencies into a single .all.pp file using mddepend.pl: this allows developers to move or remove header files without breaking depend builds. Running a perl script for every makefile invocation is silly, especially because all it does is parsing and rewrite makefile syntax. I will have pymake read these dependency files directly and ignore missing files (causing a rebuild without an error) using a syntax includedeps $(INCLUDEFILES) Longer-term work that would make pymake much more useful: - Build an object graph of the entire Mozilla tree recursively. I think I know how to do this, although there will be some issues with how to deal with local versus global variables. - Warn and eventually force a more rigorous dependency graph: warn if a dependent file ‘appears’ without having a rule to create it. - Make parsing a lot faster using mx.TextTools instead of native python regular expressions. Keep the regular expressions as a slow path for developers who don’t have TextTools installed. Python Reference Cycles and Closures While debugging pymake performance and memory usage I found an interesting fact, which in hind sight should have been obvious: functions which enclose themself in python create reference cycles which have to be cleaned up by the Python garbage collector: def outerFunction(outerCallback): targetsToBuild = [1, 2, 3] def innerCallback(): if len(targetsToBuild): # innerCallback closes on itself... this creates a reference cycle every time you call outerFunction # if you call outerFunction 100000 times per build, this can add up really quickly and cause large GC pauses targetsToBuild.pop(0).build(innerCallback) else: outerCallback() After finding this problem, I refactored (1, 2, 3) the pymake code to use objects instead of closures to save asynchronous state while rebuilding. Also, OptionParser instances create cycles by default. There is a lightly-documented method OptionParser.destroy which can be used to manually break these cycles (thanks to Ted for finding it). pymake now runs without creating any reference cycles and I disabled the python garbage collector. Environment Munging in MSYS When MSYS goes from an MSYS process to a Windows process, and vice-versa, it munges certain environment variables to account for the path styles. I previously thought that it only munged PATH, but I discovered today that I was wrong: MSYS was munging the MAKEFLAGS environment variable in odd ways. If MAKEFLAGS in the MSYS process was ‘ -j1 — PATH=e:/builds/mozilla-central’ it would be munged into ‘ -j1 — PATH=e;c:/mozilla-build/msys/builds/mozilla-central’ in a non-MSYS process. Without the leading space the value was not touched. I don’t know why this is, but I altered the pymake code slightly so that MAKEFLAGS would never start with a space (and would be more compatible with gmake in the process). April 3rd, 2009 at 2:43 am Why not just design packages to build using mingw and then cross-compile them from a Linux box? Even if you keep the ability to build natively on Windows, it doesn’t really matter if it goes fast. April 3rd, 2009 at 8:35 am Anonymous: Because of differences in the layout of vtables and other details, code compiled with GCC (mingw) cannot use MS-COM components. Because some of the more advanced Windows APIs (most of accessibility, for example) are only available via MS-COM, using mingw for our production builds isn’t really an options at this time. In addition, MSVC produces faster and smaller code than GCC. April 6th, 2009 at 12:56 am @Benjamin: Code compiled with GCC can use COM objects just fine, it just can’t treat them like C++ classes. It has to access COM objects the same way C does: as a structure with a bunch of function pointers in it. Various utilities exist to automatically generate the necessary headers for COM objects. April 7th, 2009 at 4:59 pm Our entire XPCOM system is built around C++ vtables being binary-compatible with MS-COM on Windows. Until we can break the ABI of Mozilla, that must be preserved. Even then, MSVC wins big on performance over GCC.
http://benjamin.smedbergs.us/blog/2009-04-02/pymake-25-faster-than-msys-make/
CC-MAIN-2015-22
refinedweb
1,113
54.02
Opened 4 years ago Closed 4 years ago Last modified 4 years ago #20115 closed Bug (duplicate) Error with MySQL database using % in direct SQL Description Hello everybody! Привет всем русскоговорящим в отдельности! I found problem in Django 1.4.2 and current version in main branch of git repo. I try to do something like this: (found names that starts with string "Jo", like Joe,John etc) from django.db import connection ... cursor=connection.cursor() cursor.execute('SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";') and take exception: Exception raised: <type 'exceptions.TypeError'> not enough arguments for format string looks very strange... after time, i found the root of problem. when execute() method start he invoke this: django/db/backends/util.py:36 def execute(self, sql, params=()): and some levels bottom it invoke this: MySQLdb/cursors.py:139 def execute(self, query, args=None): ... if args is not None: query = query % db.literal(args) Look with attention on default values of argument of functions. When i do in my code execute() additional args set by default to turple (), BUT MySQLdb in his execute method waiting None value as default. Next, if my SQL code contain a % symbol (not in placeholder meaning), that MySQLdb execute() method think that i send additional arguments to paste in SQL and do formatting. At this moment raise error because this is wrong Python code: 'SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";'%() Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2538, in run_code exec code_obj in self.user_global_ns, self.user_ns File "<ipython-input-1-4ae0cf876369>", line 1, in <module> 'SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";'%() TypeError: not enough arguments for format string In confirmation of the foregoing, if change my code to from django.db import connection ... cursor=connection.cursor() cursor.execute('SELECT * from `test`.`test_table` WHERE name LIKE "Jo%";', None) that it will be work properly. So, as a result, I propose to think about correction file django/db/backends/util.py:36 to def execute(self, sql, params=None): But i don't know about how it will be worked with another DB such Oracle, PostgreSQL. In some reason on SQLite original code don't raise exception. Change History (2) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by a problem has 5 years old??? oh, sh... Guys, seriously, somebody must solve this not big problem. Duplicate of #9055
https://code.djangoproject.com/ticket/20115
CC-MAIN-2016-50
refinedweb
414
59.8
As we like to change edition names and move functionality around from time to time, here’s a concise summary of the differences between Visual Studio 2015 Enterprise and Visual Studio 2015 Professional. By Giles Davies, Visual Studio Technical Specialist, Microsoft UK As we like to change edition names and move functionality around from time to time I thought it might be useful to try and concisely summarise the differences between Visual Studio 2015 Enterprise and Visual Studio 2015 Professional. By way of background, the 2015 release made some changes to the Visual Studio IDE line-up, replacing both the Premium and Ultimate editions with the new Enterprise edition. That means that a lot of people who had Premium are now entitled to Enterprise, and so as well as looking at the reasons you might choose Enterprise, this should also help answer the question of “now I’ve got Enterprise as an upgrade, what’s in it?”. IntelliTest IntelliTest is a brand new capability for 2015 that analyses your source code and then creates unit tests to achieve 100% code coverage for each path through that code. That means that you can get a lot more of your code covered by unit tests for less effort, helping you to add unit tests to code that doesn’t have any, and making it easy to keep on top of creating unit tests for new code. It doesn’t mean that you’ll never write a unit test again, but I’d consider this a means of getting the core unit tests generated for you, allowing you to concentrate on specific tests and scenarios based on your domain knowledge. You can tailor it to allow exceptions, override object creation and much more. It will work with MS Test, NUnit, xUnit and any other testing framework that provides an adapter for use in Visual Studio. It is currently limited to C#. Here’s a 35 min video walking through IntelliTest. IntelliTrace IntelliTrace is a historical or post-mortem debugging technology that helps to address the “I can’t reproduce it” problems, typically across dev and test environments. It was introduced in 2010 so it’s not new, and it can be used across dev, test and production environments. A simple example of its use is: A tester finds a bug in the test environment. The tester reproduces the bug with IntelliTrace collection enabled, and the bug raised then includes the IntelliTest log file. That log file includes the calls and events from the test environment. The developer opens the bug and the IntellITrace log file in Visual Studio Enterprise, and can view the exceptions raised, and for each of those exceptions see the stack trace. The developer can choose to debug any of those exceptions, in which case Visual Studio will go into debug mode with the execution halted at the line of code that threw the chosen exception. The developer can then step both forward and backwards through the source code to understand what happened. Key advantage – the developer doesn’t need to work out how to reproduce the conditions to replicate the bug in order to then start understanding how to fix it. IntelliTrace allows the developer to debug as if attached for debug, even though this takes place later and on a different environment. For a problem where it’s environment based (e.g. can be reproduced in test but not in dev) this can save a lot of time. This requires .NET 2.0 or higher C# or VB.NET and works in ASP.NET, Microsoft Azure, Windows Forms, WCF, WPF, Windows Workflow, SharePoint and 64-bit apps. You don’t need Enterprise to collect IntelliTrace data, but you do need Enterprise to use it. There’s a lot more to it. Here’s the MSDN documentation and a 12 min overview video. Architecture Tools Enterprise includes the architecture tools and these really fall into 2 camps; UML and non-UML tools. The UML tools provide support for a range of diagram types such as Class, Sequence, Activity, Use Case and Component diagrams, and allows both forward and reverse engineering. The non-UML tools are Code Maps and Layer Diagrams. These differ from the UML tools in being fundamentally related to the underlying source code. Code Maps allows you to understand and explore your source code visually. Why is that useful? It allows you to build your understanding of the relationships between different aspects of your code without needing to read the source. Code Maps allows you to drill from assemblies down to namespaces, classes, methods and down to the underlying source, as well as filter out those elements you’re not interested in, such as test code or system assemblies. You can add your own annotations and groupings, rearrange the diagrams and share them with others, via email, saved as diagrams or directly within Visual Studio. A Professional user can view CodeMaps but not author them. This is useful for people that are new to a project, or when you’re going to be making changes to code that you aren’t familiar with or perhaps can’t remember. One often overlooked capability is that you can also debug using Code Maps and this can really help in not having to keep track in your head of where you are in the code base whilst debugging. Code Maps work for .NET and C/C++. For a demo, here’s a 9 min overview video and some more documentation. Release Management Would you like to continuously deploy your code to multiple heterogeneous environments, with whatever mix of automated and human approval you require, and carry out any activities in each of those environments (provisioning, deployment, testing etc.)? That’s what the new release management tooling provides in Visual Studio 2015. Release management forms a core part of the Visual Studio DevOps support, providing continuous deployment support, and complementing the new build system, sharing the same cross-platform agents. Enterprise is required to create and edit the release definitions, defining the environments, the deployment steps required, approvals and more. Here’s an introduction as well as a 2 min high-level overview video, or this 30 min video for more depth. Testing Tools To summarise simply, you get all the testing tools in Enterprise. In other words: - Test case management - Manual testing - Exploratory testing - Automated functional testing - Load and performance testing The first three of these are included as Microsoft Test Professional is a part of the Enterprise edition. I won’t cover that now, but you can find out more here. What’s unique to Enterprise are automated functional testing and load and performance testing. The Visual Studio automated functional testing tool is Coded UI. As the name suggests, this creates automated tests (i.e. including automated verification) and records them as code – either C# or VB.NET. You can record them as you perform actions, or create tests by reusing test methods at a code level. You can also promote manual tests to create the automated test and then add verifications. Coded UI allows you to build regression suites that drive the UI of the application under test (web and thick clients), and to run those regression tests remotely, such as on a test environment and even as part of the release management capability discussed above. Note that executing a CodedUI test remotely doesn’t require Enterprise edition, so other users can run them. For more info on CodedUI here are the docs. Load and Performance Testing has been around for a long time in Visual Studio, and has evolved over the years. The core capabilities are the same; create a scenario that tests performance using a certain number of virtual users running a set of tests over a given time. You can factor in network conditions (e.g. 10% of the users are on a very poor network connection, what’s their experience?) and collect system performance counter information (CPU, memory, disk I/O and much more): Here’s a walkthrough of creating and running a load test. The latest changes have included the ability to choose to use Azure to generate the load i.e. you don’t need to find the hardware and set up the test rig. That’s without making any changes to the load test, as it’s just a radio button for choosing between the cloud and on-premise. Using the cloud means you can also choose where the load is coming from using the Azure data centres: Here are some more details on cloud load testing, as well as a 10 min video. MSDN Last but not least are the extra benefits (over Professional) that you get from Enterprise in MSDN. I’d highlight: - More Azure credit (£95 per month vs £35 pre month for Professional) so you can use more Azure services for free each month, such as running virtual machines. - eDevTech’s modern requirements management partner products - Office 365 developer subscription - Dev and Test downloads for SharePoint, Exchange, Dynamics, Office production use and PowerBI. - 45 Pluralsight courses vs 30 for Professional - 2 collections of 10 courses of Microsoft e-learning (1 in Professional) - 4 support incidents (vs 2) You can find even more details on this in the MSDN comparison matrix. Hopefully this gives you a flavour of the differences, and if you’re in the position of either deciding which edition to get, or having become entitled to Enterprise from an upgrade, then you’ll have a better idea of the key additional capabilities.
https://blogs.technet.microsoft.com/uktechnet/2016/03/16/6-differences-between-vs-2015-enterprise-and-pro/
CC-MAIN-2017-04
refinedweb
1,597
59.03
Install the DMD Compiler 1: Go to the DMD compiler download page. 2: Download the DMD D 1.0 compiler (dmd.1.030.zip) package. 3: Download the DMC Linker and Utilities (dmc.zip) package. 4: Unzip the to two packages into the c:\dmd folder location remembering to maintain the folder structure contained in the zip files. 5: Add the C:\dmd\bin\ folder to the PATH using the Windows Control Panel. More details on how to set the PATH can be found here. NOTE: Step 5 is optional as this can also be done from within Zeus as will be shown later in this tutorial. Create Some Code to Run Through the Compiler 1: Create the main.d file in this folder location: The code in the main.d file should look like this: Code: Select all C:\d\main\main.d 2: Create the math1.d and math2.d files in these folder locations: Code: Select all import std.stdio; // our import libraries import mathLIB.math1; import mathLIB.math2; int main(char[][] args) { real r1 = 0.95; writefln("real r1 = %f", r1); real r2 = __sqr(r1) * -1.0; writefln("real r2 = %f", r2); real r3 = __abs(r2); writefln("real r3 = %f", r3); real r4 = __acos(r1); writefln("real r4 = %f", r4); real r5 = __asin(r1); writefln("real r5 = %f", r5); real r6 = __atan(r1); writefln("real r6 = %f", r6); return 1; } The code in the math1.d file should look like this: Code: Select all C:\d\mathLIB\math1.d C:\d\mathLIB\math2.d The code in the math2.d file should look like this: Code: Select all module mathLIB.math1; private import std.c.math; real __abs(real x) { return fabs(x); } real __sqr(real n) { return n * n; } int __sign(real n) { return (n > 0 ? +1 : (n < 0 ? -1 : 0)); } Create a Zeus Workspace to Manage these Project Files Code: Select all module mathLIB.math2; private import std.c.math; real __acos(real x) { return std.c.math.acosl(x); } real __asin(real x) { return std.c.math.asinl(x); } real __atan(real x) { return std.c.math.atanl(x); } 1: With Zeus running use the Workspace, New menu and in the resulting dialog fill in the following details: - Workspace Name: My Example - Workspace Directory: c:\d\ 3: In the resulting dialog set the File Extensions to *.d and hit the Search button. 4: Hit the Save button and then hit the Close button. 5: Hit the Load button to load the newly created workspace into Zeus. At this point Zeus will have create a Workspace with a project tree that matches the project tree described earlier and Zeus will have also created the class browsing and intellesensing information for these two projects. For example, by clicking on the main.d file in the Main files section of the workspace, the file will be loaded into Zeus. Select the __atan function from the code and use the right mouse click, Tag Current Word popup menu to have Zeus load up the math2.d file at the location of the __atan function. Configuring the Zeus Workspace to Work with the DMD Compiler 1: With the main.d file loaded and set as the active file, click on the compile toolbar button or use the Compile, Compile menu and the following error output window should be displayed: This error is generated because the C:\dmd\bin\ folder is not in the system PATH. To fix this, the folder location could be added to the PATH using the Windows Control Panel or alternatively the PATH can be configued into the Zeus workspace. Code: Select all 'dmd.exe' is not recognized as an internal or external command, operable program or batch file. To configure the PATH into the workspace, use the Workspace, Options menu, select the General section and in the PATH entry field, add or append the C:\dmd\bin\; value. IMPORTANT NOTE: Make sure the PATH is added to both projects in the workspace. Now when the compile button is hit the following output will be produced: What has happened in this case is Zeus has run the following D compiler command line as defined in the D Document type. Code: Select all C:\d\main\main.d(12): Error: undefined identifier __sqr C:\d\main\main.d(12): Error: function expected before (), not __sqr of type int C:\d\main\main.d(14): Error: undefined identifier __abs C:\d\main\main.d(14): Error: function expected before (), not __abs of type int C:\d\main\main.d(16): Error: undefined identifier __acos C:\d\main\main.d(16): Error: function expected before (), not __acos of type int C:\d\main\main.d(18): Error: undefined identifier __asin C:\d\main\main.d(18): Error: function expected before (), not __asin of type int C:\d\main\main.d(20): Error: undefined identifier __atan C:\d\main\main.d(20): Error: function expected before (), not __atan of type int As the error messages suggest the code in the main.d is missing some external functions, which is not surprising since these functions are defined in the math1.d and math2.d files of the other project and the files do not appear anywhere on this default command line. Code: Select all dmd.exe -c -debug -v $fn One way to fix this error would be to add all the files to the command line, but a much better approach would be to use a build manager to handle the building of the project. So it's time to configure Zeus to use a build manager. Related Topics: Getting the D language debugger to work with Zeus. Intergrating the D programming language help file. Intergrating the D programming language Tango help file. Writing Zeus macros using D scripting module. Using the dfmt with Zeus Using the Dscanner (D Language) inside Zeus Using the DCD with Zeus
http://www.zeusedit.com/phpBB3/viewtopic.php?t=2465
CC-MAIN-2018-09
refinedweb
988
67.35
I gang import data from XLS to Postgres DB Budget $30-250 USD Modify an existing PHP script which converts data in an Excel spreadsheet to SQL statements. This project will entail understanding of PHP and good database skills. I will also expect the person who completes this project to be available for further projects to import data into more tables. 3 freelancere byder i gennemsnit $30 for dette job workingpeople Hi your project requirements is simple. I wish to continue with you on you this and next projects also. thanks sagar $30 USD på 1 dag (4 bedømmelser) 2.5
https://www.dk.freelancer.com/projects/php-data-processing/import-data-from-xls-postgres/
CC-MAIN-2017-43
refinedweb
101
71.65
Bicycle Control Design in Python Design of a sequential dual-loop controller for a bicycle using NumPy, SciPy, Python Control, and Plotly. Introduction¶ In this notebook I am going to develop a simple dual-loop feedback control system to balance and direct a bicycle. During the process of developing the controller, I will highlight some of the interesting dynamics and control properties of the vehicle. In particular, a bicycle requires control to both balance and direct the vehicle so I will use two feedback loops to address this. Control through steering is, in general, the primary input that has the most control authority. The steering lets the rider position the wheel contact points under the center of mass, very much like when balancing a stick on your hand, i.e. you hand is synomymous to the wheel contact points. In the same way as the hand moving in the direction of the fall of the stick, one must "steer" the bicycle into the fall. This means that if the bicycle is falling (rolling) to the left, the steering must ultimately be directed towards the left to keep the bicycle upright. Furthermore, to direct the bicycle we use this fact and effectively execute "controlled falls" to change the direction of travel. But there is one peculiarity that makes it more difficult to balance and control a bicycle than most vehicles. This is the fact that the bicycle is a non-minimum phase system and requires the rider to "countersteer". I will show how the controller design must take this into account. The main goals of the notebook are to: - Describe a mathematical plant model of a bicycle - Demonstrate the capabilities of the Python Control library - Develop a dual-loop controller for tracking a desired heading - Demonstrate the concept of countersteering Open Loop Bicycle Model¶ To come up with a suitable controller I first need a model that describes the open loop dynamics of the system, i.e. a plant model. The model I will use is pretty much the simplest model of a bicycle that will allow one to study mechanism of steering into the fall. The assumptions that the model is founded on are as follows: - The bicycle and rider mass and inertia are all lumped into a single rigid body. - The front assembly (handlebars, fork, and wheel) are massless and thus no effort is required to change the direction of the steering angle. - There are no gyroscopic effects from the spinning wheels (they are treated more like skates or skis). The following diagram shows the essential components and variables in the model: from IPython.display import SVG SVG('model-diagram.svg') with these variable definitions: - $m$: Combined mass of the bicycle and the rider - $h$: Height of the center of mass - $a$: Distance from rear wheel to the projection of the center of mass - $b$: Wheelbase - $v_r,v_f$: Speed at rear and front wheels, respectively - $g$: Acceleration due to gravity - $I_1,I_2,I_3$: Principal moments of inertia of the combined bicycle and rider - $\delta(t)$: Steering angle - $\theta(t)$: Roll angle - $\dot{\psi}(t)$: Heading angular rate The non-linear equation of motion of this model can be written as so:$$ (I_x + mh^2) \ddot{\theta} + (I_3 - I_2 - mh^2)\left(\frac{v_r \tan\delta}{b}\right)^2 \sin\theta\cos\theta -mgh\sin\theta =-mh\cos\theta \left(\frac{av_r}{b\cos^2\delta}\dot{\delta}+\frac{v_r^2}{b}\tan{\delta}\right) $$ The left hand side describes the natural roll dynamics and the right hand side gives the roll torque produced by steering. Additionally, the heading is dictated by this differential equation:$$ \dot{\psi} = \frac{v_r}{b}\tan{\delta} $$ Linearize the Model¶ The non-linear model presented above can be linearized about the upright equilibrium configuration ($\theta =\delta=0$). The simplest method to put these equations into a linear form is to assume that all of the angles are small ($\approx0$). This means that $\sin\theta\approx\theta$, $\cos\theta\approx1$, $\cos\delta\approx1$, $\tan\delta\approx\delta$, and $\tan^2(\delta)\approx0$. With that assumption and defining $I=I_1$ and $v=v_r$the linear equation of motion can now be written as:$$ (I + mh^2) \ddot{\theta} - mgh\theta = -\frac{mh}{b}\left(av\dot{\delta}+v^2\delta\right) $$ With $\theta$ as the output variable and $\delta$ as the input variable a transfer function can be created by transforming the above equation into the frequency domain:$$ \frac{\theta(s)}{\delta(s)} = -\frac{mhv}{b} \frac{as + v}{(I + mh^2)s^2 - mgh}$$ The same can be done for the heading differential equation:$$\dot{\psi}=\frac{v}{b}\delta$$$$\frac{\psi(s)}{\delta(s)}= \frac{v}{bs}$$ Dependency Installation¶ Before we begin designing the controller we will need to install some dependencies. The simplest way to get everything is to use conda and setup an environment with just the necessary packages: $ conda create -n bicycle-control pip numpy scipy ipython-notebook $ source activate bicycle-control (bicycle-control)$ conda install -c slycot control (bicycle-control)$ pip install plotly import numpy as np import control as cn import plotly.plotly as pl import plotly.graph_objs as gr Controller Design¶ At this point I will use the linear model as a foundation for a controller design. I will create a sequential dual-loop feedback controller which has an inner roll stabilization loop and an outer heading tracking loop. The final design will allow one to specify a desired heading of the bicycle. The structure of the controller is shown in the following block diagram: SVG('block-diagram.svg') First, some reasonable numerical values for each of the model constants are specified. g = 9.81 # m/s^2 m = 87.0 # kg I = 3.28 # kg m^2 h = 1.0 # m a = 0.5 # m b = 1.0 # m v = 5.0 # m/s The Python Control package has a transfer function object that I will use to define all of the transfer functions needed in the control design. The first transfer function to specify is the plant's steer to roll relationship, $\frac{\theta(s)}{\delta(s)}$. This transfer function provides a second order linear relationship relating the roll angle of the bicycle, $\theta$, to the steering angle, $\delta$, and the inner loop controller designed around this transfer function will ensure that the bicycle can follow a commanded roll angle. num = -m * h * v / b * np.array([a, v]) den = np.array([(I + m * h**2), 0.0, -m * g * h]) theta_delta = cn.TransferFunction(num, den) theta_delta -217.5 s - 2175 ----------------- 90.28 s^2 - 853.5 The first thing one may ask is whether or not the open loop system is stable? It is fairly obvious from the denominator of the transfer function (i.e. the characteristic equation), but we can use the .pole() method of a transfer function to compute the roots of the characteristic equation. If any of the poles have positive real parts, then I know the system is unstable. theta_delta.pole() array([-3.0746689, 3.0746689]) Now I see clearly that we have a pair of real poles, where one is positive, indicating that our system is unstable. This is identical to the behavior of a simple inverted pendulum. The next thing that may be of interest is the step response of the system. I know that the system is unstable but the step response can possibly reveal other information. I will use the control toolbox's forced_response function so that we can control the magnitude of the step input. We will simulate the system for 5 seconds and set a step input of 2 degrees. time = np.linspace(0.0, 5.0, num=1001) delta = np.deg2rad(2.0) * np.ones_like(time) time, theta, state = cn.forced_response(theta_delta, T=time, U=delta) Now, I'll create a reusable function for plotting a SISO input/output time history. def plot_siso_response(time, input, output, title='Time Response', x_lab='Time [s]', x_lim=None, input_y_lab='Input', input_y_lim=None, output_y_lab='Output', output_y_lim=None, subplots=True): """Plots a time history of the input and output of a SISO system.""" xaxis = gr.XAxis(title=x_lab, range=x_lim) if subplots: yaxis = gr.YAxis(title=input_y_lab, range=input_y_lim, domain=[0.0, 0.49]) yaxis2 = gr.YAxis(title=output_y_lab, range=output_y_lim, domain=[0.51, 1.0]) layout = gr.Layout(title=title, xaxis=xaxis, yaxis=yaxis, yaxis2=yaxis2, showlegend=False) output_trace = gr.Scatter(name=output_y_lab, x=time, y=output, yaxis='y2') else: yaxis = gr.YAxis(range=output_y_lim) layout = gr.Layout(title=title, xaxis=xaxis, yaxis=yaxis) output_trace = gr.Scatter(name=output_y_lab, x=time, y=output) input_trace = gr.Scatter(name=input_y_lab, x=time, y=input) data = gr.Data([input_trace, output_trace]) fig = gr.Figure(data=data, layout=layout) return fig The simulation of the system's response to a positive step input of 2 degrees in steering is shown below. This plot shows that if you apply a positive steer angle, the roll angle exponentially grows in the negative direction. So forcing the steering to the right will make you fall to the left. This is opposite of what one finds in most vehicles. Typically steering to the right causes you to go to the right. This peculiarity will influence the controller design. pl.iplot(plot_siso_response(time, np.rad2deg(delta),np.rad2deg(theta), title='Step Response', output_y_lab='Roll Angle [deg]', input_y_lab='Steer Angle [deg]')) Now it may be interesting to see if a simple proportional controller can stabilize this model and what kind of gain value is needed to do so. One way to do this is to compute the root locus of the closed loop system with a varying gain. A root locus is most informative as a plot on the imaginary/real plane, so here we define a function that will plot the roots as a function of the varying gain. def plot_root_locus(gains, roots): """Plots the root locus of the closed loop system given the provided gains.""" real_vals = np.real(roots) imag_vals = np.imag(roots) xaxis = gr.XAxis(title='Re') yaxis = gr.YAxis(title='Im') layout = gr.Layout(title='Root Locus', showlegend=False, xaxis=xaxis, yaxis=yaxis) # plots a blue "x" for the first roots open_loop_poles = gr.Scatter(x=real_vals[0, :], y=imag_vals[0, :], marker=gr.Marker(symbol='x', color='blue'), mode='markers') # plots a red "o" for the last roots last_poles = gr.Scatter(x=real_vals[-1, :], y=imag_vals[-1, :], marker=gr.Marker(symbol='o', color='red'), mode='markers') data = [] gain_text = ['k = {:1.2f}'.format(k) for k in gains] for r, i in zip(real_vals.T, imag_vals.T): data.append(gr.Scatter(x=r, y=i, text=gain_text, marker=gr.Marker(color='black'), mode="markers")) data.append(open_loop_poles) data.append(last_poles) return gr.Figure(data=gr.Data(data), layout=layout) The root locus can be computed with Python Control's root_locus function. Let's see if various negative feedback gains will stabilize the system. neg_feedback_roots, neg_feedback_gains = cn.root_locus(theta_delta, kvect=np.linspace(0.0, 10.0, num=500)) The root locus shows that for increasing negative feedback gains the bicycle will simply fall over even faster. (Use the "Show closest data on hover" option in the Plotly graph and hover over the traces to see the value of the gain.) I already know that the right steer makes the bicycle fall to the left. So if the bicycle is falling to the left a positive error causes steering to the right! Which, of course, causes the bicycle to fall over even faster. So what if I use positive feedback instead? pl.iplot(plot_root_locus(neg_feedback_gains, neg_feedback_roots)) Now this is much better. It seems that if positive feedback is applied the system can indeed be stabilized by the controller. So if one commands a roll angle the bicycle must steer in the same direction to obtain that roll angle. This proves that we must steer into the fall in order to keep a bicycle upright. pos_feedback_roots, pos_feedback_gains = cn.root_locus(theta_delta, kvect=np.linspace(0.0, -20.0, num=500)) pl.iplot(plot_root_locus(pos_feedback_gains, pos_feedback_roots)) Now that I know I can stabilize the system with positive feedback based on the roll angle error, I can choose a suitable controller that will allow me to command a roll angle and the bicycle will follow. The ability to command a roll angle is the first step to commanding a heading. For example, to head in the right direction the bicycle must eventually be steered and rolled to the right. So if I can command a rightward roll I am one step away from commanding a rightward turn. Note that our system is a Type 0 system, thus a simple proportional feedback system will stabilize the system but there will be some steady state error. If better performance is required for the inner loop control, a different compensator (e.g. PID) would be needed. But since I am developing a sequential dual-loop controller that will not be necessary. Below I define a function that generates the closed loop transfer function of a basic feedback system: def feedback(plant, controller): """Returns the closed loop system given the plant and controller of this form: + ----- ----- -->o-->| c |-->| p |---> -| ----- ----- | ------------------- """ feedforward = controller * plant return (feedforward / (1 + feedforward)).minreal() Based on the root locus plot I choose a positive feedback gain that stabilizes the roll loop and generate the closed loop transfer function $\frac{\theta}{\theta_c}$. k_theta = -2.5 theta_thetac = feedback(theta_delta, k_theta) theta_thetac 6.023 s + 60.23 --------------------- s^2 + 6.023 s + 50.78 Now the closed loop system is stable and has the expected oscillatory roots: theta_thetac.pole() array([-3.01146433+6.45807869j, -3.01146433-6.45807869j]) The closed inner loop attempts to track a commanded roll angle, $\theta_c$, and one can see how well it does that by looking at the step response. Below I command a 3 degree roll angle. Note that I get the expected steady state error with this simple controller. I could add a more complex compensator, such as a PID controller, to improve the performance of the roll control, but since I am ultimately concerned with heading control I'll leave this inner loop control as it is and will tune the performance of the heading control with the outer loop. thetac = np.deg2rad(3.0) * np.ones_like(time) time, theta, state = cn.forced_response(theta_thetac, T=time, U=thetac) pl.iplot(plot_siso_response(time, np.rad2deg(thetac), np.rad2deg(theta), input_y_lab='Commanded Roll Angle [deg]', output_y_lab='Roll Angle [deg]', subplots=False)) I can now examine the steer angle needed to produce this roll behavior. It is interesting to note here that a positive commanded roll angle requires an initial negative steer angle that settles into a positive steer angle at steady state. So, to roll the bicycle in a desired direction, the controller must steer initially in the opposite direction. The following response shows the input and output traces of the roll controller block. thetae = thetac - theta delta = k_theta * thetae pl.iplot(plot_siso_response(time, np.rad2deg(thetae), np.rad2deg(delta), input_y_lab='Roll Error [deg]', output_y_lab='Steer Angle [deg]')) The next step is to close the outer heading tracking loop. To do this I need a new "plant" transfer function that represents the linear relationship between the commanded roll angle, $\theta_c$, and the heading angle, $\psi$, which will be fed back to close the outer loop. This transfer function can be found using this relationship:$$ \frac{\psi(s)}{\theta_c(s)} = \frac{\theta(s)}{\theta_c(s)} \frac{\delta(s)}{\theta(s)} \frac{\psi(s)}{\delta(s)} $$ theta_thetac 6.023 s + 60.23 --------------------- s^2 + 6.023 s + 50.78 delta_theta = cn.TransferFunction(theta_delta.den, theta_delta.num) delta_theta 90.28 s^2 - 853.5 ----------------- -217.5 s - 2175 psi_delta = cn.TransferFunction([v], [b, 0]) psi_delta 5 - s psi_thetac = (theta_thetac * delta_theta * psi_delta).minreal() psi_thetac -12.5 s^2 - 1.665e-14 s + 118.2 ------------------------------- s^3 + 6.023 s^2 + 50.78 s Since the heading transfer function is an integrator, a pole is introduced at the origin that makes the system marginally stable and now a Type 1 system. This pole will be an issue for stability but it also means that our system will not have any steady state error for a step response with a simple control gain. psi_thetac.pole() array([-3.01146433+6.45807869j, -3.01146433-6.45807869j, 0.00000000+0.j ]) It is also interesting to check out the zeros of the system. The zeros dictate how the system responds to various inputs. In particular, there are a pair of zeros where one is in the right half plane. Right half plane zeros indicate that the system is a "non-minimum phase system" and the consequences of systems like these are very interesting. A single right half plane zero will cause the response to initially go in the "wrong" direction. This is an inherent property of a bicycle and it forces the rider to "countersteer" when they want to initiate a turn. This property makes bicycles fundamentally different than typical automobiles, boats, etc. psi_thetac.zero() array([-3.0746689, 3.0746689]) It is possible to see this phenomena by simulating the step response of $\frac{\psi(s)}{\theta_c}$. Notice that to command a rightward roll angle, the heading is initially directed to the left before it gets into a steady turn. time, psi, state = cn.forced_response(psi_thetac, T=time, U=thetac) pl.iplot(plot_siso_response(time, np.rad2deg(thetac), np.rad2deg(psi), title="Step Response", output_y_lab='Heading Angle [deg]', input_y_lab='Commanded Roll Angle [deg]')) To close the heading loop, so that I can command a heading angle, I will use the root locus technique once more. roots, gains = cn.root_locus(psi_thetac, kvect=np.linspace(0.0, 3.0, num=1001)) pl.iplot(plot_root_locus(gains, roots)) I will need negative feedback here to move the pole from the origin further into the left half plane, but too much gain will destabilize the oscillatory root. k_psi = 0.25 psi_psic = feedback(psi_thetac, k_psi) psi_psic.minreal() -3.125 s^2 + 1.388e-15 s + 29.54 --------------------------------- s^3 + 2.898 s^2 + 50.78 s + 29.54 psi_psic.pole() array([-1.14995336+6.93382365j, -1.14995336-6.93382365j, -0.59802194+0.j ]) Now the following plot shows the closed loop system's ability to track a command heading angle of 10 degrees. psic = np.deg2rad(10.0) * np.ones_like(time) time, psi, state = cn.forced_response(psi_psic, T=time, U=psic) pl.iplot(plot_siso_response(time, np.rad2deg(psic), np.rad2deg(psi), input_y_lab="Commanded Heading [deg]", output_y_lab="Heading [deg]", subplots=False)) Finally, to really see the counter steering effect during this simulation I will plot the steering input alongside both the roll and heading outputs. psie = psic - psi thetac = k_psi * psie time, theta, state = cn.forced_response(theta_thetac, T=time, U=thetac) thetae = thetac - theta delta = k_theta * thetae xaxis = gr.XAxis(title='Time [s]') yaxis = gr.YAxis(title='Steer [deg]', domain=[0.0, 0.32]) yaxis2 = gr.YAxis(title='Roll [deg]', domain=[0.33, 0.65]) yaxis3 = gr.YAxis(title='Heading [deg]', domain=[0.66, 1.0]) layout = gr.Layout(title='Commanded Heading Response', showlegend=False, xaxis=xaxis, yaxis=yaxis, yaxis2=yaxis2, yaxis3=yaxis3) steer_trace = gr.Scatter(x=time, y=np.rad2deg(delta)) roll_trace = gr.Scatter(x=time, y=np.rad2deg(theta), yaxis='y2') heading_trace = gr.Scatter(x=time, y=np.rad2deg(psi), yaxis='y3') commanded_heading_trace = gr.Scatter(x=time, y=np.rad2deg(psic), yaxis='y3') data = gr.Data([steer_trace, roll_trace, heading_trace, commanded_heading_trace]) fig = gr.Figure(data=data, layout=layout) pl.iplot(fig) This final plot shows the closed loop step response to a commanded rightward heading angle of 10 degrees. It is clear that one must initially steer about 5 degrees to the left causing a roll to the right to make the rightward change in heading. Conclusion¶ This notebook demonstrates one way to design a controller for a linear model of a bicycle. The controller shown is probably the simplest controller for tracking heading and the gains can certainly be tuned for different performance metrics. I made use of the Python Control library and the root locus design tool to find two suitable gains for the sequential dual-loop controller. Finally, simulation of the closed loop system gave very clear demonstration of the inherent need for countersteering to effectively control the vehicle. About the author¶ Jason K. Moore is a postdoctoral researcher at the Cleveland State University Human Motion & Control Lab where he works on identification of human walking control strategies for use in powered prosthetic control design. He loves bicycles, so much so that he wrote a dissertation on the topic. You can find out more about him on his website: moorepants.info.
https://plot.ly/ipython-notebooks/bicycle-control-design/
CC-MAIN-2018-09
refinedweb
3,435
57.67
Adding Movie Genres Adding Genre Field To hold Movie genres we need a lookup table. For Kind field we used an enumeration but this time genres might not be that static to declare them as an enumeration. As usual, we start with a migration. Modules/Common/Migrations/DefaultDB/ DefaultDB_20160519_154700_GenreTable.cs: using FluentMigrator; using System; namespace MovieTutorial.Migrations.DefaultDB { [Migration(20160519154700)] public class DefaultDB_20160519_154700_GenreTable : Migration { public override void Up() { Create.Table("Genre").InSchema("mov") .WithColumn("GenreId").AsInt32().NotNullable() .PrimaryKey().Identity() .WithColumn("Name").AsString(100).NotNullable(); Alter.Table("Movie").InSchema("mov") .AddColumn("GenreId").AsInt32().Nullable() .ForeignKey("FK_Movie_GenreId", "mov", "Genre", "GenreId"); } public override void Down() { } } } We also added a GenreId field to Movie table. Actually a movie can have multiple genres so we should keep it in a separate MovieGenres table. But for now, we think it as single. We'll see how to change it to multiple later. Generating Code For Genre Table Fire sergen.exe using Package Manager Console again and generate code for Genre table with the parameters shown below: Use parameters shown with dotnet sergen gif you are using ASP.NET Core version. This screenshot belongs to an older version of Sergen, just use parameters shown in new version Rebuild solution and run it. We'll get a new page like this: As you see in screenshot, it is generated under a new section MovieDB instead of the one we renamed recently: Movie Database. This is because Sergen has no idea of what customizations we performed on our Movie page. So we need to movie it under Movie Database manually. Open Modules/Movie/GenrePage.cs, cut the navigation link shown below: [assembly:Serenity.Navigation.NavigationLink(int.MaxValue, "MovieDB/Genre", typeof(MovieTutorial.MovieDB.Pages.GenreController))] ` And move it to Modules/Common/Navigation/NavigationItems.cs: //... [assembly: NavigationMenu(2000, "Movie Database", icon: "icon-film")] [assembly: NavigationLink(2100, "Movie Database/Movies", typeof(MovieDB.MovieController), icon: "icon-camcorder")] [assembly: NavigationLink(2200, "Movie Database/Genres", typeof(MovieDB.GenreController), icon: "icon-pin")] //... Adding Several Genre Definitions Now let's add some sample genres. I'll do it through migration, to not to repeat it in another PC, but you might want to add them manually through Genre page. using FluentMigrator; using System; namespace MovieTutorial.Migrations.DefaultDB { [Migration(20160519181800)] public class DefaultDB_20160519_181800_SampleGenres : Migration { public override void Up() { Insert.IntoTable("Genre").InSchema("mov") .Row(new { Name = "Action" }) .Row(new { Name = "Drama" }) .Row(new { Name = "Comedy" }) .Row(new { Name = "Sci-fi" }) .Row(new { Name = "Fantasy" }) .Row(new { Name = "Documentary" }); } public override void Down() { } } } Mapping GenreId Field in MovieRow As we did with Kind field before, GenreId field needs to be mapped in MovieRow.cs. namespace MovieTutorial.MovieDB.Entities { // ... public sealed class MovieRow : Row, IIdRow, INameRow { [DisplayName("Kind"), NotNull, DefaultValue(1)] public MovieKind? Kind { get { return (MovieKind?)Fields.Kind[this]; } set { Fields.Kind[this] = (Int32?)value; } } [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } [DisplayName("Genre"), Expression("g.Name")] public String GenreName { get { return Fields.GenreName[this]; } set { Fields.GenreName[this] = value; } } // ... public class RowFields : RowFieldsBase { // ... public readonly Int32Field Kind; public readonly Int32Field GenreId; public readonly StringField GenreName; public RowFields() : base("[mov].Movie") { LocalTextPrefix = "MovieDB.Movie"; } } } } Here we mapped GenreId field and also declared that it has a foreign key relation to GenreId field in [mov].Genre table using ForeignKey attribute. If we did generate code for Movie table after we added this Genre table, Sergen would understand this relation by checking foreign key definition at database level, and generate similar code for us. We also added another field, GenreName that is not actually a field in Movie table, but in Genre table. Serenity entities are more like SQL views. You can bring in fields from other tables with joins. By adding LeftJoin("g") attribute to MovieId property, we declared that whenever Genre table needs to be joined to, its alias will be g. So when Serenity needs to select from Movies table, it will produce an SQL query like this: SELECT t0.MovieId, t0.Kind, t0.GenreId, g.Name as GenreName FROM Movies t0 LEFT JOIN Genre g on t0.GenreId = g.GenreId This join will only be performed if a field from Genre table requested to be selected, e.g. its column is visible in a data grid. By adding Expression("g.Name") on top of GenreName property, we specified that this field has an SQL expression of g.Name, thus it is a view field originating from our g join. Adding Genre Selection To Movie Form Let's add GenreId field to our form in MovieForm.cs: namespace MovieTutorial.MovieDB.Forms { //... [FormScript("MovieDB.Movie")] [BasedOnRow(typeof(Entities.MovieRow))] public class MovieForm { //... public Int32 GenreId { get; set; } public MovieKind Kind { get; set; } } } Now if we build and run application, we'll see that a Genre field is added to our form. The problem is, it accepts data entry as an integer. We want it to use a dropdown. It's clear that we need to change editor type for GenreId field. Declaring a Lookup Script for Genres To show an editor for Genre field, list of genres in our database should be available at client side. For enumeration values, it was simple, we just run T4 templates, and they copied enum declaration to script side. Here we can't do the same. Genre list is a database based dynamic list. Serenity has notion of dynamic scripts to make dynamic data available to script side in the form of runtime generated scripts. Dynamic scripts are similar to web services, but their outputs are dynamic javascript files that can be cached on client side. The dynamic here corresponds to the data they contain, not their behavior. Unlike web services, dynamic scripts can't accept any parameters. And their data is shared among all users of your site. They are like singletons or static variables. You shouldn't try to write a dynamic script (e.g. lookup) that acts like a web service. To declare a dynamic lookup script for Genre table, open GenreRow.cs and modify it like below: namespace MovieTutorial.MovieDB.Entities { // ... [ConnectionKey("Default"), DisplayName("Genre"), InstanceName("Genre"), TwoLevelCached] [ReadPermission("Administration")] [ModifyPermission("Administration")] [JsonConverter(typeof(JsonRowConverter))] [LookupScript("MovieDB.Genre")] public sealed class GenreRow : Row, IIdRow, INameRow { // ... } We just added line with [LookupScript("MovieDB.Genre")]. Rebuild your project, launch it, after logging in, open developer console by F12. Type Q.getLookup('MovieDB.Genre') and you will get something like this: Here MovieDB.Genre is the lookup key we assigned to this lookup script when declaring it with: [LookupScript("MovieDB.Genre")] This step was just to show how to check if a lookup script is available client side. Lookup key, "MovieDB.Genre" is case sensitive. Make sure you type exact same case everywhere. Using LookupEditor for Genre Field There are two places to set editor type for GenreId field. One is MovieForm.cs, other is MovieRow.cs. I usually prefer the latter, as it is the central place, but you may choose to set it on a form, if that editor type is specific to that form only. Information defined on a form can't be reused. For example, grids use information in XYZColumn.cs / XYZRow.cs while dialogs use information in XYZForm.cs / XYZRow.cs. So it's usually better to define things in XYZRow.cs. Open MovieRow.cs and add LookupEditor attribute to GenreId property as shown below: [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor("MovieDB.Genre")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } After we build and launch our project, we'll now have a searchable dropdown (Select2.js) on our Genre field. While defining [LookupEditor] we hardcoded the lookup key. It's also possible to reuse information on GenreRow: [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow))] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } This is functionally equivalent. I'd prefer latter. Here, Serenity will locate the [LookupScript] attribute on GenreRow, and get lookup key information from there. If we had no [LookupScript] attribute on GenreRow, you'd get an error on application startup: Server Error in '/' Application. 'MovieTutorial.MovieDB.Entities.GenreRow' type doesn't have a [LookupScript] attribute, so it can't be used with a LookupEditor! Parameter name: lookupType Forms are scanned at application startup, so there is no way to handle this error without fixing the issue. Display Genre in Movie Grid Currently, movie genre can be edited in the form but is not displayed in Movie grid. Edit MovieColumns.cs to show GenreName (not GenreId). namespace MovieTutorial.MovieDB.Columns { // ... public class MovieColumns { //... [Width(100)] public String GenreName { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } } Now GenreName is shown in the grid. Making It Possible To Define A New Genre Inplace While setting genre for our sample movies, we notice that The Good, the Bad and the Ugly is Western but there is no such genre in Genre dropdown yet (so I had to choose Drama). One option is to open Genres page, add it, and come back to movie form again. Not so pretty... Fortunately, Serenity has integrated inplace item definition ability for lookup editors. Open MovieRow.cs and modify LookupEditor attribute like this: [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow), InplaceAdd = true)] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } Now we can define a new Genre by clicking star/pen icon next to genre field. Here we also see that we can use a dialog from another page (GenreDialog) in the movies page. In Serenity applications, all client side objects (dialogs, grids, editors, formatters etc.) are self-contained reusable components (widgets) that are not bound to any page. It is also possible to start typing in genre editor, and it will provide you with an option to add a new genre. How Did It Determine Which Dialog Type To Use You probably didn't notice this detail. Our lookup editor for genre selection, automatically opened a new GenreDialog when you wanted to add a new genre inplace. Here, our lookup editor made use of a convention. Because its lookup key is MovieDB.Genre, it searched for a dialog class with full names below: MovieDB.GenreDialog MovieTutorial.MovieDB.GenreDialog ... ... Luckily, we have a GenreDialog, which is defined in Modules/Genre/GenreDialog.ts and its full name is MovieTutorial.MovieDB.GenreDialog. namespace MovieTutorial.MovieDB { @Serenity.Decorators.registerClass() @Serenity.Decorators.responsive() export class GenreDialog extends Serenity.EntityDialog<GenreRow, any> { protected getFormKey() { return GenreForm.formKey; } protected getIdProperty() { return GenreRow.idProperty; } protected getLocalTextPrefix() { return GenreRow.localTextPrefix; } protected getNameProperty() { return GenreRow.nameProperty; } protected getService() { return GenreService.baseUrl; } protected form = new GenreForm(this.idPrefix); } } If, lookup key for GenreRow and its dialog class didn't match, we would get an error in browser console, as soon as we click the inplace add button: Uncaught MovieDB.GenreDialog dialog class is not found! But this is not the case as they match. In such a case, either you'd have to use a compatible lookup key like "ModuleName.RowType", or you'd need to specify dialog type explicitly: [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow), InplaceAdd = true, DialogType = "MovieDB.Genre")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } You shouldn't specify Dialog suffix, nor the full namespace, e.g. MovieTutorial.MovieDB.Genre, as Serenity automatically searches for them. Adding Quick Filter for Genre To Grid As our list of movies becomes larger, we might need to filter movies based on values of some fields, besides the quick search functionality. Serenity has several filtering methods. One of them is Quick Filter, which we'll use on Genre field. Edit Modules/MovieDB/Movie/MovieColumns.cs to add a [QuickFilter] attribute on top of GenreName field: public class MovieColumns { //... public DateTime ReleaseDate { get; set; } [Width(100), QuickFilter] public String GenreName { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } Build and navigate to Movies page. You'll a quick filtering dropdown for genre field is available: The field that is filtered is actually GenreId not GenreName that we attached this attribute to. Serenity is clever enough to understand this relation, and determined editor type to use by looking at attributes of GenreId property in GenreRow.cs. Re-runing T4 Templates As we added a new entity to our application, we should run T4 templates after building solution.
https://volkanceylan.gitbooks.io/serenity-guide/tutorials/movies/adding_movie_genres.html
CC-MAIN-2019-18
refinedweb
2,085
51.85
okhttp_kit 1.0.2 okhttp_kit # dart版okhttp3 Usage # 还是原来的配方,还是熟悉的味道 import 'package:okhttp_kit/okhttp_kit.dart'; Features and bugs # Please file feature requests and bugs at the issue tracker. 1.0.2 # - 修正 MultipartBody 1.0.1 # - 优化 1.0.0 # - 更名 okhttp_kit 0.2.1 # - 优化 0.2.0 # - 简化依赖 0.1.4 # - 优化 0.1.3 # - 优化 0.1.2 # - curl add headerFilter 0.1.1 # - bugfix - curl 0.1.0 # - dart - okhttp 3.10.0 Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: okhttp_kit: :okhttp_kit/okhttp_kit.dart'; We analyzed this package on Dec 4, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.6.1 - pana: 0.12.21 Platforms Detected platforms: Flutter, other Primary library: package:okhttp_kit/okhttp_kit.dartwith components: io. Health issues and suggestions Document public APIs. (-0.30 points) 446 out of 457 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API. Maintenance suggestions The package description is too short. (-19 okhttp_kit.dart. Packages with multiple examples should provide example/README.md. For more information see the pub package layout conventions.
https://pub.dev/packages/okhttp_kit
CC-MAIN-2019-51
refinedweb
215
56.32
Connect to the HAM #include <ha/ham.h> int ham_connect( unsigned flags); int ham_connect_nd( int nd, unsigned flags); int ham_connect_node( const char *nodename, unsigned flags); libham The ham_connect() function initializes a connection to a HAM. The ham_connect_nd() and ham_connect_node() functions initialize connections to remote HAMs. The nd specified to ham_connect_nd is the node identifier of the remote node at the time the ham_connect_nd() call is made. The ham_connect_node() function takes as a parameter a fully qualified node name (FQNN). You can call these functions any number of times, but because the library maintains a reference count, you need to call ham_disconnect() the same number of times to release the connection. Connections are associated with a specific process ID (pid). If a process performs ham_connect() and then calls fork(), the child process needs to reconnect to the HAM by calling ham_connect() again. But if a process calls any of the following: it doesn't need to call ham_connect*(), since those functions do so on their own. For all other ham*() functions, clients must call ham_connect() first. There are no flags defined at this time. Upon failure, the ham_connect*() functions return the error as set by the underlying open() library call that failed.
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.ham/topic/hamapi/ham_connect.html
CC-MAIN-2018-43
refinedweb
201
54.73
Hello all! I want to write a block that can directly access the uhd_usrp_source. This block is a mac block hence it is up on the food chain and far away from uhd_usrp_source in terms of its processing function. What is a good way of passing it a handle to the usrp_source ? I can think of some hacks (such as a static global pointer where the uhd_usrp_source C++ object registers itself) but it seems ugly to me to take that route. Is there a better way to access global objects from within a block implementation. Thanks in advance for any help. Regards, Ranga on 2013-11-14 01:28 on 2013-11-14 10:08 Hi Ranga, that's what pointers are for, after all. Just do it! Thanks to the make()-magic you basically always have a smart shared pointer instead of an block object (unless you really try to break the system ;) ). Just a quick note though: MAC is usually timing-relevant. Timed commands might not work as you expect, so please be aware that calling set_command_time on your source might break functionality since there is no out-of-order execution. Greetings, Marcus on 2013-11-14 15:41 Marcus, Thanks for your reply. What will the shared pointer be called. I see stuff like this in the code: GR_SWIG_BLOCK_MAGIC2(uhd, usrp_source) GR_SWIG_BLOCK_MAGIC2(uhd, usrp_sink) GR_SWIG_BLOCK_MAGIC2(uhd, amsg_source) Presumably, that generates a structure that is registered as a global pointer. So in my mac, I want something like extern .... At the risk of asking for too much help, can you give me some guidance or point me to a fragment of code somewhere that does this sort of thing. Thanks, Ranga on 2013-11-14 15:54 In GR 3.7, the shared pointer is usually blockname::sptr; I can't really point you to a very good example, but when you call top_block.connect(src, sink) in C++, you're giving it spointers :) As I said, whenever you make a block, you actually get a shared pointer to that instance, and not the object itself. on 2013-11-14 16:55 Marcus, Looking around I don't see where the pointer to the block is made globally visible. I am inclined to add some code to the make method to register the shared pointer in a global variable when the method is called. Since my application has only a single USRP block (source and sink), there's no danger of overwriting something. My problem is this: I have python code that creates the blocks and strings them together etc. but I want to actually access the created block from c++ code (in the mac block implementation). Let me know if I am seriously astray. Thanks again for your help. on 2013-11-14 17:13 Hi, > Looking around I don't see where the pointer to the block is made globally > visible. No where. There could be several UHD source/sink blocks, so nothing will be made globally visible by GR. > I have python code that creates the blocks and strings them together etc. > but I want to actually access the created block from c++ code (in the mac > block implementation). You'll have to give the instanciated uhd source block as an argument of your custom block constructor and play with SWIG to make the Python object be converted back to a C++ smart pointer. Have fun. > Let me know if I am seriously astray. You are. Whatever you need to do, there has to be a better way. Cheers, Sylvain on 2013-11-14 17:45 Hi Ranga, either you're seriously astray or I don't understand what you want. This is C++ running on an operating system with segmentation. There are *no* globally visibly objects, there is only calls to the operating systems / IPC to communicate with other processes and objects that live within your own process that you can directly address. Ok, there's shared memory, but you can't move a uhd_source to shared pages; that doesn't make sense. When you're in the same process, it's easy just to pass pointers around. They are objects as everything else. Let's assume you construct a flowgraph like top_block->connect(uhd_source, processing, mac, sink) then you can just do mac->set_uhd_src_pointer(uhd_source) which would be something like mymac::set_uhd_src_pointer(uhd_source::sptr src) { _uhd_src_sptr = src; } which enables you to just _uhd_src_sptr->set_center_frequency(20000); inside your class. Greetings, Marcus on 2013-11-14 17:56 Marcus, Based on what you and others have replied, I think my "most elegant" plan of attack would be to toss the generated puthon glue code (which I generated using grc-companion BTW) and do everything in C++ so I dont have to worry about the language interface at all. This way, I will not need global shared pointers. Thank you again for all the time you have spent responding to me. Ranga on 2013-11-15 10:10 _______________________________________________ Discuss-gnuradio mailing list Discuss-gnuradio@gnu.org on 2013-11-15 10:16 I am working on a dynamic spectrum mac where the MAC will reach out to a TV White space DB (and also potentially do spectrum sensing) and adjust the centre frequency of the USRP periodically. Thanks for your help! Regards, Ranga on 2013-11-15 11:18 Hi, First: Please pay attention and reply to the list and not to me personally. > A suggested "improvement" to the gnuradio code base (let me know what you > think) : > Please keep such objects in a globally visible list (I can provide a diff if there is interest) so that applications such as mine can access them. UHD > sources and sinks are likely to be quite static as are indeed most gr blocks I would suspect. What I think is that I wouldn't call that an improvement at all. IMHO It's a horrible design ... >> You'll have to give the instanciated uhd source block as an argument >> of your custom block constructor and play with SWIG to make the Python >> object be converted back to a C++ smart pointer. Have fun. > > It sounds quite messy and hence I had to ask this list if there was a better > way. Wait what ? Passing the pointer cleanly between blocks is "messy", but polluting the global application namespace is "clean" ??? I think we have radically different idea of what's good design and what's not ... > I am open to any ideas. I could of course modify the gnuradio source code > to export a global pointer but I'd love it if I could leave the core source > code alone. If I'm not mistaken, you can control the UHD source / sink with message passing to change the frequency. Then your MAC just has a msg output port connecting to the uhd message input port to control it. Cheers, Sylvain on 2013-11-15 12:01 On Thu, Nov 14, 2013 at 12:14 PM, Sylvain Munaut <246tnt@gmail.com> wrote: > Hi, > > > First: Please pay attention and reply to the list and not to me personally. > Mercy! That was an honest mistake. A thousand apologies. > It's a horrible design ... > I agree. If you notice I started off with that premise (i.e. that it was a hack). > Wait what ? Passing the pointer cleanly between blocks is "messy", > > If I'm not mistaken, you can control the UHD source / sink with > message passing to change the frequency. Then your MAC just has a msg > output port connecting to the uhd message input port to control it. > I will look at the block again but I could not see that. Thanks for taking the time to reply. Regards, Ranga
https://www.ruby-forum.com/topic/4418528
CC-MAIN-2017-43
refinedweb
1,290
71.04
- running a script form an attribute? - Vray render command - Byron bevel script - shotview - Compile 32bits plugin to server 2003 x64 - creating Color Per Vertex sets in a node - Scripting Demo Reel - Scaling object based on other object? - getting last command (should work for setAttr too)) - Error line numbers for python - Clear output window - selecting particular edges without knowing the exact number - Remove All Connection to PolyShape and Material /shadingEngine - In MEL or C++, post a redisplay of the current view? - MFnDagNode::duplicate instancing really slow - Rewrite this as a Python Class? - Get the list of Hypershade Bins ? - Attaching a Camera to a Motion Path - Custom dockable interface - How create "Bump mapping" attr in API? - Force Eclipse Navigator to add files? - Can i make a screen shot from the current camera with MEL? - geting selections name and putting in variable - Grayscale ramp = scale Y - Finding the mirror of a joint or object - Object-level Blind Data - some Qt problem with c++ - PyMel Performance (Query Curves of Animated Attrs)) - Help with match command - Changing attributes on a directionalLight - Need help!! Please!! M.E.L Scripting. - Wing ide send code to maya 2011 failure,please help - Build interim results (python) - Python variables & Maya UI buttons - Project a mesh to another with Maya API and Python - custom particle cache Emitter - export anim clips via pyMel/Python - needs auto "squash and stretch" pupils script - why is this namespace command not working? - Visual studio 2010 openmp crash - How do I reset after a script run? - reproducing skeletal animation outside Maya - getting attribute from shape node of fluid container - Connect Fluid Texture to Field - Filtering specific nodes with Python - Returning matrix from procedure? - Help with PyQt Pymel and all that other Jazz - place vector data into directionalLight rotate - changing the type of a node - User input mel - Get mobject handle - Acceleration - inserting a variable in object name - Mesh Intersecting Selection? - Python slice question - autowalk expression - list last changed attribute/s? - Change UD Attr max value? - Add to rotation w/Slider? - Python Unicode Converstion Question - Python API - OpenGL text in maya - MPxTransform::connectionBroken, MDagModifier::deleteNode on child crashes Maya - help with mel to python - Get var name after using vars()? - Create multiple joints on selected edges - Python API: MFnNurbsCurve error on degree 3 curve - How to read QT interface spinbox parameter? - Preset maya Ramp - adding same attribute to several objects works in mel but not in python? - create render layer in pre render mel command - Maya 2012 enter button bug - API only : isoparm length - Passing a list through c or cc flags - get name of currently selected object? (python) - query current selection component type - Setting up VS2008 for Maya API development - performing commands on the elements of and array - looking for reading on maya ui development with python and qt. - Change the default language to python???? - basic script to create layer overrides and disable them - Converting an edge loop to a joint in Python - command for changing rasterizer transparency value using mel - some problem of using openGL in maya c++ - A mysterious statement from a code sample - ABCshelf v2.5 - Trouble setting up PyQt4 and Maya - scripted plugin question - how to scale the picture to match the control in maya - Change Renderer to Mental Ray using Python - Mel Gui - Nesting scrollLayout into rowColumnLayout - [Python]bug with maya.cmds.skinPercent? - Help w/Var Assignment inside a Class - Convert Int to String?? - Fetch the filename from the Trax editor (Python) - How to set attribute non-keyable? - Render Method not overwriting old image? - Compare values in time (current frame with previous frame) - Expressions and a problem with calculations! - Open Maya tutorials/info - Elliptical Blendshapes WIP - Advantage of writing shaders??? - have one object rotation change anothers in local space only - Extracting the file name from the filepath - Strange polyEditUV RAM Problem?! - raycast using M3dView::viewToWorld? - Where to begin when writing a Maya CUDA plug-in? - Quick bug: ScriptEditor closes after compiling - How to toggle shelf icons like the physX shelf - Remembering selection sequence - setLineWidth - what's the command to change line thickness? - Get Menu under current Mouse position? - Why doesn't isoSelectAutoAddNewObjs work? - Mel script to Duplicate Lights along a curve - Maya API: My own mesh modifier node isn't "live" enough... - CGWorkshop Creating Maya Plugins - RotationBlend - Derive variable from another MEL Script? - RotationBlend - Point Centred Camera in Maya - Maya Mocap/Devices deprecated? - Increasing value per frame? (Expressions) - Running MEL script at start of Maya - Check if contain certain alphabet? - PyMEL / Ramp Attributes - geometry pos attract particle position - Maya 2012 MEL script Problem - Right Clicking a Shelf Button (Maya 2012) - MEL script unable to set drawing override for some reason - Render my own shape - Renaming error - No tooltip / label of my scripted shelf icons - IKFK Matching Arm Problem ARGHH! - IK FK Matching Arm Problem - int variable[] add up for themselve according to their size? - adjusting colors of a Texture File - Maya devKit with VS2010 - userPrefs refuses me - Group object by Sections - Maya API Threading question - command to change resolution in vray - Using variables inside expression (with pymel)? - custom 3d texture - API: Paintable multiattribute? - copy all textures to a directory - python - Listing history - controlling viewport display - python - Declaring a string later on in a script? - Split up an poly object by UV shells (MEL) - Delete a node and all it's subnodes, just deletes one subnode? - "Shorten" 2 floats variable value to make them exact to compare? - Python from an external interpreter - Struggling with various MEL-issues - List selected attribute? - How to find the same name objects in the scene? - passing current selection to function - changing the active viewport camera - RotatePivot Problem - appending text in fwrite? - Set mesh resolution when creating text? - playblast change format to image - python api write.Image help - "Force Open Scene" in Maya 2012. - Learning Maya API + Python to draw stuff directly to viewport - Getting Started (Recommend Readings + Glossary) - Forget the 0! - passing arguments from one functions to another! - poker cards - applying xform within a character set - merge vertices, point by point - Delete or change multiple custom attributes - Sample animation curve from Maya runtime expression - connect VS to maya - Referance Duplication - Selecting join chain - problem about setting attributes to default - Highlight Layer - Set pymel to work with 2010 and 2012 - Custom shelf ion size - Reading values by knowing the string name of a variable? - Custom Shader to Maya Shader (copying connections etc) - Selecting all Trim Edges - python expression node - Python API callback data - Probable reasons for itGeom.setPosition failing - Getting cameras direction - object type or child type... - EasyCut..for dynamic cut - Getting the Shading Group of selected face/object? - render assistant tool python - loop through attributes in AE? - Problem with MFnMesh- Internal data doesn't update - dataReferenceEdits placeHolderList - QT designer / Maya UI (iconTextButton) - Sourcing a mel script with Python - web browser python download - Memory usage of my script - evaluate script keyboard in mac? - Query loaded references - cycle warning on stretch - Can't find object in class? (python) - where is pyQt 4.7.1 for maya to download? - Build/execute 'if' statement? - Python get video Pixel Color - Help with a beginners first two scripts - Python Syntax question (Multiple Arguments) - how to get object's vertex position - [py] iterate through textFieldGrp entries - creating an expression with MEL using string variables - playblast with trax sound - How to use For Loop to control multiple object Trans X In Expressions ??? - Trying to create a MEL script working on any selected object - selection a child of first Object selected ? - Very simple MEL if/then, help please! - Selection a child of the parent by script. - Help with system, syntax and maya prompt - Maya saves wont open properly, Please help! - realtime holdout matte shader. cgfx?? - Node that creates several curves - aetemplate help - Translate and Rotate Instanced Objects - "no object matches name: pickWalk" --- ??? - Help with this hi res setup - Getting the custom data in the scene when scene file is referenced - Python "instance has no attribute" - column layout with scrollbars? - Connect texture as input to custom attribute - MEL - Automatically add joints - Smart makefile for C++ at function level - Help: Script Editor stopped showing errors / results - Help with existing deformer - cmds.confirmDialog() command in Maya 2011 - Python question(very noob) - List of all equivalent Qt widgets in MEL? - use image from a webserver in a mel window? - Python lambda and QT button - Make message attr connectable - Batch Bake Texture Animation (to one texture) - MPxNode stops computing?!? - Focus camera under cursor - Constraint Icon? (!) - can i do this? - Syntax error in adding expression with MEL command - How to create interactive tools using mel? - Faces or Normal handels constantly show - Creating MEL command/hotkeys for artisan brush - Vertex color driven by translation - listConnections - gives the same answer twice? - [pyAPI - beginner] compute method errors (MFnLightDataAttribute misusage ?) - querying dependency nodes of a reference node
http://forums.cgsociety.org/archive/index.php?f-89-p-41.html
CC-MAIN-2016-36
refinedweb
1,450
54.22
This article is a collection of Scala “object” examples. I put the word object in quotes there because it has at least two meanings in Scala. In the first meaning, just like Java, an object is an instance of a class. In its second meaning, Scala has an object keyword, and using that keyword lets you do a variety of things, including a) creating a main method to launch your application, b) creating the equivalent of Java’s static methods, and also c) creating something called a companion object. In the following Scala object examples I show how all of this works, but I don’t explain it in great detail. To learn more about Scala objects, please see the Scala Cookbook, where I share more examples and explain them in detail. Objects and object instances To cast an object instance, use asInstanceOf: val recognizer = cm.lookup("recognizer").asInstanceOf[Recognizer] Some REPL examples demonstrate this: scala> val a = 10 a: Int = 10 scala> val b = a.asInstanceOf[Long] b: Long = 10 scala> val c = a.asInstanceOf[Byte] c: Byte = 10 The equivalent of Java’s .class (classOf) If you’re coming from the Java world and want to use .class, you classOf instead: val info = new DataLine.Info(classOf[TargetDataLine], null) To create a launching point for your applications, you have two choices. First, you can define an object which extends App: object Foo extends App { // your application begins here } Or you can define an object that contains a main method: object Bar { def main(args: Array[String]) { // your application starts here } } Singleton objects You create Singleton objects in Scala with the object keyword. You can’t create static methods in a Scala class, but you can create singleton objects in Scala with the object keyword, and methods defined in a singleton can be accessed like static methods in Java. // create a singleton object CashRegister { def open { println("opened") } def close { println("closed") } } // call the CashRegister methods just like static methods object Main extends App { CashRegister.open CashRegister.close } Static methods in Scala Here are more examples of “static” methods. First define the object: import java.util.Calendar import java.text.SimpleDateFormat object DateUtils { // as "Wednesday, October 20" def getCurrentDate:String = getCurrentDateTime("EEEE, MMMM d") // as "6:20 p.m." def getCurrentTime: String = getCurrentDateTime("K:m aa") // a common function used by other date/time functions private def getCurrentDateTime(dateTimeFormat: String): String = { val dateFormat = new SimpleDateFormat(dateTimeFormat) val cal = Calendar.getInstance() dateFormat.format(cal.getTime()) } } Now call them: scala> DateUtils.getCurrentTime res0: String = 10:13 AM scala> DateUtils.getCurrentDate res1: String = Friday, July 6 The Factory Method in Scala You can implement the Factory Method in Scala by defining an apply method in a companion object. Just have the apply algorithm determine which specific type should be returned, and you can create new Animals like this: val cat = new Animal("cat") val dog = new Animal("dog") To implement this behavior, create a parent trait: trait Animal { def speak } In the same file, create a companion object, the classes that extend the base trait, and a suitable apply method: object Animal { private class Dog extends Animal { override def speak { println("woof") } } private class Cat extends Animal { override def speak { println("meow") } } // my preferred factory method def apply(s: String): Animal = { if (s == "dog") return new Dog else return new Cat } } Summary As I mentioned, these are some of the examples you’ll find in the Scala Cookbook. Please see the Cookbook for more examples and details. You can find it at these links:
https://alvinalexander.com/scala/scala-object-examples-static-methods-companion-objects/
CC-MAIN-2020-29
refinedweb
592
51.07
Hey all, I have been researching this for days now. Now that I've complained, I'm fairly new at ASP.NET, make that very new I've taken some courses and it's been a while since I studied or worked with this, and I thought this would be a very simple thing to do, and it's become and monster really quick... I need to add a simple dropdownbox with a submit button for paypal to my aspx page. So far I've seen about every hack out there, and found several incredibly ellaborate form solutions that I cannot manage to compile because they are either incomplete, or simply just incomplete instructions. So please dont reply with a link because the likeliness I've already been there is about the same as catching an STD from a prostitute. IS there anyone that could take a moment and explain to me step by step on how to either get this "ghostform" to work. These instructions suck because they dont work. I did this step by step and it's just an absolute fail. The current class file is residing in my app_code folder which is I believe where it goes however this doesn't instruct for that stept to be taken.. I've also tried to remove it from the app_code folder.. I've tried the namespace, I've tried it wiithout the namespace.. I've tried renaming have grid view control that includes a dropdown control in a template field.I wish to execute some code when the value is changed in the dropdown list. Can't figure out how to capture this event though?Any suggestions?? How can we bind a value to a combobox or dropdown? What is the property for binding a value? Thanks. Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/63915-paypal-dropdown-box-and-submit-button.aspx
CC-MAIN-2017-43
refinedweb
314
71.65
Re: STL and "function try blocks" - From: "Heinz Ozwirk" <hozwirk.SPAM@xxxxxxxx> - Date: Thu, 23 Feb 2006 23:07:52 +0100 "Babak Pourat" <pourat@xxxxxxxxxxxxxxxxxxxx> schrieb im Newsbeitrag news:466bgpF9hsfbU1@xxxxxxxxxxxxxxxxx Hallo the following code does not compile (VC 7.1): #include <vector> int testTry() try{ std::vector<int> *x = new std::vector<int>; delete x; return 0; }catch (...) { return 0; } int main(){ return 0; } d:\tmp\trytst\trytst\trytst.cpp(11) : warning C4091: '' : ignored on left of 'int' when no variable is declared d:\tmp\trytst\trytst\trytst.cpp(11) : error C2143: syntax error : missing ';' before 'inline function header' Does any one understand why it compiles if I delete the "delete x;" statement? No. I can only guess that the compiler is confused. It really looks like a compiler bug. It is valid code and accepted by other compilers, like Comeau. But there are two workarounds the problem: 1. Don't use function-try-blocks unless you really have to. 2. Insert a semicolon after the end of the catch (and before int main). This is not required by the language, and strictly speaking the program will be no valid C++ any longer, but if the compiler likes it better. Perhaps there is also 3. Upgrade to VC8, but I don't know if the bug has been fixed. HTH Heinz . - References: - STL and "function try blocks" - From: Babak Pourat - Prev by Date: can't open a file in vc++ 6 - Next by Date: Re: can't open a file in vc++ 6 - Previous by thread: Re: STL and "function try blocks" - Next by thread: Re: STL and "function try blocks" - Index(es):
http://www.tech-archive.net/Archive/VC/microsoft.public.vc.stl/2006-02/msg00095.html
CC-MAIN-2016-26
refinedweb
274
72.97
In a previous article we decided to use Python's multiprocessing module to leverage the power of multi-core machines. Our use case is all about web applications served by CherryPy and so multi-processing isn't the only interesting part: our application will be multi-threaded as well. IN this article we present a first implementation of a multi-threaded application that hands off the heavy lifting to a pool of subprocesses. The design The design is centered on the following concepts: - The main process consists of multiple threads, - The work is done by a pool of subprocesses, - Transferring data to and from the subprocesses is left to the pool manager Sample code We start of by including the necessary components: from multiprocessing import Pool,current_process from threading import current_thread,Thread from queue import Queue import sqlite3 as dbapi from time import time,sleep from random import randomThe most important ones we need are the Poolclass from the multiprocessingmodule and the Threadclass from the threadingmodule. We also import queue.Queueto act as a task list for the threads. Note that the multiprocessingmodule has its own Queueimplementation that is not only thread safe but can be used for inter process communication as well but we won't be using that one here but rely on a simpler paradigm as we will see. The next step is to define a function that may be called by the threads. def execute(sql,params=tuple()): global pool return pool.apply(task,(sql,params))It takes a string argument with SQL code and an optional tuple of parameters just like the Cursor.execute()method in the sqlite3module. It merely passes on these arguments to the apply()method of the multiprocessing.Poolinstance that is referred to by the global poolvariable. Together with SQL string and parameters a reference to the task()function is passed, which is defined below: def task(sql,params): global connection c=connection.cursor() c.execute(sql,params) l=c.fetchall() return lThis function just executes the SQL and returns the results. It assumes the global variable connectioncontains a valid sqlite3.Connectioninstance, something that is taken care of by the connectfunction that will be passed as an initializer to any new subprocess: def connect(*args): global connection connection = dbapi.connect(*args) Before we initialize our pool of subprocess let's have a look at the core function of any thread we start in our main process: def threadwork(initializer=None,kwargs={}): global tasks if not ( initializer is None) : initializer(**kwargs) while(True): (sql,params) = tasks.get() if sql=='quit': break r=execute(sql,params)It calls an optional thread initializer first and then enters a semi infinite loop in line 5. This loops starts by fetching an item from the global tasksqueue. Each item is a tuple consisting of a string and another tuple with parameters. If the string is equal to quitwe do terminate the loop otherwise we simple pass on the SQL statement and any parameters to the executefunction we encountered earlier, which will take care of passing it to the pool of subprocesses. We store the result of this query in the r variable even though we do nothing with it in this example. For this simple example we also need an database that holds a table with some data we can play with. We initialize this table with rows containing random numbers. When we benchmark the code we can make this as large as we wish to get meaningful results; after all, our queries should take some time to complete otherwise there would be no need to use more processes. def initdb(db,rows=10000): c=dbapi.connect(db) cr=c.cursor() cr.execute('drop table if exists data'); cr.execute('create table data (a,b)') for i in range(rows): cr.execute('insert into data values(?,?)',(i,random())) c.commit() c.close() The final pieces of code tie everything together: if __name__ == '__main__': global pool global tasks tasks=Queue() db='/tmp/test.db' initdb(db,100000) nthreads=10 for i in range(100): tasks.put(('SELECT count(*) FROM data WHERE b>?',(random(),))) for i in range(nthreads): tasks.put(('quit',tuple())) pool=Pool(2,connect,(db,)) threads=[] for t in range(nthreads): th=Thread(target=threadwork,kwargs={'initializer':thread_initializer}) threads.append(th) th.start() for th in threads: th.join()After creating a queue in line 5 and initializing the database in line 8, the next step is to fill a queue with a fair number of tasks (line 12). The final tasks we add to the queue signal a thread to stop (line 14). We need as many of them as there will be threads. In line 17 we initialize our pool of processes. Just two in this example, but in general the number should be equal to the number of cpu's in the system. If you omit this argument the number will default to exactly that. Next we create (line 21) and start (line 23) the number of threads we want. The target argument points to the function we defined earlier that does all the work, i.e. pops tasks from the queue and passes these on to the pool of processes. The final lines simply wait till all threads are finished. What's next? In a following article we will benchmark and analyze this code and see how we can improve on this design.
http://michelanders.blogspot.com/2011/07/sqlite-multiprocessing-proxy-part-2.html
CC-MAIN-2017-22
refinedweb
901
54.22
Ham Radio Fills Communication Gaps In Nepal Rescue Effort 141 itwbennett writes: Amateur. Re: (Score:3) Re:Once again (Score:5, Insightful) No, but if you're trying to work on a relay in the US and there is broadband interference it is still an issue. That said, I don't thing consumer powerline networking is going to be very widespread, thanks in no small part to the ARRL's effort. Further, this is why you do need to 'advertise' when amateur radio is used for public safety purposes. We are still fighting a rear guard battle and anytime the public (and our wonderful legislators) see the service as beneficial it slows down the attempts to limit amateur radio's spectrum and rights. Re: (Score:3) Actually, the FCC is now proposing that amateurs share those LF spectrums that BPL uses as experiments BY HAMS have determined they can co-exist just fine. In fact, Hams are getting more frequencies now than they have ever lost. is just one of several similar articles the ARRL has reported on recently. Please don't keep up the BS argument that we're losing our bands and privileges wh Re: (Score:1) What gets me is that ham AR callsigns in general are significantly size constrained -- we're talking a standard of 5 letters and a digit, with some of those having reserved meanings, limiting the namespace. Sure, you have up to three letters appended as a location code as well, but this is still a restricted namespace. But then, the airspace is also limited, so I guess we're lucky that there are enough dedicated hams around, while not so many that we run into significant issues that increased population de Re: (Score:2) Actually, the FCC is now proposing that amateurs share those LF spectrums that BPL uses as experiments BY HAMS have determined they can co-exist just fine. Citations? At one point, even with notching, it was ridiculously easy to kill a BPL signal with just a few watts. So I'd love to see the data. Re: (Score:2) Re: (Score:2) Do you think there is much powerline networking going on in Nepal right now? We get that a lot. When they were trying to ram Broadband over Powerline ( BPL ) down AMerica's throats a few years ago, we heard a lot of "Well when you are needed, the power will be down, and you'll have clear conditions then. Running digital signals over an exposed line makes for an antenna, and it generates a lot of interference. Problem is communications takes practice, and is a learned skill. Propagation is different on different frequencies and at different times of day and year. If you never get t Re:Once again (Score:5, Insightful) While you do have a good point, I think that any disaster that requires ham radio for communication would also likely have taken out the local power grid leaving consumer power line networking inoperable. Re: (Score:3) It's not the powerline networking in Napal that is a problem. It's the powerline networking here that is. It's over loads the receivers front end and makes it near impossible to receive the signal from Napal. That is why powerline networking is bad. The typical transmitter in an HF rig is 100 watts. Put that 100 watts in to a good yagi antenna and you can send a signal any where in the world. Even with powerline networking your signal will get out. By the time that signal gets to it's destination it Re: (Score:3) I send signals around the globe with 5 watts. 100 watts is for the guys that have crap antennas. Re: (Score:1) A good hill is the best amp. Re: (Score:2) A good amp is the best antenna. A good hill is the best amp. Until everyone does it. We used to hear about how spread spectrum was the cure for interference. Seems they forgote what happened to the noise floor whne a lot of people were using SS. So when everyone is running a California Kilowatt, all things will be reset. Re: (Score:2) I've only managed to go about 50 miles at 5 Watts on 2m, but I haven't really made a point of trying for range either. Re: (Score:2) Not freak weather, that is tropospheric ducting. It actually happens a lot more often than you think. Re: (Score:2) Not freak weather, that is tropospheric ducting. It actually happens a lot more often than you think. Just not when you need it. Kinda fun though. Re: (Score:2) Very true. I do some PSK31 usually between 5 and 15 watts. Should get on the air more often but like you said, I have a crap antenna. No seriously. Since I moved I haven't been been able to get a decent antenna in the air. Stuck with a crappy OCF dipole at 20 feet. I think the spaghetti I had last night would work better. Re:Once again (Score:5, Interesting) There are in general two kinds of operation of ham radio. First is local communications - local rescue groups using hams to help communicate and coordinate between groups on the ground and HQ. There's also the longer distance communications - these guys get the signal out so someone in an area not affected by the disaster can pass on messages and whatnot. Think more along the lines of "I'm safe and sound" type messages being passed on to family. The problem is power line broadband basically makes the long-distance communications less reliable. I mean, given Nepal's economic conditions, sending out "I'm safe" messages usually mean transmitting to India, where the infrastructure works fine. Powerline broadband would be working as well, which means your message will not be received because the receiver can't hear your message over the noise. Power line networking or broadband generally affects long-distance HF communications more so than short-range VHF/UHF comms. And that's bad because short range would mean the power and infrastructure is down so it's not a problem. But you want to pass your message to places unaffected by the disaster where there IS working infrastructure, and then you have interference. And that's the beauty of ham radio that blows people's minds away - it's not just about people talking to people in a city, but around the world - it spans the ability to talk to people from your neighbourhood or city to around the globe. Most people are fascinated because most of them only see extreme short range communications - a few miles at most for a cellphone to the tower, to a few tens of feet for wifi and Bluetooth. Telling them that it's possible to actually go around the world on wireless... Re: (Score:2) It's still important to protect the bands in-between disasters. You want hams to have working equipment ready to go when the disaster strikes. Very few are going to go through the work and expense of obtaining and maintaining equipment that they don't even get to use. Just keeping the bands interference free enough that hams get to talk to one another means that they will be turning their radios on regularly and know when something needs fixing. You also want the hams themselves to be ready for the disaster. Re: (Score:2) Power line networking is the least of our problems on HF. A more serious problem is the huge number of broadband noise generators in every modern home. Computing devices like computers, phones, and tablets are the starting point but far from the entire story. Microcontrollers are being put into EVERYTHING these days - if it has a digital display, control buttons, and/or a remote control, it probably has one or more microcontrollers in it. Most modern electronic gadgets have switching power supplies. We are Re: (Score:1) Re: (Score:2) Packet is still alive and well, but everyone I know has switched to APRS (a protocol that sits on top of AX.25). HF packet is slow, but it's there. 300 Baud doesn't pass a lot of data. I'd rather rely on packet via satellite than packet over HF. The successful HF modes (AMTOR, SITOR, etc) have forward error correction to cut down on bad data... the packet network just has to repeat everything until it's understood. W1BMW Re: (Score:1) There is also Pactor which is used extensively by the WinLink 2000 system. It is a fairly fast protocol (relative to what you get with other HF data protocols). The only downside is it requires a proprietary TNC (ie, modem) which is not cheap. Re: (Score:2) There is also Pactor which is used extensively by the WinLink 2000 system. It is a fairly fast protocol (relative to what you get with other HF data protocols). The only downside is it requires a proprietary TNC (ie, modem) which is not cheap. The Winlink users have poisoned the wells though. It's not as bad as it used to be, but many of them would just open on a frequency, and kill everything else. Thhis was especially problematic with the low bandwidth low power modes like PSK31. And there were several cases where an unattented station kust locked up and transmitted garbage for weeks. They need to prove tehy can get along with the neighbors now, and there's that little matter of proprietary software. A lot of Hams use Linux or OS X. And being Mesh networking (Score:5, Informative) Re:Mesh networking (Score:5, Insightful) No, the real benefit from amateur radio operations is that they are trained to work as a team. The reality is that the vast majority of the gear used in emergency communications are modern, reliable, commercial rigs that the operators could no more fix internally than you can fix your computer. They don't train to McGuyver the radios, they train to set up command and control links and practice working with interfaces with the Internet and government systems. That way, when the shit hits the fan they can plop down in their chair and do something useful. Yes, you can get a field station running with a length of wire and a car battery and there are lots of ham radio operators who delight in that sort of thing. But organization and teamwork is the real key to effectiveness and that is why amateur radio has been embraced by governments world wide. Re: (Score:2) RaDAR - Rapid Deployment Amateur Radio. we make a game out of it by having impromptu events where a large group goes out and tries to get to a hard to reach location without power or anything else, erects antennas and then tries to contact as many other members on that event. It's great fun. That game Saves peoples arses during emergencies. Re: (Score:2) The reality is that the vast majority of the gear used in emergency communications are modern, reliable, commercial rigs that the operators could no more fix internally than you can fix your computer. It is questionable if the "vast majority" of the gear in use is commercial gear. I'd bet that the majority is amateur gear, just because it is so much easier to deal with than the commercial gear. For example, most commercial gear requires programming software just to change the frequencies in the radio, while ham gear allows user selection much more easily. Yes, many hams, especially in the US, buy used (or new) commercial gear if they are involved with public safety groups, just because it is easier to c Re: (Score:1) Re: (Score:2) Re: (Score:1) Forgive me, but i can not tell which side you are landing on. Most Hams (at least in the US) build their shack so in the event of a large scale disaster, they can still get on the air. They often have backups of everything, so if their tower does go down, they pull out their backup, and erect a vertical dipole, or run a dipole wire antenna between trees. As for power... well the hobby made a point from the beginning of building the all the equipment so it uses 12 volt power systems which can be found in any Re: (Score:2) Why do they do this? because they know that the large telecom companies are too damn cheap to set up their networks in a way for them to be bullet proof. Because the public is too damn cheap to pay for 100% availability of telecom systems. You wouldn't pay what it would cost to have 100% available cell service during disasters, or any other public infrastructure for that matter. And governments don't pay for 100% capacity for their public safety communication systems, either, for the same reason. The public wouldn't put up with the taxes they'd have to pay to get there. A five channel trunked radio system can handle five simultaneous users (ten when Phase I As a result of the efforts of hams (Score:1) A hundred elderly Indian hams received emergency relief shipments of Geritol. A hundred more Indian hams were complaining about the sense of entitlement the lower castes had for expecting any emergency relief at all, while another few hundred Indian hams jammed the nets because it happened to be a day of the a contest and they were yelling at the emergency nets for operating on "their" frequency. Re: (Score:1) All of which had nothing to do with an earthquake in the country of Nepal. Nepal is not India. Go look at a map! Side Note (Score:1) Be careful if you're a HAM, locally I was able to find the name, address, and other information of callsigns with a simple look up. In this case not a big deal but be aware that anyone can look you up via your callsign.... [wikipedia.org] Interesting, see which country has the most. Other than that kudos to these people as they are often the last working line of communication. Re: (Score:2) - Show up at the address listed for me... they might tell you where I've deployed to if they say anything at all. W1BMW Re: (Score:1) zimmerman, mark d 716 druid hills rd temple terrace, fl 33527 Re: (Score:2) When should I tell the people that live there now when to expect you? Re: (Score:1) Still missing the point... Re: (Score:3) I really have noticed people who were looking for me, standing outside of the mailbox store looking confused. What was that? You're breaking up (Score:2) Ham [static] Fills [static] Gaps It sure does. Good troll by Stikypad (Score:2) This is normal. (Score:3) Ham radio fills in the gaps for ALL natural disasters. Katrina it was a huge aspect of communications. This is not new, this is what ham radio does. Only 8% HF Ops? (Score:1) Re: (Score:2). Re: (Score:2) It's actually pretty easy to prompt a visit from the army if you pop up on frequencies where you are not expected, in some countries. Never mind any nice citizen-consulting sunshine-respecting mostly-independent part of the Executive Branch like FCC. Guys with guns come. Re: (Score:2) Surprising that so few hams in Nepal are setup for HF operations. I wonder how many HF ham stations there are in the U.S. One can't tell by license class. I know that in a real emergency my QRP FT-817 is not going to be the most reliable but until I can fork out for some bigger solar panels and batteries to run an amp, 5 Watts is going to be what I've got. With morse code that's enough to work the world, sometimes. Beats the hell out a walkie talkie. I've been a licensed ham for almost 20 years and don't do HF because I don't find it to be very fun or interesting - making a contact 1000 miles away has lost its allure (to me) in the internet age. I do participate in local disaster drills using VHF/UHF, but am not really interested in HF to get out of the area. Though my club dues do help pay for their HF equipment, and I'm glad that we do have members interested in HF. I can run a VHF/UHF crossband repeater from my car for an unlimited time thanks to so Re: (Score:1) We need a way of keeping hams in practice (Score:2, Insightful) Although everybody appreciates the amateur service's value in disasters, ham is slowly dying in the US because it is perceived by the public as falling behind compared to the more popular commercial communications technologies. What I would like to see is for ham to be assigned a legal commercial niche that it can occupy as an incentive to buy gear and revive the experimental edge that the service has long been renowned for. How about Internet service in rural areas? Allow hams to offer commercial interconne Re:We need a way of keeping hams in practice (Score:5, Insightful) There are more licensed hams today than ever before. Part of that is because we modernized the licensing rules and don't have a Morse code test any longer (for which I take partial credit). And they already have a commercial niche. Most of them have jobs. Many of us got those jobs because of the skill we developed through Amateur Radio. In general they pay as well or better than offering ISP service to the boonies. We don't want to see commercial use of those frequencies, even if such use would help some folks get more equipment, because if that happened, there would not be room for Amateurs any longer. You should consider that all of the ham HF frequencies together are smaller than one WiFi channel. And they have global range. So, if you offer a good bandwidth signal to some home in the boonies, you have potentially used up that freuquency for the whole world! Re: (Score:3) What I would like to see is for ham to be assigned a legal commercial niche that it can occupy as an incentive to buy gear and revive the experimental edge that the service has long been renowned for. What possible commercial activity using ham radio could trigger experimental activities? Given the ability to experiment now, how could allowing commercial ham usage improve that? How about Internet service in rural areas? Allow hams to offer commercial interconnect from fiber and other wired broadband to the scattered users who have difficulty getting ISP service any other way. Cool. Consume the available ham frequencies with people selling ISP services. What a great way to promote ham radio. The connectivity we would get from this type of commercialization is, furthermore, exactly what would help the most in time of disaster. I hate to tell you, but infrastructure in the ham radio world requires a great deal of dedication and commitment. You will find a few people who will do it for fun, but a lot more hams USE the infrastructure than Re: (Score:2) Although everybody appreciates the amateur service's value in disasters, ham is slowly dying in the US because it is perceived by the public as falling behind compared to the more popular commercial communications technologies. Homeowners' associations trying to eradicate it with antenna bans don't help either. Re: (Score:2) With the rise in satellite television and the appearance of eight zillion satellite dishes, I thought that local regulation of them got slapped down because they fell under the FCC's domain and were exempt from local regulation. Re: (Score:2) Re: (Score:2) What tweak13 said: gubmints can't shut down hams, but contracts can. And if you don't like the provisions of the contract, you have the option of building your house in a subdivision where they don't have an HOA. I believe there are some in Mississippi. Re: (Score:1). Re: (Score:1) Allow hams to offer commercial interconnect from fiber and other wired broadband to the scattered users who have difficulty getting ISP service any other way. HF radio would be a candidate technology. HF frequencies would not only suck at this due to their wildly-varying (by time of day, solar activity, weather, etc.) propagation characteristics, but they wouldn't get you enough bandwidth to support anything recognizable as internet service. Seriously, the various HF bands are on the order of a couple hundred kilohertz each. A single Wi-Fi channel is 22 megahertz wide. Just how well would a single worldwide shared-media 128K wireless network work? Besides, interested parties can already do this with Wi-Fi Re:Again? (Score:5, Insightful) Do we really need a story about ham radio after every disaster? Yes. Because it's great to hear about geeks helping people. And it's wonderful to see technology used in positive ways. I love seeing people being nice to one another. These are heroes: not the assholes shooting. Any asshole thug can pick up a gun or bomb, but it takes skill, kindness, and bravery to help people you don't know to contact others. We need to see and hear more of this in the violent shitty World. Re:Again? (Score:5, Insightful). Re: (Score:1) F---ing A. Re:Again? (Score:5, Informative) In the mid-west storm spotters, ham operators, and other volunteers coordinate with sheriff's departments to get relevant information to the national weather service and out to the pubic during times of severe weather. Tornado season is a particularly busy time for them and they are appreciated. Re: (Score:1) Hell yes..!!!!!!!!! its relevant and very contemporary.. people whom speak pout about these types of things are jealous. They just spent millions of dollars and wasted man hours building a infrastructure that doesn't come close to the reliability of RADIO and the tech behind it.. Bitches just wanna bitch, because they were bored, they tried to re-invent the wheel, came up with something elliptical in stead of round, resulting in ya it works until you put a load on it, then the imperfections begin to surface Re: (Score:3) I've actually broken down on the Interstate w Re: Again? (Score:3) This is why having multiple different means of communication is important in case of emergencies. You mention cell service being down or spotty, but amateur radio is not immune to unavailability either. There are many places in the US (and the world), where you will not be able to reliably reach somebody with ham radio (especially VHF and UHF, but even HF if you're limited in what you can carry or conditions are too bad). In some of those places, phone service may work fine. Re:Again? (Score:5, Insightful) I think we do, but why? It's educational for the younger audience. I would have never known of ham radios and their usage during disasters if not for slashdot. We get new and young readers now and then. It's good for them, but maybe not for you. Re: (Score:2) Re:Again? (Score:5, Insightful) Hey Sparky.. you don't like an article?? easy fix... Dont READ it... Some of us like to hear about ham radio being used for critical stuff... geez.. What a specail snowflake.. just because he doesn't like a story, nobody else here should be able to read it either.... . Re: (Score:3) Do we really need stories about rescue efforts after every disaster? No, but some of us like the news - even that which you find repetitive. I find it interesting that, with all of the modern technologies now available, old-fashioned ham is still useful. Every time a disaster happens, even more time elapses and ham gets even older - and so the news is even more interesting. To me, this is just as anachronistic and interesting as if amateurs were using hot-air balloons to effectively deliver rescue supplies. Re: (Score:2) Do we really need stories about rescue efforts after every disaster? No, but some of us like the news - even that which you find repetitive. I find it interesting that, with all of the modern technologies now available, old-fashioned ham is still useful. Good reply. But Ham radio has definitely kept up with the times. While the old radios still work - and it's a subset of the hobby, the new stuff like the Software Defined Radio transceivers like the FlexRadios, [flex-radio.com] and the various digital/soundcard modes are nothing short of amazing. Geek-A-Licious! Disclaimer: I'm a zealot. Re: (Score:2) Anyone who is into PCs and amateur radio (or interesting tech in general) that doesn't own at least one RTLSDR dongle should dig the 10-15 dollars to get one out of their couches and start fiddling around with it and the open source software for them. The coolness factor aside, the future uses for them...and the possibility that what they can do now may be restricted in design later because of their flexibility...make these little things a must-have, and soon. Re: (Score:2) How is this insightful? It's someone moaning about the fact that they don't like a type of article. The only insight here is StinkyPad is a whiney little bitch. Re:Again? (Score:5, Interesting) Do we really need a story about ham radio after every disaster? Yes, because its an efficient indicator of the immediate scope and nature of a disaster. if the most critical and arguably resillient communications systems have finally failed, Ham is your red-flag indicator that the situation is dire. I'm sure it's being used, but not to the extent of official radio communication. Thats exactly the point. Ham is being used because Official or commerical communications systems are either damaged, destroyed, or overwhelmed beyond inteded or effective capacity. If you're in the united states the equivalent official communication would be the Emergency Alert System over a VHF repeater, if ones still standing. If not, Hams take everything from presidential to local law enforcement messages to where they need to go in a structured, orderly manner. "People communicating by any means possible," is not news. People communicating by any means possible is a normal society with twitter, cellphones, and wifi. People reliant upon analog and digital communication outside thestructure of a commercial ecosystem and in lieu of direct government correspondance is news. Ham operators build and run antennas, configure messaging relay and repeater systems, repair existing infrastructure, assist in dispatching emergency services and handle every communication thats needed in an emergency from local to state and even international SOS for emergency assistance. The point is when you're now reliant on Ham in any context to assist in a rescue effort, the outlook for existing infrastructure is very bad. Re: (Score:2) You are exactly right. One thing though, it's "Ham" or even "ham". It's not an acronym. Thanks! Re: (Score:2) Do we really need people bitching about every damned story? Nobody ever promised you a pony or that you'd never see a story you weren't personally interested in. You're free to not read it. You're also free to stop kvetching about it. Re:Again? (Score:5, Informative) Ahhh....an egocentric comment by a confirmed cellular addict. I spent two years on a sailboat in the canals and fjords of Chilean Patagonia and Argentina. I have been south of every automobile, paved road and street light in the world. Most of the time we were 100 miles or more from the nearest cell phone tower (and road). Sat phones are unreliable at these latitudes (about 55 degrees south) because the satellites are in more or less equatorial orbits. And the Chilean navy wants to hear from you twice a day when you are in Chilean waters. The only tool that will work is a single side band HF radio. When connected to A PC via a specialized modem, this setup can send and receive emails from anywhere in the world. My transmitter is only rated at 100 watts and yet it routinely communicates with stations that are more than 3000 miles away. I have contacted Europe from the Pacific Ocean. "Hobby"?!? For those of us who are really out there, amateur HF radio is the communications lifeline. P.S. Could the submitter of "Again?" make an attempt to explain to me what "official radio communication" means? 73's KR6AS Re: (Score:3, Insightful) Re: (Score:2) A small monohull is also a lot cheaper than a house, at least in most of the developed world. Even a fairly nice "yacht" (which just means "private non-business vessel") is probably affordable if you can sell your house. My parents have lived aboard for 13 years now, and their 48' (14.5m) catamaran cost significantly less than their house near Seattle. It's actually really annoying when people assume that yachties must be rolling in dough. Most have very little income, so even though the lifestyle is cheaper Re:Again? (Score:5, Interesting) Hams were absolutely crucial because we could move in and quickly setup and operate additional equipment. I know times have changed....but every time I look at the state's disaster readiness plan hams would be needed again. I think you are over estimating the ability of official channels to be ready to function on their own for weeks at a time. Re: (Score:3, Informative) Also, when a disaster strikes the cell networks are usually the first to go down. The older towers can't handle the sudden massive sp Re: (Score:2) Technically, making transceivers work when there are 30 of them in vehicles next to each other can get difficult. People wonder why you can buy a dual-band walkie talkie for $60 but the one in the police car costs much more. If it's well engineered, the one in the police car has some RF plumbing that isn't in the $60 walkie talkie. Re: (Score:2) The one on the belt of the police officer also has a few other things that make it much more expensive. First, it's more rugged than the $60 ham version; it has to be, because it is carried many hours a day and because people don't handle their working tools as carefully as they handle their personally owned equipment. Second, it has features for secure communication that aren't in the ham radio - they CAN'T be, ham radio has to be open to all listeners by law. Third, many commercial radio systems have a fe Re: (Score:2) Hell, sometimes they're hard pressed to even get in position, let alone operate. Hams have the advantage (if you want to call it that) of more than likely already having hot-damn eager people in place and ready to rock and roll. StinkyPad is probably non-tech but interested in geeky stuff and doesn't have the background or exposure to be aware of this sort of stuff. Re:Again? (Score:5, Interesting) Yes, because everyone not affected seems to assume that stuff like the Internet and cellphones will kill ham radio. Yet I'm pretty sure that while in normal circumstances you could get access to the Internet, and yes, the vast majority of people have cellphones, well, guess what? That stuff's not working now, so now what? Bit hard to use the Google or Facebook "I'm safe" feature when you can't get online now... Call a friend, or text? Pretty hard when the towers are overloaded and maybe even in states that would appear to work, but not. And that's a problem because people assume that because in the normal case it's not needed, it's obsolete. I'm sure a lot of people on /. wonder about AM/FM radios given that you can stream Pandora and other stuff off the internet. And yes, ham radio is often official radio communications methods - many rescue groups use hams to provide communications between teams on the ground and HQ, or even to provide a way to tell someone else outside the country to relay messages onwards. And local government also often uses hams for emergency communications - the ham radio infrastructure may often be better than what their official radios have. Re: (Score:2) I was downtown for 9/11 and the last big blackout. I can tell you from experience that the cell towers overloaded or had lost power within an hour of the planes hitting and almost again instantly when the power went off in the big blackout. During the blackout some cell tower installs were powered from building generators, but there was no where near enough to handle the volume. Re: (Score:2) 9/11 was especially bad because most of the telecommunications infrastructure for Lower Manhattan - landline, cellular, and internet - was in the World Trade Center. So were the primary broadcast sites of most of the TV and FM radio stations in New York City. (Some but not all of the broadcasters had backup sites in New Jersey.) Putting so many of our communication eggs in one basket may be dangerous, but it is also appealing for economic reasons; building a separate tower for each broadcaster would be a lot Re: (Score:2) No, we're all soulless sacks of meat, fuck the other guys on the other side of the planet, we'll never meet 'em, so fuck 'em. Preach it, StickyPad! Ham radio = SysVinit. (Score:2) Doesn't it make you even a little bit happy to hear that in a fucking shitty situation some good is happening? It's also a warning - don't write off old tech prematurely. Re: (Score:2) Yes, because it gives a counter point to the technophiles who'd rather see that spectrum re-purposed for other uses. We need the same story run for the POTS system after disasters, for the same reason. Re: (Score:2) Re:Again? (Score:4, Informative) You may think so, but I assure you that your impression of amateur radio's place in the scheme of things is sadly wrong. Think of them more like rabid Maker's hooked on radios instead of Arduinos and 3D printers. They aren't random people yelling breaker, breaker into a CB. It's a very technical hobby. Some might have just a transceiver and an antenna. But others have setups that look more like a satellite comm center. The people who dive into emergency comms do so with as much seriousness dedication as any EMT, fireman, or policeman. They're more like the guys who chase tornadoes. They go _to_ the trouble. But don't misunderstand their purpose. They don't do this just for emergencies. Radio is a way of life for many of them. Sure, "the communicate by any means" is still there. However, amateur radio operators provide vital communications to coordinate rescue and relief efforts all over the world, way more than just providing "I'm alive" messages. They've been doing it for over 1000 years. Ham operators happen to be sprinkled around all over the world, so they might already be there when bad shit happens. The operators have networks, procedures, and contact in place for emergency situations. Ham radio's activity in this regard is officially recognized in the US and most other countries. In the US, MARS (DoD program), ARES (civilian org, "ARRL"), and RACES (DHS program). All three deal deal with the use of amateur radio to provide emergency/disaster services. Re: (Score:1) Re: (Score:2) Ye Gods.. Listen, technical hobby it may be, some hams are technically minded, but not all of them are (back in the day, most/all of them were), Oh boy , here we go, let's play the Ham radio is doomed game, and we'll stereotype each other. Quickly tell us about how Ham radio is dying. We have the misfortune of having a couple locally who are little better than the stereotypical CB'er of old.. they shouldn't even be allowed access to license exempt PMR equipment let alone what they do have, So what? You got a couple Hams who are not living up to your demands of what makes a Ham. Is there some sort of speciall way to think and act test? Here's a dirty secret about most modern Hams, they buy their equipment and have little real idea as to what the fecking things actually do inside, and the majority of the ones who do know what the business end of a soldering iron looks like (unlike our local two muppets) slavishly follow the various mod diagrams to be found out there like electronics equivalents of script kiddies...that's the limit of their technical abilities. Here's another di Re: (Score:2) You're way more eloquent than I. Thank you. Re: (Score:2) The non technically minded hams can also be valuable in emergency communications. Sure, you need somebody to keep the ham repeater, internet link, or whatever going. But you also need people out in the field with radios, talking to people, taking their stories, and passing information along to friends, loved ones, and authorities. Those people don't need to know how their radio works to do their service. They need to know how to USE their radio, even in times of stress and heavy demands. They have an import Re: (Score:2) We regret any discomfort your stupid fucking post has caused us. Re: (Score:2) Do we really need a story about ham radio after every disaster? I'm sure it's being used, but not to the extent of official radio communication. "People communicating by any means possible," is not news. Actually yes, we do. In today's world, people seem to think that in an emergency, you just use the smartphone. Which of course is one of the first things to fail in a disaster. It's also important for people to understand that Amateur Radio is not some guy in Idaho yapping about overthrowing the Guvmint with like minded weirdos on their 1950's tube radios. My Software defined radios are marvels of electronics and computers melded together. Our digital modes are used to send and recieve forms and files. T Re: (Score:3) I'm not trying to downplay the role of amateur radio communications - I am a shortwave radio buff. But I've heard people on the news talk to survivors in Nepal using telephones. Apparently, there is some landline or satellite communications to Nepal available. Just saying. That's the case in any disaster - some traditional communications are working, but not in all areas. Even Satellite has limited capacity, it works when a few hundred, maybe even a few thousand disaster workers are using it, but if a significant fraction of the population start using their satellite phone, the system is going to be overwhelmed. Ham Radio is also capacity constrained, but with many ham radio users being trained in disaster communications, organized health and welfare messages can still be s Re: (Score:2) There are indeed satellite phones in Nepal, but they are extremely rare given the number of people that have them vs. the number that don't. Also, if you think the cell network can get overloaded in a hurry, you should look at the bandwidth budgets for those type of satellites. In disaster areas, sat phones have the same issue of 'network unavailable' when the birds are trying to pass more calls when they have bandwidth for. All commercial systems are allotted frequencies in one particular band or another an
https://tech.slashdot.org/story/15/04/29/1437242/ham-radio-fills-communication-gaps-in-nepal-rescue-effort
CC-MAIN-2016-50
refinedweb
6,712
62.27
sphinx Haskell bindings to the Sphinx full-text searching daemon. See all snapshots sphinx appears in Module documentation for 0.6.0.2 sphinx-0.6.0.2@sha256:c8c013a389825f5e70ecd3ab27e5bd08903f108aef6c0c033de6f6764401c2cc,1373 A haskell implementation of a sphinx full text search client. Sphinx is a very fast and featureful full-text search daemon. Version 0.4 is Compatible with sphinx version 1.1-beta Version 0.5+ is Compatible with sphinx version 2.0, but you can instead pass the version-one-one build flag. On hackage. Usage Constructing Queries The data type Query is used to represent queries to the server. It specifies a search string and the indexes to run the query on, as well as a comment, which may be the empty string. In order to run a query on all indexes, use "*" in the index field. The convenience function query executes a single query and constructs the Query by itself, so you don’t have to. To execute more than one Query, use runQueries. Details are below in the section Batch Queries. To construct simple queries, you can also use simpleQuery :: Text -> Query which constructs a Query over all indexes. Don’t forget that you can use record updates on a Query. In extended mode you may want to escape special query characters with escapeString. All interaction with the server, including sending queries and receiving results, is based on the Data.Text string type. You might therefore want to enable the OverloadedStrings pragma. Excerpts and XML Indexes buildExcerpts creates highlighted excerpts. You will probably need to import the types as well: import qualified Text.Search.Sphinx as Sphinx import qualified Text.Search.Sphinx.Types as SphinxT There is also an Indexable module for generating an xml file of data to be indexed. Batch Queries You can send more than one query per request to the server (which may enable server-side query optimization in certain cases. Refer to the Sphinx manual for details.) The function runQueries pipelines multiple queries together. If you are trying to combine the results, there are some helpers such as maybeQueries and resultsToMatches. mr <- Sphinx.maybeQueries sphinxLogger sphinxConfig [ SphinxT.Query query1 "db1" "" , SphinxT.Query query1 "db2" "" , SphinxT.Query query2 "db1" "" , SphinxT.Query query2 "db2" "" ] case mr of Nothing -> return Nothing Just rs -> do let combined = Sphinx.resultsToMatches 20 rs if null combined then return Nothing else return $ Just combined A note for those transitioning from 0.5.* to 0.6: the function addQueries has been removed. You can now directly send a list of Query to the server by using runQueries, which will handle the serialization for you behind the scenes. Encoding The sphinx server itself does not know about encodings except for the difference between single-byte encodings and multi-byte encodings. It assumes that all incoming queries are already properly encoded and matches the raw bytes it receives; the same holds for the results returned by the server. Hence the responsibilty for using the proper encoding (and decoding) routines lies with the caller. Version 0.6.0 of haskell-sphinx-client introduces the encoding field in both the Configuration data type and the ExcerptConfiguration data type. The library handles proper encoding and decoding in the background; just make sure you set the right encoding setting in the configuration! Details Implemenation Implementation of API as detailed in the documentation. Most search and buildExcerpts features are implemented. History Originally written by Tupil and maintained by Chris Eidhof for an earlier version of sphinx. Greg Weber improved the library and updated it for the latest version of sphinx, and is now maintaining it. Aleksandar Dimitrov updated the library to use Text. Usage of this haskell client Tupil originally wrote this for use on a commercial project. This sphinx package is now finding some use in the Yesod community. Here is a well described example usage, but do keep in mind there is no requirement to tie the generation of sphinx documents to your web application, just your database. Used in Yesod applications yesdoweb.com and eatnutrients.com.
https://www.stackage.org/lts-14.25/package/sphinx-0.6.0.2
CC-MAIN-2020-10
refinedweb
673
58.99
Az. This post gives an overview of the newly introduced experiences and capabilities made available through this feature. What's in this release? With this release,. Keep reading to find more details about the newly announced features and dev experiences for Python Functions. Powerful programming model The programming model is designed to provide a seamless and familiar experience for Python developers, so you can import existing .py scripts and modules, and quickly start writing functions using code constructs that you're already familiar with. For example, you can implement your functions as asynchronous co-routines using the async def qualifier or send monitoring traces to the host using the standard logging module. Additional dependencies to pip install can be configured using the requirements.txt format. With the event-driven programming model in Functions, based on triggers and bindings, you can easily configure the event that'll trigger the function execution and any data sources that your function needs to orchestrate with. Common scenarios such as ML inferencing and automation scripting workloads benefit from this model as it helps streamline the diverse data sources involved, while reducing the amount of code, SDKs, and dependencies that a developer needs to configure and work with at the same time. The preview release supports binding to HTTP requests, timer events, Azure Storage, Cosmos DB, Service Bus, Event Hubs, and Event Grid. Once configured, you can quickly retrieve data from these bindings or write back using the method attributes of your entry point function. Easier development As a Python developer, you don't need to learn any new tools to develop your functions. In fact, you can quickly create, debug and test them locally using a Mac, Linux, or Windows machine. The Azure Functions Core Tools (CLI) will enable you to get started using trigger templates and publish directly to Azure, while automatically handling the build and configuration for you. What's even more exciting is that you can use the Azure Functions extension for Visual Studio Code for a tightly integrated GUI experience to help you create a new app, add functions and deploy, all within a matter of minutes. The one-click debugging experience will let you test your functions locally against real-time Azure events, set breakpoints, and evaluate the call stack, simply on the press of F5. Combine this with the Python extension for VS Code, and you have a best-in-class auto-complete, IntelliSense, linting, and debugging experience for Python development, on any platform! Linux based hosting Functions written in Python can be published to Azure in two different modes, Consumption plan and the App Service plan. The Consumption plan automatically allocates compute power based on the number of incoming events. Your app will be scaled out when needed to handle a load, and scaled back down when the events become sparse. Billing is based on the number of executions, execution time and memory used, so you don't have to pay for idle VMs or reserved capacity in advance. In an App Service plan, dedicated instances are allocated to your function which means that you can take advantage of features such as long-running functions, premium hardware, Isolated SKUs, and VNET/VPN connectivity while still being able to leverage the unique Functions programming model. Since using dedicated resources decouples the cost from the number of executions, execution time, and memory used, the cost is capped to the number of instances you've allocated to the plan. Underneath the covers, both hosting plans run your functions in a docker container based on the open source azure-function/python base image. The platform abstracts away the container, so you're only responsible for providing your Python files and don't need to worry about managing the underlying Azure Functions and Python runtime. Next steps - get started and give feedback To get started, follow the links below: - Build your first serverless function using the Python in Functions Quickstart. - Find the complete Azure Functions Python develop reference. - Follow upcoming features and design discussion on our GitHub repository. - Learn about all the great things you can do with Python on Azure. - See the Python development experience with Azure Functions in action, applied to Machine Learning workloads in the webinar, “Streamline Machine Learning with Python in Azure Functions.” This release lays the groundwork for various other exciting features and scenarios. With so much being released now and coming soon, we’d sincerely love to hear your feedback. You can reach the team on Twitter and on GitHub. We actively monitor StackOverflow and UserVoice, so feel free to ask questions or leave your suggestions. We look forward to hearing from you!
https://azure.microsoft.com/it-it/blog/taking-a-closer-look-at-python-support-for-azure-functions/
CC-MAIN-2021-21
refinedweb
776
50.26
v1.92 (for Python 3.0) PDF generated using the open source mwlib toolkit see for more information Python 2 Python Choose your Python version: If you want to learn the current Python 2.x, read If you want to learn the new Python 3.0, read here or [1] [2] [3] here or download the PDF. [7] - Drew Ames in an article on Scripting Scribus published on Linux.com Yesterday I got through most of Byte of Python on my Nokia N800 and it's the easiest and most concise introduction to Python I have yet encountered. Highly recommended as a starting point for learning Python. [8] - Jason Delport on his weblog Academic Courses This book is being used as instructional material in various educational institutions: 1. 'Principles of Programming Languages' course at Vrije Universiteit, Amsterdam [9] 2. 'Basic Concepts of Computing' course at University of California, Davis [10] 3. 'Programming With Python' course at Harvard University [11] 4. 'Introduction to Programming' course at University of Leeds [12] 5. 'Introduction to Application Programming' course at Boston University [13] 6. 'Information Technology Skills for Meteorology' course at University of Oklahoma [14] 7. 'Geoprocessing' course at Michigan State University [15] 8. 'Multi Agent Semantic Web Systems' course at the University of Edinburgh [16] Python 4 Even NASA [17] The book is even used by NASA! It is being used in their Jet Propulsion Laboratory with their Deep Space Network project. Official Recommendation [18] This book has been listed on the official website for Python in the Full Tutorials section, next to the official documentation. [22] • PDF (631KB) . → Exceptions 16. → Standard Library 17. → More 18. → What Next 19. → Appendix: FLOSS 20. → Appendix: About 21. → Appendix: Revision History → Previous → Next Source: http:/ / www. swaroopch. com/ mediawiki/ index. php? oldid=1343 Contributors: Swaroop, Waterox888, 3 anonymous edits Beijing University of Technology. I think 'A Byte of Python' should be strongly recommendable for newbies as their first Python tutorial. and soon a lot of rewrite were made to fit the current wiki version and the quality of reading. which are achieved by my new 'zhpy' (python in chinese) project (launch from Aug 07). and I'm also a contributor of TurboGears web framework. google. please see the list of volunteers and languages below and decide if you want to start a new translation or help in existing translation projects. Chinese Traditional Fred Lin (gasolin-at-gmail-dot-com) has volunteered to translate the book to Chinese Traditional. An exciting feature of this translation is that it also contains the executable chinese python sources side by side with the original python sources. I found 'A Byte of Python' hit the sweet point for both newbies and experienced programmers. 'A Byte of Python' elaborates the python essentials with affordable size.I am a postgraduate at Wireless Telecommunication Graduate School. The translation are originally based on simplified chinese version. I need some material to promote python language.?. It's not too long. thanks to many tireless volunteers! If you want to help these translations. Just dedicate my translation to the potential millions of Python users in China. The recent chinese traditional version also featured with executable chinese python sources. 'It's my favorite programming language now'. it's really easy-understanding. China PR. easy-to-use and productive. My current research interest is on the synchronization. If you plan to start a new translation. This project is mainly aimed for education. Chinese Juan Shen (orion-underscore-val-at-163-dot-com) has volunteered to translate the book to Chinese. with the help of Python Numeric. 'A Byte of Python' is my tutorial to learn Python. com/ p/ zhpy/ wiki/ ByteOfZhpy). or zippy) build a layer upon python to translate or interact with python in chinese(Traditional or Simplified). I learned Python just half a year before.Python en:Translations 7 Python en:Translations There are many translations of the book available in different human languages. It is available at http:/ / code. actually. but as you can see.H. com/ p/ zhpy/ wiki/ ByteOfZhpy (http:/ / code. zhpy(pronounce (Z. Python is my major programming language for daily simulation and research job. but efficiently covers almost all important things in Python. Just as what is ensured in Swaroop's book. channel estimation and multi-user detection of multicarrier CDMA system. google. . It's clear and effective to lead you into a world of Python in the shortest time. Fred Lin .I'm working as a network firmware engineer at Delta Network. please read the Translation Howto. what . As a python evangelist (:-p). suitable to teach a complete non-programmer. de (http:/ / abop-german.gentoo. After taking a short look into Ruby. which makes translating the text a generation the output in various formats a charm. I've searched for some kind of introduction to programming. berlios. I've found the book 'How to Think Like a Computer Scientist: Learning with Python'. Bernd Hengelein (bernd-dot-hengelein-at-gmail-dot-com) and Christoph Zwerschke (cito-at-online-dot-de) have volunteered to translate the book to German. where the user interface is build using Java frameworks like Struts.we are working at the University of Florence (Italy) . The main language I use as a professional is Java. since most of my programming is about web applications. and at the same time verbose enough to teach a newbie. we had experience working with Linux platforms since ten years.it web site for Gentoo/Linux distrubution and www. Currently I'm working as a software engineer on a publicly funded project to build a web portal for all things related to computer science in Germany.gentoo.nmr. Especially text analysis and conversion is very easy with Python. We are programming on python since about seven years. it/ Programmazione/ byteofpython). I (Massimo) as service engineer and system administrator for Nuclear Magnetic Resonance Spectrometers. Germany. The Italian translation is present at www. That's all! We are impressed by the smart language used on your Book and we think this is essential for approaching the Python to new users (we are thinking about hundred of students and researcher working on our labs). I like the simple DocBook structure. gentoo. Generally I like the dynamic nature of languages like Python and Ruby since it allows me to do things not possible in more static languages like Java. German Lutz Horn (lutz-dot-horn-at-gmx-dot-de). since it is not too long. The first is good for beginners but to long to translate. Lutz Horn : I'm 32 years old and have a degree of Mathematics from University of Heidelberg.it (now under construction) for Nuclear Magnetic Resonance applications and Congress Organization and Managements.Python en:Translations 8 Italian Enrico Morelli (mr-dot-mlucci-at-gmail-dot-com) and Massimo Lucci (morelli-at-cerm-dot-unifi-dot-it) have volunteered to translate the book to Italian.Chemistry Department. written to the point. Their translation is located at http:/ / abop-german. but I try to do as much as possible with Python behind the scenes. I was very impressed with the use of blocks in this language.it/Programmazione/byteofpython (http:/ / www. The new translation is in progress and start with "Prefazione". Besides this. berlios. and 'Dive into Python'. I'm not very familiar with GUI toolkits. The second is not suitable for beginners. . Enrico as service engineer and system administrator for our CED and parallel / clustered systems. Massimo Lucci and Enrico Morelli . I think 'A Byte of Python' falls nicely between these. de). In Italy we are responsible and administrator for www. Currently I try to make more use of the functional programming features of Python and of generators. In my opinion he's absolutly right. When I discovered this book. Last year I fell in love with Python. and you can check the table of contents for more details. and maybe help spread interest for the language among people with less technical knowledge. Most tutorials and books are written in very technical English. lo5.Python en:Translations 9 Bernd Hengelein : Lutz and me are going to do the german translation together. which is a wonderful language. At the time I decided to learn python. all my problems were solved. I read somewhere in the net about a guy who said that he likes python. php/ UkÄ Å_Pythona). Although C++ is the main language I (have to) use for my daily work. org/ wiki/ Sandvika_videregÃ¥ende_skole) in Norway. or. I am 34 years old and playing with computers since the 1980's. the learning process was much harder. id/ moin. mercury. blogspot. . com/ ) and currently translating the book to Norwegian (bokmål). We just started with the intro and preface but we will keep you informed about the progress we make. a blogger (http:/ / forbedre. now some personal things about me. When I came across your book the spontaneous idea of a german translation crossed my mind. "A Byte of Python" used simple non-technical language to explain a programming language that is just as simple. Eirik Vågeskar: I have always wanted to program. The translation is in progress. Currently I am working in the field of medical imaging for a major german company. and these two things make learning Python fun. After reading half of the book. I am constantly looking for new things to learn. Dominik Kozaczko . I decided that the book was worth translating.I'm a Computer Science and Information Technology teacher. but because I speak a small language. so most high school graduates will not even have the vocabulary to understand what the tutorial is about. cgi/ ByteofPython Polish Dominik Kozaczko (dkozaczko-at-gmail-dot-com) has volunteered to translate the book to Polish. After studying computer science I started working as a software engineer. Ok. I hope the translation will help people who have found themself in the same situation as me (especially young people). I am looking forward to a good cooperation!. pl/ index. Lutz had the same idea and we can now divide the work. wikipedia. because the code looks so beautiful. when the "Commodore C64" ruled the nurseries. Luckily. bielsko. both for its possibilities and its beauty. Translation is in progress and it's main page is available here: Ukąś Pythona (http:/ / wiki. I noticed that there is very little good documentation in german available. Python en:Translations 10 Catalan Moises Gomez (moisesgomezgiron-at-gmail-dot-com) has volunteered to translate the book to Catalan. here in Romania. I'm more of a self-taught programmer and decided to learn a new language. Some time ago I needed to learn how to program in Python. concise. Romanian Paul-Sebastian Manole (brokenthorn-at-gmail-dot-com) has volunteered to translate this book to Romanian. Clear. Python. After this experience. The translation is in progress.I'm a second year Computer Science student at Spiru Haret University. . com/ notes/ Python_ro). Although I could be the one with the first initiative. The web told me there was no better way to do so but read A Byte of Python. net) (rodrigoamaral-at-gmail-dot-com) has volunteered to translate the book to Brazilian Portuguese. Danish Lars Petersen (lars-at-ioflux-dot-net) has volunteered to translate the book to Danish. Moisès Gómez . Just what I needed. I thought some other people in my country could take benefit from it too. and starts with the chapter "Taula de continguts". I'm just one volunteer so if you can help. please join me.. and Swaroop's work was really helpful. That's how popular this book is (congratulations to the author for writing such an easy to read book). But English language can be a barrier. and complete enough. I started liking Python so I decided to help translate the latest version of Swaroop's book in Romanian. why not try to translate it? And I did for a previous version of BoP. So. French Gregory (coulix-at-ozforces-dot-com-dot-au) has volunteered to translate the book to French. I my country there are two official languages. Brazilian Portuguese Rodrigo Amaral (http:/ / rodrigoamaral. I selected the Catalan language assuming that others will translate it to the more widespread Spanish.I am a developer and also a teacher of programming (normally for people without any previous experience).. Portuguese Fidel Viegas (fidel-dot-viegas-at-gmail-dot-com) has volunteered to translate the book to Portuguese. The translation is being done here (http:/ / www. Paul-Sebastian Manole . swaroopch. ISA . Gustavo Echeverria: I work as a software engineer in Argentina. '-dot-' with '. The translation is in progress. Now. and perhaps Ukranian (time permitting).' and '-underscore-' with '_' in the email addresses mentioned on this page. Russian and Ukranian Averkiev Andrey (averkiyev-at-ukr-dot-net) has volunteered to translate the book to Russian. I use mostly C# and . Turkish Türker SEZER (tsezer-at-btturk-dot-net) and Bugra Cakir (bugracakir-at-gmail-dot-com) have volunteered to translate the book to Turkish. you can read the spanish (argentinian) translation starting by the table of contents (tabla de contenidos). after receiving some requests. Swedish Mikael Jacobsson (leochingkwake-at-gmail-dot-com) has volunteered to translate the book to Swedish. . Arabic Alaa Abadi (alaanassir-at-gmail-dot-com) has volunteered to translate the book to Arabic. Note Replace '-at-' with '@' . Mongolian Ariunsanaa Tunjin (tariunsanaa-at-yahoo-dot-com) has volunteered to translate the book to Mongolian. Then I volunteered to translate the book to Spanish. I knew Python many years ago and I got stuck inmediately.Net technologies at work but strictly Python or Ruby in my personal projects.Python en:Translations 11 Spanish. I've begun to translate "A Byte of Python" with the help of Maximiliano Soler. Dashes in other places in the email address remain as-is. Not so long after knowing Python I discovered this book and it helped me to learn the language. Python en:Translations 12 Previous Next Source: http:/ / have highlighted many such differences. I started writing a few pages but it quickly became 30 pages long. Gustavo. I consider this book to be my contribution and tribute to the open source community. It is useful for experienced programmers as well. I had to choose between Python and Perl bindings for the Qt library. it has reached a stage where it has become a useful guide to learning the Python language. talked about how Python has become his favorite programming language. It did give a good idea about Python but was not complete. After a lot of rewrites. A little warning though. . I did some research on the web and I came across an article where Eric S. Python is soon going to become your favorite programming language! History Lesson I first started with Python when I needed to write an installer for a software I had written called 'Diamond' so that I could make the installation easy. php? oldid=2278 Contributors: Geopop65. but it was unsuitable for newbies. Then. Leochingkwake.echeverria. then you can also learn Python from this book. you will be interested in the differences between Python and your favorite programming language . I installed the (then) latest Red Hat 9. I became serious about making it more useful in a book form. Waterox888. is fun to program with. Morellik. I decided that Python was the language for me. Then. Rodrigoamaral. The aim is that if all you know about computers is how to save text files.in effect 'The Perfect Anti-venom to your programming problems'. About six months after my first brush with Python. If you have previous programming experience. then you can learn Python from this book. and more importantly. If you do have previous programming experience. I settled for the documentation that came with Python. I also found out that the PyQt bindings were more mature compared to Perl-Qt. It is mainly targeted at newbies. So. I started searching for a good book on Python. 20 anonymous edits Python en:Preface Python is probably one of the few programming languages which is both simple and powerful. Swaroop. Thorns. Moises. This book aims to help you learn this wonderful language and show how to get things done quickly and painlessly . Who This Book Is For This book serves as a guide or tutorial to the Python programming language. So. Vages. I managed with it since I had previous programming experience. swaroopch. However. the famous and respected hacker. I got excited about it and suddenly got the idea of writing some stuff on Python.0 Linux and I was playing around with KWord. it was too brief and small. I couldn't find any! I did find some O'Reilly books but they were either too expensive or were more like a reference manual than a guide. This is good for both and beginners as well as experts. com/ mediawiki/ index. Raymond. criticisms and feedback from enthusiastic readers which has helped me improve this book a lot. download the latest versions of the book. or build upon this work. to copy. • For any reuse or distribution. Please write to the main author (http:/ / www. transform. . although I've taken a lot of effort to make it more palatable to others :) In the true spirit of open source.e. to adapt this book • Under the following conditions: • Attribution.0 language itself is still not finalized/released. and also send me feedback. swaroopch. • This means: • You are free to Share i. Release Often". distribute and transmit this book • You are free to Remix i. you must make clear to others the license terms of this book.e. It's a constant tussle to balance this book between a beginner's needs and the tendency towards 'completeness' of information. Since the Python 3. 0/ ) license. com/ notes/ Python and clearly indicating that the original text can be fetched from this location. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of this book). com/ notes/ Python where you can read the whole book online. buy a printed hard copy (http:/ / www. Attribution must be shown by linking back to http:/ / www. If you alter. This book is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3. you may distribute the resulting work only under the same or similar license to this one. the updated book has been released and is constantly being updated. • Share Alike. • Nothing in this license impairs or restricts the author's moral rights. swaroopch. com/ contact/ ) or the respective translators with your comments and suggestions.0 release (expected in August/September 2008). Status Of The Book Changes since the last major revision in March 2005 is updating for the Python 3. I have received lots of constructive suggestions. The book needs the help of its readers such as yourselves to point out any parts of the book which are not good. this book is constantly undergoing changes. in the spirit of the open source philosophy of "Release Early. swaroopch. License 1. • Any of the above conditions can be waived if you get permission from the copyright holder. 2. swaroopch. org/ licenses/ by-nc-sa/ 3. com/ buybook). However.Python en:Preface 13 This book started out as my personal notes on Python and I still consider it in the same way. Official Website The official website of the book is http:/ / Unported (http:/ / creativecommons. It would be helpful if readers also gave feedback on how much depth this book should go into. not comprehensible or are simply wrong. org/ licenses/ bsd-license. or simply needs improvement. Swaroop. then please do inform me. W. opensource. However. please consider purchasing a printed copy (http:/ / www. php) unless otherwise noted. php? oldid=987 Contributors: Gasolin. so that I can make suitable improvements. 4.C. com/ mediawiki/ index. -. R. swaroopch. Volunteer contributions to this original book must be under this same license and the copyright must be assigned to the main author of this book. if you find some material to be inconsistent or incorrect. swaroopch. the other is to make it so complicated that there are no obvious deficiencies.C. Wendte Previous Next Source: http:/ / www. com/ buybook) or making a donation. 2 anonymous edits . Buy the Book If you wish to support the continued development of this book. A. You can reach me via my user page. All the code/scripts provided in this book is licensed under the 3-clause BSD License (http:/ / www. Something To Think About There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies. -. Feedback I have put in a lot of effort to make this book as interesting and as accurate as possible.Python en:Preface 14 3. Hoare Success in life is a matter not so much of talent and opportunity as of concentration and perseverance. make it an ideal language for scripting and rapid application development in many areas on most platforms. High-level Language When you write programs in Python. It allows you to concentrate on the solution to the problem rather than the language itself. make changes to it.e. and use pieces of it in new free programs. The official introduction to Python is: Python is an easy to learn. etc. Features of Python Simple Python is a simple and minimalistic language. He doesn't particularly like snakes that kill animals for food by winding their long bodies around them and crushing them. Easy to Learn As you will see. you can freely distribute copies of this software. Python's elegant syntax and dynamic typing. FLOSS is based on the concept of a community which shares knowledge. named the language after the BBC show "Monty Python's Flying Circus". read its source code. you never need to bother about the low-level details such as managing the memory used by your program. This is one of the reasons why Python is so good . All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any . Free and Open Source Python is an example of a FLOSS (Free/Libré and Open Source Software). changed to make it work on) many platforms. the creator of the Python language. although very strict English! This pseudo-code nature of Python is one of its greatest strengths. Portable Due to its open-source nature. as already mentioned. together with its interpreted nature. In simple terms. Python is extremely easy to get started with. Reading a good Python program feels almost like reading English.Python en:Introduction 15 Python en:Introduction Introduction Python is one of those rare languages which can claim to be both simple and powerful.it has been created and is constantly improved by a community who just want to see a better Python. I will discuss most of these features in more detail in the next section. Python has been ported to (i. Python has an extraordinarily simple syntax. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Note Guido van Rossum. You will find that you will be pleasantly surprised on how easy it is to concentrate on the solution to the problem rather than the syntax and structure of the language you are programming in. powerful programming language. the program is built around objects which combine data and functionality. AROS. QNX. twistedmatrix. Extensible If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open. z/OS. Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. Windows. all this is always available wherever Python is installed. Remember.Python en:Introduction 16 system-dependent features. Acorn RISC OS. the standard library. etc. You can use Python on Linux. you can code that part of your program in C or C++ and then use it from your Python program. FTP. com/ products/ twisted). Palm OS. GUI (graphical user interfaces). Internally. web browsers. OS/2. This also makes your Python programs much more portable. since you can just copy your Python program onto another computer and it just works! Object Oriented Python supports procedure-oriented programming as well as object-oriented programming. com/ products/ pil/ index. Amiga. Sharp Zaurus. All this. CGI. You just run the program directly from the source code. Extensive Libraries The Python Standard Library is huge indeed. unit testing. Psion. Tk. etc. VMS. actually. VxWorks. does not need compilation to binary. In object-oriented languages. This is called the 'Batteries Included' philosophy of Python. Python Imaging Library (http:/ / www. AS/400. Python has a very powerful but simplistic way of doing OOP. When you run the program. wxpython. and other system-dependent stuff. email. XML. PlayStation. cryptography. the program is built around procedures or functions which are nothing but reusable pieces of programs. 0s and 1s) using a compiler with various flags and options. there are various other high-quality libraries such as wxPython (http:/ / www. In procedure-oriented languages. org) . Solaris. especially when compared to big languages like C++ or Java. OS/390. Windows CE and even PocketPC ! Interpreted This requires a bit of explanation. Python. threading. FreeBSD. makes using Python much easier since you don't have to worry about compiling the program. HTML. htm) and many more.e. It can help you do various things involving regular expressions. documentation generation. A program written in a compiled language like C or C++ is converted from the source language i. pythonware. XML-RPC. BeOS. on the other hand. WAV files. Macintosh. C or C++ into a language that is spoken by your computer (binary code i. Besides. Embeddable You can embed Python within your C/C++ programs to give 'scripting' capabilities for your program's users.e. the linker/loader software copies the program from hard disk to memory and starts running it. Twisted (http:/ / www. making sure that the proper libraries are linked and loaded. . databases. Why not Ruby? If you didn't know already. php?sid=3882).Python en:Introduction 17 Python is indeed an exciting and powerful language. I am not as lucky. Sadly. python. If you already like and use Ruby. Raymond is the author of "The Cathedral and the Bazaar" and is also the person who coined the term Open Source. The only and very significant advantage that I feel Perl has.the Comprehensive Perl Archive Network. One of the reasons that Perl has more libraries than Python is that it has been around for a much longer time than Python. they quickly become unwieldy once you start writing bigger programs and I am speaking this out of my experience writing large Perl programs at Yahoo! When compared to Perl. clearer. It has the right combination of performance and features that make writing programs in Python both fun and easy. that it feels like it is one big (but one hell of a) hack. As the name suggests. I personally found it hard to grok the Ruby language.you can do virtually anything you can do with a computer using these modules. I do admire Perl and I do use it on a daily basis for various things but whenever I write a program. then I would definitely recommend you to continue using it. com/ article. the upcoming Perl 6 does not seem to be making any improvements regarding this. Why not Perl? If you didn't know already. What Programmers Say You may find it interesting to read what great hackers like ESR have to say about Python: • Eric S. is its huge CPAN (http:/ / cpan. He says that Python is perhaps the only language that focuses on making things easier for the . If you have ever tried writing a large program in Perl. Perl programs are easy when they are small and it excels at small hacks and scripts to 'get work done'. they all praise the beauty of the language. then I would recommend Python. Unfortunately. Perl is another extremely popular open source interpreted programming language. I always start thinking in terms of Python because it has become so natural for me. This article was the real inspiration for my first brush with Python. but for people who understand Ruby. Perl has undergone so many hacks and changes. He says that Python has become his favorite programming language (http:/ / www. Ruby is another popular open source interpreted programming language. purely from an ease-of-learning perspective. • Bruce Eckel is the author of the famous Thinking in Java and Thinking in C++ books. easier to write and hence more understandable and maintainable. However. perl. For other people who have not used it and are trying to judge whether to learn Python or to learn Ruby. this is a humongous collection of Perl modules and it is simply mind-boggling because of its sheer size and depth . org) library . you would have answered this question yourself! In other words. However this seems to be changing with the growing Python Package Index (http:/ / pypi. Python programs are definitely simpler. He says that no language has made him more productive than Python. linuxjournal. org/ pypi). com/ weblogs/ viewpost. artima. org/ dev/ 3. 0. Swaroop.0 is the new version of the language. python.0 Plans (http:/ / www. html) • Python 2. Read the complete interview (http:/ / www. com/ jobs/ index. then there is a utility to assist you to convert 2. 2 anonymous edits . python. python. python. 0/ library/ 2to3. About Python 3. swaroopch. org/ dev/ peps/ pep-3000/ ) • Miscellaneous Python 3.x source (http:/ / docs. python. He says that Python has always been an integral part of Google. html) for more details.0) • What's New in Python 3.x to 3. python. txt) Previous Next Source: http:/ / www. The main reason for a major new version of Python is to remove all the small problems and nitpicks that have accumulated over the years and to make the language even more clean. org/ download/ releases/ 3. org/ dev/ whatsnew/ 2. 0/ whatsnew/ 3. google. 6. com/ intv/ aboutme. 0/ NEWS. If you already have a lot of Python 2.6 and 3. html). • Peter Norvig is a well-known Lisp author and Director of Search Quality at Google (thanks to Guido van Rossum for pointing that out). org/ dev/ peps/ pep-0361/ ) • Python 3000 (the official authoritative list of proposed changes) (http:/ / versions and most likely will be included in Python 3. jsp?thread=208549) • What's New in Python 2. More details are at: • Guido van Rossum's introduction (http:/ / www. python. org/ dev/ 3. You can actually verify this statement by looking at the Google Jobs (http:/ / www. html) (features significantly different from previous Python 2. php? oldid=1789 Contributors: JeremyBicha. org/ dev/ peps/ pep-3100/ ) • Python News (detailed list of changes) (http:/ / en:Introduction 18 programmer. com/ mediawiki/ index.6 (http:/ / docs. html) page which lists Python knowledge as a requirement for software engineers. artima.0 Python 3.0 Release Schedule (http:/ / www. It is sometimes referred to as Python 3000 or Py3K.0 (http:/ / docs.x code. Fedora. If you see some version information like the one shown above. you can download the binaries from somewhere else and then copy to your PC and install it. $ python -V Python 3. pkg_add in FreeBSD. • [This option will be available after the final release of Python 3. OpenSUSE or {put your choice here}. To test if you have Python already installed on your Linux box. etc. Alternatively. In this case. open a shell program (like konsole or gnome-terminal) and enter the command python -V as shown below. hence I will indicate the prompt by just the $ symbol.x already installed. However.Python en:Installation 19 Python en:Installation If you have Python 2. . Note that you will need an internet connection to use this method.0.0b1 Note $ is the prompt of the shell. For Linux and BSD users If you are using a Linux distribution such as Ubuntu. if you get a message like this one: $ python -V bash: Python: command not found Then you don't have Python installed. The compilation instructions are provided at the website. then it is most likely you already have Python installed on your system. org/ download/ releases/ 3. then try python3 -V. you have two ways of installing Python on your system. such as apt-get in Ubuntu/Debian and other Debian-based Linux. then you have Python installed already.0] Install the binary packages using the package management software that comes with your OS. It will be different for you depending on the settings of your OS. 0/ ) and install it. or a BSD system such as FreeBSD. You can have both installed at the same time. Note If you have Python 2. python. This is highly unlikely but possible. you do not have to remove it to install Python 3.x installed already. yum in Fedora Linux. • You can compile Python from the source code (http:/ / www. BAT : 'PATH=%PATH%. . org/ ftp/ python/ 3. then you need to set the PATH variable appropriately. click on Control Panel -> System -> Advanced -> Environment Variables. org/ download/ releases/ 3. Summary For a Linux system. Click on the variable named PATH in the 'System Variables' section. especially IDLE.NT file. we will write our first Python program.Python en:Installation 20 For Windows Users Visit http:/ / www. add the following line to the file C:\AUTOEXEC. 0/ python-3.8 MB which is very compact compared to most other languages or software. Of course. python. For Mac OS X Users Mac OS X Users will find Python already installed on their system. Of course. installing Python is as easy as downloading the installer and double-clicking on it. Next. 2003 . then select Edit and add . we will assume that you have Python installed on your system. For Windows 2000. For older versions of Windows. Open the Terminal. For Windows NT.app and run python -V and follow the advice in the above Linux section. Caution When you are given the option of unchecking any "optional" components. 0/ and download the latest version from this website.e.0 beta 1 (http:/ / www. which was 3.C:\Python30' (without the quotes) and restart the system. DOS Prompt If you want to be able to use Python from the Windows command line i. python. 0b1. From now on. For a Windows system. use the AUTOEXEC.C:\Python30 to the end of what is already there. The installation is just like any other Windows-based software. you can install it using the package management software that comes with your distribution. msi) as of this writing. the DOS prompt. An interesting fact is that majority of Python downloads are by Windows users. This is just 12. you most probably already have Python installed on your system. use the appropriate directory name. this doesn't give the complete picture since almost all Linux users will have Python installed already on their systems by default. don't uncheck any! Some of these components can be useful for you. XP. Otherwise. we need an editor to write the source files. We will now see how to use both of these methods Using The Interpreter Prompt Start the interpreter on the command line by entering python at the shell prompt. 1 anonymous edits Python en:First Steps Introduction We will now see how to run a traditional 'Hello World' program in Python.0b2 (r30b2:65106. This will teach you how to write. There are two ways of using Python to run your program . press ctrl-z followed by enter key. we are supplying the text Hello World and this is promptly printed to the screen. swaroopch. Jul 18 2008.Python en:Installation 21 Previous Next Source: http:/ / www. You should see the words Hello World as output. How to Quit the Interpreter Prompt To exit the prompt.1500 32 bit (Intel)] on win32 Type "help". "credits" or "license" for more information. .0 → IDLE (Python GUI). If you are using IDLE.using the interactive interpreter prompt or using a source file. Here. save and run Python programs. Now enter print('Hello World') followed by the Enter key. making your journey more comfortable and helps you reach your destination (achieve your goal) in a much faster and safer way. php? oldid=1746 Contributors: Swaroop. com/ mediawiki/ index. The choice of an editor is crucial indeed. $ python Python 3. press ctrl-d if you are using IDLE or are using a Linux/BSD shell. "copyright". For Windows users. >>> print('Hello World') Hello World >>> Notice that Python gives you the output of the line immediately! What you just entered is a single Python statement. A good editor will help you write Python programs easily. you can run the interpreter in the command line if you have set the PATH variable appropriately. 18:44:17) [MSC v. We use print to (unsurprisingly) print any value that you supply to it. You have to choose an editor as you would choose a car you would buy. Choosing An Editor Before we move on to writing Python programs in source files. In case of the Windows command prompt. click on Start → Programs → Python 3. It has a graphical user interface and has buttons to compile and run your python program without a fuss. I personally use Vim for most of my programs. these are two of the most powerful editors and you will be benefitted by using them to write your Python programs. I repeat once again. If you are using Windows. sontek.Python en:First Steps 22 One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colorized so that you can see your program and visualize its running.it can make writing Python programs more fun and easy. IDEs can be very useful indeed. It is also available for installation for Linux (http:/ / love-python. we will use IDLE. enigmacurry. blogspot. python. We will explore how to use IDLE in the next section. A special note: Do not use Notepad . If you are a beginner programmer. If you are an experienced programmer. In case you are willing to take the time to learn Vim or Emacs. python. then you have a lot of choices for an editor.it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. please choose a proper editor . our IDE and editor of choice. If you still want to explore other choices of an editor. then you must be already using Vim or Emacs. com/ 2008/ 05/ 09/ emacs-as-a-powerful-python-ide/ ). please refer the IDLE documentation (http:/ / www. . com/ 2008/ 03/ install-idle-in-linux. IDLE does syntax highlighting and a lot more such as allowing you to run your programs within IDLE among other things. you might want to use geany. html) and BSDs in their respective repositories. Once you start writing large Python programs. Needless to say. then I suggest that you use IDLE. html). org/ cgi-bin/ moinmoin/ PythonEditors) and make your choice. For further details. Good editors such as IDLE (and also VIM) will automatically help you do this. python. For Vim users There is a good introduction on how to make Vim a powerful Python IDE by John M Anderson (http:/ / blog. For Emacs users There is a good introduction on how to make Emacs a powerful Python IDE by Ryan McGuire (http:/ / www. IDLE is installed by default with the Windows and Mac OS X Python installers. then you can use Kate which is one of my favorites. If you are just beginning to program. see the comprehensive list of Python editors (http:/ / www. You can also choose an IDE (Integrated Development Environment) for Python. See the comprehensive list of IDEs that support Python (http:/ / www. If you are using Linux/FreeBSD. then I highly recommend that you do learn to use either of them as it will be very useful for you in the long run. net/ 2008/ 05/ 11/ python-with-a-modular-ide-vim/ ). In this book. org/ idle/ doc/ idlemain. org/ cgi-bin/ moinmoin/ IntegratedDevelopmentEnvironments) for more details. Note that you can always run the program on any platform by specifying the interpreter directly on the command line such as the command python helloworld.py If you are using IDLE.py. Then click on File → Save. click on File → New Window and enter the following program. that person can be yourself after six months! The comments are followed by a Python statement. How It Works Let us consider the first two lines of the program. We will learn about functions in a → later chapter. use the menu Run → Run Module or the keyboard shortcut F5. please type the above program exactly as shown and above and run the program again. print is not the same as Print . ensure there are no spaces or tabs before the first character in each line . enter the following program and save it as helloworld. These are called comments . what .note the lowercase p in the former and the uppercase P in the latter.py Hello World If you got the output as shown above. As Simon Cozens [1] puts it.this is useful for readers of your program so that they can easily understand what the program is doing.whenever the first two characters of the source file are #! followed by the location of a program. #!/usr/bin/python #Filename: helloworld.you have successfully run your first Python program. The output is as shown below. Python does not use comments except for the special case of the first line here.py print('Hello World') Run this program by opening a shell (Linux terminal or DOS prompt) and entering the command python helloworld. $ python helloworld. Important Use comments sensibly in your program to explain some important details of your program .py . it is the 'traditional incantation to the programming gods to help you learn the language better' :) .e.Python en:First Steps 23 Using A Source File Now let's get back to programming. In case you got an error. this tells your Linux/Unix system that this program should be run with this interpreter when you execute the program. Here we call the print function this just prints the text 'Hello World'.all it does is just say 'Hello World' when you run it. This is explained in detail in the next section. Start your choice of editor. the first program that you write and run is the 'Hello World' program . There is a tradition that whenever you learn a new programming language. congratulations! . If you are using IDLE.anything to the right of the # symbol is a comment and is mainly useful as notes for the reader of the program. Remember. It is called the shebang line . Note that Python is case-sensitive i.we will see why this is important later. Also. To make things more fun. We use the . Whenever you run any program. There will usually be a similar directory for your username on your system. we have been able to run our program as long as we know the exact path. So far. We see that /home/swaroop/bin is one of the directories in the PATH variable where swaroop is the username I am using in my system. Then. We can make this program available everywhere by simply copying this source file to one of the directories listed in PATH./ to indicate that the program is located in the current directory. It is like creating your own commands just like cd or any . you can add a directory of your choice to the PATH variable . Just change the first line of the program to the following: #!/usr/bin/env python The env program will in turn look for the Python interpreter which will run the program. you can use the special env program on Linux/Unix systems. $ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin $ cp helloworld.py $ . the system looks for that program in each of the directories listed in the PATH environment variable and then runs that program.Python en:First Steps 24 you should understand now is that whatever you supply in the parentheses will be printed back to the screen./helloworld and it will still work since the system knows that it has to run the program using the interpreter whose location is specified in the first line in the source file. What if you don't know where Python is located? Then. you can rename the file to just helloworld and run it as ./helloworld. Alternatively.py Hello World The chmod command is used here to change the mode of the file by giving execute permission to all users of the system. anywhere. $ chmod a+x helloworld. we supply 'Hello World' which is referred to as a string - don't worry. Executable Python Programs This applies only to Linux/Unix users but Windows users might be curious as well about the first line of the program. What if we wanted to be able to run the program from anywhere? You can do this by storing the program in one of the directories listed in the PATH environment variable. First.py /home/swaroop/bin/helloworld $ helloworld Hello World We can display the PATH variable using the echo command and prefixing the variable name by $ to indicate to the shell that we need the value of this variable. we will explore these terminologies in detail later. In this case. we have to give the program executable permission using the chmod command then run the source program. we execute the program directly by specifying the location of the source file. a program or a script or software all mean the same thing. save and run Python programs at ease. then you can use the built-in help functionality.r. you can obtain information about almost anything in Python. run help(print) . Getting Help If you need quick information about any function or statement in Python. Use help() to learn more about using help itself! In case you need to get help for operators like return.t. Summary You should now be able to write. let's learn some more Python concepts.Python en:First Steps 25 other commands that you use in the Linux terminal or DOS prompt. For example. References: [1] The author of the amazing 'Beginning Perl' book → Previous → Next Source: http:/ / displays the help for the print function which is used to print things to the screen. Python. Caution W. com/ mediawiki/ index. then you need to put those inside quotes such as help('return') so that Python doesn't get confused on what we're trying to do. 9 anonymous edits . swaroopch. This is very useful especially when using the interpreter prompt. Note Press q to exit the help. php? oldid=2332 Contributors: Swaroop. Similarly. Now that you are a Python user. org/ faq/ basic_q. 9. Numbers Numbers in Python are of three types . .you want to take some input. unicode.4.3 * 10-4. html#16). In this case. which means almost any language in the world (http:/ /("ascii"). 52.integers.23 and 52. please see the related discussion at StackOverflow (http:/ / stackoverflow.6j) Note for Experienced Programmers There is no separate 'long int' type. all these are referred to as literal constants. all strings are in Unicode.Python en:Basics 26 Python en:Basics Just printing 'Hello World' is not enough.it is a constant because its value cannot be changed. Literal Constants An example of a literal constant is a number like 5. The E notation indicates powers of 10. floating point and complex numbers. manipulate it and get something out of it. The default integer type can be any large value. • Examples of complex numbers are (-5+4j) and (2. then use str.23. Hence. 1.3 . Strings A string is a sequence of characters. • Examples of floating point numbers (or floats for short) are 3.25e-3 or a string like 'This is a string' or "It's a string!". com/ questions/ 175240/ how-do-i-convert-a-files-format-from-unicode-to-ascii-using-python#175270). Strings are basically just a bunch of words. The number 2 always represents itself and nothing else . is it? You want to do more than that . We can achieve this in Python using constants and variables.3E-4. The words can be in English or any other language that is supported in the Unicode standard.you use its value literally. By default. It is called a literal because it is literal . • An examples of an integer is 2 which is just a whole number.3E-4 means 52. For more details. so pay attention to the following part on how to use strings in Python. If a strictly ASCII-encoded byte-stream is needed. I can almost guarantee that you will be using strings in almost every Python program that you write. Note for Experienced Programmers There are no "ASCII-only" strings because Unicode is a superset of ASCII. " I asked. You specify the single quote as \' . using double quotes. "What's your name?. This is the second sentence. . you have to indicate the backslash itself using the escape sequence \\. spaces and tabs are preserved as-is.e.". What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown previously or you can use an escape sequence for the newline character . So. An example is "What's your name?" Triple Quotes You can specify multi-line strings using triple quotes . You can use single quotes and double quotes freely within the triple quotes. For example: "This is the first sentence.\n to indicate the start of a new line.\t." is equivalent to "This is the first sentence. Double Quotes Strings in double quotes work exactly the same way as strings in single quotes. An example is: '''This is a multi-line string. This is the first line. Now. All white space i. you can specify the string as 'What\'s your name?'. a single backslash at the end of the line indicates that the string is continued in the next line. you will have to specify that this single quote does not indicate the end of the string. Another useful escape sequence to know is the tab . He said "Bond.(""" or '''). Also. This can be done with the help of what is called an escape sequence.notice the backslash. how will you specify this string? For example. Similarly." ''' Escape Sequences Suppose. Another way of specifying this specific string would be "What's your name?" i. An example is This is the first line\nThis is the second line. There are many more escape sequences but I have mentioned only the most useful ones here. but no newline is added.\ This is the second sentence. James Bond. you have to use an escape sequence for using a double quote itself in a double quoted string.e.Python en:Basics 27 Single Quotes You can specify strings using single quotes such as 'Quote me on this'. You cannot specify 'What's your name?' because Python will be confused as to where the string starts and ends. you want to have a string which contains a single quote ('). the string is What's your name?. This is the second line. One thing to note is that in a string. For example. they are automatically concatenated by Python. you cannot change it. the format method can be called to substitute those specifications with corresponding arguments to the format method.py age = 25 name = 'Swaroop' print('{0} is {1} years old'. age)) print('Why is {0} playing with that python?'. Note for Regular Expression Users Always use raw strings when dealing with regular expressions.py Swaroop is 25 years old Why is Swaroop playing with that python? How It Works: A string can use certain specifications and subsequently. Otherwise. We will see why this is not a limitation in the various programs that we see later on. The format Method Sometimes we may want to construct strings from other information.they do not differ in any way. There is no real need for it and I am sure you won't miss it. backreferences can be referred to as '\\1' or r'\1'. This is where the format() method is useful. it really isn't.Python en:Basics 28 Raw Strings If you need to specify some strings where no special processing such as escape sequences are handled. Although this might seem like a bad thing.format(name. Note for C/C++ Programmers There is no separate char data type in Python. . String Literal Concatenation If you place two string literals side by side. An example is r"Newlines are indicated by \n". then what you need is to specify a raw string by prefixing r or R to the string. Note for Perl/PHP Programmers Remember that single-quoted strings and double-quoted strings are the same .format(name)) Output: $ python str_format. For example. #!/usr/bin/python # Filename: str_format. a lot of backwhacking may be required. Strings Are Immutable This means that once you have created a string. 'What\'s ' 'your name?' is automatically converted in to "What's your name?". What Python does in the format method is that it substitutes each argument value into the place of the specification. when using the format method. • Examples of valid identifier names are i.format(>> '{name} wrote {book}'. underscores ('_') or digits (0-9). There are some rules you have to follow for naming identifiers: • The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore ('_'). python.. we can change the message without having to deal with the variables used and vice-versa. __my_name. Notice that we could achieved the same using string concatenation: name + ' is ' + str(age) + ' years old' but notice how much uglier and error-prone this is.333' >>> '{0:_^11}'. the second specification is {1} corresponding to age which is the second argument to the format method.e.format(1/3) # decimal (. Variables are just parts of your computer's memory where you store some information. Similarly. name_23. .3}'. we say 'the object'.Python en:Basics 30 Data Types Variables can hold values of different types called data types. Python refers to anything used in a program as an object. This line is called a statement because it states that . Objects Remember. I follow the convention of having all Python programs saved with the extension . 1. How to write Python programs Henceforth. Save it as a file with the filename mentioned in the comment. First. we will see how to create our own types using classes. We will now see how to use variables along with literal constants.py. Note for Object Oriented Programming users Python is strongly object-oriented in the sense that everything is an object including numbers. we assign the literal constant value 5 to the variable i using the assignment operator (=). the standard procedure to save and run a Python program is as follows: 1.py 5 6 This is a multi-line string. Enter the program code given in the example. 1. strings and functions. Open your favorite editor.''' print(s) Output: $ python var. This is the second line. This is the second line.py i = 5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. Example: Using Variables And Literal Constants # Filename : var. Save the following example and run the program. How It Works: Here's how this program works. In later chapters. 1. Instead of saying 'the something'. This is meant in the generic sense. Run the interpreter with the command python program. You can also use the executable method as explained earlier. The basic types are numbers and strings.py or use IDLE to run the programs. which we have already discussed. Note for static language programmers Variables are used by just assigning them a value. Next. unsurprisingly. and the same can be written as i = 5.Python en:Basics 31 something should be done and in this case. we print the value of i using the print statement which.) which indicates the end of a logical line/statement. I have never used or even seen a semicolon in a Python program. In fact. Then we add 1 to the value stored in i and store it back. Logical And Physical Lines A physical line is what you see when you write the program. then you have to explicitly specify this using a semicolon (. An example of writing a logical line spanning many physical lines follows. s = 'This is a string. For example. The idea is to avoid the semicolon as much as possible since it leads to more readable code. Python implicitly assumes that each physical line corresponds to a logical line. This is referred to as explicit line joining. \ This continues the string.if this was on a line by itself (as you see it in an editor). i = 5 print(i) is effectively same as i = 5. print(i) However. we get the value 6. or even i = 5. print(i). An example of a logical line is a statement like print('Hello World') . we assign the literal string to the variable s and then print it. If you want to specify more than one logical line on a single physical line. Use more than one physical line for a single logical line only if the logical line is really long. No declaration or data type definition is needed/used. just prints the value of the variable to the screen. then this also corresponds to a physical line. print(i). We then print it and expectedly. Python encourages the use of a single statement per line which makes code more readable.' print(s) . I strongly recommend that you stick to writing a single logical line in a single physical line only. Implicitly. Similarly. A logical line is what Python sees as a single statement. we connect the variable name i to the value 5. square brackets or curly braces. print\ (i) is the same as print(i) Sometimes. line 4 print('Value is '. This is called indentation. i) # Error! Notice a single space at the start of the line ^ IndentationError: unexpected indent Notice that there is a single space at the beginning of the second line. This means that statements which go together must have the same indentation. Cases where you can use new blocks will be detailed in later chapters such as the control flow chapter. Indentation Whitespace is important in Python. Actually. there is an implicit assumption where you don't need to use a backslash. I strongly recommend that you use a single tab or four . The error indicated by Python tells us that the syntax of the program is invalid i. Similarly. You can see this in action when we write programs using lists in later chapters. This continues the string. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line. For example: i = 5 print('Value is '.py". of course). How to indent Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. This is is called implicit line joining. One thing you should remember is that wrong indentation can give rise to errors. This is the case where the logical line uses parentheses.e. i) # Error! Notice a single space at the start of the line print('I repeat. you get the following error: File "whitespace.Python en:Basics 32 This gives the output: This is a string. whitespace at the beginning of the line is important. the value is '. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along. We will see examples of how blocks are important in later chapters. which in turn is used to determine the grouping of statements. i) When you run this. Each such set of statements is called a block. Be sure to become comfortable with what you have read in this chapter.Python en:Basics 33 spaces for each indentation level. A simple example of an expression is 2 + 3. 10 anonymous edits Python en:Operators and Expressions Introduction Most statements (logical lines) that you write will contain expressions. Choose either of these two indentation styles. In this case. Vages. we can move on to more interesting stuff such as control flow statements. swaroopch. 50 . Operators We will briefly take a look at the operators and their usage: Note that you can evaluate the expressions given in the examples using the interpreter interactively.e. Run from __future__ import braces to learn more. Note to static language programmers Python will always use indentation for blocks and will never use braces. 2 and 3 are the operands. Previous Next Source: http:/ / www. For example. An expression can be broken down into operators and operands.2 gives a negative number. 'a' + 'b' gives 'ab'. Operators require some data to operate on and such data is called operands. com/ mediawiki/ index. More importantly. Minus Either gives a negative -5. use that indentation style only. . Summary Now that we have gone through many nitty-gritty details. to test the expression 2 + 3. Operators are functionality that do something and can be represented by symbols such as + or by special keywords. choose one and use it consistently i. use the interactive Python interpreter prompt: >>> 2 + 3 5 >>> 3 * 5 15 >>> Operator Name Explanation Examples + Plus Adds the two objects 3 + 5 gives 8. php? oldid=2376 Contributors: Swaroop.24 gives 26. number or gives the subtraction of one number from the other . // Floor Division Returns the floor of the 4 // 3 gives 1. Otherwise.e. two numbers or returns the string repeated that many times. invert -(x+1) < Less Than Returns whether x is less than 5 < 3 gives False and 3 < 5 gives True. x == y returns True. | Bit-wise OR Bitwise OR of the numbers 5 | 3 gives 7 ^ Bit-wise XOR Bitwise XOR of the numbers 5 ^ 3 gives 6 ~ Bit-wise The bit-wise inversion of x is ~5 gives -6. Left to the left by the number of shifting by 2 bits gives 1000 which represents the bits specified. This is called short-circuit evaluation. 'la' * 3 gives 'lalala'. Python will not evaluate evaluation of y y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. y = 6. -25. x != y returns True. x == y returns True. and Boolean AND x and y returns False if x is x = False. ** Power Returns x to the power of y 3 ** 4 gives 81 (i. or Equal To than or equal to y == Equal To Compares if the objects are x = 2. y = 'str'. represented in memory by bits or binary digits i. the decimal 5.e. quotient % Modulo Returns the remainder of the 8 % 3 gives 2. x is False. <= Less Than or Returns whether x is less than x = 3.25 gives 1. != Not Equal To Compares if the objects are x = 2. x = 'str'. it always returns False.Python en:Operators and Expressions 34 * Multiply Gives the multiplication of the 2 * 3 gives 6. y = 2. 11 is represented in bits by 1011 to the right by the number of which when right shifted by 1 bit gives 101 which is bits specified. Note gives True. y = 'stR'. 3 * 3 * 3 * 3) / Divide Divide x by y 4 / 3 gives 1. it returns True. division << Left Shift Shifts the bits of the number 2 << 2 gives 8. the capitalization of these names. y. Equal To or equal to y >= Greater Than Returns whether x is greater x = 4. y = 3. 2 is represented by 10 in bits. All comparison operators Comparisons can be chained arbitrarily: 3 < 5 < 7 return True or False. it returns False. x >= 3 returns True. In this case. > Greater Than Returns whether x is greater 5 > 3 returns True.3333333333333333. If x = True. y = 3. (Each number is decimal 8. than y they are first converted to a common type. not x returns False. not equal not Boolean NOT If x is True. If both operands are numbers.5 % 2. equal x = 'str'. x == y returns False. 0 and 1) >> Right Shift Shifts the bits of the number 11 >> 1 gives 5. else it returns since x is False. x and y returns False False. . & Bitwise AND Bitwise AND of the numbers 5 & 3 gives 1. y = True. x <= y returns True.5. python. This means that in a given expression. Floor Division and Remainder +x. a = a * 3 as: a = 2. from the lowest precedence (least binding) to the highest precedence (most binding). Operator Description lambda Lambda Expression or Boolean OR and Boolean AND not x Boolean NOT in. y = False. Negative . 0/ reference/ expressions. >. Evaluation Order If you had an expression such as 2 + 3 * 4. The following table. This means that the multiplication operator has higher precedence than the addition operator. taken from the Python reference manual (http:/ / docs. not in Membership tests is. /. is not Identity tests <. See Changing the Order of Evaluation below for details. == Comparisons | Bitwise OR ^ Bitwise XOR & Bitwise AND <<. is provided for the sake of completeness. !=. x or y returns True. it returns True. This makes the program more readable.Python en:Operators and Expressions 35 or Boolean OR If x is True. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. -x Positive. <=. hence there is a shortcut for such expressions: You can write: a = 2. else it returns evaluation of y Short-circuit evaluation applies here as well. Division. The following table gives the precedence table for Python. //. >=. Python will first evaluate the operators and expressions lower in the table before the ones listed higher in the table. % Multiplication. Addition and subtraction *. . org/ dev/ 3. x = True. Shortcut for math operation and assignment It is common to run a math operation on a variable and then assign the result of the operation back to the variable. a *= 3 Notice that var = var operation expression becomes var operation= expression. html#evaluation-order). is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. >> Shifts +. operators with same precedence are evaluated in a left to right manner..) Binding or tuple display [expressions. the parentheses should be used reasonably (do not overdo it) and should not be redundant (as in 2 + (3 + 4)). As with everything else.it helps us to change the order of evaluation. 2 * (length + breadth)) Output: . a = b = c is treated as a = (b = c).] List display {key:datum. For example. There is an additional advantage to using parentheses .Python en:Operators and Expressions 36 ~x Bitwise NOT ** Exponentiation x.py length = 5 breadth = 2 area = length * breadth print('Area is'. For example...have the same precedence. .. Associativity Operators are usually associated from left to right i. For example. then you can write something like (2 + 3) * 4. For example. ..) Function call (expressions.} Dictionary display The operators which we have not already come across will be explained in later chapters.. . 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences.e.e. we can use parentheses. Operators with the same precedence are listed in the same row in the above table. + and . Expressions Example: #!/usr/bin/python # Filename: expression. if you want addition to be evaluated before multiplication in an expression.. Changing the Order Of Evaluation To make the expressions more readable. 2 + 3 + 4 is evaluated as (2 + 3) + 4.. area) print('Perimeter is'.attribute Attribute reference x[index] Subscription x[index1:index2] Slicing f(arguments . Some operators like assignment operators have right to left associativity i. we will see how to make use of these in our programs using statements. notice how Python 'pretty-prints' the output. swaroopch.Python en:Operators and Expressions 37 $ python expression. Even though we have not specified a space between 'Area is' and the variable area. com/ mediawiki/ index. we directly use the value of the expression 2 * (length + breadth) in the print function. operands and expressions . Python puts it for us so that we get a clean nice output and the program is much more readable this way (since we don't need to worry about spacing in the strings we use for output). 4 anonymous edits . Previous Next Source: http:/ / www. Summary We have seen how to use operators.these are the basic building blocks of any program. Next.py Area is 10 Perimeter is 14 How It Works: The length and breadth of the rectangle are stored in variables by the same name. We store the result of the expression length * breadth in the variable area and then print it using the print function. php? oldid=1579 Contributors: Swaroop. In the second case. This is an example of how Python makes life easy for the programmer. We use these to calculate the area and perimeter of the rectangle with the help of expressions. Also. there has always been a series of statements and Python faithfully executes them in the same order. it is a little lower than that') # you must have guess > number to reach here print('Done') # This last statement is always executed. this is achieved using control flow statements. The else clause is optional... it is a little lower than that Done $ python if. after the if statement is executed Output: $ python if. Example: #!/usr/bin/python # Filename: if. else: print('No. it is a little higher than that') # Another block # You can do whatever you want in a block . you guessed it.py Enter an integer : 22 .Python en:Control Flow 38 Python en:Control Flow Introduction In the programs we have seen till now. There are three control flow statements in Python .if.py Enter an integer : 50 No.py number = 23 guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations. else we process another block of statements (called the else-block). The if statement The if statement is used to check a condition and if the condition is true. for and while..') # New block starts here print('(but you do not win any prizes!)') # New block ends here elif guess < number: print('No. we run a block of statements (called the if-block). We set the variable number to any integer we want. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds) and requires you to become . Python sees the ends of the program and simply finishes up. We'll read more about them in the next chapter. Functions are just reusable pieces of programs. Once we enter something and press enter key. Are you? Notice how the if statement contains a colon at the end . Although this is a very simple program. we take the user's guess using the input() function. we compare the guess of the user with the number we have chosen. it is true') After Python has finished executing the complete if statement along with the associated elif and else clauses.we are indicating to Python that a block of statements follows. Next.py Enter an integer : 23 Congratulations. What we have used here is the elif clause which actually combines two related if else-if else statements into one combined if-elif-else statement. Actually. This is why indentation is so important in Python. it is a little higher than that Done $ python if. say 23.. and if so. A minimal valid if statement is: if True: print('Yes. Remember that the elif and else parts are optional. as a string. we check if the guess is less than the number. In this case. we print a success message. Then. (but you do not win any prizes!) Done How It Works: In this program. Then. it is the main block where execution of the program starts and the next statement is the print('Done') statement. I have been pointing out a lot of things that you should notice even in this simple program. I hope you are sticking to the "consistent indentation" rule. We supply a string to the built-in input function which prints it to the screen and waits for input from the user. the input() function returns what we entered.Python en:Control Flow 39 No. it moves on to the next statement in the block containing the if statement. we inform the user to guess a little higher than that. If they are equal. The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with proper indentation. of course) You can have another if statement inside the if-block of an if statement and so on . you guessed it. we take guesses from the user and check if it is the number that we have. This makes the program easier and reduces the amount of indentation required. Notice that we use indentation levels to tell Python which statements belong to which block.this is called a nested if statement. After this. Done How It Works: .py number = 23 running = True while running: guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations. You can use an if.py Enter an integer : 50 No.') else: print('No. it is a little higher than that. Example: #!/usr/bin/python # Filename: while. it is a little lower than that.') running = False # this causes the while loop to stop elif guess < number: print('No..else statement to do the same thing (and in some cases..elif.Python en:Control Flow 40 aware of all these initially. but after that. Note for C/C++ Programmers There is no switch statement in Python. The while loop is over. you guessed it. it is a little higher than that.') else: print('The while loop is over. A while statement is an example of what is called a looping statement. use a dictionary to do it quickly) The while Statement The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement can have an optional else clause. Enter an integer : 23 Congratulations.') # Do anything else you want to do here print('Done') Output: $ python while. Enter an integer : 22 No. it is a little lower than that. you guessed it. you will become comfortable with it and it'll feel 'natural' to you. First.Python en:Control Flow 41 In this program. We will see more about sequences in detail in later chapters. as we have done in the previous section. else we continue to execute the optional else-block and then continue to the next statement. Example: #!/usr/bin/python # Filename: for. For example.py 1 2 3 4 The for loop is over How It Works: In this program. After this block is executed. What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number.in statement is another looping statement which iterates over a sequence of objects i.5) . This aptly demonstrates the use of the while statement. We move the input and if statements to inside the while loop and set the variable running to True before the while loop. go through each item in a sequence. If there is an else clause for a while loop. The True and False are called Boolean types and you can consider them to be equivalent to the value 1 and 0 respectively.py for i in range(1.there is no need to repeatedly run the program for each guess. it is always executed unless you break out of the loop with a break statement. If it is true.. we execute the while-block again. 5): print(i) else: print('The for loop is over') Output: $ python for. range(1. we are printing a sequence of numbers. The for loop The for.e. We generate this sequence of numbers using the built-in range function. the condition is again checked which in this case is the running variable. What you need to know right now is that a sequence is just an ordered collection of items. we are still playing the guessing game. we check if the variable running is True and then proceed to execute the corresponding while-block.this may even be the first time that the condition is checked. but the advantage is that the user is allowed to keep guessing until he guesses correctly . Note for C/C++ Programmers Remember that you can have an else clause for the while loop. The else block is executed when the while loop condition becomes False . it does not include the second number. Note for C/C++/Java/C# Programmers The Python for loop is radically different from the C/C++ for loop. one at a time. but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters. more expressive and less error prone in Python. 2. In this case.Python en:Control Flow 42 gives the sequence [1. The for loop then iterates over this range .5 . Example: #!/usr/bin/python # Filename: break.. the for loop is simpler. 4] which is like assigning each number (or object) in the sequence to i. When included. 3. range(1. i < 5.e. C# programmers will note that the for loop in Python is similar to the foreach loop in C#. For example. i++).3]. if you want to write for (int i = 0. we just print the value in the block of statements. range takes a step count of 1. stop the execution of a looping statement.5) is equivalent to for i in [1.in loop works for any sequence. In C/C++.e.5. 2. 3. Here.for i in range(1. The break Statement The break statement is used to break out of a loop statement i. we have a list of numbers generated by the built-in range function. If we supply a third number to range. Remember that the range extends up to the second number i. and then executing the block of statements for each value of i. As you can see. it is always executed once after the for loop is over unless a break statement is encountered.py while True: s = (input('Enter something : ')) if s == 'quit': break print('Length of the string is'. Remember that the for. even if the loop condition has not become False or the sequence of items has been completely iterated over. 4]. Remember that the else part is optional.py Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 21 . An important note is that if you break out of a for or while loop.5). then in Python you write just for i in range(0. Java programmers will note that the same is similar to for (int i : IntArray) in Java 1. By default.2) gives [1. then that becomes the step count. any corresponding loop else block is not executed. len(s)) print('Done') Output: $ python break. . Example: #!/usr/bin/python # Filename: continue.py while True: s = input('Enter something : ') if s == 'quit': break if len(s) < 3: print('Too small') continue print('Input is of sufficient length') # Do other kinds of processing here. Output: $ python test. we repeatedly take the user's input and print the length of each input each time.. We are providing a special condition to stop the program by checking if the user input is 'quit'. We stop the program by breaking out of the loop and reach the end of the program. Remember that the break statement can be used with the for loop as well..Python en:Control Flow 43 Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something : use Python! Length of the string is 12 Enter something : quit Done How It Works: In this program. The length of the input string can be found out using the built-in len function.py Enter something : a Too small Enter something : 12 Too small . Summary We have seen how to use the three control flow statements . becoming comfortable with them is essential. Note that the continue statement works with the for loop as well. we use the built-in len function to get the length and if the length is less than 3. we will see how to create and use functions. we skip the rest of the statements in the block by using the continue statement. Next. So. 8 anonymous edits Python en:Functions Introduction Functions are reusable pieces of programs.Python en:Control Flow 44 Enter something : abc Input is of sufficient length Enter something : quit How It Works: In this program. swaroopch. but we process them only if they are at least 3 characters long. php? oldid=1664 Contributors: Swaroop. The function concept is probably the most important building block of any non-trivial software (in any programming language). We have already used many built-in functions such as the len and range. Otherwise. These are some of the most often used parts of Python and hence. while and for along with their associated break and continue statements. Previous Next Source: http:/ / def sayHello(): print('Hello World!') # block belonging to the function # End of function . They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. so we will explore various aspects of functions in this chapter. Functions are defined using the def keyword. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. An example will show that this is actually very simple: Example: #!/usr/bin/python # Filename: function1. This is known as calling the function.if. the rest of the statements in the loop are executed and we can do any kind of processing we want to do here. com/ mediawiki/ index. we accept input from the user. Next follows the block of statements that are part of this function. Note the terminology used . b): if a > b: print(a. 'is maximum') printMax(3. b) else: print(b. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results. Parameters are specified within the pair of parentheses in the function definition.Python en:Functions 45 sayHello() # call the function sayHello() # call the function again Output: $ python function1. Notice that we can call the same function twice which means we do not have to write the same code again. Example: #!/usr/bin/python # Filename: func_param.py Hello World! Hello World! How It Works: We define a function called sayHello using the syntax as explained above. This function takes no parameters and hence there are no variables declared in the parentheses. separated by commas.the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments. we supply the values in the same way. When we call the function. which are values you supply to the function so that the function can do something utilising those values. 'is maximum') elif a == b: print(a. y) # give variables as arguments Output: . These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs. 4) # directly give literal values x = 5 y = 7 printMax(x. 'is equal to'.py def printMax(a. Function Parameters A function can take parameters. In the first usage of printMax. We find out the greater number using a simple if. we define a function called printMax where we take two parameters called a and b. arguments. So.Python en:Functions 46 $ python func_param.else statement and then print the bigger number.. we call the function using variables.e. we assign the value 2 to x. In the last print function call. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name. In the second usage. Python uses the value of the parameter declared in the function. . Local Variables When you declare variables inside a function definition. The printMax function works the same in both the cases. x) func(x) print('x is still'. the first time that we use the value of the name x. x) x = 2 print('Changed local x to'. the x defined in the main block remains unaffected. x) Output: $ python func_local. we display the value of x in the main block and confirm that it is actually unaffected. Next. The name x is local to our function. y) causes value of argument x to be assigned to parameter a and the value of argument y assigned to parameter b. they are not related in any way to other variables with the same names used outside the function i.e.py 4 is maximum 7 is maximum How It Works: Here. we directly supply the numbers i. when we change the value of x in the function. Example: #!/usr/bin/python # Filename: func_local.py x = 50 def func(x): print('x is'. printMax(x.py x is 50 Changed local x to 2 x is still 50 How It Works: In the function. variable names are local to the function. For example. not inside any kind of scope such as functions or classes). then you have to tell Python that the name is not local. You can specify more than one global variable using the same global statement. We do this using the global statement.e. You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). x) func() print('Value of x is'. z. global x. Example: #!/usr/bin/python # Filename: func_global. Using the global statement makes it amply clear that the variable is defined in an outermost block.Python en:Functions 47 Using The global Statement If you want to assign a value to a name defined at the top level of the program (i. It is impossible to assign a value to a variable defined outside a function without the global statement.py x is 50 Changed global x to 2 Value of x is 2 How It Works: The global statement is used to declare that x is a global variable .py x = 50 def func(): global x print('x is'. x) x = 2 print('Changed global x to'. this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. However. y. when we assign a value to x inside the function. that change is reflected when we use the value of x in the main block. x) Output: $ python func_global. .hence. but it is global. More precisely.this is explained in detail in later chapters. Let's take an example: #!/usr/bin/python # Filename: func_nonlocal. We declare that we are using this x by nonlocal x and hence we get access to that variable. Default Argument Values For some functions. There is another kind of scope called "nonlocal" scope which is in-between these two types of scopes. Try changing the nonlocal x to global x and also by removing the statement itself and observe the difference in behavior in these two cases. Example: . the 'x' defined in the first line of func_outer is relatively neither in local scope nor in global scope.. x) def func_inner(): nonlocal x x = 5 func_inner() print('Changed local x to'. just remember this. Since everything in Python is just executable code. Nonlocal scopes are observed when you define functions inside functions. For now.py x is 2 Changed local x to 5 How It Works: When we are inside func_inner. the default argument value should be immutable .py def func_outer(): x = 2 print('x is'. Note that the default argument value should be a constant. x) func_outer() Output: $ python func_nonlocal. This is done with the help of default argument values. you can define functions anywhere.Python en:Functions 48 Using nonlocal statement We have seen how to access variables in the local and global scope above. we can give values to only those parameters which we want. b=5. using the function is easier since we do not need to worry about the order of the arguments. a. we supply both the string and an argument 5 stating that we want to say the string message 5 times. but def func(a=5. b=5) is valid. Example: #!/usr/bin/python # Filename: func_key. Two. c=10): print('a is'. b) is not valid. 'and b is'.one. b.py def say(message. If we don't supply a value. For example.py def func(a.e. There are two advantages . provided that the other parameters have default argument values.Python en:Functions 49 #!/usr/bin/python # Filename: func_default. then you can give values for such parameters by naming them . you cannot have a parameter with a default argument value before a parameter without a default argument value in the order of parameters declared in the function parameter list. Important Only those parameters which are at the end of the parameter list can be given default argument values i.we use the name (keyword) instead of the position (which we have been using all along) to specify the arguments to the function. c) func(3. we supply only the string and it prints the string once.py Hello WorldWorldWorldWorldWorld How It Works: The function named say is used to print a string as many times as specified. times = 1): print(message * times) say('Hello') say('World'. 5) Output: $ python func_default. In the first usage of say. then by default. def func(a. In the second usage of say. the string is printed just once. 7) . We achieve this by specifying a default argument value of 1 to the parameter times. 'and c is'. Keyword Arguments If you have some functions with many parameters and you want to specify only some of them.this is called keyword arguments . This is because the values are assigned to the parameters by position. 7). Notice. 2. this can be achieved by using the stars: #!/usr/bin/python # Filename: total. the variable a gets the value of 25 due to the position of the argument. Then. c=24) func(c=50. followed by two parameters with default argument values. 3. a=100) Output: $ python func_key. a=100).py a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 How It Works: The function named func has one parameter without default argument values. keyword arguments. *numbers. VarArgs parameters TODO Should I write about this in a later chapter since we haven't talked about lists and dictionaries yet? Sometimes you might want to define a function that can take any number of parameters. c=24). In the first usage.py def total(initial=5. In the second usage func(25. we use keyword arguments completely to specify the values. vegetables=50. func(3. that we are specifying value for parameter c before that for a even though a is defined before c in the function definition. The variable b gets the default value of 5. In the third usage func(c=50. **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print(total(10. fruits=100)) Output: $ python total. the parameter b gets the value 7 and c gets the default value of 10. 1.py 166 How It Works: . the parameter c gets the value of 24 due to naming i. the parameter a gets the value 3.Python en:Functions 50 func(25.e. Python en:Functions 51 I strongly recommend that you use docstrings for any non-trivial function that you write. swaroopch. we will see how to use as well as create Python modules. Since the Python language itself does not interpret these annotations in any way (that functionality is left to third-party libraries to interpret in any way they want). The pydoc command that comes with your Python distribution works similarly to help() using docstrings. 3107 (http:/ / www. Next. Therefore. we will skip this feature in our discussion. php? oldid=2379 Contributors: Swaroop. com/ mediawiki/ index. Previous Next Source: http:/ / www. python. please see the Python Enhancement Proposal No. 7 anonymous edits . Remember to press the q key to exit help. Automated tools can retrieve the documentation from your program in this manner. Vages. Annotations Functions have another advanced feature called annotations which are a nifty way of attaching additional information for each of the parameters as well as the return value.Python en:Functions 54 your program. org/ dev/ peps/ pep-3107/ ). Summary We have seen so many aspects of functions but note that we still haven't covered all aspects of it. we have already covered most of what you'll use regarding Python functions on an everyday basis. If you are interested to read about annotations. However. Python en:Modules 55 Python en:Modules Introduction You have seen how you can reuse code in your program by defining functions once.py import sys print('The command line arguments are:') for i in sys.zip'. What if you wanted to reuse a number of functions in other programs that you write? As you might have guessed. First. There are various methods of writing modules.py extension that contains functions and variables. python. 'C:\\Python30\\lib'. we import the sys module using the import statement. 'C:\\Python30\\DLLs'. A module can be imported by another program to make use of its functionality. but the simplest way is to create a file with a . . For example. they can be used from your Python code when using the standard Python interpreter.e. The sys module contains functionality related to the Python interpreter and its environment i. Another method is to write the modules in the native language in which the Python interpreter itself was written.py we are arguments The PYTHONPATH is [''.py we are arguments The command line arguments are: using_sys. 'C:\\Python30'. 'C:\\Python30\\lib\\plat-win'. org/ extending/ ) and when compiled. Example: #!/usr/bin/python # Filename: using_sys. this translates to us telling Python that we want to use this module. the answer is modules.argv: print(i) print('\n\nThe PYTHONPATH is'. 'C:\\Windows\\system32\\python30. '\n') Output: $ python using_sys. we will see how to use the standard library modules. sys. 'C:\\Python30\\lib\\site-packages'] How It Works: First.path. This is how we can use the Python standard library as well. you can write modules in the C programming language (http:/ / docs. Basically. the system. e. The argv variable in the sys module is accessed using the dotted notation i. Otherwise.argv[2] and 'arguments' as sys. then the . Note that the current directory is the directory from which the program is launched. Note that the initialization is done only the first time that we import a module. If you are using an IDE to write and run these programs. it looks for the sys module. the arguments passed to your program using the command line.it will be much faster since a portion of the processing required in importing a module is already done. Observe that the first string in sys.path.py files.path is empty .argv[0].Python en:Modules 56 When Python executes the import sys statement.py' as sys.e. Also. In this case. so Python does some tricks to make it faster.argv[3]. This .argv.this empty string indicates that the current directory is also part of the sys.path which is same as the PYTHONPATH environment variable. Notice that Python starts counting from 0 and not 1. print(os.pyc file is useful when you import the module the next time from a different program .argv contains the list of command line arguments i.argv variable for us to use. and hence Python knows where to find it. Run import os. then the statements in the body of that module is run and then the module is made available for you to use. Specifically.getcwd()) to find out the current directory of your program.argv variable is a list of strings (lists are explained in detail in a later chapter. the sys.e. when we execute python using_sys.py we are arguments. Another advantage of this approach is that the name does not clash with any argv variable used in your program. Remember. It clearly indicates that this name is part of the sys module. 'we' as sys. Here. Note These . Byte-compiled . If Python does not have permission to write to files in that directory.pyc files Importing a module is a relatively costly affair.pyc which is an intermediate form that Python transforms the program into (remember the introduction section on how Python works?). you will have to place your module in one of the directories listed in sys.argv[1]. sys. Python stores the command line arguments in the sys.pyc files will not be created. then the Python interpreter will search for it in the directories listed in its sys.path contains the list of directory names where modules are imported from. . these byte-compiled files are platform-independent. the name of the script running is always the first argument in the sys. This means that you can directly import modules located in the current directory. look for a way to specify command line arguments to the program in the menus.argv list. 'are' as sys. If the module is found. we run the module using_sys.path variable. in this case we will have 'using_sys. One way is to create byte-compiled files with the extension .pyc files are usually created in the same directory as the corresponding . The sys. The sys. So. a module written in Python. If it was not a compiled module i.py with the python command and the other things that follow are arguments passed to the program. it is one of the built-in modules. In general. This works for any module.. Example: #!/usr/bin/python # Filename: using_name. the code in that module is executed. This is handy in the particular situation of figuring out if the module is being run standalone or being imported.. everytime for it).py if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') Output: $ python using_name. This can be achieved using the __name__ attribute of the module.. then you can use the from sys import argv statement. As mentioned previously.statement If you want to directly import the argv variable into your program (to avoid typing the sys. A module's __name__ Every module has a name and statements in a module can find out the name of its module. .import . then you can use the from sys import * statement. If you want to import all the names used in the sys module. We can use this concept to alter the behavior of the module if the program was used by itself and not when it was imported from another module.Python en:Modules 57 The from ..py This program is being run by itself $ python >>> import using_name I am being imported from another module >>> How It Works: Every Python module has it's __name__ defined and if this is '__main__'. you should avoid using this statement and use the import statement instead since your program will avoid name clashes and will be more readable. when a module is imported for the first time. it implies that the module is being run standalone by the user and we can take appropriate actions. path. Version 0.py Hi. Python makes good reuse of the same notation to give the distinctive 'Pythonic' feel to it so that we don't have to keep learning new ways to do things. As you can see. Here is a version utilising the from. __version__) .py extension.import syntax: #!/usr/bin/python # Filename: mymodule_demo2. The following example should make it clear. Remember that the module should be placed in the same directory as the program that we import it in. You just have to make sure it has a .py import mymodule mymodule. __version__ sayhi() print('Version'..1 How It Works: Notice that we use the same dotted notation to access members of the module.sayhi() print ('Version'.1' # End of mymodule. We will next see how to use this module in our other Python programs. this is mymodule speaking. #!/usr/bin/python # Filename: mymodule_demo. you've been doing it all along! This is because every Python program is also a module.') __version__ = '0.py def sayhi(): print('Hi.py The above was a sample module. there is nothing particularly special about compared to our usual Python program. or the module should be in one of the directories listed in sys. Example: #!/usr/bin/python # Filename: mymodule.py from mymodule import sayhi.__version__) Output: $ python mymodule_demo. this is mymodule speaking.Python en:Modules 58 Making Your Own Modules Creating your own modules is easy. mymodule. 'copyright'.py. 'executable'. classes and variables defined in that module. 'meta_path'. 'float_info'. 'builtin_module_names'. Run import this to learn more and see this discussion (http:/ / stackoverflow. '_getframe'. 'modules'. it returns the list of names defined in the current module. 'gettrace'. 'maxunicode '. Notice that if there was already a __version__ name declared in the module that imports mymodule. When no argument is applied to it. the identifiers include the functions. 'dllhandle' . 'getcheckinterval'. You could also use: from mymodule import * This will import all public names such as sayhi but would not import __version__ because it starts with double underscores. Example: $ python >>> import sys # get list of attributes. 'path_importer_cache'. The dir function You can use the built-in dir function to list the identifiers that an object defines. 'flags'. 'getprofile'. 'intern'. 'argv'. 'call_tracing'. '__stdout__'. com/ questions/ 228181/ zen-of-python) which lists examples for each of the principles. 'getrefcount'. '__package__'. 'displayhook'. Hence. For example. 'getrecursionlimit'. 'dont_write_bytecode'. '__doc__'. it is always recommended to prefer the import statement even though it might make your program a little longer. '__stdin__'. it returns the list of the names defined in that module. 'exec_prefix'. '__name__'. This is also likely because it is common practice for each module to declare it's version number using this name. 'path'. for the sys module >>> dir(sys) ['__displayhook__'. 'excepthook'. . Zen of Python One of Python's guiding principles is that "Explicit is better than Implicit". ' byteorder'.py is same as the output of mymodule_demo. 'getfil esystemencoding'. '__s tderr__'.Python en:Modules 59 The output of mymodule_demo2. '_current_frames'. When you supply a module name to the dir() function. 'path_hooks'. '_clear_type_cache'. 'getdefaultencoding'. there would be a clash. 'callstats'. '__excepthook__'. 'maxsize'. 'exit'. for a module. 'hexversion'. 'exc_info'. 'getwindowsversion'. in this case. 'getsizeof'. '_compact_freelists'. 'api_version'. Notice that the list of imported modules is also part of this list. A note on del . In order to observe the dir in action. We remove the variable/attribute of the current module using the del statement and the change is reflected again in the output of the dir function. 'setprofile'. we use the dir function without passing parameters to it. 'sys'] >>> How It Works: First.it is as if it never existed before at all. 'ps2'. 'sys'] >>> a = 5 # create a new variable 'a' >>> dir() ['__builtins__'. 'sys'] >>> del a # delete/remove a name >>> dir() ['__builtins__'. we define a new variable a and assign it a value and then check dir and we observe that there is an additional value in the list of the same name. you can no longer access the variable a . 'setrecursionlimit '. 'ps1'. 'winver'] >>> dir() # get list of attributes for current module ['__builtins__'. '__doc__'. we see the usage of dir on the imported sys module. 'stderr'. '__name__'. 'setcheckinterval'.Python en:Modules 60 'platfor m'. We can see the huge list of attributes that it contains. 'prefix'. By default. '__package__'. '__doc__'. Note that the dir() function works on any object. in this case del a. '__package__'. 'settrace'. '__package__'.this statement is used to delete a variable/name and after the statement has run. '__name__'. For example. 'stdout'. . 'a'. 'warnoptions'. or dir(str) for the attributes of the str class. '__name__'. 'version'. it returns the list of attributes for the current module. 'subversion'. Next. '__doc__'. run dir(print) to learn about the attributes of the print function. 'stdin'. 'version_in fo'. __init__. we will learn about some interesting concepts called data structures.__init__.asia/ . 'africa'.africa/ . The standard library that comes with Python is an example of such a set of packages and modules.world/ . We have seen how to use these modules and create our own modules.Python en:Modules 61 Packages By now.madagascar/ .bar.py . This is how you would structure the folders: .foo. Packages are another hierarchy to organize modules. Packages are just folders of modules with a special __init__. etc.__init__. Functions and global variables usually go inside modules. modules are reusable programs. and these subpackages in turn contain modules like 'india'.py .path>/ .py . php? oldid=2371 Contributors: Swaroop. Previous Next Source: http:/ / file that indicates to Python that this folder is special because it contains Python modules. com/ mediawiki/ index. you must have started observing the hierarchy of organizing your programs.py Packages are just a convenience to hierarchically organize modules. What if you wanted to organize modules? That's where packages come into the picture. Next.__init__.py . Summary Just like functions are reusable parts of programs.india/ . You will see many instances of this in the standard library. 7 anonymous edits . Variables usually go inside functions. Let's say you want to create a package called 'world' with subpackages 'asia'. etc. swaroopch. 'madagascar'.py .py .<some folder present in the sys. you can store a sequence of items in a list. A list is an example of usage of objects and classes. len(shoplist). Example: #!/usr/bin/python # Filename: using_list. Since we can add and remove items. You can use these variables/names only when you have an object of that class.e.they are structures which can hold some data together. A class can also have fields which are nothing but variables defined for use with respect to that class only. 'items to purchase. 'mango'. List A list is a data structure that holds an ordered collection of items i.e. There are four built-in data structures in Python . Quick Introduction To Objects And Classes Although I've been generally delaying the discussion of objects and classes till now. instance) i of class (i. we say that a list is a mutable data type i.') print('These items are:'. you can think of it as creating an object (i. end=' ') . When we use a variable i and assign a value to it. they are used to store a collection of related data. type) int. Python provides an append method for the list class which allows you to add an item to the end of the list. except that you probably have each item on a separate line in your shopping list whereas in Python you put commas in between them. you can read help(int) to understand this better. 'banana'] print('I have'.e. mylist.Python en:Data Structures 62 Python en:Data Structures Introduction Data structures are basically just that . mylist.py # This is my shopping list shoplist = ['apple'. In other words. Note the use of dotted notation for accessing methods of the objects. The list of items should be enclosed in square brackets so that Python understands that you are specifying a list.e. remove or search for items in the list. We will see how to use each of them and how they make life easier for us. functions defined for use with respect to that class only. A class can also have methods i. tuple. This is easy to imagine if you can think of a shopping list where you have a list of items to buy. Once you have created a list. this type can be altered. Fields are also accessed by the dotted notation. In fact.list. For example. For example. for example.append('an item') will add that string to the list mylist. You can use these pieces of functionality only when you have an object of that class. 'carrot'. a little explanation is needed right now so that you can understand lists better. you can add. We will explore this topic in detail later in its own chapter.e.field. dictionary and set. say integer 5 to it. 'rice'] I will sort my list now Sorted shopping list is ['apple'.this is different from the way strings work.in loop to iterate through the items of the list. 'banana'. we sort the list by using the sort method of the list. we add an item to the list using the append method of the list object. shoplist) Output: $ python using_list. 'banana'. 'carrot'. My shopping list is now ['apple'. 'mango'. In shoplist. It is important to understand that this method affects the list itself and does not return a modified list . We have also used the for. 'mango'. as already discussed before. Then. This is what we mean by saying that lists are mutable and that . shoplist) print('I will sort my list now') shoplist. Next. 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana'. Then.append('rice') print('My shopping list is now'.') shoplist.. we only store strings of the names of the items to buy but you can add any kind of object to a list including numbers and even other lists. end=' ') print('\nI also have to buy rice. 'mango'. shoplist[0]) olditem = shoplist[0] del shoplist[0] print('I bought the'. Notice the use of the end keyword argument to the print function to indicate that we want to end the output with a space instead of the usual line break. By now. shoplist) print('The first item I will buy is'. These items are: apple mango carrot banana I also have to buy rice. olditem) print('My shopping list is now'. 'carrot'. we check that the item has been indeed added to the list by printing the contents of the list by simply passing the list to the print statement which prints it neatly. you must have realised that a list is also a sequence.py I have 4 items to purchase. The speciality of sequences will be discussed in a later section.sort() print('Sorted shopping list is'.Python en:Data Structures 63 for item in shoplist: print(item. 'carrot'. 'rice'] How It Works: The variable shoplist is a shopping list for someone who is going to the market. 'penguin') # remember the parentheses are optional print('Number of animals in the zoo is'. we mention which item of the list we want to remove and the del statement removes it from the list for us. new_zoo[2]) print('Last animal brought from old zoo is'. see help(list) for details. 'camel'. the tuple of values used will not change. We see that the len function can be used to get the length of the tuple. 'penguin') Last animal brought from old zoo is penguin Number of animals in the new zoo is 5 How It Works: The variable zoo refers to a tuple of items.py Number of animals in the zoo is 3 Number of cages in the new zoo is 3 All animals in new zoo are ('monkey'. 'elephant'. Think of them as similar to lists. Tuples are defined by specifying items separated by commas within an optional pair of parentheses. 'penguin')) Animals brought from old zoo are ('python'. If you want to know all the methods defined by the list object. len(zoo)) new_zoo = ('monkey'. new_zoo[2][2]) print('Number of animals in the new zoo is'.Python en:Data Structures 64 strings are immutable. One major feature of tuples is that they are immutable like strings i. Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values i. 'camel'. len(new_zoo)) print('All animals in new zoo are'. This also indicates that a tuple is a sequence as well.py zoo = ('python'.e.e. 'elephant'. ('python'. We achieve this by using the del statement. Here. when we finish buying an item in the market. zoo) print('Number of cages in the new zoo is'. Example: #!/usr/bin/python # Filename: using_tuple. you cannot modify tuples. but without the extensive functionality that the list class gives you. new_zoo) print('Animals brought from old zoo are'. 'elephant'. . len(new_zoo)-1+len(new_zoo[2])) Output: $ python using_tuple. We specify that we want to remove the first item from the list and hence we use del shoplist[0] (remember that Python starts counting from 0). we want to remove it from the list. Tuple Tuples are used to hold together multiple objects. Next. Note for Perl programmers A list within a list does not lose its identity i. ) if you mean you want a tuple containing the item 2. The dictionaries that you will be using are instances/objects of the dict class. they are just objects stored using another object. Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name. Dictionary A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i. Back to reality. Therefore. a tuple with a single item is not so simple.3) ) mean two different things . Example: #!/usr/bin/python # Filename: using_dict. Parentheses Although the parentheses is optional.e. You have to specify it using a comma following the first (and only) item so that Python can differentiate between a tuple and a pair of parentheses surrounding the object in an expression i. If you want a particular order. then you will have to sort them yourself before using it. we associate keys (name) with values (details). As far as Python is concerned.e.2.e. the new_zoo tuple contains some animals which are already there along with the animals brought over from the old zoo. Pairs of keys and values are specified in a dictionary by using the notation d = {key1 : value1. lists are not flattened as in Perl.the former prints three numbers whereas the latter prints a tuple (which contains three numbers). or a tuple within a list. that's all. However. note that a tuple within a tuple does not lose its identity.py . This is pretty simple once you've understood the idiom. Tuple with 0 or 1 items An empty tuple is constructed by an empty pair of parentheses such as myempty = (). key2 : value2 }. print(1. Remember that key-value pairs in a dictionary are not ordered in any manner. Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. For example. you have to specify singleton = (2 .Python en:Data Structures 65 We are now shifting these animals to a new zoo since the old zoo is being closed. etc. We can access the items in the tuple by specifying the item's position within a pair of square brackets just like we did for lists. Note that you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. I prefer always having them to make it obvious that it is a tuple. This is called the indexing operator. This basically translates to say that you should use only simple objects for keys. We access the third item in new_zoo by specifying new_zoo[2] and we access the third item within the third item in the new_zoo tuple by specifying new_zoo[2][2]. or a list within a tuple.2.3) and print( (1. The same applies to a tuple within a tuple. especially because it avoids ambiguity. ab['Swaroop']) # Deleting a key-value pair del ab['Spammer'] print('\nThere are {0} contacts in the address-book\n'.com' } print("Swaroop's address is".the key followed by the value.the del statement.org Contact Larry at larry@wall.com'. 'Spammer' : 'spammer@hotmail.format(len(ab))) for name. address)) # Adding a key-value pair ab['Guido'] = 'guido@python.org' if 'Guido' in ab: # OR ab. Next. We simply specify the dictionary and the indexing operator for the key to be removed and pass it to the del statement.. We retrieve this pair and assign it to the variables name and address correspondingly for each pair using the for. ab['Guido']) Output: $ python using_dict.org'.items(): print('Contact {0} at {1}'. We then access key-value pairs by specifying the key using the indexing operator as discussed in the context of lists and tuples.org How It Works: We create the dictionary ab using the notation already discussed.org Guido's address is guido@python. We can delete key-value pairs using our old friend . Observe the simple syntax. 'Larry' : 'larry@wall.in loop and then print these values in the .format(name.py Swaroop's address is swaroop@swaroopch.Python en:Data Structures 66 # 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' : 'swaroop@swaroopch.org'. address in ab.has_key('Guido') print("\nGuido's address is".com Contact Matsumoto at matz@ruby-lang. we access each key-value pair of the dictionary using the items method of the dictionary which returns a list of tuples where each tuple contains a pair of items . There is no need to know the value corresponding to the key for this operation. 'Matsumoto' : 'matz@ruby-lang.com There are 3 contacts in the address-book Contact Swaroop at swaroop@swaroopch. We can check if a key-value pair exists using the in operator or even the has_key method of the dict class. a part of the sequence. shoplist[1:3]) print('Item 2 to end is'. shoplist[0]) print('Item 1 is'. Sequences Lists. if you have used keyword arguments in your functions. 'mango'. shoplist[-1]) print('Item -2 is'. also have a slicing operation which allows us to retrieve a slice of the sequence i. We can add new key-value pairs by simply using the indexing operator to access a key and assign that value. it is just a key access of a dictionary (which is called the symbol table in compiler design terminology). The indexing operation which allows us to fetch a particular item in the sequence directly. shoplist[1:-1]) print('Item start to end is'.the key-value pair is specified by you in the parameter list of the function definition and when you access variables within your function. shoplist[1]) print('Item 2 is'. name[0]) # Slicing on a list print('Item 1 to 3 is'. tuples and strings. Keyword Arguments and Dictionaries On a different note.lists. 'carrot'.Python en:Data Structures 67 for-block. shoplist[-2]) print('Character 0 is'. shoplist[2:]) print('Item 1 to -1 is'. but what are sequences and what is so special about them? The major features is that they have membership tests (i.e. tuples and strings are examples of sequences. 'banana'] name = 'swaroop' # Indexing or 'Subscription' operation print('Item 0 is'. as we have done for Guido in the above case.e.py shoplist = ['apple'. The three types of sequences mentioned above . the in and not in expressions) and indexing operations. shoplist[2]) print('Item 3 is'. you have already used dictionaries! Just think about it . shoplist[:]) # Slicing on a string . You can see the documentation for the complete list of methods of the dict class using help(dict). shoplist[3]) print('Item -1 is'. Example: #!/usr/bin/python # Filename: seq. includes position 2 but stops at position 3 and therefore a slice of two items is returned. If the first number is not specified. shoplist[:] returns a copy of the whole sequence. 'carrot'. Remember that Python starts counting numbers from 0. The first number (before the colon) in the slicing operation refers to the position from where the slice starts and the second number (after the colon) indicates where the slice will stop at. This is also referred to as the subscription operation. Thus. 'carrot'] Item 2 to end is ['carrot'. If the second number is left out.. 'banana'] Item 1 to -1 is ['mango'. shoplist[-1] refers to the last item in the sequence and shoplist[-2] fetches the second last item in the sequence. in which case. name[:]) Output: $ python seq. we see how to use indexes to get individual items of a sequence. Python will start at the beginning of the sequence. Note that the slice returned starts at the start position and will end just before the end position i. The index can also be a negative number. Python will fetch you the item corresponding to that position in the sequence. 'mango'. Whenever you specify a number to a sequence within square brackets as shown above. Remember the numbers are optional but the colon isn't. 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop How It Works: First. 'carrot'] Item start to end is ['apple'.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Character 0 is s Item 1 to 3 is ['mango'. Hence. name[1:3]) print('characters 2 to end is'. name[1:-1]) print('characters start to end is'. shoplist[1:3] returns a slice of the sequence starting at position 1.e. shoplist[0] fetches the first item and shoplist[3] fetches the fourth item in the shoplist sequence. Therefore. the start position is included but the end position is excluded from the sequence slice. Similarly. .Python en:Data Structures 68 print('characters 1 to 3 is'. Python will stop at the end of the sequence. name[2:]) print('characters 1 to -1 is'. copy() >>> bric. 2. 'mango'. The great thing about sequences is that you can access tuples. the step size is 1): >>> shoplist = ['apple'. 'mango'.issuperset(bri) True >>> bri. shoplist[:-1] will return a slice of the sequence which excludes the last item of the sequence but contains everything else. and so on.intersection(bric) {'brazil'. You can also provide a third argument for the slice. lists and strings all in the same way! Set Sets are unordered collections of simple objects. 'banana'] >>> shoplist[::2] ['apple'. Negative numbers are used for positions from the end of the sequence. 'mango'. you can test for membership. etc. find the intersection between two sets. 'russia'. For example. the prompt so that you can see the results immediately.remove('russia') >>> bri & bric # OR bri. Using sets.add('china') >>> bric. . Try various combinations of such slice specifications using the Python interpreter interactively i. we get the items with position 0. 'banana'] >>> shoplist[::1] ['apple'. 'carrot'. which is the step for the slicing (by default. 'india'} How It Works: The example is pretty much self-explanatory because it involves basic set theory mathematics taught in school. 'apple'] Notice that when the step is 2. whether it is a subset of another set. .. 'carrot'.Python en:Data Structures 69 You can also do slicing with negative positions. 'banana'] >>> shoplist[::-1] ['banana'. 'carrot'] >>> shoplist[::3] ['apple'. >>> bri = set(['brazil'. we get the items with position 0. These are used when the existence of an object in a collection is more important than the order or how many times it occurs. When the step size is 3. 'india']) >>> 'india' in bri True >>> 'usa' in bri False >>> bric = bri. 3.e.. 'carrot'. 'carrot'.py print('Simple Assignment') shoplist = ['apple'. 'banana'] mylist is ['carrot'. 'carrot'. Generally. shoplist) print('mylist is'. the variable only refers to the object and does not represent the object itself! That is. then you have to use the slicing operation to make a copy. Remember that if you want to make a copy of a list or such kinds of sequences or complex objects (not simple objects such as integers). 'mango'.Python en:Data Structures 70 References When you create an object and assign it to a variable. you don't need to be worried about this. If you just assign the variable name to another name.py Simple Assignment shoplist is ['mango'. 'carrot'. This is called as binding of the name to the object. 'banana'] Copy by making a full slice shoplist is ['mango'. but there is a subtle effect due to references which you need to be aware of: Example: #!/usr/bin/python # Filename: reference. both of them will refer . 'banana'] mylist is ['mango'.'. so I remove it from the list print('shoplist is'. mylist) # notice that now the two lists are different Output: $ python reference. 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] # I purchased the first item. 'banana'] How It Works: Most of the explanation is available in the comments. 'carrot'. the variable name points to that part of your computer's memory where the object is stored. the string starts with "Swa"') if 'a' in name: print('Yes. For a complete list of such methods. Some useful methods of this class are demonstrated in the next example. we see a lot of the string methods in action. . it contains the string "war"') delimiter = '_*_' mylist = ['Brazil'. 'India'. You have to use slicing operation to make a copy of the sequence. 'Russia'.Python en:Data Structures 71 to the same object and this could be trouble if you are not careful. did you know that strings are also objects and have methods which do everything from checking part of a string to stripping spaces! The strings that you use in program are all objects of the class str. What more can there be to know? Well. see help(str).join(mylist)) Output: $ python str_methods.py Yes.find('war') != -1: print('Yes. Example: #!/usr/bin/python # Filename: str_methods. The str class also has a neat method to join the items of a sequence with the string acting as a delimiter between each item of the sequence and returns a bigger string generated from this. the string starts with "Swa" Yes.py name = 'Swaroop' # This is a string object if name. it contains the string "a"') if name. The startswith method is used to find out whether the string starts with the given string. More About Strings We have already discussed strings in detail earlier. it contains the string "war" Brazil_*_Russia_*_India_*_China How It Works: Here. 'China'] print(delimiter. it contains the string "a" Yes.startswith('Swa'): print('Yes. The find method is used to do find the position of the given string in the string or returns -1 if it is not successful to find the substring. Note for Perl programmers Remember that an assignment statement for lists does not create a copy. The in operator is used to check if a given string is a part of the string. sourceforge. by designing and writing a program which does something useful. htm) and add C:\Program Files\GnuWin32\bin to your system PATH environment variable. 2. I have created the following list on how I want it to work. 1. Although. 3. The name of the zip archive is the current date and time. Note that you can use any archiving command you want as long as it has a command line interface so that we can pass arguments to it from our script. swaroopch. com/ mediawiki/ index. 5 anonymous edits Python en:Problem Solving We have explored various parts of the Python language and now we will take a look at how all these parts fit together. Windows users can install (http:/ / gnuwin32. If you do the design. . The files are backed up into a zip file. The backup must be stored in a main backup directory. there is not enough information for us to get started with the solution. The files and directories to be backed up are specified in a list. you may not come up with the same kind of analysis since every person has their own way of doing things. we design our program. php) from the GnuWin32 project page (http:/ / gnuwin32. net/ downlinks/ zip. 4. The Problem The problem is "I want a program which creates a backup of all my important files". php? oldid=1582 Contributors: Swaroop. These data structures will be essential for writing programs of reasonable size.Python en:Data Structures 72 Summary We have explored the various built-in data structures of Python in detail. In this case. similar to what we did for recognizing the python command itself. we will next see how to design and write a real-world Python program. sourceforge. Previous Next Source: http:/ / www. For example. A little more analysis is required. this is a simple problem. 5. how do we specify which files are to be backed up? How are they stored? Where are they stored? After analyzing the problem properly. The idea is to learn how to write a Python script on your own. We make a list of things about how our program should work. We use the standard zip command available by default in any standard Linux/Unix distribution. Now that we have a lot of the basics of Python in place. net/ packages/ zip. so that is perfectly okay. check the zip command manual on what could be wrong. # 4. How It Works: You will notice how we have converted our design into code in a step-by-step manner. # 2.format(target. #!/usr/bin/python # Filename: backup_ver1. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. If this command fails.system call and run the program. ' '.join(source)) # Run the backup if os.strftime('%Y%m%d%H%M%S') + '. The files and directories to be backed up are specified in a list.zip' # 5.py Successful backup to E:\Backup\20080702185040. source = ['"C:\\My Documents"'. we are in the testing phase where we test that our program works properly.Python en:Problem Solving 73 The Solution As the design of our program is now reasonably stable. Now copy/paste the printed zip_command to the shell prompt and see if it runs properly on its own. .e.sep + time. target) else: print('Backup FAILED') Output: $ python backup_ver1. remove the bugs (errors) from the program. we can write the code which is an implementation of our solution. put a print(zip_command) just before the os.system(zip_command) == 0: print('Successful backup to'. If the above program does not work for you. The files are backed up into a zip file. then we have to debug our program i.py import os import time # 1. If it doesn't behave as expected.zip Now. If this command succeeds. then check the Python program if it exactly matches the program written above. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}". 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. The name of the zip archive is the current date and time target = target_dir + os. Using os. there might be problems if you have not designed the program properly or if you have made a mistake in typing the code. Unix. The above program works properly. Now that we have a working backup script. use 'C:\\Documents' or r'C:\Documents'.strftime() function. we finally run the command using the os. Then. in the shell . It will also have the . The target directory is where store all the backup files and this is specified in the target_dir variable. html#time. We convert the source list into a string using the join method of strings which we have already seen how to use. This is called the operation phase or the deployment phase of the software. The time. Linux/Unix users are advised to use the executable method as discussed earlier so that they can run the backup script anytime anywhere. it joins the two strings together and returns a new one. For example. it will be '\\' in Windows and ':' in Mac OS. Then. The -q option is used to indicate that the zip command should work quietly.zip extension and will be stored in the target_dir directory. The options are followed by the name of the zip archive to create followed by the list of files and directories to backup. but (usually) first programs do not work exactly as you expect. Notice the use of os. The %m specification will be replaced by the month as a decimal number between 01 and 12 and so on. it should include all the subdirectories and files. we have created a script to take a backup of our important files! Note to Windows Users Instead of double backslash escape sequences. The zip command that we are using has some options and parameters passed. it will be '/' in Linux. org/ dev/ 3. strftime). we create a string zip_command which contains the command that we are going to execute.sep instead of these characters directly will make our program portable and work across these systems.Python en:Problem Solving 74 We make use of the os and time modules by first importing them. etc. we print the appropriate message that the backup has failed or succeeded. Depending on the outcome of the command. . The two options are combined and specified in a shortcut as -qr. else it returns an error number. You can check if this command works by running it on the shell (Linux terminal or DOS prompt).e. The -r option specifies that the zip command should work recursively for directories i. python. We create the name of the target zip file using the addition operator which concatenates the strings i. Then. However. we specify the files and directories to be backed up in the source list.e.e. we can use it whenever we want to take a backup of the files.sep variable .strftime() function takes a specification such as the one we have used in the above program.it returns 0 if the command was successfully. The name of the zip archive that we are going to create is the current date and time which we find out using the time. The %Y specification will be replaced by the year without the century. you will have to go back to the design phase or you will have to debug your program. 0/ library/ time.this gives the directory separator according to your operating system i. That's it. you can also use raw strings. For example. Appropriately.system function which runs the command as if it was run from the system i. do not use 'C:\Documents' since you end up using an unknown escape sequence \D.e. The complete list of such specifications can be found in the Python Reference Manual (http:/ / docs. Third advantage is that separate directories will help you to easily check if you have taken a backup for each day since the directory would be created only if you have taken a backup for that day. # 2.py import os import time # 1. One of the refinements I felt was useful is a better file-naming mechanism . Second advantage is that the length of the filenames are much shorter. ' '. today) # The name of the zip file target = today + os.strftime('%H%M%S') # Create the subdirectory if it isn't already there if not os. The files are backed up into a zip file. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".sep + now + '. source = ['"C:\\My Documents"'.sep + time. The files and directories to be backed up are specified in a list.strftime('%Y%m%d') # The current time is the name of the zip archive now = time. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3.path.format(target. target) . However.join(source)) # Run the backup if os. we can make some refinements to it so that it can work better on a daily basis.Python en:Problem Solving 75 Second Version The first version of our script works. The current day is the name of the subdirectory in the main directory today = target_dir + os.exists(today): os.zip' # 5.using the time as the name of the file within a directory with the current date as a directory within the main backup directory. #!/usr/bin/python # Filename: backup_ver2. # 4. This is called the maintenance phase of the software. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it.mkdir(today) # make directory print('Successfully created directory'. First advantage is that your backups are stored in a hierarchical manner and therefore it is much easier to manage.system(zip_command) == 0: print('Successful backup to'. The files are backed up into a zip file.path. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3. # 2.strftime('%H%M%S') . 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. If it doesn't exist. we create it using the os.sep + time. I am finding it hard to differentiate what the backups were for! For example. Note The following program does not work.py import os import time # 1. I might have made some major changes to a program or presentation. # 4.py Successfully created directory E:\Backup\20080702 Successful backup to E:\Backup\20080702\202311. please follow along because there's a lesson in here.py Successful backup to E:\Backup\20080702\202325. Third Version The second version works fine when I do many backups.strftime('%Y%m%d') # The current time is the name of the zip archive now = time. #!/usr/bin/python # Filename: backup_ver3.zip How It Works: Most of the program remains the same. The current day is the name of the subdirectory in the main directory today = target_dir + os. but when there are lots of backups. then I want to associate what those changes are with the name of the zip archive. so do not be alarmed.mkdir function.Python en:Problem Solving 76 else: print('Backup FAILED') Output: $ python backup_ver2. The changes is that we check if there is a directory with the current day as name inside the main backup directory using the os. The files and directories to be backed up are specified in a list. source = ['"C:\\My Documents"'. This can be easily achieved by attaching a user-supplied comment to the name of the zip archive.exists function.zip $ python backup_ver2. we see that the single logical line has been split into two physical lines but we have not specified that these two physical lines belong together.join(source)) # Run the backup if os. it also tells us the place where it detected the error as well.mkdir(today) # make directory print('Successfully created directory'. This correction of the program when we find errors is called bug fixing. we make this correction to our program.replace(' '. On careful observation. Remember that we can specify that the logical line continues in the next physical line by the use of a backslash at the end of the physical line.sep + now + '.system(zip_command) == 0: print('Successful backup to'.sep + now + '_' + comment.zip' else: target = today + os. So.py File "backup_ver3. . target) else: print('Backup FAILED') Output: $ python backup_ver3.zip' # Create the subdirectory if it isn't already there if not os.py". So we start debugging our program from that line. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}". When we observe the error given by Python.sep + now + '_' + ^ SyntaxError: invalid syntax How This (does not) Work: This program does not work! Python says there is a syntax error which means that the script does not satisfy the structure that Python expects to see. Basically.exists(today): os. ' '.Python en:Problem Solving 77 # Take a comment from the user to create the name of the zip file comment = input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os. Python has found the addition operator (+) without any operand in that logical line and hence it doesn't know how to continue.path. today) # 5.format(target. line 25 target = today + os. '_') + '. py import os import time # 1.join(source)) # Run the backup if os.zip' else: target = today + os. We use the zip command to put the files in a zip archive zip_command = "zip -qr {0} {1}".sep + time.sep + now + '. The files and directories to be backed up are specified in a list. The current day is the name of the subdirectory in the main directory today = target_dir + os.mkdir(today) # make directory print('Successfully created directory'. today) # 5.sep + now + '_' + \ comment. source = ['"C:\\My Documents"'. ' '. # 4.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment = input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os.strftime('%Y%m%d') # The current time is the name of the zip archive now = time. The files are backed up into a zip file. target) else: print('Backup FAILED') Output: .format(target.replace(' '. The backup must be stored in a main backup directory target_dir = 'E:\\Backup' # Remember to change this to what you will be using # 3.exists(today): os. 'C:\\Code'] # Notice we had to use double quotes inside the string for names with spaces in it. '_') + '.system(zip_command) == 0: print('Successful backup to'.path.zip' # Create the subdirectory if it isn't already there if not os.Python en:Problem Solving 78 Fourth Version #!/usr/bin/python # Filename: backup_ver4. # 2. 0/ library/ zipfile. Notice that we are replacing spaces in the comment with underscores .Python en:Problem Solving 79 $ python backup_ver4. then this is attached to the name of the zip archive just before the . We can get these names from the sys. For example. However. python. but there is always room for improvement. if a comment was supplied. More Refinements The fourth version is a satisfactorily working script for most users.this is because managing filenames without spaces are much easier. However. html) module instead of the os. We take in the user's comments using the input function and then check if the user actually entered something by finding out the length of the input using the len function. org/ dev/ 3.zip How It Works: This program now works! Let us go through the actual enhancements that we had made in version 3. The most important refinement would be to not use the os.system way of creating a backup in the above examples purely for pedagogical purposes. you can include a verbosity level for the program where you can specify a -v option to make your program become more talkative. If the user has just pressed enter without entering anything (maybe it was just a routine backup or no special changes were made).py Enter a comment --> added new examples Successful backup to E:\Backup\20080702\202836_added_new_examples. Another possible enhancement would be to allow extra files and directories to be passed to the script at the command line. so that the example is simple enough to be understood by everybody but real enough to be useful. Can you try writing the fifth version that uses the zipfile (http:/ / docs. I have been using the os.zip extension.argv list and we can add them to our source list using the extend method provided by the list class. then we proceed as we have done before.zip $ python backup_ver4.system call? . They are part of the standard library and available already for you to use without external dependencies on the zip program to be available on your computer.py Enter a comment --> Successful backup to E:\Backup\20080702\202839.system way of creating archives and instead using the zipfile or tarfile built-in module to create these archives. These phases can be summarised as follows: 1. Next.Python en:Problem Solving 80 The Software Development Process We have now gone through the various phases in the process of writing a software. Do It (Implementation) 4. Previous Next Source: http:/ / www. Maintain (Refinement) A recommended way of writing programs is the procedure we have followed in creating the backup script: Do the analysis and design. Now. we will discuss object-oriented programming. not built. Use (Operation or Deployment) 6. com/ mediawiki/ index. Test (Testing and Debugging) 5. 3 anonymous edits . Test and debug it. Remember. How (Design) 3. Summary We have seen how to create our own Python programs/scripts and the various stages involved in writing such programs. add any features that you want and continue to repeat the Do It-Test-Use cycle as many times as required. Start implementing with a simple version. Use it to ensure that it works as expected. php? oldid=1395 Contributors: Swaroop. Software is grown. You may find it useful to create your own program just like we did in this chapter so that you become comfortable with Python as well as problem-solving. What (Analysis) 2. swaroopch. it is strongly recommended that you use the name self . we have designed our program around functions i. Variables that belong to an object or class are referred to as fields. Such functions are called methods of the class. A class creates a new type where objects are instances of the class. and by convention. This particular variable refers to the object itself. you can give any name for this parameter. The fields and methods of the class are listed in an indented block. There is another way of organizing your program which is to combine data and functionality and wrap it inside something called an object. blocks of statements which manipulate data. This is called the procedure-oriented way of programming.any other name is definitely frowned upon. They are called instance variables and class variables respectively. A class is created using the class keyword. it is given the name self. Although. This terminology is important because it helps us to differentiate between functions and variables which are independent and those which belong to a class or object.they must have an extra first name that has to be added to the beginning of the parameter list.5 programmers will find this similar to the boxing and unboxing concept. . but you do not give a value for this parameter when you call the method. Classes and objects are the two main aspects of object oriented programming. the fields and methods can be referred to as the attributes of that class. There are many advantages to using a standard name . This is unlike C++ and Java (before version 1. C# and Java 1. Collectively. Most of the time you can use procedural programming.5) where integers are primitive native types. This is called the object oriented programming paradigm. See help(int) for more details on the class.Python en:Object Oriented Programming 81 Python en:Object Oriented Programming Introduction In all the programs we wrote till now. The self Class methods have only one specific difference from ordinary functions . Note for Static Language Programmers Note that even integers are treated as objects (of the int class).any reader of your program will immediately recognize it and even specialized IDEs (Integrated Development Environments) can help you if you use self. Fields are of two types . An analogy is that you can have variables of type int which translates to saying that variables that store integers are variables which are instances (objects) of the int class. Objects can store data using ordinary variables that belong to the object. you can use object oriented programming techniques.e. Python will provide it.they can belong to each instance/object of the class or they can belong to the class itself. Objects can also have functionality by using functions that belong to a class. but when writing large programs or have a problem that is better suited to this method. py class Person: pass # An empty block p = Person() print(p) Output: $ python simplestclass. we confirm the type of the variable by simply printing it. This also means that if you have a method which takes no arguments.method(myobject. arg2) . Next.Person object at 0x019F85F0> How It Works: We create a new class using the class statement and the name of the class. The address will have a different value on your computer since Python can store the object wherever it finds space. then you still have to have one argument . An example will make this clear. (We will learn more about instantiation in the next section).the self. For our verification. When you call a method of this object as myobject. This is followed by an indented block of statements which form the body of the class.Python en:Object Oriented Programming 82 Note for C++/Java/C# Programmers The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#. Notice that the address of the computer memory where your object is stored is also printed. Say you have a class called MyClass and an instance of this class called myobject. . this is automatically converted by Python into MyClass.py <__main__. #!/usr/bin/python # Filename: simplestclass. we have an empty block which is indicated using the pass statement. It tells us that we have an instance of the Person class in the __main__ module.this is all the special self is about. arg1.method(arg1. arg2). Classes The simplest class possible is shown in the following example. You must be wondering how Python gives the value for self and why you don't need to give a value for it. we create an object/instance of this class using the name of the class followed by a pair of parentheses. In this case. how are you?') p = Person() p. We will now see an example. Notice that the sayHi method takes no parameters but still has the self in the function definition.sayHi() Output: $ python method. #!/usr/bin/python # Filename: method. The __init__method There are many method names which have special significance in Python classes.py class Person: def __init__(self.name) p = Person('Swaroop') p. name): self.py Hello.sayHi() # This short example can also be written as Person('Swaroop').sayHi() Output: . my name is'.py class Person: def sayHi(self): print('Hello. how are you? How It Works: Here we see the self in action. Example: #!/usr/bin/python # Filename: class_init.sayHi() # This short example can also be written as Person(). Notice the double underscores both at the beginning and at the end of the name. The __init__ method is run as soon as an object of a class is instantiated.name = name def sayHi(self): print('Hello.Python en:Object Oriented Programming 83 Object Methods We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable. self. We will see the significance of the __init__ method now. The method is useful to do any initialization you want to do with your object. Class variables are shared . Class And Object Variables We have already discussed the functionality part of classes and objects (i.they can be accessed by all instances of that class. name): '''Initializes the data. now let us learn about the data part. Most importantly. This is the special significance of this method. There is only one copy of the class variable and when any one object makes a change to a class variable.''' # A class variable. Object variables are owned by each individual object/instance of the class.e.class variables and object variables which are classified depending on whether the class or the object owns the variables respectively. i.Python en:Object Oriented Programming 84 $ python class_init.py class Robot: '''Represents a robot. the robot # adds to the population Robot.name = name print('(Initializing {0})'. An example will make this easy to understand: #!/usr/bin/python # Filename: objvar. That's why they are called name spaces.''' self.population += 1 . we just create a new field also called name.format(self. fields. The data part. counting the number of robots population = 0 def __init__(self. that change will be seen by all the other instances. are nothing but ordinary variables that are bound to the namespaces of the classes and objects.e. Now. each object has its own copy of the field i. The dotted notation allows us to differentiate between them.name)) # When this person is created. with a name. Here.e.name field in our methods which is demonstrated in the sayHi method. There are two types of fields . my name is Swaroop How It Works: Here. they are not shared and are not related in any way to the field by the same name in a different instance. we are able to use the self. notice that we do not explicitly call the __init__ method but pass the arguments in the parentheses following the class name when creating a new instance of the class. Notice these are two different variables even though they are both called 'name'. we define the __init__ method as taking a parameter name (along with the usual self). This means that these names are valid within the context of these classes and objects only. methods). In this case.py Hello. ''' print('We have {0:d} robots.format(self. .name)) Robot.") del droid1 del droid2 Robot.'. (Initializing C-3PO) Greetings.'. they can do that.howMany() print("\nRobots can do some work here.''' print('{0} is being destroyed!'.format(Robot.name)) else: print('There are still {0:d} robots working.\n") print("Robots have finished their work.format(Robot.population)) def sayHi(self): '''Greeting by the robot. So let's destroy them.''' print('Greetings.population == 0: print('{0} was the last one.'.name)) def howMany(): '''Prints the current population.sayHi() Robot. my masters call me {0}.sayHi() Robot.howMany() droid2 = Robot('C-3PO') droid2.format(self.format(self.'. Yeah. my masters call me C-3PO.population)) howMany = staticmethod(howMany) droid1 = Robot('R2-D2') droid1.Python en:Object Oriented Programming 85 def __del__(self): '''I am dying.population -= 1 if Robot.howMany() Output: (Initializing R2-D2) Greetings. We have 2 robots. We have 1 robots. my masters call me R2-D2. as we have seen in this example.sayHi.e.. Here.population. This is called an attribute reference.'. So let's destroy them.population count by 1. Remember this simple difference between class and object variables. we also see the use of docstrings for classes as well as methods. Since we don't need such information. R2-D2 is being destroyed! There are still 1 robots working.name is specific to each object which indicates the nature of object variables.''' print('We have {0:d} robots. We can access the class docstring at runtime using Robot. we increase the population count by 1 since we have one more robot being added. Also observe that the values of self. We refer to the object variable name using self. population belongs to the Robot class and hence is a class variable. com/ developerworks/ linux/ library/ l-cpdecor.__doc__ Just like the __init__ method.Python en:Object Oriented Programming 86 Robots can do some work here. In this method. In this program. we refer to the population class variable as Robot. This means we can define it as either a classmethod or a staticmethod depending on whether we need to know which class we are part of.format(Robot.name notation in the methods of that object. html): @staticmethod def howMany(): '''Prints the current population.population and not as self. Remember. we will go for staticmethod. We could have also achieved the same using decorators (http:/ / www. it is no longer being used and is being returned to the computer system for reusing that piece of memory. .__doc__ and the method docstring as Robot. there is another special method __del__ which is called when an object is going to die i. ibm. The name variable belongs to the object (it is assigned using self) and hence is an object variable.population)) Decorators can be imagined to be a shortcut to calling an explicit statement. Observe that the __init__ method is used to initialize the Robot instance with a name. Robots have finished their work. we simply decrease the Robot. C-3PO is being destroyed! C-3PO was the last one. How It Works: This is a long example but helps demonstrate the nature of class and object variables. In this method. We have 0 robots. Thus. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix). changes in the subtypes do not affect other subtypes. #!/usr/bin/python # Filename: inherit. Python uses name-mangling to effectively make it a private variable. the object can be treated as an instance of the parent class. age and address. Inheritance can be best imagined as implementing a type and subtype relationship between classes. you can add a new ID card field for both teachers and students by simply adding it to the SchoolMember class. This quickly becomes unwieldy. This is called polymorphism where a sub-type can be substituted in any situation where a parent type is expected i. Inheritance One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the inheritance mechanism. However. We will now see this example as a program. courses and leaves for teachers and. The Teacher and Student classes are called the derived classes or subclasses.e. They have some common characteristics such as name. If you want to explicitly see it in action. Also observe that we reuse the code of the parent class and we do not need to repeat it in the different classes as we would have had to in case we had used independent classes.e. we have to use the del statement which is what we have done here. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types. One exception: If you use data members with names using the double underscore prefix such as __privatevar.Python en:Object Oriented Programming 87. They also have specific characteristics such as salary. If we add/change any functionality in SchoolMember. Another advantage is that if you can refer to a teacher or student object as a SchoolMember object which could be useful in some situations such as counting of the number of school members. Thus. For example. Note for C++/Java/C# Programmers All class members (including the data members) are public and all the methods are virtual in Python. marks and fees for students. The SchoolMember class in this situation is known as the base class or the superclass. Suppose you want to write a program which has to keep track of the teachers and students in a college. this is automatically reflected in the subtypes as well. There are many advantages to this approach. You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes.py . A better way would be to create a common class called SchoolMember and then have the teacher and student classes inherit from this class i. 40.__init__(self.''' print('Name:"{0}" Age:"{1}"'. 75) print() # prints a blank line members = [t. name. name.name)) def tell(self): SchoolMember.tell(self) print('Marks: "{0:d}"'. name.__init__(self.age).''' def __init__(self. age. marks): SchoolMember.marks = marks print('(Initialized Student: {0})'. 30000) s = Student('Swaroop'.format(self.''' def __init__(self. self. Shrividya'.marks)) t = Teacher('Mrs.format(self. age) self. s] for member in members: member.tell() # works for both Teachers and Students Output: $ python inherit.format(self. name. age.salary = salary print('(Initialized Teacher: {0})'. 25.tell(self) print('Salary: "{0:d}"'. age): self.name.name)) def tell(self): SchoolMember. age) self.salary)) class Student(SchoolMember): '''Represents a student.py (Initialized SchoolMember: Mrs.format(self.format(self.name = name self. salary): SchoolMember. Shrividya) . end=" ") class Teacher(SchoolMember): '''Represents a teacher.format(self.''' def __init__(self.Python en:Object Oriented Programming 88 class SchoolMember: '''Represents any school member. name.age = age print('(Initialized SchoolMember: {0})'.name)) def tell(self): '''Tell my details. Python en:Object Oriented Programming 89 (Initialized Teacher: Mrs. This is very important to remember . Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop) Name:"Mrs. we specify the base class names in a tuple following the class name in the class definition. We have also seen the benefits and pitfalls of object-oriented programming. We also observe that we can call methods of the base class by prefixing the class name to the method call and then pass in the self variable along with any arguments.if more than one class is listed in the inheritance tuple. observe that the tell method of the subtype is called and not the tell method of the SchoolMember class. swaroopch.Python does not automatically call the constructor of the base class. A note on terminology . Python is highly object-oriented and understanding these concepts carefully will help you a lot in the long run. then it is called multiple inheritance. 6 anonymous edits . One way to understand this is that Python always starts looking for methods in the actual type. you have to explicitly call it yourself. If it could not find the method. Next. we will learn how to deal with input/output and how to access files in Python. com/ mediawiki/ index. Swaroop. it starts looking at the methods belonging to its base classes one by one in the order they are specified in the tuple in the class definition. Summary We have now explored the various aspects of classes and objects as well as the various terminologies associated with it. Also. which in this case it does. Previous Next Source: http:/ / www. Next. php? oldid=2359 Contributors: Horstjens.. we observe that the __init__ method of the base class is explicitly called using the self variable so that we can initialize the base class part of the object. The ability to create. For example. we can also use the various methods of the str (string) class.py Enter text: racecar Yes. it is a palindrome $ python user_input. Input from user #!/usr/bin/python # user_input. you would want to take input from the user and then print some results back. We can also provide a third argument that determines the step by which the slicing is done. For example. Another common type of input/output is dealing with files. We can achieve this using the input() and print() functions respectively. it is a palindrome How It Works: We use the slicing feature to reverse the text. For output. it is not a palindrome") Output: $ python user_input. read and write files is essential to many programs and we will explore this aspect in this chapter. you can use the rjust method to get a string which is right justified to a specified width. We've already seen how we can make slices from sequences using the seq[a:b] code starting from position a to position b.py Enter text: sir No.py Enter text: madam Yes. it is a palindrome") else: print("No. See help(str) for more details. The .py def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Enter text: ') if (is_palindrome(something)): print("Yes. it is not a palindrome $ python user_input.Python en:Input Output 90 Python en:Input Output Introduction There will be situations where your program has to interact with the user. i. Homework exercise: Checking whether a text is a palindrome should also ignore punctuation.close() # close the file Output: $ python using_file. when you are finished with the file. -1 will return the text in reverse.close() # close the file f = open('poem. 'w') # open for 'w'riting f.Python en:Input Output 91 default step is 1 because of which it returns a continuous part of the text.write(poem) # write text to file f. Once the user has entered. you call the close method to tell Python that we are done using the file.txt') # if no mode is specified. end='') f. readline or write methods appropriately to read from or write to the file. Can you improve the above program to recognize this palindrome? Files You can open and use files for reading or writing by creating an object of the file class and using its read. For example. "Rise to vote. The ability to read or write to the file depends on the mode you have specified for the file opening. wiktionary.py Programming is fun .e. Example: #!/usr/bin/python # Filename: using_file. Giving a negative step.. Then it waits for the user to type something and press the return key." is also a palindrome but our current program doesn't say it is. 'r'ead mode is assumed by default while True: line = f. spaces and case. If the original text and reversed text are equal.readline() if len(line) == 0: # Zero length indicates EOF break print(line. Then finally.txt'. then the text is a palindrome (http:/ / en. We take that text and reverse it. the input() function will then return that text. The input() function takes a string as argument and displays it to the user. sir.py poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = open('poem. org/ wiki/ palindrome). it means that we have reached the end of the file and we 'break' out of the loop. By deafult.data' # the list of things to buy shoplist = ['apple'. We don't need to specify a mode because 'read text file' is the default mode.close() del shoplist # destroy the shoplist variable # Read back from the storage . open() considers the file to be a 't'ext file and opens it in 'r'ead mode. Now. This is called storing the object persistently. We can also by dealing with a text file ('t') or a binary file ('b').Python en:Input Output 92 When the work is done if you wanna make your work also fun: use Python! How It Works: First.py import pickle # the name of the file where we will store the object shoplistfile = 'shoplist. 'mango'. Example: #!/usr/bin/python # Filename: pickling. Next. We are suppressing the newline by specifying end='' because the line that is read from the file already ends with a newline character. By default.dump(shoplist.txt file to confirm that the program has indeed written and read from that file. Pickle Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later. 'wb') pickle. We read in each line of the file using the readline method in a loop. we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file. There are actually many more modes available and help(open) will give you more details about them. write mode ('w') or append mode ('a'). In our example. The mode can be a read mode ('r'). This method returns a complete line including the newline character at the end of the line. 'carrot'] # Write to the file f = open(shoplistfile. When an empty string is returned. we finally close the file. Then. open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. f) # dump the object to a file f. we open the same file again for reading. the print() function prints the text as well as an automatic newline to the screen. check the contents of the poem. 1 anonymous edits Python en:Exceptions Introduction Exceptions occur when certain exceptional situations occur in your program. What if we misspelt print as Print? Note the capitalization. in <module> Print('Hello World') NameError: name 'Print' is not defined >>> print('Hello World') Hello World . 'rb') storedlist = pickle. This process is called pickling. For example. line 1. 'carrot'] How It Works: To store an object in a file. we have to first open the file in 'w'rite 'b'inary mode and then call the dump function of the pickle module. we retrieve the object using the load function of the pickle module which returns the object. Similarly. Swaroop. >>> Print('Hello World') Traceback (most recent call last): File "<pyshell#0>". we will explore the concept of exceptions.load(f) # load the object from the file print(storedlist) Output: $ python pickling. This process is called unpickling. Next.py ['apple'. swaroopch. com/ mediawiki/ index. Errors Consider a simple print function call. php? oldid=1583 Contributors: Horstjens. Next. what if you are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program was running? Such situations are handled using exceptions. In this case. Summary We have discussed various types of input/output and also file handling and using the pickle module. 'mango'. Python raises a syntax error. Previous Next Source: http:/ / en:Input Output 93 f = open(shoplistfile. what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error. except statement. >>> s = input('Enter something --> ') Enter something --> Traceback (most recent call last): File "<pyshell#2>".format(text)) Output: $ python try_except. Exceptions We will try to read input from the user. Handling Exceptions We can handle exceptions using the try.') else: print('You entered {0}'. in <module> s = input('Enter something --> ') EOFError: EOF when reading a line Python raises an error called EOFError which basically means it found an end of file symbol (which is represented by ctrl-d) when it did not expect to see it. line 1. The except . This is what an error handler for this error does. Press ctrl-d and see what happens...py Enter something --> # Press ctrl-d Why did you do an EOF on me? $ python try_except.Python en:Exceptions 94 Observe that a NameError is raised and also the location where the error was detected is printed. $ python try_except. #!/usr/bin/python # Filename: try_except.py Enter something --> # Press ctrl-c You cancelled the operation.py try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation. We have already seen this in action above. In the next example. The error or exception that you can arise should be class which directly or indirectly must be a derived class of the Exception class.''' def __init__(self.length. atleast): Exception.atleast = atleast try: text = input('Enter something --> ') if len(text) < 3: raise ShortInputException(len(text).atleast)) else: print('No exception was raised. Raising Exceptions You can raise exceptions using the raise statement by providing the name of the error/exception and the exception object that is to be thrown. #!/usr/bin/python # Filename: raising. length. it will handle all errors and exceptions. ex. 3) # Other work can continue as usual here except EOFError: print('Why did you do an EOF on me?') except ShortInputException as ex: print('ShortInputException: The input was {0} long. or a parenthesized list of errors/exceptions.py class ShortInputException(Exception): '''A user-defined exception class. If no names of errors or exceptions are supplied. what's the point of having a try block? If any error or exception is not handled.Python en:Exceptions 95 clause can handle a single specified error or exception. Note that there has to be at least one except clause associated with every try clause. we will also see how to get the exception object so that we can retrieve additional information..except block. expected at least {1}'\ .length = length self.__init__(self) self. Otherwise. The else clause is executed if no exception occurs.py Enter something --> a . then the default Python handler is called which just stops the execution of the program and prints an error message.') Output: $ python raising. You can also have an else clause associated with a try.format(ex. In the except clause. . we mention the class of error which will be stored as the variable name to hold the corresponding error/exception object.close() print('(Cleaning up: Closed the file)') Output: $ python finally. Within this particular except clause.py import time try: f = open('poem.length which is the length of the given input. #!/usr/bin/python # Filename: finally.Finally Suppose you are reading a file in your program. expected at least 3 $ python raising. we are creating our own exception type. end='') time.readline() if len(line) == 0: break print(line. It has two fields .txt') while True: # our usual file-reading idiom line = f. You will have to embed one within another if you want to use both.Python en:Exceptions 96 ShortInputException: The input was 1 long. we use the length and atleast fields of the exception object to print an appropriate message to the user. This new exception type is called ShortInputException.') finally: f.py Programming is fun When the work is done if you wanna make your work also fun: !! You cancelled the reading from the file.sleep(2) # To make sure it runs for a while except KeyboardInterrupt: print('!! You cancelled the reading from the file. This is analogous to parameters and arguments in a function call. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the finally block..py Enter something --> abc No exception was raised. Note that you can use an except clause along with a finally block for the same corresponding try block. and atleast which is the minimum length that the program was expecting. Try . How It Works: Here. Previous Next Source: http:/ / www. python. It fetches the object returned by the open statement.py with open("poem. More discussion on this topic is beyond scope of this book. Next.finally statements. We have seen how to create our own exception types and how to raise exceptions as well.__enter__ function before starting the block of code under it and always calls thefile. the finally clause is executed and the file object is always closed. It always calls the thefile..except and try. swaroopch.. The with statement Acquiring a resource in the try block and subsequently releasing the resource in the finally block is a common pattern. com/ mediawiki/ index. press ctrl-c to interrupt/cancel the program.. so please refer PEP 343 (http:/ / www. However. Summary We have discussed the usage of the try. before the program exits. let's call it "thefile" in this case. Observe that the KeyboardInterrupt exception is thrown and the program quits. php? oldid=1470 Contributors: Swaroop. What happens behind the scenes is that there is a protocol used by the with statement.__exit__ after finishing the block of code. When the program is still running. So the code that we would have written in a finally block is should be taken care of automatically by the __exit__ method. end='') How It Works: The output should be same as the previous example.Python en:Exceptions 97 (Cleaning up: Closed the file) How It Works: We do the usual file-reading stuff. This is what helps us to avoid having to use explicit try. The difference here is that we are using the open function with the with statement .sleep function so that the program runs slowly (Python is very fast by nature).we leave the closing of the file to be done automatically by with open. Hence. 2 anonymous edits . but we have arbitrarily introduced sleeping for 2 seconds after printing each line using the time. there is also a with statement that enables this to be done in a clean manner: #!/usr/bin/python # Filename: using_with.txt") as f: for line in f: print(line.finally statements repeatedly. we will explore the Python Standard Library. org/ dev/ peps/ pep-0343/ ) for comprehensive explanation. 0.version_info[0] < 3: warnings. say. Suppose we want to check the version of the Python command being used so that. warnings if sys. python. You can find complete details for all of the modules in the Python Standard Library in the 'Library Reference' section (http:/ / docs. we want to ensure that we are using at least version 3.version_info (3. RuntimeWarning) else: print('Proceed as normal') Output: .0: #!/usr/bin/python # Filename: versioncheck. org/ dev/ 3. The first entry is the major version.version_info[0] >= 3 True How It Works: The sys module has a version_info tuple that gives us the version information. 0. 2) >>> sys. I highly recommend coming back to this chapter when you are more comfortable with programming using Python. for example. The sys module gives us such functionality. Note If you find the topics in this chapter too advanced. We will explore some of the commonly used modules in this library. However. 'beta'. you may skip this chapter. Let us explore a few useful modules.Python en:Standard Library 98 Python en:Standard Library Introduction The Python Standard Library contains a huge number of useful modules and is part of every standard Python installation. 0/ library/ ) of the documentation that comes with your Python installation.py import sys.warn("Need Python 3. We can check this to.argv list contains the command-line arguments. ensure the program runs only under Python 3. >>> import sys >>> sys. It is important to become familiar with the Python Standard Library since many problems can be solved quickly if you are familiar with the range of things that these libraries can do. sys module The sys module contains system-specific functionality.0 for this program to run". We have already seen that the sys. startswith('Windows'): logging_file = os. If the Python version number is not at least 3.debug("Start of the program") logging.233 : INFO : Doing something 2008-09-03 13:18:16. 'test. logging module What if you wanted to have some debugging messages or important messages to be stored somewhere so that you can check whether your program has been running as you would expect it? How do you "store somewhere" these messages? This can be achieved using the logging module.5 versioncheck.log') else: logging_file = os. 'test.platform(). we display a corresponding warning.log.Python en:Standard Library 99 $ python2.py Proceed as normal How It Works: We use another module from the standard library called warnings that is used to display warnings to the end-user. filemode = 'w'.log') logging.getenv('HOMEPATH').warning("Dying now") Output: $python use_logging. os.join(os. #!/usr/bin/python # Filename: use_logging.233 : WARNING : Dying now .DEBUG.py:6: RuntimeWarning: Need Python 3.233 : DEBUG : Start of the program 2008-09-03 13:18:16.join(os.path.log If we check the contents of test. logging if platform.getenv('HOMEDRIVE').path.py versioncheck.info("Doing something") logging.getenv('HOME'). ) logging. platform. it will look something like this: 2008-09-03 13:18:16.py Logging to C:\Users\swaroop\test.py import os.basicConfig( level=logging.0 for this program to run RuntimeWarning) $ python3 versioncheck. filename = logging_file. format='%(asctime)s : %(levelname)s : %(message)s'.. see import platform. This can be achieved using a few modules. we figure out the home drive. the operating system and the logging module to log information. org/ issue3763).version_info[0] != 3: sys.Python en:Standard Library 100 How It Works: We use three modules from the standard library . Once the program has run.0 beta 2 (http:/ / bugs.response # Get your own APP ID at (for more information. warning or even critical messages. urllib. The reason to use a special function rather than just adding the strings together is because this function will ensure the full location matches the format expected by the operating system. urllib. we check which operating system we are using by checking the string returned by platform.com/wsregapp/ YAHOO_APP_ID = 'jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8. First. the platform module for information about the platform i.e.exit('This program needs Python 3.yahoo. If it is Windows. help(platform)). For other platforms.com/WebSearchService/V1/webSearch' . Putting these three parts together. even though no information was displayed to the user running the program. urllib and json modules How much fun would it be if we could write our own program that will get search results from the web? Let us explore that now. Finally.yahooapis. python. We configure the logging module to write all the messages in a particular format to the file we have specified.path.py import sys if sys.join() function to put these three parts of the location together. TODO This program doesn't work yet which seems to be a bug in Python 3.parse. information.the os module for interacting with the operating system. we get the full location of the file. First is the urllib module that we can use to fetch any webpage from the internet.request. the home folder and the filename where we want to store the information. #!/usr/bin/python # Filename: yahoo_search.lBSfPhwr' SEARCH_BASE = '. We use the os.0') import json import urllib. urllib. we can check this file and we will know what happened in the program. we can put messages that are either meant for debugging..urlopen(url)) if 'Error' in result: raise YahooSearchError(result['Error']) return result['ResultSet'] query = input('What do you want to search for? ') for result in search(query)['Result']: print("{0} : {1}".Python en:Standard Library 101 class YahooSearchError(Exception): pass # Taken from(urllib.request. starting from the first result.urlencode(kwargs) result = json. So for example.format(result['Title']. yahooapis. for the words "byte of python".html def search(query. . and we are asking for the output in JSON format. results=20. We then loop through these results and display it to the end-user. We make a connection to this URL using the urllib.com/python/python-json.yahoo.update({ 'appid': YAHOO_APP_ID.parse. lBSfPhwr& results=20& start=1& output=json) and you will see 20 results. result['Url'])) Output: TODO How It Works: We can get the search results from a particular website by giving the text we are searching for in a particular format.parse. 'query': query. start=1. open this link in your web browser (http:/ / search. 'results': results. **kwargs): kwargs. 'output': 'json' }) url = SEARCH_BASE + '?' + urllib. We have to specify many options which we combine using key1=value1&key2=value2 format which is handled by the urllib.urlencode() function. 'start': start.request.urlopen() function and pass that file handle to json.load() which will read the content and simultaneously convert it to a Python object. Passing tuples around Ever wished you could return two different values from a function? You can. com/ projects/ PyMOTW/ ) series. we will cover various aspects of Python that will make our tour of Python more complete. org/ dev/ 3. html) and so on.Python en:Standard Library 102 Module of the Week Series There is much more to be explored in the standard library such as debugging (http:/ / docs. html).. com/ mediawiki/ index. It is highly recommended to browse through the Python Standard Library documentation (http:/ / docs. If you want to interpret the results as (a. 'second error details') . Next. then you just need to star it just like you would in function parameters: . return (2. All you have to do is use a tuple. doughellmann. html). handling command line options (http:/ / docs. 0/ library/ getopt. Summary We have explored some of the functionality of many modules in the Python Standard Library. org/ regular_expressions/ index. python. The best way to further explore the standard library is to read Doug Hellmann's excellent Python Module of the Week (http:/ / www. In this chapter. we will cover some more aspects that will make our knowledge of Python more well-rounded. b = <some expression> interprets the result of the expression as a tuple with two values.. 2 anonymous edits Python en:More Introduction So far we have covered majority of the various aspects of Python that you will use.. diveintopython. >>> def get_error_details(): . python. org/ dev/ 3. swaroopch. php? oldid=1156 Contributors: Swaroop. Previous Next Source: http:/ / www. regular expressions (http:/ / www. errstr = get_error_details() >>> errnum 2 >>> errstr 'second error details' Notice that the usage of a. org/ dev/ library/ pdb. python.. <everything else>). 0/ library/ ) to get an idea of all the modules that are available. >>> errnum. . The following example should make this clear: >>> flag = True >>> if flag: print 'Yes' . etc. 5) Special Methods There are certain methods such as the __init__ and __del__ methods which have special significance in classes.. say. b (8. For example.. Yes Notice that the single statement is used in-place and not as a separate block. 4] >>> a 1 >>> b [2. 3. you can use this for making your program smaller. other) Called when the less than operator (<) is used. __lt__(self.) This method is called just before the newly created object is returned for usage. 3. a conditional statement or looping statement. python. 0/ reference/ datamodel. 4] This also means the fastest way to swap two variables in Python is: >>> a = 5. except for error checking. this is what Python does for the list class itself! Some useful special methods are listed in the following table. Special methods are used to mimic certain behaviors of built-in types. *b = [1.Python en:More 103 >>> a. see the manual (http:/ / docs. then you can specify it on the same line of. If you want to know about all the special methods. Similarly.. org/ dev/ 3. . Name Explanation __init__(self. If your block of statements contains only one single statement. b = 8 >>> a. __len__(self) Called when the built-in len() function is used for the sequence object.) __getitem__(self. html#special-method-names). there is one caveat. if you want to use the x[key] indexing operation for your class (just like you use it for lists and tuples). b = b. a >>> a. Single Statement Blocks We have seen that each block of statements is set apart from the rest by its own indentation level. >. there are special methods for all the operators (+. mainly because it will be much easier to add an extra . then all you have to do is implement the __getitem__() method and your job is done. __del__(self) Called just before the object is destroyed __str__(self) Called when we use the print function or when str() is used. If you think about it. key) Called when x[key] indexing operation is used. 2. Although. I strongly recommend avoiding this short-cut method. Well. the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function. #!/usr/bin/python # Filename: lambda. b : cmp(a['x']. only expressions. 3.py listone = [2. we use a function make_repeater to create new function objects at runtime and return it. #!/usr/bin/python # Filename: list_comprehension.sort(lambda a.py def make_repeater(n): return lambda s: s * n twice = make_repeater(2) print(twice('word')) print(twice(5)) Output: $ python lambda. Note that even a print statement cannot be used inside a lambda form. Suppose you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 only when the number itself is greater than 2. 'y' : 3 }. A lambda statement is used to create the function object. { 'x' : 4.py wordword 10 How It Works: Here. 'y' : 1 } ] # points. Lambda Forms A lambda statement is used to create new function objects and then return them at runtime. b['x'])) List Comprehension List comprehensions are used to derive a new list from an existing list. Essentially.Python en:More 104 statement if you are using proper indentation.sort() by providing a compare function created using lambda? points = [ { 'x' : 2. TODO Can we do a list. 4] listtwo = [2*i for i in listone if i > 2] print(listtwo) Output: . List comprehensions are ideal for such situations. total += pow(i. >>> powersum(2... If a ** prefix had been used instead. For example. all extra arguments passed to the function are stored in args as a tuple. the eval function is used to evaluate valid Python expressions which are stored in a string. total = 0 ...Python en:More 105 $ python list_comprehension.py [6. 10) 100 Because we have a * prefix on the args variable.. 4) 25 >>> powersum(2. the extra parameters would be considered to be key/value pairs of a dictionary. for i in args: . >>> def powersum(power. return total . as opposed to written in the program itself. >>> eval('2*3') 6 . we can generate a string containing Python code at runtime and then execute these statements using the exec statement: >>> exec('print("Hello World")') Hello World Similarly... power) .. Receiving Tuples and Lists in Functions There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. 3. Note that the original list remains unmodified. 8] How It Works: Here. *args): . A simple example is shown below. This is useful when taking variable number of arguments in the function. we derive a new list by specifying the manipulation to be done (2*i) when some condition is satisfied (if i > 2). '''Return the sum of each argument raised to specified power.''' ... exec and eval The exec function is used to execute Python statements which are stored in a string or file.. The advantage of using list comprehensions is that it reduces the amount of boilerplate code required when we use loops to process each element of a list and store it in a new list.. if you are very sure that you will have at least one element in a list you are using and want to check this. >>> i = [] >>> i. The interesting part is that you will have eval(repr(object)) == object most of the time. For example. Next. line 1. The repr function The repr function is used to obtain a canonical string representation of the object. the repr function is used to obtain a printable representation of the object. at this stage. However. we will discuss how to explore Python further. it is better to catch exceptions..append('item') >>> repr(i) "['item']" >>> eval(repr(i)) ['item'] >>> eval(repr(i)) == i True Basically. we have covered most of what you are ever going to use in practice. Most of the time. an AssertionError is raised. This is sufficient for you to get started with whatever programs you are going to create. then assert statement is ideal in this situation. in <module> AssertionError The assert statement should be used judiciously.Python en:More 106 The assert statement The assert statement is used to assert that something is true. >>> mylist = ['item'] >>> assert len(mylist) >= 1 >>> mylist. and raise an error if it is not true.pop() 'item' >>> mylist [] >>> assert len(mylist) >= 1 Traceback (most recent call last): File "<stdin>". When the assert statement fails. . delete or search for your contacts such as friends. then here's a hint. Hint (Don't read) Create a class to represent the person's information. Once you are able to do this. If you found that program easy. here are some ways to continue your journey with Python: .Python en:More 107 Previous Next Source: http:/ / www. swaroopch. here's another one: Implement the replace command (http:/ / unixhelp. Use the pickle module to store the objects persistently on your hard disk.-) . 1 anonymous edits Python en:What Next If you have read this book thoroughly till now and practiced writing a lot of programs. delete and modify the persons. modify. I would suggest that you tackle this problem: Create your own command-line address-book program using which you can browse. swaroopch. from simple string substitution to looking for patterns (regular expressions). com/ contact/ ) thanking me for this great book . Use the dictionary built-in methods to add. ac. php? oldid=1463 Contributors: Swaroop. If you still want directions on how to proceed. Details must be stored for later retrieval. If you have not done it already. Also. please consider making a donation. You have probably created some Python programs to try out stuff and to exercise your Python skills as well. This is fairly easy if you think about it in terms of all the various stuff that we have come across till now. family and colleagues and their information such as email address and/or phone number. Now. add. This step is optional but recommended. After that. Use a dictionary to store person objects with their name as the key. immediately send me a mail (http:/ / www. The question now is 'What Next?'. you can claim to be a Python programmer. you should. contributing improvements or volunteering translations to support the continued development of this book. then you must have become comfortable and familiar with Python. com/ mediawiki/ index. ed. This command will replace one string with another in the list of files provided. uk/ CGI/ man-cgi?replace). The replace command can be as simple or as sophisticated as you wish. announce/ t/ 37de95ef0326293d) • Python Papers (http:/ / pythonpapers. python. etc. python. com/ python-iaq. Tutorials. Books. com/ questions/ tagged/ python) Tips and Tricks • Python Tips & Tricks (http:/ / www. lang. org/ doc/ faq/ general/ ) • Norvig's list of Infrequently Asked Questions (http:/ / norvig. Papers. com/ group/ comp.Python en:What Next 108 Example Code The best way to learn a programming language is to write a lot of code and read a lot of code: • The PLEAC project (http:/ / pleac. web services. com/ recipes/ langs/ python/ ) is an extremely valuable collection of recipes or tips on how to solve certain kinds of problems using Python. html) is an excellent series of Python-related articles by David Mertz. com/ videos/ python) • GoogleTechTalks videos on Python (http:/ / youtube. org) . fyicenter. html) • Python Interview Q & A (http:/ / dev. google. html) • Official Python FAQ (http:/ / www. idyll. siafoo. The Dive Into Python book explores topics such as regular expressions. XML processing. html) • The Effbot's Python Zone (http:/ / effbot. python. html) • StackOverflow questions tagged with python (http:/ / beta. java2s. Videos The logical next step after this book is to read Mark Pilgrim's awesome Dive Into Python (http:/ / www. org) book which you can read fully online as well. stackoverflow. com/ results?search_query=googletechtalks+ python) • Awaretek's comprehensive list of Python tutorials (http:/ / www. Other useful resources are: • ShowMeDo videos for Python (http:/ / showmedo. org/ articles/ advanced-swc/ ) • Charming Python (http:/ / gnosis. com/ Code/ Python/ CatalogPython. org/ dev/ howto/ doanddont. awaretek. html) • Rosetta code repository (http:/ / www. net/ article/ 52) • Advanced Software Carpentry using Python (http:/ / ivory. net/ pleac_python/ index. org/ wiki/ Category:Python) • Python examples at java2s (http:/ / www. rosettacode. unit testing. This is a must-read for every Python user. in detail. cx/ publish/ tech_index_cp. htm) • Python Cookbook (http:/ / code. org/ zone/ ) • Links at the end of every Python-URL! email (http:/ / groups. diveintopython. com/ tutorials. com/ Interview-Questions/ Python/ index. Questions and Answers • Official Python Dos and Don'ts (http:/ / docs. activestate. sourceforge. PyGTK This is the Python binding for the GTK+ toolkit which is the foundation upon which GNOME is built. then follow the Official Python Planet (http:/ / planet. Qt is extremely easy to use and very powerful especially due to the Qt Designer and the amazing Qt documentation. wxPython This is the Python bindings for the wxWidgets toolkit. There are lots of choices for GUI using Python: PyQt This is the Python binding for the Qt toolkit which is the foundation upon which the KDE is built. you can create GUI apps fast. read the PyGTK tutorial (http:/ / www. qtrac. html). GTK+ works well on Linux but its port to Windows is incomplete. org) and/or the Unofficial Python Planet (http:/ / you can use it to create non-GPL software as well. There are many IDEs available for wxPython which include GUI designers as well such as SPE (Stani's Python Editor) (http:/ / spe. telecommunity. read the PyQt tutorial (http:/ / zetcode. pycs. eu/ pyqtbook. Windows. To get started. wxPython has a learning curve associated with it.python discussion group (http:/ / groups. To get started. PyQt is free if you want to create open source (GPL'ed) software and you need to buy it if you want to create proprietary closed source software. To install and use these libraries. python/ topics) is the best place to ask your question.lang. Eby's excellent EasyInstall tool (http:/ / peak. News If you want to learn what is the latest in the world of Python. it is very portable and runs on Linux. Mac and even embedded platforms. com/ DevCenter/ EasyInstall#using-easy-install). However. python. pygtk. then the comp. python. GTK+ has many quirks in usage but once you become comfortable. The documentation is yet to improve. google. org/ pypi) which you can use in your own programs. Starting with Qt 4. Graphical Software Suppose you want to create your own graphical programs using Python. planetpython. Make sure you do your homework and have tried solving the problem yourself first. You can create both free as well as proprietary software using GTK+. you can use Philip J. net/ ) and . and don't know whom to ask. org/ tutorial. org). com/ tutorials/ pyqt4/ ) or the PyQt book (http:/ / www. lang.Python en:What Next 109 Discussion If you are stuck with a Python problem. The Glade graphical interface designer is indispensable. Installing libraries There are a huge number of open source libraries at the Python Package Index (http:/ / pypi. Bindings are what allow you to write programs in Python and use the libraries which are themselves written in C or C++ or other languages. html). com/ group/ comp. This can be done using a GUI (Graphical User Interface) library with their Python bindings. TkInter is portable and works on both Linux/Unix as well as Windows. pythonpapers. Various Implementations There are usually two parts a programming language . net/ pypy/ dist/ pypy/ doc/ home. see Page 26 of the The Python Papers. We have been using the CPython software to run our programs. For more choices. aspx?ProjectName=IronPython) A Python implementation that runs on the . To get started.NET platform. It is referred to as CPython because it is written in the C language and is the Classical Python interpreter. The software is what actually runs our programs. see the GuiProgramming wiki page at the official python website (http:/ / www. There are also other software that can run your Python programs: Jython (http:/ / www. read the Tkinter tutorial (http:/ / www. You can create free as well as proprietary software using wxPython. This means you can use . sourceforge. you have seen a TkInter program at work. PyPy (http:/ / codespeak.Python en:What Next 110 the wxGlade (http:/ / wxglade. com) A Python implementation that is specialized for thread-based performance. To get started. com/ library/ tkinter/ introduction/ ). org) A Python implementation that runs on the Java platform. TkInter This is one of the oldest GUI toolkits in existence. . A language is how you write something. python. com/ Wiki/ View.NET libraries and classes from within Python language and vice-versa. net/ ) GUI builder. For a more detailed and comprehensive analysis. Java or C# in the above three implementations) Stackless Python (http:/ / www. if Linux is a chosen platform. If you have used IDLE. The second factor is whether you want the program to run only on Windows or on Mac and Linux or all of them. Volume 3. is whether you are a KDE or GNOME user on Linux. Summary of GUI Tools Unfortunately. It doesn't have one of the best look & feel because it has an old-school look to it. The first factor is whether you are willing to pay to use any of the GUI tools. codeplex. I suggest that you choose one of the above tools depending on your situation. IronPython (http:/ / www. com/ wxpython/ ). html) A Python implementation written in Python! This is a research project to make it fast and easy to improve the interpreter since the interpreter itself is written in a dynamic language (as opposed to static languages such as C.the language and the software. Importantly. read the wxPython tutorial (http:/ / zetcode. org/ ThePythonPapersVolume3Issue1. jython. This means you can use Java libraries and classes from within Python language and vice-versa. stackless. there is no one standard GUI tool for Python. The third factor. pdf). Issue 1 (http:/ / archive. TkInter is part of the standard Python distribution. org/ cgi-bin/ moinmoin/ GuiProgramming). pythonware. this is the the beginning of the end!. kernel. as they say. wikipedia. You can start automating your computer to do all kinds of previously unimaginable things or write your own games and much much more. php? oldid=1845 Contributors: Swaroop. It runs on almost all platforms. FLOSS are free for usage. presentation. then you are already familiar with FLOSS since you have been using Python all along and Python is an open source software! Here are some examples of FLOSS to give an idea of the kind of things that community sharing and building can create: • Linux. 2 anonymous edits Python en:Appendix FLOSS Free/Libre and Open Source Software (FLOSS) FLOSS (http:/ / en. and particularly the sharing of knowledge. This is the next generation web browser which is giving great competition to Internet Explorer. which itself is based on the concept of sharing. Best of all. you can just reboot your computer and run Linux off the CD! This allows you to completely try out the new OS before installing it on your computer. org) ] • Mozilla Firefox. org/ Tamarin:IronMonkey) which is a port of IronPython to work on top of a JavaScript interpreter which could mean that you can use Python (instead of JavaScript) to write your web-browser ("Ajax") programs. Summary We have now come to the end of this book but. it is giving competition to Microsoft Windows. [ Ubuntu Linux (http:/ / www. The extensions concept allows any kind of plugins to be used. modification and redistribution. This is an excellent office suite with a writer.a Python implementation written in Common Lisp and IronMonkey (http:/ / wiki. get started! Previous Next Source: http:/ / www. com) ] • OpenOffice. [ OpenOffice (http:/ / en:What Next 111 There are also others such as CLPython (http:/ / common-lisp. You are now an avid Python user and you are no doubt ready to solve many problems using Python. org/ wiki/ FLOSS) is based on the concept of a community. It is blazingly fast and has gained critical acclaim for its sensible and impressive features. It can even open and edit MS Word and MS PowerPoint files with ease. . sponsored by Canonical and it is the most popular Linux distribution today. [ Linux Kernel (http:/ / www. Now. Each of these implementations have their specialized areas where they are useful. spreadsheet and drawing components among other things. mozilla. This is a FLOSS operating system that the whole world is slowly embracing! It was started by Linus Torvalds as a student.org. net/ project/ clpython/ ) . If you have already read this book. This is a community-driven distribution. swaroopch. openoffice. So. ubuntu. com/ mediawiki/ index. org) ] • Ubuntu. It allows you to install a plethora of FLOSS available and all this in an easy-to-use and easy-to-install manner. swaroopch. net) So. check out the following websites: • linux. This list could go on forever. TORCS racing game. Drupal content management system for websites. org) ] • MySQL. To get the latest buzz in the FLOSS world. distrowatch. com) • DistroWatch (http:/ / www. 1 anonymous edits . Banshee audio player. who says open source ain't fun? .NET applications to be created and run on Linux. Xine . org/ products/ thunderbird) ] • Mono. This is the popular open source web server. freshmeat. This is an extremely popular open source database server. microsoft. [ Apache (http:/ / httpd.. Mac OS and many other platforms as well. mysql. ECMA (http:/ / www.. linux. [ MySQL (http:/ / www. PHP language. [ Mozilla Firefox (http:/ / handles more websites than all the competition (including Microsoft IIS) combined. that's right . newsforge. This is an open source implementation of the Microsoft . Microsoft . com) • LinuxToday (http:/ / www. ecma-international. Quanta+ editor. VIM editor.the movie player.com (http:/ / www. linuxtoday. html) ] This list is just intended to give you a brief idea . In fact.. KDevelop IDE. org/ en/ start. sourceforge. It is most famous for it's blazing speed. mozilla.NET platform. GIMP image editing program. Yes. This is a video player that can play anything from DivX to MP3 to Ogg to VCDs and DVDs to .. it is the most popular web server on the planet! It runs nearly more than half of the websites out there. net) • FreshMeat (http:/ / www. apache. com) ] • VLC Player.there are many more excellent FLOSS out there. such as the Perl language. mozilla. PostgreSQL database server. videolan. Windows. php? oldid=1580 Contributors: Swaroop. com) Visit the following websites for more information on FLOSS: • SourceForge (http:/ / www.-) [ VLC media player (http:/ / en:Appendix FLOSS 112 • Its companion product Thunderbird is an excellent email client that makes reading email a snap. Mozilla Thunderbird (http:/ / www. com) • NewsForge (http:/ / www. org/ vlc/ ) ] • GeexBox is a Linux distribution that is designed to play movies as soon as you boot up from the CD! [ GeexBox (http:/ / geexbox. It allows . com). com/ net) ] • Apache web server.NET (http:/ / www. It is the M in the famous LAMP stack which runs most of the websites on the internet. org). . mono-project. [ Mono (http:/ / www. go ahead and explore the vast. com/ mediawiki/ index. free and open world of FLOSS! Previous Next Source: http:/ / www. org/ products/ firefox). FreeBSD. I switched to DocBook XML using Kate but I found it too tedious. I had used Red Hat 9. Now I edit everything online and the readers can directly read/edit/discuss within the wiki website. Finally. In the sixth draft. So. I still use Vim for editing thanks to the ViewSourceWith extension for Firefox (https:/ / addons. The standard default fonts are used as well. which automatically provides syntax highlighting to all the program listings. . org) as the basis of my setup (http:/ / en:Appendix About 113 Python en:Appendix About Colophon Almost all of the software that I have used in the creation of this book are free and open source software. in Python of course. I was using KWord to write the book (as explained in the History Lesson in the preface). I had written a CSS document to give color and style to the HTML pages. but it produced very sloppy HTML from the document. com/ notes/ ). mediawiki. The standard fonts are used as well. Initially. I used Fedora Core 3 Linux as the basis of my setup. org/ en-US/ firefox/ addon/ 394) that integrates with Vim. However. I decided to use Quanta+ to do all the editing. swaroopch. I switched to OpenOffice which was just excellent with the level of control it provided for formatting as well as the PDF generation. Birth of the Book In the first draft of this book. The standard XSL stylesheets that came with Fedora Core 3 Linux were being used. mozilla. I discovered XEmacs and I rewrote the book from scratch in DocBook XML (again) after I decided that this format was the long term solution. Teenage Years Later. I'm using MediaWiki (http:/ / Linux as the foundation of my setup and in the sixth draft. I had also written a crude lexical analyzer. Now For this seventh draft. 99 • 22/02/2004 • Added a new chapter on modules. Added details about variable number of arguments in functions. • 0.it is more coherent and readable.15 • 28/03/2004 • Minor revisions • 1.97 • 13/02/2004 • Another completely rewritten draft.90 • 04/09/2008 and still in progress • Revival after a gap of 3.00 • 08/03/2004 • After tremendous feedback and suggestions from readers. swaroopch.0 • Rewrite using MediaWiki (again) • 1. • 0.10 • 09/03/2004 • More typo corrections.Python en:Appendix About 114 About The Author http:/ / www. Rewrote my DocBook setup from scratch. • 1. com/ mediawiki/ index. in DocBook XML (again).20 • 13/01/2005 • Complete rewrite using Quanta+ on FC3 with lot of corrections and updates. Book has improved a lot .5 years! • Updating to Python 3. including a crude-yet-functional lexical analyzer for automatic VIM-like syntax highlighting of the program listings. thanks to many enthusiastic and helpful readers. . swaroopch. • 0. com/ about/ Previous Next Source: http:/ / www. I have made significant revisions to the content along with typo corrections.98 • 16/02/2004 • Wrote a Python script and CSS stylesheet to improve XHTML output. Many new examples. • 1. • 1. php? oldid=236 Contributors: Swaroop Python en:Appendix Revision History • 1.12 • 16/03/2004 • Additions and corrections. com/ mediawiki/ index. • 0.60 • 21/11/2003 • Fully rewritten and expanded. swaroopch. • 0. • 0. • 0.91 • 30/12/2003 • Corrected typos. php? oldid=240 Contributors: Swaroop .15 • 20/11/2003 • Converted to DocBook XML.10 • 14/11/2003 • Initial draft using KWord.93 • 25/01/2004 • Added IDLE talk and more Windows-specific stuff • 0. → Previous → Back to Table of Contents Source: http:/ / www. Improvised many topics.90 • 18/12/2003 • Added 2 more chapters. • 0.92 • 05/01/2004 • Changes to few examples. • 0.Python en:Appendix Revision History 115 • 0. OpenOffice format with revisions.20 • 20/11/2003 • Corrected some typos and errors. org/ dev/ peps/ pep-3106/ • Built-in set class. idyll. 0/ reference/ datamodel.format() instead of % operator • http:/ / www. python. org/ dev/ library/ string.py. python. org/ dev/ peps/ pep-3131/ • print() function • http:/ / www. org/ 2008/ 4/ 18/ Indenting%20Python%20with%20VIM. python.Python en:Appendix Changes for Python 3000 116 Python en:Appendix Changes for Python 3000 • Vim and Emacs editors • http:/ / henry. etc. html#formatstrings • Dict method changes • http:/ / www. enigmacurry. python. python. org/ dev/ peps/ pep-3127/ • nonlocal statement • http:/ / www. python. org/ dev/ peps/ pep-3115/ • Abstract Base Classes • http:/ / www. org/ dev/ peps/ pep-3111/ • Integer Literal Support and Syntax • http:/ / www. html • Metaclasses • http:/ / www. precheur. python. org/ dev/ 3. org/ dev/ peps/ pep-3116/ • Exception handling . python. sourceforge. python. python. html • http:/ / www. org/ dev/ peps/ pep-3101/ • http:/ / docs. python.) • http:/ / ivory. com/ 2008/ 05/ 09/ emacs-as-a-powerful-python-ide/ • String . org/ dev/ peps/ pep-3104/ • Functions can take * argument (varargs) for lists and keyword-only arguments • http:/ / www. html#about-unicode • Non-ASCII identifiers allowed • http:/ / www. htm on Windows • Classes • http:/ / docs.unicode only • http:/ / docs. org/ dev/ peps/ pep-3107/ • Better explanation of modules. org/ dev/ peps/ pep-3119/ • Not sure if any changes required for New I/O • http:/ / www. python. 0/ tutorial/ introduction. python. net/ packages/ zip. packages and their organization (including __init__. org/ dev/ peps/ pep-3105/ • raw_input() becomes input() • http:/ / www. org/ dev/ peps/ pep-3102/ • Functions can have annotations (make a passing note?) • http:/ / www. python. org/ dev/ 3. in data structures chapter • Problem Solving • Use http:/ / gnuwin32. org/ articles/ advanced-swc/ #packages • String . python. ac. com/ Code/ Python/ CatalogPython. repr/ascii functions • getopt/optparse . org/ dev/ library/ json. rosettacode. html • http:/ / docs. python. python. org/ dev/ peps/ pep-3110/ • Standard Library . siafoo. python. html • http:/ / docs. org/ dev/ library/ warnings. com/ mediawiki/ index. html (important) • http:/ / docs. html • http:/ / www. org • http:/ / effbot. net/ article/ 52 Source: http:/ / www. python. html • Books & Resources • http:/ / www. com/ group/ comp. org. swaroopch. python. org/ dev/ library/ logging. coderholic. org/ dev/ 3.interesting additions • Reorganization : http:/ / www. html • http:/ / docs. html • eval.Python en:Appendix Changes for Python 3000 117 • http:/ / www. htm • Tips & Tricks • http:/ / www. 24/ man. com/ Interview-Questions/ Python/ index. announce/ t/ 37de95ef0326293d • Examples • http:/ / www. com/ free-python-programming-books/ • http:/ / pythonpapers. php? oldid=242 . python. org/ dev/ howto/ doanddont. python. python. org • http:/ / www. google. uk/ hppd/ hpux/ Users/ replace-2. com/ python-iaq. ed. connect. python. html • http:/ / www. org/ dev/ library/ pdb. org/ dev/ peps/ pep-3132/ • with statement • http:/ / www. lang. org • http:/ / dev. python. org/ dev/ peps/ pep-0352/ • http:/ / www. python. python. mobilepythonbook. fyicenter. org/ dev/ peps/ pep-0343/ • What Next? • Implement 'replace' • http:/ / unixhelp. python. html • Debugging • http:/ / docs. org/ dev/ peps/ pep-3109/ • http:/ / www. html • More • Unpacking can take * argument • http:/ / www. uk/ CGI/ man-cgi?replace • Mention use of PyPI • Q&A • http:/ / docs. 0/ library/ trace. org/ dev/ library/ urllib. org/ dev/ peps/ pep-3108/ • http:/ / docs. python.how to write a standard command-line program using python? • something like replace? • http:/ / hpux. python. java2s. org/ zone/ • Links at the end of every Python-URL! email • http:/ / groups. org/ doc/ faq/ general/ • http:/ / norvig. 0/ . org/ licenses/ by-sa/ 3.Python en:Appendix Changes for Python 3000 118 Contributors: Swaroop License Creative Commons Attribution-Share Alike 3.0 Unported http:/ / creativecommons.
https://de.scribd.com/document/50112117/Python-3-Tutorial-Byte-of-Python-v192
CC-MAIN-2019-18
refinedweb
36,083
69.38
I am not asking for the code im asking for the best way to do something. So I have at the moment this class: package com.definem.ws.alpha; public class Event { private enum EventTypes{ WCHARAK,CONNECT,DISCONNECT,CCHAR,DCHAR,DEVLOGIN } } Not really mutch an actually not using it. I found this code to be not tutorial worthy. The server is working (and you see a couple of people walk and such) but my question is: - What's the best way to implement a event system What I mean by this, you have an user that clicks on npc1 so the client will do this lets say: if(Player.clicked(npc1)){ Printwriter.println("talk" + 1); } how could i make an event system that is usable on server as client aswell. like PlayerDied,PlayerLoot,PlayerCommand,PlayerRevived do I use enums and print a that enum when you do something? - Do you store the npc's state(event) on the server on the client? This is for later, when you have 10 npc's on one map, you will need a thread i suppose and then put them in a hashmap itterate over that hashmap and set them all to a specific event ? - Do you create a Hashmap,list with all the connected user's on a specific map ? This is more of a desinger faulth of my server, I don't store all the connected user's anyware. I just let them connect but I don't see where they are and such. I wrote a small text beneath each question that explains all things and sometimes give's an example anwser but are there better solutions? Thanks,Arno(Cornetto456)
http://www.dreamincode.net/forums/topic/267924-world-server-best-way-to-handle-this/
CC-MAIN-2016-26
refinedweb
279
68.81
Sometimes I find code like the following (actually some class-wizards create such code): // C.h namespace NS { class C { void f(); }; } and in the implementation file: // C.cpp #include "C.h" using namespace NS; void C::f() { //... } All the compilers I tried accept that kind of code (gcc, clang, msvc, compileonline.com). What makes me feel uncomfortable is the using namespace NS;. From my point of view C::f() lives in the global namespace in an environment that has unqualified access to objects living in namespace NS. But in the compiler's opinion void C::f() lives in namespace NS. As all compilers I tried share that point of view they are probably right, but where in the standard is this opinion backed? Yes, the syntax is indeed legal, but no, your function actually does live in the namespace NS. The code you are seeing is actually equivalent to namespace NS { void C::f() { /* ... } } or to void NS::C::f() { /* ... */ } which may be more similiar to what you are used to. Because of the using-directive you can omit the NS part not only in calling code, but also in its definition. The Standard has an example that matches your code (after the bold emphasized part): 3.4.3.2 Namespace members [namespace.qual] 7 (7.3.1) ] So you may omit the initial part of the nested-name-specifier, but not any intermediate part.
http://www.dlxedu.com/askdetail/3/a482a095a9f8032a8cb5f8555b0cc464.html
CC-MAIN-2018-30
refinedweb
236
67.86