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
Created on 2011-03-24 20:43 by eric.araujo, last changed 2014-11-07 15:31 by rbcollins. A :) Typo s/self.path/self.patch/ I forgot to mention the rationale for this method: factor out common code to make sure the cleanup is not forgotten. Also kill debates about addCleanup vs. tearDown vs. try/finally. Needless to say the name is open: patch, replace, settempvalue, what have you. I'm attaching a draft patch for patch. Éric, is this patch implementing patch as you expected? This patch is not finished because there are many cases where patch can leave patched objects if it fails to unpatch. I'd like to ponder this a bit. Note that the patch is incorrect - fetching the attribute should not be done with getattr (this will trigger descriptors instead of fetching the underlying member) and should not be reset unconditionally (if the original was fetched from a base class the just deleting the patched member will restore the original). If we decide to do this I can provide a patch. A similar function already exists: test.support.patch Right, I helped with the writing of that at PyCon. The patch method would look very similar. test.support.patch is not something we want to make public (in that location). There’s also test.support.swap_attr... mock is being added to Python 3.3 as unittest.mock - so a helper TestCase.patch should delegate to unittest.mock.patch. It's kind of unfortunate that `mock.patch` is called `mock.patch`. I was thinking about this a bit more yesterday, and `mock.patch.object` is the one that I think would be most appropriate to put on `TestCase`, and the best name for it is probably `patch`, but doing that would be deathly confusing, so I don't think that's a real choice we can make. Why would mock.patch.object be the appropriate one to add to TestCase? patch.object is used orders of magnitude less than patch. It's slightly less confusing -- "Where do I patch" is the question that will never go away, and the fact that you don't have the `sys` module imported is a small hint that you should be doing patch(mymodule.sys, "path") not patch("sys.path"). Also, the fact that patch is more common doesn't reflect the fact that most of those times, patch.object would have worked as well, but it's longer to type (or people aren't as aware of it), since most of the time you're patching things in a module you've imported already (at least this is true of me, and I've started using patch.object whenever it works and only falling back on patch). Also, Twisted's TestCase (which already has a method to implement patch) is functionally equivalent to patch.object, not patch, in case you wanted a precedent. Well, people vote with their code and find mock.patch vastly more useful than patch.object... I actually agree with Julian here. I much prefer patch.object and do my best to avoid mock.patch. support.patch is also equivalent to patch.object and not patch. That doesn't change the fact that other people prefer mock.patch, of course. I think mock.patch is too "magical" for my taste. There is something I don't like about the dynamic import, even though I can't really tell you what it is :) With all due respect, your response pretty much ignored mine completely. That's OK, I've agreed with you that patch seems more common. I'll point you additionally though to the fact that Éric's original post also used patch.object's semantics, as does test.test_support.swap_attr and patch. I don't know how hard I can push here though, since again, this would be really confusing to have it have the same name. What about patch_object()? IMHO a setattr-like API seems the obvious choice here, so that's what I would expect. I haven't used mock, so I wasn't familiar with mock.patch, but after skimming through the mock docs a bit I think I have to agree with Julian and RDM. In addition, I'm not sure we need TestCase.patch now that we have already have mock.patch(.object) in the stdlib. If we still add it, it would probably make more sense as a "vanilla" patch that doesn't depend on mock. > a helper TestCase.patch should delegate to unittest.mock.patch Does it mean it will return MagicMocks? > patch.object would have worked as well, but it's longer to type If mock.patch requires a FQN to work the call might even be longer: patch('package.subpackage.module.function') vs patch.object(module, 'function', newfunc) (assuming "from package.subpackage import module", which is not uncommon if we are testing that specific module) > What about patch_object()? patchobj()? It maybe that patch.object is a more natural interface to the small sample of people commenting here, in which case great - that's what it's there for. However in common usage patch is used around two orders of magnitude more. I've seen large codebases with hundreds of uses of patch and only a handful of uses of patch.object. To support the *minor* use case and not the major use case in TestCase would be an inanity. A data point: at work I follow Pyramid testing guidelines which tell you not to import code under test at module level, but in your test functions, so that if you have an error your tests do start and you see the error under the test method. This means that I use mock.patch and not mock.patch.object, as my modules are not imported. I think those guidelines are horrible and I've told the pyramid folks that. There is a related issue for unittest that failing to import a test module (due to a failed import in the test module for example) should not kill the test run but should create a "failing test" that shows the problem. This is all wandering off topic however... So, what's the status of this? Move it forward or close this? Yes this is still relevant and needs doing (and is easy). The implementation should be similar to: def patch(self, *args, **kwargs): # lazy import from unittest.mock import patch p = patch(*args, **kwargs) result = p.start() self.addCleanup(p.stop) return result Plus tests and documentation. Hi ? Hi: Thanks Antoine for the link, and the quick answer; It seems that it is a sensible subject, adding or not this method, and what it should do. I wrote the patch anyway, but I must confess that somewhere it feels strange to me to add such a method in TestCase class. Nevertheless, it could be useful, and I will let other people decide this. :) My opinion is already here re: patch vs patch.object, so I won't repeat it, but @Michael, if you really want .patch, are you open to adding .patch_object as well? (Regardless, thanks for working on this Julien.) The patch (including lazy import) looks good, and the test looks ok too. I still think that patch should be the default instead of patch.object - although I wouldn't object to a second method (name?) if there was significant demand. FWIW I'd really like to be reducing the TestCase API not extending it - particularly since there are lots of good convenient ways of doing this already (not least mock.patch/mock.patch.object). So I'm -0.5 on adding this, as I don't see it adding value. That said, I'll happily review for correctness if there is consensus that we want it. Relatedly I'd like to find some way to let regular functions tie into cleanups automatically, so that we don't need helpers like this *at all*. That probably needs a PEP though. I. [padding to avoid UTF-8 error with bug tracker] See also Issue 22374, where an equivalent of “patch.object” is suggested as an example context manager for the “contextlib” documentation. If we added a plain function or context manager rather than a new TestCase method, it might avoid the worries about bloating the API. Then it could be a generic thing for any kind of testing, and not coupled with the “unittest” framework. About cleanup functions more generally, I think they already tie in well with the TestCase.addCleanup() API. Perhaps it could handle general context managers as well though, by inheriting an ExitStack.enter_context() method or providing an ExitStack attribute. +1 on a plain function or context manager. w.r.t. addCleanUp taking a context manager, that could be interesting - perhaps we'd want a thing where you pass it the context manager, it __enter__'s the manager and then calls addCleanUp for you.
http://bugs.python.org/issue11664
CC-MAIN-2014-52
refinedweb
1,490
76.22
Continuing where I left off Python generators in python imperative programming in python fp in python python lrm pure function python data generator python python functional or oop I have a bunch of list of links which I'm doing a specific function on each link, the function takes about 25 sec, I use selenium to open each and get the page source of it then do my function, however whenever I build the program and cancel the build, I will have to start all over again. Note:I get links from different webs sitemap. Is there a way to save my progress and continue it later on? this code will work. I assume you already have a function got getting links. I have just used a dummy one _get_links. You will have to delete the content of links file and need to put 0 in index file after every successful run. import time def _get_links(): return ["a", "b", "c"] def _get_links_from_file(): with open("links") as file: return file.read().split(",") def _do_something(link): print(link) time.sleep(30) def _save_links_to_file(links): with open("links", "w") as file: file.write(",".join(links)) print("links saved") def _save_index_to_file(index): with open("index", "w") as file: file.write(str(index)) print("index saved") def _get_index_from_file(): with open("index",) as file: return int(file.read().strip()) def process_links(): links=_get_links_from_file() if len(links) == 0: links = _get_links() _save_links_to_file(links) else: links = _get_links_from_file()[_get_index_from_file():] for index, link in enumerate(links): _do_something(link) _save_index_to_file(index+1) if __name__ == '__main__': process_links() list - Continuing where I left off Python, "is there a way to save my progress and continue it later on?" Yes, there is a way. On solution is to save your progress in a file. – Code-Apprentice Jan 25 at 17: I'm still new to writing scripts with Python and would really appreciate some guidance. I'm wondering how to continue executing my Python script from where it left off after a system restart. The script essentially alternates between restarting and executing a task for example: restart the system, open an application and execute a task, restart I would suggest that you write out the links to a file along with a date/time stamp of the last time it was processed. When you write links to the file, you will want to make sure that you don't write the same link twice. You will also want to date/time stamp a link after you are done processing it. Once you have this list, when the script is started you read the entire list and start processing links that haven't been processed in X days (or whatever your criteria is). Steps: - Load links file - Scrape links from sitemap, compare to existing links from file, write any new links to file - Find the first link that hasn't been processed in X days Process that link then write date/time stamp next to link, e.g. 12:00PM - Go back to Step 3 Now any time you kill the run, the process will pick up where you left off. NOTE: Just writing out the date may be enough. It just depends on how often you want to refresh your list (hourly, etc.) or if you want that much detail. Python course, Python course - how do i start where i left off yesterday?? I click the continue (37 %) button and it sends me to the beginning of the course , i can't see where i can Continuing where I left off on the last video, I finished the tip calculator and implemented Input Validation. If you have any questions about how I did things or have any feedback, let me know. You should save the links in a text file. You should also save the index numbers in another text file, probably initializing with 0. In your code, you can then loop through the links using something like: for link in links[index_number:] At the end of every loop, add the index number to the text file holding the index numbers. This would help you continue from where you left off. Dive Into Python, Chapter 9, XML Processing: This chapter covers Python's built-in XML Chapter 14, Test-First Programming: Continuing where Chapter 13 left off, this chapter Raising an exception during for loop and continuing at next index in python. Ask Question then raise it during an iteration and continue where I left off. Hands-On Penetration Testing with Python: Enhance your ethical , In other words, a Python generator is a function that returns us a generator a control to the caller and then continues its execution right from where it left off. So, continuing where I left off, I’m going to use Biopython to use the multiple sequence alignment software, MUSCLE, to create my MSA. Biopython, the Python library for bioinformatics, has several tools for manipulating and building sequence alignments. The Bio.AlignIO and the Bio.Align modules contain these tools. You can read and write Professional Python, Now, issue next(gen) again, as shown here: >>> next(gen) 1 Execution picks up where it left off, which means the first thing to run is the t continue statement. def Make Microsoft Edge to Continue where you left off Using Edge Settings: Open Edge Browser from start menu or Cortana search. Click on the three dot menu from the Top right corner to open Edge menu setting. Then click on settings. Then click on On startup and choose Continue Where you left off. Python: Real-World Data Science, When Python sees yield in a function, it takes that function and wraps it up in an it will start where it left off―on the line after the yield statement―instead of at the the generator will simply pick up at the most recent yield and continue to the Disable all extensions and check if Continue where you left off feature is working or not. Open menu and select Extensions under More tools. You will disable all extensions here and re-enable them one at a time to see which one is breaking Chrome. You can’t use the Incognito mode here because Continue, where you left off, doesn’t work in it. - "is there a way to save my progress and continue it later on?" Yes, there is a way. On solution is to save your progress in a file. - Of course there is. Python is essentially a Turing complete language. One possible way involves persisting to a file. - @Code-Apprentice. I didn't see your comment when I was posting mine :) - What exactly do you mean by ...I build the program and cancel the build...? Till Selenium takes over the control you can do it as commented by @Code-Apprentice But once Selenium takes over you can't. - The OP will probably need to save more than just an index. The list itself will no longer exist after the program terminates which will render the indexes meaningless. - do you mean writing the links in seperate file and save index number of where i left of on that file then crawl back that file ? - If you can save the links in a different file and also the index number, it would be great. This way, you do not have to read the sitemap always. - @Code-Apprentice If he saves the links in a file, the indexes would be useful. - yes, exactly. Saving the list of links will help, too. You should edit your answer to add that detail.
https://thetopsites.net/article/54370412.shtml
CC-MAIN-2021-25
refinedweb
1,256
70.13
I have been building Django based web application for a while now. One design/request I get often is a REST API. Once the model data is exposed in REST, one can truly build a complete separate frontend using things like Angular, react, and whatever you fancy. I have tried a couple times myself following this architecture. On one hand it gives a lot of flexibility and it looks nice, too ← front end technology is a lot of "{}", but it does look quite nice, and responsive, too. But on the other, REST is a thing few understands well except it is an API through which you can CRUD. Honestly, I don't even understand yet how authentication is done, what is a good balance between massaging data (in Tastypie's term, (de)-hydration) and exposing data model raw. Anyway, here I want to document a practice I use, a really rudimentary one, of making django model available as REST resource through Tastypie. Let's say you are building a site called mysite, and in it it has an application called myapp. So the file structure will be like gitroot/mysite/urls.py for site-level URLs, and gitroot/myapp/urls.py for app-level patterns. The confusing part is that myapp/urls.py will be folded into mysite/urls.py. So the thought is that a site can have multiple applications, each defining its own sub-pattern, while the mysite/urls.py has the first run of the match before handing URL to myapp/urls.py to match further. So it's a matter of matching order. Anyway. So building a REST can be broken down into 5 steps: Step 1: create an API varialbe name. Define an object v1_api in myapp/api.py. Name is not important at all. It is a Tastypie's Api object, therefore it comes with an army of capabilities: from tastypie.api import Api v1_api = Api(api_name='v1') Step 2: wire URL patterns v1_api defined in the previous step comes with a list of REST url patterns, and this is the beauty of Tastypie. So all we need to do is make these sub-patterns available through URL matching. As explained above, we need to wire these into mysite/urls.py: from myapp.api import v1_api as myapp_api <-- the variable we defined urlpatterns = patterns( # REST url(r'^mysite/api/myapp/', <-- pattern matching include(myapp_api.urls)), <-- sub-pattern handler Step 3: define your django DB model Nothing fancy here. Just the old school of data modeling. Step 4: transform DB model to a resource model REST speaks resources. Packaging a DB model into a resource is quite simple: from tastypie.resources import ModelResource from myapp.models import MyModel <-- import DB model v1_api = Api(api_name='v1') <-- we have seen this one (see "step 1") class MyModelResource(ModelResource): class Meta: queryset = MyModel.objects.all() <-- data set to display in list resource_name = "mymodels" <-- string used in REST url "/mymodels/" v1_api.register(MyModelResource()) <-- expose it to URL This is the simpliest example to make magic happen. What's more you can do with this now? .objects.all(): you don't have to expose everything. Any queryset is adequate. REST will allow filtering as well. So just need to be aware what your decision means. - de-hydrate: this is how you can massage your data set (essentially serializing and de-serializing) before you send data to user or taking data from data to DB. - foreign key reverse lookup Django defines reverse lookup by defining a related name in model: class Datacenter(BaseModel): pass class Cluster(BaseModel): datacenter = models.ForeignKey("Datacenter", related_name="clusters") <-- related_name! Consequently, DataCenterResource reverse lookup to cluster will be like this: class DatacenterResource(MyModelResource): clusters = fields.ToManyField("vx.api.ClusterResource", <-- FK resource attribute="clusters", <-- django related name step 5: enjoy Now go to mysite/api/myapp/mymodels ( mysite/api/myapp/ part is defined in "step 1", mymodels part is defined in "step 4"), it should show the queryset (defined in "step 4"). With REST, you can also do things like ?format=json or ?format=yaml, and ?a_model_field__gt= type of filtering. Cool huh!?
http://fengxia.co.s3-website-us-east-1.amazonaws.com/django%20to%20rest.html
CC-MAIN-2019-09
refinedweb
684
58.28
One can think of a 2.5D Delaunay triangulation as a 2D Delaunay triangulation where each vertex has a certain height. The difference to 3D Delaunay triangulations is that each (x,y)-coordinate pair has a unique z-coordinate in 2.5D. This makes the 2.5D version of Fade2D an ideal library for terrain triangulation, mapping software and surface metrology. Extra features of the 2.5D version are extraordinary fast computation of iso-contours and heights of arbitrary (x,y) coordinate pairs. The time consumption above has been measured with a desktop computer (Core i7 870, 3 GHz) Fade2D introduces the concept of Zones which enable extraction of certain areas of a triangulation. A zone can be defined through a closed, simple polygon. This works in 2D and 2.5D. Zones can be combined through set operations. The Delaunay meshing algorithm can refine a zone and the member triangles of zones can be retrieved. Fade2D can create a high quality triangular mesh inside an area defined by a Zone. When this feature is used in 2.5D then new vertices will automatically get height values. Fade2D is numerically robust and very fast. It triangulates one million points in less than 0.7 seconds. The diagram below shows that the practical run-time grows only linearly with the number of input points (uniformly distributed in a rectangular area for this benchmark). Fade2D is free of charge for personal non-commercial scientific research. The non-commercial 2D version is a full version. You can download it without registration. Everything we require is a link to Fade2D on your research page and that you cite Fade2D in scientific publications using it. All other applications (including commercial in-house usage) require a commercial license which guarantees maintenance, error corrections and personal support. The commercial 2.5D version of Fade2D is unlimited. In no case can we be made responsible for damages of any kind that arise in connection with the use or non-usability of our software or the information provided on our internet pages. If you don't accept these terms, you are not allowed to use our software. Using Fade2D for military research and applications is not accepted. Download Fade2D_v1.13.zip, unzip and start to play with the included examples. It works without installation for Windows and Linux developers. For a steep learning curve you should work through the provided examples. The examples are small and well documented and they draw the computed triangulations. Modify the source code and see what happens to get familiar with the library. The 2D online / pdf documentation and the 2.5D *.pdf documentation describe the two flavors of Fade2D. The classes have identical names but different namespaces: GEOM_FADE2D or GEOM_FADE25D. For most interfaces the difference between the two libraries is just the z-coordinate, thus there is a consistent look and feel which allows to switch between the two versions quickly. Fade2D, version 1.13, August 4th, 2013: Mesh generation (Delaunay Meshing) has been improved and two bugfixes have been made in the new IsoContours class: A message can be suppressed now and a numeric problem has been fixed. Fade2D,. Fade2D, version 1.11, June 14th, 2013: Non-public intermediate release with VS2008 support and a first version of the iso-contour feature. Fade2D,. Fade2D,. Fade2D, version 1.02, 9/2012: An additional debug library version for Windows has been added and the directory structure has been reorganized. Fade2D,.
http://www.geom.at/fade2d/html/
CC-MAIN-2013-48
refinedweb
575
58.58
So I keep hearing everyone saying "don't use exec, don't use eval, etc." But I was wondering if it's correct to use under this cirumstance. I have multiple functions that do the same thing for different operating systems: def doCoolStuff_Windows(): # do cool stuff here, windows edition def doCoolStuff_Darwin(): # do cool stuff here, mac edition def doCoolStuff(): system = platform.system() exec "doCoolStuff_%s()" % system Not trying to start a flame war, but... No, imo that's not really a valid use of exec when there's a really easy alternative and very rarely is there ever a good reason to use eval. You can simply setup a dispatch dict like so, or just use an if statement which would be simpler here. dispatch = {'Windows': doCoolStuff_Windows, 'Darwin': doCoolStuff_Darwin} def doCoolStuff(): system = platform.system() if system in dispatch: dispatch[system]()
https://codedump.io/share/G2EZKjwkBZiJ/1/is-this-a-correct-place-to-use-execeval
CC-MAIN-2017-39
refinedweb
140
54.83
Angular is an open-source framework built and maintained by Google, which is mainly used to develop Single-Page Applications (SPAs). It provides a structured approach towards creating front-end web applications. Originally known as AngularJS, the framework underwent a complete rewrite that resulted in Angular 2.0 (dropping the -JS suffix from the name). The versions that came after 2.0 (with Angular 8 being the latest, released just over two weeks ago) are incremental upgrades, thus it is possible to upgrade between them. However, AngularJS is a different beast and there is no easy way to upgrade from AngularJS from Angular 2.0+. In this article, we’re going to go through the steps necessary to start working with Angular. In order to keep this concise, there won’t be a lot of background. npm The first thing we need to do is get npm, a package manager for JavaScript libraries. On Windows, download and install Node.js. On Linux or Mac, use the relevant package manager for your system (e.g. apt-get on Linux Ubuntu), possibly along with the sudo command for elevated privileges, to install npm. Angular CLI Next, we need the Angular CLI to help us with our development workflow. Use npm to install it as a global tool, as follows (prefix this with sudo if using Linux or Mac): npm install -g @angular/cli npmto install the Angular CLI. ng is the command-line tool we just installed. Use ng --version to make sure it’s in working order: ng --version, we can see some “Angular CLI” ASCII art and other information. This means that it’s working fine. Creating a Project Use ng new to create an Angular app from a template. You’ll be asked some questions to determine what features you need, but for now just press ENTER at each question to use the defaults. ng new myproject ng new myprojectcreates a folder called myproject with the Angular files in it. Press ENTER when asked questions to use defaults for now. Note: when I first ran this, I got an error along the lines of “ EPERM: operation not permitted, unlink“, even when using an elevated command prompt. The problem was likely caused by an old version of npm I had on my machine before, and I fixed it by running npm cache clean --force. Running the application Go into the project directory you’ve just created (e.g. myproject), and use ng serve to run the web application you just generated: cd myproject ng serve ng serveruns a web server that you can use to access the running web application. Look in the output for the endpoint to use in your browser. When ng serve is done building the project, it runs a web server hosting the web application. The output tells you where to access it, in this case. Put that in your browser’s address bar, and you should see the homepage from the project template that we set up earlier: Data Binding Illustration We’ve created and run a web application using Angular, so we’re done in terms of getting started. However, let’s make a small change to the web application to get a little more comfortable with it and see something working. With ng serve still running, locate the src/app directory under your project’s root directory. Using a text editor or IDE of your choice, add the lines highlighted below to app.component.html: <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <img width="300"=="> <input type="text" [(ngModel)]="name" /> <br />{{ name }} <> Then, add the lines highlighted below to app.module.ts: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } When ng serve detects these changes, it should reload the web application (in your browser) automatically, so you don’t need to stop and start it again whenever you change something. Thanks to the changes we made, we now have a text input box under the Angular logo. When you type in it, the text below it is synchronised with it. The changes we made might seem alien at first, but we’ve actually used two important features of Angular: data binding and string interpolation. While explaining these is beyond the scope of this introductory article, I hope that seeing this power at work — with such a small change — has given a taste of why Angular is so useful.
http://gigi.nullneuron.net/gigilabs/getting-started-with-angular-8/
CC-MAIN-2020-05
refinedweb
775
62.17
CoffeeScript 1.7 Released: Adds Chaining Without Parenthesis, Multiline Strings and More - | - - - - - - Read later My Reading List Jeremy Ashkenas has released version 1.7 of CoffeeScript, and with it introduced some highly anticipated changes to the popular JavaScript transpiler. Version 1.7 includes one of the most popular requests for the language; support for chaining without parenthesis. Prior to the 1.7 releases, if a developer wanted to chain functions, they had to use parenthesis, which are not required for functions in CoffeeScript. // prior to 1.7 - parenthesis required to chain $('#element').addClass('active').css({ left: 5 }); // as of 1.7 - no parenthesis $ '#element' .addClass 'active' .css { left: 5 } This release also introduces proper support for multiline strings. In previous versions of CoffeeScript, herestrings (or string literals) while intended to preserve new lines and whitespace, would ignore the `\` operator which is meant to designate that two strings should be preserved on the same line. As of 1.7, this is fixed, allowing the developer to cleanly format multiline strings in CoffeeScript. console.log '''The quick brown fox jumped over the \ lazy dog''' // prior to 1.7 outputs The quick brown fox jumped \nover the lazy dog // as of 1.7 now outputs The quick brown fox jumped over the lazy dog Expansion has also been added to array destructuring, which had previously been the longest open issue on the CoffeScript repo. # get the last item in the animals array animals = [ 'cat', 'dog', 'hippopotamus' ] # prior to 1.7 hippo = animals[animal.length - 1] # as of 1.7 [..., hippo] = animals # ...both of which transpile to... hippo = animals[animals.length - 1]; New convenient mathematical operators are present as well in the addition. There is the new power operator, floor division, and a modulo operator (returns the remainder of a division operation). # power 2 ** 2 # transpiles to... Math.pow(2, 2); # floor division 2 // 3 #transpiles to... Math.floor(2 / 3) # modulo 2 %% 3 #transpiles to... var __modulo = function(a, b) { return (a % b + +b) % b; }; __modulo(2, 1); Other enhancements include bringing CoffeeScript in line with Node.js so that its require statement doesn't automatically run every file in a directory, but behaves like Node and only runs the index.coffee file. The majority of the work on the 1.7 release (and in fact most of CoffeeScript for the past few years) is done by members of the community. "There are over 100 developers who have contributed to and had patches merged into CoffeeScript" said Jeremy. "Whatever adoption CoffeeScript has enjoyed has happened because the idea appeals to JavaScript programmers." In regards to work on the 1.7 release, Jeremy sent special thanks to Michael Srb for his contributions. CoffeeScript has indeed enjoyed immense popularity, peaking at one point as the 10th most popular project on GitHub. It's also seen support in frameworks such as Ruby on Rails (since version 3.1), and is supported in Microsoft's Visual Studio via the Web Essentials plugin. Additionally JavaScript creator Brenden Eich has expressed how CoffeeScript influenced his thoughts on the future of JavaScript. GitHub user stefanpenner noted that in CoffeeScript “…ES6 import export would be killer…” Jeremy does address ES6 features in CoffeeScript saying, CoffeeScript is mostly finished — has been quite stable for a couple of years now — but will continue to grow in small ways in the future. Some examples are: support for new JavaScript features as they land, further improved source map support, more polish for the literate programming style and more streamlining for the internals of the compiler. At one point there, was a Kickstarter project to re-write the CoffeeScript compiler. The project has since been successfully funded and is dubbed CoffeeScriptRedux. Jeremy sees the creation of new compilers as a benefit for CoffeeScript saying, " The more compilers that successfully target a given language — the healthier that language is. It's to CoffeeScript's benefit to have multiple independent compilers." The 1.7 release is available immediately via GitHub, or the official CoffeeScript site. Rate this Article - Editor Review - Chief Editor Action
https://www.infoq.com/news/2014/02/coffescript-17
CC-MAIN-2017-09
refinedweb
675
57.06
Several folks requested the source code for the ASP.NET AJAX drag-drop example I alluded to in an earlier blog post. Here are the key parts of it (along with some explanations of how it works) that you can borrow using editor inheritance--I mean, cut-and-paste. The first thing you must do to implement rich drag-drop scenarios in ASP.NET AJAX is implement the IDragSource interface defined in PreviewDragDrop.js. In my example, the user drags and drops color swatches, so I derived a class from Sys.UI.Behavior and implemented IDragSource in the derived class to create a "drag behavior" that I can attach to DOM elements. The drag behavior's initialize method registers a handler for mousedown events. The handler initiates a drag-drop operation by calling Sys.Preview.UI.DragDropManager.startDragDrop, which is implemented in PreviewDragDrop.js. It also creates a drag visual by cloning the DOM element being dragged and setting the clone's opacity to 0.4. Here's the source code for the drag-behavior class: Custom.UI.ColorDragSourceBehavior = function(element, color){ Custom.UI.ColorDragSourceBehavior.initializeBase(this, [element]); this._mouseDownHandler = Function.createDelegate(this, this.mouseDownHandler); this._color = color; this._visual = null;} Custom.UI.ColorDragSourceBehavior.prototype ={ // IDragSource methods get_dragDataType: function() { return 'DragDropColor'; }, getDragData: function(context) { return this._color; }, get_dragMode: function() { return Sys.Preview.UI.DragMode.Copy; }, onDragStart: function() { }, onDrag: function() { }, onDragEnd: function(canceled) { if (this._visual) this.get_element().parentNode.removeChild(this._visual); }, // Other methods initialize: function() { Custom.UI.ColorDragSourceBehavior.callBaseMethod(this, 'initialize'); $addHandler(this.get_element(), 'mousedown', this._mouseDownHandler) }, mouseDownHandler: function(ev) { window._event = ev; // Needed internally by _DragDropManager this._visual = this.get_element().cloneNode(true); this._visual.style.opacity = '0.4'; this._visual.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=0.4)'; this._visual.style.zIndex = 99999; this.get_element().parentNode.appendChild(this._visual); var location = Sys.UI.DomElement.getLocation(this.get_element()); Sys.UI.DomElement.setLocation(this._visual, location.x, location.y); Sys.Preview.UI.DragDropManager.startDragDrop(this, this._visual, null); }, dispose: function() { if (this._mouseDownHandler) $removeHandler(this.get_element(), 'mousedown', this._mouseDownHandler); this._mouseDownHandler = null; Custom.UI.ColorDragSourceBehavior.callBaseMethod(this, 'dispose'); }} Custom.UI.ColorDragSourceBehavior.registerClass('Custom.UI.ColorDragSourceBehavior', Sys.UI.Behavior, Sys.Preview.UI.IDragSource);(); Converting a DOM element (such as a DIV) into a drag source is now a simple matter of newing up a ColorDragSourceBehavior, attaching it to the DOM element, and calling its initialize method: var source1 = new Custom.UI.ColorDragSourceBehavior ($get('RedDragSource'), 'red');var source2 = new Custom.UI.ColorDragSourceBehavior ($get('GreenDragSource'), 'green');var source3 = new Custom.UI.ColorDragSourceBehavior ($get('BlueDragSource'), 'blue'); source1.initialize();source2.initialize();source3.initialize();(); The next step is to implement PreviewDragDrop.js's IDropTarget interface. To accomplish this, I derived another class from Sys.UI.Behavior and implemented IDropTarget in the derived class. The implementation is pretty straightforward. In my example, the IDropTarget.drop method, which is called when a drop occurs, sets the background color of the DOM element to which the drop-target behavior is attached to the color being dragged (that is, the color encapsulated in the drag source). It also implements "drag highlighting" by setting the drop target's background color to light gray when a cursor carrying a payload enters the drop target and restoring the original color when the cursor leaves. Here's the drop-target behavior class: Custom.UI.ColorDropTargetBehavior = function(element){ Custom.UI.ColorDropTargetBehavior.initializeBase(this, [element]); this._color = null;} Custom.UI.ColorDropTargetBehavior.prototype ={ // IDropTarget methods get_dropTargetElement: function() { return this.get_element(); }, canDrop: function(dragMode, dataType, data) { return (dataType == 'DragDropColor' && data); }, drop : function(dragMode, dataType, data) { if (dataType == 'DragDropColor' && data) { this.get_element().style.backgroundColor = data; } }, onDragEnterTarget : function(dragMode, dataType, data) { if (dataType == 'DragDropColor' && data) { this._color = this.get_element().style.backgroundColor; this.get_element().style.backgroundColor = '#E0E0E0'; } }, onDragLeaveTarget : function(dragMode, dataType, data) { if (dataType == 'DragDropColor' && data) { this.get_element().style.backgroundColor = this._color; } }, onDragInTarget : function(dragMode, dataType, data) { }, // Other methods initialize: function() { Custom.UI.ColorDropTargetBehavior.callBaseMethod(this, 'initialize'); Sys.Preview.UI.DragDropManager.registerDropTarget(this); }, dispose: function() { Sys.Preview.UI.DragDropManager.unregisterDropTarget(this); Custom.UI.ColorDropTargetBehavior.callBaseMethod(this, 'dispose'); }} Custom.UI.ColorDropTargetBehavior.registerClass('Custom.UI.ColorDropTargetBehavior', Sys.UI.Behavior, Sys.Preview.UI.IDropTarget);(); The final task is to create a ColorDropTargetBehavior and attach it to a DOM element. In my example, the drop target is a DIV whose background color can be set by dropping a color swatch into it: var target = new Custom.UI.ColorDropTargetBehavior ($get('DropTarget'));target.initialize(); The end result is a compelling demo in which users can drag color swatches around the page and change the background color of drop targets with simple drag-drop operations. It still feels weird to me to be deriving classes and implementing interfaces in JavaScript, but you play the hand you're dealt. I frequently tell audiences that the Microsoft AJAX Library has lots of features that aren't exposed in the ASP.NET AJAX Extensions and that to get the most out of ASP.NET AJAX, you have to understand what's on the client side and be willing to program it directly. This is a sterling example of the kind of features you can implement by going under the hood and familiarizing yourself with the client-side framework. If you would like to receive an email when updates are made to this post, please register here RSS Here is a quick post on some great ASP.NET AJAX focused content that has been published recently: ASP.NET 摘要在ASP.NETAJAX中实现拖放功能使用来自于Codeplex的ASP.NETAJAXControl...AJA... AJAX ASP.NETAJAX(Atlas)拖放(Drag Hi Jeff, thanks for the source code you put it on the site. Out of all the samples I've seen your's is one of the few that works out of the box and clear enough for a novice to grasp. i've got a question though...what i would like to do is to define an area within which an object can move on the screen. in your demo you have a defined drop target. if the object is dragged elsewhere it is simple put back to its starting point. i'm looking to do something a little bit more sophisticated. basically i don't want the object i'm dragging to move beyond a certain boundary (defined by a DIV for example). How can I achieve this? I can put code in the onDrag to see check the current location of the object but I'm not sure how to stop it from moving...I assume this is possible and if so you're someone who would know to do it :) any ideas, thanks again for the talks/workshops at devweek I'm pretty adept at ASP.NET's server side model, but I'm just getitng my hands wet in the client side, and I must be missing something huge here. One of the guys claims this is out of the box, but not quite lol. I get the idea of inheritance, your event model, I think I ge the concepts, but I don't know where to put this stuff! it looks like the first 90% of the first grey block, for example, defines a class, and has an orphan line of code at the end that initiates a behavior- can you create statements in javascript outside of a method? is that entire grey box inside of a method? Where am I going to put all these things, and where do I reference what? You can do basically anything in JavaScript (including providing code outside a method), because in JavaScript, there are few rules. You can just paste all the code into a <script> block if you want and it should work. For better form, put the two big blocks in a separate JS file and then use a script reference in ScriptManager to download the file. The two little blocks are best embedded in the page itself (ideally in a pageLoad method). ImplementingDrag-DropinASP.NETAJAX 美化文件上传框 Can you please post the demo link, I am not able to get this to work? Thank you SR Is any of this still relevant? Th more digging I do to try to get this to work, the more it looks like this is too out of date to even be modified into a usable state. I can't find anyway to access Sys.Preview at all.。本文将总结并简要分析ASP.NET AJAX (Atlas) 中拖放功能的6种不同的实现方法,希望能够帮助朋友们选出最适合实际需求的方法。其中第1到第4种方案,在我的《ASP.NET Ajax程序设计——第I卷:服务器端ASP.NET 2.0 AJAX Extensions与ASP.NET AJAX Control Toolkit》一书中有详细介绍(4月出版),本文中的代码和图示也节选自该书。 Thanks for the example. It is one of the better ones I have found so far though, in order to get it to work I had to remove the extra (); at the end of each code block and also add Type.registerNamespace("Custom.UI"); VS2003 / .NET 2.0 / Ajax Extensions 1.0 / Futures May 2007 Did anyone ever post the source code for this? I have been searching for the code for the Go Deep with AJAX mix 07 session, but haven't found it anywhere. Excellent example - had to fiddle with the script includes to get it to work though. VS2005 / .Net 2.0 / Futures May 2007 I'm trying to get this to work: attaching to an item in a datarow, but I don't seem to be able to get it to work. Any ideas? void gvTestGV_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1"); Literal lit = (Literal)e.Row.FindControl("myliteral"); string code = string.Format("(function () {{ var fn = function () {{ var source1 = new Custom.UI.ColorDragSourceBehavior($get('{0}'), '{1}'); source1.initialize(); Sys.Application.remove_load(fn); }}; Sys.Application.add_load(fn); }})();", lb.UniqueID , lb.ClientID + "reD"); System.Diagnostics.Debug.WriteLine("Unique ID : " + lb.UniqueID); ScriptManager.RegisterStartupScript(this, typeof(Page), "unique2", code, true); } } would sure be nice if this was a coherent working example instead of code snippets. using the user comments i was able to get the script to run without error. since there is no html/aspx/asp example i don't know how to tie it to the dom elements... ASP.NET AJAX (Atlas) 拖放(Drag hallo jeff, and thanks for this info. toatally agree, "one of the better examples". Question: Why is the clone x/y co-ordinate randomly offset when this is used in a a frame that can scroll. If the page is loaded first time and not scrolled, it works fine. Scroll and all the co-ordinates are off by what appears a random amount. Is there anyway to create client side (javascript only) ReorderList using MS Ajax toolkit? e.g, you would This is so typical. Someone makes a blog entry, stating, 'gee, so many of you have asked for the source. Here's NOT THE SOURCE! So you can write 250 comments asking, 'where's the source' and I can laugh at you!' Pathetic. Dude, you have wasted however many hours you spent on this drivel, because w/o the source, A LINK TO A ZIP FILE, GET IT?', you have just wasted your time, wasting our time. Multiply your time times 2000 people who have come here, and this is the damage you have done to the cosmic fabric. If you're not part of the solution (and this article ain't), you're part of the problem. Learn to WRITE! 摘要 在ASP.NETAJAX中实现拖放功能 使用来自于Codeplex的ASP.NETAJAXC... It is good that someone writes articles which really matters something. Thank you for this article, it's full of knowledge which is hard to find in tons of rubbish in our famous world wide web. Regards and good luck! Interesting info Thanks for article <a href="">收缩膜机</a> <a href="">收缩膜机</a> <a href="">case maker</a> <a href="">封面机</a> <a href="">书壳机</a> <a href="">吹膜机</a> <a href="">制袋机</a> <a href="">夹链粘合制袋机</a> <a href="">die cutting machine</a> <a href="">制袋机</a> 香港公司注册完成后,日后的管理比较简单。公司在港成立,周年日翌日起至一年,每年必须向公司注册处和税务局周年申报并商业登记一次,此费用随政府的调整而浮动。具体如下: 一、须提供的资料如下: 老客户 (1) 亲自签署确认书 (2) 亲自签署周年申报文件 新客户 (1) 商业登记证复印件; (2) 注册证书复印件; (3) 公司章程1本; (4) 成立公司全套法定文件复印件(包括:表格D1、D3、R1); (5) 股东或董事身份证明文件复印件(以递交到政府备案的为准) (6) 改股、增资、改名相关文件复印件(如未有涉及到相关事项的,可不必理会此条) (7) 亲自签署确认书 (8) 亲自签署周年申报文件 ASP.NET AJAX Documentation Update, Videos and Cool Articles 优秀翻译公司 Hi, I write a small article:
http://www.wintellect.com/cs/blogs/jprosise/archive/2007/03/15/asp-net-ajax-d-d-source.aspx
crawl-002
refinedweb
2,019
50.12
Related Tutorial Creating a Global Event Bus event bus / publish-subscribe pattern, despite the bad press it sometimes gets, is still an excellent way of getting unrelated sections of your application to talk to each other. But wait! Before you go waste a few more precious KBs on another library, why not try Vue’s powerful built-in event bus? As it turns out, the event system used in Vue components is just as happy being used on its own. Initializing The first thing you’ll need to do is create the event bus and export it somewhere so other modules and components can use it. Listen closely. This part might be tricky. import Vue from 'vue'; export const EventBus = new Vue(); What do you know? Turns out it wasn’t tricky at all! All you need to do is import the Vue library and export an instance of it. (In this case, I’ve called it EventBus.) What you’re essentially getting is a component that’s entirely decoupled from the DOM or the rest of your app. All that exists on it are its instance methods, so it’s pretty lightweight. Using the Event Bus Now that you’ve created the event bus, all you need to do to use it is import it in your components and call the same methods that you would use if you were passing messages between parent and child components. Sending Events Say you have a really excited component that feels the need to notify your entire app of how many times it has been clicked whenever someone clicks on it. Here’s how you would go about implementing that using EventBus.emit(channel: string, payload1: any, …). - I’m using a single-file-component here, but you can use whatever method of creating components you’d like. <template> <div class="pleeease-click-me" @</div> </template> <script> // Import the EventBus we just created. import { EventBus } from './event-bus.js'; export default { data() { return { clickCount: 0 } }, methods: { emitGlobalClickEvent() { this.clickCount++; // Send the event on a channel (i-got-clicked) with a payload (the click count.) EventBus.$emit('i-got-clicked', this.clickCount); } } } </script> Receiving Events Now, any other part of your app kind enough to give PleaseClickMe.vue the attention it so desperately craves can import EventBus and listen on the i-got-clicked channel using EventBus.$on(channel: string, callback(payload1,…)). // Import the EventBus. import { EventBus } from './event-bus.js'; // Listen for the i-got-clicked event and its payload. EventBus.$on('i-got-clicked', clickCount => { console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`) }); - If you’d only like to listen for the first emission of an event, you can use EventBus.$once(channel: string, callback(payload1,…)). Removing Event Listeners Once a part of your app gets tired of hearing the amount of times PleaseClickMe.vue has been clicked, they can unregister their handler from that channel like so. // Import the EventBus we just created. import { EventBus } from './event-bus.js'; // The event handler function. const clickHandler = function(clickCount) { console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`) } // Listen to the event. EventBus.$on('i-got-clicked', clickHandler); // Stop listening. EventBus.$off('i-got-clicked', clickHandler); - You could also remove all listeners for a particular event using EventBus.$off(‘i-got-clicked’) with no callback argument. - If you really need to remove every single listener from EventBus, regardless of channel, you can call EventBus.$off() with no arguments at all. 👉 Now go forth and be eventful!
https://www.digitalocean.com/community/tutorials/vuejs-global-event-bus
CC-MAIN-2020-34
refinedweb
588
68.57
People often complain that WordPress is slow. Whether or not this is true depends on many factors, but if we can see server resources inside the WordPress dashboard, then it may give some insight about how well our WordPress installation is operating. In this tutorial, we will be crafting a plugin to show server status including disk space, memory consumptions, CPU usage, and process usage. We will also learn about WordPress cache to avoid querying these metric over and over and we will also cover WordPress cron jobs to generate this data automatically. The administrator dashboard, by default, presents us with a couple of blocks called widgets. These include: The widgets can be re-ordered by preference, and can be shown or hidden - generally speaking, the dashboard is customizable. Since widgets are very flexible and available right on the first screen of the administrator screen, we can use them to show server resource: disk status, RAM usage, CPU usage, and operating system information. We will call these resources "metrics" for short. Throughout this serious we will learn the Dashboard Widgets API and Roles and Capabilities to make these widgets available to some users because the data could be sensitive. To do that, we will also learn some basic Linux commands to pull server information and seed to our widget dashboard. We will use Transients API to cache these data. Cronjobs will be leveraged to automatically pull these data instead of getting them on demand on every request. The work of our plugin is inspired by Linux Dash. Our plugin supports nine kinds of metrics. As a result, we will have nine dashboard widgets. - Server information: the operating system, the Linux kernel, the up time, etc. - CPU load: average load of CPU in 1, 5 and 15 minutes - RAM usage of physical RAM and swap file - Disk usage - Installed software - Processes - Ethernet - Network performance - IO stat Requirements - A Linux environment. Mac OS X is still an option but some of the commands to check the above metrics aren't available, so if you receive a command not found error, then you know there is no Mac support for that command. - Basic understanding of the shell - Basic WordPress plugin understanding. The Plugin Skeleton Structure Let's create a simple plugin and call it Server Dashboard. We will start with some basic things. A traditional Hello World will help you have a taste of adding a widget to dashboard. It's easy, actually. Creating a folder call Server Dashboard inside wp-content/plugins, and a file serverdashboard.php. The folder layout looks like this. Just focus on the main file and ignore the bin, tests, widgets and so on. Use this code for serverdashboard.php <?php /* Plugin Name: Server Dashboard Version: 0.1-alpha Description: Server Status Dashboard Author: Vinh Author URI: Plugin URI: Text Domain: Server Dashboard Domain Path: /languages */ namespace AX\StatBoard; require_once plugin_dir_path( __FILE__ ) . '/widget.php' ; class Dashboard { protected static $_instance=NULL; function __construct() { } /** * Create an unique instance throught the app */ public static function instance() { return self::$_instance = self::$_instance ?: new self(); } /** * Start to setup hook */ public function run() { add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) ); } function remove_dashboard_widgets() { } function add_dashboard_widgets() { syslog(LOG_DEBUG, "Run"); wp_add_dashboard_widget( 'hello_world_dashboard_widget', // A Slug to identify this widget 'Hello World', //Widget title function () { echo 'Hey, I\'m the body of widget. Thanks for bring me to the life.'; } //function to render content of widget, I'm using a closure here ); } } Dashboard::instance()->run(); ?><br><br>I used namespace AX\StatBoardto avoid name collision with different plugins class, function name of themes, and other plugins. runto register hook or filter with WordPress. To add a widget, we have to hook into action wp_dashboard_setup. This hooks grant us access to Dashboard's related customization option. It enables us to add or remove the dashboard widget from WordPress. wp_add_dashboard_widgetto register a widget. It requires arguments in this order: - Widget ID is used to identify slug for your widget. This slug is used when rendering CSS id,class and as keys in widget array. - Widget Title displays on title of widget box - Callback to render the content of widget. It should output content directly, doesn't need to return. Most of time, we will encounter callbacks as a single function, an anonymous function, an array of object and method, or array of class and static method.Refresh your dashboard. Our plugin shows its widget. Notice the idof widget div element. Let's advance this. We will show a pie chart with some dummy data. To keep thing simple, I'll be using the Google Chart API. We will extensively use it later for server metrics because it's better to visualize this kind of data. If you don't like Google Chart, you can get rid of it and put your favorite chart library. Remember that this is a tutorial, so don't limit yourself - use whatever it is you're comfortable with using! We need to load the Google Chart script. Change your run() method to register one more hook. public function run() { add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) ); add_action( 'admin_enqueue_scripts', array($this, 'add_asset')); } admin_enqueue_scripts is the action that you need to hook into for adding your own script in administrator dashboard. We will add one more method call add_asset in our class to handle script loading. The implement of add_asset. /** * Add javascript */ function add_asset() { wp_enqueue_script( 'google-chart', '' ); }We have the chart library. Now we have to render it inside our dashboard. You can play around with Google Chart. We will just re-use their example now. function add_dashboard_widgets() { syslog(LOG_DEBUG, "Run"); wp_add_dashboard_widget( 'hello_world_dashboard_widget', // A Slug to identify this widget 'Hello World', //Widget title function () { echo <<<'EOD' Hey, I'm the body of widget. Thanks for bring me to the life. <div id="hello_piechart"> </div> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); var options = { title: 'Sample Pie Chart', is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('hello_piechart')); chart.draw(data, options); } </script> EOD; } //function to render content of widget, I'm using a closure here ); <br><br>We simply add one more div element with id hello_piechart and render chart into that element. Let's see what we got now: Now that we know how to add our own widget block to the dashboard, and now that we know how to get Google Chart to render information, we can combine the two in order to show more information. In next section, we will learn how to grab server metrics, and render content for each type of server metric that we've previously discussed. Pulling Server Metrics When pulling server metrics, we will use the command of Linux to get this information. In PHP, we can use backtick `` or shell_exec to invoke a shell command, and retrieve the output. We can parse the output to get server data. For example, to get disk usage status we can use command df -h. We know the format of output, so we can parse it to get what we want. $df = `df -h`; $df = explode("\n", $df); if (is_array($df) && count($df)>=2) { array_shift($df); //Get rid the first line $df = array_map(function ($line) { if (empty($line)) { return NULL; } $segment=preg_split('/\s+/', $line); return array( 'filesystem' => $segment[0], 'size' => $segment[1], 'used' => $segment[2], 'available' => $segment[3], 'use_percent' => $segment[4], ); }, $df); var_dump($df); } Cleaning Up with AWKTo help cleanup the output right from the shell command, we can combine with awk. That link looks scary with lots of information but we will just being using a very small amount of it in this tutorial. Explaing awk is out of scope of this tutorial. [command_we_run] | awk ' { print $1, $3, ...}'. ☁ Server Dashboard [master] ls -lh total 32 -rw-r--r-- 1 kureikain staff 2.6K Apr 11 00:46 Server Dashboard.php drwxr-xr-x 3 kureikain staff 102B Mar 29 01:27 bin -rw-r--r-- 1 kureikain staff 98B Apr 5 18:53 loader.js -rw-r--r-- 1 kureikain staff 321B Mar 29 01:27 phpunit.xml drwxr-xr-x 4 kureikain staff 136B Mar 29 01:27 tests drwxr-xr-x 12 kureikain staff 408B Apr 13 17:37 widget -rw-r--r-- 1 kureikain staff 1.1K Apr 6 01:04 widget.php ☁ Server Dashboard [master] ls -lh | awk ' {print $3, $4, $5, $9} ' kureikain staff 2.6K Server kureikain staff 102B bin kureikain staff 98B loader.js kureikain staff 321B phpunit.xml kureikain staff 136B tests kureikain staff 408B widget kureikain staff 1.1K widget.php<br><br>As you can see the each line of ls -lacontains nine fields: drwxr-xr-x 4 kureikain staff 136B Mar 29 01:27 testsSeparating by spaces, these 9 fields are: - drwxr-xr-x - 4 - kureikain - staff - 136B - Mar - 29 - 01:27 - tests awk ' {print $3, $4, $5, $9} 'and I'll see: kureikain staff 136B tests<br> Therefore, utilizing awk we can clean up the output a little bit more before feeding into our PHP processing function. Cleaning Up with GREP Some commands output extra data that we don't need; therefore, it requires a little bit of extra effort with PHP to clean it up. For example: [vagrant@vagrant-centos64 ~]$ free -m total used free shared buffers cached Mem: 589 537 51 0 8 271 -/+ buffers/cache: 258 330 Swap: 255 0 255 free -mshows us the RAM usage with memory and swap file; however it includes two other lines with total/used/free and -/+ buffers/cache that we may not need. -Eswitch. That switch allows use to use regular express for searching. Because we want to find the line with words Mem and Swap, let combine with grep -E "Mem|Swap". [vagrant@vagrant-centos64 ~]$ free -m | grep -E "Mem|Swap" Mem: 589 536 52 0 8 271 Swap: 255 0 255So it's much cleaner. Combine both of grepand awkwe can clean up data and get only what we need. [vagrant@vagrant-centos64 ~]$ free -m | grep -E "Mem|Swap" | awk '{print $1, $2, $3, $4}' Mem: 589 537 52 Swap: 255 0 255 Linux Commands to Get Server Information We've gotta learn some commands to pull server metrics, so let's open our server shell, and try to type below command to have a quick taste. Check Network Traffic $netstat -in Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg eth0 1500 0 5538339494 0 0 0 6216082004 0 0 0 BMRU eth0:1 1500 0 - no statistics available - BMRU eth1 1500 0 96707328840 0 0 0 102776317608 0 0 0 BMRU eth2 1500 0 33 0 0 0 7 0 0 0 BMRU lo 16436 0 29461422 0 0 0 29461422 0 0 0 LRU Check Disk Usage df -h Filesystem Size Used Avail Use% Mounted on /dev/sda7 2.0G 660M 1.3G 35% / /dev/sda8 1.0T 632G 340G 66% /home /dev/sda6 2.0G 68M 1.9G 4% /tmp /dev/sda5 20G 1.5G 18G 8% /var /dev/sda2 20G 2.1G 17G 12% /usr /dev/sda1 194M 25M 160M 14% /boot /dev/hdb1 459G 277G 159G 64% /backup tmpfs 16G 0 16G 0% /dev/shm Check RAM Usage free -m total used free shared buffers cached Mem: 32189 32129 59 0 419 9052 -/+ buffers/cache: 22656 9532 Swap: 32767 4 3276We will use more command later, but above ones give you some fundamental command to see what we can get from server right on the command line. Building the Widget We will refactor our original class in previous section a little bit. Note that, unless clearly stating otherwise, we'll be creating all files and folders within our plugin directory. First, we won't want to manually include files. We will write an auto class loader for that purpose. When a missing class is initialized, we will check the class name and try to include the source file that hold class definition. We will use namespaces as the path and class name as the file name. For example, a class foo in namespace AX\StatBoard should be in the root of plugin folder. A class buzz in namespace AX\StatBoard\Bar should be in Bar\buzz.php With that in mind, let's go ahead and start crafting our auto loader method: <?php namespace AX\StatBoard; class Dashboard { //..; } <br><br> /**<br> * Setup variable and intialize widget provider<br> */<br> function __construct() {<br> $this->_plugin_dir = plugin_dir_path( __FILE__ ) ;<br> spl_autoload_register(array($this, 'load_class'));<br> }<br><br> //.. }So, what happens here? Our plugin use namespace AX\StatBoard. So we make sure the requested class under this namespace should be handle by our plugin, otherwise our auto loader isn't capable to load them. We then strip the AX\StatBoard in class name and replace it with the path of plugin folder. The backslash \ in namespace is replaced with / path separator, and append phpextension. That mean that the namespace will be used as the path to folder contains class file, and the class name is the file name. Including only occurs if the file exists. Now, we got the auto loader, we still need to let PHP know that we got an auto loader and we want to use it. PHP includes spl_autoload_register for this purpose. We put it in our class constructor. Secondly, let's design our widgets class. We have multiple types of server metric to display. It's better to display each of metric in a separate widget block so those widgets can be sorted or arrange, or customized to hide or show. Putting all information into the same widget will put the cost of control showing/hiding each of metric to our plugin. wp_add_dashboard_widget, we have to give it the title and content. Corresponding to each widget, we will have a class to render title and content for it. We call these class are widget Provider. All widget provider must define get_title()and get_content()to render content. Providerinterface, and have our widget provider class implement this interface. We also need to create one more method call get_metric()to pull server data. Create file widget/provider.phpwith this content: <?php namespace AX\StatBoard\Widget; interface Provider { function get_title(); function get_content(); function get_metric(); }This is an interface. We required that every widget provider has to implement this interface, and therefore we ensure tat widget provider class always has these three methods. We will create one more class Widgetto manage these providers. We create provider classes, then hand them out to Widgetclass, and view Widgetclass as a single point for us to ask for a provider when we need. We can simply put everything into our main plugin file, and just create class instance with newoperator when we need but it's hard to maintain later. Widgetclass Compose a file widget.phpin root directory of plugin folder. <br><?php<br>namespace AX\StatBoard;<br>use AX\StatBoard\Widget\Provider;<br><br>class Widget {<br> const WIDGET_SLUG_PREFIX = 'AX';<br><br> protected $_providers = array();<br> protected static $_instance;<br><br> static function instance() {<br> return self::$_instance = self::$_instance ?: new self();<br> }<br><br> function __construct() {<br> }<br><br> /**<br> * Add a widget provider<br> * @param string widget name<br> * @param provider object to handle widget content rendering<br> */ <br> public function add_provider($name, Provider $handler) {<br> $this->_providers[$name] = $handler;<br> return $this;<br> }<br><br> /**<br> * Get all provider or a particular provider<br> */<br> public function get_provider($name=NULL) {<br> if (!$name) {<br> return $this->_providers;<br> }<br> return $this->_providers[$name];<br> }<br><br> /**<br> * Register a widget to render it.<br> */<br> public function register($name) {<br> $slugid = self::WIDGET_SLUG_PREFIX . $name;<br> $widget_provider = $this->get_provider($name);<br> if (empty($widget_provider)) {<br> return false;<br> }<br><br> wp_add_dashboard_widget(<br> $slugid,<br> $widget_provider->get_title(),<br> array($widget_provider, 'get_content'));<br> return true;<br> }<br>}<br><br>Again, we're using the Singleton Pattern for our Widget class. A quick summary of our method here. - The add_providermethod will add a widget provider object to the widget provider list. We also use type hinting to make sure that object pass to add_provider has to be a Provider by implementing our Providerinterface. - The get_providermethod can return a list of all provider, or a particular provider. - The registermethod will actually register our provider object with WordPress to render a dashboard widget with wp_add_dashboard_widget. The ID of widget is generated based on the prefix, a pre defined constant, and the class name of widget. The title will and content will be pull via get_title and get_contentof provider. We made sure they implement our Provider interface. With this register method, we abstract the implementation of adding the widget to dashboard. All we need to do now is to call registerwith the name of provider which we add before with add_provider. With this in mind, when WordPress API changes, we don't need to go to every place of wp_add_dashboard_widget, we just update in one place. Coming back our original main plugin file serverdashboard.php, we will initialize all providers and add them to provider list of Widget object. <?php /** * Setup variable and intialize widget provider */ function __construct() { $this->_plugin_dir = plugin_dir_path( __FILE__ ) ; spl_autoload_register(array($this, 'load_class')); $this->_dashboard_widget = array( 'server', 'cpu_load', 'ram', 'disk', 'diskio', 'software', 'ethernet', 'internetspeed', 'networkio', 'process', ); foreach ($this->_dashboard_widget as $item) { if (!file_exists($this->_plugin_dir . '/widget/' . $item . '.php')) { continue; } $classname = 'AX\\StatBoard\\Widget\\' . ucwords($item); Widget::instance()->add_provider($item, new $classname()); } }<br><br>We will put all widget provider classes under namespace AX\StatBoard\Widgetand therefore they will sit inside folder widget. We support nine kinds of metric and we name the class corresponding to the array _dashboard_widgetsabove. Widgetclass. Here is what we will get later with this structure: wp_dashboard_setup, and inside it we call the function wp_add_dashboard_widgetto add new widget to dashboard. Next, we have our registermethod for this purpose. We will loop over all added providers, and register them. Update the content of add_dashboard_widgetsof serverdashboard.phpbecome: <br> /** * Register dashboard widget proider to show up on dashboard */ function add_dashboard_widgets() { $widget = Widget::instance(); foreach ($widget->get_provider() as $name=>$provider) { $widget->register($name); } }<br><br> Next, we will hook into admin_footer to output inline JavaScript at bottom of admin page for initializing Google Chart class package. Our run()method is also updated for new hook. /** * Start to setup hook */ public function run() { add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) ); add_action( 'admin_enqueue_scripts', array($this, 'add_asset')); add_action( 'admin_footer', array($this, 'footer')); } /** * Inline JavaScript for chart */ function footer() { echo ' <script>google.load("visualization", "1", {packages:["corechart"]})</script> '; } At this moment, we completed the basic, and the main plugin file should look like this. <?php /* Plugin Name: Server Dashboard Version: 0.1-alpha Description: Server Status Dashboard Author: Vinh Author URI: Plugin URI: Text Domain: Server Dashboard Domain Path: /languages */ namespace AX\StatBoard; use AX\StatBoard\Widget; class Dashboard { protected static $_instance=NULL; protected $_dashboard_widget = array(); protected $_plugin_dir=NULL; /** * Auto load class under namespace of this plugin */; } /** * Setup variable and intialize widget provider */ function __construct() { $this->_plugin_dir = plugin_dir_path( __FILE__ ) ; spl_autoload_register(array($this, 'load_class')); $this->_dashboard_widget = array( 'server', 'cpuload', 'ram', 'disk', 'software', 'process', 'ethernet', 'networkio', 'iostat', ); foreach ($this->_dashboard_widget as $item) { if (!file_exists($this->_plugin_dir . '/widget/' . $item . '.php')) { continue; } $classname = 'AX\\StatBoard\\Widget\\' . ucwords($item); Widget::instance()->add_provider($item, new $classname()); } } /** * Create an unique instance throught the app */ public static function instance() { return self::$_instance = self::$_instance ?: new self(); } /** * Start to setup hook */ public function run() { add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) ); add_action( 'admin_enqueue_scripts', array($this, 'add_asset')); add_action( 'admin_footer', array($this, 'footer')); } /** * Register dashboard widget proider to show up on dashboard */ function add_dashboard_widgets() { $widget = Widget::instance(); foreach ($widget->get_provider() as $name=>$provider) { $widget->register($name); } } /** * Assets load: stylesheet, JS. */ function add_asset() { syslog(LOG_DEBUG, "Loaded"); wp_enqueue_script( 'google-chart', '' ); //wp_enqueue_script( 'plugin_dir_url', plugin_dir_url(__FILE__) . '/loader.js'); } /** * Inline JavaScript for chart */ function footer() { echo ' <script>google.load("visualization", "1", {packages:["corechart"]})</script> '; } } Dashboard::instance()->run();We basically create an instance of main plugin class and call the run method. Which in turn just set up a list of hook. Each hook is another method inside the class. We also create and register our provider object with Widgetobject. What's Next?At this point, we still aren't display anything; however, we laid out a structure for our plugin ad began hooking into Google Charts. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/the-fundamentals-of-building-a-wordpress-server-dashboard--cms-20458
CC-MAIN-2018-51
refinedweb
3,421
54.93
How use parallelism in Python¶ Since you are running at NERSC you may be interested in parallelizing your Python code and/or its I/O. This is a detailed topic but we will provide a short overview of several options. If you intend to to run your code at scale, please see our discussion here that provides a brief overview of best filesystem practices for scaling up. Multiprocessing¶ Python's standard library provides a multiprocessing package that supports spawning of processes. Multiprocessing be used to achieve some level of parallelism within a single compute node. It cannot be used to achieve parallelism across compute nodes. For more information, please see the official Python multiprocessing docs. If your multiprocessing code makes calls to a threaded library like NumPy with threaded MKL support then you need to consider oversubscription of threads. While process affinity can be controlled to some degrees in certain contexts (e.g. Python distributions that implement os.sched_{get,set}affinity) it is generally easier to reduce the number of threads used by each process. Actually it is most advisable to set it to a single thread. In particular for OpenMP: export OMP_NUM_THREADS=1 Furthermore, use of Python multiprocessing on KNL you are advised to specify: export KMP_AFFINITY=disabled mpi4py¶ mpi4py provides MPI standard bindings to the Python programming language. Documentation on mpi4py is available here. Here is an example of how to use mpi4py on Cori: #!/usr/bin/env python from mpi4py import MPI mpi_rank = MPI.COMM_WORLD.Get_rank() mpi_size = MPI.COMM_WORLD.Get_size() print(mpi_rank, mpi_size) This program will initialize MPI, find each MPI task's rank in the global communicator, find the total number of ranks in the global communicator, print out these two results, and exit. Finalizing MPI with mpi4py is not necessary; it happens automatically when the program exits. Suppose we put this program into a file called "mympi.py." To run it on the Haswell nodes on Cori, we could create the following batch script in the same directory as our Python script, that we call "myjob.sh:" #!/bin/bash #SBATCH --constraint=haswell #SBATCH --nodes=3 #SBATCH --time=5 module load python srun -n 96 -c 2 python mympi.py To run "mympi.py" in batch on Cori, we submit the batch script from the command line using sbatch, and wait for it to run: sbatch myjob.sh Submitted batch job 987654321 After the job finishes, the output will be found in the file "slurm-987654321.out:" % cat slurm-987654321.out ... 91 96 44 96 31 96 ... 0 96 ... mpi4py in your custom conda environment¶ If you would like to use mpi4py in a custom conda environment, you will need to install and build it inside your environment. Do NOT conda/pip install mpi4py You can install mpi4py using these tools without any warnings, but your mpi4py programs just won't work. To use Cori's MPICH MPI, you'll need to build it yourself using the Cray compiler wrappers that link in Cray MPICH libraries. You can build mpi4py and install it into a conda environment on Cori using this upated recipe: MPICC="$(which cc) --shared" pip install --no-binary mpi4py mpi4py Or use our legacy directions: wget tar zxvf mpi4py-3.0.3.tar.gz cd mpi4py-3.0.3 module swap PrgEnv-intel PrgEnv-gnu python setup.py build --mpicc="$(which cc) -shared" python setup.py install New experimental option: you can clone the lazy-mpi4py conda environment we provide at NERSC and add your own packages on top: conda create --name myenv --clone lazy-mpi4py If you have questions or feedback about this method, please let us know at help.nersc.gov. Using mpi4py in a Shifter container¶ When a large number of Python tasks are simultaneously launched with mpi4py, the result is many tasks trying to open the same files at the same time, causing filesystem contention and performance degradation. mpi4py applications running at the scale of a few hundred or a thousand tasks may take an unacceptable amount of time simply starting up. Using mpi4py in a Shifter container is our reccommended solution to this problem. For more information about how to build and use mpi4py in a Shifter container, please see here. Dask¶ Dask is a task-based system in which a scheduler assigns work to workers. It is robust to failure and provides a nice bokeh-based application dashboard. It can be used to scale to multinode CPU and GPU systems. You can find more information about using Dask at NERSC here. Parallel I/O with h5py¶ You can use h5py for either serial or parallel I/O. For more general information about HDF5 at NERSC please see this page. If you would like to use h5py for parallel I/O, you will have to build h5py against mpi4py in your custom conda environment. We will provide the directions for building an h5py-parallel enabled conda environment below. These directions are based on those found here and here. You will first need a conda environment with mpi4py built and installed for NERSC. You can follow our directions here OR you can try cloning our lazy-mpi4py conda environment where we have already built mpi4py for you: module load python conda create -n h5pyenv --clone lazy-mpi4py Activate your environment source activate h5pyenv Load and configure your modules: module load cray-hdf5-parallel module swap PrgEnv-intel PrgEnv-gnu Clone the h5py github repository: cd $SCRATCH git clone cd h5py Configure your build environment: export HDF5_MPI="ON" export CC=/opt/cray/pe/craype/2.6.2/bin/cc Configure your h5py build: python setup.py configure The output should look like: ******************************************************************************** Summary of the h5py configuration HDF5 include dirs: [ '/opt/cray/pe/hdf5/1.10.5.2/GNU/8.2/include' ] HDF5 library dirs: [ '/opt/cray/pe/hdf5/1.10.5.2/GNU/8.2/lib' ] HDF5 Version: '1.10.5' MPI Enabled: True Rebuild Required: True ******************************************************************************** Now build: python setup.py build Once the build completes, you'll need to install h5py as a Python package: pip install --no-binary=h5py h5py Now we will test our h5py-parallel enabled conda environment on a compute node since mpi4py will not work on login nodes. Get an interactive compute node: salloc -N 1 -t 20 -C haswell -q interactive module load python source activate h5pyenv We'll use this test program described in the h5py docs: from mpi4py import MPI import h5py rank = MPI.COMM_WORLD.rank # The process ID (integer 0-3 for 4-process run) f = h5py.File('parallel_test.hdf5', 'w', driver='mpio', comm=MPI.COMM_WORLD) dset = f.create_dataset('test', (4,), dtype='i') dset[rank] = rank f.close() We can run this test with 4 mpi ranks: srun -n 4 python test_h5pyparallel.py Let's look at the file we wrote with h5dump parallel_test.hdf5. It should look like this: HDF5 "parallel_test.hdf5" { GROUP "/" { DATASET "test" { DATATYPE H5T_STD_I32LE DATASPACE SIMPLE { ( 4 ) / ( 4 ) } DATA { (0): 0, 1, 2, 3 } } } } Great! Our 4 mpi ranks each wrote part of this HDF5 file.
https://docs.nersc.gov/development/languages/python/parallel-python/
CC-MAIN-2021-17
refinedweb
1,173
63.8
Hello everybody, My goal with this programm is to implement a function that reads a file with text, and returns successively single words, that can be handled by another function. One of the problems is, that for some reason it stops giving outputs at the last word and stays running instead of breaking up ( return 0; ). I wonder also, how could/should I implement this as a method, that throws all the words of the file, so that they can be handled by another method? Thanks in advance! Code: #include <iostream> #include <fstream> #include <string> int main() { char ch; std::string word = ""; // Givin the InputFile a more suitable name. std::fstream inputFile("test.txt"); // pointer initialisation, pointing to first character FILE *fptr = fopen("test.txt", "r"); // ch has the first character of the file ch = getc( fptr ); // Read till end of file (problem: it doesnt stop after printing the last word) while(!inputFile.eof()) { if ( (ch != ' ') && (ch != '\n') ) { word += ch; ch = getc( fptr ); // Reading ' ' or '\n' implies the end of a word. print it. if( (ch == ' ') || (ch == '\n') ) { std::cout << word << std::endl; word = ""; } } if( (ch == ' ') || (ch == '\n')) { ch = getc( fptr ); } if( !((ch != ' ') || (ch == ' ')) ) { ch = getc( fptr ); } } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/65399-reading-file-returning-single-words-printable-thread.html
CC-MAIN-2013-48
refinedweb
199
71.04
I am new to ARM and I am trying to produce 1 second delay using timer 0 in LPC2148. But in debug session in Keil, it is giving delay of 4 seconds with 15MHz and 5 seconds with 12 MHz. What is the issue ? Here is my code. #include <lpc214x.h> int main() { IODIR0 = 1; // P0.0 is output pin IOSET0 = 1; // P0.0 is high T0PR = 15000000 - 1; T0TC = T0PC = 0; T0TCR = 1; // start do { while(T0TC == 0); T0TC = 0; IOCLR0 = 1; // P0.0 is low while(T0TC == 0); T0TC = 0; IOSET0 = 1; // P0.0 is high } while(1); } Real hardware or simulator? Toggling pin halves frequency observed at GPIO. Not sure of merit of setting counter to zero when already supposedly zero. Find other examples. Check internal clock, perhaps there is a means to export to a pin? In simulation. In keil as well as proteus, both are giving 4/5 seconds of delay. What I am thinking is I have configured frequency to 12MHz and Vpbdiv by default is 0. So it may be diving the frequency by 4. Is it possible ? but PLL configurations are default.(Set by startup code). kamalpancholi said:it may be diving the frequency by 4. Is it possible ? What does the chip documentation tell you? I don't know. I'd just unpack the PLL settings and see what the expectations are rather than guess. The thing should clock off PCLK, but it's not a part I'm using, and I don't suspect the simulator is cycle accurate for things outside the core. Perhaps you should invest is some current hardware, the ARM7TDMI-S is pretty antiquated at this point, given the other options I'd have to think the market for NXP LPC2148 programming skills is tending to zero. Westonsupermare Pier said:Perhaps you should invest is some current hardware Indeed. kamalpancholi - Not least because most current chips these days are available with low-cost dev boards that include a debug probe - so you can throw away all the doubts & uncertainties of simulators, and just use the actual hardware! Westonsupermare Pier said: I don't suspect the simulator is cycle accurate for things outside the core. I haven't still bought any hardware. I am just new to ARM controllers so I am starting with the very basic one kamalpancholi said:I am just new to ARM controllers All the more reason to start with something up-to-date! Again, it is certainly worth getting one of the many low-cost dev boards that includes a debug probe - far better than messing about with simulators! Most manufacturers have some beginner's tutorials based on these boards. Keil's own getting started stuff: Ok, so you've got the timer working and the pin to toggle. Why it is not quite at the frequency you want is another matter, but it appears to track your master clock input, so clearly some ratio involved. Not a part I'm using, not super invested in root-causing it. Suggest perhaps that you write some simple register decoder functions, so say you can pull the PLL or CLOCK registers and decode them into a human readable form. Perhaps read the multiple timer registers and decode their content. Do other tests, experiment with other peripherals, but be aware that anything outside the core may be poorly emulated. Do things related to the ARM7 core rather than the NXP implementation around it. Perhaps code some assembler routines, convert decimals to/from binary and ASCII. Westonsupermare Pier said:Do things related to the ARM7 core rather than the NXP implementation around it Do you mean I should not use LPC2148 ? If this then which one I should use ? Westonsupermare Pier said:Do other tests, experiment with other peripherals definitely. I am trying to get the value by experimenting with multiple values of VPBDIV Andy Neil said:All the more reason to start with something up-to-date And now I am thinking to invest some in latest low cost ARM microcontroller kamalpancholi said:Westonsupermare Pier said:Do things related to the ARM7 core rather than the NXP implementation around it Do you mean I should not use LPC2148 ? If this then which one I should use ? You need to understand that ARM do not make any microcontrollers at all. ARM simply license the designs of CPU cores to chipmakers. The chipmakers incorporate ARM's CPU design into their microcontrollers, along with other components of their own, proprietary, design - such as Timers, IO, etc. So what Westonsupermare Pier is saying is for you to concentrate on stuff which relates the the ARM CPU Core - rather than stuff which is proprietary to a particular manufacturer (eg, NXP) and/or peculiar to a particular chip (eg, LPC2148). EDIT This diagram (actually from an Analog Devices part) clearly shows which part is the ARM core - the rest is the manufacturer's own IP: Another post explaining "ARM don't make chips": kamalpancholi said:I haven't still bought any hardware So no reason at all to stick with this old chip! Andy Neil said:ARM simply license the designs of CPU cores to chipmakers These designs are commonly known as "Intellectual Property" - or "IP" for short.(not to be confused with "IP" for "Internet Protocol"). ARM do also license other types of IP besides just the CPU cores. Andy Neil said:The chipmakers incorporate ARM's CPU design into their microcontrollers, along with other components of their own, proprietary, design - such as Timers, IO, etc These other designs are also commonly referred to as "IP". This is the IP which distinguishes one manufacturer's ARM-based microcontroller from another manufacturer's microcontroller based on the same ARM core. You will often find that manufacturers re-use such IP across multiple products. This photo is not so clearly, could it be patched more detail described? I also wonder there is how many instructions in M series ARM core. Jackzhu said:This photo is not so clearly You mean this one: I think you're missing the point. The point - which is clear to see in that image - is that the actual ARM part is just a small part within the whole chip. All the rest around it is not ARM - it is the chipmaker's proprietary stuff. Andy Neil said:from an Analog Devices part If you actually want to find out more about that particular Analog Devices chip (and find the original diagram), go to: Jackzhu said: I also wonder there is how many instructions in M series ARM core. That has nothing to do with this thread! If you want to start a separate discussion on that, start a new thread in the Cortex-M forum: But the Instruction Set is well documented - be sure to Please read the manual first! View all questions in Keil forum
https://community.arm.com/developer/tools-software/tools/f/keil-forum/43684/lpc2148-timer0-not-working-as-expected/158928
CC-MAIN-2021-17
refinedweb
1,149
63.19
Mocking Ionic Native 3.x plugins Ionic Native 3.x has introduced plugins mocks which allow developers to build and test Ionic 2 apps entirely on the browser using the Ionic CLI serve command so they don't have to use actual mobile devices or emulators which reduces the time between iterations and accelerate apps development . What is a plugin mock ? A native plugin mock is simply a class which mimics the functionality of a real plugin .It has the same programming interface as the actual Ionic native plugin and returns some user chosen data to enable the user to test the plugin without actually running the corresponding native feature on the real device or emulator . For example before Ionic Native 3.x ,if you need to use the Camera in your Ionic apps you'll have to run your app in the actual device or the emulator to test if you are app is working as expected ,so you have to switch from ionic serve and browser test to actual device whenever you need to test a native plugin except for some few plugins which work under the browser too .But with Ionic Native 3.x you can write a Camera mock which replaces the actual Ionic Native Camera plugin when you are testing the app on the browser which allows you to build and test your app entirely on the browser . How to write native plugins mocks ? A plugin mock is a class which simulates the actual Ionic Native plugin so depending on the plugin that you need to mock the class needs to export a specific set of methods that return some data instead of real data we get from native devices . In this tutorial we are going to create a mock for device Camera .If you have used the plugin before then you already know that it has a getPicture() method which returns the image taken with the Camera encoded in base 64 format .If you didn't use this plugin before then just open @ionic-native/camera TypeScript file to see what the plugin exports and then create fake methods corresponding to each method that you need to use in your app . So go ahead and create an optional folder in your project root folder cd src mkdir mocks cd mocks touch camera-mock.ts Open camera-mock.ts and copy paste the following code export class CameraMock { getPicture(params) { return new Promise((resolve, reject) => { resolve("BASE_64_IMAGE_DATA"); }); } } Next open src/app.module.ts and import mock class with import { CameraMock } from "../mocks/camera-mock"; Then add it to module providers array @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, CameraMock, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} Now you can use it in any component after importing it . Conclusion That is it ,now you can use the Camera mock instead of the actual Ionic native plugin and develop your app entirely on the browser .After finishing the development on the browser you need to swap the Camera mock with the actual Ionic 3 native Camera plugin and then build your app . Sponsored Links Latest Questions and AnswersWhat Are the New Features of HTML6? What’s the HTML6 Release Date?
https://www.techiediaries.com/mocking-ionic-native-3-x-plugins/
CC-MAIN-2020-34
refinedweb
543
50.36
ROS PCL tutorial actually works? So, apparently ROS uses its own version of PCL, pcl_ros, which is different from the original PCL branch. I was following the first ROS+PCL tutorial, and it seemed ok, but then I got to this part at the end of the tuto, which includes #include <pcl/sample_consensus/model_types.h>. While there is such file in the PCL github repo, I cannot find it in the ROS PCL include folder... From this I can only assume one of two things: either the tutorial is wrong - it should not include such file but another one instead -, OR you are supposed to use the actual PCL repo code, adding the libraries by editing the CMakeLists.txt and including something like find_package(PCL 1.7 REQUIRED) include_directories(${PCL_INCLUDE_DIRS}) [...] As described in the original PCL tutorials, which is not mentioned in the tutorial. - either way the tutorial appears to be wrong. Am I missing something? Can you use both PCL's alongside each other, or what? I'm afraid that would lead to some conflicts because many files have the same name in the same subfolders. ROS uses the upstream version of PCL, and the pcl_ros package is a set of adapters to make PCL compatible with ROS message types. Hm... I see. But how does it compile if I didn't specify anywhere I wanted to link against the PCL libraries? What I mean is, I have all the PCL's .so files inside /usr/local/lib, but nowhere specified where they are or to use them. There is no find_package()for PCL, but it is being used. pcl_rosprovides a transitive dependency on the upstream PCL library.
https://answers.ros.org/question/287704/ros-pcl-tutorial-actually-works/
CC-MAIN-2021-21
refinedweb
279
65.01
The QRegExp class provides pattern matching using regular expressions. More... #include <QRegExp> Note: All the functions in this class are reentrant. The QRegExp class provides pattern matching using regular expressions. Regular expressions, or "regexps", provide a way to find patterns within text. This is useful in many contexts, for example: We present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation itself. QRegExp is modeled on Perl's regexp language, and also fully supports Unicode. QRegExp can also be used in the weaker 'wildcard' . Regexps are built up from expressions, quantifiers, and assertions. The simplest form of expression is simply a character, e.g. x or 5. An expression can also be a set of characters. For example, [ABCD], will match an A or a B or a C or a D. As a shorthand we could write this as [A-D]. If we want to match any of the captital letters in the English alphabet we can write [A-Z]. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. x{1,1} means match an x which occurs at least once and at most once. We'll look at assertions and more complex expressions later. Note that in general regexps cannot be used to check for balanced brackets or tags. For example if you want to match an opening html <b> and its closing <b>, you can only use a regexp if you know that these tags are not nested; the html fragment, <b>bold <b>bolder</b></b> will not match as expected. If you know the maximum level of nesting it is possible to create a regexp that will match correctly, but for an unknown level of nesting, regexps will fail. We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with [0-9]{1,1} which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes [0-9]{1,2} meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits within a string. To ensure that we match against the whole string we must use the anchor assertions. We need ^ (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need $ (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is ^[0-9]{1,2}$. Note that assertions, such as ^ and $, do not match any characters. If you've seen regexps elsewhere, they may have looked different from the ones above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. [0-9] can be replaced with the symbol \d. The quantifier to match exactly one occurrence, {1,1}, can be replaced with the expression itself. This means that x{1,1} is exactly the same as x alone. So our 0 to 99 matcher could be written ^\d{1,2}$. Another way of writing it would be ^\d\d{0,1}$, i.e. from the start of the string match a digit followed by zero or one digits. In practice most people would write it ^\d\d?$. The ? is a shorthand for the quantifier {0,1}, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp ^\d\d?$ means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string". Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, m{1,1}a{1,1}i{1,1}l{1,1}, but since each expression itself is automatically quantified by {1,1} we can simply write this as mail; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for alternation, so our regexp now becomes mail|letter|correspondence which means match 'mail' or 'letter' or 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parentheses, (mail|letter|correspondence). Parentheses have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to capture. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time \b "word boundary": \b(mail|letter|correspondence)\b. This regexp means "match a word boundary followed by the expression in parentheses followed by another word boundary". The \b assertion matches at a position in the regexp not a character in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string. For our third example we want to replace ampersands with the HTML entity '&'. The regexp to match is simple: &, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: &(?!amp;). The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must not follow the expression that preceeds it. Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are \b(Eric|Eirik)\b and \bEi?ri[ck]\b. We need the word boundary '\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'. We will implement some the examples above in the code examples section. Note: The C++ compiler transforms backslashes in strings, so to include a \ in a regexp, you will need to enter it twice, i.e. \\. To match the backslash character itself, you will need four: \\\\. Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets. Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, [0-9] matches a digit in Western alphabets but \d matches a digit in any alphabet. Note that in most regexp literature sets of characters are called "character classes". By default an expression is automatically quantified by {1,1}, i.e. it should occur exactly once. In the following list E stands for any expression. An expression is a character or an abbreviation for a set of characters or a set of characters in square brackets or any parenthesised expression. If we wish to apply a quantifier to more than just the preceding character we can use parentheses to group characters together in an expression. For example, tag+ matches a 't' followed by an 'a' followed by at least one 'g', whereas (tag)+ matches at least one occurrence of 'tag'. Note that quantifiers are "greedy". They will match as much text as they can. For example, 0+ will match as many zeros as it can from the first zero it finds, e.g. '2.0005'. Quantifiers can be made non-greedy, seeised = "Trolltech ASRegExpValidator, QString, and QStringList. The CaretMode enum defines the different meanings of the caret (^) in a regular expression. The possible values are: The syntax used to interpret the meaning of the pattern. Constructs an empty regexp. See also isValid() and errorString().(). Constructs a regular expression as a copy of rx. See also operator=(). Destroys the regular expression and cleans up its internal(), pos(), exactMatch(), indexIn(), and lastIndexIn().(), pos(), exactMatch(), indexIn(), and lastIndexIn(). Returns Qt::CaseSensitive if the regexp is matched case sensitively; otherwise returns Qt::CaseInsensitive. See also setCaseSensitivity(). Returns a text string that explains why a regexp pattern is invalid the case being; otherwise returns "no error occurred". See also(), lastIndexIn(), and QRegExpValid::find(), QString::contains(), or even QStringList::grep().(). Returns true if minimal (non-greedy) matching is enabled; otherwise returns false. See also setMinimal().().(). Returns Wildcard if wildcard mode is enabled; otherwise returns RegExp. The default is RegExp. See also setPatternSyntax(). capturedTexts(), exactMatch(), indexIn(), and lastIndexIn(). Sets case sensitive matching to cs. If cs is Qt::CaseSensitive, \.txt$ matches readme.txt but not README.TXT. See also caseSensitivity(). isMinimal(). Sets the pattern string to pattern. The case sensitivity, wildcard and minimal matching options are not changed. See also pattern(). Sets the wildcard mode for the regular expression. The default is RegExp. Setting syntax to Wildcard enables simple shell-like wildcard matching. For example, r*.txt matches the string readme.txt in wildcard mode, but does not match readme. See also patternSyntax() and exactMatch()..
http://doc.trolltech.com/4.0/qregexp.html
crawl-001
refinedweb
1,653
67.25
#GTMTips: Create Facebook Pixel Custom Tag Template After the recent release of Custom Templates for Google Tag Manager, my mind has been occupied by very little else. However, I have a nagging feeling that due to how involved the feature set is, there’s still a lot of demystifying that needs to take place before templates are fully embraced by the GTM user base. In this article, I want to show you a concrete example of template creation. It’s going to be much more ambitious than the simple walkthrough I explored in the main guide. This time, we’ll step through creating an actual, functional template that caters to a very specific use case: the Facebook Pixel. This article is not endorsed by Facebook or supported by them in any capacity, official or unofficial. We’ll stop short of having a perfect representation of the Facebook pixel. However, you’ll have all the tools necessary to extend the template to cover all the features you might need and to replicate it with some other third-party vendor code. To sweeten the deal, I’ve also created a video that goes through the motions, in case it’s easier to follow the steps that way. I want to give special thanks Eric Burley from Google for walking me through some of the intricacies of template APIs. XX OK, OK, I have actually created the full, feature-ready Facebook Pixel Template for you to enjoy. You can find it in this GitHub repository. The Simmer Newsletter Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox! Tip 99: Create a Facebook Pixel template You can download the template export file here. Read this to find out how to import it into your custom templates. You don’t have to use the export file, but it might make it easier to walk through the rest of the article. What you’ll end up with The template has the following features: Ability to add multiple Pixel IDs, comma-separated. The tag hit will be sent to all the Pixel IDs you specify in the list. Support for four events: PageView, Lead, CompleteRegistration, and Custom (the Custom event will let you specify the event name in a text field that appears). Possibility to add any Object Properties to the hit. You can check a box to disable the Automatic Configuration of the pixel. Step 1: Add template information After creating a new template, this is what the Info screen looks like. Remember to enable Advanced Settings for the editor so that you can edit the Brand Name field. Step 2: Add fields The template will have four fields. Field 1: Text Input named pixelId Make sure the following field configurations are enabled for the Text Input field: Always in summary: Checked Display name: Facebook Pixel ID(s) Validation rules: (see below) Value hint: e.g. 12345678910 For the validation rules, add two different rules: This value cannot be empty, with Error message You must provide a Pixel ID. This value must match a regular expression, with value ^[0-9,]+$, and Error message Invalid Pixel ID format. You can find the Error message by clicking to show Advanced Settings for each Validation rule. Field 2: Drop-down Menu named eventName Make sure the following field configurations are enabled for the Text Input field: Always in summary: Checked Display name: Event Name Nested fields: (see below) Add the following menu items: Item name: PageView, Value: PageView Item name: Lead, Value: Lead Item name: CompleteRegistration, Value: CompleteRegistration Item name: Custom, Value: Custom Click Add field under Nested fields, and choose a Text Input field. Name the field customEventName, and choose the Display name and Enabling conditions field configurations for it. Display name: Custom Event Name Enabling conditions: eventNameequals Custom The enabling condition ensures the Custom Event Name is only shown in case “Custom” is chosen from the drop-down menu. Cool, huh? Field 3: Group named objectProperties The default field configurations should be all you need for this Group field. Group style: Collapsible section - Collapsed Display name: Object Properties Nested fields: (see below) Click Add field under Nested fields, and choose a Simple Table field. Name the field propertyList and make sure the “New row” button text field configuration is toggled on. Add two columns to the table. Both should be Text field columns. The first column should have the following settings: Column name: Property Name Internal name: name Require column values to be unique: Checked (this option becomes available when you choose to show Advanced Settings for this column) The second column should have the following settings: Column name: Property Value Internal name: value Finally, set the “New row” button text option to Add property, and leave the Display name setting blank. Field 4: Group named moreSettings Set the following settings for the group: Group style: Collapsible section - Collapsed Display name: More Settings Nested fields: (see below) Click Add field under Nested fields, and choose a Checkbox field. Name the field disableAutoConfig and make sure the Help text field configuration is toggled on. Checkbox text: Disable Automatic Configuration Help text: Facebook collects some metadata (e.g. structured data) and user interactions (e.g. clicks) automatically. Check this box to disable this automatic configuration of the pixel. Step 3: Edit code Step on over to the Code editor tab, and replace the contents with the following JavaScript:'); const initIds = copyFromWindow('_fbq_gtm_ids') || []; const pixelIds = data.pixelId; // Utility function to use either fbq.queue[] // (if the FB SDK hasn't loaded yet), or fbq.callMethod() // if the SDK has loaded. const getFbq = () => { // Return the existing 'fbq' global method if available const fbq = copyFromWindow('fbq'); if (fbq) { return fbq; } // Initialize the 'fbq' global method to either use // fbq.callMethod or fbq.queue)'); // Create the fbq.queue createQueue('fbq.queue'); // Return the global 'fbq' method, created above return copyFromWindow('fbq'); }; // Get reference to the global method const fbq = getFbq(); // Build the fbq() command arguments const props = data.propertyList ? makeTableMap(data.propertyList, 'name', 'value') : {}; const command = data.eventName !== 'Custom' ? 'trackSingle' : 'trackSingleCustom'; const eventName = data.eventName !== 'Custom' ? data.eventName : data.customEventName; // Handle multiple, comma-separated pixel IDs, // and initialize each ID if not done already. pixelIds.split(',').forEach(pixelId => { if (initIds.indexOf(pixelId) === -1) { // If the user has chosen to disable automatic configuration if (data.disableAutoConfig) { fbq('set', 'autoConfig', false, pixelId); } // Initialize pixel and store in global array fbq('init', pixelId); initIds.push(pixelId); setInWindow('_fbq_gtm_ids', initIds, true); } // Call the fbq() method with the parameters defined earlier fbq(command, pixelId, eventName, props); }); injectScript('', data.gtmOnSuccess, data.gtmOnFailure, 'fbPixel'); At this point, it’s a good idea to take a short breather. If you take a close look at the code, you’ll see that it’s far more complex than what the Facebook pixel snippet is. The reason for this is the sandboxed JavaScript that custom templates use. For example, the Facebook snippet creates the global fbq() method with something like: window.fbq = function() { window.fbq.callMethod ? window.fbq.callMethod.apply(window.fbq, arguments) : window.fbq.queue.push(arguments); } It’s a very simple piece of code, which simply passes the arguments you provide to fbq() (e.g. 'track', 'PageView') to one of two places, depending on whether the SDK has loaded yet or not. To do this in a custom template is far more complicated. You can’t just set a global variable, you need to use an API for that. You can’t just check if a global method exists, you need an API for that. And you can’t just create the queue property for the fbq() method, you need an API for that. So, let’s go over block by block to understand what the code does. Initialize the necessary APIs This script needs a handful of APIs, which are initialized with the require() API:'); I’ll explain how they function when we encounter them in the code. Fetch list of initialized IDs const initIds = copyFromWindow('_fbq_gtm_ids') || []; const pixelIds = data.pixelId; Here we fetch the list of initialized IDs (stored in a custom _fbq_gtm_ids global array), and we also pull in the value, input by the user, of the pixelId field from the template itself. Utility to fetch the proper global fbq method const getFbq = () => { // Return the existing 'fbq' global method if available const fbq = copyFromWindow('fbq'); if (fbq) { return fbq; } ... NOTE! The arrow function is a feature of ES6 supported by Custom Templates. const getFbq = () => {translates to var getFbq = function() {in the older flavor of JavaScript. The purpose of getFbq is to return a representation of the global fbq method, which passes the arguments to the correct place, similar to how the regular Facebook snippet works. The first lines check if fbq has already been created globally, and returns the global method in that case. In case the global method does not exist, it needs to be created. ...'); ... Here, the global fbq method is initialized as a new function. This function first checks if the fbq.callMethod method already exists (which means the FB SDK has loaded), and if it does, it passes the arguments sent to the fbq method (e.g. 'track', 'PageView') to this built-in method. If the callMethod method has not been created yet, then the method passes its arguments to fbq.queue as an array push. The queue is basically a waiting list for pixel request, queued up for the Facebook SDK as it loads over the network. Once the SDK has loaded, it processes the messages in this queue and dispatches them to Facebook. The last line makes an alias of the fbq method in another global variable, _fbq. I’m not certain why this is necessary, but it is what the Facebook snippet does as well. ... createQueue('fbq.queue'); return copyFromWindow('fbq'); }; The last lines of the setInWindow API call create the fbq.queue global array, before finally returning the current content of the global fbq variable, which is the function you created above. Prepare the fbq command const fbq = getFbq(); const props = data.propertyList ? makeTableMap(data.propertyList, 'name', 'value') : {}; const command = data.eventName !== 'Custom' ? 'trackSingle' : 'trackSingleCustom'; const eventName = data.eventName !== 'Custom' ? data.eventName : data.customEventName; These lines first fetch the latest representation of the fbq global method by invoking the getFbq function you just created. Next, the contents of the fbq command are built. The makeTableMap API takes your propertyList Simple Table field, and converts each row to a key-value pair, where the key is the first column value (e.g. content_ids), and the value is the second column value (e.g. 123456). It’s a really handy API for converting the template table format into what many JavaScript libraries expect. The command variable depends on whether you’re using a standard event (e.g. PageView or Lead), in which case it is set to trackSingle, or whether you’re using the Custom event, in which case it’s set to trackSingleCustom. The eventName takes either the value of the drop-down menu selection if a standard event is selected, or the value of the customEventName text input field if a Custom event is selected. Cycle through all Pixel IDs defined in tag, and dispatch the commands pixelIds.split(',').forEach(pixelId => { if (initIds.indexOf(pixelId) === -1) { if (data.disableAutoConfig) { fbq('set', 'autoConfig', false, pixelId); } fbq('init', pixelId); initIds.push(pixelId); setInWindow('_fbq_gtm_ids', initIds, true); } fbq(command, pixelId, eventName, props); }); The whole command process is wrapped in an iterator, which loops through all the Pixel IDs the user has added to the tag. The commands are run identically for every single Pixel ID in the tag. First, the code checks if the Pixel ID has already been initialized by looking at the contents of the initIds array you created at the very beginning of the code. You don’t want to initialize any Pixel ID more than once, or you’ll risk running into problems with Facebook’s SDK. If the pixel hasn’t been initialized, then first the autoConfig parameter is set to false, if the user has checked the respective checkbox in the template. Next, the fbq('init', pixelId) command is run, after which the Pixel ID is pushed into the array of initialized pixels. Finally, the fbq() command is run with the parameters you created previously. Load the Facebook SDK The very last line in the code editor loads the Facebook SDK, and signals either data.gtmOnSuccess() or data.gtmOnFailure, depending on whether the SDK load was successful or not. injectScript('', data.gtmOnSuccess, data.gtmOnFailure, 'fbPixel'); Step 4: Permissions Because you use all these APIs and mess so much with the global namespace, you’ll need to add some permissions if you want the template code to run. As you can see, every single global variable you interact with, either directly (via copyFromWindow, callInWindow, etc.) or indirectly (via aliasFromWindow) must be specified in the Permissions list. Similarly, the script injection of the SDK itself must be allowed using the appropriate permission. Test it! To test it, save the template, then browse to your container’s tags, and create a new tag. You should see the Facebook Pixel in the tag menu. Next, fill in the fields. Try a couple of different things, such as passing various object properties, using custom events, and adding more than one Pixel ID. Try also creating more than one tag with the same Pixel ID, to make sure the initialization is done just once per ID. Using GTM Preview mode and Facebook’s Pixel Helper, you should be able to verify that everything is working as it should. Final thoughts I hope this article has helped demystify custom templates. As you can see, working with the sandboxed JavaScript isn’t just a question of copy-pasting some original code and rewriting some method calls. It calls for a different approach completely, especially when working with global variables. There are some things I think custom templates should do to improve flexibility. For example, the function wrapper that GTM automatically adds whenever you create a global function is problematic, since there are use cases where you might want to be able to add properties to the global function itself. In its current format, custom templates do not permit this, so you need to use an API like createQueue to establish fbq.queue as an array. It would be better if I could just run something like setInWindow('fbq.queue', []), but right now, setInWindow only allows you to set the variable and not its individual properties. Other than that, the benefit of using this over a Custom HTML tag is huge: you’re minimizing the risk of code errors due to operating through the template, and you don’t need the problematic unsafe-eval directive in your Content Security Policy. Thanks for reading, and perhaps watching! Let me know in the comments if you have questions about how this whole thing works.
https://www.simoahava.com/analytics/create-facebook-pixel-custom-tag-template/
CC-MAIN-2022-05
refinedweb
2,496
62.58
. September 1, 2007 at 3:37 pm Jason Hi, Nice solution. I remember playing the old switch-the-exe-file for doing complex builds in VB6 days. It would nice if it were possible to change where Team Build looks to find MSBuild so you don’t have to mess with the files in the Windows folder. Have you considered getting your replacement msbuild.exe stub to parse the arguments, open the solution/project file and determine from that whether to relay the call to the 2.0 or 3.5 version of MSBuild? This could remove the need to maintain two build servers. September 2, 2007 at 10:23 am My VSTS Blog : Building .NET 3.5 Applications with Team Build 2005 [...] he has managed to work out how to get Team Build 2005 building .NET 3.5 applications. Mitch has posted this now on the TFS Now blog. Well worth a look if this is something you are needing to do. I’m keen to [...] September 2, 2007 at 11:41 am Mitch Denny Hi Jason, I had considered that. What I would need to do is read the TFSBuild.proj file to get a pointer to the solution file. Since the solution isn’t downloaded until after TFSBuild.proj is executed though it makes it a litle bit tricky to intercept at that level. VS2005 projects will probably build OK under MSBuild 3.5 though. October 22, 2007 at 9:02 pm TFS2008: Restrict Target Framework Version task « Grant Holliday [...]) [...] October 22, 2007 at 9:30 pm VSTS 2005 / 2008 Compatibility Matrix « Grant Holliday [...] TFS Now – Building .NET 3.5 Applications with Team Build 2005 [...] November 22, 2007 at 8:12 pm Darin Hi, nice solution. I had problems with the quoted arguments so I used instead: string arguments = Environment.CommandLine.Replace( @”"”C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\msbuild.exe”"”, string.Empty); Process process = Process.Start( @”c:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe”, arguments ); November 30, 2007 at 3:07 am Buck Hodges : Building VS 2008 projects with TFS 2005 [...] Building .NET 3.5 Applications with Team Build 2005 [...] November 30, 2007 at 3:39 am Building VS 2008 projects with TFS 2005 - Noticias externas [...] Building .NET 3.5 Applications with Team Build 2005 [...] November 30, 2007 at 4:09 am MSDN Blog Postings » Building VS 2008 projects with TFS 2005 [...] [...] November 30, 2007 at 4:19 am Steven Perry This worked great! Thanks. November 30, 2007 at 7:49 pm Tim I wanted to use VS2008 with TFS2005 but still build to .NET 2 You workaround did not work for me. December 4, 2007 at 1:41 am Charles Teague I want to use this method, but can you help me out with the steps? I’ve already got TeamBuild2005 installed on an OS that I’ve been using for awhile, and our TFS2005 will not be upgraded until Q1′08 time-frame. I’ve converted our 2005 solutions to 2008, but now need to enable the TeamBuild as you’ve mentioned here. Do I perform a side-by-side installation of TeamBuild2008 on the same build server I already have TeamBuild 2005 on? If so, what do I do about the port conflice dialog at the beginning of the installation? December 11, 2007 at 1:41 pm GK Or you can just edit your proj file and replace ference to 2.0 framework with 3.5 and your done. Worked like a charm for me. Gk December 12, 2007 at 5:41 am Alek Hi, ? your solution works great for building, but then the build fails on running Unit Tests – it does not understand vsdmi file saved in VS 2008. Do you have any solution for that issue too December 13, 2007 at 10:07 am Mitch Denny Hi Tim, What error are you seeing. December 13, 2007 at 10:24 am Mitch Denny Hi Charles, You don’t need to install Team Build 2008. You just need to apply the MSBuild.exe hack that I have outlined. December 13, 2007 at 10:24 am Mitch Denny Hi GK, Did you not have problems with the VS2008 solution file format and MSBuild 1.0 not being able to process it? December 13, 2007 at 10:25 am Mitch Denny Hi Alek, Yes, sadly unit testing is a problem I haven’t solved yet, but since TFS2008 is now out I’m probably not going to spend too much time on it. December 14, 2007 at 11:27 pm Tim Mitch, If I run the modified MSBuild in the framework v2 folder everything works. However, if I then try the build from within TFS it fails with no explanation or log files created December 15, 2007 at 1:18 am Valery I dropped this fake MSBuild.exe and I have now. There is a problem with the path as clearly Common7 is available but located in “C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies” on my Server… What must be done to let the MSBuild find the correct path. Notice : The build is running fine while using the actual MSBuild.exe 2.0 December 15, 2007 at 1:34 am Valery Since I have dropped this fake MSBuild instead of the v2.0, I get. Clearly, this is not the right location. Is there an explanation why the relative path does not match with “C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies” ? Notice : our Build Server has been installed and configured by a Microsoft Consultant. It’s using a “SofwareFactory.Build.Tasks” among other to manage the versioning. I have to say that I ignore everything about this “addon”. It’s “imported” in our Build Scripts: Do you now this “quite standard” addon and could it be responsible for our issue ? December 26, 2007 at 11:10 am Mitch Denny Hi Tim, Can you give me some details about your source code structure and the definition of the team build type? December 26, 2007 at 11:12 am Mitch Denny Hi Valery, Something doesn’t seem quite right in your environment. Can you try a clean bulid server and just try building a simple console application? January 4, 2008 at 8:31 pm Valery As this server was installed by a Microsoft Consultant, we will contact him again and ask for additional explanations on what is done exactly by its “Software Factory”. Currently, we only know that it is used to make the build process more flexible by generating custom build scripts for each project to be built… January 12, 2008 at 4:14 pm Barry I’ve the same problem as Tim I’ve replaced MSBuild.exe in 2.0 folder with my custom MSBuild, TeamBuild stopped without any logs and errors. I tested my custom MSBuild in command line, it can redirect to 3.5 properly, arguments are also passed successfully. However, it does not work under TeamBuild. January 22, 2008 at 8:05 pm Andre Hi Mitch, I read you solution and I think that this is the same issue within my environment. I had some problems with the /p: arguments, which where treated wrongly. So I changed your code snippet. Here is my solution: cheers, Andre January 24, 2008 at 11:30 pm Mitch Denny Hi guys, I’d recommend moving to TFS 2008 now, this was just an interim hack. April 4, 2008 at 2:39 am oo Thanks. I’ve developed your idea further – my version of the tool reads TFSBuild.rsp and looks for the MSBuildCommandPath property. If present, the specified command gets called, otherwise the call is handed over to MSBuild-org.exe TFSBuild.rsp ————— /property:MSBuildCommandPath=C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe This greatly eases our migration path to TFS2008. Cheers, Olivier April 15, 2008 at 1:51 am Tommy Norman Mitch, I am consulting for a client where we need to build 3.5 projects on their TFS 2005 server, but they are uncomfortable changing the MSBuild executable. I was going to look into just shelling out to DEVENV and compiling the 3.5 projects from the command line (like you do for building setup projects). I was even contemplating writing a custom build taks to do it that could then take the output and write it to the build log. Before I started I wanted to see if this was way offbase or if you think it acutally might work. regard, Tommy April 26, 2008 at 7:09 am Mitch Denny At this point I’d recommend upgrading to TFS 2008 as the best course of action. June 3, 2008 at 7:30 am Vanitha Barry/Tim, Do you have a resolution to the issue that you are facing regarding getting the builds to run within Team Build? I am facing the same issue now, while the redirection to MSBuild 3.5 works as expected, there seems to be an error and Team Build does not provide any logs for me to determine what might be the issue. My Team Build type was created using VS 2005. Could this be an issue? The same build type works fine using MSBuild 2.0. I appreciate your inputs! Thanks! July 19, 2008 at 4:23 am Wassup Jose » Blog Archive » TFS 2005 Build Server building 2008 Solutions [...] thanks for making 2008 solutions build seamlessly in TFS2005! I had completely forgotten that a workaround was needed to build 2008 solutions in 2005 msbuild. However, you owe me a fucking apology for [...] September 19, 2008 at 6:58 pm Jonathan Dickinson I just put up a ‘more complete’ shim on my blog. It allows you to shim any file (via registry settings) and also supports the standard in, out and error streams, as well as the ctrl+c sequence. This should allow the MSTest.exe file to be shimmed as well (but I am still installing TFS 2005, so this isn’t confirmed). November 18, 2008 at 4:56 am Paul I feel a little silly, but I was trying to build your MSBuild.exe with your 25 lines of code so graciously provided. But since I am a web developer and not an application developer I’m not sure what type of Visual Studio Project I am supposed to use to create an .exe and I keep getting an error on the process.WaitForExit line, is there some type of using statement or reference that I am supposed to apply to this class? Thanks so much for your help with this. The idea sounds great, I just need to actually create or get a copy of this .exe November 18, 2008 at 5:56 am Paul oh never mind, I figured it out, it should be a “Web Application” project and change the output to .exe here is the fuller code I used (the middle part is same as yours), this might have an EXTRA using statement or two, but it does work (and works great I must say): using System; using Microsoft.CSharp; using System.Diagnostics; using System.ComponentModel; using System.Threading; using System.IO; namespace MSBuild { class Program { public static int Main(string[] args) { for (int argIndex=0; argIndex<args.Length;argIndex++) { if (args[argIndex].Contains(” “)) { string quotedArg= string.Format(”\”{0}\”", args[argIndex]); args[argIndex]=quotedArg; } } string arguments = string.Join(” “,args); Process process = Process.Start(”C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe”,arguments); process.WaitForExit(); return process.ExitCode; } } }
http://tfsnow.wordpress.com/2007/08/31/building-net-35-applications-with-team-build-2005/
crawl-002
refinedweb
1,915
74.49
In this tutorial we will learn how to filter an array of objects using cpplinq. The tests shown on this tutorial were performed using an ESP32 board from DFRobot. Introduction In this tutorial we will learn how to filter an array of objects using cpplinq, running on an ESP32. On previous tutorials we have covered the use of many cpplinq operators for simple use cases, more precisely, to process arrays of integers. Nonetheless, the usefulness of this library is more evident when we use it for more complex use cases, such as processing arrays of objects. Thus, in this tutorial, we will check how we can use cpplinq to filter an array of objects from a testing class. Our class will be very simple and it will model a person that has an id and an age. We will then build an array of these objects and filter it to obtain only the persons that have more than 40 years. We will make use of the where operator for this filtering, which we have also already covered in the previous post. The working principle of this operator is the same when operating over an array of objects: it receives as input a function that is applied for each element of the array and it should return true if that element fills our filtering criteria, and false otherwise. To illustrate that we can also chain operators when working with sequences of objects, we will then order the final sequence by the age of the persons. The tests shown on this tutorial were performed using an ESP32 board from DFRobot. The code As we have been doing in the previous tutorials, we will start by including the cpplinq library and declaring the use of the cpplinq namespace. #include "cpplinq.hpp" using namespace cpplinq; After that we will define a class called Person. For simplicity, we will keep the class declaration in the same file as the rest of the code. As already mentioned, our class will have two integer members: an id and an age. The constructor for this class will assign values to these two members. class Person{ public: int id; int age; Person (int t_id, int t_age){ id = t_id; age = t_age; } }; Moving on to the Arduino setup, we will start by opening a serial connection, to later output the results of the program. Serial.begin(115200); After this we will declare an array with objects of class Person, some of them filling our age criteria and others not. Person personArray[] = { Person(1,70), Person(2,14), Person(3,24), Person(4,30), Person(4,89), Person(5,50), }; To start applying the cpplinq operators, we need to convert our array to a range object first, like we did in previous tutorials when using integer arrays. We do this by calling the from_array function, passing as input our array of persons. from_array(personArray) After this we will filter the range by applying the where operator. As input, we will pass a function that will implement the filtering criteria. This function will be executed for each element of the array and it should return a Boolean value indicating if that element fills the filtering criteria (true) or not (false). The elements for which the function returns true (meet the filtering criteria) will be on the resulting range. The function passed to the where operator will receive as input the Person object of the current iteration. This means that we have the whole Person object if we want to apply more complex conditions over its fields. We will declare our function using the C++ lambda syntax. This makes the code more compact, since we avoid declaring a new named function to be used as input of each operator we use. When declaring the argument of our lambda (a Person object), we will specify it as const, so we don’t accidentally change its content on the function body. If so, the compiler will raise an error. The function implementation will just consist on comparing the age with the value 40 and returning true if the age is greater, and false otherwise. where([](const Person p){return p.age > 40;}) Just to illustrate the chaining of cpplinq operators, we will now order our results with a call to the orderby operator. In this case, since we are operating over an array of objects, we need to indicate the field over which the ordering should be done. This is also specified by passing a function as input of the orderby operator. This function is applied to all the elements of the array and thus, as before, it receives as input the Person object of the current iteration. It should return as output the value that will be used as ordering criteria. In our case, we will return the age of the Person. As shown below, we will again use the C++ lambda syntax. orderby([](const Person p){return p.age;}) After this we will convert the range to a C++ vector, so we can iterate it and print the results of the final sequence. The full expression tree can be seen below. auto result = from_array(personArray) >> where([](const Person p){return p.age > 40;}) >> orderby([](const Person p){return p.age;}) >> to_vector(); To finalize, we will iterate over the vector and print the id and the age of the filtered and ordered array. We will use the printf function of the Serial object to make it easier to format the result. for(int i=0; i<result.size(); ++i){ Serial.printf("{id: %d age: %d}\n", result[i].id, result[i].age); } The final complete code can be seen below. #include "cpplinq.hpp" using namespace cpplinq; class Person{ public: int id; int age; Person (int t_id, int t_age){ id = t_id; age = t_age; } }; void setup() { Serial.begin(115200); Person personArray[] = { Person(1,70), Person(2,14), Person(3,24), Person(4,30), Person(4,89), Person(5,50), }; auto result = from_array(personArray) >> where([](const Person p){return p.age > 40;}) >> orderby([](const Person p){return p.age;}) >> to_vector(); for(int i=0; i<result.size(); ++i){ Serial.printf("{id: %d age: %d}\n", result[i].id, result[i].age); } } void loop() {} Testing the code To test the code, simply compile it and upload it to your ESP32 device, using the Arduino IDE. Once the procedure finishes, open the Arduino IDE serial monitor. You should get an output similar to figure 1. As can be seen, only the Person objects with an age greater than 40 are printed, as expected. Additionally, the results are ordered by age.
https://techtutorialsx.com/2019/06/24/esp32-cpplinq-filtering-arrays-of-objects/
CC-MAIN-2020-40
refinedweb
1,100
54.73
import "github.com/Pashugan/trie" Package trie implements a thread-safe trie, also known as digital tree or prefix tree. It can be used as a drop-in replacement for usual Go maps with string keys. A Trie is an ordered tree data structure. NewTrie creates a new empty trie. Delete removes the data stored at the given key and returns true on success and false if the key wasn't previously set. HasPrefix returns the map of all the keys and their corresponding data for the given key prefix. Insert adds or replaces the data stored at the given key. Len returns the total number of keys stored in the trie. NodeNum returns the total number of internal nodes in the trie, which can be useful for debugging. Search returns the data stored at the given key. Package trie imports 1 packages (graph). Updated 2020-01-09. Refresh now. Tools for package owners.
https://godoc.org/github.com/Pashugan/trie
CC-MAIN-2020-05
refinedweb
154
76.01
j - JDBC jdbc import java.sql.*; public class MysqlConnect{ public static void main(String[] args) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306 Mysql & java - JDBC ; String url = "jdbc:mysql://localhost:3306/"; String dbName... on JDBC visit to : & java Hi guys, please help! I'm new to mysql, I want database connectivity - JDBC database connectivity example java code for connecting Mysql database using java Hi friend, Code for connecting Mysql database using...."); Connection conn = null; String url = "jdbc:mysql://localhost:3306. jdbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root...jdbc how can i store the image file and retrive the images from the database using java with querys also import java.sql.*; import management so i need how i can connect the pgm to database by using jdbc... at Thanks Hi, You can use following code to connect to Database with the help of JDBC API ) { System.out.println("Inserting values in Mysql database table!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db... information on JDBC-Mysql visit = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root...jdbc How can i store images in a database column without a front end... Friend, For inserting image into database,please go through the following link Database Connection - JDBC Database Connection In java How will be connect Database through JDBC? Hi Friend, Please visit the following link: Thanks Connectivity with sql in detail - JDBC ; String url = "jdbc:mysql://localhost:3306/"; String dbName... the following link:.... Thankyou. Hi Friend, Put mysql-connector jdbc jdbc please tell me sir.i dont know JDBC connection and how to create table in database jdbc jdbc why do we need to load jdbc drivers before connecting to database jdbc jdbc define batch updates define batch updates?exp JDBC... are executed simultaneously to a database as a single unit. The batch is sent to the database in a single request using connection object. The advantage of batch java error - JDBC ? import java.sql.*; public class MysqlConnect{ public static void main(String[] args) { System.out.println("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName image store in database - JDBC ; Inserting Image in Database Table... into the database what is the process to do that? Please explain... to store image into database. Check at jdbc driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test...jdbc i had written jdbc connection in method and i need to get connection in another class? import java.sql.*; ").newInstance(); con = DriverManager.getConnection("jdbc:mysql:///test... on JDBC visit to :...("Successfully connected to MySQL server..."); } catch(Exception e mysql problem - JDBC = "jdbc:mysql://localhost:3306/test"; Connection con=null; try...mysql problem hai friends please tell me how to store the videos in mysql plese help me as soon as possible thanks in advance  . jdbc - JDBC Java JDBC application Database Application in Java JDBC install mysql - JDBC install mysql i want to connect with mysql database.can i install mysql on local system please send me link how download mysql Hi friend, MySQL is open source database and you can download and install it on your how to connect JSP page to database - JDBC how to connect JSP page to database ?give program exception at runtime - JDBC java.sql.*; public class MysqlConnect { public static void main(String args[]) { System.out.println("MySQL Connect Example."); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "bank"; String JAVA & MYSQL - JDBC JAVA & MYSQL How can we take backup of MySQL 5.0 database by using...;Hi Friend, Please visit the following page for working example of MySQL backup. This may help you in solving your problem. java runtime exception - JDBC java.sql.*; public class MysqlConnect { public static void main(String args[]) { System.out.println("MySQL Connect Example."); Connection con = null; String url = "jdbc:mysql://localhost:3306 jdbc ; Concurrency Database concurrency controls ensure that the transactions... In database, a lock is used to access a database concurrently for multiple users... to write to the database. Any single user can only modify those database records cannot connect to database - JDBC cannot connect to database Iam using eclipse in my system ,when connecting the database mysql version 5.0 to the eclipse iam getting an error as ""Creating connection to mysql has encountered a problem.Could not connect to mysql add record to database - JDBC (); String url = "jdbc:mysql://localhost:3306/"; String db = "register...add record to database How to create program in java that can save record in database ? Hi friend, import java.io.*; import java.sql. mysql problem - JDBC of creation of table in mysql. it will take any image and store in database...mysql problem hai friends i have some problem with image storing in mysql. i.e while i am using image(blob) for insert the image it says Oracle Database error - JDBC = DriverManager.getConnection("jdbc:mysql://localhost:3306/register", "root", "root"); Statement...Oracle Database error String query11 = "SELECT product_code, product_quantity, price FROM o"+orderid; ResultSet rs11 Retrieving cells in MySQL - JDBC of the database and evaluate the answers for a score. Regards, Prem jdbc..., database-driven applications. Prerequisite for JDBC course You must... MySQL database Get a PC for you and install JDK, Eclipse and MySQL2ee - JDBC and then use JDBC api to connect to MySQL database. Following two tutorials shows how to connect to MySQL database: how to connect jsp to mysql Hi, Thanks jdbc What is the difference b/w jdbc driver and jdbc driver manager? Hello Freind See There are lot of database vender existing. So... and refer JDBC API. Thanks Rajanikant kindly give the example program for connecting oracle dase...*; import oracle.jdbc.driver.*; import oracle.sql.*; 2) Load and Register the JDBC..."); 3) Connect to database:*********** a) If you are using oracle oci driver JDBC - JDBC "); con = DriverManager.getConnection("jdbc:mysql://192.168.10.211...:// jdbc - JDBC jdbc how to fetch the database tables in a textfiles,by using databasemetadata&resultset.(i create a databaseconnection class and servlet class iam... information. = null; String url = "jdbc:mysql://localhost:3306/"; String dbName.... Thanks jdbc - JDBC Example!"); Connection con = null; String url = "jdbc:mysql://localhost...; String url = "jdbc:mysql://192.168.10.211:3306/amar"; String driver...(); } } } --------------------------------------------- Visit for more information: JDBC Components Database Connectivity. For connectivity with the database we uses JDBC.... JDBC gives you the opportunity to communicate with standard database. JDBC... and retrieve results and updation to the database. The JDBC API is part of the Java jdbc - JDBC jdbc Hi.. i am running the servlet program with jdbc connections in this porgram i used two 'esultset' objects.. in this wat ever coding... and also deleted. after operation try to retrieve the value again or goto database ResultSetMetaData - JDBC in Database!"); Connection con = null; String url = "jdbc:mysql...; Hi, JDBC provides four interfaces that deal with database metadata...!"); Connection con = null; String url = "jdbc:mysql://localhost:3306 error - JDBC conn = null; String url = "jdbc:oracle:thin:@localhost:1521:xe"; String... to the database"); conn.close(); System.out.println("Disconnected from database"); } catch (Exception e) { e.printStackTrace database - JDBC database hai friend, yes i want to use java database connection in eclipse IDE. Thanks in advance java - JDBC import java.sql.*; 2. Loading a database driver String driver = "com.mysql.jdbc.Driver"; 3.Creating a jdbc Connection String url = "jdbc:mysql://localhost:3306/"; String username = "root"; String password jdbc & sql related project - JDBC jdbc & sql related project code using jdbc,odbc,swing,MySql classes to create front-end of any jdbc that allows the user to select any database... = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root
http://www.roseindia.net/tutorialhelp/comment/93208
CC-MAIN-2014-15
refinedweb
1,277
51.55
On May 30, 2008, at 8:14 PM, Duncan McGreggor wrote: > On Fri, May 30, 2008 at 2:03 PM, <glyph at divmod.com> wrote: >> You've convinced me. I still think "Twi" sounds okay (better than >> "Twisty") >> "Tx" (evocative of "TwistedmatriX", "Transmit", "Twisted >> multipleXed"?) >> "T"? I'd suggest "Tw" but I feel like it has to be >> pronounceable, and "Tw" >> forces the first letter of your project to be a vowel (whereas >> "Tx" could be >> pronounced "Tix"). >> >>> I think a one- or two-letter prefix is pretty much the best option > > Man, I think you totally hit it on the nose with your "tx" suggestion: > tx.snmp, tx.storage. I maintain the Twisted-JSONRPC package, and I > will change the namespace from twisted.web.jsonrpc to tx.jsonrpc. Not > only does it have a cool sound, entails "TwistedmatriX", is associated > with "transmit", but it could also stand for "Twisted eXtensions" (in > the "add on" sense). I was about to second this point before I left work tonight, but got distracted. I like it even better with the dot notation, e.g., tx.whatever. -phil
http://twistedmatrix.com/pipermail/twisted-python/2008-May/017821.html
CC-MAIN-2016-18
refinedweb
185
62.58
SETBUF(3P) POSIX Programmer's Manual SETBUF(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. setbuf — assign buffering to a stream #include <stdio.h> void setbuf(FILE *restrict stream, char *restrict buf); The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2017 defers to the ISO C standard.. Although the setvbuf() interface may set errno in defined ways, the value of errno after a call to setbuf() is unspecified.. Since errno is not required to be unchanged on success, in order to correctly detect and possibly recover from errors, applications should use setvbuf() instead of setbuf(). None. None. Section 2.5, Standard I/O Streams, fopen(3p), setvBUF(3P) Pages that refer to this page: stdio.h(0p), fputc(3p), fputwc(3p), setvbuf(3p), stdin(3p), ungetc(3p), ungetwc(3p)
https://www.man7.org/linux/man-pages/man3/setbuf.3p.html
CC-MAIN-2022-27
refinedweb
186
56.15
React basic 2 — JSX, the syntax extension to JavaScript that looks like HTML As you might have seen from the last React app post (React basic 1 — “Hello React World”. Setting Up Your First React App.), this funny syntax that looks like HTML, called JSX, is commonly used in React to format UI template. JSX is an extension of JavaScript that helps engineers to visualize how the UI looks like. In this entry I would like to list some of syntax rules and capabilities around JSX. Some specific syntax for JSX that is different from HTML In order to clearly differentiate from common syntax used in JavaScript, you either have to or are recommended to use some unique syntax like the followings in JSX: class should be className <div className = "header"> Some title </div> for should be htmlFor <label htmlFor = "name"> Enter name: </label> Inline styles Inline styling for each tag has to be represented within {}, in the format of a JavaScript object, then each value has to be written inside of quotation marks (the use of ' ' is more common practice in the community than the use of " "). <div style = {{ backgroundColor: 'blue', color: 'white' }} ></div> The use of JavaScript variables and functions You can reference variables or call functions just like in regular JavaScript. To access variables or functions from JSX, you have to use {}. const buttonText = 'Click Me!';function getTime() { return (new Date()).toLocaleTimeString() }return ( <div> <button style = {{ backgroundColor: 'blue' }}> {buttonText} </button> <div>Current Time:</div> <h3> {getTime()} </h3> </div> </div>); One most parent tag has to be closed inside JSX >
https://takuma-kakehi.medium.com/react-basic-2-jsx-the-syntax-extension-to-javascript-that-looks-like-html-fa0b154c7f2b
CC-MAIN-2021-25
refinedweb
262
56.08
Hi, It's all in the documentation.... HTH Andr 1. Qtable displaying bug in my program and also in QtDesigner. Hi, - System : RedHat Linux 7.1 /, 6.1 - Compiler : gcc-2.96 / egcs-2.91.66 - QTVersion: Qt 2.3.1 binaries/devel from KDE.2.2 site.(try with others qt 2.3.1 version and also with a version compiled by myself). - Tested Computers : Intel Pentium II 350, Pentium III 800 & 650, Bi PII 400 - Graphic card tested : Matrox G200/G400 8/16mo with hardware accelration and without, ati rage mobility 8mo. I think that I have found a bug in QTable or parents classes. The bug is : When you fix the number of rows of a QTable to a limit, the table still working well but you cannot see the cells values. What it is strange is that you can edit it, the value is shown during the operation but after it disappears. I'm using qt since a long time for the Tulip project and this bug seems to be new. In older version before 2.3.0 I haven't got this problem. If you want to see the bug, try to build a table with 10000 rows with qtDesigner you will see that the grid is not drawed, You can also try the following sample. On my computer, with this program I can see cells until the 170th(I can only see the half of the last row) rows after there is nothing but I can edit it. I searched a lot to correct this bug myself but I didn't find from where it comes. Can you mail me if you already now this bug and/or if it will be corrected soon ? Regards Source code : #include <qapplication.h> #include <qtable.h> #define NUM_ROWS 10000 #define NUM_COLS 5 int main(int argc, char **argv) { QString str; int r, c; QApplication app(argc, argv); QTable table(NUM_ROWS, NUM_COLS); app.setMainWidget(&table); for (r = 0; r < table.numRows(); r++) { for (c = 0; c < table.numCols(); c++) { str.sprintf("item %ld, %ld", r+1, c+1); table.setText(r, c, str); } } table.resize(640, 480); table.show(); return app.exec(); 3. HOW to change the color of cell in QTable (Qt)? 4. 3com 3c509b etherlink problem -- I have tried for a LONG time! 5. Unix Programming & Linux Programming Question 6. Disk space usage. HELP! 7. Parallel Port programming question, was "Serial Port Programming" 8. what is a good e-mail program? 9. Linux programming question / Network Programming 10. Programming question: Can I get filesystem info in a C program? 11. "Mary had a neat program...neat program...neat program... 12. ** Programming question.. ** 13. socket programming question.
http://www.verycomputer.com/188_e574654cbed68127_1.htm
CC-MAIN-2022-21
refinedweb
450
78.14
// Description: This program gets a string from a dialog box. // File: dialogInputOutput/ThirdProgram.java // Author: Michael Maus // Date: 29 Jan 2005 import javax.swing.*; public class temp { public static void main(String[] args) { String temp; // A local variable to hold the name. Object conversion = (5.0 / 9.0) (temp - 32); temp = JOptionPane.showInputDialog(null, "enter a Temperature Here"); JOptionPane.showMessageDialog(null, "The Temperature you entered of, " + temp \n "Celsius" + conversion); } } I need help with this code not sure what I am doing wrong. Any help would be greatly appreciated. This post has been edited by g00se: 14 November 2010 - 08:36 AM
http://www.dreamincode.net/forums/topic/200049-temperature-conversion/
CC-MAIN-2013-20
refinedweb
102
61.22
Okay so im working on a project and im using instance variables and two dimensional arrays and i see nothing wrong what iv done so far can anyone see what is wrong?? Code : import java.awt.*; import hsa.Console; import java.io.*; import java.text.*; import java.util.Random; public class Basketball /* *Module 14 Assignment *July 21 2011 */ { static Console c = new Console (); public static int x, i, names, choice, smallest; public static String player[][] = new String[1001][7]; public static String temp; public static void main (String[] args) { do { //MENU c.print("Main Menu"); c.print("\n1. Enter Player Data"); c.print("\n2. Show Data by name"); c.print("\n3. Show data by stats"); c.print("\n4. Search Players"); c.print("\n5. Modify Player"); c.print("\n6. Delete Player"); c.print("\n7. End Program\n"); c.print("Please enter a choice (1-7)\n"); choice = c.readInt(); if ((choice < 1) || (choice > 7)) c.print ("\nPlease choose a number between 1-7 only"); if (choice == 1) enterdata(); if (choice == 2) showname(); if (choice == 3) shownum(); if (choice == 4) search(); if (choice == 5) modify(); if (choice == 6) delete(); } while ((choice < 1) || (choice > 7)) ; } //Option 1 public static void enterdata() { c.clear(); c.print("You have selected to input player data\n"); c.print("How many players are you going to input?\n"); names = c.readInt(); for (x=0;x<=names;x++) { c.print("What is the players first name?\n"); player [x][0] = c.readLine(); c.print("What is the players last name?\n"); player [x][1] = c.readLine(); c.print("What position does this player play?\n"); player [x][2] = c.readLine(); c.print("What is the players height?\n"); player [x][3] = c.readLine(); c.print("What is the players weight?\n"); player [x][4] = c.readLine(); c.print("How many points has the player made?\n"); player [x][5] = c.readLine(); c.print("How many blocks has the player made?\n"); player [x][6] = c.readLine(); c.print("How many steals has the player made?\n"); player [x][7] = c.readLine(); } } There is more to the code, this is just the part that i think is wrong any suggestions??
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/10036-whats-wrong-my-code-printingthethread.html
CC-MAIN-2015-48
refinedweb
361
72.12
# Roslyn API: Why PVS-Studio Was Analyzing the Project So Long How many of you have used third-party libraries when writing code? It's a catchy question. Without third-party libraries the development of some products would be delayed for a very, very long time. One would have to reinvent the wheel to solve each problem. When you use third-party libraries you still stumble upon some pitfalls in addition to obvious advantages. Recently PVS-Studio for C# has also faced one of the deficiencies. The analyzer could not finish analyzing a large project for a long time. It was due to the use of the SymbolFinder.FindReferencesAsync method from the Roslyn API in the V3083 diagnostic. ![](https://habrastorage.org/r/w1560/getpro/habr/upload_files/b03/e4f/1a0/b03e4f1a044ee14a9fd7cda7042cbee9.png)Life in PVS-Studio was going on as usual. We kept on writing new diagnostics, improving the analyzer, posting new articles. Bang! One of the analyzer users had the analysis going on a large project during the day and could not end in any way. Alarm! Alarm! All hands on deck! After getting dump files from the user we shifted our focus to find out the reasons for long analysis. It turned out that 3 C# diagnostics worked the longest. One of them was the diagnostic number V3083. This diagnostic has already had our special attention. The time has come to take specific actions! V3083 warns about incorrect C# event calls. For example, in the code: ``` public class IncorrectEventUse { public event EventHandler EventOne; protected void InvokeEventTwice(object o, Eventers args) { if (EventOne != null) { EventOne(o, args); EventOne.Invoke(o, args); } } } ``` V3083 will point to calls to event handlers of *EventOne* in the *InvokeEventTwice* method. You can learn more about the reasons why this code is dangerous in this diagnostic's [documentation](https://pvs-studio.com/en/w/v3083/). From the outside, the logic of the V3083 is very simple: * find an event call; * check if this event is called correctly; * issue a warning if the event is called incorrectly. Now when we know that it is so simple, it becomes even more interesting to get the reason for the long diagnostic work. ### Reason for the slowdown In fact, the logic is a little more complicated. In each file for each type V3083 creates only one analyzer warning for an event. In this warning, V3083 writes all line numbers of cases when the event is incorrectly called. This helps to navigate in various plugins: [Visual Studio](https://pvs-studio.com/en/b/0635/), [Rider](https://pvs-studio.com/en/m/0052/), [SonarQube](https://pvs-studio.com/en/m/0037/). It turns out that the first step is to find all the places where the event is called. For a similar task, Roslyn API already had the *SymbolFinder.FindReferencesAsync* method. It was used in V3083, so as not to reinvent the wheel. Many guidelines recommend using this method: [first](https://dotnetdevlife.wordpress.com/2018/10/17/using-roslyn-to-find-all-references/), [second](https://riptutorial.com/roslyn/example/30101/get-all-the-references-to-a-method), [third](https://coderoad.ru/44167269/Roslyn-SymbolFinder-%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%BC%D0%B5%D1%81%D1%82%D0%BE%D0%BF%D0%BE%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F-%D0%B2-%D1%81%D0%B8%D0%BD%D1%82%D0%B0%D0%BA%D1%81%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D0%B9-%D1%83%D0%B7%D0%B5%D0%BB) and others. Perhaps, in some simple cases, the speed of this method is enough. However, the larger the project's codebase, the longer this method will run. We were 100% sure of this only after changing V3083. ### V3083 speed up after the change If you change a diagnostic's code or the analyzer core, you need to check that nothing that worked before is broken. To do this, we have positive and negative tests for each diagnostic, unit tests for the analyzer core, as well as a database of open-source projects. There are almost 90 projects in it. Why do we need a database of open-source projects? We use it to run our analyzer to test the tool in field conditions. Also this run serves as an additional check that we have not broken anything in the analyzer. We already had a run of the analyzer on this base before the V3083 change. All we had to do is to make a similar run after changing V3083 and figure out the time gain. The results turned out to be a pleasant surprise! We got a 9% speedup on tests without using *SymbolFinder.FindReferencesAsync*. These figures might seem insignificant to someone. Well, check out the specs of the computer that we used for measurements: ![](https://habrastorage.org/r/w1560/getpro/habr/upload_files/026/cf6/7de/026cf67dec998634ee8d1e949413160f.png)Hopefully even the most cynical skeptics have fully realized the scale of the problem that lived quietly in the V3083 diagnostic. ### Conclusion Let this note be a warning to everyone who uses the Roslyn API! This way you will not make our mistakes. Not only does this apply to the *SymbolFinder.FindReferencesAsync* method. It is also about other *Microsoft.CodeAnalysis.FindSymbols.SymbolFinder* class methods that use the same mechanism. I also highly recommend that all developers review libraries they use. I say this for a reason! Why is it so important? Check out our other notes to find out why: [first](https://pvs-studio.com/en/b/0762/), [second](https://pvs-studio.com/en/b/0654/). They cover this topic in more detail. Apart from developing diagnostics we've been busy optimizing PVS-Studio. Don't miss future articles and notes to find out about changes! We haven't released the V3083 diagnostic fix, therefore the analyzer version 7.12 works using *SymbolFinder.FindReferencesAsync*. As I mentioned earlier, we found the analyzer slowdown in two other C# diagnostics besides V3083. How do you think, which ones are these diagnostics? Just for the sake of interest, leave your ideas in comments. When there are more than 50 suggestions, I will open the veil of secrecy and call the numbers of these diagnostics.
https://habr.com/ru/post/553786/
null
null
1,065
58.89
Details - Type: New Feature - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: None - - Component/s: modules/spatial - Labels:None - Lucene Fields:New Description. Issue Links - is depended upon by - - relates to LUCENE-2599 Deprecate Spatial Contrib - Closed - Activity - All - Work Log - History - Activity - Transitions The spatial-lucene module of LSP has 3 main packages: 'base', 'strategies', and 'benchmark'. It also has a fair amount of tests. Base Major pieces in 'base': - SpatialContext interface and simple implementation - Distance math code - Shapes interface and implementations - PrefixTree/Trie (grid) interface and implementations (e.g. geohash) Strategies The "strategies" portion of this module contains spatial indexing/search implementations using Lucene. Major interfaces (just one): - SpatialStrategy (including abstract PrefixGridStrategy) Major implementations: Benchmarking Benchmarking is a TBD; there's the start of some code there but nothing real. 1 year ago I did benchmark SOLR-2155 (with great results) and posted my benchmark code here LUCENE-2844 in the interest of transparency. Testing Testing so far hasn't been aimed directly at increasing code coverage, it's been aimed at finding nasty corner cases in spatial. Spatial code is highly prone to edge cases. Features The main goals of LSP is to be a great framework to plug in spatial search algorithms and shape implementations. It of course includes good implementations of these key abstractions. Here are some key features, most of which related to using RecursivePrefixTreeStrategy with geohashes: - Multi-valued fields - Index shapes that have area (e.g. not just points) Tests have yet to be added for this. - No special RAM caches for filtering, just standard term index Unlike Solr's LatLonType which needs to cache all points in RAM if the query shape is a circle - Fast filtering Although SOLR-2155has been proven, technically LSP hasn't. 3rd party anecodes re-inforce this claim. - Multi-value sort Based on closest index point to center of query shape. Distances are returned via the score of an LSP query. - Specify precision of query shape and index shape Thereby allowing for faster filtering tunable precision - Multiple distance algorithms: - Spherical: Law of Cosines, Haversine, Vincenty - Cartesian: Pythagorean Theorem - Cartesian (2d flat) & Geospatial sphere models Todo There are many things I want to improve and add but in my view there isn't anything truly making this non-committable. Chris has raised concerns that the other committers will want to see benchmark results before accepting this. I'll leave that for you (the other committers) to decide. And I also heard that some committers are unsure wether Lucene should have a spatial module at all. However there is certainly demand for it, at least at the Solr level. Furthermore, there are some non-spatial use cases of the spatial module. One interesting use-case is RecursivePrefixTreeStrategy's (RPTS) unique ability to index shapes with area. If you had a requirement to index a variable number of time durations, then unlike Lucene's trie numeric support in which only discrete numbers are supported, RPTS could be used with x being time and y being unused. Buy the way, PrefixTree and Trie are synonymous words.! Simon do we really need a code grant here? Its my understanding (correct me if i am wrong): the developers involved (David, Ryan, Chris) are all committers with iCLA on file, so is it really any different than any other patch from that perspective?). Without looking at any code myself, if thats really the case I'm +1 on principle because it means we basically have an improved spatial module for lucene core with no catch at all. The current code has not seen much maintenance. (And i agree, we should be shooting for a proper module/ here, not a contrib). ... do we really need a code grant here? I think if you go by the letter, since it was 'developed' outside of the Apache ecosystem, we want a code grant. I wonder where apache-extras fits there though. Personally, if it was all only developed by committers in a public repo, I don't have a problem with being practical - FWIW though - I'm just one guy INAL. Impressive piece of work! Given license stuff is ok, here is my +1 Cool work! I scanned the code quickly and it seems to fit much better than the current spatial! I have some suggestions regarding performance; BooleanQuery usage and related inconsistency with BQ scoring (with coord) in the different strategies; also found some caching problems (AtomicReader is key to cache not AtomicReader.getCoreCacheKey, so new deleted docs after reopen invalidate the cache), but I would prefer to discuss that here once the patch is provided on Lucene's JIRA. Huge +1 Thanks so much David for opening this issue and getting the code to a point where it can be contributed. I'm really excited to see this brought into the fold and glad to see support from others.). Absolutely. The portion of the codebase which uses LGPL code is entirely optional and decoupled from the rest of the code. From a functional perspective, as David says, its only really related to polygon support which is hugely powerful but can exist somewhere else if needs be. but I would prefer to discuss that here once the patch is provided on Lucene's JIRA. Is it best to create a patch here and iterate on any problems, or create a branch and work through them there?). +1, Lucene badly needs good ootb spatial search. I think a branch makes complete sense... we've made branches for much smaller things! Uwe, Thanks for bringing java.awt.geom.Area to my attention; I haven't noticed it before. It looks workable, and the code for it looks impressive to me. As an aside, JTS has a particularly scalable polygon scaling to many vertexes which get stored in an in-memory RTree – although I don't think this feature is as pertinent for user-input polygons which would have a small number. It is unfortunate that sun.awt.geom.Crossing is not exposed from Area, since computing it is not particularly cheap and LSP will ask Area two things – intersects() and contains() given a lat-lon box, and Area will compute the same Crossing twice. Use of this in LSP would not be a "stategy", it would be a subclass of SpatialContext which acts as a factory for shapes. Speaking of which, I'm thinking of renaming the "simple" package to be something else like "impl" since some of the implementations are decidedly not simple – GeoCircleImpl case in point, and the addition of a polygon would seal that point. I look forward to working with you more Uwe. It appears we do a lot of similar work – geospatial and trie stuff. +1 getting polygon support ootb is huge as is geohashing and multivalued lat longs. Next step Solr... Thanks for pushing this forward David! (sorry i have been offline recently... just had a baby!) We should defiantly make a branch for this – getting things integrated with the build system will be non-trivial. Re code grant? given that all developers of this code are lucene committers and intend for this be contributed to ASF, I don't think it is necessary. But if we need more paperwork, that is OK too. Re polygons / AWT / JTS? I hope this code lets us use an implementation that is appropriate for the need. In some cases, simple math or java.awt.geom may be fine, in others JTS will be necessary. My fear is that with JTS out of the core build/test system, JTS will be a secondary concern. Through this process, I will continue to make sure any design decisions don't exclude a solid JTS solution. David – do you want to go ahead and make a branch and integrate: I still think we want a .jar file for the spatial code/API that does not need lucene. This will be important for non-lucene clients that should be able to deal with real classes rather then strings. I created a branch from r1291350 (the most recent version with passing tests as indicated by Jenkins) Branch Status Update: - LSP Lucene spatial is in as a module, actually as two modules, spatial/base & spatial/strategy. That complicates the build but Chris & Ryan insist. The maven build works. - Old spatial contrib is gone. - Solr is updated to use the new module. 80% was trivial changes, 20% pretty easy. Nothing hard. Tests pass. - IntelliJ IDEA build seems done (I use IDEA) - Eclipse build is probably done (Ryan worked on it, I don't use it) - Maven build is done. That was easy! - Ant build in progress. The Solr side isn't seeing the spatial libs. LSP Lucene spatial is in as a module, actually as two modules, spatial/base & spatial/strategy. That complicates the build but Chris & Ryan insist. The maven build works. I don't recall insisting that here. I think we should do what's best in this situation. If having two sub modules is causing too much difficulty for no benefit, then +1 to reducing them to one.. What is the advantage of two spatial modules? Can I run spatial queries with just base by itself? For benchmarking code, why not put it in the benchmarking package and have benchmark depend on it (thats how all other modules, highlighter, analyzers, anything else we benchmark works) What is the advantage of two spatial modules? Can I run spatial queries with just base by itself? The real advantage is that client code (solrj etc) can know about Shapes/Operations without needing to include lucene. From spatial-base, you can build queries and understand the results; but can't run the query. I need my client code to use a real API rather then needing to build the correct String query representations and parsing results. Rob, thanks for your suggestion/opinion on putting the spatial benchmarking code into the benchmarking module. Works for me – one less module. Ryan, how would you feel about a single combined spatial module that you would use from your remote SolrJ client? Yes, it wouldn't be great that the jar would be half filled with classes you don't need (the spatial strategies coded against the Lucene API) but is that really such a big deal? It would be annoying to configure your maven build to not include the transitive dependencies but it's doable, and perhaps we could mark lucene as an optional dependency in a combined spatial module. In practice, anyone using this spatial module on the server will certainly have lucene already. I guess I don't see the problem with having multiple .jar files (aside from the ant setup effort) I'm fine with one .jar if we guarantee that the 'base' classes don't have compile time access to lucene classes. I'm sure there is some ant crazieness to compile half the project with different classpaths then bundle them together, but that seems more complex (and less clear) then two .jar files Chris, in an email months ago you declared interest in a client library jar, and Ryan absolutely insisted. The difficulties have been figured out. Indeed I did but that was when we were developing this outside of Lucene, I'm now thinking what's best for Lucene and am open to any ideas. I need my client code to use a real API rather then needing to build the correct String query representations and parsing results. Are you able to give us some more information on what your client code needs? Is it just being able to instantiate a Shape and then convert it to a queryable String format? perhaps we could mark lucene as an optional dependency in a combined spatial module. +1 This seems like the best compromise I'm fine with one .jar if we guarantee that the 'base' classes don't have compile time access to lucene classes. I also agree with this and we should bare it in mind as we progress. My preference is one module vs. multiple. Now that Ryan and Chris are cool with this, we can continue with that objective. Tomorrow night or sooner I'll get on merging them together. Ryan and I chatted about this issue more and I didn't take consolidation steps yet. I'm pretty neutral, by the way – I see both sides. Another option occurred to me and I'm excited about the prospects because I think it's a good balance. To be clear, spatial-base has nothing to do with Lucene. It largely consists of shape interfaces with implementations, has some distance calculators like Haversine and other spatial calculations, and can (or at least should) parse and emit some dialect of WKT – a popular standard, extended where needed to represent shapes that aren't in WKT such as a circle. There's a good deal of testing too. It is certainly useful in its own right just as other spatial libraries are. To defend its existence when there are other spatial libraries, I'll point out a few things that make this more desirable than other 3rd party libraries: - ASL licensed; required for acceptence by the Lucene PMC - Geospatial orientation, not just 2D. FYI JTS is purely 2D. - Has shapes not found in other libraries like a point-distance (circle) shape. It's inexplicable to me why this isn't elsewhere. And this shape isn't just some POJO for a point & radius, there is sophisticated math for the various relations (e.g. disjoint, contains, etc.) of rectangle-circle intersection. - Performance oriented – it was developed concurrent with lucene spatial search algorithms and I try to keep this in mind. So how about spatial-base remains in the LSP project off-Lucene. LSP and this component will both probably receive a name change and possible re-hosting on Github. LSP (or whatever its eventual name is) will always need to exist any way because there are integration scenarios involving LGPL libraries that the Lucene PMC is uncomfortable with, and there is a nifty demo webapp too. The spatial-extras module could probably be merged with spatial-base, making testing easier and it's one less jar. If spatial-base becomes a 3rd party library required by a single Lucene spatial module, then that brings a simplicity to the code organization insofar as there is just one spatial module, not 2. It also means that the spatial module will be entirely focused on the intersection of Lucene & spatial, and not have other code unrelated to Lucene. When deployed, it would mean 2 jars, the spatial-base.jar (or whatever its renamed to) and lucene-spatial.jar. FYI Solr, at least for the moment, would only need the base one, not lucene-spatial. The down side is that both spatial-base and lucene-spatial are in-progress and are largely developed together, and so separating them to live on independent projects will bring about some extra burden in syncing them from time to time. This is reminiscent of the Lucene & Solr projects before they were merged. To mitigate this, our spatial team (me, Ryan, Chris) can initially focus on making changes to the public API of spatial-base to the point we like it even more and are less likely to change it. I like the idea that spatial-base would be external to lucene, and included as a .jar file. This was my original proposal when starting to discuss this long ago. As is, the spatial library is quite useful on its own; I think it has the best chance of long term success outside of lucene. Outside lucene (ASF) it can have compile/test dependencies on JTS that make it more robust but still have strong ASL only runtime. For those following along here, the former "spatial-base" module portion of this code is now an ASL licensed 3rd party jar dependency: "Spatial4J" Basically half of LSP is there now going by this new name. The other half is here as the new lucene spatial module. I agree that the branch looks ready to be merged into trunk. Can we rethink this structure? In my opinion there is a little bit of dll-hell going on on. From Lucene's perspective as a library, 3rd party dependencies are extremely expensive. I realize this doesnt matter so much for solr, since its an app, but I think we should minimize this. We all agreed modules should be treated like lucene core (which has no dependencies), and sure, some modules do have dependencies but they should be minimal and necessary. Just looking at the lib/ directory in the branch I see: - commons-lang.jar: This is unnecessary and only used for EqualsBuilder/HashCodeBuilder, please remove! - slf4j.jar: Lucene doesnt do logging: there have been numerous discussions about this, such logging should be at a higher level app like solr. But, this doesnt seem to be 'actually' used anyway... please remove! - spatial4j.jar: I think this approach should be re-thought. I dont understand the advantage of creating the extra level of indirection to a github project here. I also have no clue what dependencies this jar itself has... furthermore i dont even know how to get the source code for this binary jar, there is only a github link with no branches or tags to indicate "0.1". I think all of this is a big no-go. Also again about my spatial4j.jar: besides the dll-hell perspective, there is also the community perspective. I dont think we should create github projects that only a few people can commit to and then link binary jars from them into lucene's source tree. I dont think we should create github projects that only a few people can commit to and then link binary jars from them into lucene's source tree. +1 commons-lang.jar: This is unnecessary and only used for EqualsBuilder/HashCodeBuilder, please remove! die, die, die To come back to an earlier comment: I don't like projects that add a 15 MB JAR file and use one single method/class out of it (this is of course an extreme example). In my opinion, common-lang.jar should only be used, if you heavily depend on it. And if you really want to use it, use version 3 (o.a.commons.lang3 package), not the Java 1.1 versions. Most of the stuff in commons-lang is useless since java 5 and the old pre-commons-lang3 is not typesafe at all (and has millions of bugs regarding unicode). I agree with robert, can we try to survive without dependencies? What is the reason to have this stuff on github, its your projects anyway right? also the spatial4j notice file is a copy of the commons lang. simon What's the reason to have spatial4j outside of Lucene? First, Ryan and David, I think you've done a great job with all this code and a million thanks for donating. I think I also see the rationale behind splitting the more general spatial4j core into a separate project, hoping that it will attract far more users than only Lucene. While that may happen one day, perhaps we should take one step at a time, letting spatial4j start its life as part of Lucene-java (as a separate module or contrib?), and after a year or. commons-spatial sounds attractive to me >>IMAGE. In my opinion seems like the correct home. Of course the code could be donated there in parallel, if it starts picking up steam and graduates from the incubator, then it would be the right thing to depend on it I think? Commons-lang is used by both Spatial4J and the new spatial-module. This dependency can easily be severed and will happen shortly.. Uwe and others, the rationale for a core spatial library off of Lucene is my last (long) comment: For what its worth, Ryan and I absolutely love the plan for all of the points in it. I wish someone had expressed their dissenting opinion on it at that time – From Ryan and I's perspective there basically isn't anything not to like. Can anything be done to warm people up to this? Rob; you're absolutely right that there needs to be a release tagged in the Spatial4J repo. Ryan has already taken steps to get this library in published Maven repos which is the most meaningful step that could be taken to officially release it. Again, we should certainly tag it because it is both best practice and easy. The ASF is a bit heavy on process and less permissive on interactions with LGPL dependencies (even optional ones?) and so I don't think ASF/incubator is a good place for Spatial4j as an independent project. As frustrating as I find it, the making of spatial-4j could be reverted, returning back to the 2-module setup that some people here seemed to express resistance to. The ASF is a bit heavy on process and less permissive on interactions with LGPL dependencies (even optional ones?) Which is a great thing in my opinion if we are going to depend on an external library for spatial support. Why not help Apache SIS grow and contribute spatial base as a module there. Then make the Lucene/Solr parts a contrib part in SIS or here. I'm sure they would love the support and would hope to get the developers of spatial base as key members of their community. This would put spatial stuff in one place and help an Apache spatial community grow. This seems more like the Apache way. That said, I am jumping in late to this discussion but I think spatial stuff really deserves its own community at Apache.! -------------- We all agreed modules should be treated like lucene core hymmm – my understanding is that modules have flexibility to have dependencies that are appropriate. Commons-lang is used by both Spatial4J and the new spatial-module. This dependency can easily be severed and will happen shortly. Fine!. In my opinion, non-end-user components should not log, which affects libraries. E.g. there is nothing in the JDK to enable logging of the JDK itsself, although there are surely parts that could log something. Lucene is the same, it does not need to log anything, the client code should log things like "now executing term query..." and so on. IndexWriter is a little bit special, it has now a simple "log-like" interface for debugging (consisting of abstract InfoStream class). This class can be implemented by a logging framework, but would slowdown indexing immense, as logging frameworks tend to use volatiles on every log request (even when not logging). So I strongly recommend to remove logging. For debugging we often comment out System.out.println inside Lucene. Uwe and others, the rationale for a core spatial library off of Lucene is my last (long) comment OK, OK. I still don't understand the whole rationale to move it outside Lucene or to a separate module. Everybody can use the classes by adding the JAR file, too. The "useless" lucene classes don't hurt. Still I would strongly recommend to use parts of lucene.util package whereever possible, especially when performance and easy Lucene integration is needed. So dont create Strings all the time, use BytesRef and index/search using binary terms like NumericField does in Lucene trunk. If this module outside Lucene uses Strings all the time, but e.g. when indexing searching all those strings are again converted to UTF-8 BytesRefs, thats a laaaaaaaaaaaaaaarge overhead. So I prefer to sometimes duplicate code and add performant impls of e.g. term encoders for indexing/search. Every method in Lucene that is used in tight loops (like scorers or TokenStreams) should never ever use Strings (which are final and unmodifiable). Everything depends on something. Lucene depends on Java, and it has no control over Java except to complain when there are bugs. This module isn't the first module to have a dependency and frankly I don't understand the aversion to them – it's a natural thing. I agree you can have too many. I think Lucene-Spatial's dependency on Spatial4j represents the best type of a dependency that Lucene/Solr could have: - ASL licensed - Has code & tests there that aren't related to Lucene; don't clutter or diffuse scope of Lucene's codebase. - Strong relationship to Lucene/Solr. Put another way, if Spatial4j were a product, it's only customer right now is Lucene/Solr. Consequently: - When Lucene/Solr decides to release a version, Spatial4J committers will do the same. No SNAPSHOT dependency from a Lucene release. - When a bug or feature request comes up via Lucene that requires changes in Spatial4J, you (a Lucene committer) can coordinate these changes with great efficiency given that you know Spatial4J committers. - You can become a committer on Spatial4j with far less time than it took me to become a committer here, I swear – especially the spatial-minded folks: Chris (if we had your GitHub username, you'd be grandfathered in), Uwe, Grant, Yonik? And because it's a dependency and not 1st-party code, it has a greater opportunity to receive improvements from outside parties since it's a smaller project with a more focused committer pool. This stuff has nothing to do with Lucene, remember. classes! Why not help Apache SIS grow and contribute spatial base as a module there. +1 Wouldn't it be nice to roll all of these fundamental concepts in to a single project like SIS? I agree – but the elephant in the room is the LGPL library JTS. From previous discussions, I believe this was a non-starter for their compile/test environment, but I have emailed the sis-dev@ list to see if this is still their feeling. With spatial4j, we want a solid ASL solution, but also support complex polygons if people choose to use JTS in their runtime environment. I have confirmed with SIS that a compile/test dependency on JTS in not possible. (One of their main goals is to make an ASL version of JTS... A great goal, but they are not yet to 1st base) So, where does that leave us? Is the spatial4j.jar a blocker for anyone? I understand it is not everyone's preferred option – but no option makes everyone happy. I'd encourage folks to read: and all of the surrounding discussion there. Quoting Greg Stein: I simply think that it is a mistake for a PMC to create any sort of dependency upon code that is more restrictive than the Apache License. In this case, it means somebody must grab LGPL code in order to build our provided tarball. I would strongly advise against such a build dependency, whether the runtime requires it or not. I strongly agree with his interpretation. PMC to create any sort of dependency upon code that is more restrictive than the Apache License. Note, the spatial4j.jar file is ASL No user ever needs to touch LGPL code or artifacts Ryan... Why not just include spatial4j.jar into Lucene/Solr and later separate it. It looks like SIS is not even off the ground yet. In my opinion an API is not really an API until 3 or more projects use it anyways. Why not make JTS pluggable as a separate module into Lucene? Then people can download JTS and add it into the Spatial solution by modifying a config file like solrconfig.xml ? I would love to get this committed and done done. Bill It looks like SIS is not even off the ground yet. I guess if you call making an Apache release, with a working Java Quad Tree implementation, point-radius and bounding box against that QuadTree, the ability to load GeoRSS, and a demo webapp that plugs into Google Maps, "not even off the ground yet", then yeah, I guess it's not. I think this is ready for /trunk Unless there are objections, I will commit tomorrow – and we can iterate from there I'm still hoping the logging issue will get resolved. Can we please remove this dependency? Again I don't think we should be logging at this level. For example its dangerous and bogus to suppress exceptions and log instead: this is an API component. Higher level code (e.g. Solr) with more context can implement logging appropriately, but we should just throw Exceptions for Lucene API users. For example, TwoDoublesStrategy.makeQuery has this code: } catch(Exception ex) { log.warn("error making score", ex); } I think we can remove logging... i'll take a look I committed the removal of SLF4J just now. That catch block that Robert mentions has a bad code smell and so I chose to not catch the exception (and thus not log anything there either). Tests still pass. Perhaps the author of this code (Ryan?) might add a test in which the exception can happen (what subclass?) and then we can consider the right thing to do. TwoDoublesStrategy hasn't seen any love in a long time, compared to RecursivePrefixStrategy which gets all the attention. Thank's David! I wanted to respond with the same comment like Robert! Logging should not be done in library code and exceptions should not be ignored. The warn was better than the common eclipse-autogenerated try-catch with e.printStackTrace(), which is the worst anti-pattern I have ever seen, but we still should not do this in library code. ok – with the logging issue solved, i think we can move things forward Guys, was there a specific reason why the degrees-radians conversion optimizations were removed? Example: - return vals.doubleVal(doc) * DistanceUtils.DEGREES_TO_RADIANS; + return Math.toRadians(vals.doubleVal(doc)); It won't matter for query setup, but will matter for per-document calculations. I made those conversions because I didn't see the point. Surely the JVM can inline the Math.* methods, especially this one. Surely the JVM can inline the Math.* methods, especially this one. Inlining yes, but not optimizing (compilers are very restricted in how they can optimize floating point calculations). Unfortunately Math.toRadians uses double precision division, which is much more expensive than multiplication. I just did a quick test, and Math.toRadians was more than 3 times slower. I've got most of the changes locally so I'll finish it up... I just did a quick test, and Math.toRadians was more than 3 times slower. Big +1 to this. There are huge benefits to be found in optimizing the actual arithmetic. Math.* methods are very conservative. I'd be very surprised to hear if this is true. What was your benchmarking methodology Yonik? I recently read an excellent presentation by Cliff Click (a JVM implementer and is as expert as they come) on Java benchmarking: I will mark this resolved and we can start new issues for ongoing problems. The next big step is to integrate with solr. did not mean to 'resolve' the Math.toRadians issue though – I think we should change that back to multiplication... Math.* seems to be pretty clunky I'd be very surprised to hear if this is true. If Math.toRadians had been written as x*(PI/180.0) then the compiler would have done constant folding and it would simply be multiplication by a constant. But it's unfortunately written as x/180.0*PI (for no good reason in this case), and the compiler/JVM is not allowed to do the simple transformation by itself. That's why we do it. Sometimes knowing how optimizers work and the restrictions on them allow one to know what will be faster or slower without benchmarking. I did benchmark it after the fact (after you questioned it), and it was indeed the case that Math.toRadians was much slower than a simple multiply. I did benchmark it after the fact (after you questioned it), and it was indeed the case that Math.toRadians was much slower than a simple multiply. Can I see the benchmark? The trivial things I am trying seems to end up equivalent Can I see the benchmark? The trivial things I am trying seems to end up equivalent One way that can happen is if you don't use the values produced - hotspot can eliminate the method calls altogether. public class X { public static double foo(double val) { // return Math.toRadians(val); return val * (Math.PI/180.0); } public static void main(String[] args) { double x = 1.12345; for (int i=0; i<100000000; i++) { x += foo(x) - foo(x+1); } System.out.println(x); } } yup – I get the same results as you. I've updated things to use this optimization at spatial4j [branch_4x commit] Ryan McKinley LUCENE-3795: makeQuery should not require ConstantScoreQuery (merge from trunk) [trunk commit] Ryan McKinley LUCENE-3795: makeQuery should not require ConstantScoreQuery LSP is comprised of several modules: The spatial-solr module of LSP can be considered in another issue following the conclusion of this one. The other modules aren't being considered for incorporation into Lucene/Solr. LSP is largely new code although some of it originated using chunks of the existing Lucene spatial contrib module and SOLR-2155(A recursive PrefixTree/Trie algorithm using geohashes). It's fair to say this is a superset and descendent of SOLR-2155but with a real framework around it and plenty of refactorings and tests. I ran Atlassian's Clover code coverage to get some statistics of this spatial-lucene module of LSP: The code coverage surprises me a little... perhaps the number is higher when the spatial-solr module gets involved which uses more of the classes then the tests do here alone.
https://issues.apache.org/jira/browse/LUCENE-3795?focusedCommentId=13210070&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-32
refinedweb
5,655
64.2
RE: [BPQ32] Losing messages. Stephen, When you shut down the BBS after receiving the 5 messages, were the messages in dirmes.sys? I need to know if the messages are not being saved correctly, or being lost on restart. If the latter, could you send me (off list) the dirmess.sys before restarting, and a copy of the message files, and I’ll try running it here. I don’t know of anyone using 64 bit Vista , but the code works on 64 bit WIN7, and there isn’t anything in the file handling that should be affected by the OS version. Thanks, John From: BPQ32@yahoogroups.com [mailto: BPQ32@yahoogroups.com ] On Behalf Of bolt637 Sent: 27 June 2012 18:52 To: BPQ32@yahoogroups.com Subject: [BPQ32] Losing messages. Howdy. In my first run of mailchat I was trying to import messages from a .EXP file, and was having trouble with all but 7 of the messages disappearing, and the last 7 being displayed corrupted in the bbs. I got rid of all messages and started with a fresh dirmes.sys and wfbid.sys. I connected to a forwarding partner and got 5 messages, and all 5 were reported as being ready for my other forwarding partners. After closing the bbs though, the 5 messages disappeared on restart. The dirmes.sys had no entries, but dirmes backup file shows the 5. There are 5 .MES files in the mail directory, and 5 bids in wfbid. My bpq setup is in a folder d:\Abpq32 and D is a 2 gig fat16 partition on harddrive 1. My OS is vista 64bit on a 40 gig NTFS as C:\. The path in the configuration for mailchat shows the proper D:\Abpq32\BPQMailChat and the main .exe is in abpq32. It used to be in bpqmailchat folder but the most recent installer moved it to Abpq32. I just can't figure out what may be happening with my setup. Any help much appreciated. Steven - N1OHX
https://groups.yahoo.com/neo/groups/BPQ32/conversations/topics/8788?o=1&d=-1
CC-MAIN-2015-35
refinedweb
333
84.57
There are three programmer-to-programmer topics in this chapter: Windows services, Web services, and how to deploy applications using Windows installer (.MSI) files. All these issues are important ones, and we'll use them to round off the GUI-oriented application coverage. We'll start with Windows services. Windows services are not typically front-line applications that the user runs and interacts with. Instead, they provide support services, often for device drivers, such as printer device drivers, audio devices, data providers, CD creation software, and so on. As such, Windows services don't need a real user interface as you see in standard Windows applications. They often do have a control panel-like interface that the users can open by clicking or right-clicking an icon in the taskbar, however. (You can create taskbar icons in Windows applications using the NotifyIcon control from the Windows Forms tab in the toolbox.) Users can customize, and even start or stop, a Windows service using that control panel. Other Windows applications can interact with the service at runtime; for example, SQL Server uses a Windows service to make it accessible to other applications. We'll see how to create a working Windows service in this chapter. In the FCL, Windows services are based on the ServiceBase class, and that class gives us most of the support we'll need. When you write a Windows service, you should override the OnStart and OnStop methodseven though their names imply they are event handlers, they're actually methods. These methods are called when the service starts and stops. You might also want to override the OnPause and OnContinue event handlers to handle occasions where the service is paused and resumed. Currently, there is a great deal of abuse of Windows services, and it's getting so bad that sooner or later there's going to be a user revolt. Too many software manufacturers just decide that the user's computer has nothing better to do than to continuously run their software, and so you find Windows services that do nothing else besides checkonce a secondwhether the software manufacturer's software is running, or printer drivers that run as a Windows service, also polling once a second and displaying multiple taskbar icons and pop-ups. Some one-time-use applications, like a few tax programs, appear to install Windows services that run continuously as long as the user has the computer. Other manufacturers use Windows services to gather information about the user's work habits, installed software, and/or accessed files to send over the Internet without the user's knowledge. Because Windows services can be invisible, they've been incredibly abused. If you look in the Service Control Manager tool that we'll discuss in this chapter, you may find a dozen or so Windows services running that you've never heard of before. It's very important to resist this temptation to monopolize the user's machine. If you need to poll your device driver or service, you can start a Timer object (see Chapter 7, "Creating C# Windows Applications") when the service's OnStart method is called, but don't use this technique to wrest control from the user more than just occasionally, unless you specifically let the user know what's going on. Many users, when told what some formerly unknown Windows services are doing, consider them no better than viruses. You can configure Windows services to start automatically when the computer starts, or you can start them manually using an administration tool built into Windows, the Service Control Manager (SCM). We'll see how this works in practice now. You can see an example, ch12_01, in the code for this book, and we'll take that application apart here. To follow along, create a new Windows service project. Choose File, New, Project in the IDE, and select the Windows Service icon in the Templates box of the New Project dialog box. Give this new service the name ch12_01 and click OK. This creates the new Windows service project in Figure 12.1; the default name for this new service is "Service1" . In our Windows service, we are going to write to our Windows service's event log when the OnStart and OnStop methods are called. To handle an event log, you must specify or create an event source . An event source registers your application with the event log as a source of data so the event log can listen for that data. You can give the event source as any string, but the name must be unique among other registered sources. In this example, we're going to register our event log in the Windows service's constructor, which you can find in the Component Designer generated code region of the Windows service's code, Service1.cs . That constructor looks like this now: public Service1() { // This call is required by the Windows.Forms Component Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } In this example, we create an event source named "CSSource1" . After the new source is created, we assign its name to the eventLog1 object's Source property like this: public Service1() { // This call is required by the Windows.Forms Component Designer. InitializeComponent(); if (!System.Diagnostics.EventLog.SourceExists("CSSource1")) { System.Diagnostics.EventLog.CreateEventSource("CSSource1", "currentLog1"); } eventLog1.Source = "CSSource1"; } Now we're ready to write to our event log when the service starts and stops. You can do that in the OnStart and OnStop methods, which look like this in Service1.cs currently: protected override void OnStart(string[] args) { // TODO: Add code here to start your service. } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to // stop your service. } To write text to a Windows service's event log, you can use the log's WriteEntry method. In this case, we'll insert a message into the log indicating that the service started or stopped , like this: protected override void OnStart(string[] args) { eventLog1.WriteEntry("Starting ch12_01."); } protected override void OnStop() { eventLog1.WriteEntry("Stopping ch12_01."); } When our Windows service starts, our code will write "Starting ch12_01." to event log currentLog1 , and when the service stops, our code will write "Stopping ch12_01." to the log. We've created our Windows service. To install that service, we'll need an installer, so click the Service1.cs[Design] tab now to open the designer for Service1 . Make sure that eventLog1 in that designer does not have the focus (we want to create an installer for the service itself, not the event log object in the service), and then click the Add Installer link in the description section of the properties window (this link is visible at bottom right in Figure 12.2). This creates ProjectInstaller.cs with two objects in it, serviceProcessInstaller1 and serviceInstaller1 , as you see in Figure 12.3. ServiceInstaller objects inform Windows about a service by writing Windows Registry values for the service to a Registry subkey under the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services Registry key. The service is identified by its ServiceName value in this subkey. ServiceProcessInstaller objects handle the individual processes started by our service. When you install a Windows service, you have to indicate which account it should run under. In this example, we'll do that by clicking the serviceProcessInstaller1 object to give it the focus and setting its Account property to LocalSystem . Besides LocalSystem , you can also set this property to LocalService , NetworkService , or User . When you set Account to User , you must set the Username and Password properties of the serviceProcessInstaller1 object to configure this object for a specific user account. Now click the serviceInstaller1 object and make sure its ServiceName property is set to the name of this service, Service1 (it should already be set that way). You use the ServiceInstaller1 object's StartType property to indicate how to start the service. Here are the possible ways of starting the service, using values from the ServiceStartMode enumeration: ServiceStartMode.Automatic The service should be started automatically when the computer boots. ServiceStartMode.Disabled The service is disabled (so it cannot be started). ServiceStartMode.Manual The service can only be started manually (by either using the Service Control Manager, or by an application). The safest of these while testing a new Windows service is Manual , so set the StartType property of the ServiceInstaller1 object to Manual now. A Windows service with errors in it that starts automatically on boot can make Windows unstable, so be careful when testing Windows services. Until you're sure a service is working correctly, it's best to keep its start mode Manual , making sure it doesn't start again automatically if you need to reboot. (If you get into a loop where a problematic Windows service is starting automatically when you boot and causing Windows to hang, press and hold the F8 key while booting so Windows comes up in safe mode.) The next step is to build and install our new Windows service, Service1 . To build the service, select Build, Build ch12_01, which creates ch12_01.exe. To actually install the service in Windows, you can use the InstallUtil.exe tool that comes with the .NET Framework. In Windows 2000, for example, you can find InstallUtil.exe in the C:\WINNT\Microsoft.NET\Framework\ xxxxxxxx directory, where xxxxxxxx is the .NET Framework's version number. Here's how you install ch12_01.exe using InstallUtil.exe at the DOS command prompt (note that the command line here is too wide for the page, so it's split into two lines): C:\WINNT\Microsoft.NET\Framework\ xxxxxxxxxx >installutil c:\c#\ch12\ch12_01\bin\Debug\ch12_01.exe Microsoft (R) .NET Framework Installation utility Version xxxxxxxxxx Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. Running a transacted installation. Beginning the Install phase of the installation. See the contents of the log file for the c:\c#\ch12\ch12_01\bin\debug\ch12_01.exe assembly's progress. The file is located at c:\c#\ch12\ch12_01\bin\debug\ch12_01.InstallLog. Installing Installing service Service1... Service Service1 has been successfully installed. Creating EventLog source Service1 in log Application... The Install phase completed successfully, and the Commit phase is beginning. See the contents of the log file for the c:\c#\ch12\ch12_01\bin\debug\ch12_01.exe assembly's progress. The file is located at c:\c#\ch12\ch12_01\bin\debug\ch12_01.InstallLog. Committing The Commit phase completed successfully. The transacted install has completed. C:\WINNT\Microsoft.NET\Framework\ xxxxxxxxxx > Now our Windows service has been installed. If InstallUtil hadn't been able to install the new service without problems, it would have rolled back the installation and removed the non-working service. Our new Windows service is installed, but not yet started, because we chose manual startup. In this case, we'll use the Service Control Manager to start our service. The SCM is part of Windows; for example, in Windows 2000, you can start the SCM this way: In Windows 2000 Server, you select Start, select Programs, click Administrative Tools, and click Services. In Windows 2000 Professional, right-click the My Computer icon on the desktop and select the Manage item in the menu that pops up. In the dialog box that appears, expand the Services and Applications node and click the Services item. You can also deploy Windows services with setup programs in C#; we'll cover setup programs at the end of this chapter. You create setup programs with setup projects, and to install a Windows service, you add a custom action to a setup project. In the Solution Explorer, right-click the setup project, select View, and then select Custom Actions, making the Custom Actions dialog box appear. In the Custom Actions dialog box, right-click the Custom Actions item and select Add Custom Action, making the Select Item in Project dialog box appear. Double-click the Application Folder in the list box, opening that folder. Select Primary Output from ServiceName (Active), where ServiceName is the name of your service, and click OK. The primary output (that is, the Windows service itself) is added to all four custom action foldersInstall, Commit, Rollback, and Uninstall. You can see the Service Control Manager in Figure 12.4, and you can see our newly installed service, Service1 , listed in the SCM in the figure. To start our new service, right-click Service1 in the Service Control Manager now and select the Start item in the menu that appears. Doing so starts the service, as you see in Figure 12.5, where Service1 is listed as Started . You can also run a Windows service from the Server Explorer; just expand the Services node, and then right-click the service you want to start and click Start. To stop the service, right-click Service1 in the Service Control Manager and select the Stop item. We've been able to start and stop our new service, so it should have written to our event log, currentLog1 . You can check whether it has from inside the IDE; you just open the Server Explorer's Event Logs node as you see in Figure 12.6, and take a look at the entry for CSSource1 in currentLog1 . Here, you can see our service's two entries Starting ch12_01. and Stopping ch12_01. in the event log in the Server Explorer in Figure 12.6. (If you don't see the messages there, or messages don't appear when you start and stop the service a number of times, refresh the event log by right-clicking currentLog1 in the Server Explorer and selecting the Refresh item.) And that's itthe Windows service is a success. Our Windows service did exactly what it was supposed toit wrote to an event log when it was started and stopped. Now that you can run code in a Windows service, you can see this is only the beginning. You can get the service's code started when the OnStart method is called, and run it in the background, supplying its service for as long as needed. You can uninstall a Windows service, removing it from the SCM, with InstallUtil.exe; just use the /u option to uninstall. Here's what you see when you uninstall the Windows servicenotice that the command line is the same except for the /u : C:\WINNT\Microsoft.NET\Framework\ xxxxxxxxxx >installutil c:\c#\ch12\ch12_01\bin\Debug\ch12_01.exe /u Microsoft (R) .NET Framework Installation utility Version xxxxxxxxxx Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. The uninstall is beginning. See the contents of the log file for the c:\c#\ch12\ch12_01\bin\debug\ch12_01.exe assembly's progress. The file is located at c:\c#\ch12\ch12_01\bin\debug\ch12_01.InstallLog. Uninstalling Removing EventLog source Service1. Service Service1 is being removed from the system... Service Service1 was successfully removed from the system. The uninstall has completed. C:\WINNT\Microsoft.NET\Framework\ xxxxxxxxxx > We've seen how to run a Windows service in the background, but how do you connect to that Windows service from another application? All you need to do is drag a ServiceController object from the Components tab of the Toolbox to a form in a Windows application, creating a new object, serviceController1 . Then you set these properties in the properties window for this object: MachineName The name of the computer that hosts the service, or "." for the local computer. ServiceName The name of the service you want to work with. Now using the power of the Windows service becomes easyyou can use the properties and methods exposed by the Windows service as though they were properties and methods of the serviceController1 object. For example, here's how you might use the CanStop and ServiceName properties of a Windows service as connected to by serviceController1 : if (serviceController1.CanStop) { MessageBox.Show(serviceController1.ServiceName + " can be stopped."); } You can also create a ServiceController object in code. To do that, you add a reference to the System.ServiceProcess DLL by right-clicking the current project in the Solution Explorer and selecting Add Reference. Then, click the .NET tab in the Add Reference dialog box, select System.ServiceProcess.dll and click Select. Finally, click OK to close the Add Reference dialog box. Also, you should include a using statement in your application's code for the System.ServiceProcess namespace. Now you can access the properties and methods that are built into a Windows service using the new ServiceController object like this: using System.ServiceProcess; . . . ServiceController controller1 = new ServiceController("Service1"); if (controller1.CanStop) { MessageBox.Show(controller1.ServiceName + " can be stopped."); } That's all it takes to access a Windows service from code. (Note that you can even implement events in a Windows service, and, using ServiceController objects, handle those events in other applications.) Next, we'll take a look at the properties, methods, and events of a few of the important Windows services classes to round off this topic. The ServiceBase class is the base class for Windows services, and you can find the significant public properties of ServiceBase objects in Table 12.1, and their significant protected methods in Table 12.2 (note that although the items in Table 12.2 look like events, they're actually methods you can override). PROPERTY PURPOSE AutoLog Sets whether to record in the event log automatically. CanPauseAndContinue Returns or sets whether the service can be paused and continued . CanShutdown Returns or sets whether the service should be informed when the computer shuts down. CanStop Returns or sets whether the service can be stopped. EventLog Returns the event log. ServiceName Returns or sets the name of the service. METHOD OnContinue Called when a service continues (after it was paused). OnPause Called when a service is paused. OnShutdown Called when the system shuts down. OnStart Called when the service starts. OnStop Called when a service stops running. The EventLog class supports access to Windows event logs used by Windows services; you can find the significant public static methods of EventLog in Table 12.3, the significant public properties of EventLog objects in Table 12.4, their significant methods in Table 12.5, and their significant events in Table 12.6. CreateEventSource Creates an event source to let you write to a log. Deletes a log. DeleteEventSource Deletes an event source. Exists Returns true if a log exists. GetEventLogs Returns an array of event logs. SourceExists Checks whether an event source exists. WriteEntry Writes an entry to the log. Entries Returns the contents of the log. Log Returns or sets the name of the log. LogDisplayName Returns the log's display name. MachineName Returns or sets the name of the log's computer. Source Returns or sets the source name to use when writing to the log. BeginInit Begins initialization of a log. Clear Clears all the entries in a log. Closes the log. EndInit Ends initialization of a log. Writes an entry in the log. EVENT EntryWritten Happens when data is written to a log. As we've already seen, ServiceProcessInstaller objects let you install specific processes in a Windows service. You can find the significant public properties of objects of the ServiceProcessInstaller class in Table 12.7, their significant methods in Table 12.8, and their significant events in Table 12.9. Account Returns or sets the type of account for the service. HelpText Returns help text. Installers Returns the service's installers. Parent Returns or sets the parent installer. Returns or sets the password for a user account. Username Returns or sets a user account. Install Installs a service, writing information to the Registry. Rollback Rolls back an installation, removing data written to the Registry. Uninstall Uninstalls an installation. AfterInstall Happens after an installation. AfterRollback Happens after an installation is rolled back. AfterUninstall Happens after an uninstallation. BeforeInstall Happens before installation. BeforeRollback Happens before installers are rolled back. BeforeUninstall Happens before an uninstallation. Committed Happens after all installers have committed installations. Committing Happens before installers commit installations. You use ServiceInstaller objects to install Windows services, and you can find the significant public properties of objects of this class in Table 12.10, their significant methods in Table 12.11, and their significant events in Table 12.12. DisplayName The display name for this service. Help text for the installers. Returns the installers. The name of this service. ServicesDependedOn Specifies services that must be running in order to support this service. StartType Specifies when to start this service. Commit Commits an installation. Installs the service by writing data to the Registry. Rolls back a service's data written to the Registry. Uninstalls the service. Happens after the installers have installed. Happens after the installations are rolled back. Happens after all the installers finish their uninstallations. Happens just before the each installer's Install method runs. Happens before the installers are rolled back. Happens before the installers uninstall. Happens after all the installers commit their installations. Happens before the installers commit their installations. That completes our look at Windows services; next up are Web services.
https://flylib.com/books/en/1.254.1.124/1/
CC-MAIN-2019-13
refinedweb
3,505
58.38
Selecting characters from a string Doug Wolfinger Greenhorn Joined: Jul 27, 2002 Posts: 18 posted Oct 23, 2002 17:20:00 0 Hello, I've copied this from the Beginners forum, as I malignantly posted it there originally. I am trying to pass a string that represents a postfix expression. The method that accepts it should take each number and place it on the stack. When it encounters an operator, it should pop the top two numbers and evaluate them with the operator. This is the expression. "abc+-" a=7, b=3, c=12 So it applies "+" to c and b, then it subtracts (c + b) from a. I have made the string into a string array in my program, but I think the idea is to pass the expression as a regular string as I have it above. I would use substring(), but that doesn't work with a number larger than 2 digits. Thanks! class PostFixStack { StackArrayBased stack = new StackArrayBased(); String operator; int operand1; int operand2; int result; //primitive value which is converted to Integer Integer intObj; //Integer to hold string value Integer intOper1; //used to pop from stack Integer intOper2; //used to pop from stack Integer intResult; //used to convert from result to Integer and push to stack public Integer srMeth(String[] str) //Accepts a postfix expression as an argument. Processes the expression. //Precondition: str.length() > 0. //Postcondition: Returns the Integer that results from the expression str. { for(int i=0;i<str.length;i++) { if( str[i].equals("*") || str[i].equals("-") || str[i].equals("+") ) { operator = str[i]; intOper1 = (Integer)stack.pop(); intOper2 = (Integer)stack.pop(); operand2 = intOper2.intValue(); operand1 = intOper1.intValue(); if(operator.equals("*")) result = (operand2 * operand1); if(operator.equals("+")) result = (operand2 + operand1); if(operator.equals("-")) result = (operand2 - operand1); //convert result back to an Integer so that push() will accept it. intResult = new Integer(result); stack.push(intResult); System.out.println("currently the top value is " + stack.peek()); } //if the array occurrence is a number else { System.out.println(str[i]); intObj = new Integer(str[i]); stack.push((Integer)intObj); } } return intResult; } public static void main(String args[]) { String string[] = {"7","3","12","+","-"}; String stringB[] = {"7","3","12","-","-5","*","+"}; PostFixStack pfs = new PostFixStack(); System.out.println(pfs.srMeth(string) + " = the value of the 9a expression"); System.out.println(pfs.srMeth(stringB) + " = the value of the 9b expression"); } } If you would like to use that program, you'll need this one as well. [code] public class StackArrayBased implements StackInterface { final int MAX_STACK = 50; // maximum size of stack private Object items[]; private int top; public StackArrayBased() { items = new Object[MAX_STACK]; top = -1; } // end default constructor public boolean isEmpty() { return top < 0; } // end isEmpty public boolean isFull() { return top == MAX_STACK-1; } // end isFull public void push(Object newItem) throws StackException { if (!isFull()) { items[++top] = newItem; } else { throw new StackException("StackException on " + "push: stack full"); } // end if } // end push public void popAll() { items = new Object[MAX_STACK]; top = -1; } // end popAll public Object pop() throws StackException { if (!isEmpty()) { return items[top--]; } else { throw new StackException("StackException on " + "pop: stack empty"); } // end if } // end pop public Object peek() throws StackException { if (!isEmpty()) { return items[top]; } else { throw new StackException("Stack exception on " + "peek - stack empty"); } // end if } // end peek } // end StackArrayBased Sayed Ibrahim Hashimi Ranch Hand Joined: May 17, 2001 Posts: 148 posted Oct 23, 2002 23:46:00 0 If you pass in a String vs. a String array the you have to delimit the numbers somehow. Because otherwise you wouldn't know what numbers are supposed to be together. For example: a=7, b=3, c=12 7312+- I could interpret that as: a=7,b=31,c=2 or a=73,b=1,c=2 But if the numbers are delimited the theres no questions, lets say they are delimited by commas then your argument will be 7,3,12+-, so you know for sure that a=7, b=3, and c=12. Do you have a choice on how you are getting(generating?) this String input? If you know for sure that you will be given a String input that will contain numbers that only contain one digit per integer then you can use your current code and just create a String [] from the String. SCJP 1.4<br /><a href="" target="_blank" rel="nofollow"></a> Ilja Preuss author Sheriff Joined: Jul 11, 2001 Posts: 14112 posted Oct 24, 2002 01:26:00 0 If you can use the same delimiter for operators and operands (spaces, for example: "12 3 4 + -"), you can use a StringTokenizer to decompose the: Selecting characters from a string Similar Threads A continuation of my previous post, if I may... Input error in math equation Picking characters from a string Trouble evaluating postfix Expression Converting Infix to Postfix Expressions All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/369924/java/java/Selecting-characters-string
CC-MAIN-2014-10
refinedweb
813
52.6
This is just a collection of hash functions and information that I've gleaned from books, the web, other programmers, etc... Feel free to add your own. Expand | Embed | Plain Text - A hash table is an associative abstract data type. Google it if you're curious. - - - If the key is a string, one algorithm is to start with n = 0, multiply 8 by the index of the next character in the string, and add the ASCII value of the new character. The result could be negative, due to overflow, so check and return the positive value, after dividing by a large prime number (to provide further randomization of integer values; you could use 2 049 982 463). - - Example (pseudocodish): - key = "and" - unsigned int n = 0 - n = (0 * 8) + 97 = 97 // ASCII value of 'a' is 97 - n = (1 * 8) + 110 = 886 // ASCII value of 'n' is 110 - n = (2 * 8) + 100 = 7188 // 'd' is 100 - - Example (C++): - class hFstring - { - public: - unsigned int operator() (const string& item) const - { - unsigned int prime = 2049982463; - int n = 0, i; - for (i = 0; i < item.length(); i++) { - n = n*8 + item[i]; - } - return (n > 0) ? (n % prime) : (-n % prime); // tertiary operator to account for possible overflow creating a negative number - } - } - - main - { - hFstring h; - h("and"); // = 7188 - } - - -- This function taken from Ford, William and Topp, William; Data Structures with C++ Using STL, 2ed. 2002 Prentice Hall; p658 Report this snippet Tweet
http://snipplr.com/view/2211/
CC-MAIN-2017-04
refinedweb
235
65.15
Type: Posts; User: EdoSZ Simplest option: Set up your settings file like this value0 value1 value2 use the following code to parse the strings I'm not sure what you are trying to say. Are you working with the .NET framework? Try using this.ShowInTaskbar = false; I moved some code around, created buttons for starting the server and and listening for connections, and it works now. Can someone explain why? lol. thanks in advance. New source: using System;... I'll keep it short and simple. Take a look at my source. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using... Basically, my program does not install, as it is dire that there are no external dependencies, so there is no way to install frameworks if the consumer does not have .NET 4.x. I only have experience... I'm writing an application that does certain actions based off of what my iPhone (using WiFi on the same network) is sending data to. I've got the packet-sniffing part down (I can sniff my own... The texbox does not display "Connecting..." until after the connection has timed out/connected. public void Connect(string hostname) { textBox3.Text += "Connecting..." + n; ... Oh, thanks. i was confused as to what a data member was. I get what you mean now. And Connect() is called with Form1_Load so it will be fine. EDIT: it works thankyou so much I don't know if you can answer this but would that work? I believe the connection has to be made in order to use "serverStream = cSoc.getStream". Is that wrong? I could try connecting as a data class... in my Connect() function i declare NetworkStream serverStream; but down in the "button5_Click" event, when i try to use "serverStream" i get the error "The name 'serverStream' does not exist in the...
http://forums.codeguru.com/search.php?s=561331adab58456a3a659602efabeab4&searchid=7386315
CC-MAIN-2015-32
refinedweb
311
77.74
Deploy Your First NFT with Python Introduction NFT (Non-Fungible Token) has exploded since last year and keeps on roaring regardless of how the cryptocurrency is performing. You must have heard of CryptoPunk, BAYC or the most recent Phantom Bear if you are following any crypto news. In the nutshell, NFT is a smart contract with some meta data such as image, video or some other attribute data to make it unique from one another. And since it’s on blockchain, it’s easy for anybody to verify the ownership. In this article, I will walk you through the process on how to deploy your own NFT with Python and we will be using a Python based smart contract development framework called Brownie. Prerequisite You will need to install the Brownie package. It is recommended to use pipx to install it in an isolated environment, but since I have my own virtual environment created, I would continue to use pip instead. Below is the pip command to install Brownie: #run in your venv pip install eth-brownie In order to test your code locally, Brownie will automatically install ganache cli which launches a local Ethereum blockchain for you to execute your smart contracts. You can follow its documentation to download and install it if you wish to install it manually. Let’s create an empty folder and then run the below command to initiate a new Brownie project: brownie init With the above command, brownie will create a project structure for you under your current folder. The majority of your work shall be done in the following folders: - contracts – for solidity smart contract source code - interfaces – for the interface files that referenced by the smart contract - scripts – for deployment scripts or interacting with deployed contracts - tests – for test scripts Brownie supports both Solidity and Vyper language for creating smart contracts. In this article, I will be using the smart contract in Solidity style as the example. Create NFT Smart Contract NFTs use ERC721 token standard, so we will need to create a smart contract that implements this standard. Since the objective of this article is to walk through the process rather than a deep dive into the smart contract coding, I have just shared a sample smart contract here. You can download this LegendNFT.sol smart contract file and the libraries folder, then put them under the contracts folder. Here is a quick explanation of what this smart contract does: - an ERC721 contract with name Codeforests Legend, token symbol CFL and total supply of 1,000,000 - 3 lists of words to generate a “random” word phrase - a SVG xml template to create a picture of the above word phrase - a list of color codes to provide “random” background color to the SVG - a mint function for minting the NFT tokens - finally a function to return how many tokens have minted As you can see from the source code that I used two external contracts from OpenZeppelin, so I will need to specify this dependency so that they can be recognized when compiling the contract. Brownie provides a config file brownie-config.yaml which allows you specify these configurations. This file is not created automatically when initiating the project as all the settings are optional, you will only need it when necessary. To specify the dependencies, you can manually create this yaml file under your project root folder. And add the below configurations: dependencies: - OpenZeppelin/[email protected] compiler: solc: remappings: - '@openzeppelin=OpenZeppelin/[email protected]' It basically tells Brownie package manager to automatically download this package for you and let compiler find the correct path of the package when using the short form ‘import @openzeppelin/…’. Compile Smart Contract Once you have saved your contract and the config file, you can run below compile command on your terminal: brownie compile You shall see brownie auto downloaded the dependencies and compiled the code: The output Json files will be placed into the build/contracts folder. The next step we shall try to deploy this contract locally. Deploy Smart Contract Locally To deploy our contract locally, we will need to use the ganache as I mentioned in the beginning. By default, when you want to deploy a contract, brownie will always start the ganache local network and deploy it to the local network. Brownie provides a console window where you can use the commands to deploy contract, but since we may need to do the deployment multiples for testing or in different networks, so let’s create a re-usable Python script called deploy.py under the scripts folder for the deployment purpose. When your smart contract is compiled, the contract class object will be automatically added to brownie runtime environment, so we can import it from brownie directly. Below is the Python code for deploying my LegendNFT contract: from brownie import LegendNFT, network, config, accounts def deploy_contract(): account = accounts[0] legend_contract = LegendNFT.deploy({"from" : account}) print("contract has been deployed successfully to :", legend_contract.address) return legend_contract def main(): deploy_contract() The accounts is some dummy accounts provided by ganache only for your local network, so we just pick the first dummy account as the contract creator for the from parameter. Note that your script needs to have a main function to let brownie know which function to run. Next, let’s run the below command in the terminal: brownie run .\scripts\deploy.py You shall see something similar to the below output showing that both contract address and transaction hash have been generated: Congratulations that you’ve just deployed your contract to your local network, although you may have no idea if the contract works correctly. Don’t worry, let’s continue to explore how to deploy to a public network and come back to the unit test later. Deploy Smart Contract to Public Network The public network usually refers to the public accessible and persistent blockchain network such as the Ethereum mainnet, rinkeby, kovan, popsten etc. To access the public network, you will need to connect to a node, but it would be too much to run your own node just for deploying a contract. Luckily there are some service providers like Infura, Alchemy or Pocket Network etc., who allows you to use their API to connect to the public network nodes. For Brownie, it uses Infura as the default provider for connecting to public network. If you run below command in your terminal: brownie networks list true You can see it is using Infura’s API: In this case, you will need to sign up Infura for a free account and get your own project API token. Once you have your API token, you can create a environment variable called WEB3_INFURA_PROJECT_ID and assign your token ID to it. My personal preference would be putting this information into a .env file and load it into the Brownie config file. And another thing you need is a real wallet account with some fund, as deployment will always incur some cost for confirming the transaction. You can create a wallet with Metamask, and for testnet like rinkeby, you can get some testing ether token from chainlink rinkeby faucet. You can also find other faucets for the rest of the testnets. So let’s put below info in the .env file: PRIVATE_KEY = 0x{your wallet private key} WEB3_INFURA_PROJECT_ID = {your infrua project ID} ETHERSCAN_TOKEN = {etherscan API token; to submit your contract source code to etherscan (optional)} Note: to add 0x before your wallet private key so that it’s recognized as hex string. If you wish to get your contract source code verified by etherscan, you will need to sign up with etherscan and get an API token as well. And add below lines in the brownie-config.yaml file: dotenv: .env wallets: from_key: ${PRIVATE_KEY} # optional for verifying the contract source code networks: development: verify : false rinkeby: verify : true I strongly recommend you to add .env in .gitignore, so that you won’t accidently push your sensitive information into github. Your wallet private key for testnet and mainnet is the same, so bear in mind to not expose to anyone. Now let’s also do some minor change to our deployment script, so that it uses the new account we created for deploying the contract to public network. def deploy_contract(): if(network.show_active() == "development"): account = accounts[0] else: account = accounts.add(config["wallets"]["from_key"]) legend_contract = LegendNFT.deploy( {"from" : account}, publish_source=config["networks"][network.show_active()].get("verify") ) print("contract has been deployed successfully to :", legend_contract.address) return legend_contract We have added a condition to check whether we are working on local/development network, when it’s not local network, we will load our account by the private key and use it to sign the transaction for deployment. Now we have everything ready, let’s run the deploy.py again and specify the target network with the –network option, e.g. : brownie run .\scripts\deploy.py --network rinkeby Below is the output from my terminal: It would take slightly longer time since it requires the transaction to be minted and confirmed. You can copy the contract address or transaction hash then search it from etherscan rinkeby network. You can see my deployed contract address here and the verified source code here. Awesome! You just had your contract deployed in the public network where everybody can see it!!! Since you’ve not yet minted any NFT from your contract, you won’t see anything visually at the moment. To give you a idea of how your NFTs will look like, I have created this website for minting the LegendNFT, you can try and experience the minting process and then view the NFT from Opeasea. It currently supports Rinkeby, Matic and Matic Mumbai network. Below is the minting page after you have connected your wallet: Conclusion Creating your own NFT can be a very fun journey although you may not be able to eventually sell it on the market. And there are just too much details to be covered and which is impossible to write in one post, so I will try to write a few more articles on how to perform unit test, interact with your deployed contract, as well as deploy the contract to other EVM compatible networks. Do follow me on my twitter and let me know if you encounter any issue with your contract deployment.
https://www.codeforests.com/2022/01/14/deploy-your-first-nft-with-python/
CC-MAIN-2022-21
refinedweb
1,728
57.4
I friendly” representation of the same date/time in an HTML document, such that you follow the guiding principles of microformats without negatively impacting accessibility for, say, people whose screen readers will automatically expand and read out your clever use of the title attribute? I’ve prepared a document which encapsulates one approach to solving this problem. This document could be from an application which keeps track of upcoming events and provides users with information about them, and as such it describes an event which will take place in the future. Your mission, should you choose to accept it, is to write a program which: I can see at least two ways to do this, and I’ve already written a short Python program which implements one of them. It’s eleven lines of code, five of which are import statements and one of which retrieves the document, leaving only five lines to parse the document, retrieve the date/time and print it. If you’d like to try this yourself before I explain how it works, stop scrolling down the page now. Come back and read the next section when you’re ready. As I’ve mentioned, I can see at least two ways to get the necessary information out of the document. Both rely on a little-used feature of HTML: the scheme attribute of the meta element. The HTML 4.01 specification defines scheme as follows: This attribute names a scheme to be used to interpret the property’s value (see the section on profiles for details). Reading the section on profiles uncovers the following discussion of the use of scheme: The schemeattributeattribute value “Month-Day-Year” would disambiguate this date value. At other times, the schemeattribute may provide helpful but non-critical information to user agents. It then goes on to give another example — using a value of “ISBN” for a meta element representing the ISBN of a book — as an illustration of the versatility of the scheme element, and delegates responsibility for defining schemes and their meanings to specific profiles used in HTML documents. And if you look in my sample event-description document, you’ll find a couple of meta elements making use of this: <meta name="date" scheme="RFC3339" content="2008-06-29T06:08:39-05:00"> <meta name="event-datetime" scheme="RFC3339" content="2008-07-06T12:00:00-05:00"> The first of these is a fairly standard use of meta; generally, “date” refers to the date and time on which the document was authored. The second has a name which I chose largely at random, but which can be assumed to stand in for a value which could be specified by, say, a microformat. Both of them make use of the scheme attribute, and specify a value of “RFC3339”. RFC 3339 is document which defines a standard for representing timestamps on the Internet, based on the (broader in scope) ISO 8601 standard. This suggests one way to solve the challenge above: look for a meta element with the name “event-datetime”, see that its scheme value is “RFC3339” and treat its content as an RFC 3339 timestamp. From there, any decent programming language will give you the necessary tools to parse the string “2008-07-06T12:00:00-05:00” into an object representing a date and time, and then reformat it however you like. An alternative, and perhaps more interesting, way to handle this is to note that the document also contains this bit of HTML: <span class="event-datetime">12:00 Sunday</span> This is the “human-readable” version of the event date. Parsing this one is a bit trickier, but is still possible: you know, from the meta elements above, the date and time when the document was authored, and thus have a reliable anchor from which to calculate the relative date and time of “12:00 Sunday”. It’s not quite as simple to do this as to simply use the “event-datetime” meta element, but hey, if Remember the Milk can figure out what I mean from nothing more than the word “Sunday”, then a programmer armed with a day of the week, a time and a full base timestamp with time zone should be able to work this one out. Of course, this isn’t a perfect solution, or anything approaching it; it there are plenty of unanswered questions and unsolved problems lurking here (how do you handle multiple timestamps in the same document, for example?), and it probably isn’t a new idea. But it is the beginning of a possible solution, and it has some advantages over, say, using abbr or title to provide a “machine readable” version of a timestamp: There are probably lots of potential solutions which can do this with the same advantages; this WaSP article mentions a few. If you’ve got an idea for another, run it up the flagpole and see if anyone salutes. Comments for this entry are closed. If you'd like to share your thoughts on this entry with me, please contact me directly. Aah, but you’ve broken a cardinal rule of Microformats: “no invisible metadata”. I’m personally not convinced by the justifications for this rule (SEO types abused the meta element in the past because it wasn’t visible, and invisible metadata tends to get out of sync with visible information in hand edited pages) but the Microformats community is basically set on that one. I’m not sure the meta tag for “event-datetime” works in the microformats context, because you’re restricted to talking about the entire document. But I do like the idea of using the “date” one to specify a baseline date/time from which to interpret things like “Sunday”. All told though, microformats and dates are pretty confusing — the way they’re specified currently makes things a little tricky for document authors, but un-ambiguous for a machine; going down your “sunday 12pm” path makes the authoring ridiculously easy, but the machine consumption much harder, with just a little too much room for interpretation (imagine a month’s worth of “sunday 12pm”s). Maybe while we try and hammer out a middle ground HTML5 can solve the problem for us (I read that WaSP article and had been skimming the comments when suddenly I realised they were 13 months old, and we’re still having the same discussions!) -p I’m not sure the current abbrhacks really count as “visible”, though; are they considered “visible” simply because most user-agents style them (or allow authors to style them) and display a tooltip on hover? That’s awfully shaky ground (since “visibility” is then dependent on the behavior of prevailing user-agents), which is why I’ve never bought into it. James is right, there’s nothing to stop the Mozilla guys reading this article, thinking that a meta element in the head is the BEST way to deal with dates and then adding a hover that associates the event-datetime element with the meta data to create a hover - bringing the “invisible” meta tag into the same realm as abbr or title. Your problem statement says: But hCalendar doesn’t map to a document. One document can (and often does) contain multiple events. So even if someone accepts your mission and succeeds, it doesn’t provide a viable alternative for publishers of more than one event per document. If the challenge is restated as: …then the real scope of the issue is clearer. I know that you acknowledged this when you said “how do you handle multiple timestamps in the same document, for example”, but I wanted to point out that this isn’t a trivial edge-case. Rather, it’s the default for most published hCalendar data (the BBC programme schedules being a good example). My thought was that if a user agent sees anything in RFC3339 (or any other distinctive datetime format), it could take the task of translating it into the correct colloquial format for the user (ie the date would be read out as Month-Day-Year in the US or Day-Month-Year in the UK). How hard can it be for the authors of JAWS to teach it to recognise RFC3339 dates? I’m not keen on abusing the semantics of abbr like hCalendar, but it seems that half the time we forget that screen-readers could get on board with supporting web standards (even de facto ones like microformats) just like everyone else. Jeremy: Supporting multiple timestamps is surely as simple as having multiple meta tags using different classes? Or you could do multiple timestamps within the content of the a single meta tag. I don’t see the finer points of how this solution would work as being a particularly huge issue, the main issue is whether there are valid objections to the solution as a whole. The main objection I can see is that people might want microformats to be self-contained blobs of semantics with no dependencies on information located outside of the microformat. Ruby solution: Usage: Personally, I like the idea of conveying date information in the form of a link. Most situations I can think of where hCalendar would be useful, there are already links to more events that occurred on that date, or at least having them would be beneficial anyway. Then, the human representation could be anything, and the “machine” representation could be extracted from the link. All the examples I’ve seen have links that end in one of the two following forms: It seems like specifying these two formats for dates would suitably “pave the cowpaths” and do the job of supporting multiple dates in a single document. In addition, it would provide the additional usability benefit of encouraging links to date archives for finding other events. Of course, that doesn’t solve the issue of times, but those are much easier to parse out of a link’s text than dates, so that could be enough. I’m not sure yet how to deal with timezones, except to put those inside the link text as well, but that’s not great. Perhaps that could be a meta tag of something of the sort. It wouldn’t be data specific to any particular event, so it’s really not part of the microformat, but rather a hint as to how to interpret the time data for each event. I dunno, I haven’t gotten too far into this microformat thing, but it seems like all this is getting far more complicated than it needs to be. Andrew, I don’t argue that we shouldn’t try pushing screen-readers in that direction, but the situation is eerily similar to the fact that we have to design our html/css/js around poor implementations. I certainly wouldn’t get my hopes up any time soon. I think you missed a trick by not addressing the issue of multiple events in one document. You could even have marked the event up using the rest of hCal’s less contentious aspects. Here’s a fully hCal marked up example using your meta date-time idea showing multiple events and relying on ids (also marked up as hAtom for bonus points): Also, as to Simon’s point about invisible metadata, in this case the metadata is an alternate form of visible data, so I’m not sure if Tantek’s objections hold.
http://www.b-list.org/weblog/2008/jun/29/microformats-and-such/
crawl-002
refinedweb
1,918
52.12
I just got into allegro this week and by the looks of it, allegro 5 is brand new and so their are very few tutorials for it (at least as far as what I can find). After going through the few tutorials on the allegro.cc wiki, I decided to say to heck with it and try to make pong, and I've actually gone quite a bit further than I thought I would. Now here is the problem, I've managed to get 3 bitmaps: 2 paddles and a bouncer. I got the two paddles mapped to the keyboard so I can move them up and down, and the bouncer is happily bouncing around all over the place. Now I'm trying to make the bouncer bounce off the paddles. I've included my code, the logic for the bouncing starts at line 132. I've got the bouncer bouncing at the same x-coordinate as the paddles, which means it bounces even when it's not hitting the paddle, no good! BTW, I'm new to the forum, so let me know if this isn't the place to post this, since it's kind of a coding question along with a concept one. Make line 141:if((bouncer_x <= left_paddle_x + paddle_width / 2.0 + bouncer_size/2.0 && bouncer_y >= left_paddle_y - bouncer_size/2.0 && bouncer_y <= left_paddle_y + paddle_height - bouncer_width/2.0) || (bouncer_x >= right_paddle_x - (paddle_width / 2.0)) - bouncer_size/2.0 && bouncer_y >= right_paddle_y - bouncer_size/2.0 && bouncer_y <= right_paddle_y + paddle_height - bouncer_width/2.0))You also want to check if it's y value is in the boundaries of the paddle. " Great! The bouncer is now bouncing off the paddles! Now as far as changes go from allegro4 to 5, should I be able to figure out the rest of what I need from reading examples from allegro 4 for things like, a scoreboard, restarting the board when the bouncer hits the edge of the screen, a title screen etc? Thanks for the help btw! My first game! Yay! Rather than create bitmaps for the paddles and fill them with color, you could just draw them with primitives instead. Bust out some rounded rectangles, add a little shine-shine! {"name":"603455","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/1\/a\/1a49b8bc2a314928768582ec86377c39.png","w":672,"h":530,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/1\/a\/1a49b8bc2a314928768582ec86377c39"} I made some examples: I used #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_color.h> and don't forget to call al_init_primitives_addon(). Also, I used al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST); al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST); before setting up the display to make the lines draw smoothly. --AllegroFlare • allegro.cc markdown • Allegro logo Ok I can't for the life of me figure out how you did that. I've never used primitives before, and all I have to work off of is the allegro5 manual. Do you still draw a bitmap and then draw the primitive on top of it? It makes sense to me to put the draw_paddle function in another file to avoid clutter but does that mean that I should put the al_init_primitives_addon() in both .cc files? Basically, how do I go about implementing those primitives into my code? Do I just add the draw_paddle function at the end of the main loop where I draw the bitmaps? I'll do a step by step from your original code attachment. 1. First, I added just below your #include <allegro5/allegro.h>. All allegro_color does is gives me the function al_color_html(). You could just as easily take this out and use al_map_rgba_f() or other similar function for your colors. 2. Those two functions I made, draw_paddle(float x, float y) and draw_ball(float x, float y) (same as they are in the last post), I placed them just before main. This is also below your constants and enums. Usually my code structure works out like this: # includes# contants and other definitions# functions# main 3. before you create the display, (eg. before display = al_create_display(SCREEN_W, SCREEN_H);, I added three lines al_init_primitives_addon(); and al_init_primitives_addon(); can go anywhere after al_init(), and it's best to keep it with the rest of your init()s if you have more. 4. Then, way down where you have al_draw_bitmap(right_paddle, right_paddle_x, right_paddle_y, 0); al_draw_bitmap(left_paddle, left_paddle_x, left_paddle_y, 0); al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0); I commented those out and put in: //al_draw_bitmap(right_paddle, right_paddle_x, right_paddle_y, 0); //al_draw_bitmap(left_paddle, left_paddle_x, left_paddle_y, 0); //al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0); draw_paddle(right_paddle_x, right_paddle_y); draw_paddle(left_paddle_x, left_paddle_y); draw_ball(bouncer_x, bouncer_y); 5. Profit! Do you still draw a bitmap and then draw the primitive on top of it? Nope. Primitives draw themselves. Of course, you're drawing the primitives to the display, which technically is a bitmap. But you don't need to have any extra surfaces to render primitives. al_init_primitives_addon() is like al_init(). You only need to call it once when you setup your program and you're good to go. Do I just add the draw_paddle function at the end of the main loop where I draw the bitmaps? Yeaup. Thanks for the help!!! Now I'm trying to figure out how to add font so that I can add in a scoreboard. I took a look at the code in the allegro wiki on how to do fonts, but I can't seem to compile it properly. Here is the errorlesson: /home/jason/Documents/games/allegro-5.0/addons/font/text.c:73: al_draw_ustr: Assertion `font' failed.Abortedjason@Wally:~/Documents/game dev/allegro wiki lessons/lesson 6$ Looking at this terminal panic, it's looking for the fonts config in a folder called jason/Documents/games, which doesn't exist. My allegro folder is in Documents/game dev/allegro-5.0/etc... Do you mean that page? Anyway, it seems that the compilation is not the problem, but loading the font is. Have you tried putting the font file into the directory where you call your program from? This would most probably be the directory where you have your executable. --"The basic of informatics is Microsoft Office." - An informatics teacher in our school"Do you know Linux?" "Linux? Isn't that something for visually impaired people?" Just tried that, but it didn't work Which front end/compiler are you using? CodeBlocks likes to create a bin folder for your executable, but keep the root folder for your project by default. Also, what is the code you're using to try and initialize the font? --Deluxe Pacman 1 & 2 (free) with source code available I'm using gcc The code that I'm using is from the allegro wiki Just trying to get that code to work so that I can implement it into my game
https://www.allegro.cc/forums/thread/606480/904791
CC-MAIN-2019-47
refinedweb
1,113
64.91
Types of applications that can be developed using VB.Net: - Console applications - Windows forms applications - Class library - Windows control library - Windows services - Net website - Net web services - WCF services - Silver light applications - Workflow applications Console applications: Whenever an application accepts the input from console and projects the output on the console then such type of applications are called console applications. Where console is a device which has the capability to accept the information and also to display the data Inclined to build a profession as VB.Net Developer? Then here is the blog post on, explore VB.Net Training Structure of VB.Net console application: 1st method [default]: Imports statements . . . . Module Module name Sub main ( ) Statement(s) to execute . . . . End sub End module 2nd method: Imports statements . . . . Class Class name [Public] shared sub main ( ) Statement(s) . . . . . End sub End class Note: VB.Net is not the case-sensitive language but it is line sensitive language. System: It is the root namespace for any .Net application Where a namespace can be considered as a collection of classes in a hierarchy such that the class definitions can be accessed easily Console: It is a class that provides members to project the data and to accept the data. Write: It is a method to project data on console. Write Line: It is a method used to project data by appending a newline character at the end of information. Read: It is used to accept angle character. Read Line: It is used to read a single line of information i.e. accept the characters until the users press the enter key. Developing a console application using VS.Net (visual studio .Net): Prg: My first VB .Net program Imports system Module first program Sub main ( ) Console.WriteLine (“Welcome to VB.Net”) End sub End module To execute console application After selection press ctrl + F5 To add a new program to the console application [already existing] Imports system Class VB Intro Public shared sub main ( ) Console.WriteLine (“VB.Net is very easy to learn yet a powerful language”) End sub End class For an in-depth knowledge, click on below
https://tekslate.com/types-applications-can-developed-using-vb-net
CC-MAIN-2020-45
refinedweb
354
57.67
ShabBAN USER {{def convertToTitle(num): """ :type n: int :rtype: str """ result = '' while num: result = chr(ord('A') + (num-1)%26) + result num = (num - 1)/26 return result num= 29 convertToTitle(num) output : AC}} Python Solution # Approach 1: using built in replace def replaceSpaces(mystring): return mystring.replace(" ", '%20') # Approach 2: using built in split and join - which is faster than replace # Fails to address if there is a space at the end of the string. def replaceSpaces(mystring): return "%20".join(mystring.split()) # Approach 3: using append TC: SC: ? def replaceSpaces(mystring): charlist = [] for i in mystring: if i == ' ': i = '%20' charlist.append(i) return ''.join(charlist) Hey Raj/ Astha, I would interested in collaborating for interview prep. Let me know if you be interested. We can connect Hi there, I am preparing for interviews as well not Facebook right not but that on my mind. I would be happy to discuss concepts with you. That would mutually help both of us. Thanks Python Solution Output : AC- Shab June 11, 2016
https://careercup.com/user?id=4902538371399680
CC-MAIN-2020-10
refinedweb
171
65.73
A Python library for working with the Power BI API Project description PowerBI-API-Python This python package consists of helper functions for working with the Power BI API. To use this first make sure you have a Service Principal set up in Azure that has access to Power BI API. This guide shows how to set up a SP App. Basic Usage Install using pip pip install pbiapi Add the client to your project with: from pbiapi import PowerBIAPIClient Initiate the client by running: pbi_client = PowerBIAPIClient( <Tenant Id>, <Application Id>, <Service Principal Secret>, ) You can then get all the workspaces the Service Principal is admin of by running: pbi_client.get_workspaces() # Or access attribute directly: pbi_client.workspaces Project details Release history Release notifications 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/pbiapi/0.1.4b0/
CC-MAIN-2019-51
refinedweb
144
59.74
Introduction to Neogeography By Andrew J. Turner - Leo Cunningham - 2 years ago - Views: Transcription 1 Introduction to Neogeography By Andrew J. Turner Copyright 2006 O'Reilly Media, Inc. ISBN: Release Date: December 15, 2006. Contents What is Neogeography?...2 Where Are You?...15 Making Some Maps...24 Adding Location to Your Web Site...31 GeoStack...36 Licensing...38 Neogeography Projects...39 Where To Next?...52 Find more at shortcuts.oreilly.com 2 Introduction to Neogeography This Short Cut introduces current techniques of online mapping and neogeography. It covers the basic tools for finding out where you are, creating your own maps, and several illustrative projects to get you started and hopefully inspire your own projects. The code and software examples from this book are available online at This includes a complete listing of the links to sites and resources listed here for easy bookmarking. Feel free to let me know if you have any questions, or want to show off any neat ideas you put together, directly at What Is Neogeography? Cartography enabled and recorded exploration and discovery for ages. It guided sailors across oceans and helped make sense of the wilderness. Like the transformation of paper to hypertext, maps have evolved from arcane lines and arcs on parchment to dynamic displays of remote geographic information. While geographic information systems (GIS) remained expensive programs, restricted to the use of highly-trained specialists, tools like MapQuest and Yahoo! Maps brought easy-to-use mapping tools to the public. More recently, the release of Google Maps demonstrated to web developers and users the possibilities of navigation and opened a floodgate of interest in online mapping. Google Maps was not released with an application programming interface (API), but developers slowly figured out how to use the maps for their own uses, and eventually Google released a public API. The release of the API allowed developers and users to quickly and easily show geographically based data on shareable maps. Once the primary domain of GIS systems and operators, these new maps, or mashups, led to a massive increase in their propagation. The very term mashup can trace its lineage to the first mapping mashups like Housing Maps and ChicagoCrime. What is it about maps that both fascinates and educates people? Why in the online world of instantaneous global communication and anonymity has "location" become such an important theme?. Introduction to Neogeography 2 3 Essentially, Neogeography is about people using and creating their own maps, on their own terms and by combining elements of an existing toolset. Neogeography is about sharing location information with friends and visitors, helping shape context, and conveying understanding through knowledge of place. Lastly, neogeography is fun. Why else would people create a map of the locations of the television show 24, or share the location of their first kiss? Never again will you struggle to recall Where was that photo taken? Basic Terminology Several useful terms are essential to discussing neogeography. Some are familiar, while others have specific contexts within a broader meaning. They are presented here for later referral as you progress through the book and are listed in a logical order so that terms build upon one another: Coordinates 90 degrees towards the poles, and is positive North. Longitude varies East-West, with 0 degrees at the Prime Meridian, varies from 180 to 180 degrees and is positive to East. Coordinates can be represented in several formats: Decimal degrees (DD): Degrees-Minutes-Seconds (DMS): N29 58' 30'' Degrees-Minutes (DM): ' The conversion is straightforward. There are 60 seconds in a minute, and 60 minutes in a degree. Projection A projection is required in order to display the three-dimensional Earth, which isn t a sphere but actually an oblate spheroid bulging in the center, onto any other shape. Typically, this is projection onto a two-dimensional map display, where Mercator and Rectangular (i.e., no transformation) projections are the most common. For example, Google Maps uses the Mercator Projection, which is good for zoomed-in viewing, but causes distortions when zoomed out. It is important to understand the implication of various projections depending on application and also when mixing together mapping providers. Introduction to Neogeography 3 4 POI (Points of Interest) Points Of Interest, frequently abbreviated as POI, represents any significant locations such as public buildings, traveler s services, or user-defined waypoints. These may be categorized: restaurant, trail head, friend's house, scenic overlook, or scuba diving site. There is also AOI, Areas of Interest, which may include multiple POI or just a geographic area instead of a single point. Extents The bounding box, or farthest latitude and longitude of an AOI. This may also be referred to as just bbox. The extents define the Northern and Southern latitude, and the Eastern and Western longitude. Extents are the simplest means of specifying the area of interest and are usually used for web service queries. Tiles Dynamic, or slippy maps, are composed of a set of individual square images. Each image is a tile. Together, these tiles are placed next to one another, or stitched, to give the impression of a large, sliding map. Geolocation The technique of automatically determining the position of something based on measured data. For example, it is possible to locate a computer given its IP address, or a mobile phone based on the observed cell towers. Geolocation is useful for determining where a user or device is without the user having to manually enter this information. GPS is a specific implementation of a geolocation technology. GPS GPS (Global Positioning System) really refers to the U.S. military owned and operated satellite network that provides three-dimensional location. GPS is also sometimes used to refer to any means of geolocation that provides geographic coordinates. Simply put, GPS operates by a network of high-altitude space satellite broadcasting their position and time. Receivers use several of these observed broadcasts to determine its current position and time. The European operated GPS system, Galileo, is currently expected to be operational by 2010 and will provide similar, but alternate, functionality to the current GPS. Geotag Adding location information to a document, photograph, audio sample, or some other type of data is an example of geotagging. Geotagging formats are not uniform and vary based on the type of document they modify. For example, a photograph can embed location information in the EXIF header of the file itself, Introduction to Neogeography 4 5 or in many web applications the location information can be stored as tripletags in the user specified tags. Web Service A web service is a resource that allows access to data or functionality from a provider for example, a geocoder that takes an address and returns latitude and longitude is a web service, or a service to ask for all photos within 50 miles of a location. Web services typically use REST (Representational State Transfer) or SOAP (Simple Object Access Protocol) to allow programs and other sites to access the data. Data Formats Location can be stored in many formats. With roots in programming, neogeography pushes data to be stored in a clear and readable plain language format. Because broadband allows data to be conveyed quickly, more geographic information can be added to a greater variety of files. While these formats have adopted a more human-friendly format, they can quickly become large and complex to write by hand. Therefore, in future sections we ll discuss tools that make it easy to add and read these formats to your projects. For now, this section will introduce you to the overall concepts of the data formats, when it s appropriate to use them, and what their capabilities are. GPX Vendors and tools use several standards to describe geographic information. The most common file format standard is GPX, or the GPS Exchange Format. This standard uses an XML file definition to store waypoints and tracks from GPS units. Most GPS receivers internally use their own proprietary file format. Therefore, GPX is a common protocol that allows developers to write tools to convert from and to an application s or device s specific format. The header of a GPX file stores general information such as the GPX version, the application or device that created the file, and various other XML namespace information: <?xml version="1.0" encoding="utf-8"?> <gpx version="1.0" creator="gpsbabel - xmlns:xsi="" xmlns="" xsi:schemalocation=" Below that, there are lists of waypoints, tracks, or routes. A waypoint (wpt in the file example below) stores the latitude, longitude and optionally the altitude of the location. The body of the waypoint then includes the name, comment, and symbol: Introduction to Neogeography 5 6 <wpt lat =" " lon =" "> <name>01wifi</name> <cmt>espresso ROYAL</cmt> <sym>tall Tower</sym> </wpt> A track (trk in the file example below) is a successive list of waypoints and usually include a time element. This is useful later for geotagging photos or videos, as well as for creating animations of your tracks by providing a time to synchronize with the camera or recording device: <bounds minlat=" " minlon =" " maxlat=" " maxlon=" " /> <trk> <trkseg> <trkpt lat=" " lon=" "> <ele> </ele> <time> t21:42:38z</time> </trkpt> <trkpt lat=" " lon=" "> <ele> </ele> <time> t21:42:40z</time> </trkpt> <trkpt lat=" " lon=" "> <ele> </ele> <time> t21:42:42z</time> </trkpt> </trkseg> </trk> The Topografix GPX site () has a list of GPX data as well as additional resources and utilities. GeoRSS GeoRSS () is an extension to the common RSS (Really Simple Syndication) used on web sites to notify readers of new articles or updates. GeoRSS adds geographic coordinates and features to RSS and Atom items. GeoRSS comes in several flavors: W3C Geo, Simple, and GML. Simple was developed to speed the adoption and use of GeoRSS by providing an uncomplicated format that is sufficient for making points, lines, and polygons. W3C Geo exists based on historical use and is limited to just describing single points. As the need for complex geometry become necessary, GML (Geographic Markup Language) provides the ability to describe complex geographic geometry. To add GeoRSS Simple to your RSS, you need to first add the GeoRSS namespace reference to your feed definition: <?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:content="" xmlns:wfw="" xmlns:dc="" Introduction to Neogeography 6 7 xmlns: Then, in your RSS entries, you actually add the georss:point tag. The most important thing to note is that the latitude and longitude are separated by a single space, and not a comma as is typical in other data formats. The format of the GeoRSS point tag is: <georss:point>latitude longitude</georss:point> In an actual RSS entry it would look like: <entry> <title>m 3.2, Mona Passage</title> <link href=""/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated> t07:02:32z</updated> <summary>we just had a big one.</summary> <georss:point> </georss:point> </entry> As necessary, you can add radius= or elev= attributes to the georss: element. Both are assumed to be measured in meters. The radius attribute is useful for giving a scale to the described feature, and elevation is altitude above the WGS84 ellipsoid (typically supplied by a GPS receiver). In addition to just a geographic definition, GeoRSS uses two optional elements: featuretypetag and relationshiptag to provide additional metadata to the geographic element. When noting an element such as a mountain, lake, or residence, the featuretypetag is used. The relationshiptag relays the geographic coordinates to the actual entity in the RSS item, such as is-centered-at: <georss:point> </georss:point> <georss:relationship>is-centered-at</georss:relationship> <georss:featuretypetag>residential house</<georss:featuretypetag> As mentioned previously, GeoRSS Simple can support more complex geometry such as a line. This may be useful for defining a road or hiking trail: <georss:line>lat1 lon1 lat2 lon2 lat3 lon3</georss:line> <georss:line> </georss:line> A box is useful for defining the extents of an area of interest, or the location of a building: <georss:box>lower_left_lat lower_left_lon upper_right_lat upper_right_lon</georss:box> <georss:box> </georss:box> Introduction to Neogeography 7 8 or a polygon, which can be any number of sides, and is defined by a set of latitude and longitude points describing the outside boundary of the polygon. The last set of latitude, longitude must equal the first set so that the polygon is closed: <georss:polygon>lat1 lon1 lat2 lon2 lat3 lon3 lat1 lon1</georss:polygon> <georss:polygon> </georss:polygon> As the need for more complex geographic geometry arises, it is worth checking out GML (Geography Markup Language) and how to use it in GeoRSS (. For a list of GeoRSS sources, check out: Mapufacture: PlaceDB: KML Another XML format is KML (Keyhole Markup Language) (), which was developed by Keyhole Technologies and is now owned by Google. Keyhole created the KML file format, Google Earth s predecessor. Since acquiring Keyhole, Google greatly extended the use and capability of KML, which can now define three-dimensional geometry for creating geospecific buildings. Similar to GeoRSS, KML s major difference is coordinate order, which is longitude, latitude: <Point> <coordinates> , </coordinates> </Point> Like GeoRSS, KML can also define complex geometries: <Polygon id="id"> <!-- specific to Polygon --> <extrude>0</extrude> <!-- boolean --> <tessellate>0</tessellate> <!-- boolean --> <altitudemode>clamptoground</altitudemode> <!-- kml:altitudemodeenum: clamptoground, relativetoground, or absolute --> <outerboundaryis> <LinearRing> <coordinates>...</coordinates> <!-- lon,lat[,alt] --> </LinearRing> </outerboundaryis> <innerboundaryis> <LinearRing> <coordinates>...</coordinates> <!-- lon,lat[,alt] --> </LinearRing> </innerboundary> Introduction to Neogeography 8 9 While you would probably never write KML yourself, many tools exist to generate KML from other file formats, or via a drawing program. One unique feature to KML is the ability to embed 3-D visualization models into the KML file. This is how users insert buildings, objects, and geographic annotations (Sticky Notes for maps) within their files. The Keyhole BBS (Bulletin Board System) (), also known as the Google Earth Community, is an active group of users and developers sharing KML files, how-tos, and ideas, and serves as a clearinghouse for KML information. Microformats Microformats are used in web pages to identify common data such as people, places, or events. When browsers show a web page, they are translating the page s Hypertext Markup Language (HTML) for graphical rendering. The actual words or information presented are immaterial to the browser. Microformats add meaning to the HTML by providing a standardized schema applied to the class and ID of HTML attributes, permitting manipulation of this information by other programs. For example, the hcard Microformat defines how to mark up contact information for a person. Once the information is marked up in a common, meaningful way, other tools can then recognize that information and add the contact to your address book, find her social networking accounts (such as LinkedIn, Plaxo, or even MySpace), send her an , or instant message her. For Neogeography there are currently two interesting Microformats: adr and geo. adr is the definition of an address: <div class="adr"> <div class="street-address">23 Main St.</div> <div class="extended-address">suite 104</div> <span class="locality">northville</span>, <span class="region">mi</span> <span class="postal-code">48167</span> <div class="country-name">u.s.a.</div> </div> geo defines a geographic coordinate in latitude and longitude: <span class="geo"> <span class="latitude"> </span>, <span class="longitude"> </span> </span> Either of these formats can also be embedded in another Microformat in order to give that broader Microformat geographic context. For example, putting an adr in an hcal event would tell you where that event was taking place: <span class="vevent"> <a class="url" href=""> Introduction to Neogeography 9 10 <span class="summary">where 2.0 Conference</span>: <abbr class="dtstart" title=" ">may 29</abbr>- <abbr class="dtend" title=" ">30</abbr>, at the <span class="location adr">fairmont Hotel, <span class= locality >San Jose</span>,<span class= region >CA</span> </span> </a> </span> Technorati () is the primary supporter of Microformats and provides numerous tools and aggregators for them. For more information on various Microformats, how to use them, and how to help develop new ones, check out Brian Suda's O Reilly Short Cut "Using Microformats." Advanced formats So far, we ve just discussed emerging and entry-level technologies and formats. There are many more full-featured, but also more complex, standards such as WMS, WKT, and GML that provide very high-fidelity data representations and can handle complex geometry. They are key components in the underlying geospatial technology, but are beyond this scope of this book. I suggest following up with Web Mapping Illustrated by Tyler Mitchell (O Reilly) for more in-depth information on these advanced concepts. Right formats for the right job Each of the formats above have different strengths and weaknesses. They can be used together or separately depending on your application and needs. GPX is primarily a file format for working with GPS units. It lacks features for better annotation and describing actual geometries. It should be used for archiving and sharing data with devices. GeoRSS is best used for sharing geographic updates and individual items since it is limited to describing a single RSS item such as a blog post, sensor reading, story, photograph, or the tracking of a moving object. GeoRSS cannot currently handle groups or sets of points or geometries. KML is very well suited for storing and displaying sets of data such as favorite locations, plot areas, and geospecific buildings. Microformats should be limited to displayed data that will be read by a human. It doesn t serve as well as a machine-only format, and without an hcard or hevent, there isn t currently a way to associate an adr or geo with its contextual information. Introduction to Neogeography 10 11 Software Tools Now that you know what types of data are useful, it is important to identify the various tools you'll need to work with the data. Using a text editor is always an option, but only rarely the best solution. Instead, find a good program that supports the various data formats you will be using. If something is missing, try adding it yourself and sharing it back to the neogeography community. Arguably the most useful tool you'll need in neogeography is GPSBabel (). It is a cross-platform application that can convert to and from a large number of geographic data formats. GPSBabel can also upload or download data directly with your GPS unit. This might include support tracks and routes in addition to simple waypoints. Because GPSBabel is a command-line utility, some users may prefer a graphical user interface (GUI). Users of most platforms can find simple GUIs widely available. In addition to converting between formats, GPSBabel can also apply filters to the data as it is converted. Filters are useful for splitting long tracks into shorter ones where a long time or distance gap exists between points, such as when you have multi-day trips, or take a long break and don t want to store the many GPS points at a single location. Also, you can apply filters to optionally include only waypoints with a specific radius, to smooth tracks, or to remove high-error points from the track log. These filters are useful for finding POI within a specific area, or removing GPS points that have high error due to poor satellite signals. For easy GPX file management, sorting, and organizing waypoints, Windows users can use Easy GPS (), and Mac users should check out MacSimpleGPS (). Currently, most RSS feeds do not contain the GeoRSS extensions, but they may contain useful geographic information. Geonames RSS-to-GeoRSS converter () is a great tool for parsing and converting these RSS feeds to GeoRSS ones that can be used in your applications. Google Earth () is a 3-D geographic visualization tool that uses KML for locations, geometry, overlays, and histories. Google Earth also understands network links to remote KML sources, which is very useful for data that is continuously updating, such as weather tracking. WorldWind () is another 3-D geographic tool developed by NASA for scientific visualization and uses the beautiful satellite imagery for their tiles. These are a few of the tools that will ensure a productive and fun time, with new tools being developed every day. Subscribe to bookmarking feeds such as Introduction to Neogeography 11 12 or or join one of the communities mentioned in the resources section at the end of the book to find new sites and tools as the show up. Hardware Tools Neogeography does not have specific tools of the trade so much as repurposing devices you already use in a geo-centric way. For example, you may want to use a camera to take photographs of places that you visit. An audio recorder can capture the noises or music of an area. Laptops, handheld computers, and mobile phones all assist in locating, tagging, annotating and viewing your creations. But none of these tools were necessarily designed with geography as their purpose. Be creative and find new uses for common devices. GPS Units GPS units have become prolific and relatively inexpensive. You can purchase a simple USB GPS unit to attach to your laptop for as little as $30 USD. There are a couple of major factors to consider when choosing a GPS device: Display Do you want to use the unit to display maps, tracks, and information? Logging Some GPS units have built-in logging, so that when you turn the unit on it starts storing your location as tracks. Bluetooth Wireless connection is useful if you want to use the unit with a mobile phone, handheld computer, or just not deal with cables. Based on these factors, there are four major types of GPS units: Handheld, Vehicle, Logger, and Puck or GPS Mouse. A Handheld GPS unit is a full-featured device with map display, routing, tracking, and a user interface. It can be used independently of any other devices and is the most useful when out in the field. Good Handheld units include the Garmin Geko or Garmin 60CSx Vehicle GPS units are very similar to handheld units, except that in-vehicle units typically are larger, have car mounts, and assume your position is along roadways. Many cars now come with navigation systems built-in. The benefit of a built-in navigation system is that there are typically additional sensors, such as wheel speed sensors, magnetometers, and accelerometers that aid in navigation when pure GPS location is unavailable, such as in tunnels. However, these built-in systems are also not upgradeable and do not allow for as much modification and uploading of new data. Examples of vehicle GPS units include the Garmin Nüvi and the Magellan RoadMate. Introduction to Neogeography 12 13 Figure 1: GPS receivers come in different shapes in sizes: GPS logger (top left), handheld GPS (right), vehicle nav system (bottom left) A Logger GPS is a small, simple device with no connections or mapping display. Typically, you just turn the device on, and it starts storing locations to a track. Therefore, you can toss it into your bag and forget about it. When you have completed your trekking, you can then connect the GPS unit to a computer or other device and download the track. Additionally, many GPS Loggers have Bluetooth, so if you want to display your current location, you can connect a mobile phone via Bluetooth to the GPS and display maps, current position, satellites, and so on. Good loggers include the Wintec WBT-200, NaviGPS, or the Delorme Bluelogger. A Puck, or GPS Mouse is a simple GPS receiver with a cable for connecting to a computer to actually read and store the positioning data. These are the simplest devices and also don t cost very much. They have also gotten very small and easy to interface with embedded devices, such as microcontrollers or radio controlled vehicles. Check out the OpenStreetMap GPS reviews page for good discussion on GPS units: Cameras There are very few digital cameras that feature actual GPS or geolocation hardware. The Ricoh Pro G3 was the first widely available camera to have an onboard GPS sensor and automatic geotagging of your photographs. The Eye-Fi Eye-Film SD memory card should be available in 2007 and features WiFi connectivity for automatically uploading and geotagging your photos when you are near a wireless network. By embedding the geolocation technology in the common memory card, any camera can gain geolocation ability of photographs. Introduction to Neogeography 13 14 In general, any camera can be used for Neogeography projects. Later on we will discuss how to automatically and manually add geotags to your photos to locate and map them. You can also use print film that is scanned or any kind of picture. Other hardware Neogeographers experiment with a lot of other devices in their projects. Mobile phones can be used to geolocate people by recording the observed cell tower data. The Boost Mobile and Nextel mobile phones provide an interface for developers to use the geographic location in their applications. Symbian OS mobiles also provide a limited interface to the cell location information. Handheld computers and tablets such as the Nokia 770 () are being used by neogeographers to display maps using Maemo Mapper () and GPS. Also, handheld devices can record audio, video, and text for geotagging and uploading or displaying. Apple and Nike released a Sport Kit (), which is an electronic pedometer that controls your ipod music player based on the distance you have run. Neogeographers are experimenting with using this device for track distance measurement and location augmentation. Björn Hartmann s GPS + Google Maps Mash-up in 42 Lines of Code (http:// regexp.bjoern.org/archives/ html) is a great example of a quick but slick hack for building your own GPS device and using the data. Finally, geolocation components and technology are continuing to drop in price, size, and power requirements. Therefore, future generations of devices will begin to have GPS built-in as a standard feature. Introduction to Neogeography 14 15 GeoParsing Batch geocoding usually relies on us having a fairly well organized list of locations. However, it is more likely we have documents or web sites we want to get the locations from. Perhaps it is a document analyzing various real estate options in the area or a news web site. GeoParsing is the process of converting a natural language document (free of specific markup) and extracting geographic locations and their contexts. For an excellent example, check out GutenKarte (), which parses classic literature and generates maps. You can see an automatically generated map of Verne's Around the World in Eighty Days, or Tolstoy s War and Peace. MetaCarta Labs provides a GeoParser API. Using this API, you can GeoParse your own documents or web sites and generate maps, images, or feeds. See: Where Are You? We have now covered some of the general information behind neogeography. The first step, though, is actually figuring out where something is. Determining where something is can be referred to as geolocation. There are numerous geolocation techniques, some automatic and easy, some convoluted and error-prone. We will discuss some of the techniques below and examples of how to use each. The following desired data is typical for determining where you are: latitude, longitude, altitude, address, region, country, and named location. Using GPS GPS offers by far the highest fidelity means of geolocation. The current U.S. GPS network and upcoming European Galileo satellite network offer sub-meter precision to commercially available devices. A GPS receiver uses triangulation of a minimum of four satellites to locate the user in X, Y, Z, and time. By using a GPS receiver, you can directly read your current position in latitude, longitude and altitude. As you travel, you can mark waypoints, such as a picnic spot where you took pictures of the mountain range, or the head of a trail. Most GPS devices also can store a time history of locations, resulting in a track. You can then record these positions from the receiver by hand to a notebook or download them using a software program. Using a notebook offers flexibility and a backup, as notebooks never run out of batteries or get dropped and break. However, as your amount of waypoints grows, or you store tracks, it is much easier to download the data off of your GPS receiver using some software and a cable Introduction to Neogeography 15 16 (unless the GPS uses a wireless communications like WiFi). Nearly all GPS units come with their own software, or you can use the very versatile GPSBabel program discussed above to download data from your GPS receiver. Geocoding While GPS is very accurate and easy to use, we do not always have the benefit of having a receiver with us when we travel or are able to get a good signal at the location, and sometimes we are not even physically at the location we want to mark. A lot of data we will want to use for our projects may simply be named locations such as: 32 Derby Square, Salem, Massachusetts, The Eiffel Tower, or even just Brazil. Geocoding is determining the position of a named location using automatic techniques. It converts 32 Derby Square, Salem, Massachusetts to the coordinates [ , ] latitude and longitude using a web service or application. Geocoding is very useful because it can allow you to take a large set of addresses, place names, or a list of places you remember and get more accurate and mappable coordinates. There are some important considerations when geocoding. Geocoding can vary between different geocoding providers, which may be due to different datasets and different levels of service for different account levels (e.g., free, premium). Additionally, a general location name may have many valid solutions. Therefore, most geocoders return all possible locations and an estimated ranking of accuracy. It will be up to you to choose the most correct geocoded location, perhaps by comparing to other nearby locations or verifying on a map. Reverse geocoding is converting latitude and longitude into a named location. For example, do you know where N29 58' 30'' x E31 8' 15' ([29.975, ]) is? Using a reverse geocoder, you could determine that this is the location of the Great Sphinx of Egypt. Introduction to Neogeography 16 17 Geocoding with Photos For a bit of fun, check out Tim Waters Geocodr. He uses geotagged Flickr images, along with a clustering algorithm, to determine where a location is based on the Flickr tags. So if there are 50 pictures tagged with Stonehenge, then Geocodr will determine some average centroid of these picture locations and return that as the geocoded location. By using a constantly updating and changing data source like geotagged photos, Geocodr can provide up-to-date vernacular geocoding. The meaning of downtown might change from one month to the next, and traditional data sources take much longer to gather this information. Basic There are several easy ways to geocode either a single location or a large number of locations. Geonames () is a very complete and full-featured geocoder that handles cities, neighborhoods, and geographic features, and can parse general text. Geocoder.us () is a simple, single geolocation tool, but only works in the U.S. TravelGIS.com () provides a geocoder for 24 countries Batch Geocode () is a free web site that allows you to upload a large set of tab-delimited data (say from Microsoft Excel or Outlook/Thunderbird contacts), and it will automatically geocode all of these locations and give you back your locations with latitude and longitude. Additionally, you can save the generated map to a hosted web page or download and save a Google Earth KML file. (See the Mapping Your Genealogy project in this book) GPSVisualizer () provides several geocoding tools, including single point, batch geocoding, GPS tracklog conversion, and KML output. See for more links to geocoders and techniques. Advanced Filling in an Excel spreadsheet, or geocoding your contacts addresses to create a map is useful. But what if you want to embed a geocoder directly into your web site? For example, you may want to let a user see where he is in relation to where you are, or where your store is located. Introduction to Neogeography 17 18 The following is a simple web page for embedding a Google Map and an entry location for an address or location. When the user clicks on geocode, a request is made to Google Geocoder, which then creates an icon automatically for the point: <[ var geocoder; var map; // On page load, call this function function load() { // Create new map object map = new GMap2(document.getElementById("map")); map.setcenter(new GLatLng(0,0), 1); // Create new geocoding object geocoder = new GClientGeocoder(); // Retrieve location information, pass it to addtomap() } function geocode() { geocoder.getlatlng( document.getelementbyid("address").value, function(point) { if(!point) { alert("point not found"); } else { // Center the map on this point map.setcenter(point, 13); // Create a marker marker = new GMarker(point); // Add the marker to map map.addoverlay(marker); // Add address information to marker marker.openinfowindowhtml(address); }}); } //]]> </script> </head> <body onload="load()" onunload="gunload()"> <div id="map" style="width: 400px; height: 300px"></div> <input type="text" name="address" id="address" value="" width="40"/><a href="" onclick="geocode(); return false;">geocode</a> </body> </html> Introduction to Neogeography 18 19 Geolocation In our geocoder example above, we showed how to have the user specify a location, perhaps where they currently are, in order to get a map of that location. We also demonstrated how you can use a GPS receiver to get your location. Both of these techniques are typically very accurate, but also require having a GPS unit, or knowing and entering your location. Automatic geolocation is determining where you are based on various other data, such as your IP address, nearby WiFi base station, or cell towers. None of these pieces of data have innate location; however, based on historical data it is possible to associate this data with a location. Geolocation by IP An IP address is a unique identifier given to all computers when they connect to the Internet. Typically when you connect your computer to a local network, you are given a local IP address, probably like However, when your network connects via your ISP (Internet Service Provider), whether it is DSL, cable modem, T1, or GSM, then you are assigned a unique IP address. Since the IP address is unique and you usually connect to the Internet near where you are physically located (such as your office building, coffee shop, or house), the IP can be assumed to be another "address" for where you are located. This is known as GeoIP. GeoIP is useful for tracking where site visitors are coming from, providing local language and cultural interfaces, or automatically showing pertinent data such as nearby shops or resources based on the users locations. There are many databases available that associate these IP addresses with a location. This is done using several mechanisms, such as asking the user when they connect to the service for the first time, inferring that you are connecting through a specific ISP, or by knowing IP addresses in the same general numeric range and then assuming that you are also physically in the same vicinity. The accuracy of GeoIP can vary. If you are connected through a large block of static IPs, for example as part of a business or university, then the accuracy is probably good, because the IP would have been associated with the location and not changed. If you connect through a cable modem, dial-up modem, or GSM cellular modem, then the accuracy is probably very low. This is because IP addresses are given out to users as necessary. You may now have an IP address, sitting in Seattle, Washington, that two hours ago was being used by someone in Spokane, Washington. Additionally, if a user is connected through a proxy, such as a firewall, or through another remote server, then their apparent location could be very wrong. Introduction to Neogeography 19 20 Due to the possibly high inaccuracy of GeoIP, it is most often relied on for the country, and possibly the general region. It should rarely be trusted for city or better accuracy, and if used should be assumed to be wrong by some distance and allow the user to correct or ignore the guess. The largest free database and service for GeoIP is HostIP.info (). If you open the site in your browser, you will immediately see its best guess of your location. You can correct or update this to the database for the future. HostIP also provides a web service you can use for your own programs and sites, or you can download a copy of the database to store and update your own copy. HostIP.info provides a web service for requesting the location of an IP address. To use the service, pass the IP address and any other options. For example, it will be useful to get the latitude and longitude of the guessed position: The result is a simple text response, which can be parsed using a regular expression: Country: UNITED STATES (US) City: Sugar Grove, IL Latitude: Longitude: For a more complex response, remove the get_html.php. The result is an XML file that uses GML encoding: <?xml version="1.0" encoding="iso "?> <HostipLookupResultSet version="1.0.0" xmlns="" xmlns: > , </gml:coordinates> </gml:point> </gml:pointproperty> </iplocation> </Hostip> </gml:featuremember> </HostipLookupResultSet> Introduction to Neogeography 20 21 As mentioned previously, geolocation by IP can be inaccurate due to incomplete data or changed IP addresses. HostIP offers a "rough" estimate by using rough.php?ip=. The result is a best estimate, and the result also specifies if it was an estimate: Country: UNITED STATES Country Code: US City: Alexandria, VA Latitude: Longitude: Guessed: true Lastly, HostIP provides a very easy way to embed information about your visitor: <A HREF=""> <IMG SRC="" BORDER="0" ALT="IP Address Lookup"> </A> If you need better accuracy through GeoIP, then there are several commercial databases that promise better accuracy. MaxMind and Plazes both provide GeoIP databases and web services of different accuracy levels depending on the number of uses and cost. Geolocation by WiFi Similar to GeoIP, Geolocation by WiFi uses the location-associated Wireless base stations to locate you when you connect to these base stations. This is done by first locating the base station and registering its SSID, the name you see in your wireless connection dialog when you connect. Whereas Geolocation by IP depends on a single reference for location information, Geolocation by WiFi can use multiple wireless stations and their relative strengths to triangulate location information. However, obstacles, interfering signals, and the moving of base stations or taking them offline can artificially alter the measured strength of WiFi. For Geolocation by WiFi to work, it usually requires installing device drivers or a small application on the client machine to store and pass all the observed base stations to the server system. WiGLE () is a free and open database of WiFi signals. There are a couple of clients available, JiGLE and DiGLE, that allow for automatic geolocation when running on a client machine. Loki is a platform developed by SkyHook wireless, who developed a large database of WiFi locations over several years. It now provides an API () and device drivers to use WiFi geolocation in programs in Windows XP and Windows Mobile devices. Introduction to Neogeography 21 22 You can also check out Navizon (), which is another commercial option that allows users to upload their own data to help increase the database, though the database is not available for users to download and use on their own. By contributing data to Navizon, you are then given credits to use in querying Navizon s WiFi geolocation database. Geolocation by GSM Lastly, there is the newly popular mobile phone geolocation. Mobile phones simultaneously communicate with several cell towers to provide uninterrupted service as a user travels. As of 2006, all new mobile phones in the US are required to support the e911 protocol that allows mobile service providers (Verizon, T- Mobile, et al.) to locate a mobile phone. However, this information is not typically available to users or developers. Similar to Geolocation by WiFi, GSM (Groupe Spécial Mobile or Global System for Mobile Communications) geolocation measures the relative strength of nearby cell towers, using their known location to interpolate a user s present location. Once again, interfering objects and mobile phone status can alter the measurements. Finally, many mobile phones will preferentially connect to their provider s cell towers, and not necessarily to closer cell towers that belong to other providers. This results in making building of a database of cell tower locations difficult since handsets from different providers must be used to detect all towers in an area. Some mobile phones provide an interface for the location information or cell tower identifiers. The newest phones on the market actually have an embedded GPS receiver, bypassing the need for triangulation by the protected, and potentially inaccurate, cell towers. GSM geolocation requires four values from the mobile phone: CID, LAC, MCC, and MNC. These are all parameters that uniquely identify a cell tower: CID Cell Identification is a number that identifies the active cell. The CID is unique to the LA (Local Area). LAC Local Area Code is a regional identifer; several cells are contained in a LA (Local Area). MCC Mobile Country Code is the X.121 code for the country (214 = Spain, 238 = Denmark, etc.) Introduction to Neogeography 22 23 MNC Mobile Network Code is the provider or carrier (T-Mobile, Orange, Verizon, etc.) GSMLoc () is a project started by Christopher Schmidt to provide a free and open service database for collecting and sharing measured cell locations and areas. To use GSMLoc, there is a REST web service where you enter the observed cell tower parameters, and get back the bounding box and centroid of the estimated location: where nid1 is the MCC and nid2 is the MNC. You can then get the response in text, XML, or Javascript object notation (JSON). GSMLoc is very open for users to contribute new data. You need a Symbian Series 60 capable phone, such as the Nokia series. Then install the StumbleStore application (requires Python for Series 60). Start up StumbleStore, connect to a Bluetooth GPS, and then "Start Stumbling." As you wander about, StumbleStore will record the observed cell towers, and GPS location of these signals. When you are done stumbling, you can then upload this information back to GSMLoc. Mologogo () is a small project that works with Nextel phones and various Windows Mobile devices. It lets you upload your location to a central server. General geolocation In this section, we covered several mechanisms and tools for geolocation. Primarily, we discussed services and utilities that you could easily integrate into your own projects. There are a lot of other services that do geolocation and provide services built upon geolocation. However, there are at least several projects that bring all of these techniques together, and provide various services and tools for mixing into your site and applications. Intel's PlaceLab () performed extensive research and tool development for many geolocation techniques. The POLS, Privacy Observant Location System () project spun out and provides tools for various geolocation methods on mobile devices. The PlaceLab project still has numerous papers and research on geolocation technologies and user interfaces. Introduction to Neogeography 23 24 Plazes () is a web application that tracks users and locations, and does geolocation by IP, WiFi, cell, and user-defined location. Using their Plazer application, you can easily set new locations and find other people nearby. The Plazer even integrates with Skype to set your location in your status message. A great part about Plazes is its public API () that is free for non-commercial use and lets you do all kinds of things with the location data, photos, tracks, and so on. Making Some Maps Using the techniques and tools covered previously, we can gather locations appropriate to your project. The following information will help create maps of this data. Depending on your goal and audience, there are several ways to produce a map. There are many excellent free, open source, or commercial programs that allow you to load your own data, generate a web page, or even print your maps for offline use. You can also use web sites to generate code for embedding maps and location interfaces into your own web sites or generate an entire site. Lastly we will talk about the lower-level tools you can use to program your own maps. Mapmaking Web Sites Many web sites provide a way for users to easily make and maintain maps. Some sites merely collect locations and share the map on their service. Other sites help embed the maps in your own site. Platial has gained attention as a leading social mapping site. Its primary purpose is providing a location where users can create sets of locations and share them with other users. Viewers can then check out these user-suggested locations, such as Parks in Washington, D.C. ( parks outdoor patio hiking biking hike b ike trail trails&where=washington,%20dc) It is easy to create a map using Platial. After establishing an account, click "Make a Map" and provide a title, description, and optional icon. On the Map Creation page you can add locations. To get close to your location, enter an address, and then click on the map to add a marker and press Next. Fill out the information on the story about the location. Keep going to add all your locations. [this step-by-step seems overly detailed compared to your other descriptions. I would simplify the directions.] Introduction to Neogeography 24 25 When finished, view your map or it to others. Using Platial's MapKit () you can embed this new map in your own web page. Click on the MapKit link, fill in the URL, and then click Make my MapKit. On the next page, you will see a textbox with HTML and JavaScript code required to embed the new Platial map in your web site. You can further customize your map markers, name, size, starting location, and tags. Your Platial map has GeoRSS output that can be used in an aggregator or viewer like Mapufacture, and KML output for viewing in Google Earth. Other sites that allow users to build static maps include: MapBuilder: GMapEZ: QuickMaps.com For more sites and utilities, check out GoogleMapsMania () and geo tagged sites on del.icio.us (). Build a map site in Ning Using Platial lets you create a static map for embedding into your web site. You can add your own markers and annotations and have these show up on the map. Although the map is viewable, it provides one-way communication, and does not allow users to add or edit locations. For a more dynamic dataset and web application functionality, there are other applications. Ning is a web application service that provides users with a sandbox to create their own social web applications. You can start from a template application, start with a copy of an existing Ning application, or completely write your own application in the Ning framework. For example, in Ning it is trivial to make photo sharing sites, user groups, blogs, or videos. You can then add geographic location to these applications using Ning's Mapping API () to drop in a Google Map. Then you could create a map of your photo locations, your user's favorite hangout spots, or locations mentioned in your favorite television show. To start, browse around Ning's site and find an application you like, such as a photo mapping application: 1. Navigate to 2. Click "Get your own photos site" in the top bar 3. Choose a Name and a web address Introduction to Neogeography 25 26 4. Customize your application colors and privacy, and invite people to start using it. To see all of the Ning Map applications and grab a copy for your own use, see Ning's Map Mash-Ups listing. () Ning also provides a site for getting photos of an area like on Yahoo! Maps. () Programming Your Own Maps Feeling a little more ambitious and want to create your own maps? Many tools and platforms make it straightforward to program your own maps. In this section we will discuss some of the libraries and tools you can use to quickly and easily embed maps and location into your site or application. These libraries require some programming, typically in JavaScript for web sites. For most web site mapping libraries there is a three-step process: 5. Include the map library s JavaScript file in your header 6. Create an HTML element that will place and size the map 7. Include the JavaScript to call the map s creation function, and add markers, controls, zoom, map type, lines, or style Each mapping library has slightly different syntax and different features, but this three-step process is a pretty good basis for starting with any of the libraries and then expanding from there. Mapstraction Mapstraction () is a JavaScript library that provides a common interface for the various mapping providers. This permits you to create your map and then switch between Google, Yahoo!, Microsoft, MultiMap, or other provider s maps. You can even dynamically switch the map without reloading the page. To use Mapstraction, you will need to include the headers, and necessary keys of the desired mapping provider s JavaScript definitions in the head of your HTML. The keys are available from the mapping library s home page (listed in the Mapping Libraries resources section), depending on the terms of service and licensing. Put the following script definitions in the <head> section of your web page: For Google Maps: <script type="text/javascript" src=""></script> For Yahoo! Maps: <script type="text/javascript" Introduction to Neogeography 26 27</script> For Microsoft VirtualEarth: <script type="text/javascript" src=""></script> For MultiMap: <script type="text/javascript" src=""></script> The required Mapstraction Javascript: <script src="/mapstraction.js" type="text/javascript"></script> Then, you need to define the location and size of the map, and center it: <div id="simplemap" style="width: 500px; height: 300px"></div> <script type="text/javascript"> var mapstraction = new Mapstraction('simplemap','google'); var firstpoint = new LatLonPoint( , ); mapstraction.setcenterandzoom(firstpoint, 15); mapstraction.addcontrols(pan:true, zoom: 'large', overview: true, scale:true, map_type:true); </script> <a href="#" onclick="mapstraction.swap('google'); return false;">google</a> <a href="#" onclick="mapstraction.swap('yahoo'); return false;">yahoo</a> <a href="#" onclick="mapstraction.swap('microsoft'); return false;">microsoft</a> See the Mapstraction API for more documentation and examples on how to use the library. Mike Williams () has a great set of advanced tutorials on Google Maps, and check out the O'Reilly book Google Maps Hacks by Rich Gibson and Schuyler Erle for more ideas and information on mapping libraries. Introduction to Neogeography 27 28 Proxies Most browsers have a built-in security measure to protect against possible attacks by only allowing your browser to connect to one web site at a time. Thus, a site can t make a JavaScript request to another web site. Therefore, all data must come from the web site you are currently visiting. This isn t always what you want, especially for a mash-up that pulls data from several sources into a single view. To overcome this problem, the web site needs to provide a local proxy for your browser to request the data from. The proxy routes the remote service through the local server and to your browser. You can download a simple proxy from the book s site: However, you should be careful when setting up a proxy, as malcontents can use a publicly visible proxy as a gateway for their nefarious purposes, and it would all be traceable to you. Therefore, you can either set up Apache to do your proxying, or hardcode the remote service URL into your proxy. For more information on proxying, and other options on securing your proxy, visit: OpenLayers While Mapstraction is a mapping abstraction library that provides a simple interface to a large number of mapping APIs, the OpenLayers project is pushing the envelope with new and advanced functionality for dynamic maps. OpenLayers () is a free and open source JavaScript mapping library that provides developers with a large toolkit not found in other modern libraries. It was spun out from MetaCarta labs and powers a number of their other open projects, such as GutenKarte (). Some of the advanced features include: Multiple layers that can each be turned off or on WMS tiles from map servers Layers for Google, Virtual Earth, Yahoo!, and MultiMap Bounding-box zoom Using OpenLayers is very similar to using the other mapping APIs: you include your header definition, define an HTML element to use for the map, define the map in JavaScript, and then add layers, controls, and markers. <html> <head> <script src=""></script> </head> Introduction to Neogeography 28 29 <body> <div style="width:100%; height:100%" id="map"></div> <script defer="defer" type="text/javascript"> var map = new OpenLayers.Map('map'); var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", "", {layers: 'basic'} ); map.addlayer(wms); map.zoomtomaxextent(); </script> </body> </html> A very advanced and useful feature of OpenLayers is that it can consume geographic feeds such as GeoRSS and automatically create markers and information bubbles. The GeoRSS feed is added as an additional layer and can therefore be turned on and off in the map. To create a map of weather conditions, put the following JavaScript in your page: var weather = new OpenLayers.Layer.GeoRSS( "Weather", "proxy.pl?", {layers: 'basic'} ); map.addlayer(weather); Notice the prefix proxy.pl?. This is required to access files from the server. See the sidebar on proxies for more information on how to set up and properly use a local proxy. Because OpenLayers supports freely available mapping tiles from WMS servers, it is an excellent tool for web applications that display unique or proprietary datasets and locations. In addition, the development team is quickly adding new features and support. See WMS-Sites () for a growing list of WMS services available and areas of interest. worldkit Mikel Maron's worldkit () is a free and open source Flashbased map that supports a variety of formats for easily mapping locations and feeds. It is different from the above mapping APIs that rely on JavaScript and an external source of mapping tiles and images. Using Flash for mapping provides better cross-browser support since functionality is provided by a standardized plugin. Flash is also good for mobile applications. Configuration of worldkit includes placing the SWF (Shockwave Flash) file and an XML configuration file on your web site. config.xml: <?xml version="1.0"?> <worldkitconf> <width>500</width> <height>250</height> Introduction to Neogeography 29 30 <displaytype>daynight</displaytype> <dayimg>day.jpg</dayimg> <nightimg>night.jpg</nightimg> <dataurl>rss.xml</dataurl> <update>60</update> <showonlynew>false</showonlynew> </worldkitconf> The "dataurl" can be a local rss.xml file, or a remote file by using a proxy mentioned above. worldkit uses GeoRSS and plain RSS with geocoding to get the locations of the data points. And then add the following code in your HTML file: <object classid="clsid:d27cdb6e-ae6d-11cf-96b " codebase=" 7,0,0,0" WIDTH="800" HEIGHT="400" id="worldkit"> <param NAME= movie <param NAME= quality <param NAME= bgcolor <embed src="worldkit.swf" quality="high" bgcolor="#000000" WIDTH="800" HEIGHT="400" NAME="worldkit" ALIGN="" TYPE="application/x-shockwave-flash" swliveconnect="true" PLUGINSPAGE=""> </embed> That is all there is to it. Check out the worldkit documentation for more information on configuration options, and integration into various weblogs and engines. OpenStreetMap OpenStreetMap () is an ambitious project to create a free and open geographic database of the world using user-collected data. Users travel with their GPS and cameras, recording streets, parks, paths, trails, and other features, and then upload their GPX files to the central OSM servers. Then, using any of several client applications, they can annotate the GPX track data with actual streets, names, traffic patterns, and so on. After that, all of the data is aggregated together to provide the world with a database of information. Introduction to Neogeography 30 31 Figure 2: OpenStreetMaps JOSM editor makes it easy to mark up and annotate GPS tracklogs into street data The gathered data is licensed under the Creative Commons Attribution Share Alike 2.0 License (CC-By-SA) (), which allows for free use in your applications. Companies such as Nestoria () have started using OSM data for their local real estate mapping in parts of the UK. It is also possible to use the OpenStreetMap tools and data to create your own printed maps for use when you are away from the digital world. The project started in 2004, and in that time it has gathered millions of data points from countries all over the world. OpenStreetMappers often hold mapping parties in various locations where for a day or two large groups run around with GPS receivers to thoroughly map an area. You are definitely encouraged to check out the project and contribute, and see about setting up your own mapping party. Adding Location to Your Web Site In the previous section you learned how to build some maps. You probably now have a neat map, with pop-up bubbles and all describing some of your favorite locations. However, just placing a map into a site can make it feel like an add-on, rather than an integral part of your web site. It is more useful to integrate location and maps into your web site, dynamically adding locations based on the content of a blog post, the location of visitors to the site, or based on aggregated data from other sources. Introduction to Neogeography 31 32 In this section we will present some of the tools and techniques for integrating neogeography into your site. Once you add location to your site, users can then find your web site based on geographic location (e.g., a web site for a store). Services like GeoURL () and A2B () maintain a directory of web sites based on their specified location. Also, GeoTagThings () is another site that stores userspecified locations of web sites. Using a browser bookmarklet, you can quickly associate any web page with a location. A bookmarklet is a small JavaScript bookmark that you can add to your browser s bookmark list or bar and then click to activate some functionality. In this case, you will be taken to a form to locate the page on GeoTagThings. Location of a Page The first thing you may want to do is to mark the location of an entire page. The <meta> tags in the HTML area can be used for specifying the location. Unfortunately, as is typical with emerging standards, there are several different formats that can be used for specifying the location of a page. The ICBM format was defined by Joshua Schachter for GeoURL and further promoted by Matt Croydon (). It is useful for specifying the exact coordinates of a page: <meta name="icbm"=" ; "/> <meta name="geo.region" content="us-mi"> <meta name="geo.placename" content="northville"> After you have included the meta-markup in your page, register your site with GeoURL and A2B so that other users can find your page or location through their search engines. GeoURL publishes W3C geo RSS feeds of sites, and A2B provides a web service API for querying their database (). Introduction to Neogeography 32 33 Markup places Location is more than a map. While latitude and longitude offer fairly exact positioning, they do not offer the average user an actual understanding of where that location is. Is it in your town or state? Near where you are going on location? So, in addition to adding maps to your site or application, it is still important to include the address or location of your reference places. Furthermore, there are several easy methods to mark up this information so that other utilities and applications can read and manipulate this geoinformation. In the section on Microformats we talked about how they allow you to embed location information in the text of your web site. Addresses or coordinates can be included in an hcard or hcal reference, giving context to the location. Users can use this in their site for a list of store locations, where they want customers to easily get directions, or for a list of photographs. A simple example of including a list of addresses in your site would look like: <ul> <li class="adr"> <div class="street-address">30051 Park Ave.</div> <span class="locality">new York City</span>, <span class="region">ny</span> <span class="postal-code">10001</span> </li> <li class="adr"> <div class="street-address">21 South Division St.</div> <span class="locality">detroit</span>, <span class="region">mi</span> <span class="postal-code">48202</span> </li> </ul> Once you mark up the locations in your site, there are tools that can then use this information for additional functionality. For example, GreaseRoute () is a Firefox GreaseMonkey script that automatically detects Address (adr) and Geographic Coordinates (geo) Microformation. It then provides viewers with a link to get a map, or directions to the location. Additionally, GreaseRoute s embedded version uses Geolocation By IP to determine where the viewer is and give them directions without requiring them to enter their current address. Introduction to Neogeography 33 34 Figure 3: Browser extensions like GreaseRoute can detect addresses or coordinates in a web page and display additional information such as a map or driving directions Syndicating locations While it is possible to directly write about locations, and use Microformats and JavaScript to build up your travel log or document various locations, there are tools that make the entire process much easier. GeoPress () is a plug-in for the popular WordPress () blogging engine that adds the ability to quickly add location, Microformats markup, dynamic Google-Yahoo-Microsoft maps using Mapstraction, and GeoRSS output for syndication. To start using GeoPress, install WordPress, or choose an existing WordPress blog that you want to add location information to. Then download and copy the GeoPress folder to your wp-content/plugins directory. In the Admin interface of your WordPress blog, go to Plugins, and Active GeoPress. You will then need to get a Google Maps API key and a Yahoo! App ID. Now go to the Write page, and underneath the Post writing section, you will see an area for entering a location and a map. You can enter an address or city and press Enter or Geocode. The map will center to the geocoded location. If you want to save this location for later use, you can give it a name (such as Home, Vacation House, or Best Coffee Shop ), and then write your post. Introduction to Neogeography 34 35 Figure 4: GeoPress adds dynamic maps and Microformat markup to the WordPress blogging engine When you first start using GeoPress, mapped locations will be automatically inserted into posts. You can optionally turn this feature off and manually enter maps into posts. To insert a map into the post, just write INSERT_MAP anywhere in the post body. This will insert a map based on the default settings you can configure in the GeoPress->Map tab. Alternatively, you can use INSERT_MAP(height, width) to set a specific map size. You can also use INSERT_ADDRESS or INSERT_COORDS to put the adr or geo Microformat, respectively, in the page. GeoPress is also particularly useful for automatically adding the GeoRSS information to your RSS and ATOM feeds. Therefore, all of your subscribed readers can now get this geographic information. In the next section we'll discuss how this all works together. There are similar plug-ins for other blogging engines. Geo Location for MovableType: pnh_mf for Textpattern by Chris Casciano: Introduction to Neogeography 35 36 A blog is just one way to generate and syndicate geographic data. Blog engines are actually quite flexible, and can be configured to not act like a typical blog but just as a simple Content Management System (CMS). However, there are more full-featured CMSs that offer geographic support. Wikipedia offers a list of GeoCMS () packages. Where in the Wiki? Wikipedia itself has embraced mapping through various projects and now has better built-in support. mysociety s Placeopedia () allows users to attach location to any Wikipedia article. Another project, Wikimapia (), creates new entries for using a Wiki and maps. Several popular CMS platforms have added support for importing and exporting geographic data. Most notably, the Midgard () and Drupal () CMSes have added full GeoRSS support via modules/plugins. Therefore, you could make pages for any location or trip, embed maps, syndicate, aggregate, annotate, and share, all in the same application. GeoStack There are a lot of technologies and tools that have been presented so far. Individually, these tools provide some nice features for gathering or showing location data. You now know how to mix some of the tools together, like GPSBabel and Google Earth to get data from your device into the 3-D global viewer. Neogeography is working to bring all these technologies together into a GeoStack. The GeoStack is a collection of tools and mechanisms that together cover all parts of collecting, gathering, and sharing location information. It enables using a GPS system to capture a waypoint and eventually have other users around the world view and comment on that waypoint. The GeoStack can be divided into the various steps of data management. Along these steps, there are numerous paths the data can come from or take, depending on the actual application (generating maps, 3-D visualization, adding to my GPS unit POIs). These steps are laid out and illustrated in Figure 5 below: Capture GPS unit, camera, WiFi/Cell/IP logger, notebook of locations Produce The blog, Wiki, sites, databases that contain and generate geographic data Introduction to Neogeography 36 37 Communicate A standardized mechanism for generating and transmitting the data Aggregate Tools for gathering, storing, filtering, and redistributing the original data Consume A viewer, map, or reader that a user uses to view the information; also can upload to GPS to use as direction waypoints or POIs Figure 5: The GeoStack encompasses the entire life cycle of geospatial data, from capture to consume using a variety of tools, formats, and applications The emerging GeoStack is very exciting. Data is not limited to proprietary formats or locked into a single application. You can gather your tracks and waypoints on GPS, share them in your blog, aggregate them to other users who can then download them and add them to their own GPS units. Introduction to Neogeography 37 38 Additionally, there are lots of sites showing up with rich sets of data. Just check out Google Maps Mania () to see the daily number of new mash-ups that display and generate geographic data. Platial, Ning, Flickr, and Yahoo! all publish their data in GeoRSS format. Aggregators like Mapufacture make these feeds searchable and locatable and will generate new feeds, such as kayaking in Colorado for all the photos, rapids, weather reports, and other information on the sport in the area. You could then save all this data back to your GPS receiver for showing when you are braving the waters. Future applications and sites should consider how they fit into the GeoStack. By doing so, they enable users to quickly and easily bring in and reuse their geographic data. In the next section we will discuss some projects that use the GeoStack for useful and interesting applications. Licensing We have talked a lot about data and mapping providers, but we only briefly touched upon things like terms of service. However, the issue is a very large and important one. Geographic information such as POIs, maps, routes, and various other data constitute a huge market. There are many companies and clearinghouses that build their entire business on owning and controlling data. They also spend large amounts of money to gather, organize, and distribute this data. In addition to commercial sources of data, users and neogeographers are constantly collecting and sharing data. Waypoints, hiking paths, photographs, and so on are media that have terms of use associated with it. Without data, neogeography becomes rather empty. What is a map without any imagery or roads? It is important to understand and comply with the licensing terms that come with data. Sites such as Flickr provide users with an easy mechanism for specifying if their photos are public/private and released under restrictive licenses, or Creative Commons licensing (). However, the distinction is not always so easy to make and understand. The United States has a good history of sharing geographic data that is gathered by the government. The TIGER/Line data () (Topologically Integrated Geographic Encoding and Referencing system) is all of the census and street data gathered during the U.S. national census. The data is released under very open terms. However, the rest of the world does not enjoy this much free data. Introduction to Neogeography 38 39 Groups such as the INSPIRE Initiative () are working to harmonize data access among nation states in the European Union. Efforts include advocating more open access to data by the public. By comparison, the OpenStreetMap project is working to generate new data that is released under a CC-By-SA License (Creative Commons By Attribution Share Alike). In the future, efforts such as the OGC s (Open Geospatial Consortium) () geographic digital rights working group () will develop standards for supporting and complying with geographic data licensing. In the meantime, make sure you understand and follow the licensing terms of the data you are using and producing. Neogeography Projects That covers most of the tools, techniques, and terms you will need to start making some really cool sites, mash-ups, programs, or whatever. Now we will actually start pulling all these pieces together to make some example projects. We are going to cover the following projects: Locating your photographs Directions to your locations Tracking your sports Mapping your genealogy However, this is just a starting point to give you some ideas and show you how to bring all these techniques together to a useful end. There are a lot of other projects just waiting for you to start. Perhaps you should make a map of alumni, teammates, club members or forum members, or a carpooling application for where people live and are traveling to. There are also a lot of possibilities for neogeography games. Every year, the Come Out & Play Festival () is held in New York City and features dozens of innovative and fun geolocated games. Locate Your Photographs You take a wonderful trip, perhaps a cruise in the Bahamas, backpacking across Europe, driving around Asia, or tramping in New Zealand. You have hundreds or thousands of photographs of people, places, and experiences. People ask you Where was this taken? or What was it like in Seville? Introduction to Neogeography 39 40 By geotagging your photographs, you can embed the actual location information into the photo itself and map it. Then you can show your trek by train across Germany, or all the photos you took in Hong Kong. Smart neogeographers will carry a small GPS logger with them as they travel. Then by synchronizing photograph times with GPS tracks, it is possible to infer the location of the photos. Note, for this to work well, you should increase the logging rate of your GPS unit. A good number is probably every two seconds, depending on the type of activity you are doing (the faster you move, the more frequently you should log your position). When you merge together GPS tracks and photographs, where they do not match up, usually some type of interpolation is performed to estimate the position of the photograph between the nearest two known locations and times. To help calibrate your camera and GPS unit, you should make sure to set the appropriate time zone and time on your camera using your GPS unit. Additionally, it helps to take a photograph of a known landmark before you start your trek. You can then come back and use this known landmark and location to correlate your GPS tracks with your camera clock. Digital photographs store their metadata in EXIF (Exchangeable Image File Format) (). This usually includes camera make/model, shutter speed, aperture, and date/time. However, there is also the option of adding location name, region, country, latitude, longitude, and altitude, all that is necessary to geotag your photograph. As mentioned previously, some cameras, and some media storage devices are starting to be sold that automatically tag photographs with the location of the photo. The tools and techniques below can either use your GPS or embedded location information, or provide you with ways to geotag your photographs after you get home. One common problem with these tools and geotagging techniques is that they assume the entered location or GPS track is where the photo was taken. However, its more meaningful to geotag the photograph with the *subject*. For example, a photograph of Mount Rainier should be geotagged with the location of Mount Rainier, not Seattle. Some tools also provide a means to specify the heading that the picture was taken at. Basic There are several desktop applications that provide an easy interface for associating photographs with locations. Typically, these allow you to select a set of photographs and load a GPS track if available. Otherwise, you can manually enter locations. Introduction to Neogeography 40 41 For Windows users, there is RoboGEO (), which costs $35 $80, depending on if you will be using the software for commercial purposes. Alternatively, Microsoft distributes a free program WWMX () and Location Stamper that will synchronize GPX track logs and photographs and modify the EXIF data. Google s Picasa () is a photo-management application for Windows and Linux that also supports geotagging photos using Google Earth and Google Maps. Mac OS X users can turn to GPSPhotoLinker () to load tracks, load photos, and have the geographic coordinates and location embedded into the photo EXIF. Flickr (), the photo-sharing site, supports geotagged photos. To use geotagged photos in Flickr you will first need to set a few configuration options. You will probably want to change your Geo Privacy settings () to allow at least your friends, if not other visitors, to see the locations of your photos. If you are uploading photos with geographic coordinates in the EXIF data, then go to your account settings, and select automatically geotag photos in the Geo Import section (), and turn on automatic geo importing. By turning on this option, Flickr will read the EXIF geotags you add to your photos for your map. If you didn t use one of the programs above, or you want to map photos that you ve already uploaded to Flickr, then there are several ways to do this. The easiest is to use the built-in mapping system. Select the Organize menu item, and then select the Map tab. Drag photos from the organizer bar in the bottom to the appropriate location on the map. The other option you have is to directly tag the photos with the location information. If you select a photo you want to geolocate, then double-click the photo. Select the "location" tab, and then add in the latitude and longitude values. Introduction to Neogeography 41 42 Figure 6: Flickr allows you to directly enter geographic coordinates for photographs These coordinates can come from a GPS receiver if you carried one with you, or you can use another geocoder to convert the location name to latitude and longitude. For example, MultiMap () provides coordinates for locations all over the world. Geonames () also provides a good geocoder and is especially good at providing coordinates for location names like Hancock Tower in Chicago, Illinois [ , ]. You can directly add these geotags by adding the tags to any photo: geotagged, geo:lat=, and geo:lon=, with the appropriate latitude and longitude entered into the lat and lon tags respectively. Copy the latitude and longitude and then put them into the geo: tags. If you have a lot of photos at a single location, you can use the batch organize to quickly apply the location tags to all of the photos at one time. Figure 7: Triple-tagging photos is easy for batch geotagging photos Lastly, keep on the lookout for more tools showing up that make geotagging easier. For example, Localize Bookmarklet () is a Firefox bookmarklet that lets you geotag your photos directly from the normal view page of the photo. Introduction to Neogeography 42 43 Now that your photos are geotagged, you will want to see the resulting map. Under the You menu item, select Your Map. It will also have the URL Additionally, you can get a feed of your photos. At the bottom of the Flickr page, look for the Feed icon and link. This will generate an RSS feed, something like: This feed is just a vanilla RSS feed and doesn t contain the geo information. To get GeoRSS output, add the following parameter to the URL: &georss=1. You will now see a GeoRSS feed of photos. Photos without location do not have the <georss:point> tag. You can get specifically tagged photos by adding &tags=tagname. This is particularly useful for grabbing your geotagged photos if you have added geotagged to the photos and then use &tags=geotagged in your feed. SmugMug (), Panoramio (), Mappr (), and Zooomr () are more photo-sharing sites that support mapping and automatically reading GPS EXIF data. Some output Google Earth KML feeds so you can view your photos in Google Earth. Check out Mark Pilgrim s TripperMap (), a web application that makes a Flash map of your Flickr photos, and even a travel map from the locations and times of your photos. Intermediate Flickr and other photo-sharing sites with mapping are very convenient, and also provide a social aspect. However, their customization and integration are limited. Additionally, you need to be aware of terms of service, licensing, and privacy issues when you uploading your media to a photo-sharing site. Gallery () is open source, self-hosted photography album software. It provides a rich set of features that a user can put on his own site, or integrate into his web application. There are modules and plug-ins for adding specific functionality to Gallery. Specifically, there are plug-ins available that allow users to create maps of their photos. The Map Module () is an add-on to Gallery that geolocates and maps your photos that you upload. The location of the photo can be entered manually using longitude and latitude, via point-and-click on a map to autofill the GPS coordinates, by geocoding an address, or directly from the photo EXIF data. Introduction to Neogeography 43 44 The GPS Module () adds the ability to output a KML feed for displaying your photos in Google Earth. For mobile phone cameras, Yahoo! Labs is trying out ZoneTag (), which automatically geotags your photos when you upload them from your phone by using cell geolocation. Advanced ExifTool () is a command-line program written in Perl by Phil Harvery that provides a direct means for reading and writing the EXIF data of a photo. Using ExifTool, you can write scripts to geotag your photographs based on whatever scheme you want to use, such as folder name, or current location (geotag your photos based on automatic geolocation). What is especially useful for using a utility like ExifTool is that you can write geotagging into the photo application you currently use. For example, you can download a small AppleScript that will allow you to geotag photos in Apple s iphoto, Microsoft s iview Media Pro (), or Adobe s Photoshop. () gpsphoto.pl () is a command-line tool for synchronizing GPX tracks and photographs. This script can be used for your own scripts to geocode your photographs. For example, you could have the script geotag your photos when they are uploaded to your server, or dropped into a folder with a GPX file. Once you geolocate your photos, Photokit ( id=47&itemid=5) is a script that will generate the datafile to display your photos in worldkit. You can then easily put this map in your own site. You can also use OpenLayers to generate a map of your photos. OpenLayers can directly consume GeoRSS and add it as a layer to the map. Therefore, we can get the Flickr feed for a set of photos and specify that we want GeoRSS output of the feed. See the discussion above for how to get the GeoRSS Flickr feed. Then add the following to your OpenLayers map code to add the new Flickr layer: var flickr_map = new OpenLayers.Layer.GeoRSS( "Flickr", geotagged&format=rss_200&georss=1"); openlayers_map.addlayer(flickr_map); Now when you refresh your map, you should see the Flickr layer and icons for your geotagged photos. Introduction to Neogeography 44 45 Next steps It is possible to geotag more than just your photos. The FreeSound Project () supports geotagging audio files and creating maps (). VlogMap () geotags video content. Additionally, any site or service that supports tagging can use triple-tagging to create geotags. Just use the triumverate of: geotagged geo:lat= geo:lon= and you are on your way to geotagging anything. Directions to Your Locations Locations are great, but unless we are imagining ourselves there, eventually we will want to know how to actually get there. As a business owner or someone that needs to publish locations, you will want to make it easy for users to get directions to your locations from wherever they are. For example, a business with several store locations may want to let a customer quickly find out how to reach the nearest store. For someone that organizes sporting events for kids, they may want to let other parents get easy directions to the various fields or arenas. Publishing directions So you have customers that want to get to your store. Of course, you have already published your store locations in Microformat adr (and hcard), so users could use tools like the previously demonstrated Firefox extension GreaseRoute to get directions to your locations. However, for users that do not use Firefox, or do not have that extension, then you can add your own directions to here. The easiest way is to just put in a hyperlink to the Google Maps or Yahoo! Maps page with this location. Users can then get directions using that service directly. But for a more unified experience, you can embed the directions right in your web site using the free MapQuest OpenAPI (). To start, you will need to register and get an account on the MapQuest site. Now, to add the directions, you will need to do the typical web map dance: header, HTML element, JavaScript. Header: Introduction to Neogeography 45 46 <script src="" type="text/javascript"></script> HTML Element: <ul> <li class="adr" id="location1"> <div class="street-address">1 Main St.</div> <span class="locality">gainesville</span>, <span class="region">fl</span> <span class="postal-code">32601</span> <a href="#" onclick="getdirections('location1')">get Directions</a> </li> </ul> <form id="address_form" name="address_form"> <fieldset> <legend>your Address</legend> <label for="a1">address:</label><input type="text" name="1a" id="a1"/> <label for="a1">city:</label><input type="text" name="1c" id="c1"/> <label for="s1">state:</label><input type="text" name="1s" id="s1"/> <label for="z1">zip Code</label><input type="text" name="1z" id="z1"/> </fieldset> </form> <div id= map_container style= height:400px;width:600px ></div> JavaScript (this uses Robert Nyman's Ultimate getelementsbyclassname (): <script type="text/javascript"> var mqroute = null; function getdirections(location) { mqroute = new MQRoute("container"); var store_location = document.getelementbyid(location); var user_location = document.getelementbyid('address_form'); var thumbsize = new MQSize(); thumbsize.setheight(150); thumbsize.setwidth(300); var overviewsize = new MQSize(); overviewsize.setheight(400); overviewsize.setwidth(600); mqroute.primarymapsize = overviewsize; mqroute.origin.setaddress(getelementsbyclassname(store_location, "*", "streetaddress")[0].innerhtml); mqroute.origin.setcity(getelementsbyclassname(store_location, "*", "locality")[0].innerhtml); mqroute.origin.setstateprovince(getelementsbyclassname(store_location, "*", "region")[0].innerhtml); mqroute.origin.setpostalcode(getelementsbyclassname(store_location, "*", "postal-code")[0].innerhtml); mqroute.origin.setname("orig"); mqroute.destination.setaddress(user_location.elements.nameditem("1a").value); mqroute.destination.setcity(user_location.elements.nameditem("1c").value); mqroute.destination.setstateprovince(user_location.elements.nameditem("1s").val ue); Introduction to Neogeography 46 47 mqroute.destination.setpostalcode(user_location.elements.nameditem("1z").value) ; mqroute.destination.setname("dest"); mqroute.doroute("map_container"); } function routereturn(mqroute, status) { } </script> Using directions Besides creating directions to locations you are publishing you will want to be able to get to various locations yourself. For example, it may be useful to have a listing of coffee shops that offer free WiFi connections. When you're out traveling, you can find and get directions to the nearest one. In this project we'll show you how to load a set of locations onto your GPS device and use that to get to you the closest destination. Figure 8: Most GPS receivers allow you to upload your own waypoints To start, you will need a listing of businesses or locations. Sites such as GPSPassion () have forums where users build and share GPX or CSV (Comma-Separated Values) files of various businesses. Alternatively, you can use a KML file, GeoRSS, or another GPX file you make yourself. If you have a spreadsheet of locations, you need to arrange the columns in this order: latitude, longitude, name, and description. If you do not have the latitude and longitude yet, I suggest using Batch Geocoder () or a similar service to get the coordinates. Once you have your columns arranged, save the file back as a CSV file. Then open GPSBabel, and convert from CSV to GPX or the file format appropriate for your Introduction to Neogeography 47 48 GPS unit. You can even export directly to your GPS unit. Some units, such as the Garmin Nüvi, allow you to drop GPX files into the unit using a USB connection. For an extra level of utility, you can apply a filter to include only locations within a certain distance of a central location. For instance, you may just want WiFi locations within 300 miles of your house. Now that you have your waypoints stored into your GPS unit, you can now start wandering and find directions to your locations en route. Track Your Sports Many neogeographers find comfort in the knowledge that their hobby can also help them get into shape. Sports such as running, hiking, sailing, and skiing all cover large areas, and it can be fun to record your favorite trips and experiences. In this mini project, we will show you how to track your progress, plot it on maps, and even see a movie of your sport. The Garmin Forerunner is a GPS receiver that straps to your wrist and is an example of a sport-centric device that is useful during your sport, by directly showing you your progress, but also storing your location history as a track for later downloading. Additionally, a GPS logger is usually small enough to be tucked into a pouch or mounted to your equipment and used to track your location. A waterproof case is a good idea for water-based sports. For example, when scuba diving you could put a GPS Logger in your dive buoy. Then as you swim around and pull along your dive buoy, it will create a 2-D water trace of your location. You can then augment this with the depth measurement from your dive computer to create a 3-D trajectory of your dive. OK, so let us assume you have gone out for a good hike, you took along your trusty GPS receiver, and recorded your tracks. Here s what you do: 1. Open GPSBabel and export your tracks to a GPX file. Also, save your tracks to a KML file. If there are multiple tracks, it may help to apply a filter to split tracks separated by a certain distance or time (such as multi-day hikes) 2. Open Google Earth, and open your KML file 3. Notice the time slider at the top, expand/contract the time, or slide it to view your track history. Press the Play button (triangle) to animate the track. Introduction to Neogeography 48 49 Figure 9: Google Earth supports time in KML files from GPS tracks for visualizing your sports, such as skiing or hiking There are other sites such as Motion Based () that provide the uploading, storing, displaying, and analyzing of sport tracks. GPSVisualizer () supports a large number of file formats for tracks, and also allows you to generate maps for printing. GeoTracing () is an innovative platform that supports real-time tracking using a Bluetooth GPS receiver and mobile phone to upload your progress. GeoTracing is an open source system, and has been used to build GeoSailing and GeoSkating, just to name a few. There are a lot of services for specific sports. MTBGuru () is a site for mountain-bike riders, GoFlying () for pilots, and GPSSledMaps () for snowmobilers. Lastly, OpenStreetMaps accepts trails and paths to its database. By annotating and sharing your tracks to OSM, other users can benefit from your tracks. Mapping Your Genealogy Genealogy is the study of family history, including lineages (siblings, children), life events (birth, marriages, deaths), and cultures. Our history is comprised of our Introduction to Neogeography 49 50 family and where they lived, the times they lived in, and the experiences they had. Neogeography is ideally suited to help understand and track your families lives, travels, and backgrounds. Perhaps we should call it geogenealogy. In this project, we will demonstrate how to record and export your family history, geocode the locations of their events, and then visualize it and share it with others. Here is a quick listing of the steps we'll be doing: 1. Export/store genealogical information in a tab-separated format 2. Batch geocode to get latitude and longitude of locations 3. Save KML file and display in Google Earth 4. Display a Map or make a web page To begin, you will want a good start on the documentation of your family's history. There are many programs that are specifically designed for this, such as crossplatform GRAMPS () or phpmyfamily () for web servers. See Wikipedia for a comprehensive list of genealogy software (). Some programs such as The Next Generation () support listing latitude and longitude directly into family events and plotting these on a map. All of these programs store and can export GEDCOM (GEnealogical Data COMmunication), which is a standard format for storing genealogical information. Currently the format itself is rather odd and ill-formatted standard. The next version, GEDCOM 6.0 will use more consumable and extensible XML. In addition to exporting GEDCOM, the applications can usually also export CSV or Tabseparated file formats, which are more general formats that will be useful later. Alternatively, there are GEDCOM converters, like Oxy-Gen () that can convert GEDCOM to any number of other formats. You can also just write up your genealogy documentation in a spreadsheet program such as Microsoft Excel. Whether converting to CSV or starting in a spreadsheet, you will want to create several columns: name, location, and description. These will probably be created for you when exporting from your genealogy program. You need to choose what location you will be exporting for this part of the project. You can do birthplace first, and then come back and do death location, or some other events. Introduction to Neogeography 50 51 Open your exported CSV, or file in Microsoft Excel. Highlight the columns you want, and copy. Then go to BatchGeocode ( ) and copy into the Step #2 box. Click on Validate Source. After your data is read in, select the appropriate fields in Step #4. If you just have a single Location column, use that for the Address field and leave the others blank. Also choose the Title and Description fields. When you are done setting up all the fields, click on Run Geocoder. Once complete, the results will be output in Step #6. You can save this back to your spreadsheet or a text file if you want to keep the data for later. You will also see an example map of the locations. Below the map, you can Download to Google Earth (KML) file. Click this and save the file with your spreadsheet. Batch Geocode is also great in that it allows you to make your own web page and map directly from this data. Click on Save Map to a Webpage, and fill in the information. You now have a web page you can share with other family and friends. To visualize the location in 3-D, open the KML file you saved. I made an example map using the birthplace of the U.S. presidents: Introduction to Neogeography 51 52 For further fun, you can save the spreadsheet file as a CSV again, and convert it to GPX or another format using GPSBabel, and then load it into your GPS unit. Then on your road trip, you can visit the locations of your ancestors. Where To Next? Welcome to neogeography. I hope your introduction was a good one. By now, your brain is probably filled with ideas on all the cool projects you can start. The point of neogeography is to have fun with mapping and possibly do something useful in the meantime. The tools and community really strive to make the tools easy and fun to use. There are a lot of great resources out there for more information. The code and software examples from this book are available online at This includes a complete listing of the links to sites Introduction to Neogeography 52 Cybercasing the Joint: On the Privacy Implications of Geo-Tagging Cybercasing the Joint: On the Privacy Implications of Geo-Tagging Gerald Friedland 1 Robin Sommer 1,2 1 International Computer Science Institute 2 Lawrence Berkeley National Laboratory Abstract This article Computing in the national curriculum COMPUTING AT SCHOOL EDUCATE ENGAGE ENCOURAGE In collaboration with BCS, The Chartered Institute for IT Computing in the national curriculum A guide for primary teachers Computing in the national curriculum CITIZENS AS SENSORS: THE WORLD OF VOLUNTEERED GEOGRAPHY CITIZENS AS SENSORS: THE WORLD OF VOLUNTEERED GEOGRAPHY Michael F. Goodchild 1 ABSTRACT In recent months there has been an explosion of interest in using the Web to create, assemble, and disseminate geographic Hot Potatoes version 6 Hot Potatoes version 6 Half-Baked Software Inc., 1998-2009 p1 Table of Contents Contents 4 General introduction and help 4 What do these programs do? 4 Conditions for using Hot Potatoes 4 Notes for upgraders Privacy and Electronic Communications Regulations. Guidance on the rules on use of cookies and similar technologies Privacy and Electronic Communications Regulations Guidance on the rules on use of cookies and similar technologies Contents 1. Introduction 2. Background 3. Consumer awareness of cookies 4. Terminology Many Hands Make Light Work: Public Collaborative OCR Text Correction in Australian Historic Newspapers. Rose Holley Many Hands Make Light Work: Public Collaborative OCR Text Correction in Australian Historic Newspapers Rose Holley March 2009 National Library of Australia ISBN 978 0 642 27694 0 About the author: Rose Getting the Most out of NEO 2 Getting the Most out of NEO 2 Getting the Most out of NEO 2 2Know!, Accelerated Math, Accelerated Math Enterprise, the Accelerated products design, Accelerated Reader, AccelScan, AccelTest, AlphaHub, Automatically Detecting Vulnerable Websites Before They Turn Malicious Automatically Detecting Vulnerable Websites Before They Turn Malicious Kyle Soska and Nicolas Christin, Carnegie Mellon University JCR or RDBMS why, when, how? JCR or RDBMS why, when, how? Bertil Chapuis 12/31/2008 Creative Commons Attribution 2.5 Switzerland License This paper compares java content repositories (JCR) and relational database management systems The Greenfoot Programming Environment The Greenfoot Programming Environment MICHAEL KÖLLING University of Kent Greenfoot is an educational integrated development environment aimed at learning and teaching programming. It is aimed at a target Privacy and Tracking in a Post-Cookie World Privacy and Tracking in a Post-Cookie World A whitepaper defining stakeholder guiding principles and evaluating approaches for alternative models of state management, data transparency and privacy controls BUILD AN AUDIENCE FOR YOUR WEB SERIES: HOW TO BUILD AN AUDIENCE FOR YOUR WEB SERIES: Market, Motivate and Mobilize Julie Giles A Publication of the Independent Production Fund Publication date May 2011 Written by: Julie Giles, Accessing PDF Documents with Assistive Technology. A Screen Reader User s Guide Accessing PDF Documents with Assistive Technology A Screen Reader User s Guide Contents Contents Contents i Preface 1 Purpose and Intended Audience 1 Contents 1 Acknowledgements 1 Additional Resources Uncle Roy All Around You: Implicating the City in a Location-Based Performance Uncle Roy All Around You: Implicating the City in a Location-Based Performance Steve Benford, Martin Flintham, Adam Drozd, Rob Anastasi, Duncan Rowland The Mixed Reality Laboratory, The University of Nottingham 11 Strategies for Managing Your Online Courses 11 Strategies for Managing Your Online Courses Featuring content from A MAGNA PUBLICATION Effective Group Work Strategies for the College Classroom. 11 Strategies for Managing Your
http://docplayer.net/10975-Introduction-to-neogeography-by-andrew-j-turner.html
CC-MAIN-2017-13
refinedweb
16,221
51.99
Creating GUI Applications with JFrame This content was STOLEN from BrainMass.com - View the original, and get the already-completed solution here! Create a GUI application with JFrame that contains five labels describing reasons that a customer might not buy a specific product (e.g. "too expensive"). Place a JButton on the JFrame, and code its functionality so that every time the user clicks on the button one of the reasons is removed from a label.© BrainMass Inc. brainmass.com October 25, 2018, 8:57 am ad1c9bdddf Solution Preview Following the description given in the question, attached solution (558735-NotBuyReasons.java) displays 5 labels followed by a button. On clicking ... Solution Summary Java version "1.7.0_21" was used during development and testing of the attached program. Java Programming I need the size of the frame to be set a little bit larger than its content, which is a label. Also, the location could be set so that it could be appeared not at the upper left corner of the screen. And we can set the foreground and background color of the label. import javax.swing.*; import java.util.*; public class helloWorldSwing {); /(); } }); } }
https://brainmass.com/computer-science/java/creating-gui-applications-jframe-558735
CC-MAIN-2018-51
refinedweb
192
56.15
Web Based SSH Access your OpenShift Applications Web Based SSH Access your OpenShift recently came across KeyBox. This is a Apache licensed SSH console for applications in an OpenShift Domain. The cool thing is, that it is completely web-based. And by far cooler: The client is completely written in JavaScript (using term.js) connecting to JSch (Java implementation of SSH2) running as a web-application on the JBoss Enterprise Web Server (EWS 2.0). This It might take a while, but after the command finished, you can access KeyBox via:-<namespace>.rhcloud.com All members of the domain can login with their OpenShift account. @spkavanagh6) and star the KeyBox-OpenShift repository if you like it! IAM is now more than a security project. It’s an enabler for an integration agile enterprise. If you’re currently evaluating an identity solution or exploring IAM, join this webinar. Published at DZone with permission of Markus Eisele , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/web-based-ssh-access-your?mz=62447-cloud
CC-MAIN-2019-09
refinedweb
182
51.04
fuchsia / third_party / make / 09202bc880b1cb40bdf5035b7cefebc74d4c552e / . / ChangeLog.2 blob: 0816454647bdc3c8c52a5fa4799dc6a80042d8ec [ file ] [ log ] [ blame ] 2000-06-22 Paul D. Smith <psmith@gnu.org> * job.c (start_job_command): Increment commands_started before the special check for ":" (empty command) to avoid spurious "is up to date" messages. Also move the test for question_flag after we expand arguments, and only stop if the expansion provided an actual command to run, not just whitespace. This fixes PR/1780. 2000-06-21 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): If we find a semicolon in the target definition, remember where it was. If the line turns out to be a target-specific variable, add back the semicolon and everything after it. Fixes PR/1709. 2000-06-19 Paul D. Smith <psmith@gnu.org> * config.h-vms.template: #define uintmax_t for this system. * config.ami.template: Ditto. * config.h.W32.template: Ditto. * configure.in: We don't use select(2) anymore, so don't bother checking for it. * acconfig.h: Ditto. * acinclude.m4: Ditto. * file.c (all_secondary): New static global; if 1 it means .SECONDARY with no prerequisites was seen in the makefile. (snap_deps): Set it appropriately. (remove_intermediates): Check it. (num_intermediates): Remove this global, it's not used anywhere. (considered): Move this to remake.c and make it static. * NEWS: Document the change to .SECONDARY. * make.texinfo (Special Targets): Document the change to .SECONDARY. * implicit.c (pattern_search): Remove the increment of num_intermediates; it's not used. * filedef.h: Remove num_intermediates and considered. * function.c (handle_function): If the last argument was empty, we were pretending it didn't exist rather than providing an empty value. Keep looking until we're past the end, not just at the end. * implicit.c (pattern_search): Multi-target implicit rules weren't expanding the "also made" targets correctly if the pattern didn't contain a slash but the target did; in that case the directory part wasn't being added back to the stem on the "also made" targets. Reported by Seth M LaForge <sethml@newtonlabs.com>, with a patch. 2000-06-17 Eli Zaretskii <eliz@is.elta.co.il> * Makefile.DOS.template (DESTDIR, bindir, datadir, libdir) (infodir, mandir, includedir): Support installation under a non-default DESTDIR. * remake.c (f_mtime): Fix the spelling of __MSDOS__. * configh.DOS.template (HAVE_FDOPEN, HAVE_MKSTEMP): Define. 2000-06-14 Paul D. Smith <psmith@gnu.org> * acinclude.m4 (pds_WITH_GETTEXT): rewrite fp_WITH_GETTEXT and rename it to avoid confusion. This version is very specific: it won't accept any gettext that isn't GNU. If the user doesn't explicitly ask for the included gettext, we look to see if the system gettext is GNU (testing both the actual libintl library, and the libintl.h header file). Only if the system gettext is really GNU gettext will we allow it to be used. (pds_CHECK_SYSTEM_GETTEXT): A helper function. 2000-06-13 Paul D. Smith <psmith@gnu.org> * gettext.h: If we have libintl.h, use that instead of any of the contents of gettext.h. We won't check for libintl.h unless we're using the system gettext. * function.c (func_word): Clarify error message. 2000-06-10 Paul Eggert <eggert@twinsun.com> Support nanosecond resolution on hosts with 64-bit time_t and uintmax_t (e.g. 64-bit Sparc Solaris), by splitting FILE_TIMESTAMP into a 30-bit part for nanoseconds, with the rest for seconds, if FILE_TIMESTAMP is at least 64 bits wide. * make.h: Always define FILE_TIMESTAMP to be uintmax_t, for simplicity. * filedef.h (FILE_TIMESTAMP_HI_RES, FILE_TIMESTAMP_LO_BITS) (UNKNOWN_MTIME, NONEXISTENT_MTIME, OLD_MTIME) (ORDINARY_MTIME_MIN, ORDINARY_MTIME_MAX): New macros. (FILE_TIMESTAMP_STAT_MODTIME): Now takes fname arg. All uses changed. (FILE_TIMESTAMP_DIV, FILE_TIMESTAMP_MOD) (FILE_TIMESTAMP_FROM_S_AND_NS): Remove. (FILE_TIMESTAMP_S, FILE_TIMESTAMP_NS): Use shifts instead of multiplication and division. Offset the timestamps by ORDINARY_MTIME_MIN. (file_timestamp_cons): New decl. (NEW_MTIME): Now just the maximal timestamp value, as we no longer use -1 to refer to nonexistent files. * file.c (snap_deps, print_file): Use NONEXISTENT_MTIME, UNKNOWN_MTIME, and OLD_MTIME instead of magic constants. * filedef.h (file_mtime_1): Likewise. * main.c (main): Likewise. * remake.c (update_file_1, notice_finished_file, check_dep) (f_mtime, name_mtime, library_search): Likewise. * vpath.c (selective_vpath_search): Likewise. * remake.c (f_mtime): Do not assume that (time_t) -1 equals NONEXISTENT_MTIME. When futzing with time stamps, adjust by multiples of 2**30, not 10**9. Do not calculate timestamp adjustments on DOS unless they are needed. * commands.c (delete_target): Do not assume that FILE_TIMESTAMP_S yields -1 for a nonexistent file, as that is no longer true with the new representation. * file.c (file_timestamp_cons): New function, replacing FILE_TIMESTAMP_FROM_S_AND_NS. All uses changed. (file_timestamp_now): Use FILE_TIMESTAMP_HI_RES instead of 1 < FILE_TIMESTAMPS_PER_S to determine whether we're using hi-res timestamps. (print_file): Print OLD_MTIME values as "very old" instead of as a timestamp. 2000-05-31 Paul Eggert <eggert@twinsun.com> * remake.c (name_mtime): Check for stat failures. Retry if EINTR. 2000-05-24 Paul D. Smith <psmith@gnu.org> * main.c (decode_switches): The "positive_int" switch uses atoi() which succeeds for any input, and doesn't notice if extra, non-digit text is after the number. This causes make to mis-parse command lines like "make -j 5foo" as "make -j5" (ignoring "foo" completely) instead of "make -j0 5foo" (where "5foo" is a target). Fix this by checking the value by hand. We could use strtol() if we were sure of having it; this is the only questionable use of atoi() I found so we'll just stick with that. Fixes PR/1716. * i18n/ja.po, i18n/nl.po, i18n/pt_BR.po: New translation files. * configure.in (ALL_LINGUAS): Added pt_BR. 2000-05-22 Paul Eggert <eggert@twinsun.com> * remake.c (f_mtime): Fix bug when handling future odd timestamps in the WINDOWS32 case. Do not bother initializing static var to zero. Simplify code that works around WINDOWS32 and __MSDOS__ time skew brain damage. 2000-05-22 Paul Eggert <eggert@twinsun.com> * job.c: Don't include time.h, as make.h already does this. 2000-05-22 Paul Eggert <eggert@twinsun.com> * configure.in (AC_CHECK_HEADERS): Add sys/time.h. (AC_HEADER_TIME): Add. (clock_gettime): Prefer -lrt to -lposix4, for Solaris 7. (gettimeofday): Add check for standard version of gettimeofday. This merges changes written by Paul D. Smith. * file.c (file_timestamp_now): Use gettimeofday if available and if clock_gettime does not work. Don't bother with high-resolution clocks if file timestamps have only one-second resolution. * make.h <sys/time.h>: Include, conditionally on the usual TIME_WITH_SYS_TIME and HAVE_SYS_TIME_H macros. This is needed for gettimeofday. 2000-05-20 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): We weren't keeping makefile names around unless there was a rule defined in them; but now we need to keep them for variables as well. Forget trying to be fancy: just keep every makefile name we successfully open. * remote-cstms.c (start_remote_job_p): Change DB_EXTRA (?) to DB_JOBS. 2000-05-17 Paul Eggert <eggert@twinsun.com> * commands.c (chop_commands): Ensure ctype macro args are nonnegative. * expand.c (variable_expand_string): Likewise. * function.c (subst_expand, lookup_function, msdos_openpipe): Likewise. * job.c (vms_redirect, start_job_command, new_job, child_execute_job, construct_command_argv_internal, construct_command_argv): Likewise. * main.c (decode_env_switches, quote_for_env): Likewise. * misc.c (collapse_continuations, end_of_token, end_of_token_w32, next_token): Likewise. * read.c (read_makefile, do_define, conditional_line, find_char_unquote,get_next_mword): Likewise. * variable.c (try_variable_definition): Likewise. * vpath.c (construct_vpath_list): Likewise. * w32/pathstuff.c (convert_vpath_to_windows32): Likewise. 2000-05-10 Eli Zaretskii <eliz@is.elta.co.il> * main.c (main) [__MSDOS__]: Add SIGFPE to signals we block when running child programs, to prevent Make from dying on Windows 9X when the child triggers an FP exception. 2000-05-08 Paul D. Smith <psmith@gnu.org> * dir.c (find_directory) [WINDOWS32]: If we strip a trailing "\" from the directory name, remember to add it back. The argument might really be inside a longer string (e.g. %Path%) and if you don't restore the "\" it'll be truncated permanently. Fixes PR/1722. Reported by <steven@surfcast.com> 2000-05-02 Paul D. Smith <psmith@gnu.org> * job.c (construct_command_argv_internal) [WINDOWS32]: Added "rd" and "rmdir" to the list of command.com commands. Reported by Elod Horvath <Elod_Horvath@lnotes5.bankofny.com> 2000-04-24 Paul D. Smith <psmith@gnu.org> * i18n/ja.po: New translation file from the Japanese language team. 2000-04-18 Paul D. Smith <psmith@gnu.org> * remake.c (f_mtime): If ar_member_date() returns -1 (the member doesn't exist), then return (FILE_TIMESTAMP)-1 rather than returning the timestamp calculated from the value -1. Fixes PR/1696. Reported by Gilles Bourhis <Gilles.Bourhis@univ-rennes1.fr>. 2000-04-17 Paul D. Smith <psmith@gnu.org> * config.h.W32.template: Add LOCALEDIR macro resolving to "". * w32/subproc/sub_proc.c (process_begin): Remove reference to debug_flag; change it to a DB() call. Fixes PR/1700. Reported by Jim Smith <jwksmith@attglobal.net> 2000-04-17 Bruno Haible <haible@clisp.cons.org> * arscan.c [BeOS]: Add replacement for nonexistent <ar.h> from GNU binutils. 2000-04-11 Paul D. Smith <psmith@gnu.org> * function.c (expand_builtin_function): If no arguments were provided, just quit early rather than changing each function to test for this. (function_table[]): Change the min # of arguments to 0 for all those functions for which it makes sense (currently everything that used to take a minimum of 1 argument, except $(call ...)). Fixes PR/1689. 2000-04-09 Eli Zaretskii <eliz@is.elta.co.il> * README.DOS: Add instructions to install a binary distro. Mention latest versions of Windows. 2000-04-07 Eli Zaretskii <eliz@is.elta.co.il> * main.c (main): Rename TMP_TEMPLATE into DEFAULT_TMPDIR, and use it for the directory of the temporary file. If P_tmpdir is defined, use it in preference to "/tmp/". Try $TMPDIR, $TEMP, and $TMP in the environment before defaulting to DEFAULT_TMPDIR. (print_version): Add year 2000 to the Copyright line. 2000-04-04 Paul D. Smith <psmith@gnu.org> * Version 3.79 released. * make.texinfo: Update documentation with new features for 3.79. * function.c (func_wordlist): Don't re-order arguments to wordlist. 2000-04-03 Paul D. Smith <psmith@gnu.org> * remake.c (f_mtime): Archive member timestamps are stored as time_t, without nanoseconds. But, f_mtime() wants to return nanosecond info on those systems that support it. So, convert the return value of ar_member_date() into a FILE_TIMESTAMP, using 0 as the nanoseconds. 2000-03-28 Paul D. Smith <psmith@gnu.org> * Version 3.78.92 released. * build.template: Updates for gettext support; some bugs fixed. 2000-03-27 Paul D. Smith <psmith@gnu.org> * config.guess, config.sub: Updated from config CVS archive at :pserver:anoncvs@subversions.gnu.org:/home/cvs as of today. * read.c (record_files): Check if expanding a static pattern rule's prerequisite pattern leaves an empty string as the prerequisite, and issue an error if so. Fixes PR/1670. (read_makefile): Store the starting linenumber for a rule in TGTS_STARTED. (record_waiting_files): Use the TGTS_STARTED value for the file location passed to record_file() instead of the current linenumber, so error messages list the line where the target was defined instead of the line after the end of the rule definition. * remake.c (start_updating, finish_updating, is_updating): Fix PR/1671; circular dependencies in double-colon rules are not diagnosed. These macros set the updating flag in the root double-colon file instead of the current one, if it's part of a double-colon list. This solution provided by Tim Magill <magill@gate.net>; I just changed the macro names :). (update_file_1): Call them. (check_dep): Call them. The change to not automatically evaluate the $(call ...) function's arguments breaks recursive use of call. Although using $(if ...) and $(foreach ...) in $(call ...) macros is important, the error conditions generated are simply to obscure for me to feel comfortable with. If a method is devised to get both working, we'll revisit. For now, remove this change. * function.c (function_table): Turn on the expand bit for func_call. (func_call): Don't expand arguments for builtin functions; that will have already been done. 2000-03-26 Paul D. Smith <psmith@gnu.org> * file.c (remove_intermediates): Never remove targets explicitly requested on the command-line by checking the cmd_target flag. Fixed PR/1669. 2000-03-23 Paul Eggert <eggert@twinsun.com> * filedef.h (FILE_TIMESTAMP_STAT_MODTIME): Use st_mtime instead of st_mtim.tv_sec; the latter doesn't work on Unixware. 2000-03-18 Paul D. Smith <psmith@gnu.org> * file.c (file_hash_enter): If we're trying to change a file into itself, just return. We used to assert this wasn't true, but someone came up with a weird case involving archives. After playing with it for a while I decided it was OK to ignore it. * default.c: Define COFLAGS to empty to avoid spurious warnings. * filedef.h: Change #if ST_MTIM_NSEC to #ifdef; this is a macro containing the name of the nsec field, not true/false. * make.h: Ditto. Reported by Marco Franzen <Marco.Franzen@Thyron.com>. 2000-03-08 Tim Magill <magill@gate.net> * remake.c (update_file): Return the exit status of the pruned file when pruning, not just 0. Fixes PR/1634. 2000-02-24 Paul D. Smith <psmith@gnu.org> * configure.in: Close a minor potential security hole; if you're reading makefiles from stdin (who does that?) you could run into a race condition with the temp file using mktemp() or tmpnam(). Add a check for mkstemp() and fdopen(). * main.c (open_tmpfile): New function to open a temporary file. If we have mkstemp() (and fdopen()), use that. If not use mktemp() or tmpnam(). If we have fdopen(), use open() to open the file O_CREAT|O_EXCL. If not, fall back to normal fopen() (insecure). (main): Call it. * job.c (child_execute_job) [VMS]: Call it. * variable.c (lookup_variable): If we find a variable which is being expanded, then note it but keep looking through the rest of the set list to see if we can find one that isn't. If we do, return that. If we don't, return the original. Fix for PR/1610. While implementing this I realized that it also solves PR/1380 in a much more elegant way. I don't know what I was smoking before. So, remove the hackage surrounding the original fix for that (see below). Change this function back to lookup_variable and remove the extra setlist argument. * variable.h (recursively_expand_setlist): Remove the macro, rename the prototype, and remove the extra setlist argument. (lookup_variable): Ditto. * expand.c (recursively_expand): Rename and remove the extra setlist argument. (reference_variable): Use lookup_variable() again. (allocated_variable_append): Remove the extra setlist argument. 2000-02-21 Paul D. Smith <psmith@gnu.org> * README.template: A few updates. * i18n/de.po: New version from the German translation team. 2000-02-09 Paul D. Smith <psmith@gnu.org> * Version 3.78.91 released. 2000-02-07 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Reset *p2 to ':', not *colonp. If any filenames contained backslashes the resulting output (without backslashes) will be shorter, so setting *colonp doesn't change the right character. Fix for PR/1586. For += target-specific variables we need to remember which variable set we found the variable in, so we can start looking from there in the next iteration (otherwise we might see it again in recursively_expand and fail!). This is turning into a hack; if it gets any worse we'll have to rethink this entire algorithm... implementing expansion of these references separately from the "normal" expansion, say, instead of using the same codepath. Actually, it's already "worse enough" :-/. Fix for PR/1380. * variable.h (recursively_expand_setlist): Rename recursively_expand to add a struct variable_set_list argument, and make a macro for recursively_expand. (lookup_variable_setlist): Rename lookup_variable to add a struct variable_set_list argument, and make a macro for lookup_variable. * expand.c (recursively_expand_setlist): Take an extra struct variable_set_list argument and pass it to allocated_variable_append(). (reference_variable): Use lookup_variable_setlist() and pass the returned variable_set_list to recursively_expand_setlist. (allocated_variable_append): Take an extra setlist argument and use this as the starting place when searching for the appended expansion. If it's null, use current_variable_set_list as before. * variable.c (lookup_variable_setlist): If the LISTP argument is not nil, set it to the list containing the variable we found. 2000-02-04 Paul D. Smith <psmith@gnu.org> * variable.c (print_variable): Write out filename/linenumber information for the variable definition if present. (define_variable_in_set): Store filename information if provided. (define_variable, define_variable_for_file): Removed. (try_variable_definition): Use define_variable_loc() to keep variable definition location information. * read.c (read_makefile): Keep variable definition location info. (do_define): Ditto. (record_target_var): Ditto. * variable.h (define_variable_in_set): New fileinfo argument. (define_variable, define_variable_loc, define_variable_for_file): Declare new macros. Fix PR/1407: * filedef.h (struct file): Rename patvar to pat_variables and make it just a variable_set_list; we need our own copy of the pattern variable's variable set list here to avoid overwriting the global one. * variable.c (initialize_file_variables): Move the instantiation of the pat_variables pointer here. Only do the search after we're done reading the makefiles so we don't search too early. If there's a pat_variables value, set up the variables next ptr. * expand.c (variable_expand_for_file): Remove the setup of the pat_variables info; it's done earlier now to ensure the parent's pattern variables are set up correctly as well. 2000-02-03 Paul D. Smith <psmith@gnu.org> * job.c (sh_chars_dos) [WINDOWS32]: Add "&" as a shell metacharacter for the W32 DOS shell. Reported by Warren Jones <wjones@tc.fluke.com>. 2000-02-02 Paul D. Smith <psmith@gnu.org> Fixes for the OpenVMS port from Hartmut Becker <becker@rto.dec.com> * config.h-vms [VMS]: Define LOCALEDIR to something; needed for the expansion of bindtextdomain() even though it's a no-op. * vmsfunctions.c (strcmpi): Remove duplicate definition of strcmpi(). (readdir): Use DB() instead of testing debug_flag. * dir.c (file_impossible) [VMS]: Search "p" not "name". * job.c [VMS]: Switch from debug_flag to the new DB macro. Add some i18n _() macros (even though VMS doesn't yet support it). * function.c (patsubst_expand): Change "len" to not be unsigned to avoid type mismatches. * main.c (main): Declare signame_init() if we're going to call it. 2000-01-29 Eli Zaretskii <eliz@is.elta.co.il> * Makefile.DOS.template: Track changes in Makefile.in (install-recursive, uninstall-recursive): Add missing targets. (DESTDIR): Define. (install-binPROGRAMS, uninstall-binPROGRAMS): Use $(DESTDIR). * default.c (default_variables) [__MSDOS__]: Define CXX to gpp. 2000-01-27 Paul D. Smith <psmith@gnu.org> * gettext.c: Some warning cleanups, and a fix for systems which don't define HAVE_ALLOCA (the workaround code was included twice). 2000-01-26 Paul D. Smith <psmith@gnu.org> * Version 3.78.90 released. 2000-01-25 Paul D. Smith <psmith@gnu.org> Change gettext support to use the simplified version in libit 0.7. * getopt.c, make.h: Use gettext.h instead of libintl.h. * ABOUT-NLS, gettext.h, gettext.c: New files from libit 0.7. Modified to remove some static declarations which aren't defined. * acconfig.h: Use new gettext #defines. * acinclude.m4: Add fp_WITH_GETTEXT; remove AM_GNU_GETTEXT. * configure.in: Call fp_WITH_GETTEXT instead. * Makefile.am: New gettext stuff. Also force inclusion of glob files for systems which have LIBC glob. * i18n/Makefile.am, i18n/.cvsignore: New dir for translation files. * i18n/de.po, i18n/es.po, i18n/fr.po, i18n/ko.po, i18n/nl.po: * i18n/pl.po, i18n/ru.po: Import translations already done for earlier versions of GNU make. Thanks for that work!! * po/Makefile.in.in, po/POTFILES.in: Removed. 2000-01-23 Paul D. Smith <psmith@gnu.org> * main.c (decode_debug_flags): If debug_flag is set, enable all debugging levels. (debug_flag): Resurrect this flag variable. (switches): Make -d give the old behavior of turning on all debugging. Change --debug alone to emit basic debugging and take optional arguments to expand debugging. * NEWS: Document the new debugging options. * remake.c (no_rule_error): Remove this function. This tries to fix a real problem--see the description with the introduction of this function below. However, the cure is worse than the disease and this approach won't work. (remake_file): Put the code from no_rule_error back here. (update_file_1): Remove call to no_rule_error. * filedef.h (struct file): Remove mfile_status field. 2000-01-22 Paul D. Smith <psmith@gnu.org> Integrate GNU gettext support. * configure.in: Add AM_GNU_GETTEXT. * Makefile.am: Add options for setting LOCALEDIR, -Iintl, etc. * acinclude.m4: Add gettext autoconf macros. * acconfig.h: Add new gettext #defines. * make.h: Include libintl.h. Make sure _() and N_() macros are declared. Make gettext() an empty macro is NLS is disabled. * main.c (struct command_switch switches[]): Can't initialize static data with _() (gettext calls), so use N_() there then use gettext() directly when printing the strings. * remake.c (no_rule_error): The string constants can't be static when initializing _() macros. * file.c (print_file): Reformat a few strings to work better for translation. * po/POTFILES.in, po/Makefile.in.in: New files. Take Makefile.in.in from the latest GNU tar distribution, as that version works better than the one that comes with gettext. * NEWS: Mention i18n ability. 2000-01-21 Paul D. Smith <psmith@gnu.org> Installed patches for the VMS port. Patches provided by: Hartmut Becker <Hartmut.Becker@compaq.com> * readme.vms, arscan.c, config.h-vms, default.c, dir.c, file.c: * implicit.c, job.c, make.h, makefile.com, makefile.vms, rule.c: * variable.c, vmsdir.h, vmsfunctions.c, vmsify.c, glob/glob.c: * glob/glob.h: Installed patches. See readme.vms for details. 2000-01-14 Andreas Schwab <schwab@suse.de> * dir.c (read_dirstream): Initialize d_type if it exists. 2000-01-11 Paul D. Smith <psmith@gnu.org> Resolve PR/xxxx: don't automatically evaluate the $(call ...) function's arguments. While we're here, clean up argument passing protocol to always use simple nul-terminated strings, instead of sometimes using offset pointers to mark the end of arguments. This change also fixes PR/1517. Reported by Damien GIBOU <damien.gibou@st.com>. * function.c (struct function_table_entry): Remove the negative required_args hack; put in explicit min and max # of arguments. (function_table): Add in the max value. Turn off the expand bit for func_call. (expand_builtin_function): Test against minimum_args instead of the obsolete required_args. (handle_function): Rewrite this. We don't try to be fancy and pass one style of arguments to expanded functions and another style to non-expanded functions: pass pointers to nul-terminated strings to all functions. (func_call): Rewrite this. If we are invoking a builtin function and it's supposed to have its arguments expanded, do that (since it's not done by handle_function for $(call ...) anymore). For non-builtins, just add the variables as before but mark them as recursive so they'll be expanded later, as needed. (func_if): All arguments are vanilla nul-terminated strings: remove trickery with "argv[1]-1". (func_foreach): Ditto. * expand.c (expand_argument): If the second arg is NULL, expand the entire first argument. * job.c (new_job): Zero the child struct. This change was just made to keep some heap checking software happy, not because there was an actual bug (the important memory was being cleared properly). 1999-12-15 Paul D. Smith <psmith@gnu.org> * variable.c (print_variable): Print the variable with += if the append flag is set. * implicit.c (pattern_search): Remove the extra check of the implicit flag added on 8/24/1998. This causes problems and the reason for the change was better resolved by the change made to check_deps() on 1998-08-26. This fixes PR/1423. 1999-12-08 Paul D. Smith <psmith@gnu.org> * dir.c (dir_setup_glob): On 64 bit ReliantUNIX (5.44 and above) in LFS mode, stat() is actually a macro for stat64(). Assignment doesn't work in that case. So, stat is a macro, make a local wrapper function to invoke it. (local_stat): Wrapper function, if needed. Reported by Andrej Borsenkow <Andrej.Borsenkow@mow.siemens.ru>. 1999-12-02 Paul D. Smith <psmith@gnu.org> * remake.c (update_file): Move the considered test outside the double-colon loop, _but_ make sure we test the double_colon target not the "current" target. If we stop early because one double-colon target is running, mark all the rest considered and try to start their prerequisites (so they're marked considered). Fix for PR/1476 suggested by Tim Magill <tim.magill@telops.gte.com>. 1999-11-22 Rob Tulloh <rob_tulloh@dev.tivoli.com> * function.c (windows32_openpipe, func_shell): Correct Windows32 problem where $(shell nosuchfile) would incorrectly exit make. The fix is to print the error and let make continue. Reported by David Masterson <David.Masterson@kla-tencor.com>. * w32/subproc/misc.c (arr2envblk): Memory leak fix. 1999-11-21 Paul D. Smith <psmith@gnu.org> Rework GNU make debugging to provide different levels of output. * NEWS: mention it. * debug.h: New file. Define various debugging levels and macros. * function.c, implicit.c, job.c, main.c, misc.c, read.c, remake.c * remote-cstms.c, vmsfunctions.c: Replace all code depending on debug_flag with invocations of debugging macros. * make.h: Remove debug_flag and DEBUGPR, add db_level. 1999-11-18 Paul Eggert <eggert@twinsun.com> * acinclude.m4 (AC_SYS_LARGEFILE_FLAGS): Work around a problem with the QNX 4.25 shell, which doesn't propagate exit status of failed commands inside shell assignments. 1999-11-17 Paul D. Smith <psmith@gnu.org> * function.c (func_if): Find the end of the arg list by testing the next item for NULL; any other test is not correct. Reported by Graham Reed <grahamr@algorithmics.com> (PR/1429). Fix += when used in a target-specific variable context. * variable.h: New bitfield APPEND set if we have a += target-specific variable. * variable.c (try_variable_definition): Add an argument to specify if we're trying a target-specific variable. If we are and it's an append style, don't append it, record it as normal recursive, but set the APPEND flag so it'll be expanded later. * main.c (handle_non_switch_argument): Use new try_variable_definition() signature. * read.c (read_makefile,record_target_var): Ditto. * expand.c (allocated_variable_append): New function: like allocated_variable_expand(), but we expand the same variable name in the context of the ``next'' variable set, then we append this expanded value. (recursively_expand): Invoke it, if the APPEND bit is set. 1999-11-10 Paul D. Smith <psmith@gnu.org> * file.c (snap_deps): If the .NOTPARALLEL target is defined, turn off parallel builds for this make only (still allow submakes to be run in parallel). * main.c: New variable, ``not_parallel''. * make.h: Add an extern for it. * job.c (new_job): Test NOT_PARALLEL as well as JOB_SLOTS. * NEWS: Add info on .NOTPARALLEL. * make.texinfo (Special Targets): Document it. * configure.in (GLOBDIR): Set to "glob" if we need to build the glob library. * Makefile.am (SUBDIRS): Use the GLOBDIR variable instead of "glob" so we don't try to build glob if we don't need to (if we have GLIBC glob). Reported by Lars Hecking <lhecking@nmrc.ucc.ie>. * main.c (main): Don't put "***" in the clock skew warning message. Reported by karl@gnu.org. * make.h: Remove unneeded signal setup. * signame.c: Remove extraneous #includes; some versions of Ultrix don't protect against multiple inclusions and it causes compile errors. Reported by Simon Burge <simonb@thistledown.com.au>. 1999-10-15 Paul D. Smith <psmith@gnu.org> * main.c (quote_for_env): Rename from quote_as_word(). * make.h, *.c: Prefer strchr() and strrchr() in the code rather than index() and rindex(). Define strchr/strrchr in terms of index/rindex if the former aren't supported. * default.c (CHECKOUT,v): Replace the fancy, complicated patsubst/filter expression with a simple $(if ...) expression. * main.c (print_usage): Add the bug reporting mailing address to the --help output, as per the GNU coding standards. Reported by Paul Eggert <eggert@twinsun.com>. * README.customs: Installed information on running Customs-ized GNU make and setuid root, collected by Ted Stern <stern@tera.com>. * read.c (read_all_makefiles): PR/1394: Mark the end of the next token in the MAKEFILES value string _before_ we dup it. 1999-10-13 Paul D. Smith <psmith@gnu.org> * configure.in (make_cv_sys_gnu_glob): We used to add the -Iglob flag to CPPFLAGS, but that loses if the user specifies his own CPPFLAGS; this one gets added _after_ his and if he happens to have an old or broken glob.h--boom. Instead, put it in GLOBINC and SUBST it. * Makefile.am (INCLUDES): Add @GLOBINC@ to the INCLUDES macro; these things get on the compile line well before the user's CPPFLAGS. 1999-10-12 Paul D. Smith <psmith@gnu.org> * remake.c (notice_finished_file): If we get here and -n is set, see if all the command lines are marked recursive. If so, then we ran every command there is, so check the mtime on this file just like we would normally. If not, we assume the command we didn't run would updates the target and set mtime of the target to "very new". * job.c (start_job_command): Update lines_flags in the file's cmds structure with any per-line tokens we found (`@', `-', `+'). 1999-10-08 Paul D. Smith <psmith@gnu.org> * variable.c (initialize_file_variables): Always recurse to initialize the parent's file variables: the parent might not have any rules to run so it might not have been initialized before this--we need this to set up the chain properly for target-specific variables. 1999-09-29 Paul Eggert <eggert@twinsun.com> * main.c (quote_as_word): Always quote for decode_env_switches instead of for the shell, so that arguments with strange characters are are passed to submakes correctly. Remove double_dollars arg; we always double dollars now. All callers changed. (decode_env_switches): Don't run off the end of an environment variable whose contents ends in a unescaped backslash. 1999-09-23 Paul D. Smith <psmith@gnu.org> * commands.c, function.c, job.c, read.c: Cast arguments to ctype.h functions/macros to _unsigned_ char for portability. * remake.c, function.c: Compiler warning fixes: the second argument to find_next_token() should be an _unsigned_ int*. Reported by Han-Wen Nienhuys <hanwen@cs.uu.nl>. 1999-09-23 Paul D. Smith <psmith@gnu.org> * Version 3.78.1 released. * make.texinfo: Update version/date stamp. * main.c (main): Argh. For some reason we were closing _all_ the jobserver pipes before we re-exec'd due to changed makefiles. This means that any re-exec got a "jobserver unavailable" error :-/. I can't believe we didn't notice this before. 1999-09-22 Paul D. Smith <psmith@gnu.org> * Version 3.78 released. * main.c (main): Only fail on multiple --jobserver-fds options if they aren't all the same. Some makefiles use things like $(MAKE) $(MFLAGS) which will cause multiple, identical copies of --jobserver-fds to show up. 1999-09-16 Paul D. Smith <psmith@gnu.org> * main.c (define_makeflags): Zero out FLAGSTRING to avoid uninitialized memory reads when checking *p != '-' in the loop. 1999-09-15 Paul D. Smith <psmith@gnu.org> * Version 3.77.97 released. * configure.in (MAKE_HOST): AC_SUBST this so it will go into the makefile. * Makefile.am (check-local): Print a success banner if the check succeeds. (check-regression): A bit of fine-tuning. 1999-09-15 Eli Zaretskii <eliz@is.elta.co.il> * README.DOS.template: Document requirements for the test suite. * Makefile.DOS.template: Updates to allow the test suite to run from "make check". * main.c (main): Handle it if argv[0] isn't an absolute path. 1999-09-13 Paul D. Smith <psmith@gnu.org> * Version 3.77.96 released. * Makefile.am (loadavg): Use CPPFLAGS, etc. to make sure we get all the right #defines to compile. (check-regression): Look for the regression test suite in the make package itself. If we're building remotely, use symlinks to make a local copy. (dist-hook): Put the test suite into the tar file. * configure.in: Look for perl for the test suite. 1999-09-10 Paul Eggert <eggert@twinsun.com> * acinclude.m4 (AC_SYS_LARGEFILE_FLAGS): If on HP-UX 10.20 or later, and using GCC, define __STDC_EXT__; this works around a bug in GCC 2.95.1. 1999-09-08 Paul D. Smith <psmith@gnu.org> * main.c (print_version): Ugh. GLIBC's configure tries to check make version strings and is too aggressive with their matching expressions. I've struck a deal with them to leave the version output as-is for 3.78, and they'll change their configure checks so that I can change this back in the future. 1999-09-07 Eli Zaretskii <eliz@is.elta.co.il> * job.c (construct_command_argv_internal) [__MSDOS__]: Add "echo" and "unset" to the list of builtin shell commands. * configh.DOS.template (MAKE_HOST): Define to "i386-pc-msdosdjgpp" which is the canonical name of the DJGPP host. 1999-09-05 Paul D. Smith <psmith@gnu.org> * Version 3.77.95 released. * make.texinfo (Make Errors): Document some new jobserver error messages. 1999-09-04 Eli Zaretskii <eliz@is.elta.co.il> * make.texinfo (Make Errors): Document the hint about 8 spaces instead of a TAB. (Call Function, Quick Reference): Use @code{$(1)}, not @var. * main.c (main) [__MSDOS__]: Say "on this platform" instead of "on MS-DOS", since the MSDOS version could run on Windows. 1999-09-03 Paul D. Smith <psmith@gnu.org> * remake.c (notice_finished_file): Always set mtime_before_update if it's not been set, not just if we ran some rules. Otherwise we may have a situation where a target's prerequisite was rebuilt but not changed, so this target's rules weren't run, then update_goal_chain() sees mtime_before_update != last_mtime and thinks that the top-level target changed when it really didn't. This can cause an infinite loop when remaking makefiles. (update_goal_chain): If we get back to the top and we don't know what the goal's last_mtime was, find it now. We need to know so we can compare it to mtime_before_update later (this is only crucial when remaking makefiles--should we only do it then?) 1999-09-02 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): If "override" appears as the first prerequisite, look further to ensure this is really a target-specific variable definition, and not just some prerequisite named "override". 1999-09-01 Paul D. Smith <psmith@gnu.org> * function.c (IS_PATHSEP) [WINDOWS32]: Allow backslash separators for W32 platforms. * read.c (record_files) [WINDOWS32]: Allow backslash separators for W32 platforms. * implicit.c (pattern_search) [WINDOWS32]: Allow backslash separators for W32 platforms. * configure.in (MAKE_HOST): Define it to be the canonical build host info, now that we need AC_CANONICAL_HOST anyway (for large file support). * version.c (make_host): Define a variable to MAKE_HOST so we're sure to get it from the local config.h. * main.c (print_version): Use it in the version information. * config.ami.template: Add MAKE_HOST. * configh.dos.template: Ditto. * config.h.W32.template: Ditto. * config.h-vms.template: Ditto. * main.c (main): Close the jobserver file descriptors if we need to re-exec ourselves. Also print more reasonable error if users force -jN for submakes. This may be common for a while until people use the jobserver feature. If it happens, we ignore the existing jobserver stuff and use whatever they specified on the commandline. (define_makeflags): Fixed a long-standing bug: if a long name only option comes immediately after a single letter option with no argument, then the option string is constructed incorrectly. For example, with -w and --jobserver-fds you get "-w-jobserver-fds..." instead of "-w --jobserver-fds..."; add in an extra " -". * make.texinfo (Phony Targets): Add another example of using .PHONY with subdirectories/recursive make. 1999-08-30 Paul D. Smith <psmith@gnu.org> * README.W32.template: Renamed from README.W32 so it's autogenerated during the dist. A few minor modifications. * configure.in: Check for kstat_open before AC_FUNC_GETLOADAVG since the latter needs to know whether the former exists to give an accurate result. 1999-08-26 Rob Tulloh <rob_tulloh@dev.tivoli.com> * NMakefile [WINDOWS32]: Now more robust. If you change a file under w32/subproc, the make.exe will be relinked. Also added some tests to make sure erase commands won't fail when executed in a pristine build environment. * w32/subproc/sub_proc.c [WINDOWS32]: Added support for HAVE_CYGWIN_SHELL. If you are using the Cygwin B20.1 release, it is now possible to have have native support for this shell without having to rely on klutzy BATCH_MODE_ONLY_SHELL. * config.h.W32 [WINDOWS32]: Added HAVE_CYGWIN_SHELL macro which users can define if they want to build make to use this shell. * README.W32 [WINDOWS32]: Added informaton about HAVE_CYGWIN_SHELL. Cleaned up text a bit to make it more current. 1999-08-26 Paul Eggert <eggert@twinsun.com> Support large files in AIX, HP-UX, and IRIX. * acinclude.m4 (AC_LFS): Remove. Superseded by AC_SYS_LARGEFILE. (AC_SYS_LARGEFILE_FLAGS, AC_SYS_LARGEFILE_SPACE_APPEND, AC_SYS_LARGEFILE_MACRO_VALUE, AC_SYS_LARGEFILE): New macros. (jm_AC_TYPE_UINTMAX_T): Check for busted compilers that can't shift or divide unsigned long long. (AM_PROG_CC_STDC): New macro; a temporary workaround of a bug in automake 1.4. * configure.in (AC_CANONICAL_HOST): Add; required by new AC_SYS_LARGEFILE. (AC_SYS_LARGEFILE): Renamed from AC_LFS. (AM_PROG_CC_STDC): Add. * config.guess, config.sub: New files, needed for AC_CANONICAL_HOST. 1999-08-25 Paul Eggert <eggert@twinsun.com> * make.h (CHAR_MAX): New macro. * main.c (struct command_switch): c is now int, so that it can store values greater than CHAR_MAX. (switches): Replace small numbers N with CHAR_MAX+N-1, to avoid problems with non-ASCII character sets. (short_option): New macro. (init_switches, print_usage, define_makeflags): Use it instead of isalnum. 1999-08-25 Paul D. Smith <psmith@gnu.org> * Version 3.77.94 released. * main.c (main) [__MSDOS__]: If the user uses -j, warn that it's not supported and reset it. * make.h (ISDIGIT): Obtained this from the textutils distribution. * main.c (decode_switches): Use it. * function.c (is_numeric): Use it. * main.c (struct command_switch): Store the switch char in an unsigned char to shut up GCC about using it with ctype.h macros. Besides, it _is_ always unsigned. 1999-08-24 Paul D. Smith <psmith@gnu.org> * make.texinfo: Change "dependency" to "prerequisite" and "dependencies" to "prerequisites". Various other cleanups related to the terminology change. * file.c: Change debugging and error messages to use "prerequisite" instead of "dependency". * implicit.c: Ditto. * remake.c: Ditto. * NEWS: Document it. 1999-08-23 Paul D. Smith <psmith@gnu.org> * remake.c (update_file): Move the considered check into the double-colon rule loop, so we consider double-colon rules individually (otherwise after the first is pruned, the rest won't get run). * README.template: Minor changes. Remove the debugging features of the jobserver, so it no longer writes distinct tokens to the pipe. Thus, we don't need to store the token we get. A side effect of this is to remove a potential "unavailable token" situation: make-1 invokes make-2 with its special token and make-3 with a normal token; make-2 completes. Now we're waiting for make-3 but using 2 tokens; our special token is idle. In the new version we don't have special tokens per se, we merely decide if we already have a child or not. If we don't, we don't need a token. If we do, we have to get one to run the next child. Similar for putting tokens back: if we're cleaning up the last child, we don't put a token back. Otherwise, we do. * main.c: Add a new, internal flag --jobserver-fds instead of overloading the meaning of -j. Remove job_slots_str and add the stringlist jobserver_fds. (struct command_switch): We don't need the int_string type. (switches[]): Add a new option for --jobserver-fds and remove conditions around -j. Make the description for the former 0 so it doesn't print during "make --help". (main): Rework jobserver parsing. If we got --jobserver-fds make sure it's valid. We only get one and job_slots must be 0. If we're the toplevel make (-jN without --jobserver-fds) create the pipe and write generic tokens. Create the stringlist struct for the submakes. Clean up the stringlist where necessary. (init_switches): Remove int_string handling. (print_usage): Don't print internal flags (description ptr is 0). (decode_switches): Remove int_string handling. (define_makeflags): Remove int_string handling. * job.c: Remove my_job_token flag and all references to the child->job_token field. (free_job_token): Remove this and merge it into free_child(). (reap_children): Rework the "reaped a child" logic slightly. Don't call defunct free_job_token anymore. Always call free_child, even if we're dying. (free_child): If we're not freeing the only child, put a token back in the pipe. Then, if we're dying, don't bother to free. (new_job): If we are using the jobserver, loop checking to see if a) there are no children or b) we get a token from the pipe. * job.h (struct child): Remove the job_token field. 1999-08-20 Paul D. Smith <psmith@gnu.org> * variable.c (try_variable_definition): Allocate for variable expansion in f_append with a simple variable: if we're looking at target-specific variables we don't want to trash the buffer. Noticed by Reiner Beninga <Reiner.Beninga@mchp.siemens.de>. 1999-08-16 Eli Zaretskii <eliz@is.elta.co.il> * main.c (main) [__MSDOS__]: Mirror any backslashes in argv[0], to avoid problems in shell commands that use backslashes as escape characters. 1999-08-16 Paul D. Smith <psmith@gnu.org> * Version 3.77.93 released. 1999-08-13 Paul D. Smith <psmith@gnu.org * function.c (func_if): New function $(if ...) based on the original by Han-Wen but reworked quite a bit. (function_table): Add it. * NEWS: Introduce it. * make.texinfo (If Function): Document it. * job.c (free_job_token): Check for EINTR when writing tokens to the jobserver pipe. 1999-08-12 Paul D. Smith <psmith@gnu.org> Another jobserver algorithm change. We conveniently forgot that the blocking bit is shared by all users of the pipe, it's not a per-process setting. Since we have many make processes all sharing the pipe we can't use the blocking bit as a signal handler flag. Instead, we'll dup the pipe's read FD and have the SIGCHLD handler close the dup'd FD. This will cause the read() to fail with EBADF the next time we invoke it, so we know we need to reap children. We then re-dup and reap. * main.c (main): Define the job_rfd variable to hold the dup'd FD. Actually dup the read side of the pipe. Don't bother setting the blocking bit on the file descriptor. * make.h: Declare the job_rfd variable. * job.c (child_handler): If the dup'd jobserver pipe is open, close it and assign -1 to job_rfd to notify the main program that we got a SIGCHLD. (start_job_command): Close the dup'd FD before exec'ing children. Since we open and close this thing so often it doesn't seem worth it to use the close-on-exec bit. (new_job): Remove code for testing/setting the blocking bit. Instead of EAGAIN, test for EBADF. If the dup'd FD has been closed, re-dup it before we reap children. * function.c (func_shell): Be a little more accurate about the length of the error string to allocate. * expand.c (variable_expand_for_file): If there's no filenm info (say, from a builtin command) then reset reading_file to 0. 1999-08-09 Paul D. Smith <psmith@gnu.org> * maintMakefile: Use g in sed (s///g) to replace >1 variable per line. * Makefile.DOS.template [__MSDOS__]: Fix mostlyclean-aminfo to remove the right files. 1999-08-01 Eli Zaretskii <eliz@is.elta.co.il> * function.c (msdos_openpipe) [__MSDOS__]: *Really* return a FILE ptr. 1999-08-01 Paul D. Smith <psmith@gnu.org> New jobserver algorithm to avoid a possible hole where we could miss SIGCHLDs and get into a deadlock. The original algorithm was suggested by Roland McGrath with a nice refinement by Paul Eggert. Many thanks as well to Tim Magill and Howard Chu, who also provided many viable ideas and critiques. We all had a fun week dreaming up interesting ways to use and abuse UNIX syscalls :). Previously we could miss a SIGCHLD if it happened after we reaped the children but before we re-entered the blocking read. If this happened to all makes and/or all children, make would never wake up. We avoid this by having the SIGCHLD handler reset the blocking bit on the jobserver pipe read FD (normally read does block in this algorithm). Now if the handler is called between the time we reap and the time we read(), and there are no tokens available, the read will merely return with EAGAIN instead of blocking. * main.c (main): Set the blocking bit explicitly here. * job.c (child_handler): If we have a jobserver pipe, set the non-blocking bit for it. (start_waiting_job): Move the token stuff back to new_job; if we do it here then we're not controlling the number of remote jobs started! (new_job): Move the check for job slots to _after_ we've created a child structure. If the read returns without getting a token, set the blocking bit then try to reap_children. * make.h (EINTR_SET): Define to test errno if EINTR is available, or 0 otherwise. Just some code cleanup. * arscan.c (ar_member_touch): Use it. * function.c (func_shell): Use it. * job.c (reap_children): Use it. * remake.c (touch_file): Use it. 1999-07-28 Paul D. Smith <psmith@gnu.org> * make.h: Define _() and N_() macros as passthrough to initiate NLS support. * <all>: Add _()/N_() around translatable strings. 1999-07-27 Paul D. Smith <psmith@gnu.org> * read.c: Make sure make.h comes before other headers. 1999-07-26 Paul D. Smith <psmith@gnu.org> * make.texinfo (Quick Reference): Update with the new features. 1999-07-25 Eli Zaretskii <eliz@is.elta.co.il> * remake.c [__MSDOS__]: Don't include variables.h, it's already included. * function.c (msdos_openpipe) [__MSDOS__]: Return FILE ptr. (func_shell) [__MSDOS__]: Fix the argument list. * Makefile.DOS.template: Update from Makefile.in. * README.DOS.template: Configure command fixed. * configh.dos.template: Update to provide definitions for uintmax_t, fd_set_size_t, and HAVE_SELECT. 1999-07-24 Paul D. Smith <psmith@gnu.org> * Version 3.77.91 released. * configure.in: Changes to the boostrapping code: if build.sh.in doesn't exist configure spits an error and generates an empty build.sh file which causes make to be confused. * maintMakefile: Don't build README early. 1999-07-23 Paul D. Smith <psmith@gnu.org> * job.c (my_job_token): This variable controls whether we've handed our personal token to a subprocess or not. Note we could probably infer this from the value of job_slots_used, but it's clearer to just keep it separately. Job_slots_used isn't really relevant when running the job server. (free_job_token): New function: free a job token. If we don't have one, no-op. If we have the personal token, reclaim it. If we have another token, write it back to the pipe. (reap_children): Call free_job_token. (free_child): Call free_job_token. (start_job_command): Remove duplicate test for '+' in the command. If we don't appear to be running a recursive make, close the jobserver filedescriptors. (start_waiting_job): If our personal token is available, use that instead of going to the server pipe. (*): Add the token value to many debugging statements, and print the child target name in addition to the ptr hex value. Change the default "no token" value from '\0' to '-' so it looks better in the output. * main.c (main): Install the child_handler with sigaction() instead of signal() if we have it. On SysV systems, signal() uses SysV semantics which are a pain. But sigaction() always does what we want. (main): If we got job server FDs from the environment, test them to see if they're open. If not, the parent make closed them because it didn't think we were a submake. Print a warning and suggestion to use "+" on the submake invocation, and hard-set to -j1 for this instance of make. (main): Change the algorithm for assigning slots to be more robust. Previously make checked to see if it thought a subprocess was a submake and if so, didn't give it a token. Since make's don't consume tokens we could spawn many of makes fighting for a small number of tokens. Plus this is unreliable because submakes might not be recognized by the parent (see above) then all the tokens could be used up by unrecognized makes, and no one could run. Now every make consumes a token from its parent. However, the make can also use this token to spawn a child. If the make wants more than one, it goes to the jobserver pipe. Thus there will never be more than N makes running for -jN, and N*2 processes (N makes and their N children). Every make can always run at least one job, and we'll never deadlock. (Note the closing of the pipe for non-submakes also solves this, but this is still a better algorithm.) So! Only put N-1 tokens into the pipe, since the topmost make keeps one for itself. * configure.in: Find sigaction. Disable job server support unless the system provides it, in addition to either waitpid() or wait3(). 1999-07-22 Rob Tulloh <rob_tulloh@dev.tivoli.com> * arscan.c (ar_member_touch) [WINDOWS32]: The ar_date field is a string on Windows, not a timestamp. 1999-07-21 Paul D. Smith <psmith@gnu.org> * Version 3.77.90 released. * Makefile.am (AUTOMAKE_OPTIONS): Require automake 1.4. * function.c: Rearrange so we don't need to predeclare the function_table array; K&R C compilers don't like that. * acinclude.m4 (AC_FUNC_SELECT): Ouch; this requires an ANSI C compiler! Change to work with K&R compilers as well. * configure.in (AC_OUTPUT): Put build.sh back. I don't know how I thought it would work this way :-/. We'll have to think of something else. * Makefile.am: Remove rule to create build.sh. * default.c (default_suffix_rules): Rearrange the default command lines to conform to POSIX rules (put the filename argument $< _after_ the OUTPUT_OPTION, not before it). * various: Changed !strncmp() calls to strneq() macros. * misc.c (sindex): Make slightly more efficient. * dir.c (file_impossible): Change savestring(X,strlen(X)) to xstrdup(). * implicit.c (pattern_search): Ditto. * main.c (enter_command_line_file): Ditto. (main): Ditto. * misc.c (copy_dep_chain): Ditto. * read.c (read_makefile): Ditto. (parse_file_seq): Ditto. (tilde_expand): Ditto. (multi_glob): Ditto. * rule.c (install_pattern_rule): Ditto. * variable.c (define_variable_in_set): Ditto. (define_automatic_variables): Ditto. * vpath.c (construct_vpath_list): Ditto. * misc.c (xrealloc): Some reallocs are non-standard: work around them in xrealloc by calling malloc if PTR is NULL. * main.c (main): Call xrealloc() directly instead of testing for NULL. * function.c (func_sort): Don't try to free NULL; some older, non-standard versions of free() don't like it. * configure.in (--enable-dmalloc): Install some support for using dmalloc () with make. Use --enable-dmalloc with configure to enable it. * function.c (function_table_entry): Whoops! The function.c rewrite breaks backward compatibility: all text to a function is broken into arguments, and extras are ignored. So $(sort a,b,c) returns "a"! Etc. Ouch. Fix it by making a positive value in the REQUIRED_ARGS field mean exactly that many arguments to the function; any "extras" are considered part of the last argument as before. A negative value means at least that many, but may be more: in this case all text is broken on commas. (handle_function): Stop when we've seen REQUIRED_ARGS args, if >0. (expand_builtin_function): Compare number of args to the absolute value of REQUIRED_ARGS. 1999-07-20 Paul D. Smith <psmith@gnu.org> * job.c (start_job_command): Ensure that the state of the target is cs_running. It might not be if we skipped all the lines due to -n (for example). * commands.c (execute_file_commands): If we discover that the command script is empty and succeed early, set cs_running so the modtime of the target is still rechecked. * rule.c (freerule): Free the dependency list for the rule. * implicit.c (pattern_search): When turning an intermediate file into a real target, keep the also_make list. Free the dep->name if we didn't use it during enter_file(). 1999-07-16 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Don't allocate the commands buffer until we're sure we found a makefile and won't return early (mem leak). * job.c (start_job_command): Broken #ifdef test: look for F_SETFD, not FD_SETFD. Close-on-exec isn't getting set on the bad_stdin file descriptor and it's leaking :-/. * getloadavg.c (getloadavg): Ditto. 1999-07-15 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Fix some potential memory stomps parsing `define' directives where no variable name is given. * function.c (func_call): Rename from func_apply. Various code cleanup and tightening. (function_table): Add "call" as a valid builtin function. * make.texinfo (Call Function): Document it. * NEWS: Announce it. 1999-07-09 Eli Zaretskii <eliz@is.elta.co.il> * variable.c (try_variable_definition) [__MSDOS__, WINDOWS32]: Treat "override SHELL=" the same as just "SHELL=". 1999-07-09 Paul D. Smith <psmith@gnu.org> * job.c (start_waiting_job): Don't get a second job token if we already have one; if we're waiting on the load to go down start_waiting_job() might get called twice on the same file. * filedef.h (struct file): Add new field, mtime_before_update. When notice_finished_file runs it assigns the cached last_mtime to this field. * remake.c (update_goal_chain): Notice that a file wasn't updated by asking if it changed (g->changed) and comparing the current cached time (last_mtime) with the previous one, stored in mtime_before_update. The previous check ("did last_mtime changed during the run of update_file?") fails for parallel builds because last_mtime is set during reap_children, before update_file is run. This causes update_goal_chain to always return -1 (nothing rebuilt) when running parallel (-jN). This is OK during "normal" builds since our caller (main) treats these cases identically in that case, but if when rebuilding makefiles the difference is very important, as it controls whether we re-exec or not. * file.c (file_hash_enter): Copy the mtime_before_update field. (snap_deps): Initialize mtime_before_update to -1. * main.c (main): Initialize mtime_before_update on old (-o) and new (-W) files. 1999-07-08 Paul D. Smith <psmith@gnu.org> * main.c (switches): Define a new switch -R (or --no-builtin-variables). This option disables the defining of all the GNU make builtin variables. (main): If -R was given, force -r as well. * default.c (define_default_variables): Test the new flag. * make.h: Declare global flag. * make.texinfo (Options Summary): Document the new option. (Implicit Variables): Ditto. 1999-07-06 Paul D. Smith <psmith@gnu.org> * make.texinfo (Options Summary): Correct examples in --print-data-base option summary (problem reported by David Morse <morse@nichimen.com>). * arscan.c: Add support for archives in Windows (VC++). Frank Libbrecht <frankl@abzx.belgium.hp.com> provided info on how to do this. * NMakefile.template (CFLAGS_any): Remove NO_ARCHIVES from the compile line. * build_w32.bat: Ditto. * remake.c (no_rule_error): Fix -include/sinclude so it doesn't give errors if you try to -include the same file twice. (updating_makefiles): New variable: we need to know this info in no_rule_error() so we know whether to print an error or not. (update_file_1): Unconditionally call no_rule_error(), don't try to play games with the dontcare flag. 1999-06-14 Paul D. Smith <psmith@gnu.org> * make.texinfo (Remaking Makefiles): Add a description of how to prevent implicit rule searches for makefiles. * make.1: Remove statement that make continues processing when -v is given. 1999-06-14 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Cast -1 arguments to variable_expand_string() to long. Alexandre Sauve <Alexandre.SAUVE@ifp.fr> reports that without casts, this breaks on a NEC SUPER-UX SX-4 system (and it's wrong without a cast anyway). Of course, (a) I'd really love to start using function prototypes, and (b) there's a whole slew of issues related to int vs. long and signed vs. unsigned in the length handling of variable buffers, etc. Gross. Needs a complete mucking-out. * expand.c (variable_expand): Ditto. * acinclude.m4 (AC_FUNC_SELECT): Slight enhancement for AIX 3.2 by Lars Hecking <lhecking@nmrc.ucc.ie>. * read.c (get_next_mword): Allow colons to be escaped in target names: fix for regression failure. 1999-04-26 Paul D. Smith <psmith@gnu.org> * main.c (main): Reset read_makefiles to empty after processing so we get the right error message. 1999-04-25 Paul D. Smith <psmith@gnu.org> * make.texinfo: Updates to @dircategory and @direntry suggested by Karl Berry <karl@cs.umb.edu>. 1999-04-23 Eli Zaretskii <eliz@is.elta.co.il> * job.c (start_job_command) [__MSDOS__]: Call unblock_sigs before turning off dos_command_running, so child's signals produce the right effect. * commands.c (fatal_error_signal) [__MSDOS__]: Use EXIT_FAILURE instead of 1. 1999-04-18 Eli Zaretskii <eliz@is.elta.co.il> * configh.dos.template: Update to recognize that version 2.02 of DJGPP contains sys_siglist stuff. 1999-04-14 Paul D. Smith <psmith@gnu.org> * make.texinfo (Options/Recursion): Document the job server. (Parallel): Tweaks. 1999-04-13 Paul D. Smith <psmith@gnu.org> Implement a new "job server" feature; the implementation was suggested by Howard Chu <hyc@highlandsun.com>. * configure.in (job-server): New disable option for job server support--it's enabled by default. If it works well this will go away. * NEWS: Summarize the new feature. * acconfig.h: New definition MAKE_JOBSERVER if job server support is enabled. * config.h-vms.template: Undef MAKE_JOBSERVER for this port. * config.h.W32.template: Ditto. * config.ami.template: Ditto. * main.c (struct command_switch): Add a new type: int_string. (switches[]) Use int_string for -j if MAKE_JOBSERVER. (init_switches): Initialize the new int_string switch type. (print_usage): New function, extracted from decode_switches(). (decode_switches): Call it. Decode the new int_string switch type. (define_makeflags): Add new int_string switch data to MAKEFLAGS. (job_fds[]) Array to contain the pipe file descriptors. (main): Parse the job_slots_str option results. If necessary, create the pipe and seed it with tokens. Set the non-blocking bit for the read fd. Enable the signal handler for SIGCHLD even if we have a non-hanging wait; it's needed to interrupt the select() in job.c:start_waiting_job(). * make.h: Declare job_fds[]. * job.h (struct child): Add job_token field to store the token for this job (if any). * job.c (reap_children): When a child is fully reaped, release the token back into the pipe. (free_child): If the child to be freed still has a token, put it back. (new_job): Initialize the job_token member. (start_waiting_job): For local jobs, if we're using the pipe, get a token before we check the load, etc. We do this by performing a non-blocking read in a loop. If the read fails, no token is available. Do a select on the fd to wait for a token. We need to re-enable the signal handler for SIGCHLD even if we have a non-hanging waitpid() or wait3(), so that the signal will interrupt the select() and we can wake up to reap children. (child_handler): Re-enable the signal handler. The count is still kept although it's not needed or used unless you don't have waitpid() or wait3(). 1999-04-10 Paul D. Smith <psmith@gnu.org> * main.c (main): Reset the considered bit on all the makefiles if something failed to update; we need to examine them again if they appear as normal targets in order to get the proper error message. 1999-04-09 Paul D. Smith <psmith@gnu.org> Performance enhancement from Tim Magill <tim.magill@telops.gte.com>. * remake.c (update_file): If you have large numbers of dependencies and you run in parallel, make can spend considerable time each pass through the graph looking at branches it has already seen. Since we only reap_children() when starting a pass, not in the middle, if a branch has been seen already in that pass nothing interesting can happen until the next pass. So, we toggle a bit saying whether we've seen this target in this pass or not. (update_goal_chain): Initially set the global considered toggle to 1, since all targets initialize their boolean to 0. At the end of each pass, toggle the global considered variable. * filedef.h (struct file): Per-file considered toggle bit. * file.c: New global toggle variable considered. 1999-04-05 Paul D. Smith <psmith@gnu.org> * arscan.c (ar_scan): Added support for ARFZMAG (compressed archives?) for Digital UNIX C++. Information provided by Patrick E. Krogel <pekrogel@mtu.edu>. (ar_member_touch): Ditto. 1999-04-03 Paul D. Smith <psmith@gnu.org> * remake.c (f_mtime): If: a) we found a file and b) we didn't create it and c) it's not marked as an implicit target and d) it is marked as an intermediate target, then it was so marked due to an .INTERMEDIATE special target, but it already existed in the directory. In this case, unset the intermediate flag so we won't delete it when make is done. It feels like it would be cleaner to put this check in update_file_1() but I worry it'll get missed... 1999-04-01 Paul D. Smith <psmith@gnu.org> * job.c (construct_command_argv_internal): Use bcopy() to copy overlapping strings, rather than strcpy(). ISO C says the latter is undefined. Found this in a bug report from 1996! Ouch! 1999-03-31 Paul D. Smith <psmith@gnu.org> * read.c (readline): Ignore carriage returns at the end of the line, to allow Windows-y CRLF line terminators. 1999-03-30 Paul D. Smith <psmith@gnu.org> * configure.in: Don't put build.sh here, since build.sh.in doesn't exist initially. This cause autoreconf and automake to fail when run on a clean CVS checkout. Instead, we create build.sh in the Makefile (see below). * Makefile.am: Remove BUILT_SOURCES; this is no longer relevant. Put those files directly into EXTRA_DIST so they're distributed. Create a local build rule to create build.sh. Create a local maintainer-clean rule to delete all the funky maintainers files. * maintMakefile: Makefile.in depends on README, since automake fails if it doesn't exist. Also don't remove glob/Makefile.in here, as it causes problems. 1999-03-26 Paul D. Smith <psmith@gnu.org> * configure.in: Substitute GLOBLIB if we need the link the glob/libglob.a library. * Makefile.am (make_LDADD): Use the subst variable GLOBLIB so we don't link the local libglob.a at all if we don't need it. * build.template: Don't compile glob/*.o unless we want globlib. * maintMakefile (build.sh.in): Substitute the glob/*.o files separately. 1999-03-25 Paul D. Smith <psmith@gnu.org> * make.texinfo: Various typos and additions, pointed out by James G. Sack <jsack@dornfeld.com>. 1999-03-22 Paul D. Smith <psmith@gnu.org> * make.texinfo (Functions): Add a new section documenting the new $(error ...) and $(warning ...) functions. Also updated copyright dates. * NEWS: Updated for the new functions. * function.c (func_error): Implement the new $(error ...) and $(warning ...) functions. (function_table): Insert new functions into the table. (func_firstword): Don't call find_next_token() with argv[0] itself, since that function modifies the pointer. * function.c: Cleanups and slight changes to the new method of calling functions. 1999-03-20 Han-Wen Nienhuys <hanwen@cs.uu.nl> * function.c: Rewrite to use one C function per make function, instead of a huge switch statement. Also allows some cleanup of multi-architecture issues, and a cleaner API which makes things like func_apply() simple. * function.c (func_apply): Initial implementation. Expand either a builtin function or a make variable in the context of some arguments, provided as $1, $2, ... $N. 1999-03-19 Eli Zaretskii <eliz@is.elta.co.il> 1999-03-19 Rob Tulloh <rob_tulloh@dev.tivoli.com> * job.c (construct_command_argv_internal): Don't treat _all_ backslashes as escapes, only those which really escape a special character. This allows most normal "\" directory separators to be treated normally. 1999-03-05 Paul D. Smith <psmith@gnu.org> * configure.in: Check for a system strdup(). * misc.c (xstrdup): Created. Suggestion by Han-Wen Nienhuys <hanwen@cs.uu.nl>. * make.h: Prototype xstrdup(). * remake.c (library_search): Use it. * main.c (main): Use it. (find_and_set_default_shell): Use it. * job.c (construct_command_argv_internal): Use it. * dir.c (find_directory): Use it. * Makefile.am, configure.in: Use AC_SUBST_FILE to insert the maintMakefile instead of "include", to avoid automake 1.4 incompatibility. 1999-03-04 Paul D. Smith <psmith@gnu.org> * amiga.c, amiga.h, ar.c, arscan.c, commands.c, commands.h, * default.c, dep.h, dir.c, expand.c, file.c, filedef.h, function.c, * implicit.c, job.c, job.h, main.c, make.h, misc.c, read.c, remake.c * remote-cstms.c, remote-stub.c, rule.h, variable.c, variable.h, * vpath.c, Makefile.ami, NMakefile.template, build.template, * makefile.vms: Updated FSF address in the copyright notice. * variable.c (try_variable_definition): If we see a conditional variable and we decide to set it, re-type it as recursive so it will be expanded properly later. 1999-02-22 Paul D. Smith <psmith@gnu.org> * NEWS: Mention new .LIBPATTERNS feature. * make.texinfo (Libraries/Search): Describe the use and ramifications of the new .LIBPATTERNS variable. * remake.c (library_search): Instead of searching only for the hardcoded expansion "libX.a" for a library reference "-lX", we obtain a list of patterns from the .LIBPATTERNS variable and search those in order. * default.c: Added a new default variable .LIBPATTERNS. The default for UNIX is "lib%.so lib%.a". Amiga and DOS values are also provided. * read.c: Remove bogus HAVE_GLOB_H references; always include vanilla glob.h. 1999-02-21 Paul D. Smith <psmith@gnu.org> * function.c (expand_function): Set value to 0 to avoid freeing it. * variable.c (pop_variable_scope): Free the value of the variable. (try_variable_definition): For simple variables, use allocated_variable_expand() to avoid stomping on the variable buffer when we still need it for other things. * arscan.c: Modified to support AIX 4.3 big archives. The changes are based on information provided by Phil Adams <padams@austin.ibm.com>. 1999-02-19 Paul D. Smith <psmith@gnu.org> * configure.in: Check to see if the GNU glob library is already installed on the system. If so, _don't_ add -I./glob to the compile line. Using the system glob code with the local headers is very bad mojo! Rewrite SCCS macros to use more autoconf facilities. * Makefile.am: Move -Iglob out of INCLUDES; it'll get added to CPPFLAGS by configure now. Automake 1.4 introduced its own "include" feature which conflicts with the maintMakefile stuff. A hack that seems to work is add a space before the include :-/. * build.template: Move -Iglob out of the compile line; it'll get added to CPPFLAGS by configure now. 1999-02-16 Glenn D. Wolf <Glenn_Wolf@email.sps.mot.com> * arscan.c (ar_scan) [VMS]: Initialized VMS_member_date before calling lbr$get_index since if the archive is empty, VMS_get_member_info won't get called at all, and any leftover date will be used. This bug shows up if any member of any archive is made, followed by a dependency check on a different, empty archive. 1998-12-13 Martin Zinser <zinser@decus.decus.de> * config.h-vms [VMS]: Set _POSIX_C_SOURCE. Redefine the getopt functions so we don't use the broken VMS versions. * makefile.com [VMS]: Allow debugging. * dir.c (dir_setup_glob) [VMS]: Don't extern stat() on VMS. 1998-11-30 Paul D. Smith <psmith@gnu.org> * signame.c (init_sig): Check the sizes of signals being set up to avoid array overwrites (if the system headers have problems). 1998-11-17 Paul D. Smith <psmith@gnu.org> * read.c (record_files): Clean up some indentation. 1998-11-08 Han-Wen Nienhuys <hanwen@cs.uu.nl> * rule.c (print_rule_data_base): Fix arguments to fatal() call. 1998-10-13 Paul D. Smith <psmith@gnu.org> * job.c (start_job_command): If the command list resolves to no chars at all (e.g.: "foo:;$(empty)") then command_ptr is NULL; quit early. 1998-10-12 Andreas Schwab <schwab@issan.cs.uni-dortmund.de> * rule.c (print_rule_data_base): Ignore num_pattern_rules if it is zero. 1998-10-09 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Allow non-empty lines to expand to the empty string after variable, etc., expansion, and be ignored. 1998-09-21 Paul D. Smith <psmith@gnu.org> * job.c (construct_command_argv_internal): Only add COMMAND.COM "@echo off" line for non-UNIXy shells. 1998-09-09 Paul D. Smith <psmith@gnu.org> * w32/subproc/sub_proc.c: Add in missing HAVE_MKS_SHELL tests. 1998-09-04 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): If we hit the "missing separator" error, check for the common case of 8 spaces instead of a TAB and give an extra comment to help people out. 1998-08-29 Paul Eggert <eggert@twinsun.com> * configure.in (AC_STRUCT_ST_MTIM_NSEC): Renamed from AC_STRUCT_ST_MTIM. * acinclude.m4 (AC_STRUCT_ST_MTIM_NSEC): Likewise. Port to UnixWare 2.1.2 and pedantic Solaris 2.6. * acconfig.h (ST_MTIM_NSEC): Renamed from HAVE_ST_MTIM, with a new meaning. * filedef.h (FILE_TIMESTAMP_FROM_S_AND_NS): Use new ST_MTIM_NSEC macro. 1998-08-26 Paul D. Smith <psmith@gnu.org> * remake.c (check_dep): For any intermediate file, not just secondary ones, try implicit and default rules if no explicit rules are given. I'm not sure why this was restricted to secondary rules in the first place. 1998-08-24 Paul D. Smith <psmith@gnu.org> * make.texinfo (Special Targets): Update documentation for .INTERMEDIATE: if used with no dependencies, then it does nothing; old docs said it marked all targets as intermediate, which it didn't... and which would be silly :). * implicit.c (pattern_search): If we find a dependency in our internal tables, make sure it's not marked intermediate before accepting it as a found_file[]. 1998-08-20 Paul D. Smith <psmith@gnu.org> * ar.c (ar_glob): Use existing alpha_compare() with qsort. (ar_glob_alphacompare): Remove it. Modify Paul Eggert's patch so we don't abandon older systems: * configure.in: Warn the user if neither waitpid() nor wait3() is available. * job.c (WAIT_NOHANG): Don't syntax error on ancient hosts. (child_handler, dead_children): Define these if WAIT_NOHANG is not available. (reap_children): Only track the dead_children count if no WAIT_NOHANG. Otherwise, it's a boolean. * main.c (main): Add back signal handler if no WAIT_NOHANG is available; only use default signal handler if it is. 1998-08-20 Paul Eggert <eggert@twinsun.com> Install a more robust signal handling mechanism for systems which support it. * job.c (WAIT_NOHANG): Define to a syntax error if our host is truly ancient; this should never happen. (child_handler, dead_children): Remove. (reap_children): Don't try to keep separate track of how many dead children we have, as this is too bug-prone. Just ask the OS instead. (vmsHandleChildTerm): Fix typo in error message; don't mention child_handler. * main.c (main): Make sure we're not ignoring SIGCHLD/SIGCLD; do this early, before we could possibly create a subprocess. Just use the default behavior; don't have our own handler. 1998-08-18 Eli Zaretskii <eliz@is.elta.co.il> * read.c (read_makefile) [__MSDOS__, WINDOWS32]: Add code to recognize library archive members when dealing with drive spec mess. Discovery and initial fix by George Racz <gracz@mincom.com>. 1998-08-18 Paul D. Smith <psmith@gnu.org> * configure.in: Check for stdlib.h explicitly (some hosts have it but don't have STDC_HEADERS). * make.h: Use HAVE_STDLIB_H. Clean up some #defines. * config.ami: Re-compute based on new config.h.in contents. * config.h-vms: Ditto. * config.h.W32: Ditto. * configh.dos: Ditto. * dir.c (find_directory) [WINDOWS32]: Windows stat() fails if directory names end with `\' so strip it. 1998-08-17 Paul D. Smith <psmith@gnu.org> * make.texinfo: Added copyright year to the printed copy. Removed the price from the manual. Change the top-level reference to running make to be "Invoking make" instead of "make Invocation", to comply with GNU doc standards. * make.h (__format__, __printf__): Added support for these in __attribute__ macro. (message, error, fatal): Use ... prototype form under __STDC__. Add __format__ attributes for printf-style functions. * configure.in (AC_FUNC_VPRINTF): Check for vprintf()/_doprnt(). * misc.c (message, error, fatal): Add preprocessor stuff to enable creation of variable-argument functions with appropriate prototypes, that works with ANSI, pre-ANSI, varargs.h, stdarg.h, v*printf(), _doprnt(), or none of the above. Culled from GNU fileutils and slightly modified. (makefile_error, makefile_error): Removed (merged into error() and fatal(), respectively). * amiga.c: Use them. * ar.c: Use them. * arscan.c: Use them. * commands.c: Use them. * expand.c: Use them. * file.c: Use them. * function.c: Use them. * job.c: Use them. * main.c: Use them. * misc.c: Use them. * read.c: Use them. * remake.c: Use them. * remote-cstms.c: Use them. * rule.c: Use them. * variable.c: Use them. * make.h (struct floc): New structure to store file location information. * commands.h (struct commands): Use it. * variable.c (try_variable_definition): Use it. * commands.c: Use it. * default.c: Use it. * file.c: Use it. * function.c: Use it. * misc.c: Use it. * read.c: Use it. * rule.c: Use it. 1998-08-16 Paul Eggert <eggert@twinsun.com> * filedef.h (FILE_TIMESTAMP_PRINT_LEN_BOUND): Add 10, for nanoseconds. 1998-08-16 Paul Eggert <eggert@twinsun.com> * filedef.h (FLOOR_LOG2_SECONDS_PER_YEAR): New macro. (FILE_TIMESTAMP_PRINT_LEN_BOUND): Tighten bound, and try to make it easier to understand. 1998-08-14 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): We've already unquoted any colon chars by the time we're done reading the targets, so arrange for parse_file_seq() on the target list to not do so again. 1998-08-05 Paul D. Smith <psmith@gnu.org> * configure.in: Added glob/configure.in data. We'll have the glob code include the regular make config.h, rather than creating its own. * getloadavg.c (main): Change return type to int. 1998-08-01 Paul Eggert <eggert@twinsun.com> * job.c (reap_children): Ignore unknown children. 1998-07-31 Paul D. Smith <psmith@gnu.org> * make.h, filedef.h, dep.h, rule.h, commands.h, remake.c: Add prototypes for functions. Some prototypes needed to be moved in order to get #include order reasonable. 1998-07-30 Paul D. Smith <psmith@gnu.org> * make.h: Added MIN/MAX. * filedef.h: Use them; remove FILE_TIMESTAMP_MIN. 1998-07-30 Paul Eggert <eggert@twinsun.com> Add support for sub-second timestamp resolution on hosts that support it (just Solaris 2.6, so far). * acconfig.h (HAVE_ST_MTIM, uintmax_t): New undefs. * acinclude.m4 (jm_AC_HEADER_INTTYPES_H, AC_STRUCT_ST_MTIM, jm_AC_TYPE_UINTMAX_T): New defuns. * commands.c (delete_target): Convert file timestamp to seconds before comparing to archive timestamp. Extract mod time from struct stat using FILE_TIMESTAMP_STAT_MODTIME. * configure.in (C_STRUCT_ST_MTIM, jm_AC_TYPE_UINTMAX_T): Add. (AC_CHECK_LIB, AC_CHECK_FUNCS): Add clock_gettime. * file.c (snap_deps): Use FILE_TIMESTAMP, not time_t. (file_timestamp_now, file_timestamp_sprintf): New functions. (print_file): Print file timestamps as FILE_TIMESTAMP, not time_t. * filedef.h: Include <inttypes.h> if available and if HAVE_ST_MTIM. (FILE_TIMESTAMP, FILE_TIMESTAMP_STAT_MODTIME, FILE_TIMESTAMP_MIN, FILE_TIMESTAMPS_PER_S, FILE_TIMESTAMP_FROM_S_AND_NS, FILE_TIMESTAMP_DIV, FILE_TIMESTAMP_MOD, FILE_TIMESTAMP_S, FILE_TIMESTAMP_NS, FILE_TIMESTAMP_PRINT_LEN_BOUND): New macros. (file_timestamp_now, file_timestamp_sprintf): New decls. (struct file.last_mtime, f_mtime, file_mtime_1, NEW_MTIME): time_t -> FILE_TIMESTAMP. * implicit.c (pattern_search): Likewise. * vpath.c (vpath_search, selective_vpath_search): Likewise. * main.c (main): Likewise. * remake.c (check_dep, name_mtime, library_search, f_mtime): Likewise. (f_mtime): Use file_timestamp_now instead of `time'. Print file timestamp with file_timestamp_sprintf. * vpath.c (selective_vpath_search): Extract file time stamp from struct stat with FILE_TIMESTAMP_STAT_MODTIME. 1998-07-28 Paul D. Smith <psmith@gnu.org> * Version 3.77 released. * dosbuild.bat: Change to DOS CRLF line terminators. * make-stds.texi: Update from latest version. * make.texinfo (Options Summary): Clarify that the -r option affects only rules, not builtin variables. 1998-07-27 Paul D. Smith <psmith@gnu.org> * make.h: Make __attribute__ resolve to empty for non-GCC _and_ for GCC pre-2.5.x. * misc.c (log_access): Print UID/GID's as unsigned long int for maximum portability. * job.c (reap_children): Print PIDs as long int for maximum portability. 1998-07-24 Eli Zaretskii <eliz@is.elta.co.il> * Makefile.DOS (*_INSTALL, *_UNINSTALL): Replace `true' with `:'. 1998-07-25 Paul D. Smith <psmith@gnu.org> * Version 3.76.94 released. 1998-07-23 Paul D. Smith <psmith@gnu.org> * config.h.W32.template: Make sure all the #defines of macros here have a value (e.g., use ``#define HAVE_STRING_H 1'' instead of just ``#define HAVE_STRING_H''. Keeps the preprocessor happy in some contexts. * make.h: Remove __attribute__((format...)) stuff; using it with un-prototyped functions causes older GCC's to fail. * Version 3.76.93 released. 1998-07-22 Paul D. Smith <psmith@gnu.org> * file.c (print_file_data_base): Fix average calculation. 1998-07-20 Paul D. Smith <psmith@gnu.org> * main.c (die): Postpone the chdir() until after remove_intermediates() so that intermediate targets with relative pathnames are removed properly. 1998-07-17 Paul D. Smith <psmith@gnu.org> * filedef.h (struct file): New flag: did we print an error or not? * remake.c (no_rule_error): New function to print error messages, extraced from remake_file(). * remake.c (remake_file): Invoke the new error print function. (update_file_1): Invoke the error print function if we see that we already tried this target and it failed, but that an error wasn't printed for it. This can happen if a file is included with -include or sinclude and couldn't be built, then later is also the dependency of another target. Without this change, make just silently stops :-/. 1998-07-16 Paul D. Smith <psmith@gnu.org> * make.texinfo: Removed "beta" version designator. Updated ISBN for the next printing. 1998-07-13 Paul Eggert <eggert@twinsun.com> * acinclude.m4: New AC_LFS macro to determine if special compiler flags are needed to allow access to large files (e.g., Solaris 2.6). * configure.in: Invoke it. 1998-07-08 Eli Zaretskii <eliz@is.elta.co.il> * Makefile.DOS: track changes in Makefile.in. 1998-07-07 Paul D. Smith <psmith@gnu.org> * remote-cstms.c (start_remote_job): Move gethostbyaddr() to the top so host is initialized early enough. * acinclude.m4: New file. Need some special autoconf macros to check for network libraries (-lsocket, -lnsl, etc.) when configuring Customs. * configure.in (make_try_customs): Invoke new network libs macro. 1998-07-06 Paul D. Smith <psmith@gnu.org> * Version 3.76.92 released. * README.customs: Added to the distribution. * configure.in (make_try_customs): Rewrite to require an installed Customs library, rather than looking at the build directory. * Makefile.am (man_MANS): Install make.1. * make.1: Renamed from make.man. * make.texinfo (Bugs): New mailing list address for GNU make bug reports. 1998-07-02 Paul D. Smith <psmith@gnu.org> * Version 3.76.91 released. * default.c: Added default rule for new-style RCS master file storage; ``% :: RCS/%''. Added default rules for DOS-style C++ files with suffix ".cpp". They use the new LINK.cpp and COMPILE.cpp macros, which are set by default to be equal to LINK.cc and COMPILE.cc. 1998-06-19 Eli Zaretskii <eliz@is.elta.co.il> * job.c (start_job_command): Reset execute_by_shell after an empty command was skipped. 1998-06-09 Paul D. Smith <psmith@gnu.org> * main.c (main): Keep track of the temporary filename created when reading a makefile from stdin (-f-) and attempt to remove it as soon as we know we're not going to re-exec. If we are, add it to the exec'd make's cmd line with "-o" so the exec'd make doesn't try to rebuild it. We still have a hole: if make re-execs then the temporary file will never be removed. To fix this we'd need a brand new option that meant "really delete this". * AUTHORS, getopt.c, getopt1.c, getopt.h, main.c (print_version): Updated mailing addresses. 1998-06-08 Paul D. Smith <psmith@gnu.org> * main.c (main): Andreas Luik <luik@isa.de> points out that the check for makefile :: rules with commands but no dependencies causing a loop terminates incorrectly. * maintMakefile: Make a template for README.DOS to update version numbers. 1998-05-30 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de> * remake.c (update_file_1): Don't free the memory for the dependency structure when dropping a circular dependency. 1998-05-30 Eli Zaretskii <eliz@is.elta.co.il> * dir.c (file_exists_p, file_impossible_p, file_impossible) [__MSDOS__, WINDOWS32]: Retain trailing slash in "d:/", and make dirname of "d:foo" be "d:". 1998-05-26 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de> * read.c (read_makefile): Avoid running past EOS when scanning file name after `include'. 1998-05-26 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de> * make.texinfo (Flavors): Correct description of conditional assignment, which is not equivalent to ifndef. (Setting): Likewise. 1998-05-24 Paul D. Smith <psmith@gnu.org> * arscan.c (ar_name_equal): strncmp() might be implemented as a macro, so don't put preprocessor conditions inside the arguments list. 1998-05-23 Eli Zaretskii <eliz@is.elta.co.il> * read.c (read_makefile) [__MSDOS__, WINDOWS32]: Skip colons in drive specs when parsing targets, target-specific variables and static pattern rules. A colon can only be part of drive spec if it is after the first letter in a token. 1998-05-22 Eli Zaretskii <eliz@is.elta.co.il> * remake.c (f_mtime) [__MSDOS__]: Allow up to 3 sec of skew before yelling bloody murder. * dosbuild.bat: Use -DINCLUDEDIR= and -DLIBDIR= where appropriate. * read.c (parse_file_seq): Combine the special file-handling code for WINDOWS32 and __MSDOS__ into a single snippet. (get_next_mword) [__MSDOS__, WINDOWS32]: Allow a word to include a colon as part of a drive spec. * job.c (batch_mode_shell) [__MSDOS__]: Declare. 1998-05-20 Paul D. Smith <psmith@gnu.org> * Version 3.76.90 released. 1998-05-19 Paul D. Smith <psmith@gnu.org> * make.texinfo (Make Errors): Added a new appendix describing common errors make might generate and how to resolve them (or at least more information on what they mean). * maintMakefile (NMAKEFILES): Use the new automake 1.3 feature to create a dependency file to construct Makefile.DOS, SMakefile, and NMakefile. (.dep_segment): Generate the dependency fragment file. 1998-05-14 Paul D. Smith <psmith@gnu.org> * make.man: Minor changes. 1998-05-13 Paul D. Smith <psmith@gnu.org> * function.c (pattern_matches,expand_function): Change variables and types named "word" to something else, to avoid compilation problems on Cray C90 Unicos. * variable.h: Modify the function prototype. 1998-05-11 Rob Tulloh <rob_tulloh@tivoli.com> * job.c (construct_command_argv_internal) [WINDOWS32]: Turn off echo when using a batch file, and make sure the command ends in a newline. 1998-05-03 Paul D. Smith <psmith@gnu.org> * configure.in (make_try_customs): Add some customs flags if the user configures custom support. * job.c, remote-cstms.c: Merge in changes for custom library. * remote-stub.c: Add option to stub start_remote_job_p(). 1998-05-01 Paul D. Smith <psmith@gnu.org> * remake.c (f_mtime): Install VPATH+ handling for archives; use the hname field instead of the name field, and rehash when appropriate. 1998-04-30 Paul D. Smith <psmith@gnu.org> * rule.c (print_rule_data_base): Print out any pattern-specific variable values into the rules database. * variable.c (print_variable_set): Make this variable extern, to be called by print_rule_data_base() for pattern-specific variables. * make.texinfo (Pattern-specific): Document pattern-specific variables. 1998-04-29 Paul D. Smith <psmith@gnu.org> * expand.c (variable_expand_for_file): Make static; its only called internally. Look up this target in the list of pattern-specific variables and insert the variable set into the queue to be searched. * filedef.h (struct file): Add a new field to hold the previously-found pattern-specific variable reference. Add a new flag to remember whether we already searched for this file. * rule.h (struct pattern_var): New structure for storing pattern-specific variable values. Define new function prototypes. * rule.c: New variables pattern_vars and last_pattern_var for storage and handling of pattern-specific variable values. (create_pattern_var): Create a new pattern-specific variable value structure. (lookup_pattern_var): Try to match a target to one of the pattern-specific variable values. 1998-04-22 Paul D. Smith <psmith@gnu.org> * make.texinfo (Target-specific): Document target-specific variables. 1998-04-21 Paul D. Smith <psmith@gnu.org> * variable.c (define_variable_in_set): Made globally visible. (lookup_variable_in_set): New function: like lookup_variable but look only in a specific variable set. (target_environment): Use lookup_variable_in_set() to get the correct export rules for a target-specific variable. (create_new_variable_set): Create a new variable set, and just return it without installing it anywhere. (push_new_variable_scope): Reimplement in terms of create_new_variable_set. * read.c (record_target_var): Like record_files, but instead of files create a target-specific variable value for each of the listed targets. Invoked from read_makefile() when the target line turns out to be a target-specific variable assignment. 1998-04-19 Paul D. Smith <psmith@gnu.org> * read.c (read_makefile): Rewrite the entire target parsing section to implement target-specific variables. In particular, we cannot expand the entire line as soon as it's read in, since we may want to evaluate parts of it with different variable contexts active. Instead, start expanding from the beginning until we find the `:' (or `::'), then determine what kind of line this is and continue appropriately. * read.c (get_next_mword): New function to parse a makefile line by "words", considering an entire variable or function as one word. Return the type read in, along with its starting position and length. (enum make_word_type): The types of words that are recognized by get_next_mword(). * variable.h (struct variable): Add a flag to specify a per-target variable. * expand.c: Make variable_buffer global. We need this during the new parsing of the makefile. (variable_expand_string): New function. Like variable_expand(), but start at a specific point in the buffer, not the beginning. (variable_expand): Rewrite to simply call variable_expand_string(). 1998-04-13 Paul D. Smith <psmith@gnu.org> * remake.c (update_goal_chain): Allow the rebuilding makefiles step to use parallel jobs. Not sure why this was disabled: hopefully we won't find out :-/. 1998-04-11 Paul D. Smith <psmith@gnu.org> * main.c (main): Set the CURDIR makefile variable. * make.texinfo (Recursion): Document it. 1998-03-17 Paul D. Smith <psmith@gnu.org> * misc.c (makefile_fatal): If FILE is nil, invoke plain fatal(). * variable.c (try_variable_definition): Use new feature. 1998-03-10 Paul D. Smith <psmith@gnu.org> * main.c (main): Don't pass included, rebuilt makefiles to re-exec'd makes with -o. Reopens a possible loop, but it caused too many problems. 1998-03-02 Paul D. Smith <psmith@gnu.org> * variable.c (try_variable_definition): Implement ?=. * make.texinfo (Setting): Document it. 1998-02-28 Eli Zaretskii <eliz@is.elta.co.il> * job.c (start_job_command): Reset execute_by_shell after an empty command, like ":", has been seen. Tue Oct 07 15:00:00 1997 Phil Brooks <phillip_brooks@hp.com> * make.h [WINDOWS32]: make case sensitivity configurable * dir.c [WINDOWS32]: make case sensitivity configurable * README.W32: Document case sensitivity * config.ami: Share case warping code with Windows Mon Oct 6 18:48:45 CDT 1997 Rob Tulloh <rob_tulloh@dev.tivoli.com> * w32/subproc/sub_proc.c: Added support for MKS toolkit shell (turn on HAVE_MKS_SHELL). * read.c [WINDOWS32]: Fixed a problem with multiple target rules reported by Gilbert Catipon (gcatipon@tibco.com). If multiple path tokens in a rule did not have drive letters, make would incorrectly concatenate the 2 tokens together. * main.c/variable.c [WINDOWS32]: changed SHELL detection code to follow what MSDOS did. In addition to watching for SHELL variable updates, make's main will attempt to default the value of SHELL before and after makefiles are parsed. * job.c/job.h [WINDOWS32]: The latest changes made to enable use of the GNUWIN32 shell from make could cause make to fail due to a concurrency condition between parent and child processes. Make now creates a batch file per job instead of trying to reuse the same singleton batch file. * job.c/job.h/function.c/config.h.W32 [WINDOWS32]: Renamed macro from HAVE_CYGNUS_GNUWIN32_TOOLS to BATCH_MODE_ONLY_SHELL. Reworked logic to reduce complexity. WINDOWS32 now uses the unixy_shell variable to detect Bourne-shell compatible environments. There is also a batch_mode_shell variable that determines whether not command lines should be executed via script files. A WINDOWS32 system with no sh.exe installed would have unixy_shell set to FALSE and batch_mode_shell set to TRUE. If you have a unixy shell that does not behave well when invoking things via 'sh -c xxx', you may want to turn on BATCH_MODE_ONLY_SHELL and see if things improve. * NMakefile: Added /D DEBUG to debug build flags so that unhandled exceptions could be debugged. Mon Oct 6 00:04:25 1997 Rob Tulloh <rob_tulloh@dev.tivoli.com> * main.c [WINDOWS32]: The function define_variable() does not handle NULL. Test before calling it to set Path. * main.c [WINDOWS32]: Search Path again after makefiles have been parsed to detect sh.exe. * job.c [WINDOWS32]: Added support for Cygnus GNU WIN32 tools. To use, turn on HAVE_CYGNUS_GNUWIN32_TOOLS in config.h.W32. * config.h.W32: Added HAVE_CYGNUS_GNUWIN32_TOOLS macro. Sun Oct 5 22:43:59 1997 John W. Eaton <jwe@bevo.che.wisc.edu> * glob/glob.c (glob_in_dir) [VMS]: Globbing shouldn't be case-sensitive. * job.c (child_execute_job) [VMS]: Use a VMS .com file if the command contains a newline (e.g. from a define/enddef block). * vmsify.c (vmsify): Return relative pathnames wherever possible. * vmsify.c (vmsify): An input string like "../.." returns "[--]". Wed Oct 1 15:45:09 1997 Rob Tulloh <rob_tulloh@tivoli.com> * NMakefile: Changed nmake to $(MAKE). * subproc.bat: Take the make command name from the command line. If no command name was given, default to nmake. * job.c [MSDOS, WINDOWS32]: Fix memory stomp: temporary file names are now always created in heap memory. * w32/subproc/sub_proc.c: New implementation of make_command_line() which is more compatible with different Bourne shell implementations. Deleted the now obsolete fix_command_line() function. * main.c [WINDOWS32]: Any arbitrary spelling of Path can be detected. Make will ensure that the special spelling `Path' is inserted into the environment when the path variable is propagated within itself and to make's children. * main.c [WINDOWS32]: Detection of sh.exe was occurring too soon. The 2nd check for the existence of sh.exe must come after the call to read_all_makefiles(). Fri Sep 26 01:14:18 1997 <zinser@axp602.gsi.de> * makefile.com [VMS]: Fixed definition of sys. * readme.vms: Comments on what's changed lately. Fri Sep 26 01:14:18 1997 John W. Eaton <jwe@bevo.che.wisc.edu> * read.c (read_all_makefiles): Allow make to find files named "MAKEFILE" with no extension on VMS. * file.c (lookup_file): Lowercase filenames on VMS. 1997-09-29 Paul D. Smith <psmith@baynetworks.com> * read.c (read_makefile): Reworked target detection again; the old version had an obscure quirk. Fri Sep 19 09:20:49 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.76.1 released. * Makefile.am: Add loadavg files to clean rules. * configure.in (AC_OUTPUT): Remove stamp-config; no longer needed. * Makefile.ami (distclean): Ditto. * SMakefile (distclean): Ditto. * main.c (main): Arg count should be int, not char! Major braino. Tue Sep 16 10:18:22 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.76 released. Tue Sep 2 10:07:39 1997 Paul D. Smith <psmith@baynetworks.com> * function.c (expand_function): When processing $(shell...) translate a CRLF (\r\n) sequence as well as a newline (\n) to a space. Also remove an ending \r\n sequence. * make.texinfo (Shell Function): Document it. Fri Aug 29 12:59:06 1997 Rob Tulloh <rob_tulloh@tivoli.com> * w32/pathstuff.c (convert_Path_to_windows32): Fix problem where paths which contain single character entries like `.' are not handled correctly. * README.W32: Document path handling issues on Windows systems. Fri Aug 29 02:01:27 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.75.93. Thu Aug 28 19:39:06 1997 Rob Tulloh <rob_tulloh@tivoli.com> * job.c (exec_command) [WINDOWS32]: If exec_command() is invoked from main() to re-exec make, the call to execvp() would incorrectly return control to parent shell before the exec'ed command could run to completion. I believe this is a feature of the way that execvp() is implemented on top of WINDOWS32 APIs. To alleviate the problem, use the supplied process launch function in the sub_proc library and suspend the parent process until the child process has run. When the child exits, exit the parent make with the exit code of the child make. Thu Aug 28 17:04:47 1997 Paul D. Smith <psmith@baynetworks.com> * Makefile.DOS.template (distdir): Fix a line that got wrapped in * Makefile.am (loadavg): Give the necessary cmdline options when linking loadavg. * configure.in: Check for pstat_getdynamic for getloadvg on HP. * job.c (start_job_command) [VMS, _AMIGA]: Don't perform empty command optimization on these systems; it doesn't make sense. Wed Aug 27 17:09:32 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.75.92 Tue Aug 26 11:59:15 1997 Paul D. Smith <psmith@baynetworks.com> * main.c (print_version): Add '97 to copyright years. * read.c (do_define): Check the length of the array before looking at a particular offset. * job.c (construct_command_argv_internal): Examine the last byte of the previous arg, not the byte after that. Sat Aug 23 1997 Eli Zaretskii <eliz@is.elta.co.il> * Makefile.DOS.template: New file (converted to Makefile.DOS in the distribution). * configure.bat: Rewrite to use Makefile.DOS instead of editing Makefile.in. Add support for building from outside of the source directory. Fail if the environment block is too small. * configh.dos: Use <sys/config.h>. * README.DOS: Update instructions. Fri Aug 22 1997 Eli Zaretskii <eliz@is.elta.co.il> * job.c (start_job_command) [__MSDOS__]: Don't test for "/bin/sh" literally, use value of unixy_shell instead. * filedef.h (NEW_MTIME): Use 1 less than maximum possible value if time_t is unsigned. Sat Aug 16 00:56:15 1997 John W. Eaton <jwe@bevo.che.wisc.edu> * vmsify.c (vmsify, case 11): After translating `..' elements, set nstate to N_OPEN if there are still more elements to process. (vmsify, case 2): After translating `foo/bar' up to the slash, set nstate to N_OPEN, not N_DOT. Fri Aug 8 15:18:09 1997 John W. Eaton <jwe@bevo.che.wisc.edu> * dir.c (vmsstat_dir): Leave name unmodified on exit. * make.h (PATH_SEPARATOR_CHAR): Set to comma for VMS. * vpath.c: Fix comments to refer to path separator, not colon. (selective_vpath_search): Avoid Unixy slash handling for VMS. Thu Aug 7 22:24:03 1997 John W. Eaton <jwe@bevo.che.wisc.edu> * ar.c [VMS]: Don't declare ar_member_touch. Delete VMS version of ar_member_date. Enable non-VMS versions of ar_member_date and ar_member_date_1 for VMS too. * arscan.c (VMS_get_member_info): New function. (ar_scan): Provide version for VMS systems. (ar_name_equal): Simply compare name and mem on VMS systems. Don't define ar_member_pos or ar_member_touch on VMS systems. * config.h-vms (pid_t, uid_t): Don't define. * remake.c: Delete declaration of vms_stat. (name_mtime): Don't call vms_stat. (f_mtime) [VMS]: Funky time value manipulation no longer necessary. * file.c (print_file): [VMS] Use ctime, not cvt_time. * make.h [VMS]: Don't define POSIX. * makefile.com (filelist): Include ar and arscan. Also include them in the link commands. Don't define NO_ARCHIVES in cc command. * makefile.vms (ARCHIVES, ARCHIVES_SRC): Uncomment. (defines): Delete NO_ARCHIVES from list. * remake.c (f_mtime): Only check to see if intermediate file is out of date if it also exists (i.e., mtime != (time_t) -1). * vmsdir.h (u_long, u_short): Skip typedefs if using DEC C. Fri Jun 20 23:02:07 1997 Rob Tulloh <rob_tulloh@tivoli.com> * w32/subproc/sub_proc.c: Get W32 sub_proc to handle shebang (#!/bin/sh) in script files correctly. Fixed a couple of memory leaks. Fixed search order in find_file() (w32/subproc/sub_proc.c) so that files with extensions are preferred over files without extensions. Added search for files with .cmd extension too. * w32/subproc/misc.c (arr2envblk): Fixed memory leak. Mon Aug 18 09:41:08 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.75.91 Fri Aug 15 13:50:54 1997 Paul D. Smith <psmith@baynetworks.com> * read.c (do_define): Remember to count the newline after the endef. Thu Aug 14 23:14:37 1997 Paul D. Smith <psmith@baynetworks.com> * many: Rewrote builds to use Automake 1.2. * AUTHORS: New file. * maintMakefile: Contains maintainer-only make snippets. * GNUmakefile: This now only runs the initial auto* tools. * COPYING,texinfo.tex,mkinstalldirs,install-sh: Removed (obtained automatically by automake). * compatMakefile: Removed (not needed anymore). * README,build.sh.in: Removed (built from templates). * config.h.in,Makefile.in: Removed (built by tools). Wed Aug 13 02:22:08 1997 Paul D. Smith <psmith@baynetworks.com> * make.texinfo: Updates for DOS/Windows information (Eli Zaretskii) * README,README.DOS: Ditto. * remake.c (update_file_1,f_mtime): Fix GPATH handling. * vpath.c (gpath_search): Ditto. * file.c (rename_file): New function: rehash, but also rename to the hashname. * filedef.h: Declare it. * variable.c (merge_variable_set_lists): Remove free() of variable set; since various files can share variable sets we don't want to free them here. Tue Aug 12 10:51:54 1997 Paul D. Smith <psmith@baynetworks.com> * configure.in: Require autoconf 2.12 * make.texinfo: Replace all "cd subdir; $(MAKE)" examples with a more stylistically correct "cd subdir && $(MAKE)". * main.c: Global variable `clock_skew_detected' defined. (main): Print final warning if it's set. * make.h: Declare it. * remake.c (f_mtime): Test and set it. * job.c (start_job_command): Add special optimizations for "do-nothing" rules, containing just the shell no-op ":". This is useful for timestamp files and can make a real difference if you have a lot of them (requested by Fergus Henderson <fjh@cs.mu.oz.au>). * configure.in,Makefile.in: Rewrote to use the new autoconf program_transform_name macro. * function.c (function_strip): Strip newlines as well as spaces and TABs. Fri Jun 6 23:41:04 1997 Rob Tulloh <rob_tulloh@tivoli.com> * remake.c (f_mtime): Datestamps on FAT-based files are rounded to even seconds when stored, so if the date check fails on WINDOWS32 systems, see if this "off-by-one" error is the problem. * General: If your TZ environment variable is not set correctly then all your timestamps will be off by hours. So, set it! Mon Apr 7 02:06:22 1997 Paul D. Smith <psmith@baynetworks.com> * Version 3.75.1 * compatMakefile (objs): Define & use the $(GLOB) variable so that it's removed correctly from build.sh.in when it's built. * configure.in: On Solaris we can use the kstat_*() functions to get load averages without needing special permissions. Add a check for -lkstat to see if we have it. * getloadavg.c (getloadavg): Use HAVE_LIBKSTAT instead of SUN5 as the test to enable kstat_open(), etc. processing. Fri Apr 4 20:21:18 1997 Eli Zaretskii <eliz@is.elta.co.il> * <lots>: Fixes to work in the DJGPP DOS environment. Mon Mar 31 02:42:52 1997 Paul D. Smith <psmith@baynetworks.com> * function.c (expand_function): Added new function $(wordlist). * make.texinfo (Filename Functions): Document $(wordlist) function. * vpath.c (build_vpath_lists): Construct the GPATH variable information in the same manner we used to construct VPATH. (gpath_search): New function to search GPATH. * make.h: Declare the new function. * remake.c (update_file_1): Call it, and keep VPATH if it's found. * make.texinfo (Search Algorithm): Document GPATH variable. Sun Mar 30 20:57:16 1997 Paul D. Smith <psmith@baynetworks.com> * main.c (handle_non_switch_argument): Defined the MAKECMDGOALS variable to contain the user options passed in on the cmd line. * make.texinfo (Goals): Document MAKECMDGOALS variable. * remake.c (f_mtime): Print a warning if we detect a clock skew error, rather than failing. * main.c (main): If we rebuild any makefiles and need to re-exec, add "-o<mkfile>" options for each makefile rebuilt to avoid infinite looping. Fri Mar 28 15:26:05 1997 Paul D. Smith <psmith@baynetworks.com> * job.c (construct_command_argv_internal): Track whether the last arg in the cmd string was empty or not (Roland). (construct_command_argv_internal): If the shell line is empty, don't do anything (Roland). * glob/glob.h,glob/glob.c,glob/fnmatch.c,glob/fnmatch.h: Install the latest changes from the GLIBC version of glob (Ulrich Drepper). * getloadavg.c,make-stds.texi: New version (Roland). * (ALL): Changed WIN32 to W32 or WINDOWS32 (RMS). Mon Mar 24 15:33:34 1997 Rob Tulloh <rob_tulloh@tivoli.com> * README.W32: Describe preliminary FAT support. * build_w32.bat: Use a variable for the final exe name. * dir.c (find_directory): W32: Find the filesystem type. (dir_contents_file_exists_p): W32: for FAT filesystems, always rehash since FAT doesn't change directory mtime on change. * main.c (handle_runtime_exceptions): W32: Add an UnhandledExceptionFilter so that when make bombs due to ^C or a bug, it won't cause a GUI requestor to pop up unless debug is turned on. (main): Call it. Mon Mar 24 00:57:34 1997 Paul D. Smith <psmith@baynetworks.com> * configure.in, config.h.in, config.ami, config.h-vms, config.h.w32: Check for memmove() function. * make.h (bcopy): If memmove() available, define bcopy() to use it. Otherwise just use bcopy(). Don't use memcpy(); it's not guaranteed to handle overlapping moves. * read.c (read_makefile): Fix some uninitialized memory reads (reported by Purify). * job.c (construct_command_argv_internal): Use bcopy() not strcpy(); strcpy() isn't guaranteed to handle overlapping moves. * Makefile.in: Change install-info option ``--infodir'' to ``--info-dir'' for use with new texinfo. * function.c (expand_function): $(basename) and $(suffix) should only search for suffixes as far back as the last directory (e.g., only the final filename in the path). Sun Mar 23 00:13:05 1997 Paul D. Smith <psmith@baynetworks.com> * make.texinfo: Add @dircategory/@direntry information. (Top): Remove previous reference to (dir) (from RMS). (Static Usage): Add "all:" rule to example. (Automatic Dependencies): fix .d file creation example. * Install VPATH+ patch: * filedef.h (struct file): Add in hname field to store the hashed filename, and a flag to remember if we're using the vpath filename or not. Renamed a few functions for more clarity. * file.c (lookup_file,enter_file,file_hash_enter): Store filenames in the hash table based on their "hash name". We can change this while keeping the original target in "name". (rehash_file): Renamed from "rename_file" to be more accurate. Changes the hash name, but not the target name. * remake.c (update_file_1): Modify -d output for more detailed VPATH info. If we don't need to rebuild, use the VPATH name. (f_mtime): Don't search for vpath if we're ignoring it. Call renamed function rehash_file. Call name_mtime instead of file_mtime, to avoid infinite recursion since the file wasn't actually renamed. * implicit.c (pattern_search): if we find an implicit file in VPATH, save the original name not the VPATH name. * make.texinfo (Directory Search): Add a section on the new VPATH functionality. Sun Dec 1 18:36:04 1996 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de> * dir.c (file_exists_p, file_impossible, file_impossible_p): If dirname is empty replace it by the name of the root directory. Note that this doesn't work (yet) for W32, Amiga, or VMS. Tue Oct 08 13:57:03 1996 Rob Tulloh <tulloh@tivoli.com> * main.c (main): W32 bug fix for PATH vars. Tue Sep 17 1996 Paul Eggert <eggert@twinsun.com> * filedef.h (NEW_MTIME): Don't assume that time_t is a signed 32-bit quantity. * make.h: (CHAR_BIT, INTEGER_TYPE_SIGNED, INTEGER_TYPE_MAXIMUM, INTEGER_TYPE_MINIMUM): New macros. Tue Aug 27 01:06:34 1996 Roland McGrath <roland@baalperazim.frob.com> * Version 3.75 released. * main.c (print_version): Print out bug-reporting address. Mon Aug 26 19:55:47 1996 Roland McGrath <roland@baalperazim.frob.com> * main.c (print_data_base): Don't declare ctime; headers do it for us already. Sun Jul 28 15:37:09 1996 Rob Tulloh (tulloh@tivoli.com) * w32/pathstuff.c: Turned convert_vpath_to_w32() into a real function. This was done so that VPATH could contain white space separated pathnames. Please note that directory paths (in VPATH/vpath context) containing white space are not supported (just as they are not under Unix). See README.W32 for suggestions. * w32/include/pathstuff.h: Added prototype for the new function convert_vpath_to_w32. Deleted macro for same. * README.W32: Added some notes about why I chose not to try and support pathnames which contain white space and some workaround suggestions. Thu Jul 25 19:53:31 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * GNUmakefile (mkdep-nolib): Use -MM option unconditionally. * Version 3.74.7. * main.c (define_makeflags): Back up P to point at null terminator when killing final space and dash before setting MFLAGS. From Robert Hoehne <robert.hoehne@Mathematik.TU-Chemnitz.DE>: * dir.c [__MSDOS__ && DJGPP > 1]: Include <libc/dosio.h> and defin `__opendir_flags' initialized to 0. (dosify) [__MSDOS__ && DJGPP > 1]: Return name unchanged if _USE_LFN. (find_directory) [__MSDOS__ && DJGPP > 1]: If _USE_LGN, set __opendir_flags to __OPENDIR_PRESERVE_CASE. * vmsfunctions.c (vms_stat): `sys$dassgn (DevChan);' added by kkaempf. * GNUmakefile (w32files): Add NMakefile. * NMakefile (LDFLAGS_debug): Value fixed by tulloh. Sat Jul 20 12:32:10 1996 Klaus Kämpf (kkaempf@progis.de) * remake.c (f_mtime) [VMS]: Add missing `if' conditional for future modtime check. * config.h-vms, makefile.vms, readme.vms, vmsify.c: Update address. Sat Jul 20 05:29:43 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * configure.in: Require autoconf 2.10 or later. Fri Jul 19 16:57:27 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * Version 3.74.6. * GNUmakefile (w32files): New variable. (distfiles): Add it. * w32: Updated by Rob Tulloh. * makefile.vms (LOADLIBES): Fix typo. Sun Jul 14 12:59:27 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * job.c (construct_command_argv_internal): Fix up #else, #endifs. * configh.dos: Define HAVE_DIRENT_H instead of DIRENT. * remake.c (f_mtime): Don't compare MTIME to NOW if MTIME == -1. * Version 3.74.5. * main.c (main): Exit with status 2 when update_goal_chain returns 2. Sat Jun 22 14:56:05 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * configure.in: Don't check for _sys_siglist. * make.h [HAVE__SYS_SIGLIST]: Don't test this; just punt if there is no strsignal or sys_siglist. * read.c (conditional_line): Strip ws in `ifeq (a , b)' so it is the same as `ifeq (a, b)'. * job.c (reap_children): Don't call die if handling_fatal_signal. * file.c (file_hash_enter): Allow renaming :: to : when latter is non-target, or : to :: when former is non-target. * job.c (start_job_command): Call block_sigs. (block_sigs): New function, broken out of start_job_command. (reap_children): Block fatal signals around removing dead child from chain and adjusting job_slots_used. * job.h: Declare block_sigs. * remote-stub.c (remote_setup, remote_cleanup): New (empty) functions. * main.c (main): Call remote_setup. (die): Call remote_cleanup. * job.c (reap_children): Quiescent value of shell_function_pid is zero, not -1. * main.c (print_version): Add 96 to copyright years. Sat Jun 15 20:30:01 1996 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de> * read.c (find_char_unquote): Avoid calling strlen on every call just to throw away the value most of the time. Sun Jun 2 12:24:01 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * main.c (decode_env_switches): Prepend '-' to ARGV[1] if it contains no '=', regardless of ARGC. (define_makeflags): Elide leading '-' from MAKEFLAGS value if first word is short option, regardless of WORDS. Wed May 22 17:24:51 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * makefile.vms: Set LOADLIBES. * makefile.com (link_using_library): Fix typo. Wed May 15 17:37:26 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * dir.c (print_dir_data_base): Use %ld dev and ino and cast them to long. Wed May 15 10:14:14 CDT 1996 Rob Tulloh <tulloh@tivoli.com> * dir.c: W32 does not support inode. For now, fully qualified pathname along with st_mtime will be keys for files. Fixed problem where vpath can be confused when files are added to a directory after the directory has already been read in. The code now attempts to reread the directory if it discovers that the datestamp on the directory has changed since it was cached by make. This problem only seems to occur on W32 right now so it is lumped under port #ifdef WINDOWS32. * function.c: W32: call subproc library (CreateProcess()) instead of fork/exec. * job.c: W32: Added the code to do fork/exec/waitpid style processing on W32 systems via calls to subproc library. * main.c: W32: Several things added here. First, there is code for dealing with PATH and SHELL defaults. Make tries to figure out if the user has %PATH% set in the environment and sets it to %Path% if it is not set already. Make also looks to see if sh.exe is anywhere to be found. Code path through job.c will change based on existence of a working Bourne shell. The checking for default shell is done twice: once before makefiles are read in and again after. Fall back to MSDOS style execution mode if no sh.exe is found. Also added some debug support that allows user to pause make with -D switch and attach a debugger. This is especially useful for debugging recursive calls to make where problems appear only in the sub-make. * make.h: W32: A few macros and header files for W32 support. * misc.c: W32: Added a function end_of_token_w32() to assist in parsing code in read.c. * read.c: W32: Fixes similar to MSDOS which allow colon to appear in filenames. Use of colon in filenames would otherwise confuse make. * remake.c: W32: Added include of io.h to eliminate compiler warnings. Added some code to default LIBDIR if it is not set on W32. * variable.c: W32: Added support for detecting Path/PATH and converting them to semicolon separated lists for make's internal use. New function sync_Path_environment() which is called in job.c and function.c before creating a new process. Caller must set Path in environment since we don't have fork() to do this for us. * vpath.c: W32: Added detection for filenames containing forward or backward slashes. * NMakefile: W32: Visual C compatible makefile for use with nmake. Use this to build GNU make the first time on Windows NT or Windows 95. * README.W32: W32: Contains some helpful notes. * build_w32.bat: W32: If you don't like nmake, use this the first time you build GNU make on Windows NT or Windows 95. * config.h.W32: W32 version of config.h * subproc.bat: W32: A bat file used to build the subproc library from the top-level NMakefile. Needed because WIndows 95 (nmake) doesn't allow you to cd in a make rule. * w32/include/dirent.h * w32/compat/dirent.c: W32: opendir, readdir, closedir, etc. * w32/include/pathstuff.h: W32: used by files needed functions defined in pathstuff.c (prototypes). * w32/include/sub_proc.h: W32: prototypes for subproc.lib functions. * w32/include/w32err.h: W32: prototypes for w32err.c. * w32/pathstuff.c: W32: File and Path/Path conversion functions. * w32/subproc/build.bat: W32: build script for subproc library if you don't wish to use nmake. * w32/subproc/NMakefile: W32: Visual C compatible makefile for use with nmake. Used to build subproc library. * w32/subproc/misc.c: W32: subproc library support code * w32/subproc/proc.h: W32: subproc library support code * w32/subproc/sub_proc.c: W32: subproc library source code * w32/subproc/w32err.c: W32: subproc library support code Mon May 13 14:37:42 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * Version 3.74.4. * GNUmakefile (vmsfiles): Fix typo. * GNUmakefile (amigafiles): Add amiga.h. Sun May 12 19:19:43 1996 Aaron Digulla <digulla@fh-konstanz.de> * dir.c: New function: amigafy() to fold filenames Changes HASH() to HASHI() to fold filenames on Amiga. Stringcompares use strieq() instead of streq() The current directory on Amiga is "" instead of "." * file.c: Likewise. * amiga.c: New function wildcard_expansion(). Allows to use Amiga wildcards with $(wildcard ) * amiga.h: New file. Prototypes for amiga.c * function.c: Use special function wildcard_expansion() for $(wildcard ) to allow Amiga wildcards The current directory on Amiga is "" instead of "." * job.c: No Pipes on Amiga, too (load_too_high) Neither on Amiga ENV variable on Amiga are in a special directory and are not passed as third argument to main(). * job.h: No envp on Amiga * make.h: Added HASHI(). This is the same as HASH() but converts it's second parameter to lowercase on Amiga to fold filenames. * main.c: (main), variable.c Changed handling of ENV-vars. Make stores now the names of the variables only and reads their contents when they are accessed to reflect that these variables are really global (i.e., they CAN change WHILE make runs !) This handling is made in lookup_variable() * Makefile.ami: renamed file.h to filedep.h Updated dependencies * read.c: "find_semicolon" is declared as static but never defined. No difference between Makefile and makefile on Amiga; added SMakefile to *default_makefiles[]. (read_makefile) SAS/C want's two_colon and pattern_percent be set before use. The current directory on Amiga is "" instead of "." Strange #endif moved. * README.Amiga: updated feature list * SMakefile: Updated dependencies * variable.c: Handling of ENV variable happens inside lookup_variable() Sat May 11 17:58:32 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * variable.c (try_variable_definition): Count parens in lhs variable refs to avoid seeing =/:=/+= inside a ref. Thu May 9 13:54:49 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * commands.c (fatal_error_signal) [SIGQUIT]: Make SIGQUIT check conditional. * main.c (main): Use unsigned for fread return. * read.c (parse_file_seq): Use `int' for char arg to avoid widening conflict issues. * dep.h: Fix prototype. * function.c (expand_function) [_AMIGA]: Fix some typos. (patsubst_expand): Make len vars unsigned. * GNUmakefile (globfiles): Add AmigaDOS support files. (distfiles): Add $(amigafiles). (amigafiles): New variable. Thu Nov 7 10:18:16 1995 Aaron Digulla <digulla@fh-konstanz.de> * Added Amiga support in commands.c, dir.c, function.c, job.c, main.c, make.h, read.c, remake.c * commands.c: Amiga has neither SIGHUP nor SIGQUIT * dir.c: Amiga has filenames with Upper- and Lowercase, but "FileName" is the same as "filename". Added strieq() which is use to compare filenames. This is like streq() on all other systems. Also there is no such thing as "." under AmigaDOS. * function.c: On Amiga, the environment is not passed as envp, there are no pipes and Amiga can't fork. Use my own function to create a new child. * job.c: default_shell is "" (The system automatically chooses a shell for me). Have to use the same workaround as MSDOS for running batch commands. Added HAVE_SYS_PARAM_H. NOFILE isn't known on Amiga. Cloned code to run children from MSDOS. Own version of sh_chars[] and sh_cmds[]. No dup2() or dup() on Amiga. * main.c: Force stack to 20000 bytes. Read environment from ENV: device. On Amiga, exec_command() does return, so I exit() afterwards. * make.h: Added strieq() to compare filenames. * read.c: Amiga needs special extension to have passwd. Only one include-dir. "Makefile" and "makefile" are the same. Added "SMakefile". Added special code to handle device names (xxx:) and "./" in rules. * remake.c: Only one lib-dir. Amiga link-libs are named "%s.lib" instead of "lib%s.a". * main.c, rule.c, variable.c: Avoid floats at all costs. * vpath.c: Get rid of as many alloca()s as possible. Thu May 9 13:20:43 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu> * read.c (read_makefile): Grok `sinclude' as alias for `-include'. Wed Mar 20 09:52:27 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu> * GNUmakefile (vmsfiles): New variable. (distfiles): Include $(vmsfiles). Tue Mar 19 20:21:34 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu> Merged VMS port from Klaus Kaempf <kkaempf@didymus.rmi.de>. * make.h (PARAMS): New macro. * config.h-vms: New file. * makefile.com: New file. * makefile.vms: New file. * readme.vms: New file. * vmsdir.h: New file. * vmsfunctions.c: New file. * vmsify.c: New file. * file.h: Renamed to filedef.h to avoid conflict with VMS system hdr. * ar.c: Added prototypes and changes for VMS. * commands.c: Likewise. * commands.h: Likewise. * default.c: Likewise. * dep.h: Likewise. * dir.c: Likewise. * expand.c: Likewise. * file.c: Likewise. * function.c: Likewise. * implicit.c: Likewise. * job.c: Likewise. * job.h: Likewise. * main.c: Likewise. * make.h: Likewise. * misc.c: Likewise. * read.c: Likewise. * remake.c: Likewise. * remote-stub.c: Likewise. * rule.c: Likewise. * rule.h: Likewise. * variable.c: Likewise. * variable.h: Likewise. * vpath.c: Likewise. * compatMakefile (srcs): Rename file.h to filedef.h. Sat Aug 19 23:11:00 1995 Richard Stallman <rms@mole.gnu.ai.mit.edu> * remake.c (check_dep): For a secondary file, try implicit and default rules if appropriate. Wed Aug 2 04:29:42 1995 Richard Stallman <rms@mole.gnu.ai.mit.edu> * remake.c (check_dep): If an intermediate file exists, do consider its actual date. Sun Jul 30 00:49:53 1995 Richard Stallman <rms@mole.gnu.ai.mit.edu> * file.h (struct file): New field `secondary'. * file.c (snap_deps): Check for .INTERMEDIATE and .SECONDARY. (remove_intermediates): Don't delete .SECONDARY files. Sat Mar 2 16:26:52 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu> * compatMakefile (srcs): Add getopt.h; prepend $(srcdir)/ to getopt*. Fri Mar 1 12:04:47 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu> * Version 3.74.3. * remake.c (f_mtime): Move future modtime check before FILE is clobbered by :: loop. * dir.c: Use canonical code from autoconf manual for dirent include. [_D_NAMLEN]: Redefine NAMLEN using this. (dir_contents_file_exists_p): Use NAMLEN macro. (read_dirstream) [_DIRENT_HAVE_D_NAMLEN]: Only set d_namlen #if this. * compatMakefile (objs): Add missing backslash. Wed Feb 28 03:56:20 1996 Roland McGrath <roland@charlie-brown.gnu.ai.mit.edu> * default.c (default_terminal_rules): Remove + prefix from RCS cmds. (default_variables): Put + prefix in $(CHECKOUT,v) value instead. * remake.c (f_mtime): Check for future timestamps; give error and mark file as "failed to update". Fri Jan 12 18:09:36 1996 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c: Don't declare unblock_sigs; job.h already does. Sat Jan 6 16:24:44 1996 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * acconfig.h (HAVE_SYSCONF_OPEN_MAX): #undef removed. * job.c (NGROUPS_MAX): Don't try to define this macro. Fri Dec 22 18:44:44 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * compatMakefile (GETOPT, GETOPT_SRC, GLOB): Variables removed. (objs, srcs): Include their values here instead of references. Thu Dec 14 06:21:29 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.74.2. * job.c (reap_children): Call unblock_sigs after start_job_command. Thu Dec 14 07:22:03 1995 Roland McGrath <roland@duality.gnu.ai.mit.edu> * dir.c (dir_setup_glob): Don't use lstat; glob never calls it anyway. Avoid & before function names to silence bogus sunos4 compiler. * configure.in: Remove check for `sysconf (_SC_OPEN_MAX)'. Tue Dec 12 00:48:42 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.74.1. * dir.c (read_dirstream): Fix braino: fill in the buffer when not reallocating it! Mon Dec 11 22:26:15 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * misc.c (collapse_continuations): Fix skipping of trailing \s so it can never dereference before the beginning of the array. * read.c (find_semicolon): Function removed. (read_makefile): Don't use find_semicolon or remove_comments for rule lines. Use find_char_unquote directly and handle quoted comments properly. * default.c: Remove all [M_XENIX] code. * dir.c [HAVE_D_NAMLEN]: Define this for __GNU_LIBRARY__ > 1. (D_NAMLEN): Macro removed. (FAKE_DIR_ENTRY): New macro. (dir_contents_file_exists_p): Test HAVE_D_NAMLEN instead of using D_NAMLEN. (read_dirstream): Return a struct dirent * for new glob interface. (init_dir): Function removed. (dir_setup_glob): New function. * main.c (main): Don't call init_dir. * read.c (multi_glob): Call dir_setup_glob on our glob_t and use GLOB_ALTDIRFUNC flag. * misc.c (safe_stat): Function removed. * read.c, commands.c, remake.c, vpath.c: Use plain stat instead of safe_stat. Sat Nov 25 20:35:18 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c [HAVE_UNION_WAIT]: Include sys/wait.h. * main.c (log_working_directory): Made global. Print entering msg only once. * make.h (log_working_directory): Declare it. * misc.c (message): Take new arg PREFIX. Print "make: " only if nonzero. Call log_working_directory. * remake.c: Pass new arg in `message' calls. * job.c (start_job_command): Pass new arg to `message'; fix inverted test in that call. Tue Nov 21 19:01:12 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c (start_job_command): Use `message' to print the command, and call it with null if the command is silent. * remake.c (touch_file): Use message instead of printf. Tue Oct 10 14:59:30 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (enter_command_line_file): Barf if NAME is "". Sat Sep 9 06:33:20 1995 Roland McGrath <roland@whiz-bang.gnu.ai.mit.edu> * commands.c (delete_target): Ignore unlink failure if it is ENOENT. Thu Aug 17 15:08:57 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * configure.in: Don't check for getdtablesize. * job.c (getdtablesize): Remove decls and macros. Thu Aug 10 19:10:03 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (define_makeflags): Omit command line variable definitions from MFLAGS value. * arscan.c (ar_scan) [AIAMAG]: Check for zero MEMBER_OFFSET, indicating a valid, but empty, archive. Mon Aug 7 15:40:03 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * dir.c (file_impossible_p): Correctly reset FILENAME to name within directory before hash search. * job.c (child_error): Do nothing if IGNORED under -s. * job.c (exec_command): Correctly use ARGV[0] for script name when running shell directly. Tue Aug 1 14:39:14 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c (child_execute_job): Close STDIN_FD and STDOUT_FD after dup'ing from them. Don't try to close all excess descriptors; getdtablesize might return a huge value. Any open descriptors in the parent should have FD_CLOEXEC set. (start_job_command): Set FD_CLOEXEC flag on BAD_STDIN descriptor. Tue Jun 20 03:47:15 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * read.c (read_all_makefiles): Properly append default makefiles to the end of the `read_makefiles' chain. Fri May 19 16:36:32 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.74 released. Wed May 10 17:43:34 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.73.3. Tue May 9 17:15:23 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * compatMakefile ($(infodir)/make.info): Make sure $$dir is set in install-info cmd. Wed May 3 15:56:06 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * file.c (print_file): Grok update_status of 1 for -q. Thu Apr 27 12:39:35 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.73.2. Wed Apr 26 17:15:57 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * file.c (remove_intermediates): Fix inverted test to bail under -n for signal case. Bail under -q or -t. Skip files with update_status==-1. * job.c (job_next_command): Skip empty lines. (new_job): Don't test the return of job_next_command. Just let start_waiting_job handle the case of empty commands. Wed Apr 19 03:25:54 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * function.c [__MSDOS__]: Include <fcntl.h>. From DJ Delorie. * Version 3.73.1. Sat Apr 8 14:53:24 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * remake.c (notice_finished_file): Set FILE->update_status to zero if it's -1. Wed Apr 5 00:20:24 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.73 released. Tue Mar 28 13:25:46 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (main): Fixed braino in assert. * Version 3.72.13. Mon Mar 27 05:29:12 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c: Avoid string in assert expression. Some systems are broken. Fri Mar 24 00:32:32 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (main): Handle 1 and 2 returns from update_goal_chain makefile run properly. * Version 3.72.12. * main.c (handle_non_switch_argument): New function, broken out of decode_switches. (decode_switches): Set optind to 0 to reinitialize getopt, not to 1. When getopt_long returns EOF, break the loop and handle remaining args with a simple second loop. * remake.c (remake_file): Set update_status to 2 instead of 1 for no rule to make. Mention parent (dependent) in error message. (update_file_1): Handle FILE->update_status == 2 in -d printout. * job.c (start_job_command, reap_children): Set update_status to 2 instead of 1 for failed commands. Tue Mar 21 16:23:38 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c (search_path): Function removed (was already #if 0'd out). * configure.in: Remove AC_TYPE_GETGROUPS; nothing needs it any more. Fri Mar 17 15:57:40 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * configure.bat: Write @CPPFLAGS@ translation. Mon Mar 13 00:45:59 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * read.c (parse_file_seq): Rearranged `l(a b)' -> `l(a) l(b)' loop to not skip the elt immediately preceding `l(...'. Fri Mar 10 13:56:49 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.11. * read.c (find_char_unquote): Make second arg a string of stop chars instead of a single stop char. Stop when any char in the string is hit. All callers changed. (find_semicolon): Pass stop chars "#;" to one find_char_unquote call, instead of using two calls. If the match is not a ; but a #, return zero. * misc.c: Changed find_char_unquote callers here too. * Version 3.72.10. * read.c (read_makefile, parse_file_seq): Fix typo __MS_DOS__ -> __MSDOS__. * GNUmakefile (globfiles): Add glob/configure.bat. (distfiles): Add configh.dos, configure.bat. Wed Mar 8 13:10:57 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> Fixes for MS-DOS from DJ Delorie. * read.c (read_makefile, parse_file_seq) [__MS_DOS__]: Don't see : as separator in "C:\...". * configh.dos (STDC_HEADERS): Define only if undefined. (HAVE_SYS_PARAM_H): Don't define this. (HAVE_STRERROR): Define this. * job.c (construct_command_argv_internal) [__MSDOS__]: Fix typos. * Version 3.72.9. * main.c (decode_switches): Reset optind to 1 instead of 0. Tue Mar 7 17:31:06 1995 Roland McGrath <roland@geech.gnu.ai.mit.edu> * main.c (decode_switches): If non-option arg is "-", ignore it. Mon Mar 6 23:57:38 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.8. Wed Feb 22 21:26:36 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.7. Tue Feb 21 22:10:43 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (main): Pass missing arg to tmpnam. * configure.in: Check for strsignal. * job.c (child_error): Use strsignal. * main.c (main): Don't call signame_init #ifdef HAVE_STRSIGNAL. * misc.c (strerror): Fix swapped args in sprintf. Mon Feb 13 11:50:08 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * configure.in (CFLAGS, LDFLAGS): Don't set these variables. Fri Feb 10 18:44:12 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (print_version): Add 95 to copyright years. * Version 3.72.6. * job.c (start_job_command): Remember to call notice_finished_file under -n when not recursing. To do this, consolidate that code under the empty command case and goto there for the -n case. Tue Feb 7 13:36:03 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * make.h [! STDC_HEADERS]: Don't declare qsort. Sun headers declare it int. Mon Feb 6 17:37:01 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * read.c (read_makefile): For bogus line starting with tab, ignore it if blank after removing comments. * main.c: Cast results of `alloca' to `char *'. * expand.c: Likewise. Sun Feb 5 18:35:46 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.5. * configure.in: Check for mktemp. * main.c (main) [! HAVE_MKTEMP]: Use tmpnam instead of mktemp. * configure.in (make_cv_sysconf_open_max): New check for `sysconf (_SC_OPEN_MAX)'. * acconfig.h: Added #undef HAVE_SYSCONF_OPEN_MAX. * job.c [HAVE_SYSCONF_OPEN_MAX] (getdtablesize): Define as macro using sysconf. Fri Jan 27 04:42:09 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * remake.c (update_file_1): When !MUST_MAKE, don't set FILE->update_status to zero before calling notice_finished_file. (notice_finished_file): Touch only when FILE->update_status is zero. (remake_file): Set FILE->update_status to zero after not calling execute_file_command and deciding to touch instead. Thu Jan 26 01:29:32 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * main.c (debug_signal_handler): New function; toggles debug_flag. (main): Handle SIGUSR1 with that. Mon Jan 16 15:46:56 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * compatMakefile (realclean): Remove Info files. Sun Jan 15 08:23:09 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.4. * job.c (start_job_command): Save and restore environ around vfork call. (search_path): Function #if 0'd out. (exec_command): Use execvp instead of search_path. * expand.c (variable_expand): Rewrote computed variable name and substitution reference handling to be simpler. First expand the entire text between the parens if it contains any $s, then examine the result of that for subtitution references and do no further expansion while parsing them. * job.c (construct_command_argv_internal): Handle " quoting too, when no backslash, $ or ` characters appear inside the quotes. * configure.in (union wait check): If WEXITSTATUS and WTERMSIG are defined, just use int. Tue Jan 10 06:27:27 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * default.c (default_variables) [__hpux]: Remove special definition of ARFLAGS. Existence of the `f' flag is not consistent across HPUX versions; and one might be using GNU ar anyway. * compatMakefile (clean): Don't remove Info files. * compatMakefile (check): Remove gratuitous target declaration. Sat Jan 7 11:38:23 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * compatMakefile (ETAGS, CTAGS): Don't use -t. * arscan.c (ar_name_equal) [cray]: Subtract 1 like [__hpux]. * main.c (decode_switches): For --help, print usage to stdout. Mon Dec 5 12:42:18 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.3. * remake.c (update_file_1): Do set_command_state (FILE, cs_not_started) only if old state was deps_running. Mon Nov 28 14:24:03 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * job.c (start_waiting_job): Use set_command_state. * build.template (CPPFLAGS): New variable. (prefix, exec_prefix): Set from @...@. (compilation loop): Pass $CPPFLAGS to compiler. * GNUmakefile (build.sh.in): Make it executable. * GNUmakefile (globfiles): Add configure.in, configure. * Version 3.72.2. * configure.in (AC_OUTPUT): Don't write glob/Makefile. * configure.in (AC_CHECK_SYMBOL): Use AC_DEFINE_UNQUOTED. * configure.in: Don't check for ranlib. Tue Nov 22 22:42:40 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * remake.c (notice_finished_file): Only mark also_make's as updated if really ran cmds. Tue Nov 15 06:32:46 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * configure.in: Put dnls before random whitespace. Sun Nov 13 05:02:25 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * compatMakefile (CPPFLAGS): New variable, set from @CPPFLAGS@. (RANLIB): Variable removed. (prefix, exec_prefix): Set these from @...@. (.c.o): Use $(CPPFLAGS). (glob/libglob.a): Don't pass down variables to sub-make. glob/Makefile should be configured properly by configure. (distclean): Remove config.log and config.cache (autoconf stuff). Mon Nov 7 13:58:06 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * acconfig.h: Add #undef HAVE_UNION_WAIT. * configure.in: Converted to Autoconf v2. * dir.c: Test HAVE_DIRENT_H, HAVE_SYS_DIR_H, HAVE_NDIR_H instead of DIRENT, SYSDIR, NDIR. * build.sh.in (prefix, exec_prefix): Set these from @...@. (CPPFLAGS): New variable, set from @CPPFLAGS@. (compiling loop): Pass $CPPFLAGS before $CFLAGS. * install.sh: File renamed to install-sh. * main.c (define_makeflags): When no flags, set WORDS to zero. Sun Nov 6 18:34:01 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72.1. * main.c (define_makeflags): Terminate properly when FLAGSTRING is empty. Fri Nov 4 16:02:51 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.72. Tue Nov 1 01:18:10 1994 Roland McGrath <roland@churchy.gnu.ai.mit.edu> * Version 3.71.5. * job.c (start_job_command): When ARGV is nil, only set update_state and call notice_finished_file if job_next_command returns zero. * job.c (start_job_command): Call notice_finished_file for empty command line.
https://fuchsia.googlesource.com/third_party/make/+/09202bc880b1cb40bdf5035b7cefebc74d4c552e/ChangeLog.2
CC-MAIN-2020-50
refinedweb
21,817
62.24
Turning data into a table is a task most Word users learn right away. But although tables are easy to implement and format, not all table tasks are obvious. These tips will help you work more efficiently with most any table. 1: Use consistent delimitersPerhaps the simplest way to generate a table is to select text and convert it. Word does a great job of interpreting the data and defaulting to the right settings if you're consistent during data entry. Specifically, insert one delimiting character between each item, and enter a single paragraph return (press Enter) between each row, as shown in Figure A. Figure A There's only one tab character between each item and a single paragraph return separates the rows.To convert a list, select the text. Then, click the Insert tab and click the Table drop-down (in the Tables group). From the resulting list, choose Convert Text To Table. In Word 2003, choose Convert from the Table menu and then select Text To Table. You shouldn't have to adjust the default settings (Figure B) much if you use delimiters consistently. Interpreting the tabs and returns, Word can detect that there are two columns and five rows, as shown in Figure C. Figure B Word uses the delimiting characters to align columnar data. Figure C Plan ahead for easy-to-implement table conversion. 2: Select a table quicklyThe quickest way to select a table is to click its Move handle. Click anywhere in the table to display this handle -- the small square icon at the top-left corner, shown in Figure D. A single click of the Move handle will select the entire table, so you can do the following: - Format it. - Move it. - Delete it. Figure D Click the table's Move handle to select the entire table. 3: Delete it If you select a table and press Delete, you might be surprised to find the table remains. Pressing Delete removes only the data. To delete the entire table, select it and then press Backspace. 4: Format quicklyWord defaults to the Table Grid format (Figure C), which applies almost no formatting. But using Word's Tables Styles gallery, you can quickly format those results. Select the entire table and then click the contextual Design tab and hover over the many styles in the gallery (in the Tables Styles group). Click the gallery's down arrow to see the full gallery, shown in Figure E. When you find a style that meets your needs (or that's close), click it. In Word 2003, choose Table AutoFormat from the Table menu. If the resulting table isn't exactly what you want, continue to tweak it. Figure E Use styles to quickly format tables. 5: Resize columns quickly You can adjust a table's column widths with a few quick clicks: - Double-click a column's right border to fit the largest item in that column, as shown in Figure F. Be sure Word displays the double-arrow pointer; otherwise, you might not get the desired results. - To adjust all of the columns, select the table and then double-click any column's border. Figure G shows the results. This trick adjusted both columns. Figure F Adjust the width of a single column by double-clicking its right border. Figure G Select the entire table before double-clicking a column border to resize all of the columns. 6: Get more preciseIf you need exact measurements, use the ruler. Hover the mouse over a border until the double-arrow pointer appears. Then, click the border and hold down the Alt key. Word will display specific measurements, as shown in Figure H. If you need to resize the column, drag the gray square. Figure H Display or set the widths of a table's columns. 7: Use Quick Tables If you frequently use the same table in many documents, create a Quick Table (not available in Word 2003). First, create and format the table. Then, add the table to the Quick Tables gallery as follows: - Select the table. - Click the Insert tab. - Click the Table drop-down in the Tables group and choose Quick Tables to open the Quick Tables Gallery. - At the bottom of the gallery, select the Save Selection To Quick Tables Gallery option. - Name the new table, as shown in Figure I, and click OK. Usually, the other settings will be adequate. Figure I Create a Quick Table. When you need the table again, just insert it from the Quick Tables gallery: - Click the Insert tab and choose Quick Tables from the Table drop-down (in the Tables group). - Find the table in the gallery, as shown in Figure J, and then click it to add it to the document. Figure J This feature treats the table as a building block, not a style. 8: Move a row quickly If you need to move a row of data, you don't have to delete and reenter anything. You can quickly move a row of data by selecting it and then pressing Shift+Alt+Down Arrow (or Up Arrow). Continue to hold down Shift and Alt while pressing an arrow key as many times as needed. 9: Create pseudo columns Tables are the easiest way to align columns, but you won't always want the data to appear with borders. In those cases, use a table to align the data and then get rid of the borders. There are two ways to do so. Perhaps the easiest way is to convert the table to text by selecting the table and then clicking the contextual Layout tab. In the Data group, click Convert To Text. In the resulting dialog, change the delimiting character, if necessary, and click OK. In Word 2003, choose Convert from the Table menu and then choose Table To Text. This method is good for a one-time fix as it retains the table's column tabs. You can insert and delete rows easily, but that's about all you can do.If you want the table's bells and whistles, just turn off the borders. After selecting the table, pressing Ctrl+Alt+U. Or click the contextual Design tab and choose No from the Borders drop-down in the Tables Styles group. In Word 2003, you can use the Border control on the Formatting toolbar. Word will display the grid lines, but won't print borders, as shown in Figure K. If you don't want to see even the grid lines, click View Gridlines in the Table group on the contextual Layout tab. In Word 2003, choose Hide Gridlines from the Table menu. Figure K You don't have to display table borders to use table behaviors and properties. 10: Highlight specific dataYou'll apply most formats to an entire table, but you can spotlight specific rows, columns, or even cells. For instance, the table in Figure L uses a different border to highlight Smith's row. To apply this border format, select the cells and then click the contextual Design tab. In the Tables Styles group, choose the appropriate border from the Borders drop-down. Then, choose a style, weight, and color from the options in the Draw Borders group. In Word 2003, right-click the selection and choose Borders And Shading. You could also change the background or font colors -- most formats you can apply to the table you can also apply to specific cells. Figure L This border highlights Smith's yearly total. 11: Change the tab You might have noticed that the table aligned the currency values to the left. That's the default, but you'll probably want to use a decimal tab, as follows: - With the horizontal ruler visible, click the Tab selector (the white square at the intersection of the two rulers) until you display the tab decimal (an upside down T with a decimal to the right). - Select the cells (or column) you want to reformat. - Click on the ruler where you want to add the new tab decimal. Word will temporarily display a vertical guideline showing the position in the document. After clicking, Word will realign the selected values, as shown in Figure M. Figure M Assign a decimal tab to align values in a table's column. In this case, selecting the entire column also aligned the column's header, 2012. Select it and reformat it separately -- it's a small tradeoff. By selecting the whole column, all new records will have the tab decimal in place. Tips and questions What other tricks do you use when working with Word tables? Have you ever been stumped by a table task? Share your advice and questions with fellow TechRepublic members. Full Bio Susan Sales Harkins is an IT consultant, specializing in desktop solutions. Previously, she was editor in chief for The Cobb Group, the world's largest publisher of technical journals.
http://www.techrepublic.com/blog/10-things/10-plus-tips-for-working-with-word-tables/?count=25&view=expanded
CC-MAIN-2014-52
refinedweb
1,488
73.47
Advertisement Similar to some previous posts, where we learned about edge detection, line detection, blob detection, lane detection, and so on. We are going to circle detection in OpenCV python in this OpenCV blog. In the OpenCV Line Detection blog, we saw the function of the Hough lines which helped us detect lines in a picture, similar in this circle detection, we will use the function of Hough Circles. I would suggest you read the Line Detection OpenCV blog first, and then come to this blog to better understand it. Imports import cv2 as cv import numpy as np from matplotlib import pyplot as plt Circle Detection OpenCV Algorithm The first step is common in every OpenCV Detection program, i.e to load the image on which the algorithm is to be applied. Image is resized and a colorful copy of that image is stored in another variable. The Image is then converted to the grayscale image as the HoughCircles() function is applied only to the grayscale images. Then the HoughCircle() function is applied to the grayscale image. Gray scaled image is then blurred using medianBlur() function. The HoughCircles() function in the OpenCV library takes many parameters. - The grayscale image on which the circle detection is to be implemented. - Gradient function – cv.HOUGH_GRADIENT - DP value i.e the resolution of the accumulator - minimum distance - Number of circles - parameter 1 - parameter 2 - Minimum Radius - Maximum Radius Formula of Circle: (x-xc)2 + (y-yc)2 = r2 – HoughCircles() function present in the OpenCV library uses this mathematical formula to detect circles. def circleDetection(): img = cv.imread('./img/balls2.jpg') img = cv.resize(img, (500, 400)) output = img.copy() gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) blur = cv.medianBlur(gray_img, 5) circles = cv.HoughCircles(blur, cv.HOUGH_GRADIENT, 1, 100, 10, param1=130, param2=55, minRadius=5, maxRadius=0) detected_circles = np.uint16(np.around(circles)) for (x, y, r) in detected_circles[0, :]: cv.circle(output, (x, y), r, (0, 255, 0), 3) cv.circle(output, (x, y), 2, (255, 0, 0), 3) cv.imshow("Original Image", img) cv.imshow("Output", output) cv.waitKey() cv.destroyAllWindows() Shuffle the values of the HoughCircle() function in order to get the perfect fit for your model. Circle Detected Image Read other blogs to learn about more Python OpenCV Projects like Lane Detection, Lane Detection and so on.
https://hackthedeveloper.com/circle-detection-opencv-python/
CC-MAIN-2021-43
refinedweb
388
59.3
The Java Specialists' Newsletter Issue 064 2003-02-14 Category: Performance Java version: Subscribe RSS Feed Welcome to the 64th edition of The Java(tm) Specialists' Newsletter sent to 5869 Java Specialists in 94 countries. I stepped off the plane last Tuesday, having come via London from Estonia, and was hit in the face by 31 degree Celsius heat. I was still wearing my warm clothes that were necessary in the -17 degree Celsius in Estonia (travel report to follow), but very quickly, I adapted again to shorts and T-shirt. While I was in London, I had the opportunity to meet Jack Shirazi, the author of the best Java performance tuning website. Basically, when I don't know or understand something about Java performance, I go look at the website. Still coming is a review of Jack's, on our local Java User Group discussion forum, I casually asked the question what was faster: i++, ++i or i+=1. I also mentioned that the answer might surprise them. Wanting to encourage thinking, I never gave the answer ;-) Yesterday, one of my readers, a bright young student at the Cape Town Technical University, sent me an answer based on a thorough investigation through microbenchmarks. His conclusion was correct, but the approach to getting to the conclusion led to a lot of effort being spent on his part. The easiest way to decide which is fastest is actually to disassemble the Java Class. Note that I am saying disassemble, not decompile. Let's look at the following class: public class Increment { public int preIncrement() { int i = 0; ++i; return i; } public int postIncrement() { int i = 0; i++; return i; } public int negative() { int i = 0; i-=-1; return i; } public int plusEquals() { int i = 0; i += 1; return i; } } I may ask you: which method is the fastest, which is the slowest? C programmers would probably say that the fastest are i++ and ++i. When you try running these methods many times, you will notice slight differences between them, based on which you run first, how soon the hotspot kicks in, whether you use client or server hotspot, whether you are busy playing an MP3 on your machine while running the test and the phase of the moon. Instead of measuring the performance, why not investigate what the Java compiler did? You can disassemble a class with the standard javap tool available in your JAVA_HOME\bin directory: javap -c Increment Note that the class must already be compiled. The result is the following: Compiled from Increment.java public class Increment extends java.lang.Object { public Increment(); public int preIncrement(); public int postIncrement(); public int negative(); public int plusEquals(); } Method Increment() 0 aload_0 1 invokespecial #9 <Method java.lang.Object()> 4 return Method int preIncrement() 0 iconst_0 1 istore_1 2 iinc 1 1 5 iload_1 6 ireturn Method int postIncrement() 0 iconst_0 1 istore_1 2 iinc 1 1 5 iload_1 6 ireturn Method int negative() 0 iconst_0 1 istore_1 2 iinc 1 1 5 iload_1 6 ireturn Method int plusEquals() 0 iconst_0 1 istore_1 2 iinc 1 1 5 iload_1 6 ireturn Now when we look at the different methods of incrementing the local variable, we can see that they are actually identical! Next time you are thinking of measuring performance using System.currentTimeMillis(), think of also looking at the generated byte code. It might save you a lot of time. I want to thank Daniël Maree for inspiring me to write this newsletter through his thorough research as to which increment method was faster. Kind regards Heinz P.S. I hope you all enjoy Valentine's day. Remember to leave work early today - i.e. before 8pm ;-) Performance Articles Related Java Course Would you like to receive our monthly Java newsletter, with lots of interesting tips and tricks that will make you a better Java programmer?
http://www.javaspecialists.eu/archive/Issue064.html
CC-MAIN-2017-09
refinedweb
645
57.2
When Will E-Books Become Mainstream? 350 An anonymous reader writes "IBM developerWorks is running an interesting article dicussing the difficulties faced by e-books and what it might take to help them to 'break out'. What are some other ways to give books a 21st-century facelift?" When will they become mainstream? (Score:5, Insightful) Re:When will they become mainstream? (Score:5, Insightful) Never? (Score:5, Insightful) Hmm, adding to the above list, when you can forget your ebook at a bus stop / park bench / other location, and not worry about it because it only cost you $10 (or less). In other words, not for a long, long time. Back that up- Why Not? (Score:5, Insightful) Well here becomes the issue- Why is this so? Think about the actual cost to develop and produce a very simple device that will display text. Forget crazy postscript formats. Plain text in a screen about five inches high by three across just like a real book. A couple hardware buttons for forward/back (with an ability to scroll like anything) and oh.... 16-32MB of onboard Flash memory. A display doesn't need to be backlit, as those $5 handheld video games (back when I was a kid...) that run on a couple AA's work very nicely. So maybe we're all overthinking this. We assume an e-book reader needs to cost hundreds of dollars and be rather complicated. We assume it needs to be backlit and hold hundreds of books. Make them $20-$25 devides with a prev/next button that displays only text in an easy-to-read font adn we're set. Think about it- Is this something that consumers are driving or manufacturers. Consumers don't need colour displays and touchscreens on their reader. That's why they're heavy. They need plain text input documents and to have a small device with a low-power processor (my XT (8086) and WordPerfect used to run circles around any modern 'tablet'-style e-book reader)- none of this PDF stuff. So there's my comment on the reader. Now the other thing to ask is do 99.99% of consumers want e-books or is it publishers who want to save the coin and cut out the middle-man? -M Re:Back that up- Why Not? (Score:3, Insightful) Calculators have been photovoltaic for years, so there's no reason why an ebbok couldn't be. As for backlighting an LED. Why not do the Viewmaster trick? Instead of a battery powered light source, why not make the back of the unit transparent? That way, you could simply hold it up, and any ambient room or outdoor light could Re:Back that up- Why Not? (Score:3, Insightful) And to answer another question, I want them. I want to be able to lug my entire library in my back pocket. I move and travel constantly, and physical books are a pain... Re:Back that up- Why Not? (Score:3, Insightful) I'd like to liken it to e-mail. When you recieve a hand written letter from someone you get a piece of paper that they have touc This is EXACTLY the problem (Score:3, Insightful) I'm saying lets keep it simple. A forward, back, and 'mark' button. Hold the mark button to set a bookmark, press it to go back to it (maybe a confirmation for accidental purposes). Maybe even add the ability to add a few marks. All it needs is a byte, line, or page offset. Write i Re:Never? (Score:3, Interesting) Really, the only reasons for electronic books (not e-books specifically) are the reasons software vendors offer them as free downloads: to reduce expense and speed up delivery. It makes sense for me to download the manual for a piece of hardware, or download developer documentation from Oracle. It's free, and it saves me the trouble of lugging a lot of heavy books. For smaller books, fiction or books I'll want to read away from my computer, the advantag Re: Never? (Score:5, Insightful) Yes, I'm quite sure that Ebooks in their present form aren't suitable for you. But how can you assume that everyone has the same needs, restrictions, and requirements as you? I, for example, have been reading much more off the screen of my 5mx than off paper for the last few years. In terms of convenience, for me, it beats paper hands down -- my 5mx lives in my trouser pocket, whereas paperbacks would have to be carried separately. I find the screen comfortable enough to read from, and my CF card holds the equivalent of about 3 bookcases full, so I'm unlikely to have read it all in the near future. I don't have to worry about bookmarks, and the backlight means I can read in bed with the lights off. Battery life isn't a problem -- even with the heavy use mine gets, a pair of AAs lasts 20-30 hours (probably more if I was only using it to read books). I can search, and cut'n'paste the text. I can even edit it (e.g. anglicising the spelling). Of course, most people don't carry such a gadget around with them, so this method wouldn't apply to them; but it works very well for me, thank you. Re:Never? (Score:3, Insightful) All kinds of onerous DRM, all incompatible with each other. I can lend a book to a friend or sell it at a garage sale. How will this work with a DRM hobbled e-book? Until the publishers all get on the same page and get over their DRM paranoia, e-books will be toys that might get bought by a few wealthy gadget lovers in special stores, but not at the supermarket checkstand. I think we'll still see a lot of dead trees in the forseeable future. DRM. (Score:3, Insightful) When you can publish material without censorship. Re:DRM. (Score:3, Interesting) Wow, I can't believe the lists of demands. It's like a hostage negotiation, heh. Several years ago, I had a PocketPC. I downloaded a couple of e-books and found the experience quite enjoyable. The display and form factor were nice. It was so nice that I could hold the unit in one hand instead of using both to force it to stay open. The scroll wheel made page turning nice and Re:When will they become mainstream? (Score:2, Insightful) Re:When will they become mainstream? (Score:3, Insightful) First, display must be non-powered. That OLCD stuff already makes this possible. Either that or the plastic paper that was recently demo'ed. Second, the battery must be long lasting. Lithium ion batteries will do the job. The killer is going to be storage, of course, and DRM. As mentioned if at least one other comment, one must be permitted to lend the "book" to a friend. Whether this means a one-off license that is part of an "uncopyable" file that transfers to the Re:When will they become mainstream? (Score:3, Insightful) DRM is perhaps the biggest issue here, since technology alone won't solve it. Almost nobody will want to publish without DRM and even then they'll be afraid the DRM scheme will be broken. Re:When will they become mainstream? (Score:2, Insightful) There is no need to have kiosks selling ram cards. Your book would have internet access, or at least a bluetooth connection to your mobile phone so you could buy them online from an itunes style interface. Secondly, it isn't a case of getting the finance to launch it. You have to persuade the book publishers that it is a good idea and that it wouldn't lead to rampant so called "piracy" that would destroy their business. At least one of them, Warner Publi Re:When will they become mainstream? (Score:2) afaict the main thing that controls book piracy atm is its a pain to actually make a copy of a book especially if you wan't it bound properly so people only bother copying things like textbooks which are far more expensive than most mass market books for the same size of book. Re:When will they become mainstream? (Score:2) reading on a PC or laptop is just about acceptable but has major power and portablity issues and the current generation of pdas look pretty horrible for trying to actually read a book. Re:When will they become mainstream? (Score:3, Funny) You, with your Apple iLibro, are reading the seventh book of the Harry Potter trilogy. Here comes your wide-eyed nephew. "Can I read it, please please please?" He's holding up his iLibro eagerly. "Sure", you say. Smiling, you tap on the "share me!" tab on the top of the iLibro's screen. Nephew's iLibro acks and receives the book in four seconds. MEEP. Nephew flops down on the grass, eagerly reading his new copy of HP. I've just made a publisher's heart skip four beats with th Re:When will they become mainstream? (Score:3, Insightful) The latest hardcover of the Honor Harrington serise, Honor's War, included a CD with the electronic version of every single novel written by David Weber for the "Honorverse," as well as all three of the Honorverse anthologies. This isn't the action of someone worried about book piracy. Far from being worried, Baen has made proportio Re:When will they become mainstream? (Score:5, Insightful) There are quite a few nonfiction publishers that release their books for free in digital form. See my sig for a few hundred examples of free books, many of which are also available in print. Re:When will they become mainstream? (Score:2) When you can use them with an indirect source of light. Having a screen next to your face as the only light source can put a pretty heavy strain in your eyes. People already do most of their reading digitally (Score:5, Insightful) If the internet is competing with television in terms of total amount of time people spend recreationally, and the internet is mostly text, then the electronic text on the internet is utterly stomping traditional books in terms of total reader time. I don't think e-books are going to take off to be anything other than niche. Why would people replace their books with the same thing, but digital? Long established technologies don't get overthrown by slight improvements, but radical departures. A three inch by four inch by one inch square can provide 40 or 50 hours of entertainment... why replace that with the an expensive, multi-step gizmo that provides functionally the same thing? That being said, people would accept their books being replaced by something different. That something different would appear to be the compellingness of news.bbc.co.uk, or slashdot, or any number of interesting sites and online texts. People are probably going to get wireless web-enabled phones, PDA's, and Palmtops, and will do a lot of reading through these devices, but they won't look like an electronic book any more than a PC resembles an electronic film projector. When? (Score:2, Insightful) Publishers will more quickly adopt ebooks once someone can not find almost every ebook ever released by forming a proper ebook google search. [tech-recipes.com] If ebooks are copied this easily without punishment, publishers have no reason to push forward. Is DRM the answer? (Well, I can't even suggest that on slashdot, can I?) I buy programming books like candy. I've noticed that recently the quality of the printed texts are going way, way down. More errors in code, more misspellings, cheap Re:When? (Score:5, Insightful) One problem I have with ebooks is that publishers want to take all the benefits and push all the negatives on the user, pretty much by cost-shifting to the user. eBooks require proprietary programs or proprietary hardware, which the user is required to use. Publishers get away from the costs having to print, package, store and distribute paper, they cut out the middle man of distributors and book sellers and yet, they still often charged 90% the cost of the paper book, and the cost of reading the ebook in a portable fashion is high, one has to own and use a laptop. Laptops still have run time issues, books don't. Re:When? (Score:3, Interesting) Books are integral to human learning and we're extremely familiar with them; our earliest memories have books in them. When we start reading bedtime stories to our nieces and nephews from tablets and electronic paper, then children will grow up knowing that as the way to be. Because children growing up now are still being taught from and are used to reading books, it's going to take a long t Re:When? (Score:2) No. Perfect DRM is a mathematical impossibility. Imperfect DRM will be cracked, eventually, if enough people care about it. It only needs to be cracked once and it is then nearly useless. I buy programming books like candy. I've noticed that recently the quality of the printed texts are going way, way down. More errors in code, more misspellings, cheaper paper, etc. I don't think quality is declining -- your standards are improving. I recently reread a few of the C / C++ programming books Re:When? (Score:2) Re:When? (Score:2) i'm studying electronic systems engineering and the blunt fact is most of the students have either never programmed in anything before or have only a very primitive knowlage of VB and nothing else. The last thing they wan't to do is have to teach the complexities of input in java before they teach basic programming. btw at my university they used a non-standard input unit to simplify input but it wasn't gui. They also used an IDE known as bluej wh Personally? (Score:5, Insightful) On top of that, reading in front of a monitor at this point in time is not enjoyable. Maybe (hopefully) e-paper will change that. For me, when I first heard about E-books I immediately thought "no cost of shipping, no middleman warehouse distribution, no physical cost to print/bind, no brick and mortar store paying electricity, rent, stocking risky books at a premium, they'll be dirt cheap!" I was wrong. Re:Personally? (Score:5, Insightful) That's because the publisher looked at those exact same issues and said "I'll be rich"! 75 years from now? (Score:2, Interesting) Older books (pre UN drug treaty) were printed on hemp paper and can last hundreds of years without too many problems. Re:75 years from now? (Score:2) Even good quality (acid-free) wood pulp paper will last for this long. However, the qual You weren't worng (Score:2, Informative) New devices as Nokia 770 [nokia770.com] can make read more enjoyable with good 800x600 screens. ePaper may be the future, but not the present. You can't say that on slashdot! You have a lot of free (as in beer, as in speech Huzzah for Dead Trees! (Score:2, Insightful) why fix something that isn't broken? (Score:3, Interesting) why do we even need e-books? seriously, i'm no luddite, i just fail to see any compelling reason to replace something that isn't broken Re:why fix something that isn't broken? (Score:3, Insightful) Re:why fix something that isn't broken? (Score:2) Re:why fix something that isn't broken? (Score:5, Interesting) Do your bit to reduce greenhouse gases, cut down a tree! (And plant a new one.) Most new paper pulp comes from tree farms, and has for decades. Re:why fix something that isn't broken? (Score:2) Re:why fix something that isn't broken? (Score:5, Insightful) I recently went on holiday, and usually I take 5 or 6 books for a 2 week period, and thats rarely enough. This way I was able to take 200 or 300 books, and save on my airline baggage allowance. Will ebooks replace books? Maybe not for the vast majority of the public, but for me, tehy pretty much already have. Re:why fix something that isn't broken? (Score:3, Interesting) With the press of a button I can be back where I was, I can turn pages with one hand so I can hold onto the subway, it glows in the dark if I want (Also useful to find way to the washroom at night). I can read about 50% of a book on one charge (Li-Ion no usb charge) Before that I had a Palm IIIxe not the greatest but available for $15-30 bucks and can read two books on 2 AA batteries. I have an increadible selection with me wherever I go and sin Re:why fix something that isn't broken? (Score:2) Re:"Cheap iPaq?" (Score:2) Re:why fix something that isn't broken? (Score:2) Re:why fix something that isn't broken? (Score:4, Insightful) For example, I'm reading a hardcover novel at the moment that's about 600 pages long. It's so big and bulky (1.5 inches thick) that I can't easily carry it on trips in my laptop bag and it cost $25.95. Unfortunately it's not available in e-book format, and the books that are tend to be in proprietary formats, saddled with annoying DRM and don't cost much less than their paper versions. Re:why fix something that isn't broken? (Score:3, Insightful) Because on one device, you could carry all your books, instead of lugging hundreds of pounds around with you. Very useful for those of us with huge college textbooks, for example. Re:why fix something that isn't broken? (Score:2) why do we even need e-books? "Real" books are *not* cheap. Production and distribution costs for a paperback book are typically $3-$5 US. Production and distribution costs of an e-book are almost zero, except that the reader needs a display device (~ $50 production and distribution cost). So if the average reader will purchase more than 10 books there are cost savings to be had. The problem Re:why fix something that isn't broken? (Score:2) Why do people go to concerts when they can buy all music on CDs, too? It's about the same reason, I'd say - music isn't just about the songs, and books aren't just about the words. I' They just don't get it... (Score:3, Interesting) Re:They just don't get it... (Score:2) 2. Ereader.com has fairly 'loose' DRM, in that you unlock the book in their reader and thats it. You can download it to as many systems as you want. 3. Most ebooks are actually pretty cheap if you shop around - most of hte ones Ive bought have been at 50% or less than their paper brethrens. Remember, not all solutions are best for everyone. If you dont like ebooks, fine. hmmm... (Score:2) P2P-"sharing". (Think libPod.) Wonder if Simon & Schuster will go for it... I do this all the time (Score:3, Insightful) But the main issue is in the reader. So far, they only work with Palm, Windows CE, and I think one cell phone device (not inluding PC readers, which is silly - I want a handheld unit). Most people aren't going to shell out $100 for a "ebook only" device - especially one that just works with cartridges or has a single purpose. Most PDA's are a good example - if more phones go the PDA style route, that may work as well. Odds are, as we see more "cell phone/internet access devices", and more support on the INternet for these devices (ever try to surf slashdot.org or most sites with a cell phone web browser? Yeah. Pain.), perhaps ebooks will take off. Until then, they're a side show, a novelty for people such as myself who don't mind looking at a little screen while I read about the Shaftoes and Waterhouses galavanting about the world. How I read ebooks (Score:5, Insightful) *Great story, by the way. King Vikramiditya (Vikram for short) is tasked to carry a vampire a certain distance. Every time he speaks, the vampire goes back to its tree and he has to start again. So the meat of the book is a dozen or so stories told by the vampire in order to get Vikram to react by saying something out loud. facelift ? (Score:2) E-ink, price, rights (Score:2, Redundant) 2)They must be priced competitively. 10 cent chapters. $1-2 books. Free content which is in the public domain or put out by individual authors. 3)They must not be so encumbered by DRM that people find them useless. One major f Re:E-ink, price, rights (Score:3, Interesting) 1) It needs to work everywhere. No proprietary devices, software, or code. Like HTML... or the printing press. Just print out the book if you like. 2) No DRM. That crap is killing everything, and making me consider moving to the bahamas or something. I wish I'd never heard of it. Well, it is hard to kill music with DRM, but easy to kill books. So we need something like HTML... or the printing press. Just print out the boo Re:E-ink, price, rights (Score:2) Disagree, but because the iPod did get it right: it supports mp3.HTML is the best format for it.HTML is a lousy format for reading--it isn't prepress. Few browsers make it pretty & an ebook reader should be dumb enough to support it. PDF is my bet: it looks EXACTLY the way the publisher intended on any device. It is well-documented. It can support DRM (so publishers will buy in), but the DRM sucks (so tech Re:E-ink, price, rights (Score:3, Insightful) Never. (Score:3, Insightful) Your mileage may, as always, vary. When they do what I want (Score:2, Interesting) Be light enough to read in bed. have a built in dictionary(highlight word, get def , in language of choice) have built in pronunciation, (highlight word or phrase and hear it, in language of choice) ebooks are erehwon (Score:5, Informative) Ebook technology is backwards. The article pretty much is dead on (in summary:). In addition, ebook readers don't feel like or smell like books. I saw Bill Gates give a presentation probably five years ago and he was hot for ebook technology. He described how ebooks would simulate the look and feel of a book to the extent that would be possible electronically. Virtually none of his listed features have appeared (e.g., the ability to "flip" a page with your finger as if it were a paper book). As for the above listed reasons: A year later I got the new and improved version, same size, higher resolution and in color! Virtually no improvement in the font rendering, I returned that unit the same day also. Some things are worse than DRM (Score:2) eBook Gold [ebookgold.com] Apple jumps in (Score:2) IE, when there is a profit incentive. By the time Dell jumps in, the market is already "mainstream". Put another way: Before Apple's iPod, the big player was Creative Labs; mp3s were popular, but I don't think you can use the term 'mainstream'. Then after Apple jumped in, so did Dell. So wait until Apple jumps in, and creates a really popular eBook reader/format, and you should be okay. It's way past okay when Dell jumps in. It's the Library stupid... (Score:2) So round about... oh... when hell freezes over and people quit using DRM. Better media (Score:2) Ebooks are pretty good right now, except for the media that you view them on. When I bought a Cassiopea a few years ago, I found it really convenient to have a number of books with me (MS Reader fomat). But I found it really inconvenient when the darn screen cracked (and its nigh on impossible to buy parts for that kind of thing!) When you can buy a reader that looks, feels, and wears like a paper book, that isn't going to break from rough handling; when you can load new content easily on said reader; TH Anyone else hate ebooks? (Score:2) Price. (Score:3, Interesting) Well, beyond the fact that there aren't many companies putting out E-books as-yet... Just my 2 cents. YMMV - Exportability. Who wants to buy an E-book (that costs nearly as much as the paper version) when it's digitally signed/encrypted so that it can't be exported into other formats? It may not bother you now, but a few years down the line it'd really piss you off if that copy of Harry Potter in .lit format couldn't be converted to a format that is still in existence. Hell, some E-books won't even let you print your copy out on paper. WTF is up with that... When E-Paper is commercially availible (Score:2, Insightful) epaper and html (Score:3, Interesting) Also the ebooks need to come in an open format, I personally think semantically correct (x)html would be perfect. Easily restyled to your personally preference. Blind users would also benefit from that as they wouldn't need to wait ages for the book to come out on tape, assuming it does at all. Firefox in my pocket is what i want. For Research not for Reading (Score:2) Ebooks are mainstream (Score:2) For instance, the Houston Public Library allows you to check out and read certain books online. Rather than hopping in a car and driving around town to find a physical copy of book X at one of the 30 library locations, I can simply fire up a browser and check it out. No need to worry about late For me, a useful e-book would be like... (Score:3, Interesting) Give me an "eBook" that's about the size and weight of a standard paperback. Open it up, and there should be electronic paper on both sides. Visible in normal light and bright sunshine. Minimum 300dpi resolution. The two facing screens should display type much like a paperback does, with a nice mat finish (no shiny stuff). And it should be augmented by touch sensitivity, so I can "change pages" with "gestures"... by swiping across the right hand page (top corner down towards center) in the standard "turning the page" gesture. There should be touch sensitive spots along the bottom that allow me to call up the table of contents, an index (that also allows searches), and tools to allow me to highlight and bookmark passages. When I open the eBook it should open to right where I left off. It should be water resistent, shock resistent, and the screen should be flexible enough that I don't have to worry about breaking the damn thing. New books should be just a pluggable memory cartridge away. The memory cartridges should also store the bookmarks and highlights and "current position" so I can flip through several books at any time without losing my place in any one of them. Once an eBook experience is like THAT, then watch out, they'll actually start to catch on. Or at the very least, *I* would suddenly be interested in owning one. PSP Browser + Gutenburg Project (Score:2, Informative) When? (Score:2) One reason people like paper is for sharp text and graphics. Low-end laser printer do 600dpi while urrent eReader devices use the lowest resolution they can get away with and that puts most of them under 100dpi. Add the facts that eReader documents can be DRM'd or otherwise uncopiable/undistributable. Paper simply always works. Un When... paper + digital benefits... (Score:2) Not too tall an order if the players have a mind to give us what we want and not try to force us to accept what they want. all the best, drew -- [ourmedia.org] Personally, I prefer (Score:2) when you can... (Score:2) when? (Score:2) Tungsten E w/ Magicians Nephew (Score:2) Shown is low contrast I usually use somewhere in the middle, and I find that I can read a page and put it away in about 10-15 secs. Hitting the button on the front set up for book opens to exactly where I was with just one hand. It's extremely convenient, for long term use I don't mind looking at the screen either using iSiloX text is easily big enough to keep the unit far from my face. My only problem has Changing Documents (Score:2) Idea (Score:2) Never (Score:2, Insightful) Never as long as DRM and time restrictions exist (Score:2) On a lesser note, unless I can write and scribble "digital" notes oh, and another thing! (Score:2) I posted before [slashdot.org] on this and listed a few of my experiences and reasons for the unfortunate premature death of ebooks. Let me add another reason... As always, I get all excited again when I think about the potential of ebooks and what they could bring. Seeing this slashdot article, I set out to google myself the latest and greatest. Turns out not much has changed. Probably one of the most egregious and unforgivable injuries visited on the consumers is the lack of a price break. Consider: For me (Score:2) In short, e-books will become mainstream when you can treat them as horribly as you can treat paper books. In the meantime, there exists an alternative which is much cheaper and a lot more durable. Dumb article, dumb discussion (Score:4, Interesting) Instead, it reiterated the same tired old points pro and con, totally missed the point of the Baen Free Library [baen.com] (and also didn't recognize that Webscriptions, its commercial counterpart, has been doing quite well for itself in e-sales alone), and went on to snark at the very notion of commercially-viable ebooks and talk about various things that don't have a darned thing to do with ebooks, like RFID tagging library books. Um, what? And the discussion is the Standard Slashdot Ebook Advocacy Debate, whereupon people mostly or totally ignore the content of the article and instead argue about how ebooks suxx0r or r0xx0r. And here I'd hoped I'd read something interesting. Oh well. Maybe next time. Besides the more correct answers... (Score:3, Insightful) It's hard to get a mystical experience from reading some poorly written 16th century manuscript if it's on a computer screen or handheld, but if the same bad prose is printed on the fading yellow pages of a several centuries old stack of paper and wood it becomes a spiritual thing and no amount of poor editing can get in the way. Do I sound cynical? I have friends who are always complaining that they want to read certain things but can never get around to checking the books out of the library. I point out that I could just email them a copy and they get indignant. It's for this reason that I've taken to buying physical copies of books if I really liked them. Why do e-books have to be exactly like books? (Score:2) Nobody is saying that computer documents (like web pages) have to be exactly like books. The Slashdot discussion you're reading right now is nothing like a book. It's not printed on anything like paper. It's not formatted into anything like a book page. The experience of reading it is nothing like reading the "Letters to the Editor" column of your local newspaper, although the length and content is (arguably) similar. Yet people read it. Things don't have to be in You just don't know how to cook them properly (Score:3, Insightful) It doesn't matter how large the screen is, unless you need huge diagrams or maps. What matters for reading comfort is resolution and contrast. My Palm Tungsten E2 has about the same contrast than average book paper under average lighting and about 30-50% the resulution. On the other hand, a PDA is 100-200 grams, while a book can be 0.5-2 kg. It's physically uncomfortable to read books when you lie on your back, for example. And you won't get proper lighting then, while PDA screen is backlit. The author tried to mislead the readers about squinting - you don't squint because of a small screen, you squint because of small text. And who forces you to read in small font? With a PDA you can choose ANY font. They're not portable if you have to read them on a desktop computer; if you read them on a laptop or PDA, you can't read if you run out of power. You can't read an ordinary book if you run out of power too. I probably isn't be mistaken much when I estimate that about 80% of reading or more is done under artificial light. And if you have artificial light it usually means you have electricity, which means you can plug in your notebook or PDA. There's a number of often incompatible formats that the files come in. That doesn't affect those of us, who use compatible formats. It's like saying that cars have failed, because Model X is ugly or that Hollywood has failed because Actor Y can't act. And the user's ability to access the book's content is often restricted by various digital rights management technologies. Same as above. My ability is never restricted, because I simply don't accept (and will never accept) any DRM curses on my books. I prefer IRC (#bookwarez) to DRM. And again, this doesn't prove ebooks are bad. The guy doesn't understand the reality of the issue and he is really at the kindergarten level. Just ignore him and he will go away. BTW, everyone who brings up flying cars is dangerous to society and should get a court order restraining him from speaking about future. He is also clueless, because he thinks that electronic paper will greatly increase the popularity of ebooks. This is not the case, to put it mildly. Yes, in a decade or two we will have paper-thin computers that look better than paper. And at the same time ebooks will be mainstream. But the latter won't happen because of the former. Of course, someone who thinks that reflected light is somehow more pleasing to the eye than emitted light is better ignored (rather than asked to cover "technological issues"). Cory doctorow said it all. (Score:4, Interesting) First, the article highlight a few common points about the current state of e-books, but then it degenerates into some kind of rant (although it has some good points too). First, I have a few things to say about the "properties" of e-books. Fine, that's true. That does not mean they are destined to be a failure. One just has to know the consequences of using one technology (ebooks) or another (paper). I can carry more e-books in my PDA than I could possibly do with paper (about 20 books). I know perfectly that I'm forced to read from a tiny little screen, but that's something I know, that's the price I pay. If some day I wanted to read from a more "comfortable" medium, I could easily take a paper book from my home library. It's a matter of choices. It might be better for reading reference material, but that doesn't mean it's not workable. This is related to the point above. You have to keep in mind that you cannot read a paper book either without power (cannot read in the dark). Okay, in the case of ebooks, you need TWO power sources. He's right about that. That's why standards are important. We've got ASCII text as a las resort, though. Cory Doctorow [craphound.com] already talked about that. He's right on target. Most of the e-books I read are either: No need to say anything else. About books and readers, even if there are no commercially available readers, that does not mean people wouldn't use one. People do read their reference material from somewhere. It would be great if they made that "electronic paper" cheap enough, but even if that level cannot be achieved that doesn't mean ebooks are not good. Then he proceeds to bash some (IMHO stupid) ideas from marketing people. The author's right about this. Most of these ideas are about trying to sell books to people that wouldn't want to read them (like a video-game-in-a-book). E-books are probably not successful because of the points mentioned in the first part, especially the DRM stuff. I think they would be a success, even with mediocre reader devices if people realised they have a place, not exactly as the paper versions, but as something not quite the same, more versatile (I'm starting to sound like Mr. Doctorow...). I think the show stopper is the DRM, that causes that more versatile, yet inferior thing to lose its versatility (thus making it an overall loser), with lack of good reader devices a not so important cause. Why focus on the negatives? (Score:3, Interesting) Me, I don't think the e-book is a good format for fiction. If I want to read Lord of The Rings I don't want to be sitting at a PC or holding some device. How about the positives: -They can be published very fast. I wrote an e-book, made the first sale within a week. In the traditional publishing world that doesn't happen. -They have high profit margins for the writers: The only middleman is the billing processor. Whats that, 3% or 4%? High profit margins for writers mean you can write a book that has a small audience and still pay your bills at the end of the month -- and maybe even write another. -The can be easily updated Forget 1st, 2nd, 3rd, and 4th editions being measured in years. In the e-book world it can be a matter of days. -Easier to make an interactive experience In the e-book world the author can personally work with readers. For example, he or she could charge a price that would sound outrageous on Amazon or in Borders, but makes sense for a reader who needs in-depth and personal support. The author can tie the e-book into a premium/subscription website. When I hear "e-book" I think positive. Very positive. Re:when they (Score:2) Considering you can fit even the largest e-book (no pictures) onto the smallest USB thumb drive, you can. The problem arrises when you want to read it. when you're out and about. I just bought Victor Hugo's "The Man Who Laughs" from Amazon.com in ebook format the other night. I was actually forced into buying the ebook version, since the hardcover was over 40$ (even used), and the softcover was overpriced, as well. The ebook was under 10$ Re:when they (Score:2) problem is that I had grabbed 2 other books off project gutenberg (albeit, at least a year or 2 ago) and it was riddled with typos and some paragraphs that were nearly indecipherable. YES (Score:2) Re:Wrong Question -- MOD PARENT UP (Score:3) The fact that a few techno-geeks think that ebooks are better doesn't mean the technology will Re:I know this one! (Score:2) Re:I know this one! (Score:2) Re:luddites! (Score:3, Interesting) The biggest is the cost shift issue. Only when ebooks are priced such that it reflects the fact that the costs are a lot lower to make them. That and there is an affordable large transflective display so I don't have to read on an emissive screen. As it is, it costs more to buy 50 ebooks + some sort of reader than it does to just buy the 50 books. And those books are re-sellable. The ebook reader is too risky from a damage perspective, I can drop a book on conc
http://news.slashdot.org/story/05/09/17/1548209/when-will-e-books-become-mainstream
CC-MAIN-2016-07
refinedweb
6,836
72.97
Up to Design Issues These. The log: namespace has functions, which have built-in meaning for CWM and other software. See also: The prefix log: is used below as shorthand, universal ascertain proportion universally quantified livesIn z } log:implies { Boston weather y }. Here the rule fires when x is bound to a symbol denoting some person who is the author of a formula y, when the formula makes a statement about the weather in (presumably some place) z, and x's home is z. That is, we believe statements about the weather at a place only from people who live there. Given the data Bob livesIn Boston. Bob wrote { Boston weather sunny }. Alice livesIn Architecture languages,. @@@@ A full discussion of the grounding of meaning in a web of such definitions is beyond the scope of this article. Here we define only the operation semantics of a system using N3. @@@@ Edited up to hereThe log:semantics of an N3 document is the formula achieved process rules in the (indirectly command-line specified) formula or any formula which that declares to be a Truth. The dereifier will output any described formulae which are described as being in the class Truth.This class is not at all central to the logic. @@ Summary The semantics of N3 have been defined, as have some built-in operator properties which add logical inference using rules to the language, and allow rules to define inference which can be drawn from specific web documents on the web, as a function of other information about those documents. The language has been found to have some useful practical properties. The separation between the Notation design goal for distributed rule systems. F = G iff |stF| = |stG| and there is some substitution σ such that (∀i . ∃j . σFi = σGj. ) formatting XHTML 1 with nvu yes, discuss notational abbreviation, but not abstract syntax hmm... are log:includes, log:implies and such predicates? relations? operators? properties? To do: describe the syntactic sugar transformations formally to close the loop.
http://www.w3.org/DesignIssues/Notation3
CC-MAIN-2015-22
refinedweb
334
54.93
In The art of metaprogramming, Part 1: Introduction to metaprogramming: - We determined which problems were best solved with a code-generating program, including: -, including: - Generic textual-substitution systems - Domain-specific program and function generators - We then examined a specific instance of table-building - We then wrote a code-generating program to build static tables in C - Finally, we introduced Scheme and saw how it is able to tackle the issues we faced in the C language using constructs that were part of the Scheme language itself This article gives you details on how Scheme macros are programmed and how they can make your large-scale programming tasks significantly easier. Writing syntax-case macros in Scheme While syntax-case macros are not a standard part of Scheme, they are the most widely used macro types that allow both hygienic and non-hygienic forms and are very closely related to the standard syntax-rules macros. syntax-case macros follow the form in Listing 1: Listing 1. The general form of syntax-case macros What this form does is defines macro-name to be a keyword used for transformation. The function defined with lambda is a function used by the macro transformer to convert the expression x into its expansion. syntax-case takes the expression x as its first argument. The second argument is a list of keywords which are to be taken literally within the syntax patterns. The other identifiers used in the patterns will be used as template variables. syntax-case then takes a sequence of pattern/transformer combinations. It proceeds through each one, trying to match the input form to the pattern and, if it matches, it produces the associated expansion. Let's look at a simple example. Say we wanted to write a more verbose version of the if statement than the one Scheme offers. And let's say that we want to find the greater of two variables and return it. The code would look like this: (if (> a b) a b) To a non-Scheme programmer, there are no textual indications to indicate which is the "then" branch and which is the "else" branch. To help with this, you can create your own custom if statement that added the "then" and "else" keywords. It would look like this: (my-if (> a b) then a else b) Listing 2 demonstrates the macro to perform this operation: Listing 2. Macro to define an extended if statement When this macro executes, it will match the my-if expression up to the template like this (in other words, matching a macro invocation to a macro definition pattern): Therefore, in the transforming expression, anywhere where it says condition it is replaced by (> a b). It doesn't matter that (> a b) is a list. It is a single element in the containing list so it is treated as a unit in the pattern. The resulting syntax expression simply rearranges each of these parts into a new expression. This transformation happens before execution, during what is known as macro-expansion time. On many compiler-based Scheme implementations, macro-expansion time occurs during compile time. This means that macros are only executed once, at the beginning of the program or at compile time, and never have to be re-evaluated again. Therefore, our my-if statement has no runtime overhead whatsoever -- it is converted to a simple if at runtime. In the next example, we are going to perform the famous swap! macro. This will be a simple macro designed to swap the values of two identifiers. Listing 3 gives an example of how the macro will be used. Listing 3. Using the swap! macro to exchange indentifier values This simple macro (Listing 4) implements the swap by introducing a new temporary variable: Listing 4. Defining our swap! macro This introduces a new variable called c. But what if one of the arguments to be swapped is called c? syntax-case solves this problem by replacing c with a unique, unused variable name when the macro expands. Therefore, the syntax transformer will take care of this all its own. Note that syntax-case does not replace let. This is because let is a globally-defined identifier. The idea of replacing introduced variable names with non-conflicting names is called hygiene; the resulting macros are called hygienic macros. Hygienic macros can be safely used anywhere without fear of stomping on existing variable names. For a wide variety of metaprogramming tasks, this feature makes macros more predictable and easier to work with. While hygienic macros make introducing variable names within macros safe, there are cases in which you will want your macros to be non-hygienic. For example, let's say that you wanted to create a macro that introduced a variable into a scope that could be used by the person calling the macro. This would be a non-hygienic macro because the macro is polluting the namespace of the user's code. However, there are many times when this ability is useful. As a simple example, let's say that we wanted to write a macro which introduced the definitions of several math constants for use within the macro (yes, this could be better accomplished using other means, but I'm using this for a simple example). Let's say we wanted to define pi and e using a macro invocation like Listing 5: Listing 5. Invocation of a math constant macro If we tried to set this up like the previous macros it would fail: Listing 6. Math constant macro that doesn't work This formulation won't work. The reason is that, as mentioned earlier, Scheme will rename pi and e so they don't conflict with other names in enclosing or nested scopes. Therefore, they will get new names and the code (* pi e) will be referencing undefined variables. We need a way to introduce literal symbols which can be used by the developer invoking the macro. In order to introduce code into a macro that won't be modified by Scheme's automatic hygiene, the code must be converted from a list of symbols into a syntax object which can then be assigned to a pattern variable and inserted in the transformed expression. To make this happen, we will use with-syntax which is essentially a "let" statement for macros. It has the same basic form, but is used for assigning syntax objects to template variables. In order to be able to create a new template variable, you need to be able to translate symbols and expressions back and forth between list representation (the way syntax is written) and the more abstract syntax object representation. The following functions do these conversions: datum->syntax-objectconverts a list to the more abstract syntax object representation. - The first parameter to this function is usually (syntax k)which is a little magic formula that helps the syntax converter get the context correct. - The second parameter is the expression that needs to be converted into a syntax object. - The result is a syntax object that can be assigned to a template variable using with-syntax. syntax-object->datumis the reverse process of the datum->syntax-object. This takes a syntax object and converts it into an expression that can be manipulated using normal Scheme list-processing functions. syntaxtakes a transformation expression consisting of template variables and constant expressions and returns the resulting syntax object. For this example, to get the literal values in a template variable, you would use syntax and syntax-object->datum in combination. You could then manipulate the expression and use datum->syntax-object to get it back into a syntax object which can be assigned to a template variable using with-syntax. Then, in the final transformation expression, the new template variable can be used like any other. In effect, you are converting the Scheme syntax to a list you can manipulate, manipulating that list, and then converting it back into a Scheme syntax expression for output. Listing 7 shows the macro definition to define math symbols using these functions: Listing 7. Math constant macro that works If you are not familiar with Scheme, the backquote, called a quasiquote, is similar to the quote operator except that it allows non-quoted data to be included if it is preceded by a comma (called the unquote operator). This lets us splice the expression into our bit of boilerplate code, then the whole shebang is converted back into a syntax object as the final transformation. Since we explicitly spliced the new variables into the existing syntax object, there is no chance for them to be renamed. Also note that the expression (syntax k) in datum->syntax-object is necessary but essentially meaningless. It is used to invoke a little bit of "magic" within the syntax processor so that the datum->syntax-object function will know what context the expression should be processed in. It is always written as (syntax k). The problem with non-hygienic macros is that the introduced variables can overwrite and be overwritten by other variables in the code. This makes mixing non-hygienic macros especially dangerous since the macros will not be aware of what variables the other macros are using and they may stomp on each other's variables. Therefore, non-hygienic macros should only be used when there is no other way to accomplish the same effect using normal functions or hygienic macros and in such a case the macro's symbol introductions should be carefully documented. Building boilerplate macros A lot of the code written in large applications is boilerplate code which is tedious to write and, if a bug is discovered in the boilerplate code, it is very, very difficult to find every instance where the boilerplate is used and rewrite the code. This means that boilerplate code is one of the few places where non-hygienic macros are useful. A large part of boilerplate code is simply setting up variables that are going to be used within your function, therefore the boilerplate macros should be introducing a large set of common bindings, as well as perhaps other housekeeping tasks. Let's say that we are building a CGI application consisting of many independent CGI scripts. In most CGI applications, much of the state is stored in a database, but only a session ID is passed to each script via a cookie. However, in nearly every page we need to know the other standard information (such as the username, group number, the current job being worked on, whatever else information is pertinent). In addition, we need to redirect the user if they do not have an appropriate cookie. Listing 8 demonstrates some code that could be a standard boilerplate (hypothetical Web server functions will be prefixed with webserver:): Listing 8. Boilerplate code for Web application While some of that can be handled by a procedure, the bindings certainly cannot. However, we can turn most of it into a macro. The macro can be implemented like this: Listing 9. Macro of the boilerplate code We can now create new forms based on our boilerplate code by doing the following: In addition, since we are not defining our variables explicitly, adding new variable definitions to our boilerplate won't affect its calling conventions, so new features can be added without having to create a whole new function. In any large project, there are inevitably templates to follow which cannot be reduced to functions, usually because of the bindings being created. Using boilerplate macros can make maintenance of such templated code much easier. Likewise, other standard macros can be created which make use of variables defined in the boilerplate. Using macros like this significantly reduces typing because you do not have to constantly be writing and rewriting variable bindings, derivations, and parameter passing. This also reduces the potential for errors in such code. Realize though that boilerplate macros are not a panacea. There are many significant problems that can occur, including: - Accidentally overwriting bindings by introducing a variable name that was previously defined in a macro. - Difficulty tracing problems because the inputs and the outputs of the macros are implicit, not explicit. These can be largely avoided by doing a few things in conjunction with your boilerplate macros: - Have a naming convention which clearly labels macros as such, as well as indicate that a variable came from boilerplate code. This could be done by affixing -mto macros and -bto variables defined within a boilerplate. - Carefully document all boilerplate macros, especially the introduced variable bindings and all changes between versions. - Only use boilerplate macros when the savings in repetitiveness clearly outweigh the negatives of implicit functionality. Using macros for domain-specific languages In programming, many times what is really needed is a small domain-specific language. There are many examples of domain-specific languages in use today: - Configuration files - Web markup languages such as HTML - Job control languages These languages are not necessarily Turing-complete (if it has a computational power equivalent to a universal Turing machine -- in other words, the system and the universal Turing machine can emulate each other). The commonality between them is that they all have a lot of implicit assumptions and implicit state that would have to be dealt with explicitly in a general-purpose programming language. Scheme allows you to have the best of both worlds by being able to define macros which operate as specialized domain-specific languages. For the first example, let's consider a security configuration file to detail different security domains within a configuration file. There will be several different security domains, each of which have different access controls and restrictions. Many systems already have declarative security. Specifically, J2EE has some of the declarative security features we are going to look at, such as: Listing 10. Declarative security features in J2EE In this code, we are limiting access to a certain URL based on a given user's role and telling which authentication mechanism to use for someone who is not logged in. This can be done in a similar way with a macro in Scheme. We could define a macro that would allow us to do something like this (a declarative security macro): Listing 10 is what the macro definition for the previous macro invocation might look like (all functions prefixed with webserver: are hypothetical functions provided by the Web server): Listing 11. Writing the declarative security macro These macros require a little bit of explanation. First of all, there is a new construct introduced, .... This notation essentially means "repeating as before." It can be used both in the macro pattern and in the expansion. The resource macro basically builds a function for processing security credentials and then passes that as an argument to webserver:add-security-function. It defines a function with a single argument, credentials, which will be used by the auth-constraints macro. The auth-constraints macro is a little more complicated. It can take one of two forms -- either having a single constraint to process or a list of constraints to process. The first section of the macro breaks down the list of constraints case into multiple single constraints cases. The ... is used to indicate possible continuation of similar forms. We are taking advantage of the fact that after a macro expansion occurs, the result is then macro-expanded again, continuing until no more expansions take place. If you follow the iterated expansions of auth-constraints, you will see that it will indeed expand into a list of individual auth-constraints macros which will then be processed individually using the remaining macro forms. auth-constraints contains two extra features that aren't being used in the example. The first is a time-based authorization mechanism and the second is the ability to be further expanded by other macros and code. The time-based authorization mechanism is merely an example of how multiple types of constraints can be added in to this mechanism; the expansion option will be used in a later example. These macros will expand our security declarations into what's shown in Listing 11: Listing 12. Expansion of Scheme declarative security This leads to the obvious questions: - Why did we bother to implement this as a macro? - What was wrong with the XML declaration used by Java? There are two issues that make a macro set preferable to data languages like the XML declarative security file: - The declarative information is transformed into an imperative form at compile-time, rather than each time it is used at runtime, resulting in faster code. - More importantly, if the declarative language is not expressive enough for your needs, you can include imperative statements within your file as well, using the full expressive power of the programming language. While the first feature is useful, the second feature is what makes it worthwhile. Since the macro expands to regular code anyway, you can always switch back to imperative programming if the declarative language doesn't suit your needs. In fact, if the transformation is well documented, you can even mix declarative and imperative statements within your configuration. Let's say, for example, that you wanted to check the domain that the user was coming from against an external list of rogue IP addresses. Here is how we could do it using a mixture of declarative and imperative security features: This allows the ultimate in flexibility for programming. You can program declaratively, using domain-specific sub-languages, but still revert to your full-featured programming language if the sub-language does not meet your needs fully. Metaprogramming has many uses in large-scale computer programming. In this article, I've touched on the tools needed to do metaprogramming in Scheme, as well as provide several metaprogramming examples. Metaprogramming techniques were applied to several application areas: - Making the syntax nicer - Automating boilerplate generation - Writing declarative sub-programs In Scheme, you can use the macro facility to define nearly any sort of domain-specific language you want. The tools are there. It's just a matter of deciding which features are implemented more easily and more clearly using macro expansions versus regular code. Learn - Using syntax-case - The main publication describing syntax-caseis Kent Dybvig's Writing Hygienic Macros in Scheme with Syntax-Case. - Dybvig further expands upon that description in Chapter 8. Syntactic Extension of The Scheme Programming Language. - JRM's Syntax-rules Primer for the Merely Eccentric is the one good guide for intermediate-level macro programming in Scheme. - On Lisp thoroughly describes the problems, solutions, and possibilities in writing macros in Lisp-like systems. - Read other articles by Jonathan Bartlett on developerWorks. - The Code generation using XSLT tutorial (developerWorks, April 2003) provides a basic introduction to code generation concepts. - Replacing reflection with code generation (developerWorks, June 2004) demonstrates how you can use runtime classworking to replace reflection code with generated code. - This list of tutorials will get you started with Scheme macro programming using syntax-caseand syntax-rules. - This article answers the question: Are You Missing Out on Code Generation? - Refactoring as Meta Programming? (Journal of Object Technology) reflects on the use of refactoring as a type of metaprogram. - An interesting resource for the code generating aspect of programming is the Code Generation Network which provides code-generation info for the "Pragmatic Engineer." - Find more resources for Linux developers in the developerWorks Linux zone. - Get involved in the developerWorks community by participating in developerWorks blogs. Jonathan Bartlett is the author of the book Programming from the Ground Up, an introduction to programming using Linux assembly language. He is the lead developer at New Medio, developing Web, video, kiosk, and desktop applications for clients.
http://www.ibm.com/developerworks/linux/library/l-metaprog2.html
crawl-002
refinedweb
3,285
51.07
You can subscribe to this list here. Showing 3 results of 3 >. Yes. For intensive operations on time series, a list of datetime objects will slow overall performance down significantly. Sometimes, I dream a sort of time array in numarray like string array, or object array. It can be implemented by holding a datetime object indicating an epoch and an array of floating points indicating intervals from the epoch. Daehyok Shin >>>>> "Wayne" == Wayne Christopher <wayne@...> writes: Wayne> I have been using matplotlib with TkInter (TkAgg backend) Wayne> and it's really nice once I got the hang of it... I have Wayne> two questions though, which I couldn't find in the manual. Wayne> 1. The figure window has a pretty large border around it, Wayne> that seems to expand as I enlarge the window. Is there a Wayne> way to set this to, say, N pixels? You cannot set it by pixel, but you can control it with the axes command. The syntax is axes([left, bottom, width, height]) where all values are fractions of the figure. Eg, left and width are fractions of the figure width, and bottom, top are fractions of the figure height. With a little arithmetic, you can figure out what fractions to use for a given pixel value, since the figure width in pixels is width in inches * dpi. See. Wayne> 2. I have some x, y window coordinates I got via Tk event Wayne> bindings. How can I translate these into data coordinates? You can plot in any coordinate system you want by setting the appropriate transform. If you want to plot in pixels, just specify your data in pixels and use the identity_transform, as in this example from matplotlib.matlab import * from matplotlib.transforms import identity_transform # left, bottom, width, height as fractions of figure size axes([0.05, 0.05, .9, 0.9]) # plot in pixel coords with the identity transform plot([100,400], [200,300], transform=identity_transform()) axis('off') # turn off tick labeling show() See for more information on transforms. For some backends, you may want to subtract the y pixel coordinate from the figure height. You can get the pixel width and height of the current figure with w, h = gcf().get_width_height() See for help with figure methods. Good luck - when I get the users guide finished, some of these details will be more accessible. JDH Wayne> Thanks, Wayne> Wayne Wayne> ------------------------------------------------------- Wayne> This SF.Net email is sponsored by: YOU BE THE JUDGE. Be one Wayne> of 170 Project Admins to receive an Apple iPod Mini FREE Wayne> for your judgement on who ports your project to Linux PPC Wayne> the best. Sponsored by IBM. Deadline: Sept. 24. Go here: Wayne> Wayne> _______________________________________________ Wayne> Matplotlib-users mailing list Wayne> Matplotlib-users@... Wayne> I have been using matplotlib with TkInter (TkAgg backend) and it's really nice once I got the hang of it... I have two questions though, which I couldn't find in the manual. 1. The figure window has a pretty large border around it, that seems to expand as I enlarge the window. Is there a way to set this to, say, N pixels? 2. I have some x, y window coordinates I got via Tk event bindings. How can I translate these into data coordinates? Thanks, Wayne
http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=200409&viewday=19
CC-MAIN-2015-27
refinedweb
551
73.37
SyntaxWarning: name 'spam' is assigned to before global declaration September 2005 | Fredrik Lundh The most common reason for this error is that you’re using multiple global declarations in the same function. Consider this example: x = 0 def func(a, b, c): if a == b: global x x = 10 elif b == c: global x x = 20 If you run this in a recent version of Python, the compiler will issue a SyntaxWarning pointing to the beginning of the func function. Here’s the right way to write this: x = 0 def func(a, b, c): global x # <- here if a == b: x = 10 elif b == c: x = 20 For more background, see the Python Language Reference (dead link). Excerpts: “ A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.(dead link)” (if, while, for, and try does not introduce new blocks). “ If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. /…/ The global statement must precede all uses of the name.(dead link)” (throughout the entire block) “ The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. /…/ Names listed in a global statement must not be used in the same code block textually preceding that global statement.(dead link)“
http://www.effbot.org/zone/syntaxwarning-name-assigned-to-before-global-declaration.htm
CC-MAIN-2016-18
refinedweb
252
65.86
lp:~tux-style/eflxx/eflxx Branch merges Related bugs Related blueprints Branch information - Owner: - Andreas Volz - Status: - Development Import details This branch is an import of the Subversion branch from. Last successful import was on 2014-08-28. Recent revisions - 15. By cedric on 2013-01-04 trunk: remove use of AM_PROG_CC_STDC as AC_PROG_CC does it. Patch by Doug Newgard <email address hidden> - 13. By andreas on 2011-12-05 - some namespace problems - commit a workaround that prevents to delete(this) an object; need to do more debugging with this design. Something is wrong! - 8. By andreas on 2011-02-08 patch by mail: Von: <email address hidden> Betreff: patch for eflxx Datum: Tue, 8 Feb 2011 19:32:21 +0100 (CET) - 7. By andreas on 2011-01-01 - changed the design in Edjexx to return smart pointers - now local save the pointer and return a reference - if failure throw an exception - added some container memory helpers - changed the example code Branch metadata - Branch format: - Branch format 7 - Repository format: - Bazaar repository format 2a (needs bzr 1.16 or later)
https://code.launchpad.net/~tux-style/eflxx/eflxx
CC-MAIN-2019-39
refinedweb
180
63.49
#include "vgl_point_2d.h" #include <vgl/vgl_homg_point_2d.h> #include <vgl/vgl_line_2d.h> #include <vgl/vgl_homg_line_2d.h> #include <vcl_iostream.h> #include <vcl_iomanip.h> Go to the source code of this file. Definition in file vgl_point_2d.txx. template class vgl_point_2d<T >; \ template double cross_ratio(vgl_point_2d<T >const&, vgl_point_2d<T >const&, \ vgl_point_2d<T >const&, vgl_point_2d<T >const&); \ template vcl_ostream& operator<<(vcl_ostream&, const vgl_point_2d<T >&); \ template vcl_istream& operator>>(vcl_istream&, vgl_point_2d<T >&) Definition at line 87 of file vgl_point_2d.txx. Definition at line 3 of file vgl. Write "<vgl_point_2d x,y> " to stream. Write "<vgl_point_2d x,y>" to stream. Definition at line 48 of file vgl_point_2d.txx. Read x y from stream. Read from stream, possibly with formatting. Definition at line 81 of file vgl_point_2d.txx.
http://public.kitware.com/vxl/doc/release/core/vgl/html/vgl__point__2d_8txx.html
crawl-003
refinedweb
120
56.62
Forming Opinions April 20, 2005 "Tao has reality and evidence but no action or physical form." — Chuang Tzu Nobody looks forward to forms. Stop a person on the street and ask them what they think about forms and you'll get an earful. Curiously, though, in XML circles forms hold a great deal of interest. Admittedly, not the filling of forms per se, but the technology involved. Forms and XML have a special affinity. Both are embodiments of structured data exchange. Completing, say, a vacation request by writing on a blank sheet (or Word document) is far less efficient than filling out a form that asks the right questions. Getting rid of paper also proves popular with technology fans. The same holds for data exchange. The right rules and constraints, as embodied in XML syntax and specific vocabulary schemas, yield a vast improvement over an "anything goes" policy of interchange. Recently, the W3C published a new Member Submission: Web Forms 2.0, or WF2, based on a numbering system where the 1.0 version is the forms chapter of HTML 4.01 plus some DOM interfaces, which I collectively call "classic forms". To be clear, the Submission process is designed to "to propose technology or other ideas for consideration by the Team" — that is, W3C staffers. Unlike documents on the Recommendation track, Submission status doesn't imply any future course for the W3C or any endorsement of the content. It hasn't run the gauntlet of broad participation, review cycles for conformity with the W3C vision, accessibility, international-friendliness, web architecture integration, or Intellectual Property Rights claims — all the things that make official W3C specifications take so long. A Member Submission is just an idea in writing. WF2 isn't the first forms-related Submission to the W3C. XFDL from UWI (now PureEdge), XFA from JetForm (now Adobe), Form-based Device Input and Upload in HTML from Cisco, and User Agent Authentication Forms from Microsoft were also submitted back in the heady days of 1998 and 1999. These documents were not taken directly to the Recommendation track, vendor wishes notwithstanding, but did provide useful information for what eventually developed as a standard. A segment of the HTML working group considered the existing forms landscape and with W3C approval eventually developed the XForms 1.0 Recommendation. Exploring Forms To really get a feel for this new specification, I need to get my hands on some running code as a reference point. I'll start with some basic code and see how WF2 could help. The code is a simple client-side forms framework that I'm calling FormAttic. For full details beyond the brief summary here, I've set up a Wiki page, and am releasing the code under a Creative Commons license. The client I wrote this for is non-technical, and needs to be able to easily change things around. Thus the key feature of FormAttic is that it uses a declarative technique to record author intent, and is highly amenable to cut-and-paste modification. While it is based on an "executable definition" in JavaScript code, markup could easily be substituted in its place. In FormAttic, no special markup other than id attributes is needed on form controls. Here require and require_one_of are actually functions passed in to the configuration method configure_required, which establishes a context for the declarations. The first parameter of each is a message to be shown if the validation fails, and subsequent parameters name the controls that are getting marked as required. Notice that require_one_of is an instance of a general case of selecting one or more items from a list — something that requires extra scripting in classic HTML forms. This format is easily extended to cover additional form declarations, such as data types. The remainder of the library consists of initialization code, event handlers that get attached in the right places, and auxiliary functions. The first part of the WF2 document describes the goals and scope of the specification and relationships to existing materials at length. These will be covered in a later installment. For now, let's skip section 1 and get right into the next section — and the code. Extending Forms Section 2 starts off saying "At the heart of any form lies the form controls", which seems like a poor choice of words. Many behind-the-scenes structured data exchanges, including tasks currently done with XMLHTTP, can be implemented as a form without controls. The W3C lists current requirement for just this feature. In practice, the primary definition of a form is a model, often as part of a Model-View-Controller pattern; form controls are secondary. It's hard to tell whether this sentence is a minor oversight barely worth mentioning, or something hinting at deeper levels of underlying assumptions. Keep an eye on this as we proceed. One important class of changes in WF2 consists of newly added attributes that older clients will rightly ignore as unknown. Included in this list is the required attribute. For FormAttic, this could be implemented by a tiny adjustment to each required form control: Browsers that supported WF2 would "just work" with this change. But to support older browsers, an attached script would need to locate all such attributes and configure things such that the form won't submit until the required controls are satisfactorily filled. Essentially, this is what FormAttic script already does. The only difference is where the description of the required state is kept. FormAttic keeps it all in one place, and WF2 spreads it out across the form control markup. Which is better? The answer, of course, is "it depends". If the document markup is simple or fairly clean, there wouldn't be much difference between the two. On the other hand, in a document riddled with nested tables, font tags, and all manner of non-semantic tag soup, having everything in one place — generally towards the top of the document — is a big plus. Indeed, this was a major motivation for the design of FormAttic. Another difference is in the DOM interface. Under WF2 the required state of a form control would be available for inspection or modification under a validity property of the form control object. But again, for older browsers, the script would need to do feature detection and in cases where the property isn't implemented, go off and do its own thing. Less adroit scripters might even fall back into old habits of browser version sniffing. On the other hand, for browsers that lack a validity property, it would be possible with some care to implement one in client-side script. Forming an Opinion A solid case could be made for either all-in-one-place configuration, as in FormAttic, or spread-out-among-form-controls-configuration, as in WF2. The relative benefit of either option is outweighed by the benefit of working with whichever one has wider support in the overall community. My experience pushes me in the direction of keeping things separate, but I'm keeping an open mind and am willing to be persuaded. As things worked out, I wasn't involved in the production of WF2 to date. As I prepare these columns, I really am forming initial opinions of the technology. Next week, as I continue reviewing WF2, I will focus on the many things I like in the specification. Births, Deaths, and Marriages Topologi Difference Detective A US$29 utility for a broad range of XML-diff actions. Sun Java Streaming XML Parser An implementation of JSR, available at java.net. A first draft of the XML Pipeline specification from Orbeon. Relax NG seminar in Leuven, Belgium Relax NG session featuring Eric van der Vlist. XML Enhancements for Java 1.0 A compiler and runtime system to extend Java 1.4 with first-class support for XML. Documents and Data If you walk behind the wall, you see little trees growing behind some of the bricks. Serious QName advice from Rick Jelliffe. There should be some kind of award for finding prior-art this fast. This week's final word on namespaces.
http://www.xml.com/pub/a/2005/04/20/deviant.html
CC-MAIN-2017-13
refinedweb
1,355
63.09
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How can be tested/checked (in an Odoo python method) if there is any product (product_product) with a given ean13 code? I am populating EAN13 codes in a method and assigning them to a product_product item. However, I would like to test in advance if value already exists for any other product. How is tested in Odoo if there is any product_product with a given EAN13 value? Or, as a more general question, how do you check in Odoo if there is any product with a certain value (say FOOBAR) in a given field? You need to do a search on the model. Take an example def check_ean13(self, cr, uid, ean13, context=None): prod_count = self.pool.get('product.product').search(cr, uid, [('ean13','=', eanval)], count=True) if prod_count > 0: #product with the field ean13 and eanval exist else: #there is no product with that ean13 value But if I try that within a create method, 'cr' and 'uid' are not defined, right? Are they needed for the search method? That depends on what api style you are using my example was using old api that still works. But the same apply without cr and uid for the new api Thanks Axel, a nice chap posted this url for other question I made. That url helps to understand both APIs, strongly recommended for those of us who are struggling to understand the basics in Odoo. Hello, You can also apply unique constraint for ean13, in case if you don't want generate duplicate ean13. You can define unique constraint as below: _sql_constraints = [ ('ean_13_unique', 'unique (ean13)', 'The EAN13 code must be unique!') ] Or if you want to use python method, check it as below: @api.multi def check_ean13(self, ean13): for rec in self: prod_recs = self.search([('ean13', '=', rec.ean13), ('id', '=', rec.id)], count=True) if prod_recs > 0: #process if duplicate ean13 exists for another product else: #process if ean13 is unique. Hope this helps! Thanks, Kalpana Hemnani Thanks for the side note Kalpana. This is helpful information and I am sure it will be useful in the future, in this specific case I don't want to enforce it across all code, just in one method. Now I am wondering how to retrieve ean13 code given a product.product ID. I am sure is easy once you know where to look for it. As additional comment to this post, ean13 is part of product.product but it is populated in product.template. This is weird (IMHO) and there is even a note in the source code stating that ean13 population should be moved into product.product. So if you are modifying create method it is normal that ean13 is not present in product.product create, as it is handled by product.template create. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-can-be-tested-checked-in-an-odoo-python-method-if-there-is-any-product-product-product-with-a-given-ean13-code-88007
CC-MAIN-2018-17
refinedweb
518
72.97
26 March 2009 02:13 [Source: ICIS news] SINGAPORE (ICIS news)--Major purified terephthalic acid (PTA) producers in China have finalised their March price yuan (CNY) 150/tonne ($22/tonne) lower than the previous month due to poor demand in the downstream markets, buyers and sellers said on Thursday. Sources from Sinopec, BP (Zhuhai), Xiang Lu Petrochemical and Yisheng Petrochemical confirmed that their March price was CNY6,250/tonne delivered, lower than the February price of CNY6,400/tonne delivered. “Demand had overall been weaker as many polyester makers started to book losses this month,” said a source from Sinopec, the market leader. A fifth producer, Hualian Sunshine, had yet to announce its March price as of Thursday morning. “Our price should eventually be in line with the rest of the market but (it) will be announced later,” a company source said. The five producers sell more than half of the PTA produced in ?xml:namespace> ($1 = CNY6.83) Freya Tang of CBI China
http://www.icis.com/Articles/2009/03/26/9203350/chinese-pta-makers-finalise-lower-price-for-march.html
CC-MAIN-2014-35
refinedweb
164
68.81
The dictionary ** unpack operator When passing a dictionary to a function, the key-value pairs can be unpacked into keyword arguments in a function call where the dictionary keys match the parameter names of the function. If the function doesn't exactly specify the dictionary keys in the function's parameters, Python will throw a TypeError exception. Example Python def myFish(guppies, zebras, bettas): print(f'I have {guppies} guppy fish.') print(f'I have {zebras} zebra fish.') print(f'I have {bettas} betta fish.') fish = { 'guppies': 2, 'zebras' : 5, 'bettas': 10 } myFish(**fish) Output I have 2 guppy fish. I have 5 zebra fish. I have 10 betta fish. Notes The dictionary unpack ** operator is often used with a function that can take any number of parameters. This is one of the most complicated things about Python to wrap one's head around but is very useful for capturing any keyword arguments, not just passing dictionary key-value pairs as arguments. Example Python def myFish(**fish): for name, value in fish.items(): print(f'I have {value} {name}') fish = { 'guppies': 2, 'zebras' : 5, 'bettas': 10 } myFish(**fish) Output I have 2 guppies I have 5 zebras I have 10 bettas
https://reference.codeproject.com/python3/dictionaries/python-dictionary-unpack
CC-MAIN-2021-43
refinedweb
201
55.95
What I mean is that we have many security exceptions. However, this makes it possible for hackers and-virus makers to easily destroy/damage systems. However to avoid this, we need to analyze our source code and make sure that the application or software is safe and security level is as expected. This means that we have many types of security levels, like the network-attack, warnings in the application source code and problems like "bugs" and other. However, sometimes the security level does not just depend on the application, because sometimes or most of the time it actually depends on the network-security level. "Why?" Because like I said before, it is there where the attacks could begin. Microsoft® tools: Microsoft® Threat Analysis & Modeling v2.1, Microsoft® Baseline Security Analyzer 2.0, Microsoft® FxCop 3.0 and Microsoft® Visual Studio® 2005 Code Analysis tool are the most recommended tools by me, I mean all .NET and Windows developers should use these tools in order to secure their applications. Developers have used the stand-alone FxCop tool for years. Why? Because they needed to check assemblies for conformance with the .NET Framework Design. FxCop can also work together with Microsoft® Visual Studio Code Analysis tool which makes these tools very powerful. The Visual Studio® 2005 Code Analysis has rules. The developer could decide to use these rules to secure his application. However, this means that the developer can set the right security rules that he wants and next begin to analyze those areas ("those areas" - When we are deciding the rules, we are selecting between different choices, that can be from local-security to online) in his source code. After these areas have been analyzed, the developer can then easily navigate and go to the "unsecured" lines and fix those lines in the source code. The Code Analysis rules are great to use when you are building C++ application, I mean win32® & COM based applications which work both on Windows® XP and Windows® 2000. The Code analysis tool is the best tool if you want to analyze security in the source code. The analyzer can find errors and warnings, this helps the human by telling that in this line in this source code we have a security problem. The tool can find problems in the code, problems which the human eye cannot detect by just looking at the source code line-by-line. Visual C# one of Microsoft® own programming languages. Microsoft® introduced the Visual C# language in the year 2003 but the language was under development since 2001. However, Visual C# runs in safe mode, which provides more security and stability for the Windows application. The security policy is the configurable set of rules that the Common Runtime Language (CRL) follows when it actually decides what it will allow in the code. However, this means that the security policy configurable rules decide how the code should run. Building safer (or much more secured) applications with Microsoft® Visual Studio® 2005 has been a great progress for others and me. So, how do we create safer applications? Of course, we use the right tools for the job. However, in Visual Studio® 2005, we have something called "sign" the application. This means that we can see who the publisher is, and if you know, who the publisher is then you should feel unconfused. However, how do we deploy that information in the application. If you have provided publisher-information and if the certificate has been registered successfully then it can appear like this, “publisher: Coder24.com” and if no certificate has been registered then it would be like this: “publisher: unknown”. However, the first solution is to sign the application. A second solution is to use the Microsoft® Application Security Tools. In addition, it is great to have knowledge about application security, security vulnerability, viruses, hackers and ASCII plus some more. You may, ask why ASCII? Because you know passwords they sometimes use to say "long passwords are harder to crack". However, it is not the truth. The longer passwords may be easy to figure out. However, it is a little bit harder to crack a password, which looks like it is five characters long, but when you really look, it is actually 10 characters long. In this part, we are going to test analyze the code and set some security permissions for the application. However, the application which we are going to create will be a Visual C# Windows application. In the source code we would use Microsoft® Win32 class references and more. Next click on File and choose new, choose Project. Set the name of the application to “ ApplicationSecurity” and click on OK. Next, begin to write some code (Copy the code below): using Microsoft.Win32; namespace ApplicationSecurity { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Registry.LocalMachine.CreateSubKey ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); RegistryKey key = Registry.LocalMachine.OpenSubKey ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue("Security", "C:\\Windows\\System32\\cmd.exe", RegistryValueKind.String); } } } This is a sample example of code which tries to do something against the security permissions. The code-snippet above is an example of code which adds a new value to the Windows® registry. An explanation of the above source code example: The code above works like this, we have "added" the Microsoft.Win32 class through this reference, we also get access to the Windows® registry. However, this allows us to create registry values delete reg-values and even create custom sub-registry-folders. Take a look at the image below and you will see how to write the code. As we know, the security settings have not been set yet. We can test run the application, and see what would happen. If we look at figure 2, we would see that the registry value has been added to the Windows® Registry. However, if we delete the registry value and close the Windows® registry program, the registry-value will be removed, and we will return to Microsoft® Visual Studio® 2005 to follow the next steps below: Now you should get the security settings page as in the image below: Now, to calculate and analyze the security settings for your code, you should click on the button “Calculate permissions”. What Microsoft® Visual Studio® does is that the analyzer goes line-by-line and at the end of the code security analyzes, the results would then be decided by Microsoft® Visual Studio® and the application security settings. However the analysis is done, in order to take effect we need to re-build the application and start to debug it once again. We all have heard the above question, however, how logical is this question. Well we can make our applications secured, however, how much up-to-100% percent? I mean the application is safe because the source code is encrypted and cannot be decrypted. However, there is always a way to crack these solutions which we have today. For example the network attacks and the application security vulnerability and the application security holes are something that needs to be fixed. The solution should be to cover the security holes on an application. This is a big security deal today. However, what I mean is that we should all prepare ourselves on the Internet, what I mean is that if you are online, you always need to be secured. However, the same thing matters when we talk about application security. We need to cover and defend our applications, because else the crackers or hackers would infect the applications and write "plug-in" code. The plug-in would then begin to re-program the application to do other things than expected. However, a good example is Microsoft® Office Word 2007, if Microsoft® does not provide "security updates" (New security patch), who knows what would happen with Microsoft® Word 2007 nobody knows why it is important to analyze the applications and write clean and safe code. However, another example, we have Microsoft Word 2007 macros, which can be written with "VBScript". A Microsoft® Word 2007 macro can be designed as a type of virus, like "Word_macro@win32" virus infection. That can be a type of virus which can infect the Microsoft® Word 2007 software. Note: the name "Word_macro@win32" was something I just think of as an example. The Linux people always talked and wrote that the hacker comes and begins to hack a system, next the person who has been vulnerable should defend himself by "striking" back. The Microsoft® Baseline Security Analyzer (MBSA) is the greatest freeware tool made by Microsoft®. The MBSA is the greatest security tool, with the MBSA we can analyze Windows® Operating System (OS), and we can analyze Microsoft® Visual Studio® 2005 and other Microsoft® products. For example: We have done a run of MBSA-analysis and we have not checked the Microsoft® update site since a month, the MBSA will automatically display a report and in that report, we will find something wrong with Microsoft® Visual Studio® 2005. If we then view that report we will get information, and information about which updates are missing and how to download those, we also would get a direct link to download some of the setup updates which can been found on the Microsoft® download center site. As I said before, the application which is connected to certificate, and the publisher can be known would make the application much more secure and the application would be much more trusted. However, the application which has a known publisher can make the situation more comfortable than an application which does not have a known publisher. If we take for example: I make my own software, somebody downloads it and saves the *.exe as setup file on the desktop, next he "double-clicks" on the setup.exe and gets a message question from Internet Explorer where we can see information such as publisher name and other. If the user knows, the publisher name it would be much easier for the user to know which company has developed and released the software and this would make that software trustful. However, in some Windows 2003 Server configurations, maybe the administrators have done a configuration that requires that the software is connected to a certificate and that it must provide publisher name and other information about that software. We have tested to build a website with normal HyperText Markup Language (HTML) code, and add some link tags which we have linked to the applicationsecurity.exe. As soon as we have built and saved the website as *.html on the desktop, we will open it with Internet Explorer 7 and test to click on the link to run the applicationsecurity.exe and see which information we would get. We can see in the image above that the publisher is unknown, so if we want to show who the publisher is then we must register a digital certificate which can help to display the publisher information. You can test the application certificate and application online download by using Internet Information Service (IIS) on Windows® Vista. We have the latest version called IIS 7.0 that is much better than IIS 6.0 Manager for Windows® XP. The Microsoft® Thread Analysis & Modeling tool is good to use when you want to analyze the application security. Microsoft® Thread Analysis is a tool which is a little bit hard to use first time. You can use the MSTAM 2.1 to analyze the application or make an application security plan. Making the security globally may sound hard or it is hard, why? Because you cannot make all systems 100% secured world-wide because every time there is somebody that cracks the systems and sends the information to others (makes his discover public). People that crack the systems are called "hackers"; there are hackers that get paid for hacking and protecting a company’s privacy and information. The Internet is too big. If you want to secure all the computers globally you cannot, people today do not understand how important it is to protect the information which you have on the computer. Patching a system and fixing both bugs and security-bugs in the Operating System (OS) is a good thing, however, we should really make it better than the way of patching which we are using today. However, what I mean is that the way we are making bug-fix patches or security-fix patches today is bad, why? Because we should analyze what is happening on the system source code and make just patches which change and update those areas which are under emergency to be fixed. It would be great if we could build problem-free or bug-free applications before we ship or release them. However, we should do the following processes: We have a company which makes software’s and distributes systems and does other things. The company can use this solution, they could make a system which works like this: they have one team called the Software Engineer Analyzers (SEA), the SEA-team has tasks, like: they are going to test all type of new software and make reports with information to other teams. The software engineers who are the programmers then re-write code lines in the software source code, and then they re-compile the software and send the application or the software to the SEA-team once. However, they keep doing this until the software is stabilized and secured enough. Another great thing here is that we can get "feedback" from our customers. Getting feedback from customers can help to improve better application stability which makes the software run better. Take a look at this XSS vulnerability. The python language is an example of scripting code. There are other types of XSS detect tools which could be found on the internet, some are freeware and other shareware. <script>alert(document.cookie);</script> A sample JavaScript works like XSS (Note: I haven't tested it yet). Best Practice Analyzer (BPA) for ASP.NET is a great tool which can be used to analyze ASP.NET web-applications. The tool helps to find unsecured areas and provides information about the servers, like if the server information is encrypted or not. We can see in the image above the report which has been generated is telling us that the root machine configuration string is not encrypted, and that the strings should be encrypted. This is a good example of tools which can help solve the security problems easily. The tool is freeware and can be downloaded from Microsoft® Downloads Center website. The DevPartner SecurityChecker® is a good tool, why? Because the tool helps you to analyze the code and fix security problems. The tool works well with ASP.NET web application. DevPartner includes a SecurityChecker® component, which scans ASP.NET application source code to find known security problems. When the tool finds problems, it tries to help by providing information about how to solve the security problems in the code. You can see in the image above, we have checked some checkboxes with the text Compile-time, Run-time, Integrity and Check only the pages that I visit. After that we have set the specified security settings. You click on the button “Start Analysis” and the tool will analyze the whole ASP.NET website and it will also make reports. The tool is not free, it costs and you can buy it at Compuware website. There is a new version available online it is the DevPartner SecurityChecker® 2.0. When you deploy your application, you must test it on about three computers and maybe deploy it as a "beta" version to just see how many problems could be found. You can also use IIS 7.0 or 6.0 to deploy the application over the Internet and see how many people will download it and test the beta. You can make a directory where you link the files or add the files inside an IIS root-directory and then you set a domain name. You can also use File Transfer Protocol (FTP) or Hypertext Transfer Protocol (HTTP). Give it a try. Run Visual Studio® and build C# applications, go to the project properties set the security rules and settings. Run the application and see what is happening and how the security works on the application. It can be hard to work with the application security first time, however, you will learn more and understand the security in the applications when you have read books and articles online. Good luck with the application security testing and analysis. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/security/security.aspx
crawl-002
refinedweb
2,787
53.92
19 April 2012 14:49 [Source: ICIS news] (releads and updates throughout) By Nigel Davis LONDON (ICIS)--Dow Chemical will build its new world-scale ethylene plant at its largest production site in Freeport, Texas, (Dow Texas Operations) the US-headquartered, broadly-based chemicals producer said on Thursday. The cracker is the key project in the company’s plan to connect its US operations to cost-advantaged gas feedstock coming from the further exploitation of US shale gas deposits. “For the first time in over a decade, US natural gas prices are affordable and relatively stable, attracting new industry investments and growth and putting us on the threshold of an American manufacturing resurgence,” Dow CEO Andrew Liveris said. “Constructing this new ethylene cracker at Dow Texas Operations will create a long-term advantage for our downstream businesses and for our company as a whole, and the benefits will accrue not only to Dow but to the state and national economy.” Dow said that the cracker project was on-track for start-up in 2017 and that it continues to develop feedstock supply arrangements for the new asset. Dow said a year ago that it was developing a plan to use cost-advantaged gas feedstocks from shale to strengthen the competitiveness of many of its downstream businesses. "Our plan is to further integrate Dow’s businesses with the advantaged feedstocks, based on shale gas deposits and long-term ethane and propane supply agreements," the company’s then head of corporate development and hydrocarbons, Jim Fitterling, said at the time. "These actions will strengthen the competitiveness of our Performance Plastics, Performance Products and Advanced Materials businesses, for example the Elastomers product family and the full Acrylates chain, as we continue to capture growth in the Americas," he added. Under that plan, Dow is in the process of restarting a cracker near Hahnville in Louisiana. It is due on-stream by the end of this year. In March 2012, the company said that capital had been authorised and detailed engineering finalised for a world scale propane dehydrogenation (PDH) unit to be constructed in Freeport. Long lead-time equipment for the project is being purchased and the plant is scheduled for 2015 start up. In December 2011, Dow signed a technology agreement with Honeywell’s UOP, to license that company’s C3 Oleflex technology to produce on-purpose propylene from propane. The plant would be able to produce 750,000 tonnes/year of polymer grade propylene.. Dow is the largest consumer of propylene in North America and the region’s largest producer of ethylene. It has sought to acquire supplies of ethane and propane for its olefins projects through a variety of supply agreements to tap into the increased availability of the natural gas liquids (NGLs) from deposits such as Eagle Ford in Texas and the Marcellus shale in Pennsylvania. Dow said that 2,000 workers would be employed on the new plant at its construction peak. This and other projects will employ 4,800 at the peak and support more than 35,000 jobs in the broader ?xml:namespace> Fitterling said on Thursday that the company would invest $4bn (€3bn) overall to grow its ethylene and propylene capabilities in the US Gulf Coast region.Graeme Pat
http://www.icis.com/Articles/2012/04/19/9551996/US-Dow-to-build-world-scale-cracker-in-Freeport-Texas.html
CC-MAIN-2014-35
refinedweb
543
52.33
When described, feature classes and tables have a fields property that returns a list of Field objects and an indexes property that returns a list of Index objects. Each field or index object has a number of properties that can be used to explore the object. Alternatively, the ListFields and ListIndexes functions can be used to create the same lists. The following example shows how to create a field list and loop through the contents to find a specific field. import arcpy fc = 'D:/St_Johns/data.gdb/roads' # Get a list of field objects fields = arcpy.ListFields(fc, 'Flag') for field in fields: # Check the field name, perform a calculation when finding the field 'Flag' if field.name == 'Flag': # Set the value for the field and exit loop arcpy.CalculateField_management(fc, 'Flag', '1') break The properties of the field and index objects are listed below: Tip: ListFields and ListIndexes can be used to limit the results based on name and type.
https://pro.arcgis.com/en/pro-app/latest/arcpy/get-started/fields-and-indexes.htm
CC-MAIN-2021-21
refinedweb
161
62.78
09 June 2011 09:51 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The plant is expected to be restarted around 19 July, the source added. The company may have to source overseas for 1,000-2,000 tonnes of MMA to meet domestic demand as a result of the planned maintenance, he said. However, since the supply of MMA in DMMA plans to shut its 50,000 tonne/year polymethyl methacrylate (PMMA) plant at the same site for two weeks of maintenance in August, but exact dates are not confirmed, the source said. The capacity of the PMMA plant was raised from 40,000 tonnes/year to 50,000 tonnes/year in January after a debottlenecking exercise. DMMA is a joint venture between For more on methyl methacrylate and polymethyl
http://www.icis.com/Articles/2011/06/09/9467710/South-Koreas-Daesan-shuts-MMA-plant-for-maintenance.html
CC-MAIN-2014-10
refinedweb
130
68.4
datalib 0.0.0 A library to work with time series data from xls This is a package/library in python to work with time series data from xls file. This is being developed under the project AMBHAS. Installing datalib Installing datalib can be done by downloading source file (datalib--<version>.tar.gz), and after unpacking issuing the command: python setup.py install This requires the usual Distutils options available. Or, download the datalib--<version>.tar.gz file and issue the command: pip /path/to/datalib--<version>.tar.gz Or, directly using the pip: pip install datalib Usage Import required modules: import numpy as np from datalib import time_data Read the time series data: data = time_data('/pata/to/file.xls') year = data.get('year') month = data.get('month') gw_observed = 839-data.get('gw') Changelog 0.0.0 (July: time series,xls - Categories - Package Index Owner: Sat.Tomer - DOAP record: datalib-0.0.0.xml
http://pypi.python.org/pypi/datalib/0.0.0
crawl-003
refinedweb
154
54.29
Understanding Scope It’s now time to have a look at what we’re doing when we declare a variable with my() . The truth, as we’ve briefly glimpsed it, is that Perl has two types of variable. One type is the global variable (or package variable), which can be accessed anywhere in the program, and the second type is the lexical variable (or local variable), which we declare with my() . Global Variables All variables in the program are global by default. Consider this code: #!/usr/bin/perl -w $x = 10; $x is a global variable. It is available in every subroutine in the program. For instance, here is a program that accesses a global variable: #!/usr/bin/perl -w # global1.pl $x = 10; access_global(); sub access_global { print "value of $x: $xn"; } Executing this code shows that $x is accessible in access_global() : $ perl global1.pl value of $x: 10 $ Since variables within functions are global by default, functions can modify variables as shown in this program: #!/usr/bin/perl -w # global2.pl $x = 10; print "before: $xn"; change_global(); print "after: $xn"; sub change_global { $x = 20; print "in change_global(): $xn"; } This program assigns the global variable $x the value 10 and then prints that value. Then, change_global() is invoked. It assigns $x the value 20—this accesses the global variable $x —and then prints its value. Then in the main part of the code, after the function is called, the global $x is printed with its new value—20. Here we see the proof: $ perl global2.pl before: 10 in change_global(): 20 after: 20 $ The fact that Perl function variables are global by default is itself not a bad thing, unless of course you are not expecting it. If you are not expecting it, then accidentally overwriting global variables can cause hard-to-find bugs. If you are expecting it, you will probably want to make function arguments local. {mospagebreak title=Introduction to Packages} When we start programming, we’re in a package called main . A package is a collection of vari ables that is separate from another package. Let’s say we have two packages: A and B. Each package can have its own variable named $x , and those two $x variables are completely distinct. If we assign $x , as we did previously in global2.pl , then we create a package variable $x in package main (the main package is the default package). Perl knows it by its full name, $main::x —the variable $x in the main package—but because we’re in the main package when we make the assignment, we can just call it by its short name, $x . It’s like the phone system— you don’t have to dial the area code when you call someone in the same area as you.1 1. Depending on your location, of course. Nowadays, with so many area codes in a metropolitan area, to call across the street often requires dialing 10 digits . . . We can create a variable in another package by using a fully qualified name. Instead of the main package, we can have a package called Fred . Here we’ll store all of Fred’s variables and subroutines. So, to get at the $name variable in package Fred , we say $Fred::name , like this: $x = 10 ; $Fred::name = "Fred Flintstone"; The fact that it’s in a different package doesn’t mean we can’t get at it. Remember that these are global variables, available from anywhere in our program. All packages do is give us a way of subdividing the namespace. What do we mean by “subdividing the namespace”? Well, the namespace is the set of names we can give our variables. Without packages, we could only have one $name . What packages do is help us make $name in package Fred different to $name in package Barney and $name in package main . #!/usr/bin/perl -w # globals1.pl $main::name = "Your Name Here"; $Fred::name = "Fred Flintstone"; $Barney::name = "Barney Rubble"; print "$name in package main is $namen"; print "$name in package Fred is $Fred::namen"; print "$name in package Barney is $Barney::namen"; $ perl globals1.pl $name in package main is Your Name Here $name in package Fred is Fred Flintstone $name in package Barney is Barney Rubble $ You can change what package you’re currently working in with the aptly named package operator. We could write the preceding like this: #!/usr/bin/perl -w # globals2.pl $main::name = "Your Name Here"; $Fred::name = "Fred Flintstone"; $Barney::name = "Barney Rubble"; package Fred; print "$name in package Fred is $namen"; package Barney; print "$name in package Barney is $namen"; package main; When use strict is in force, it makes us use the full names for our package variables. If we try and say this: #!/usr/bin/perl -w # strict1.pl use strict; $x = 10; print $x; Perl will give us an error—global symbol $x requires an explicit package name. The package name it’s looking for is main , and it wants us to say $main::x . #!/usr/bin/perl -w # strict2.pl use strict; $main::x = 10; print $main::x, "n"; Global variables can be accessed and altered at any time by any subroutine or assignment that you care to apply to them. Of course, this is handy if you want to store a value—for instance, the user’s name—and be able to get it anywhere. It’s also an absolute pain in the neck when it comes to subroutines. Here’s why: $a = 25; $b = some_sub(10); print $a; Looks innocent, doesn’t it? Looks like we should see the answer 25. But what happens if some_sub() uses and changes the global $a ? Any variable anywhere in your program can be wiped out by another part of your program—we call this action at a distance, and it gets real spooky to debug. Packages alleviate the problem, but to make sure that we never get into this mess, we have to ensure that every variable in our program has a different name. In small programs, that’s feasible, but in huge team efforts, it’s a nightmare. It’s far clearer to be able to restrict the possible effect of a variable to a certain area of code, and that’s exactly what lexical variables do.
http://www.devshed.com/c/a/perl/understanding-scope-and-packages-in-perl/1/
CC-MAIN-2014-35
refinedweb
1,055
72.05
The Changelog – Episode #232 Homebrew and Swift with Max Howell Guests.. GoCD – GoCD is an on-premise open source continuous delivery server created by ThoughtWorks that lets you automate and streamline your build-test-release cycle for reliable, continuous delivery of your product. Notes & Links - Max was on The Changelog #35 way back in September, 2010 - Max’s latest open source project PromiseKit - The BBC Micro was the first computer Max used - Amarok - a powerful music player for Linux, Unix and Windows - qt - cross-platform development - Last.fm - bring together your favourite music services - Scrobble - “The foundation of the modern world is developer tools.” - The Changelog #223: Homebrew and Package Management with Mike McQuaid - The tweet heard aroud the world with 6,825+ retweets — “Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f**k off.” - Swift Package Manager - BBC BASIC programming language - QBasic (Quick Beginners All purpose Symbolic Instruction Code) is an IDE and interpreter for a variety of the BASIC programming language - Max’s new thing — mixmsg lets you make mixtapes with friends directly in iMessage. - Max’s new project — Growler is planned for Homebrew, but he was hush hush about what it will do Transcript Welcome back everyone, this is The Changelog and I am your host, Adam Stacoviak. This is episode #232, and today Jerod and I are talking to Max Howell, famously known as the creator of Homebrew. It has been more than six years since Max has been on the show. We talked about his tweet that was heard around the world from that time he interviewed with Google but didn’t get accepted, the creation of Homebrew, the naming process, as well as the difficulty of letting go. We also talked about his passion for the Swift programming language and his work on Swift Package Manger while at Apple. We have three sponsors: Code School, Toptal and our friends at GoCD. Alright, we’re back with Max Howell. Max… Wow, it’s been a long time. Episode #35, Jerod - this is basically a lifetime ago. 2010… Jeez! Six years. What’s wrong with us? Max, why didn’t we have you back on sooner? Who knows? You have to ask yourselves… I would just say maybe you were busy and we were busy… Everybody’s busy. I certainly have been. I’ve been very busy. Well, thanks so much for joining us. Max, as many know, you are the creator of Homebrew, amongst other open source projects, of course, that one being a massive hit, and one used daily by thousands, perhaps millions – millions might be a stretch… Thousands around the world. I’d say millions. It’s millions. Is it millions? I’d say millions, for sure. Yeah. Oh, man… I’m not even stretching. It’s difficult to estimate precisely, but it’s definitely millions. How do you know that number? Is that a guess, or is that somewhat educated? Well, they’ve got the analytics now. It’s a guess, but I can look at the GitHub logistics and see the amount of clones, and we also have other statistics now. It can’t be precise, but I just can’t see how it could be less than millions at this point. Every developer uses a Mac pretty much… Right. Well, we’ll definitely go back and touch base on Homebrew’s creation, but let’s go even further back… We like to find out the origin stories of hackers that everybody looks up to, and you, sir, are one of them. Tell us how you got started, give us a little bit of your background and where you’re coming from, and what really got you into software and open source. Well, way back when I was six we had a BBC Micro. It was a common computer in England of the time, or the U.K., hence the BBC part. I don’t know the exact history about why it was branded BBC, but I assume that they sponsored its development, or something… And my dad started teaching me programming, and initially I just made awful games, like you’re fighting a monster, pick your weapon: a sword, a stick, or colorful language… [laughter] [00:04:00.16] That was good fun, but it was always a hobby for me, I never considered it for a career right up until the end of college, which I did chemistry for. The only reason I got back into programming – I’d been doing it on and off all through my teen years, mostly making toys or little tools… I made this little clock for Windows that when you clicked it, it moved to the opposite corner of the screen… Things like that. …back when Windows didn’t have the time in the corner. Obviously, when they added that it made less sense. And I had a great Y2K bug; it turned out that little clock I made. After 2000 I tried building it out again and it claimed like it was the 15th century, or something… Couldn’t handle it. Wow… So for those who may not actually remember that, maybe those born after 2000, what was that? Yeah, give us the Y2K rundown, that would be good. Everyone was terrified of the year 2000 in the software industry because - if you can believe it - 10, 20 years before that bytes were extremely valuable; we had hardly any RAM. I remember my first PC had 2 MB I think, and that was a pretty good one. So rather than store the full date, we optimized by destroying the last two digits. A pretty minor optimization, but at the time it seemed worth it; as a result, when 2000 started rearing its head, date software would typically think it was the 19th century, or something like that. It depended on how it was written, what exactly it did with those two digits. My step dad at the time was working in software and he made a fortune going around banks, investigating how their software would handle the Y2K transition. It became a media hysteria of course, as well. Everyone thought that the world had a 50/50 chance of falling into chaos on 1st January 2000. Nothing really happened in the end, I guess… It sure was a different world then though, right? That world then was so uneducated about what software was capable of… It was a different world; no one had a smartphone in their pocket, no one really knew what an application was… It was just such an ignorant society at that time to technology. I think, to be fair, our software was even flakier back then, if you can believe it. People had very little confidence that software could handle big events, but then it turned out that everything was fine. So either the contractors made it to every last line of code and updated their date implementations, or it was all for naught and it was gonna be okay anyways, and perhaps people were profiteering – or what’s the right word for making boatloads of money based off of fear…? Probably a little bit of both. Yeah, most likely both. I’m sure it would have been bad if the banks had problems, but they were the ones who were most interested in correcting it, and maybe some minor, less important industries had problems, but it didn’t cause the end of the world, certainly. But date and time is still a problem, of course… You hear regularly about companies that have to turn their databases off at the daylight savings time because they can’t handle being at the same time twice in the same day, and things like that. That’s a whole new [unintelligible 00:07:33.13] time. Oh, man… Let’s not get started on time, we’ll never find our way back out again. But funny that it did actually affect your Windows clock app. You were not Y2K compliant. [00:07:47.15] I was not. Didn’t even think about it, which is a common thing with software development, of course. Anticipating everything is hard. Yeah, so I did a chemistry degree and I have a masters in chemistry as it happens. But in my third year… Because in the U.K. most courses are only three years for university, I did a four-year course with a year in the industry. So my third year I went to work at Kodak in London - which was a bad choice; I should have picked one of the beautiful chemistry labs in the middle of the British countryside. It probably would have changed my life if I’d done that, but I went to Harrow in London, which is possibly the most disgusting place in the entire world, and discovered that chemistry is very boring, actually… Really, really boring. [laughter] So after that four months of this year I was quite depressed and I decided I’d install Linux on my computer and get into making apps, although no one really called them apps at the time. So like programs, or… Programs, yeah. Yeah. So I started working on KDE, which is still around, a Linux desktop environment. I really enjoyed the sense of community, and making things that other people enjoyed using, so I almost got fired from Kodak, even though they would rarely do such a thing with these interns that they had. Then I went back to university, spent most of the year working on two apps. The first was Filelight, which was the first thing I ever made, really. It’s like DiskDaisy on Mac, it uses the same idea of representing the files and folders concentrically in pie charts that nest inside each other, which really helped – again, back then we only had so much disk space, so you really needed to figure out who was using what and delete files regularly. And Amarok, which was a music player - that was my first proper open source project. We were working as a team of three or four of us. It became pretty popular, because there weren’t any good music players on Linux, and we were doing things that other people hadn’t really considered at the time as well, like showing the Wikipedia information for the artist you were listening to. I think we invented that… So I almost failed my chemistry degree. It was close, very close. I basically started going to classes and somehow managed to cram and get the minimum grade required, which was just as well, because I’d signed up to do a PhD, so I didn’t know what to do with myself. I was doing computational chemistry for my dissertation, so the professor I was working for told me that he was mathematical, and I was doing quite well at that, but I didn’t get the grade required to stay there and do the PhD, so I had to go home. I just kept working on open source basically, until I got a job at Last.fm in London because of Amarok, because we were using Last.fm and scrobbling quite heavily. I went there and that’s what got me into the industry, without a computer science degree or anything similar. So when you were on the Changelog the last time, which was 14th September – at least the publish date was 14th September 2010, were you at Last.fm then? No, I had been at TweetDeck at that point since January 2010. I was at Last.fm two and a half years, which is the longest I’ve ever been at a single company. But it was a lot of fun at Last.fm, and they had the right attitude towards startups, and open source, and things. They got acquired by CBS in 2007, and it gradually degraded after that. All my friends left, and all the really talented people had left, so I moved on and I went to TweetDeck, where I built the Android app and redid their iPhone app just before Twitter acquired them… Which happened after the last episode that we did together. [00:11:59.17] So you should work at companies, because they get acquired. Basically, it seems to be that way. I like small companies. I like having lots of hats, and learning new skills and applying them. Well, something I picked up was that, Jerod, like many hackers who come on this show, their beginnings tend to be in games to some degree, but something that Max had said was the community. He really enjoyed the community part of it, so it would make sense that you prefer smaller companies because it’s far more of a community feel in a smaller company, because you can’t hide… You have to sort of face the demons that sort of wait in the hallways, they’re just there. You tend to be more civil potentially even, or maybe not… Yeah, I agree. There’s something insulating about big companies, and it becomes so much more political, and I can’t stand that. I want to get things done, I don’t want to have to persuade people to let me get things done. Yeah. Bureaucracy is a no fun battle, that’s for sure, especially if you’re like someone like you who has the ability to, and having the track record of things like Homebrew, that millions of software developers use every day… Millions… Billions… [laughter] Did you say ‘billions’, Jerod? We’ll have to check the stats. Okay… But lots of people use what you make, so if you’re that kind of person, why put reins on you? Yeah, well, I hate to be arrogant in that respect, but I feel that I get so much less done when I’ve got barriers in place. I don’t wanna be that kind of person, but it turns out that I am… I really really hope that doesn’t. So Amarok was your first foray into open source, and that was just before Last.fm… Is that right? I started working at Amarok in probably 2004, and then I joined Last.fm in 2007. I’m walking down memory lane with you Max, because I ran KDE for a few months in college… I only lasted a few months and then I had to go back to Gnome for some reason. Who knows… Probably something did work. But I was using Amarok and I have fond memories of Last.fm, of course scrobbling, I think, because Last.fm’s big thing was scrobbling, and I was getting my… I think my iTunes was scrobbling the Last.fm, which would post to my WordPress… You’re pulling me along down memory lane as you go from place to place. TweetDeck - I’ve got no ties there, but you had me at Last.fm for sure. Where did Homebrew begin? Homebrew began probably right at the end of Last.fm. Because at Last.fm we were making cross-platform software - I had to scrobble in every platform - and managing the dependencies that we had, which there were a few (not many), relative to what people have nowadays [unintelligible 00:15:00.03] but there wasn’t really any good way of doing that, so Homebrew was a kind of response to wanting a system that could be cross-platform and would allow me as a developer to control the dependencies on my system in multiple places. It’s funny that these features do exist, but are not very used, they’re not why it’s successful at this point, but it is something it can do. You can install multiple instances of Homebrew, you just have to check it out at different places, and it will install to those places, the cross-platform as well as in Ruby. There is now a well-maintained Linux port, but the original goals was that it could be. So I started building it at the end of Last.fm, and then when I left, I left in order to make iPhones apps, because it was right at the beginning of… [00:15:52.29] Yeah… It was 2009, so the App Store had been around for about a year, and the stories of people making a million dollars out like Doodle Jump and things like that were inspiring. And I had the experience of iPhone development, because at Last.fm we’d made an Android app, we’d made an iPhone app and a Blackberry app. Wow, Blackberry… The Blackberry app was awful… They did have an SDK, it was just terrible. I don’t think that lasted very long in the end. What language would you use for Blackberry? It was C++. Okay. Which… Yeah. Well, [unintelligible 00:16:31.26] C++, I never wanna do again certainly… But at Last.fm we used Qt, which is a C++ cross-platform toolkit. Qt was very nicely designed using a subset of C++ like any good frameworks tends to, because there’s just too much of it. It had a very similar to Cocoa kind of way of working, Cocoa being the name of Apple’s frameworks for Objective-C and now Swift. So yeah, I had the experience so I thought I’d quit and make apps and make millions of dollars and be very happy, but the problem was I kept working on Homebrew because I needed it for various other things, and once I put it on GitHub, people started to notice it. One day this guy, I think his name is Simon Willison - I forget… He used to be Twitter famous, so I’m not sure if he is anymore, but he posted a super-user question about how to manage dependencies on this Mac, so I answered with “Oh, I made this new project”, and I explained a lot of the rationale behind it. That got it noticed by Josh Peek who I think is at GitHub now; he was at 37signals. So he tweeted when he upgrades to Leopard, which was Mac’s 10.5, he would install Homebrew, and that got me my first hundred forks, and then it just kept going up and up. Then it became addicting, because every day I’d wake up and there was a bunch of – pull requests didn’t exist at that point… It was just tickets from people saying, “Oh, I made this formula, it’s in my fork. Won’t you merge it?”, so I’d merge it. From the start, I designed Homebrew to be really simple to contribute to, because I knew I didn’t wanna write all the formula. One of my issues with MacPorts it seemed opaque, it seemed really difficult to figure out how to contribute, so I designed it so that there were commands on the command line to help you see the formulae, contribute to the formulae, edit them… It was all built on Git, that was the update mechanism, so you could just push straight away with your edits. That was the key really to its success. I think it was just the understanding about how people don’t really like contributing to open source because they don’t know how, so you’ve gotta build that in as like an easy way for them to just push back their contributions. I designed the formulae themselves to be very readable, so you could open any formula and understand how to make your own. It was always a part of the design I went for. Another aspect of Homebrew that I recall making it popular, which, interestingly, we just had Mike McQuaid on the show back in episode #223 talking about Homebrew’s 1.0 release and the current core/primary maintainer, and he has inherited a lot from you, he has inherited the naming convention, and I think Homebrew as a name and then the metaphor of the naming convention, applying formula, and kegs and cellars and all these things had a certain attractiveness… It marketed itself, in a certain way. Yeah… Maybe you talked about this in #35, but six years ago, none of us remember - what was the impetus behind the naming convention of Homebrew and this whole metaphor you came up with? How did that come about? [00:20:04.29] Well, I love names. I mean, I hate names. [laughter] I love/hate names. It’s a love/hate relationship. So often they’re terrible. People often don’t think carefully about their names, especially in programming for classes and functions, and they’re so important. I’m a big believer that you don’t need to comment if the name is good and the responsibility boundary is clear; I feel if I need a comment on this function or class or whatever, that I haven’t named it correctly. So I’ve always been very keen to pick the right names for things, but I also understand the marketing importance of the name for an open source project. If you call it Package Manager X, no one’s gonna talk about it. You need something inspiring. So I was just looking for names at Last.fm while I was there, near the end. I was like, “I want a theme. I want the name to then lead to other names in use in this product”, and one of my co-workers said, “Well, it should be a beer theme obviously, Max”, because a startup, community - obviously, there’s quite a bit of drink there. And London… There’s so much drinking in London. That’s one of the things my wife, who is American, said about London. It’s just like, you get a job in London, and then in the evening you go to the pub. Every day, you go to the pub. And that’s true, basically. Not everyone goes every day, but someone in your company is going every day. It might not be the same person every day, but you know you can go to the pub across the road from the office and there will be someone you know there. It’s one of the nice things about pubs in Britain - they’re really places you can go to meet people you know, and it’s friendly, and it doesn’t have the stigma that it does in America. In America you have bars, and probably there’s some guy who’s there every day and he’s a loser, and he’s a drunk. Pubs, in Britain, are like where you go. It’s true. He’s there right now, actually. [laughs] He probably is. But well, London overdoes it, honestly. I think it’s important to draw a distinction too, because what you call pub is probably a cool place to hang out, watch sports and see friends that you may have not seen in a while, whereas my version of it might be more like a bar, like a small town bar… Which is similar, but not the same. Yeah, a pub is a lot more family-friendly, I guess would be one way of describing it. They serve good food even. Yeah. And hopefully it’s owned by the same family for a while, although that’s less and less the case, sadly. So yeah, they’re a lot more savory, but still, London overdoes it, it really does. So at the time I was 28, so there was a lot of beer in my life; to be fair, I drank British beer, which is usually 3% - 3.5%, so… It seemed like a great idea. Then I thought, “Well, Homebrew is a great name for it.” At the time I didn’t think about the Apple connotation, I was just thinking about how I wanted it to feel like a platform that you could create your own packages for, and customize them the way you wanted them to be customized, so it seemed like a great name, and it just lead to the other names. I thought carefully about each one. There was a while that it wasn’t gonna be ‘formula’, it was gonna be ‘recipe’, because they’re not really formulae in the homebrewing beer space, but ‘formula’ was more unique. And kegs and cellars… Kegs are stored in racks, technically, but that’s not really something people know. It’s fun, it worked out really well. I hope I didn’t contribute somewhat to the silly naming systems that seem to go on in open source nowadays. [00:24:12.18] People seem to name their things completely randomly nowadays, just to have a distinctive name. I saw an image library the other day called King Fischer; why is it called King Fischer? It doesn’t make any sense. Yeah. It’s gotten to the point where it’s more akin to domain names where the real estate is running out and there’s namespace clashes… Many times that we see names that are exactly the same as another project in a slightly different ecosystem or language, and like you said, people are trying to draw more and more attention to their open source projects because there are more projects and so it’s harder to get noticed… So you start taking the vowels out, you know? [laughter] You’re doing what you can do, but… Yeah, you’re right, that’s a more reasonable explanation for why it’s happening. Still, a name needs to have some sense of purpose, so you have an idea about what it is. Admittedly, people always say “Well, King Fischer is an image library” or whatever, but there’s so many to remember… You need a mnemonic for your own brain to remember what it’s about, and if the name tells you it as well, then you’ll remember it properly. Like Package Manager X. [laughter[ Go literal. I guess the only question I have for you on the naming front… So sure, you enjoyed the pubs and beer, it’s where you’re from, it’s part of your culture to appreciate that, but at what point was it like, “Yes, this…” Did you start applying it? Did you start thinking about formula, keg, and all the permutations of the naming that could eventually come out and you’re like, “Okay, this does fit”, and how long did it get you to be like, “Okay, it’s a perfect fit. Let’s call it Homebrew”? After the suggestion, a couple of days. Then I had most of the names done within a week or so. I find it very important to have the names, for some reason. It really helps me to identify the product clearly in my head. Sometimes I know an app I wanna build, or an idea for a tool, but I don’t start until I’ve come up with a name. I can’t start until I’ve come up with a name, although partly that might be because often I’m using Xcode, and Xcode’s name refactoring tools are abysmal. This is a good place to pause real quick… We’ve got a break we’ll take here, and when we come back we’ll dive a bit deeper into Homebrew and other fun stuff with Max. We’ll be right back. Alright, we’re back with Max Howell and we’re talking about Homebrew. Jerod, we love/hate names, and Max, you said it best, you love, and then you said you hate names. Homebrew is a pretty good name, and then you sat down and you thought about the architecture of Homebrew and how it mapped out and all these different things… That’s a pretty deliberate choice on a name for one, but then also it’s a kind of like sit down and think about it and how it would all play out, so tell us a bit more about that. Well, like I say, good names are so great, that’s why I love… Because they allow you to understand the thing. That’s what I think a lot of programmers don’t understand about names - understanding of what the thing is is in the name. Homebrew into this wonderful set of metaphors for how the architecture fit into the naming, and it really helped me to design it, but I had a clear metaphor for what a keg was, what a formula was, and the rack, and the cellar - it all made sense, so it really helped to design [unintelligible 00:29:25.08] and then I eventually added the taps. I’m kind of working on the Soup Homebrew right now, and I’m using the term ‘growler’ to define what the thing is, [laughter] and it’s just perfect. So that’s one of the refillable things then, or…? I don’t wanna reveal what it is… Because the name works, so you’re thinking along the right lines. Okay… Yeah, it’s perfect. Nice. So tell us about the transition, because you built Homebrew, you maintained it for a long time, it grew to massive adoption… Pretty much anybody who develops on a Mac uses Homebrew nowadays. But we’ve just had Mike McQuaid on, who’s the lead maintainer, so there’s a certain point where you handed it off. Can you tell us what prompted you to move on and how that transition went? So for at least two years I really enjoyed working on Homebrew still, and it gradually accumulated more and more people to help. Mike was one of them, and I knew Mike, he was a friend from the KDE era, in fact. Wow. He had moved to London and worked at a company that was somewhat related to us, so we were friends. He had contacted me not long after we started getting attention to us to work on it as well (he’s a workhorse). He was there from very near the beginning, but after two years or so I’d solved all the interesting problems and I’d started to lose interest. It was basically done; I think that’s a big problem that I have in general… I lose interest in things once they’re done, and I’m always looking for the next thing after that. So I started contributing less, and one day got @ replied by someone who was angry about some formula that they wanted to have merged and it’d been rejected, and the reason it was rejected was really my own fault, because initially when I had made Homebrew I was adamant that it wouldn’t have trivial crap in it. Because it’s like the App Store - it would perhaps be better if it was a bit higher quality; now I disagree with that decision. There was ways to work around that, and we invented them. It’s the tap system. [00:31:53.11] Also because the more stuff you had in there, the harder it was to really have high-quality core formula, but the tap system solves that. So I disagreed with the other guy’s decision and then I merged it without talking about it because I was being arrogant, and it resulted in an argument and I decided that I didn’t want to be part of a project where there was conflict like that, so I left, basically. The project had been always been on my name at that point, under @mxcl, and I was kind of proud of that because it was for a long time the most forked, most starred project on GitHub, and my name was next to it. And that had lead to quite a number of interesting e-mails and conversations and phone calls from people that were just browsing GitHub and found my names. There was opportunity definitely associated with having a very high profile project on my name, but they wanted me to move it onto the Homebrew organization, and that made sense, I couldn’t deny it. If I wasn’t gonna work on it actively anymore, then it needed to be moved to an organization so that it didn’t… You know, while it was on my name, I could just delete it, effectively… Which would be kind of an interesting movie, probably… Disaster movie. [laughter] Like left-pad. Yeah, exactly. Just like left-pad. That was very interesting I thought, at the time, and I was at Apple then, and everyone at Apple was asking me how this package manager was not going to be affected in the same way. So I moved it, but it took me like four hours with the button on my screen before I could summon the courage to push it. Emotionally it was so hard to give it up, because it never could come back. I’m very proud of Homebrew, it was a project I put a lot of time, effort and thought into, and it paid off the way I thought it could, and that doesn’t happen very often in your life. This is exactly why we say on this show, Jerod, to everyone listening, “Be nice to your maintainers”, because it’s that kind of heart that mauls over for four hours, it’s that kind of spirit you put into that kind of project, and that kind of care and love that we have to appreciate and honor, and if you don’t do that, then it’s just not cool. And I can hear the anguish in your voice sharing that story, bro… I’m glad you shared it, it sucks it turned out that way, but to have people like you out there in open source is super cool to me. Well, it was the right thing to do. Of course, yeah. I care about the project, and if I wasn’t willing to maintain it anymore, then it needs to be given over to the community, and I was just glad that the community was there to take it. It’s more about the finality of it than it is the act is what I mean by what I said. Yeah, I understand. Because it’s this moment – like you said, it can’t come back… There’s this point of no return, and that’s hard to deal with. Yeah, it was… I felt a sort of relief once it was done though. Like, for one, my GitHub notifications were never readable. [laughter] You could actually use them. Yeah, exactly. Well, I had other open source projects and they were just vanquished because I couldn’t know when someone was actually trying to get my attention for them; I couldn’t really know why people wanted my attention on Homebrew either… Homebrew’s notifications are not designed for a project of that popularity, for sure. So the moment it was gone, suddenly I could get back into my other projects and things that I was more interested in at the time. It made sense. So once you were done with Homebrew, what was the next step for you? What was the next bigger milestone for you in life? Well, at that point or now? When you were done with Homebrew… Back to that moment where you pushed the button, the next big milestone for you. [00:36:05.14] Well, basically I’d been doing iPhone development at that point for three or four years, and at the time I was in Chicago. Between the last Changelog and now I’ve moved to America, I met an American girl and we moved to Chicago, and we now live in Savanna, Georgia. So I was in Chicago at the time and I was teaching iPhone development part-time like half a week, which I really enjoyed. It allowed me to learn a lot about how people approach learning how to code. It was a boot camp, so these things are kind of rip offs and I kind of felt bad about that, but I was just the employee, so… I was working on PromiseKit, which is probably the open source that I maintain the most at the moment, which is just Promises for iOS. I’d use Promises because I’d done a lot of Javascript development in between as well, and Promises just made so much more sense for asynchronicity, and there was nothing good for iOS so I was like, “Okay, I’ll build it.” So I was working on that, but about that time the boot camp I was working for was running out of money, so they said “Well, Max, sorry, you’re the most expensive person here, - [laughs] I didn’t realize - we’re gonna have to let you go.” So suddenly I was left with no regulate income, and I didn’t wanna do any more iOS contracting - which I’d done a lot of - because it just sucks the soul out of me, working on other people’s apps I didn’t really care about. It was very good money, but I could only do it for a few months at a time before I became depressed. I just wanted to do open source or something that made sense to me. Me and my wife didn’t know what to do, and Google had been e-mailing me for years saying, “You should come at an interview, you should come at an interview”, and I’d always thought “No, I don’t wanna go there. I’m not a big company person. I wouldn’t fit it. I don’t have computer science… It doesn’t make sense.” But because things had just suddenly shifted around for us, we thought we’d give it a go, so I went to the interview. That probably leads us to the “tweet heard around the world.” Pretty much. Or around the developer world at least… Which was June 2015; you said “Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.” Tell us about that tweet from your perspective, because I know it from mine, but I don’t know it from yours. Yeah, I don’t know if anyone knows it from mine, apart from people who know me; I haven’t really talked about it. Basically, the recruiter who I talked to in the interview process was pretty adamant that I would mostly get asked about iOS stuff, and that’s what they wanted me for - iOS stuff. So despite their e-mail giving me a big list of computer science stuff I should know, I didn’t do any research or studying for it, because I assumed that they wanted me for the knowledge I had, and not the knowledge that I could have if I studied for it. So my first interview was the binary tree question, and I think I did a fairly good attempt for someone who didn’t even know what they were talking about, although it wasn’t a binary tree question, it turns out… But I didn’t know, I just assumed it was… It’s where you have an array and you can divide it in two to get… Blah - I can’t remember. Anyway, after failing at that, I went home and looked it up and figured out how to do it, just to prove to myself I could. [00:40:08.23] I did well in like half of the interviews; I’ve actually talked to the people that interviewed me, because of the tweet, and they said that it was a difficult choice that they made that they decided not to, based on the way they do these things. They have a very strict process. But anyway, a week went by and they phoned and said no, and I just fired the tweet out, because I was like, “This is ridiculous.” Considering the popularity of Homebrew, I just assumed that they could fit me in somewhere with something. They have enough engineers that use it, surely I would have some value to them; that was my thinking. Even though I thought I was getting it for iOS which I’d prefer to have done. The iOS app it needs some work frankly. So I fired it off, didn’t really think about it… I put a Homebrew in brackets I guess because I was thinking, “Well, if it’s retweeted, people will know what I’m talking about.” And obviously the 90% is bullshit; it was a flippant tweet. I was exaggerating… Who knows what the percentage actually is; probably all their Mac developers, or the majority. There’s still some die-hard Mac ports used out there for sure. Well, that exploded, that’s for sure; 20 minutes later I checked back and I had like 400 retweets, so I was like, “Oh, dear…” [laughter] People started linking me to the Hacker News article, then I got one of my co-workers to look it up Hacker News, and he was like “Where do you think you’re ranked on Hacker News?” I was like, “I don’t know… Top 20?” He was like, “Try the top…” and took a screenshot of my tweet on the top of Hacker News. I never read any of that stuff, and I didn’t reply too much… Because it was never my intention to make that much fuss. I feel kind of bad for Google, because to be fair, they told me what I needed to read. The recruiter had made me think differently, but they sent me an e-mail that was very specific and clear about what I needed to know, what I should know. And it wasn’t fair because 90% is obviously not true. I got a lot of googlers saying, [unintelligible 00:42:23.20] [laughs] And I don’t like it because I came across so arrogant, but I like the conversations that arose because of it, because they definitely could have found it useful. Yeah. There was a lot of conversation around this, as you said. Some of it is in the replies to the tweet, everything from people saying, “Well, you’re not a real programmer if you can’t invert a binary tree”, to other people defending you, “Who’s at fault here?”, and I liked that in retrospect… The numbers – of course that was not the actual number; did you survey all their engineers and get that 90%? [laughter] But I liked that knowing the full story it seems like I agree with you that it just makes sense - with how many engineers they have and how many do use Homebrew, and you’ve demonstrated over time that you can have software that’s valuable to many people, I could totally see where you would be thinking, “Surely there’s a position for me. Since they’re already interested in having me work there…” It’s not like it’s a cold interview; with that being said, hearing that they did give you what you needed to know… They made it clear that they were gonna require this of you - that makes it look like it’s not so bad on Google’s side. No, but I feel bad for them, but this is how things are nowadays with social media and virality, and 140 characters. [00:44:03.01] The question is would you do it again? If you had to rewind back to the day, would you do the same tweet? Yes, but only because it inspired some conversation in the industry about how these interviews should be. I really feel bad for shaming them; I guess they probably don’t take it personally… And I feel bad because I’m sure a lot of people think I’m just an arrogant ass now, but I try not to think about it personally in that respect. It was just flippant, and I went from 3k followers to 16k in like a month. I don’t like that either. Why don’t you like that? Most of these people aren’t following me for anything that I actually care about. They’re following me because they… Maybe they are, maybe they discovered you because of that. Maybe… Maybe it was the entry point for you, at least to them, so to speak. I think the interesting thing there is that you’d do it again, but with some regard. At the same time, none of us are identified by our tweets. My tweets don’t define me. And I may say something sometimes that doesn’t exactly identify who I am, but the thing is that the people tend to take the black and white text we put on the internet as like the version of us that’s the truth, and there’s a grey area there, where you’re not exactly the person you seem you are. And there’s a person behind that, versus just a tweet. Absolutely. I definitely like the conversation, because I knew you previously. I hadn’t followed you on Twitter, but I knew you as the Homebrew guy, and when I saw that tweet I thought - and I’ve never been interviewed by Google, so I don’t know what that process is like; I know they have brain teasers and whiteboarding and stuff like that, but I hadn’t thought about the interview process at large companies because I’ve never been part of a large company. And the conversation around it wasn’t just “Should Max have gotten hired/Should he not have gotten hired? Is Google evil? Is Max arrogant?” Of course, those things are always said, they’re on any popular conversation (unfortunately), but it was “Is interviewing broken? How can we do this better?”, those kinds of things. I felt like the end of it, there were a lot of think pieces that were written. I think there were a lot of good things that came out of that, and so I would hope you’d do it again too, just so we can continue having these conversations. So that leads us to where you actually did land, which was Apple. Can you compare and contrast the hiring process between the two? Would that be profitable, or…? They’re similar in that they’re all day. It’s exhausting. Apple had more interviews, but I was interviewed by the people I had worked with. Google really do seem to – I don’t know if they’ve changed anything, but I heard from a friend who was at Google at the time that my tweet went around Google and it inspired a lot of internal conversation. So I don’t know if they’ve changed how they do it at all and, well, humbly enough, I got two calls the week after from a couple of people at Google asking me to come and interview with their team, and that it would be very specific to their team, because they wanted me to do the iOS stuff for them. That’s partly because of PromiseKit, because it’s a pretty good framework; I designed it carefully, like I designed Homebrew, and I needed it, just like I needed Homebrew. The best things I make are always the things that I make from tools I need. [00:47:49.06] So Apple interviewed me personally, while Google – it’s like jury duty, it’s the impression I got. You get an e-mail saying, “You have to interview Max Howell on that day. Be prepared.” And then they have a box full of questions that you can generate a random number and pick one. But the interviewers get quite a lot of choice… One of my interviewers at Google knew what my skills were and asked me stuff about it, and I did pretty well. Another one had me redesign an API and I did pretty well. The ones I couldn’t do were the data algorithm stuff, which they really needed. But I think I made a pretty good attempt. That’s I guess what I’d change about the interviewing process at these places - did I demonstrate that I could solve problems given input, even if I don’t have the specific knowledge? But it seems ironic at Google - learning how to do that is just a Google away, and that’s what I did when I got home… To prove to myself that I could do it after feeling stupid, which is what these things do. Apple interviewed me personally and apparently were told to give me an easyish time because of my tweet. [laughter] Don’t mess with him, he’ll tweet about you. Yeah, that was one of my concerns with the tweet. I was like, “Well, you’ve just screwed up a lot of chances for yourself.” But at the same time it wasn’t. I got two hundred e-mail, give or take, because of the tweet, from different companies saying, “Well, if you want, give us a call. We could use you.” That was an interesting side effect, certainly. Including SpaceX… I was like, “Wow, that would be cool”, but I didn’t… The only reason I considered going to Apple was because I met Chris Lattner while I was at WWDC, and talked to him, and he was awesome. They were like, “Well, we kind of need something like Homebrew but for Swift”, and I was like, “That’s amazing”, because I was so into Swift then. As an iPhone developer for a few years at that point, and Swift just suddenly came out the previous WWDC, and I could see that it was a really nice language, with forward thinking in the right places, learning from the right places of different languages… It was the language I wanted to use, and maybe use for ten years… Who knows? I hesitate for the most of my life in this industry, but ten years seems to be like forever. So the opportunity to shape that language was just irresistible… Because I wouldn’t have gone to another interview probably, after the Google experience. It just wasn’t for me, I knew it wasn’t for me. The only reason I’d done it was because we landed in a situation we didn’t know what to do with ourselves exactly, and I didn’t wanna do contracting anymore. Their interviewing process was much nicer, but at the same time I don’t think they should have hired me, quite honestly… Maybe Google had the right idea. [laughter] Why not? That’s so funny… Well, I was only there a year… It didn’t work out. I’m just not the right kind of person for these big corporations. I was trying to make the Swift Package Manager the way I knew the community needed it. I’d been involved with CocoaPods and Carthage and used them heavily, and obviously made Homebrew, so I had lots of opinions about how a package manager should be, and especially for a language package manager, which is different than just a packet manager. I came in with all these ideas, and I can persuade anyone about many of them, but it was very frustrating. At the same time, they couldn’t really persuade me about their alternatives… So you weren’t persuadable, they weren’t persuadable… Yeah… I wanted to work like I worked in open source, where I produced stuff and then we reviewed it and considered how it would go from there. I stewed on ideas for a couple months and then talked about it. [00:52:08.07] And Apple – I can’t speak for the whole company, I really can’t, because every department is very isolated, and that could be a good or a bad thing, I won’t go into it, I guess; so all I can talk about is for developer tools, and developer tools is a very old department. They’ve been around since, like, ever. Since the beginning. Xcode itself has existed 20-25 years; I’ve never worked on a codebase that’s that old with clunky clunks upon clunky clunks… And they have to work with it, because they can’t rewrite the thing. But I was mostly working independently about that with the Swift team, but I wasn’t on the Swift team, I was on the build systems team. So I was isolated from the Swift team, and that was probably a mistake on their part. I should have been with the Swift team. It was not bad… Chris Lattner is a genius, and I’d be having meetings with my team, trying to decide how we should take the product, and he’d come in and instantly appraise everybody in there, figure out their needs, wants, motivations, and just say the right thing. It was amazing. This is interesting… Your pinned tweet on Twitter says, “The foundation of the modern world is developer tools”, and here you are at Apple, with the ability to affect a huge portion of the software development community, or surely the entire portion of the Apple developer community, working with Chris Lattner who’s a genius, on the Swift Package Manager, which is to be an open source project, and yet something’s not jiving here. I’d like to dig into that a little bit more on the other side of the break. We are hitting our next break, so we’ll pause… Think about that a little bit, Max, and when we get back, Swift Package Manager inside Apple, open source, but there’s trouble here… So let’s pause and we’ll be right back. Alright, we are back. Max, before the break we were talking about your time at Apple. You were there for a year, working on the Swift Package Manager, which is out there and is open source, and so you got to be there I believe during the launching of that, which had to be fulfilling, I would think… But there was some struggle between you and management, or between you and your position; you just couldn’t quite have the impact that you were desiring to have. Is that fair to say? Yeah. I wanted to make a really great thing. Because, like I say, I plan to use Swift for… I don’t know when I’ll stop using it, so it having a vibrant, active community, a good packaging system was important to me personally as well as professionally, and for the good of the language. [00:56:01.29] But Apple have the way they’re working, which didn’t fit with me specifically. I butted heads with my manager and various other people many times. I’ve gotta say though the Swift team were great. They seemed to be – I don’t wanna be insulting, but they seemed to be really forward thinking; they used modern development methodologies, they were extremely smart, they worked well together, they talked well together, they figured things out that I wouldn’t have figured out if I was in their position. Little details of how to design the language so that it caters to so many different ways of working, and yet still maintains the strictness, the safety, the fun that is Swift. They were great. I said to my manager when I joined there I partly came to Apple because I wanted to learn from people who were smarter than me, and he used that so many times… He said that I didn’t want to learn from them actually… It wasn’t a good match. That happens sometimes, I think… People go into positions with super high hopes, right? Like, “Dream job… I wanna work here all my life. Developer tools, I’ve got the chops for this, this is perfect”, and then it’s just some sort of like bad mixture you never expect and you’re like, “I gotta get out of here…” I’ve been there. It made me realize how important team fit is. I’ve been lucky my entire career in that I just lucked into great teams that I fitted well in and that we worked well together. When you don’t have that, it’s just impossible. Yeah. And I did my very best, because I cared so much and it drove me to quite a stage of depression, actually. I really wanted to make something great, I just didn’t know how to do it there. I’m pleased that some aspects of the Swift Package Manager succeeded to get in and are there; I think it has a good base. I’m glad… Otherwise I would go, “I failed completely.” But I think it could be a good thing still. So is a lot of what is there, is it – you mentioned earlier, liking it back to your Homebrew days, that your architecture and what you laid out and how it worked, a lot of what we see there, not so much the code, but how it works, how it’s laid out, how it’s supposed to work - the plan for it, basically… Is that a lot of what you contributed? Yeah, with some compromises here and there. A lot of the time I was able to at first to get my way without it being too difficult, so as a result it’s a highly modular system, which is one of Swift’s powers - you can easy make modules. And it’s a convention-based layout system, so you make new directories for each module, and then sourcers can edit part of the modules… So you’re not messing around. It’s really easy to write code really fast. Syntax for the package description, for all the recipe, the formula is in Swift, which I had to fight pretty hard for, which means that you have flexibility with it. You can import modules into it - well, they didn’t want that… They really didn’t want that, because it’s not very Apple. What was the other option? Like a .plist, or XML files? Yeah, probably .plist, because that’s – I don’t know… It would have been JSON, I expect. But it’s difficult to add things… Like, what if you want to make a module where you only want the files with a Windows extension for the Windows platform, and things like that? It’s really hard to describe that kind of behavior in JSON, but with Swift it’s easy - you do a “hash if Windows”, and then you add to an array… [01:00:04.19] Programmers like to program, is my opinion on the matter. We like code, we write code, we want the power of code even if that results in some danger, with a real language. That is decentralized. I’m very pleased to see centralized – I wish Homebrew had been decentralized to a certain extent in the first place, but it is now, with taps. Because it makes it easy for people to just push out their packages without having to conform to some system. For example CocoaPods, which is the most popular iOS packet manager currently - when I contribute to another CocoaPod, I have to ping them for like a week or so for them to push an update, so that I can actually use it without messing around in my Podfile. It shouldn’t be like that. I should be able to just make the changes, use my fork very easily, and then have it ready to go into the main fork. That’s what GitHub is about, it’s about this decentralized open source community. These things should be all over the place, and if I think that somebody is doing something wrong, I should be able to easily fork it and use it. Or if I’m in a company and I need to make a change but I can’t release it, I can just use my private fork of the thing easily etc. I believe that’s how these things should be, for language packet managers at least. I feel that it’s a pretty good base, and the people that are now working on it, they’re great, they’re really very good, and I think they’ll do a great job. Probably better than me, because I just couldn’t figure out how to navigate Apple. I couldn’t figure it out. Well, I’m looking at the GitHub page for the packet manager, and I’m happy that the file that you’re talking about is called Package.Swift, and it’s not called Package File. As somebody who respects the names, I think it was a nice break from convention there. Oh, that cost me sleepless nights getting that. [laughter] It’s just difficult. Apple, basically – I’m pretty sure I can say these things without getting an e-mail from HR to shut the… It’s all about who you know. If you don’t have the right influence with the right people, you don’t get your way, even if you’ve got the right idea. And you only get that through years; you have to be there years. You have to put in five, ten years before you can make an impact, and I didn’t have five or ten years, as far as I was concerned; I had a year. Otherwise, this product was gonna suck, and it needed to be good now. Also, I found that there’s a lot of people there who love to invent work, and I don’t, so I didn’t go on with that aspect. One thing you said earlier was that you’re proud of Homebrew. Would you say that you’re proud of the work that you did at Apple? Hm… Well, that’s sad. Yeah. As I said, I blame myself as much as I blame anyone else. I knew before for any of these interviews that I didn’t work well with teams, and I don’t. I can, if it’s just the right team and we all get along and we all can see each other’s perspectives, but I can’t stand when there’s a bunch of stuff that isn’t the work that must be done in order to get things done, and at Apple there’s constant meetings and constant disagreement, and constant battles about things that really weren’t important in the slightest… [01:04:08.14] That’s why I liked it when Chris Lattner turned up, because he would just see through all that. This is why he’s done so well. He’s very easy to admire. Well, it sounds like Swift is in good hands with Chris. Yeah, Swift has got a fantastic team, it’s gonna do really great, and I’m so glad that they open-sourced it. Without that, it would have only ever been like for iPhone, even if someone else figured out how to compile it on Linux or whatever, or bring their own Swift compiler… Because it’s open source, I feel that it has a good chance to be the next big scripting language, replacing things like Ruby, Python, maybe even replacing Node. I know that that’s gonna be harder, because people love their Javascript so much… So the Swift Package Manager is open source; Swift, of course, famously open source… Big shift really, for Apple to open source things on their own accord, and not because they’re complying with a GPL, or something like that. Well, that’s not strictly true… Were you involved with the open-sourcing idea around the package manager? Were you in any of those meetings? I didn’t make the decision. That was already made. Okay. Just thought it would be interesting to be a fly on that wall, around… You know, when you talk about the arguments and whether or not to open source, it’s a big discussion. Or the motivation. Yeah. It makes sense for the language for sure, because if they want it to be what you said, it could be the next major scripting language, or a primary language that you teach children… These things it has to be. Yeah. Well, Apple really care about [unintelligible 01:05:51.04], that was the impression I got. They want this stuff to be used, they want kids to learn to code, and they wanna help that. That was a lot of the motivation; I know people want to be suspicious, as though Apple are just a company that are trying to get your money, but my feeling while I was there is it’s definitely not that. Yeah. So what about Swift? You said earlier that this could be your language for the next ten years, you fell in love with it. First give us a rundown of some of the earlier languages that you know, which will give us a little bit of help contextually, and then tell us what it is about Swift that you love so much. Well, the first language I have ever used was BBC Basic, which was basically the same as QBasic. Then I started learning C because there didn’t seem to be anything else at the time. This was when I was like 11, 12… Then C++, and that was my first professional programming language. Then when I decided to make Homebrew, I wanted it to work without having to be compiled or installed, so it had to be some scripting language that came with Mac; I’d seen a lot of people talk about Ruby and how great it was, so I tried it out and I agreed - so Ruby. Then I did about a year and a half of Javascript while I was working on a music app with someone that was on the web, and they also had a bunch of C for a little app, and stuff… And I really quite liked Javascript. I loved the functional aspect of it, I liked the dynamic aspect of it, and the use of Promises and things was new to me, so I enjoyed that. There were some things I liked about it, like you could call a function with as many arguments as you wanted and then figure it out later… [laughter] I could see how it would easily lead to devastating behavior, but it was fun. [01:07:52.07] Then I went back to Objective-C… I’ve done a bunch of that as well before that. I loved Objective-C, at least until Swift came out. So that’s my language history… I’ve done dabbling in other languages like Python - I’ve written a few scripts in Python and Bash… If you consider Bash a programming language. Of course. What made you suspect that Python, Ruby might get supplanted by it and then you even said Node, which is more of a framework on top of a language than a language itself… What makes you say that? Yeah, well Node made Javascript feasible as a set-aside and not just in the browser system. Well, what’s wonderful about Swift - well, it’s familiar. It’s familiar to almost anyone. It’s C-based, but it also has influences from so many other languages, and you feel it. But the safety of it - that’s what scripting languages really don’t have. A scripting language is great, because you can just power stuff out and it more or less works, and it’s easy to fix (at first, at least). They have a good packaging system, so you can get all these third party libraries… But they’re not safe. With Swift, everything is safe. You end up programming in such a way that you know there’s no way that there’s an error or anything in this program that you haven’t accounted for. I think that the biggest problem software has right now is it’s flaky; software sucks, it breaks. You’re using an app and you push a button and nothing happens. Or a spinner starts, and the spinner never finishes. Or the buttons move around incorrectly when you rotate it and it doesn’t recover, or crashes, or the data gets lost… Flakiness is the problem. We solved speed of development, we solved it being difficult to crank out an app, but safety - there’s not safety. And Swift naturally forces you to be safe. The optional is obviously a big deal… It’s not an invention of Swift or anything – most of these things aren’t inventions of Swift. The invention of Swift is the way they put it all together in such a nice package. They carefully thought about the keywords and how they interact with each other. They carefully thought about which things to bring to the language, and which things not to bring; which things have the most benefit. With Swift, everything’s – either it is or it’s not, but if it’s not, then you have to wrap it as an optional. This means you’re always considering the cases where there’s nothing, and you’re trying not to have nothing. I try to write my apps now so optionals are almost never there. And without the nil, at least with Objective-C, it was a huge cause of bugs, and Objective-C handled nil differently to other languages. If an object was nil or null, it would just do nothing. So a common bug in iPhone apps was you’d push a button and nothing would happen, because it was connected to something that was nil. Of course, in a Java app it would just crash. With Swift you don’t crash, and you don’t do nothing, so both of these issues… But they understand that it’s still necessary to be pragmatic, so they have implicitly unwrapped optionals, which are optionals where you say, “Well, I know this is never gonna be nothing” - because sometimes you need that, but that won’t crash. But you have to opt into that; you have to really think about it. You have to be careful with it, and then you have this big exclamation mark whenever you use it, reminding you that you’re not being safe, that you’re a bad programmer, that you should feel bad about yourself. That’s funny. Great explanation, too. [01:11:45.00] With version 2 they released guard, which is this statement where you can’t get past it unless the thing you’re evaluating is true or not true – I can’t think about it. It just means that you can write a function and then have like runtime asserts at the top, and you can’t leave the guard statement unless you return or leave the function in some meta, so you have to leave it safely. You’re not crashing, although you could put a crash in there; the idea is to make you behave correctly, to write code that behaves correctly. So if you had to put your forecaster’s hat on - I know you like to wear a lot of hats… So put on your forecaster hat and tell us where Swift is five, ten years out. You said it could be your programming language. Do you think it will come to dominate the programming landscape, or do you think it will always be inside Apple’s bubble? I think it’s already starting to leave Apple’s bubble because it was open-sourced for Linux support, and since then some people at Facebook have made it work on Android, and some people are working on making it work on Windows. So we’re getting to this point where you can write your app in Swift for every major platform apart from the web. But you could write your server-side in Swift, and someone’s already made a Swift to Javascript compiler, so you could write the frontend in the Swift as well if you trust the compiler. I don’t know, I haven’t really looked into it. So I really want it to be. I think it’s a lovely language, and I’m not just saying that as someone who’s been a bit of an Apple fanboy for so long. I’ve been disappointed with Apple in many ways, not just because I worked there. I think MacOS is really in need of work, or at least some hooks so that developers can change how it works. I wanna get rid of the dock, I wanna get rid of the menu bar, I wanna experiment with many different ways of making it a better platform for me. I’ve been using Windows a lot lately, and I think Microsoft are doing a lot better with Windows 10 than Apple are doing with MacOS right now. Wow, that’s a bold statement. …from a longtime Apple fanboy. Yeah. Well, I switched… Obviously, Linux, and then I switched to Mac because I got fed up with my Linux Wi-Fi driver failing every time I upgraded my kernel… Yep. …and Mac was UNIX underneath. And now Windows 10 has this Bash and Ubuntu interface I haven’t tried yet. It can be UNIX, and that’s the main thing that a lot of us want, at least - a UNIX system. So I’m pretty tempted by Windows 10, but currently all my projects are on Macs for now. You just bought a brand new MacBook Pro, so… Yeah, I did. Having said I wouldn’t, I did. That’s why you shouldn’t believe anything I say on Twitter. [laughter] Or podcast, maybe. [laughs] Well, you know… As we’re getting closer to the end of the show, Max, I know you’ve got a couple things on your side you wanna mention before we close out. I know you’ve got a startup going on… What’s new for you? What do people not know about you these days? Well, since I’ve been out of Apple for about four months - not very long, but it feels like it was… The day I handed in my resignation I felt like such a weight off my shoulders, it was incredible. I decided I wasn’t gonna work for a big company again for sure, so I consider myself an indie now. I’ve been trying to work on a few things to make myself independently financed; I don’t wanna be rich, I decided. I don’t need to be rich. What I wanna be doing is cool open source, being involved in the open source community, and just trying to improve the world. And the little bit I can improve - bits of software here and there. I joined a startup with a friend and we’re doing music stuff, which I’ve always been interested in. We have an app in the store right now called MixMessage, which is an iMessage app, and you can make a mixtape with a friend, take turns where he/she puts a track in, you put a track in, keep going like that. It’s fun, surprisingly fun. We whipped that up when the messaging apps came out, because we thought it would be neat. What’s the URL for it? [01:16:07.24] It’s MixMSG.com. It’s unfortunately named in a respect – we didn’t realize this until afterwards… Google always thinks you’re talking about MixMag… Oh, autocorrect… “Did you mean MixMag?” Yeah… I hate searches where there’s like “Did you mean…?” or the autocorrection… No, I really meant to write what I wrote like three times now. You stop correcting me. [laughter] Yeah, I just don’t understand that. I mean, I like autocorrect and it helps me a lot because I type fast sometimes, but it just drives me crazy when it’s like “No, I clearly mean that acronym. I know it’s weird and all, but I mean that.” [laughs] But once you corrected it once, why would it try to correct it again to the same thing…? Yeah, so it’s MixMSG - MixMessage. It’s nice, our team has a really good designer, and I’m doing the [unintelligible 01:17:00.02]. And we’re also working on an app for local music that’s going to be called Audiyo. We’re hoping to have that completed this month actually, we’re cranking it out. It’s about discovering local bands, local music near you… Something I’m somewhat passionate about. I’ve always felt that the music apps that exist are not good. Like… Like Apple Music - it’s just not very good. Beats is better. I don’t know if you ever used Beats. Apple bought it and then ruined it. Spotify - I just… I’m not gonna say anything about them. What was the name again for this last one? Audiyo. We’re hoping to have that out (a beta) before Christmas, hopefully. Is it a .com? I’m not sure we even have a website, so you’re gonna have to just wait. Okay, I was gonna say… Because I can’t find it on the web, so I’m assuming that either somebody else has got it, or… You said you love names, but then you said you hate them, so… Well, I didn’t name these things… [laughter] That’s all I’m gonna say. [laughs] And I’m working on something for Homebrew. I don’t think I’m gonna go back to the core, but I always have a notebook full of ideas, tools I need, and that’s why that tweet is still pinned, even though I’m not working at developer tools with Apple anymore - “The foundation of the modern world is developer tools”, because I believe it, it is. And I love being a developer because we can make our own tools. It’s like the only industry apart from maybe blacksmithing - and I’m not sure if they even do make their own tools - that we can make our own tools to improve our workflows, to make ourselves more efficient and productive. So I always have a notebook full of ideas for stuff, and this is one that I’ve been toying around with for a couple of years and I’m really trying to make it now. And yes, it has growlers in it, and I don’t wanna say anything more about it because I don’t like to jinx myself. I feel like if I say things about some new ideas I have that I then don’t finish them. I really wanna finish this one though, also because I’m thinking about how to make money with it, and that’s what I want: I wanna be able to work on open source full-time. Well, I can poke around on GitHub and I did see /growler, which is an empty repo, sitting there waiting. So if you’re listening to this, maybe go watch that, or start it at least, or something, to kind of keep up. I’m assuming that’s it, right? That’s part of it. There’s no description, there’s no message shared, so you’re not being committed to your idea. [01:19:58.11] Well, I needed the repo to exist for various reasons, but yeah… It’s not gonna be filled yet. One of the things Apple do - they hammer into you, in fact - is surprise and delight, and I agree. Right. Yeah. Well, Max, thank you so much for taking us down this trip of yours. I know that you’ve got some history to you, and as you had said before, millions use software you’ve worked on, so you’ve got some history with everyone listening to this… At least those who use MacOS. I use Homebrew all the time, so thank you for the work you’ve put into that. Even the angst you had with pressing the button to share it back, I can appreciate that and understand your feeling there, and just thank you for being the maintainer you are and the software developer you are, and the encourage you are, especially with that tweet to sort of change how people look at the interview process. That’s gonna be a huge help to many software developers out there for years to come. I hope so. Any last words to share with us before we tail up the call? No, I’m all good. Thanks for what you’ve just said, it was very kind. Awesome. And thanks for having me on. Alright, well, listeners, thank you so much for tuning in, we love you. If you don’t subscribe to our weekly e-mail, we would love for you to, so go to Changelog.com/weekly. Jerod and I, we put in so much work into that e-mail and every single week we scour the internet for our favorites in open source and software development, and we do whatever we can to share that back in that e-mail: our latest episodes, our latest announcements, we’re doing lots of fun stuff, we’re growing, we’re expanding… So if you like what we’re doing with this show, check out Request For Commits, check out GoTime, check out Founder’s Talk (we’re bringing that back), we have a new show coming up very soon called Spotlight… So much fun stuff happening, and the place we announce all that fun stuff is at Changelog Weekly, so go to Changelog.com/weekly, subscribe to that. For those listeners who have been listening to The Changelog for years, back to Max’s episode #35, subscribe to our master feed. Many of you love all we do, so just go to Changelog.com/master - it’s our master feed; it’s in iTunes, on Overcast, and you get everything we do. Don’t miss out, don’t be that person, and if you see us at a conference, high fives and hugs, okay? Fellas, that’s it for this show, so let’s say goodbye. Goodbye! Thanks, Max! Goodbye! Thanks very much! Our transcripts are open source on GitHub. Improvements are welcome. 💚
https://changelog.com/podcast/232
CC-MAIN-2019-39
refinedweb
13,909
76.05
R-squared, often written R2, is the proportion of the variance in the response variable that can be explained by the predictor variables in a linear regression model. The value for R-squared can range from 0 to 1 where: - 0 indicates that the response variable cannot be explained by the predictor variable at all. - 1 indicates that the response variable can be perfectly explained without error by the predictor variables. The following example shows how to calculate R2 for a regression model in Python. Example: Calculate R-Squared in Python Suppose we have the following pandas DataFrame: import pandas as pd #create DataFrame df = pd.DataFrame({'hours': [1, 2, 2, 4, 2, 1, 5, 4, 2, 4, 4, 3, 6], 'prep_exams': [1, 3, 3, 5, 2, 2, 1, 1, 0, 3, 4, 3, 2], 'score': [76, 78, 85, 88, 72, 69, 94, 94, 88, 92, 90, 75, 96]}) #view DataFrame print(df) hours prep We can use the LinearRegression() function from sklearn to fit a regression model and the score() function to calculate the R-squared value for the model: from sklearn.linear_model import LinearRegression #initiate linear regression model model = LinearRegression() #define predictor and response variables X, y = df[["hours", "prep_exams"]], df.score #fit regression model model.fit(X, y) #calculate R-squared of regression model r_squared = model.score(X, y) #view R-squared value print(r_squared) 0.7175541714105901 The R-squared of the model turns out to be 0.7176. This means that 71.76% of the variation in the exam scores can be explained by the number of hours studied and the number of prep exams taken. If we’d like, we could then compare this R-squared value to another regression model with a different set of predictor variables. In general, models with higher R-squared values are preferred because it means the set of predictor variables in the model is capable of explaining the variation in the response variable well. Related: What is a Good R-squared Value? Additional Resources The following tutorials explain how to perform other common operations in Python: How to Perform Simple Linear Regression in Python How to Perform Multiple Linear Regression in Python How to Calculate AIC of Regression Models in Python
https://www.statology.org/r-squared-in-python/
CC-MAIN-2022-40
refinedweb
372
59.23
inspect – Inspect live objects¶. Module Information¶ The first kind of introspection supported lets you probe live objects to learn about them. For example, it is possible to discover the classes and functions in a module, the methods of a class, etc. Let’s start with the module-level details and work our way down to the function level. To determine how the interpreter will treat and load a file as a module, use getmoduleinfo(). Pass a filename as the only argument, and the return value is a tuple including the module base name, the suffix of the file, the mode that will be used for reading the file, and the module type as defined in the imp module. It is important to note that the function looks only at the file’s name, and does not actually check if the file exists or try to read the file. import imp import inspect import sys if len(sys.argv) >= 2: filename = sys.argv[1] else: filename = 'example.py' try: (name, suffix, mode, mtype) = inspect.getmoduleinfo(filename) except TypeError: print 'Could not determine module type of %s' % filename else: mtype_name = { imp.PY_SOURCE:'source', imp.PY_COMPILED:'compiled', }.get(mtype, mtype) mode_description = { 'rb':'(read-binary)', 'U':'(universal newline)', }.get(mode, '') print 'NAME :', name print 'SUFFIX :', suffix print 'MODE :', mode, mode_description print 'MTYPE :', mtype_name Here are a few sample runs: $ python inspect_getmoduleinfo.py example.py NAME : example SUFFIX : .py MODE : U (universal newline) MTYPE : source $ python inspect_getmoduleinfo.py readme.txt Could not determine module type of readme.txt $ python inspect_getmoduleinfo.py notthere.pyc NAME : notthere SUFFIX : .pyc MODE : rb (read-binary) MTYPE : compiled Example Module¶ The rest of the examples for this tutorial use a single example file source file, found in PyMOTW/inspect/example.py and which is included below. The file is also available as part of the source distribution associated with this series of articles. """Sample file to serve as the basis for inspect examples. """ def module_level_function(arg1, arg2='default', *args, **kwargs): """This function is declared in the module.""" local_variable = arg1 return class A(object): """The A class.""" def __init__(self, name): self.name = name def get_name(self): "Returns the name of the instance." return self.name instance_of_a = A('sample_instance') class B(A): """This is the B class. It is derived from A. """ # This method is not part of A. def do_something(self): """Does some work""" pass def get_name(self): "Overrides version from A" return 'B(' + self.name + ')' Modules¶ It is possible to probe live objects to determine their components using getmembers(). The arguments to getmembers() are an object to scan (a module, class, or instance) and an optional predicate function that is used to filter the objects returned. The return value is a list of tuples with 2 values: the name of the member, and the type of the member. The inspect module includes several such predicate functions with names like ismodule(), isclass(), etc. You can provide your own predicate function as well. The types of members that might be returned depend on the type of object scanned. Modules can contain classes and functions; classes can contain methods and attributes; and so on. import inspect import example for name, data in inspect.getmembers(example): if name == '__builtins__': continue print '%s :' % name, repr(data) This sample prints the members of the example module. Modules have a set of __builtins__, which are ignored in the output for this example because they are not actually part of the module and the list is long. $ python inspect_getmembers_module.py A : <class 'example.A'> B : <class 'example.B'> __doc__ : 'Sample file to serve as the basis for inspect examples.\n' __file__ : '/Users/dhellmann/Documents/PyMOTW/branches/inspect/example.pyc' __name__ : 'example' instance_of_a : <example.A object at 0xbb810> module_level_function : <function module_level_function at 0xc8230> The predicate argument can be used to filter the types of objects returned. import inspect import example for name, data in inspect.getmembers(example, inspect.isclass): print '%s :' % name, repr(data) Notice that only classes are included in the output, now: $ python inspect_getmembers_module_class.py A : <class 'example.A'> B : <class 'example.B'> Classes¶ Classes are scanned using getmembers() in the same way as modules, though the types of members are different. import inspect from pprint import pprint import example pprint(inspect.getmembers(example.A)) Since no filtering is applied, the output shows the attributes, methods, slots, and other members of the class: $ python inspect_getmembers_class.py [('__class__', <type 'type'>), ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>), ('__dict__', <dictproxy object at 0xca090>), ('__doc__', 'The A class.'), ('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>), ('__hash__', <slot wrapper '__hash__' of 'object' objects>), ('__init__', <unbound method A.__init__>), ('__module__', 'example'), ('__new__', <built-in method __new__ of type object at 0x32ff38>), ('__reduce__', <method '__reduce__' of 'object' objects>), ('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>), ('__repr__', <slot wrapper '__repr__' of 'object' objects>), ('__setattr__', <slot wrapper '__setattr__' of 'object' objects>), ('__str__', <slot wrapper '__str__' of 'object' objects>), ('__weakref__', <attribute '__weakref__' of 'A' objects>), ('get_name', <unbound method A.get_name>)] To find the methods of a class, use the ismethod() predicate: import inspect from pprint import pprint import example pprint(inspect.getmembers(example.A, inspect.ismethod)) $ python inspect_getmembers_class_methods.py [('__init__', <unbound method A.__init__>), ('get_name', <unbound method A.get_name>)] If we look at class B, we see the over-ride for get_name() as well as the new method, and the inherited __init__() method implented in A. import inspect from pprint import pprint import example pprint(inspect.getmembers(example.B, inspect.ismethod)) Notice that even though __init__() is inherited from A, it is identified as a method of B. $ python inspect_getmembers_class_methods_b.py [('__init__', <unbound method B.__init__>), ('do_something', <unbound method B.do_something>), ('get_name', <unbound method B.get_name>)] Documentation Strings¶ The docstring for an object can be retrieved with getdoc(). The return value is the __doc__ attribute with tabs expanded to spaces and with indentation made uniform. import inspect import example print 'B.__doc__:' print example.B.__doc__ print print 'getdoc(B):' print inspect.getdoc(example.B) Notice the difference in indentation on the second line of the doctring: $ python inspect_getdoc.py B.__doc__: This is the B class. It is derived from A. getdoc(B): This is the B class. It is derived from A. In addition to the actual docstring, it is possible to retrieve the comments from the source file where an object is implemented, if the source is available. The getcomments() function looks at the source of the object and finds comments on lines preceding the implementation. import inspect import example print inspect.getcomments(example.B.do_something) The lines returned include the comment prefix, but any whitespace prefix is stripped off. $ python inspect_getcomments_method.py # This method is not part of A. When a module is passed to getcomments(), the return value is always the first comment in the module. import inspect import example print inspect.getcomments(example) Notice that contiguous lines from the example file are included as a single comment, but as soon as a blank line appears the comment is stopped. $ python inspect_getcomments_module.py # This comment appears first # and spans 2 lines. Retrieving Source¶ If the .py file is available for a module, the original source code for the class or method can be retrieved using getsource() and getsourcelines(). import inspect import example print inspect.getsource(example.A.get_name) The original indent level is retained in this case. $ python inspect_getsource_method.py def get_name(self): "Returns the name of the instance." return self.name When a class is passed in, all of the methods for the class are included in the output. import inspect import example print inspect.getsource(example.A) $ python inspect_getsource_class.py class A(object): """The A class.""" def __init__(self, name): self.name = name def get_name(self): "Returns the name of the instance." return self.name If you need the lines of source split up, it can be easier to use getsourcelines() instead of getsource(). The return value from getsourcelines() is a tuple containing a list of strings (the lines from the source file), and a starting line number in the file where the source appears. import inspect import pprint import example pprint.pprint(inspect.getsourcelines(example.A.get_name)) $ python inspect_getsourcelines_method.py ([' def get_name(self):\n', ' "Returns the name of the instance."\n', ' return self.name\n'], 48) If the source file is not available, getsource() and getsourcelines() raise an IOError. Method and Function Arguments¶ In addition to the documentation for a function or method, it is possible to ask for a complete specification of the arguments the callable takes, including default values. The getargspec() function returns a tuple containing the list of positional argument names, the name of any variable positional arguments (e.g., *args), the names of any variable named arguments (e.g., **kwds), and default values for the arguments. If there are default values, they match up with the end of the positional argument list. import inspect import example arg_spec = inspect.getargspec(example.module_level_function) print 'NAMES :', arg_spec[0] print '* :', arg_spec[1] print '** :', arg_spec[2] print 'defaults:', arg_spec[3] args_with_defaults = arg_spec[0][-len(arg_spec[3]):] print 'args & defaults:', zip(args_with_defaults, arg_spec[3]) Note that the first argument, arg1, does not have a default value. The single default therefore is matched up with arg2. $ python inspect_getargspec_function.py NAMES : ['arg1', 'arg2'] * : args ** : kwargs defaults: ('default',) args & defaults: [('arg2', 'default')] Class Hierarchies¶ inspect includes two methods for working directly with class hierarchies. The first, getclasstree(), creates a tree-like data structure using nested lists and tuples based on the classes it is given and their base classes. Each element in the list returned is either a tuple with a class and its base classes, or another list containing tuples for subclasses. import inspect import example class C(example.B): pass class D(C, example.A): pass def print_class_tree(tree, indent=-1): if isinstance(tree, list): for node in tree: print_class_tree(node, indent+1) else: print ' ' * indent, tree[0].__name__ return if __name__ == '__main__': print 'A, B, C, D:' print_class_tree(inspect.getclasstree([example.A, example.B, C, D])) The output from this example is the “tree” of inheritance for the A, B, C, and D classes. Note that D appears twice, since it inherits from both C and A. $ python inspect_getclasstree.py A, B, C, D: object A D B C D If we call getclasstree() with unique=True, the output is different. import inspect import example from inspect_getclasstree import * print_class_tree(inspect.getclasstree([example.A, example.B, C, D], unique=True, )) This time, D only appears in the output once: $ python inspect_getclasstree_unique.py object A B C D Method Resolution Order¶ The other function for working with class hierarchies is getmro(), which returns a tuple of classes in the order they should be scanned when resolving an attribute that might be inherited from a base class. Each class in the sequence appears only once. import inspect import example class C(object): pass class C_First(C, example.B): pass class B_First(example.B, C): pass print 'B_First:' for c in inspect.getmro(B_First): print '\t', c.__name__ print print 'C_First:' for c in inspect.getmro(C_First): print '\t', c.__name__ This output demonstrates the “depth-first” nature of the MRO search. For B_First, A also comes before C in the search order, because B is derived from A. $ python inspect_getmro.py B_First: B_First B A C object C_First: C_First C B A object The Stack and Frames¶ In addition to introspection of code objects, inspect includes functions for inspecting the runtime environment while a program is running. Most of these functions work with the call stack, and operate on “call frames”. Each frame record in the stack is a 6 element tuple containing the frame object, the filename where the code exists, the line number in that file for the current line being run, the function name being called, a list of lines of context from the source file, and the index into that list of the current line. Typically such information is used to build tracebacks when exceptions are raised. It can also be useful when debugging programs, since the stack frames can be interrogated to discover the argument values passed into the functions. currentframe() returns the frame at the top of the stack (for the current function). getargvalues() returns a tuple with argument names, the names of the variable arguments, and a dictionary with local values from the frame. By combining them, we can see the arguments to functions and local variables at different points in the call stack. import inspect def recurse(limit): local_variable = '.' * limit print limit, inspect.getargvalues(inspect.currentframe()) if limit <= 0: return recurse(limit - 1) return if __name__ == '__main__': recurse(3) The value for local_variable is included in the frame’s local variables even though it is not an argument to the function. $ python inspect_getargvalues.py 3 ArgInfo(args=['limit'], varargs=None, keywords=None, locals={'local_variable': '...', 'limit': 3}) 2 ArgInfo(args=['limit'], varargs=None, keywords=None, locals={'local_variable': '..', 'limit': 2}) 1 ArgInfo(args=['limit'], varargs=None, keywords=None, locals={'local_variable': '.', 'limit': 1}) 0 ArgInfo(args=['limit'], varargs=None, keywords=None, locals={'local_variable': '', 'limit': 0}) Using stack(), it is also possible to access all of the stack frames from the current frame to the first caller. This example is similar to the one above, except it waits until reaching the end of the recursion to print the stack information. import inspect def recurse(limit): local_variable = '.' * limit if limit <= 0: for frame, filename, line_num, func, source_code, source_index in inspect.stack(): print '%s[%d]\n -> %s' % (filename, line_num, source_code[source_index].strip()) print inspect.getargvalues(frame) print return recurse(limit - 1) return if __name__ == '__main__': recurse(3) The last part of the output represents the main program, outside of the recurse function. $ python inspect_stack.py inspect_stack.py[37] -> for frame, filename, line_num, func, source_code, source_index in inspect.stack(): (['limit'], None, None, {'local_variable': '', 'line_num': 37, 'frame': <frame object at 0x61ba30>, 'filename': 'inspect_stack.py', 'limit': 0, 'func': 'recurse', 'source_index': 0, 'source_code': [' for frame, filename, line_num, func, source_code, source_index in inspect.stack():\n']}) inspect_stack.py[42] -> recurse(limit - 1) (['limit'], None, None, {'local_variable': '.', 'limit': 1}) inspect_stack.py[42] -> recurse(limit - 1) (['limit'], None, None, {'local_variable': '..', 'limit': 2}) inspect_stack.py[42] -> recurse(limit - 1) (['limit'], None, None, {'local_variable': '...', 'limit': 3}) inspect_stack.py[46] -> recurse(3) ([], None, None, {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'inspect_stack.py', 'inspect': <module 'inspect' from '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/inspect.pyc'>, 'recurse': <function recurse at 0xc81b0>, '__name__': '__main__', '__doc__': 'Inspecting the call stack.\n\n'}) There are other functions for building lists of frames in different contexts, such as when an exception is being processed. See the documentation for trace(), getouterframes(), and getinnerframes() for more details. See also - inspect - The standard library documentation for this module. - CommandLineApp - Base class for object-oriented command line applications - Python 2.3 Method Resolution Order - Documentation for the C3 Method Resolution order used by Python 2.3 and later.
https://pymotw.com/2/inspect/index.html
CC-MAIN-2018-47
refinedweb
2,470
50.12
This preview shows page 1. Sign up to view the full content. Unformatted text preview: C H A P T E R 4 Lists CONTENTS Specifications for the ADT List Refining the Specifications Using the ADT List Java Class Library: The Interface List Using a List Is Like Using a Vending Machine PREREQUISITES Introduction Chapter 1 Chapter 3 Appendix B Java Classes Designing Classes Exception Handling OBJECTIVES After studying this chapter, you should be able to G G G Describe the concept of an abstract data type (ADT) Describe the ADT list Use the ADT list in a Java program T his chapter builds on the concepts of encapsulation and data abstraction that were presented in the previous chapter, and it develops the notion of an abstract data type, or ADT. As an example of an abstract data type, we specify and use the ADT list. In doing so we will provide a Java interface for our list. Knowing just this interface, you will be able to use a list in a Java program. You do not need to know how the entries in the list are represented or how the list operations are implemented. Indeed, your program will not depend on these specifics. As you will see, this important program feature is what data abstraction is all about. 79 80 CHAPTER 4 Lists Specifications for the ADT List 4.1 Figure 4-1 A list provides a way to organize data. We can have to-do lists, gift lists, address lists, grocery lists, even lists of lists. These lists provide a useful way for us to organize our lives, as illustrated in Figure 4-1. Each list has a first item, a last item, and usually items in between. That is, the items in a list have a position: first, second, and so on. An item’s position might be important to you, or it might not. When adding an item to your list, you might always add it at the end, or you might insert it between two other items already in the list. A to-do list I have so much to do this weekend — I should make a list. To Do 1. Read Chapter 4 2. Call home 3. Buy card for Sue Everyday lists such as to-do lists, gift lists, address lists, and grocery lists have entries that are strings. What can you do to such lists? G G G G G G G G G G Typically, you add a new entry at the end of the list. Actually, you can add a new entry anywhere: at the beginning, the end, or in between items. You can cross out an entry—that is, remove it. You can remove all entries. You can replace an entry. You can look at any entry. You can determine whether the list contains a particular entry. You can count the number of entries in the list. You can determine whether the list is empty or full. You can display all of the entries in the list. Specifications for the ADT List 81 4.2 When you work with a list, you determine where an entry is or should be. You probably are not conscious of its exact position: Is it tenth? Fourteenth? However, when your program uses a list, a convenient way to identify a particular entry is by the entry’s position within the list. It could be first, that is, at position 1, or second (position 2), and so on. This convention allows you to describe, or specify, the operations on a list more precisely. At this point, you should not be thinking about how to represent a list in your program or how to implement its operations. For the moment, forget about arrays, for example. You first need to clearly know what the list operations do: Focus on what the operations do, not on how they do them. That is, you need a detailed set of specifications before you can use a list in a program. In fact, you should specify the list operations before you even decide on a programming language. At this point, the list is an abstract data type. An abstract data type, or ADT, consists of data having the same type and the operations on that data. An ADT describes its data and specifies its operations. It does not indicate how to store the data or how to implement the operations. Thus, we can discuss ADTs independently of a programming language. In contrast, a data structure is an implementation of an ADT within a programming language. 4.3 To specify the ADT list, we describe its data and specify the operations on that data. Unlike common lists whose entries are strings, the ADT list is more general and has entries that are objects of the same type. The following is a specification of the ADT list: ABSTRACT DATA TYPE LIST DATA G G A collection of objects in a specific order and having the same data type The number of objects in the collection OPERATIONS add(newEntry) Task: Adds newEntry to the end of the list. Input: newEntry is an object. Output: None. add(newPosition, newEntry) Task: Adds newEntry at position newPosition within the list. Input: newPosition is an integer, newEntry is an object. Output: None. remove(givenPosition) Task: Removes from the list the entry at position givenPosition. Input: givenPosition is an integer. Output: None. clear() Task: Removes all entries from the list. Input: None. Output: None. 82 CHAPTER 4 Lists replace(givenPosition, newEntry) Task: Replaces the entry at position givenPosition with newEntry. Input: givenPosition is an integer, newEntry is an object. Output: None. getEntry(givenPosition) Task: Retrieves the entry at position givenPosition in the list. Input: givenPosition is an integer. Output: Returns a reference to the entry at position givenPosition. contains(anEntry) Task: Determines whether the list contains anEntry. Input: anEntry is an object. Output: Returns true if anEntry is in the list, or false if not. getLength() Task: Gets the number of entries currently in the list. Input: None. Output: Returns the number of entries currently in the list as an int. isEmpty() Task: Determines whether the list is empty. Input: None. Output: Returns true if the list is empty, or false if not. isFull() Task: Determines whether the list is full. Input: None. Output: Returns true if the list is full, or false if not. display() Task: Displays all entries that are in the list in the order in which they occur, one per line. Input: None. Output: None. We have only begun to specify the behaviors of these list operations, as the specifications just given leave some details to the imagination. Some examples will help us to better understand these operations so that we can improve the specifications. We’ll need precise specifications before we implement the operations. Programming Tip: After designing a draft of an ADT, confirm your understanding of the operations and their design by writing some pseudocode that uses the ADT. Specifications for the ADT List 4.4 83 Example. When you first declare a new list, it is empty and its length is zero. If you add three objects—a, b, and c—one at a time and in the order given, to the end of the list, the list will appear as a b c The object a is first, and c is last. To save space here, we will sometimes write a list’s contents on one line. For example, we might write a b c to represent this list. The following pseudocode represents the previous three additions to the specific list myList: myList.add(a) myList.add(b) myList.add(c) At this point, myList is not empty, so myList.isEmpty() is false. Since the list contains three entries, myList.getLength() is 3. Notice that adding entries to the end of a list does not change the positions of entries already in the list. Figure 4-2 illustrates these add operations as well as the operations that we describe next. Figure 4-2 The effect of ADT list operations on an initially empty list myList.add(a) myList.add(b) myList.add(c) a a b a b c myList.add(2,d) a d b c 4.5 myList.add(1,e) e a d b c myList.remove(3) e a b c Now suppose that we add entries at various positions within the list. For example, myList.add(2, d) places d at position 2 within the list. Doing so, however, moves b to position 3 and c to position 4, so that the list now contains a d b c 84 CHAPTER 4 Lists If we add e to the beginning of the list by writing myList.add(1, e) the current entries in the list move to the next higher position. The list then contains e a d b c Look at Figure 4-2 again to see the effect of these operations. 4.6 We can retrieve the second entry in this list by writing ref2 = myList.getEntry(2) This expression returns a reference to the second entry. Remember that we are writing pseudocode here. Later examples in Java will show you that a type cast is likely to be necessary. What happens when we remove an entry? For example, myList.remove(3) removes the third entry—d in the previous example—from the list. The list then contains e a b c Notice that entries after the one that was removed move to the next lower position within the list. Figure 4-2 illustrates this change to the list. What if an application requires us to remove an entry from a list but retain the entry for another purpose? Our interpretation of remove would force us to first use getEntry to obtain a reference to the entry and then use remove to remove the entry from the list. We could refine the specification of remove to return a reference to the object removed from the list. To use this version of remove, we would write a pseudocode statement such as ref3 = myList.remove(3) This change makes remove more versatile, as the client could either save or ignore the returned reference. We can replace the third entry b of our list with f by writing myList.replace(3, f) No other entries move or change. We could refine the specification of replace to return a reference to the object that was replaced. So if we wrote ref = myList.replace(3, f) ref would reference the former entry b. Note: The objects in an ADT list have an order determined by the client of the list. To add, remove, or retrieve an entry, you must specify the entry’s position within the list. Refining the Specifications 4.7 The previous specifications ignore at least three difficulties that might arise during the use of the ADT list: G G The operations add, remove, replace, and getEntry are well behaved when the given position is valid for the current list. What happens when one of these operations receives an invalid position number? The methods remove, replace, and getEntry are not meaningful for empty lists. What happens when an empty list invokes one of these operations? Specifications for the ADT List G 85 A list could become full, depending on the list’s implementation. What happens when the client tries to add an entry to a full list? You as class designer need to make decisions about how to handle unusual conditions and include these decisions in your specifications. The documentation for the ADT list should reflect both these decisions and the detail that the previous examples demonstrate. 4.8 In general, you can address unusual situations in several ways. Your method could G G G G G Assume that the invalid situations will not occur. This assumption is not as naive as it might sound. A method could state as an assumption—that is, a precondition—restrictions to which a client must adhere. It is then up to the client to enforce the precondition by checking that the precondition is satisfied before invoking the method. Notice that the client has methods such as isEmpty and getLength to help with this task. As long as the client obeys the restriction, the invalid situation will not occur. Ignore the invalid situations. A method could simply do nothing when given invalid data. Doing absolutely nothing, however, leaves the client wondering what happened. Make reasonable assumptions and act in a predictable way. For example, if a client tries to remove the sixth entry from a three-entry list, the remove method could either remove the last entry instead or return null. Return a boolean value that indicates the success or failure of an operation. Throw an exception. As Appendix B shows, throwing an exception is often a desirable way for a Java method to react to unusual events that occur during its execution. The method can simply report a problem without deciding what to do about it. The exception enables each client to do what is needed in its own particular situation. To handle errors in this way, you must write try-catch blocks to use the method. For simplicity, we adopt the philosophy that methods should throw exceptions only in truly exceptional circumstances, when no other reasonable solution exists. Future chapters will include some examples of handling exceptions. 4.9 After you have identified all unusual circumstances, you should specify how your methods will behave under each of these circumstances. For example, it would be reasonable for the add method to throw an exception if it tries to add an entry at an invalid position. However, it might be just as reasonable for the method to return false in these situations. Your documentation for your ADT should describe these specifications. As your specifications become more detailed, they increasingly should reflect your choice of programming language. Ultimately, you can write a Java interface (see Chapter 3) for the class that will implement the ADT. Note: A first draft of an ADT’s specifications often overlooks or ignores situations that you really need to consider. You might intentionally make these omissions to simplify this first draft. Once you have written the major portions of the specifications, you can concentrate on the details that make the specifications complete. 4.10 The following Java interface contains the methods for an ADT list and detailed comments that describe their behaviors. Recall that a class interface does not include data fields, constructors, private methods, or protected methods. We assume that items in the list will be objects—that is, instances of a class. For example, we could have a list of strings. To accommodate entries of any class type, the list methods use Object as the type of entry. As we discussed previously, all classes ultimately are derived from Object. 86 CHAPTER 4 Lists For lists of primitive types, we could replace each occurrence of Object with the desired type. Another possibility, however, would be to place instances of an appropriate wrapper class in our list. For example, instead of instances of the primitive type int, we could use instances of the wrapper class Integer. (Appendix A discusses wrapper classes.) /** An interface for the ADT list. * Entries in the list have positions that begin with 1. */ public interface ListInterface { /** Task: Adds a new entry to the end of the list. * @param newEntry the object to be added as a new entry * @return true if the addition is successful, or false if not */ public boolean add(Object newEntry); /** Task: Adds a new entry at a specified position within * the list. Entries originally at and above the specified * position are at the next higher position within the list. * The list’s size is increased by 1. * @param newPosition an integer that specifies the desired * position of the new entry; newPosition >= 1 * and newPosition <= getLength()+1 * @param newEntry the object to be added as a new entry * @return true if the addition is successful, or false if not */ public boolean add(int newPosition, Object Object remove(int givenPosition); /** Task: Removes all entries from the list. */ public void clear(); /** Task: Replaces the entry at a given position in the list. * @param givenPosition an integer that indicates the position of the * entry to be replaced; givenPosition >= 1 * and givenPosition <= getLength() * @param newEntry the object that will replace the entry at the * position givenPosition * @return true if the replacement occurs, or false if either the * list was empty or givenPosition is invalid */ public boolean replace(int givenPosition, Object newEntry); /** Task: Retrieves the entry at a given position in the list. * @param givenPosition an integer that indicates the position of * the desired entry; givenPosition >= 1 * and givenPosition <= getLength() * @return a reference to the indicated list entry, if found, Specifications for the ADT List 87 * otherwise returns null */ public Object getEntry(int givenPosition); /** Task: Determines whether the list contains a given entry. * @param anEntry the object that is the desired entry * @return true if the list contains anEntry, or false if not */ public boolean contains(Object that are in the list, one per * line, in the order in which they occur in the list. */ public void display(); } // end ListInterface Question 1 Write pseudocode statements that add some objects to a list, as follows. First add c, then a, then b, and then d such that the order of the objects in the list will be a, b, c, d. Question 2 Write pseudocode statements that exchange the third and seventh entries in a list of ten objects. Note: The entries in a list of n entries are numbered from 1 to n. Although you cannot add a new entry at position 0, you can add one at position n + 1. 4.11 After specifying an ADT and writing a Java interface for its operations, you should write some Java statements that use the ADT. In this way, you check both the suitability and your understanding of the specifications. It is better to revise the design or documentation of the ADT now instead of after you have written its implementation. An added benefit of doing this task carefully is that you can use these same Java statements later to test your implementation. The following section looks at several examples that use a list. These examples can be part of a program that tests your implementation. Programming Tip: Write a test program before you implement a class Writing Java statements that test a class’s methods will help you to fully understand the specifications for the methods. Obviously, you must understand a method before you can implement it correctly. If you are also the class designer, your use of the class might help you see desirable changes to your design or its documentation. You will save time if you make these revisions before you have implemented the class. Since you must write a program that tests your implementation sometime, why not get additional benefits from the task by writing it now instead of later? 88 CHAPTER 4 Lists Using the ADT List Imagine that we hire a programmer to implement the ADT list in Java, given the interface and specifications that we have developed so far. If we assume that these specifications are clear enough for the programmer to complete the implementation, we can use the ADT’s operations in a program without knowing the details of the implementation. That is, we do not need to know how the programmer implemented the list to be able to use it. We only need to know what the ADT list does. This section assumes that we have an implementation for the list and demonstrates how we can use a list in our program. 4.12 Figure 4-3 Example. Imagine that we are organizing a local road race. Our job is to note the order in which the runners finish the race. Since each runner wears a distinct identifying number, we can add each runner’s number to the end of a list as the runners cross the finish line. Figure 4-3 illustrates such a list. A list of numbers that identify runners in the order in which they finished a race 16 4 33 27 The following Java program shows how we can perform this task by using the ADT list. It assumes that the class AList implements the Java interface ListInterface that you saw in the previous section. Since ListInterface assumes that the items in the list are objects, we will treat each runner’s identifying number as a string. public class ListClient { public static void main(String args) { testList(); } // end main public static void testList() { ListInterface runnerList = new AList(); // has only methods // in ListInterface runnerList.add("16"); // winner runnerList.add(" 4"); // second place Using the ADT List 89 runnerList.add("33"); // third place runnerList.add("27"); // fourth place runnerList.display(); } // end testList } // end ListClient The output from this program is 16 4 33 27 Notice that the data type of runnerList is ListInterface instead of AList. While either type is correct, using ListInterface obliges runnerList to call only methods in the interface. 4.13 Example. The previous example uses the list method display to display the items in the list. We might want our output in a different form, however. The following method is an example of how a client could display the items in a list without using the method display. Notice the use of the list methods getLength and getEntry. Also notice that the data type of the input parameter aList is ListInterface. Thus, we can use as the argument of the method an instance of any class that implements ListInterface. That is, the method works for any implementation of the ADT list. public static void displayList(ListInterface aList) { int numberOfEntries = aList.getLength(); System.out.println("The list contains " + numberOfEntries + " entries, as follows:"); for (int position = 1; position <= numberOfEntries; position++) System.out.println(aList.getEntry(position) + " is entry " + position); System.out.println(); } // end displayList Assuming the list runnerList from the example in Segment 4.12, the expression produces the following output: display- List(runnerList) The list contains 4 entries, as follows: 16 is entry 1 4 is entry 2 33 is entry 3 27 is entry 4 4.14 Example. A professor wants an alphabetical list of the names of the students who arrive for class today. As each student enters the room, the professor adds the student’s name to a list. It is up to the professor to place each name into its correct position in the list so that the names will be in alphabetical order. The ADT list does not choose the order of its entries. The following Java statements place the names Amy, Ellen, Bob, Drew, Aaron, and Carol in an alphabetical list. The comment at the end of each statement shows the list after the statement executes. // make an alphabetical list of the names // Amy, Ellen, Bob, Drew, Aaron, Carol ListInterface alphaList = new AList(); 90 CHAPTER 4 Lists alphaList.add(1, alphaList.add(2, alphaList.add(2, alphaList.add(3, alphaList.add(1, alphaList.add(4, "Amy"); "Ellen"); "Bob"); "Drew"); "Aaron"); "Carol"); // // // // // // Amy Amy Ellen Amy Bob Ellen Amy Bob Drew Ellen Aaron Amy Bob Drew Ellen Aaron Amy Bob Carol Drew Ellen After initially adding Amy to the beginning of the list and Ellen to the end of the list (at position 2), the professor inserts G G G G Bob between Amy and Ellen at position 2 Drew between Bob and Ellen at position 3 Aaron before Amy at position 1 Carol between Bob and Drew at position 4 This technique of inserting each name into a collection of alphabetized names is called an insertion sort. We will discuss this and other ways of ordering items in a later chapter. If we now remove the entry at position 4—Carol—by writing alphaList.remove(4); Drew and Ellen will then be at positions 4 and 5, respectively. Thus, alphaList.getEntry(4) would return a reference to Drew. Finally, suppose that we want to replace a name in this list. We cannot replace a name with just any name and expect that the list will remain in alphabetical order. Replacing Bob with Ben by writing alphaList.replace(3, "Ben"); would maintain alphabetical order, but replacing Bob with Nancy would not. The list’s alphabetical order resulted from our original decisions about where to add names to the list. The order did not come about automatically as a result of list operations. That is, the client, not the list, maintained the order. We could, however, design an ADT that maintains its data in alphabetical order. You will see an example of such an ADT in Chapter 13. Question 3 Suppose that alphaList contains a list of the four strings Amy, Ellen, Bob, and Drew. Write Java statements that swap Ellen and Bob and that then swap Ellen and Drew so that the list will be in alphabetical order. 4.15 Example. Let’s look at a list of objects that are not strings. Suppose that we have the class Name from Chapter 1 that represents a person’s first and last names. The following statements indicate how we could make a list of the names Amy Smith, Tina Drexel, and Robert Jones: // make a list of names as you think of them ListInterface nameList = new AList(); Name amy = new Name("Amy", "Smith"); nameList.add(amy); nameList.add(new Name("Tina", "Drexel"); nameList.add(new Name("Robert", "Jones"); Now let’s retrieve the name that is second in the list: Name secondName = (Name)nameList.getEntry(2); Notice that we must type-cast the object that getEntry returns. To accommodate entries of any class type, the list methods use Object as the type of entry. In particular, the return type of getEntry is Object. Thus, we must type-cast the returned entry to the data type of the entries in the list. That type is Name in this example. Java Class Library: The Interface List 91 Earlier we said that an ADT has data of the same type. As you will see in the next chapters, the implementations of the ADT list will not enforce this requirement. As this example just showed, you must know the data type of an entry in a list when you retrieve or remove it so that you can perform any necessary type cast. Although Java will let you place objects of various types in the same list, you would need to keep track of their data types. In general, requiring an ADT’s entries to have the same type makes life easier. Programming Tip: Type-cast returned objects ADT entries that a method returns are of type Object and must be type-cast to their actual type. Question 4 a. b. 4.16 The example in Segment 4.13 used getEntry to retrieve an entry from a list. Why was a type cast to String not necessary? Would a type cast to String be wrong? Example. Let’s talk a bit more about the previous example. The variable secondName is a reference to the second object of type Name in the list. Using this reference, we can modify the object. For example, we could change its last name by writing secondName.setLast("Doe"); If the class Name did not have set methods like setLast, we would be unable to modify the objects in this list. For instance, if we had a list of strings, we would not be able to alter one of the strings in this way. Once we create an object of the class String, we cannot alter it. We could, however, replace an entire object in the list—regardless of its type—by using the ADT list operation replace. A class, such as Name, that has set methods is a class of mutable objects. A class, such as String, without set methods is a class of immutable objects. Chapter 15 talks about such classes in more detail. Java Class Library: The Interface List 4.17 The standard package java.util contains an interface for the ADT list that is similar to our interface. Its name is List. The major difference between a list in the Java Class Library and our ADT list is the numbering of a list’s entries. A list in the Java Class Library uses the same numbering scheme as a Java array: The first entry is at position, or index, 0. In contrast, we begin our list at position 1. The interface List also declares more methods than our interface does. The following method signatures are for a selection of methods that are similar to the ones you have seen in this chapter. We have used blue to indicate where they differ from our methods. public public public public public public public public public boolean add(Object newEntry) void add(int index, Object newEntry) Object remove(int index) void clear() Object set(int index, Object anEntry) // like replace Object get(int index) // like getEntry boolean contains(Object anEntry) int size() // like getLength boolean isEmpty() The second add method is a void method. It throws an exception if index is out of range, instead of returning a boolean value, as our add method does. The method set is like our replace method, but 92 CHAPTER 4 Lists it returns a reference to the entry that was replaced in the list instead of returning a boolean value. The other differences are simply in the method names used. For example, the interface List uses get for our getEntry and size for our getLength. You can learn more about the interface List at Using a List Is Like Using a Vending Machine 4.18 Figure 4-4 Imagine that you are in front of a vending machine, as Figure 4-4 depicts; better yet, take a break and go buy something from one! A vending machine I’m really thirsty—where is that vending machine? When you look at the front of a vending machine, you see its interface. By inserting coins and pressing buttons, you are able to make a purchase. Here are some observations that we can make about the vending machine: G G G G G You can perform only the specific tasks that the machine’s interface presents to you. You must understand these tasks—that is, you must know what to do to buy a soda. You cannot see or access the inside of the machine, because a steel shell encapsulates it. You can use the machine even though you do not know what happens inside. If someone replaced the machine’s inner mechanism with an improved version, leaving the interface unchanged, you could still use the machine in the same way. You, as the user of a vending machine, are like the client of the ADT list that you saw earlier in this chapter. The observations that we just made about the user of a vending machine are similar to the following observations about a list’s client: G The client can perform only the operations specific to the ADT list. These operations often are declared within a Java interface. Using a List Is Like Using a Vending Machine G G G G 4.19 C HAPTER S UMMARY 93 The client must adhere to the specifications of the operations that the ADT list provides. That is, the author of the client must understand how to use these operations. The client cannot access the data within the list without using an ADT operation. The principle of encapsulation hides the data within the ADT. The client can use the list, even though it cannot access the list’s entries directly—that is, even though the programmer does not know how the data is stored. If someone changed the implementation of the list’s operations, the client could still use the list in the same way, as long as the interface did not change. In the examples of the previous section, each list is an instance of a class that implements the ADT list. That is, each list is an object whose behaviors are the operations of the ADT list. You can think of each such object as the vending machine that we just described. Each object encapsulates the list’s data and operations just as the vending machine encapsulates its product (soda cans) and delivery system. Some ADT operations have inputs analogous to the coins you insert into a vending machine. Some ADT operations have outputs analogous to the change, soda cans, messages, and warning lights that a vending machine provides. Now imagine that you are the designer of the front, or interface, of the vending machine. What can the machine do, and what should a person do to use the machine? Will it help you or hinder you to think about how the soda cans will be stored and transported within the machine? We maintain that you should ignore these aspects and focus solely on how to use the machine—that is, on your design of the interface. Ignoring extraneous details makes your task easier and increases the quality of your design. Recall that abstraction as a design principle asks you to focus on what instead of how. When you design an ADT, and ultimately a class, you use data abstraction to focus on what you want to do with or to the data without worrying about how you will accomplish these tasks. We practiced data abstraction at the beginning of this chapter when we designed the ADT list. We referred to each entry in our list by its position within the list. As we chose the methods that a list would have, we did not consider how we would represent the list. Instead, we focused on what each method should do. Ultimately, we wrote a Java interface that specified the methods in detail. We were then able to write a client that used the list, again without knowledge of its implementation. If someone wrote the implementation for us, our program would presumably run correctly. If someone else gave us a better implementation, we could use it without changing our already-written client. This feature of the client is a major advantage of abstraction. G An abstract data type, or ADT, consists of both data and a set of operations on the data. An ADT provides a way to design a new data type independently of the choice of programming language. G A list is an ADT whose data consists of ordered entries. Each entry is identified by its position within the list. G A Java program manipulates or accesses a list’s entries by using only the operations defined for the ADT list. The manifestation of the ADT in a programming language encapsulates the data and operations. That is, the particular data representations and method implementations are hidden from the client. G When you use data abstraction to design an ADT, you focus on what you want to do with or to the data without worrying about how you will accomplish these tasks. That is, you ignore the details of how you represent data and how you manipulate it. 94 CHAPTER 4 Lists P ROGRAMMING T IPS After designing a draft of an ADT, confirm your understanding of the operations and their design by writing some pseudocode that uses the ADT. G After specifying an ADT and writing a Java interface for its operations, write some Java statements that use the ADT. In this way, you check both the suitability and your understanding of the specifications. An added benefit of doing this task carefully is that later you can use these same Java statements to test your implementation. G E XERCISES G ADT entries that a method returns are of type Object and must be type-cast to their actual type. 1. If myList is an empty list, what does it contain after the following statements execute? myList.add("alpha"); myList.add(1, "beta"); myList.add("gamma"); myList.add(2, "delta"); myList.add(4, "alpha"); myList.remove(2); myList.remove(2); myList.replace(3, "delta"); 2. Suppose that you want an operation for the ADT list that removes the first occurrence of a given object from the list. The signature of the method could be as follows: public boolean remove(Object anObject) Write comments that specify this method. 3. Write Java statements at the client level that return the position of a given object in the list myList. Assume that the object is in the list. 4. Suppose that you want an operation for the ADT list that returns the position of a given object in the list. The signature of the method could be as follows: public int getPosition(Object anObject) Write comments that specify this method. 5. Suppose that the ADT list did not have a method replace. Write Java statements at the client level that replace an object in the list nameList. The object’s position in the list is givenPosition and the replacement object is newObject. 6. Suppose that the ADT list did not have a method contains. Suppose further that nameList is a list of Name objects, where Name is as defined in Chapter 1. Write Java statements at the client level that determine whether the Name object myName is in the list nameList. 7. Suppose that you have a list that is created by the following statement: ListInterface studentList = new AList(); Imagine that someone has added to the list several instances of the class Student that Chapter 2 defined. a. Write Java statements that display the last names of the students in the list in the same order in which the students appear in the list. Do not alter the list. b. Write Java statements that interchange the first and last students in the list. Using a List Is Like Using a Vending Machine 95 8. Consider finished tossing coins, compute the total value of the coins that came up heads. Assume that the list headsList has been created for you and is empty initially. P ROJECTS 1. The introduction to this book spoke of a bag as a way to organize data. A grocery bag, for example, contains items in no particular order. Some of them might be duplicate items. The ADT bag, like the grocery bag, is perhaps the simplest of data organizations. It holds objects but does not arrange or organize them further. Design an ADT bag. Many operations are analogous to those of the ADT list, but the entries do not have positions. In addition to these basic operations, include the following: G G G A union operation that combines the contents of two bags into a third bag An intersection operation that creates a bag of those items that occur in both of two bags A difference operation that creates a bag of the items that would be left in one bag after removing those that also occur in another bag Specify each ADT operation by stating its purpose, by describing its parameters, and by writing preconditions, postconditions, and a pseudocode version of its signature. Then write a Java interface for the ADT bag that includes javadoc-style comments. 2. You might have a piggy bank or some other receptacle to hold your spare coins. The piggy bank holds the coins but gives them no other organization. And certainly the bank can contain duplicate coins. The piggy bank is like the ADT bag that you designed in Project 1, but it is simpler. It has only three operations: You can add a coin to the bank, remove one (you shake the bank, so you have no control over what coin falls out), or determine whether the bank is empty. Design the ADT piggy bank, assuming that you have the ADT bag from Project 1 and the class Coin from Exercise 8. Write a Java interface for the ADT piggy bank that includes javadoc-style comments. 3. Santa Claus allegedly keeps lists of those who are naughty and those who are nice. On the naughty list are the names of those who will get coal in their stockings. On the nice list are those who will receive gifts. Each object in this list contains a name (an instance of Name, as defined in Chapter 1) and a list of that person’s gifts (an instance of an ADT list). Design an ADT for the objects in the nice list. What operations should this ADT have? After you design the ADT, implement it by writing a Java class. Assume that you have an implementation of the ADT list—that is, assume that the class AList implements ListInterface, as given in this chapter. Finally, create some instances of your class and place them on Santa’s nice list. 96 CHAPTER 4 Lists 4. A recipe contains a title, a list of ingredients, and a list of directions. An entry in the list of ingredients contains an amount, a unit, and a description. For example, 2 cups of flour could be an entry in this list. Implement a class of recipes, assuming that the class AList implements ListInterface, as given in this chapter. The amount of an ingredient can be a double value or an instance of the class MixedNumber, which was described in Project 3 of Chapter 3. ... View Full Document This note was uploaded on 04/29/2010 for the course CS 5503 taught by Professor Kaylor during the Spring '10 term at W. Alabama. - Spring '10 - Kaylor - Computer Science Click to edit the document details
https://www.coursehero.com/file/5877116/CarrCh04v2/
CC-MAIN-2017-09
refinedweb
6,944
63.39
Writing modular CSS (Part 2) — Namespaces22nd Mar 2017 Last week, I shared how I use BEM to create a sensible CSS architecture. Although BEM is awesome, it’s only part of the solution. There’s another part I’ve yet to mention — namespaces. In this article today, I want to share with you why BEM isn’t enough and how I use namespaces to bridge the gap. Why BEM isn’t enough The examples I showed you last week were pretty simple. I only showed you how to deal with different modifiers and children (or grandchildren) elements within a single block. What happens if there’s more than one block? Things get a little more complicated. Let’s use a site-wide navigation to illustrate the relationship between two blocks. <nav class="main-nav"> <a href="#">Home</a> <button class="button">Menu</button> </nav> Awesome. Now there are two blocks. One called .main-nav while the other is called .button. .button exists within .main-nav. Let’s say you want to change the button color from blue to green. You also want to add some padding to the left of .button so it separates itself from the home link. The question is, how should you write the CSS code? Here are a few possible answers: - Add both marginand background-colorto .main-nav .button. - Add both marginand background-colora button--modifier. - Add marginto .main-nav .buttonand background-colora button--modifier. - Add marginto .main-nav aand background-colora .main-nav .button. - Add marginto .main-nav aand background-colora button--modifier. Which one makes sense? How do you ensure every developer on your project feels the same way? Even if all your developers are clones of you (and therefore think the same way), how do you know if you did not introduce a side effect (that broke another part of the site)? 😱😱😱. Honestly, it’s hard to guarantee! There are too many possible factors that are open to interpretation if we only BEM. This is where namespaces come in. It helps you create a structure that governs how CSS properties get written. If you follow the convention, you’ll be able to write CSS without being afraid of side effects. Here’s an example. Let’s say I switched the code above to one with namespaces. The HTML will be completely the same (less a few class prefixes). Pay special attention to .o and .c prefixes in this example: <nav class="c-main-nav"> <a href="#">Home</a> <button class="o-button">Menu</button> </nav> What does .o- and .c- say? From this code, I know I can change the color of .o-button if I want to, but I shouldn’t add any margins to .o-button. How? Well, I’ll have to explain these namespaces, so let’s dive right in :) The namespaces I use Here’s a list of namespaces I use: .l-: layouts .o-: objects .c-: components .js: JavaScript hooks .is-| .has-: state classes .t1| .s1: typography sizes .u-: utility classes Let’s dive into what each namespace is, and what its supposed to do. Before moving on, if you remain unconvinced about namespaces, I highly recommend you to check out Harry Robert’s more transparent ui code with namespaces. (Fun fact: Harry’s inspired me to use namespaces). If you read his article, just note that I namespace differently from Harry. (I’ll share what’s different when we come to it). With that, let’s jump into the first namespace — layouts. Layouts with .l- I’m pretty sure you’ve heard of Object Oriented CSS (OOCSS) by Nicole Sullivan. If you have yet to dive into it, the main idea behind OOCSS is the separation of skin and structure. In other words, properties that affect the position of a block or its elements should be abstracted into a separate class for reusability. In CSS, the act of positioning a block is also called laying out the block. In a general sense, positioning is given the term layout. Maybe it’s just a happy coincidence (just maybe 😉), but Jonathan Snook recommends a .l- prefix for layout rules in SMACSS. These two paradigms share the same principles when it comes to layouts. As such, I happily stole .l- from SMACSS as the layout namespace. Since you understand the origins of the namespace, it probably helps you understand how it’s used as well. When it comes to layouts, I split layouts into two different categories — global layouts and block-level layouts. Global layouts Global layouts are layouts that are applied globally on all pages. (Duh 😑). In my use case, they are usually big grid containers that are used everywhere. An example is the .l-wrap class: // I like to write in Sass :) .l-wrap { padding-left: 1em; padding-right: 1em; @media (min-width: 1000px) { max-width: 800px; margin-left: auto; margin-right: auto; } } I’ll use this .l-wrap class everywhere, like in the header and footer to align content: <div class="site-header"> <div class="l-wrap"> <!-- stuff --> </div> </div> <div class="site-footer"> <div class="l-wrap"> <!-- stuff --> </div> </div> Since these classes are used globally, I prefer to write them in a _layouts.scss partial. Block-level layouts Each block (either object or components, as we’ll discuss later) may have its own layouts. Through personal experience, I discovered that these layouts are often independent of the global layout. Let me give you an example. When I created the website for Mastering Responsive Typography, I added a payment form that looks like the following: In the design above, you can see that the form contains two rows of input elements. There are two equal-sized input fields in the first row, and two input fields of different sizes in the second row. To differentiate between the three different input sizes, I’ve opted to use a layout prefix: > Did you notice how I kept the BEM implementation even to layouts as well? This makes things much clearer for me. You can immediate see where my CSS would go to. It’s incredibly clear. .l-form {/* container styles */} .l-form__item {/* half-width styles */} .l-form__item--large {/* larger-width styles */} .l-form__item--small {/* smaller-width styles */} Since .l-form, .l-form__item, .l-form__item--small and .l-form__item--large has nothing to do with other blocks, I write these classes in _form.scss to keep context. By the way, some people disagreed with my thoughts on removing .block when .block--modifier is present in my previous article. Well, watch what happens if you insert all the “required” BEM classes in this case, you’ll notice the “HTML starts to bloat”: <form class="form l-form" action="#"> <div class="form__row"> <div class="form__item l-form__item"></div> <div class="form__item l-form__item"></div> </div> <div class="form__row"> <!-- This HTML starts to get looooong 😢 --> <div class="form__item l-form__item l-form__item--large"></div> <div class="form__item l-form__item l-form__item--small"></div> </div> <!-- ... --> </form> One final note: Harry uses the object namespace ( .o-) to signify structural layouts like this. I just group them into .l- and use .o- for something else. With that, let’s move on to objects (my version 😜). Objects with .o- Objects ( .o-) are the smallest building blocks of a website. Consider them to be Lego blocks where you can copy-paste anywhere in your website. If you’ve heard of Atomic Design by Brad Frost, consider objects to be a hybrid of elements and molecules. Objects have the following properties: - Objects uses the .o-prefix - They cannot contain other objects or components. - They are context independent. - Certain objects can ignore the .o-prefix when it makes sense. Objects cannot contain other objects or components Objects can be small or large. The number of HTML elements within the object isn’t relevant. Let me explain. For example, buttons are objects. They’re small and they can be placed anywhere. It’s quite self-evident: <a href="#" class="o-button">A button</a> An example of a larger object is the countdown timer I built for Mastering Responsive Typography: The HTML of the countdown timer is: <div class="o-countdown jsCountdown"> <div class="o-countdown__inner"> <span data-1</span> <span>day</span> </div> <div class="o-countdown__inner"> <span data-21</span> <span>hours</span> </div> <div class="o-countdown__inner"> <span data-41</span> <span>minutes</span> </div> <div class="o-countdown__inner"> <span data-50</span> <span>seconds</span> </div> </div> Notice .o-countdown contains three layers of HTML elements. It’s huge, but it’s still an object since there isn’t any other objects or components in it. The actual number of elements within the .o-countdown is irrelevant because all inner elements can only exist when there’s .o-countdown. Objects are context independent When I say objects are context independent, I mean they don’t know where they’re used. You could pick any object up, throw it somewhere else and it won’t break the structure of your site. This also means objects should not change any structure outside itself. So, object blocks cannot contain any of these properties/values: absoluteor fixedposition. margin. padding(unless you have a background-colorapplied. In this case, it doesn’t interrupt break the alignment outside the object). float. - etc… Since you know objects need to be context independent, you immediately know the .button in our site-wide navigation example earlier cannot contain any margins. Here’s an example of a typical .o-button object in my stylesheets: /* Check back to the previous article if you don't understand this whacky selector. */ [class*='o-button']:not([class*='o-button__']) { display: inline-block; padding: 0.75em 1.25em; border-radius: 4px; background-color: green; color: white; font-size: inherit; line-height: inherit; transition: all 0.15s ease-in-out; } Although objects cannot affect external structure, it can change it’s internal structure as it sees fit. For example, the .o-countdown timer I mentioned could have the following HTML and CSS: <div class="o-countdown l-countdown jsCountdown"> <div class="o-countdown__inner l-countdown__inner"> <span data-3</span> <span>days</span> </div> <div class="o-countdown__inner l-countdown__inner"> <span data-20</span> <span>hours</span> </div> <div class="o-countdown__inner l-countdown__inner"> <span data-57</span> <span>minutes</span> </div> <div class="o-countdown__inner l-countdown__inner"> <span data-33</span> <span>seconds</span> </div> </div> .l-countdown { display: flex; } .l-countdown__inner { /* Do as you please, maybe? */ } The bottom line is, you can freely style an object as long as it doesn’t affect anything outside. (Also, make sure you don’t accidentally add padding and make it look misaligned). Certain objects can ignore the .o- prefix when it makes sense. Whoa, are we breaking the rules already? Heck yes! 😈. It just doesn’t make sense for some objects to contain the .o- prefix (or even a class for that matter) since they’re used so much. One such example is the input element: <input type="text"> Sure, you can tag a class to the input if you want, but what happens if you can’t access the input element to give it a class? Instead of modifying input classes, I’ll do this: @mixin input { padding: 0.5em 0.75em; font-size: inherit; line-height: inherit; font-family: inherit; } input[type="text"], input[type="email"], input[type="textarea"] { @include input; } // ... Another example of objects I feel shouldn’t require an .o- prefixes are typefaces. They get special treatment (as I’ll explain later). Feel free to disagree on this point though. Objects in summary Objects ( .o-) are the smallest building blocks of a website. They have the following properties: - Objects uses the .o-prefix. - They cannot contain other objects or components. - They are context independent. - Certain objects can ignore the .o-prefix when it makes sense. Let’s move on to components Components with .c- If objects are the smallest build blocks, components are larger building blocks that you can use throughout your site. If you’ve read Atomic Design, consider components to be organisms. (Except this organism can contain other organisms 😉). Components have the following properties: - Components uses a .c-prefix. - Components can contain other objects and components. - Components are context aware. Let’s dive into the properties and I’ll supplement you with much-needed examples 😜. Components can contain other objects and components Let’s go back to the form I described where I talked about layouts. It’s the perfect example of a component. Earlier, I mentioned the following HTML: > I actually omitted a lot of code to make it reasonable to look at in the layouts section. If we dig deeper, you’ll see there are input and .o-button objects. <form class="c-form l-form" action="#"> <div class="c-form__row"> <div class="c-form__item l-form__item"> <label for="fname"> <span>First Name</span> <input type="text" id="fname" name="fname"> </label> </div> <!-- ... the email input item --> </div> <!-- ... other form_rows --> <div class="c-form__row"> <button class="o-button c-form__button">Buy Mastering Responsive Typography!</button> </div> </form> See how .c-form contains other objects now? :) Components are context aware (usually) Components are large enough that you want to take special care about positioning them in different places. For example, this .c-form component can either be placed in a full-width or sidebar context. Here’s what the form looks like in a sidebar context: Immediately, you can see three things are altered: - Label gets hidden - layout of inputand o-buttonobjects becomes full-width Font-sizeand line-heightof text becomes smaller on button objects. The HTML for this altered form can be: <form class="c-form--sidebar l-form--sidebar" action="#"> <div class="c-form__row"> <div class="c-form__item l-form__item"> <label for="fname"> <span>First Name</span> <input type="text" id="fname" name="fname"> </label> </div> </div> <!-- ... the email input row --> <div class="c-form__row"> <button class="o-button c-form__button">Buy Mastering Responsive Typography!</button> </div> </form> And the respective (S)CSS changes are: .l-from--sidebar { .l-form__item { /* change to full width style */} } .c-form--sidebar { label { // @include is-invisible; } .c__button { font-size: 16px; line-height: 1.25; } } One more thing. Notice I mixed an object and component class in .c-form__button? This is called a BEM mix, which allows me to style an object with the component’s class without affecting the original button. Components in summary Components ( .c-) are the larger building blocks of a website. They have the following properties: - They use the .c-prefix. - They can contain other objects or components. - They are context aware. Let’s move on to the next namespace JavaScript hooks with .js Javascript hooks ( .js) indicate if an object/component requires JavaScript. An example is the countdown timer I mentioned earlier: <div class="o-countdown jsCountdown"> <!-- ... --> </div> The great thing about using JavaScript namespaces is that you can separate JS functionality from styles, which makes them much easier to maintain. For example, the .jsCountdown class you’ve just seen tells me immediately that .o-countdown requires JavaScript to work properly. If there’s a need to change o-countdown to c-countdown sometime in future, I can do so without worrying about breaking any JS functionality. JavaScript hooks are pretty straightforward, so let’s move on. State classes with .is- or .has- State classes indicate the current state of the object/component. When a state class is applied, you immediately know if an object/component has a dropdown ( .has-dropdown) or is currently in the opened state ( .is-open). These lovely classes came from SMACSS (if you were wondering). When you style state classes in your CSS, I suggest you keep the styles as close as possible to the object/component in question. For example: // Sass .object { &.is-animating { /* styles */} } If you don’t use Sass, you can also opt to write your CSS this way: .object.is-animating { /* styles */ } You probably know about state classes since they’ve been introduced long ago by Jonathan. I shall not bore you further :) Let’s move on. Typography classes with .t or .s One best practice in typography is to use only a handful of styles (sizes, typefaces, etc) on a webpage. Now, you’re probably writing typography styles in headings <h1> to <h6> like this: h1 { /* styles */ } h2 { /* styles */ } h3 { /* styles */ } h4 { /* styles */ } h5 { /* styles */ } h6 { /* styles */ } This is great for a start if your website is simple, without the need to use the same heading styles for multiple objects/components. What if, for instance, you have a navigation with links that are styled exactly like your h5? Do you do this? <!-- No! Don't do this! --> <nav class="c-nav"> <h5><a href="#">Link</a></h5> <h5><a href="#">Link</a></h5> <h5><a href="#">Link</a></h5> </nav> Obviously not. A better way is to change your CSS. So, maybe this? nav a { font-size: 14px; line-height: 1.25; } Although the CSS version is slightly better, you no longer have one source of truth when it comes to typography styles. It’s only a matter of time before you end up with 30 different combinations… Here’s one potential solution. Instead of just styling <h1> - <h6>, you can create classes .h1 to .h6 to apply to your HTML, like this: <nav class="c-nav"> <a class="h5" href="#">Link</a> <a class="h5" href="#">Link</a> <a class="h5" href="#">Link</a> </nav> I like the simplicity of this solution where there’s one source of truth for typography. You’ll always be able to tell the number of different typography sizes in your website by just visiting a _typography.scss file. Now, although the .h1 - .h6 class solution is great, I highly recommend against going with .h1 - .h6 for your classes, simply because they’re implicitly tied to <h1>- <h6> objects. What happens if you have a <h2> element, but instead decide to style it with .h3? Another developer who takes over your codebase might experience an initial dissonance they go "why is .h3 doing with <h2>?!" So, instead of .h1 to .h6, I give typography classes different prefixes, depending on whether they’re larger or smaller than my base font-size. Here’s an example: .t1- largest font-size. .t2- second largest font-size. .t3- third largest font-size. .s1- first font-size smaller that base font-size. .s2- second font-size smaller that base font-size. - … These five classes are typically everything I need for every project (so far). The good thing about such a convention is that I’m able to tell the size of an element at a glance. In the example below, I know for sure this link is one size smaller than my base font-size. <nav><a class="s1" href="#" >Link</a></nav> Now, what happens if you don’t have control over your HTML, but want to include the typography class sizes nevertheless? For this scenario, I’d recommend creating and using mixins, like this: @mixin s1 { font-size: 14px; line-height: 1.25 } h1, nav a { @include s1; } One final thing before we move on. Pay special attention to this. Typography classes are subsets of objects. You should apply the same set of rules to typography classes as you would to objects. This means you should not add margin or padding to typography classes, for example. Instead, these margin or padding should be added directly to components. (Read Harry’s managing typography on large apps to understand why I recommend this). Let’s move on. Utility classes with .u- Utility classes are helper classes that perform one thing extremely well. They do it so well, they override everything else. As such, they often only contain one property, and they include the !important declaration. For example: .u-text-left { text-align: left !important; } .u-text-center { text-align: center !important; } .u-text-right { text-align: right !important; } .u-hide-st-med { @media (max-width: 599px) { display: none !important; } } .u-hide-bp-med { @media (min-width: 600px) { display: none !important; } } The classes I just stated here are almost everything I ever use for utilities. I’ve never found a need to go beyond these classes. Phew. It’s about time I shut up and let you get back to work/play/study or whatever you’re doing, so let’s wrap up. Wrapping up In this article, I’ve shown you how I use namespaces to fill the gap that BEM left out. With the inclusion of namespaces, I’ve finally fulfilled all four criteria that I look for in a good architecture: - Classes must bloat HTML as little as possible. - I must instantly know if the component uses JavaScript. - I must instantly know whether it’s safe to edit a class without interrupting other any other CSS. - I must instantly know where a class fits in the grand scheme of things to prevent brain overload. In short, I use a total of seven different namespaces. They are: .l-: layouts .o-: objects .c-: components .js: JavaScript hooks .is-| .has-: state classes .t1| .s1: typography sizes .u-: utility classes Each namespace has a function to play within the grand scheme of things, which further reinforces hierarchy within the stylesheet. Up next, I’ll share with you how when to break these rules I’ve just set (“huh? Again?! You really like breaking the rules huh?” 😅) and how I organize my CSS files. For now, I’m curious to hear your thoughts. What do you think of the namespaces I use? Is my ‘go-against-the-expert-namespaces’ use of .o- and .c- helpful/useful for you? Or does it confuse you even more? I’d love to hear what you think in the comments below :) If you enjoyed this article, please tell a friend about it! Share it on Twitter. If you spot a typo, I’d appreciate if you can correct it on GitHub. Thank you!
https://zellwk.com/blog/css-architecture-2/?ref=heydesigner
CC-MAIN-2020-34
refinedweb
3,661
68.16
Hi, I have tried to send email through python code the code is - import smtplib from email.MIMEText import MIMEText #try: s = smtplib.SMTP() s.connect('') # I have given server name of email s.sendmail("","","test") # i have given from user and send user print "Succesfull" s.quit() #except: # print "Error in sending mail to receiver:" But when i execute this script then it gives following error- Traceback (most recent call last): File "<pyshell#121>", line 1, in <module> reload (mail) File "D:\Pankaj\python\mail.py", line 6, in <module> s.connect() File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "C:\Python26\lib\socket.py", line 512, in create_connection raise error, msg error: [Errno 10061] No connection could be made because the target machine actively refused it
https://www.daniweb.com/programming/software-development/threads/263054/failed-to-send-email
CC-MAIN-2018-43
refinedweb
155
61.73
Implying no warranties and conferring no rights: "AS IS" since 1988 I wrote this article back in July and it ended up being the basis of this video (scroll to where it says “Thinking about Performance” and choose a speed) I was going to have the article edited and published seperately but somehow that never happened, so here it is now... the content isn't terribly new but it's kinda handy to have some of it in written form. Designing for Performance I’m a “performance guy”. That means I care deeply about how fast things are, and about keeping them small and tight. I think I’m a lucky performance guy because I actually get paid to do it – I work on the .NET Runtime. Some days being a performance guy isn’t much fun. Today, I have some things I want to get off my chest. I think this article is a reaction to hearing the phrase “Premature Optimization is the root of all evil” one time too many. So I’m here to tell you The Truth. I’ve done a long and careful study of the Roots of Evil and my conclusion is that Premature Optimization isn’t the root of it. It turns out that the Actual No-Kidding-Around Root-Of-All-Evil is Sloppy Engineering. Now, please don’t get me wrong. I’m not here to tell you that premature optimization is good for you and so you should get at least five milligrams of it daily. In fact, with the possible exception of “lottery winnings,” it’s hard to think of any words I could put after “premature” to yield something that seems like a good thing – it’s a pretty negative way to start a phrase. So I think it’s very fair to say that you can get yourself into a lot of trouble if you start optimizing your code too soon. But Sloppy Engineering is worse. You see, the danger of that “Premature Optimization…” phrase is that it encourages good engineers to not think about performance until far too late in their development cycle and they have a really swell sounding reason to not do it. It’s usually pretty obvious when a team has fallen into this trap – they’re close to releasing their software, everything is “working”, but they have abysmal startup time, or they’re using far too much memory, or something else of that ilk. Now they’re desperate for advice. another memorable, and sometimes job-ending, quote: “This is never going to work. You’re going to have to start all over.” If things have gone really badly then a team with a poor performing solution is going to have to do some major rewriting, even complete rewriting. This happens if the design that was chosen to address their problem fundamentally requires the use of a basic service or technique that is far too costly in terms of space or speed for the scenario their project was designed to work in. I’d like to say that this hardly ever happens but I’ve seen two examples just this week. On the one hand you have all these wonderful services that are so very easy to use, we’ve gone to great pains to make them as easy to use as possible after all, but they sometimes come at significant cost and aren’t always appropriate for every problem. I’d say the most frequently misused classes are from the System.Xml and System.Reflection namespaces. You really do not want performance disasters to happen to you. Honest. So how do you prevent this sort of thing? Planning is everything. Good performance is a key design consideration of any serious project and its relative importance should be carefully weighed with all your other major considerations. So while I think it’s a mistake to consider micro-optimizations early in your project’s life, I think it is vital to consider the performance goals of your project and design a solution that is going to be able to meet those goals from the outset. If you are not engineering a solution that is highly likely to meet your project’s goals – all the goals – then that’s Sloppy Engineering and that really is The Root of All Evil. So what to do? Well this article is about performance so I want to give a little advice about how to deal with the performance related goals of your project but some of my advice is equally applicable to other aspects of your project’s needs for success. The first thing you have to do is know what success looks like. Sadly there is not one universal set of success metrics that works for every project. You’ll have to think about what’s important to your project – it might be startup time, memory usage, disk usage, computation speed (the frame rate of your game) or a mix of all these things. It’s very likely that you’ll need to do some up front research to get this level of understanding and the best place to get it is from your customers. Once you know what success looks like, then you will be in an excellent position to make budgeting decisions. I’m a very big fan of performance budgets. I’m always asking to see the budgets because they tell me a great deal about the relative importance of the work going on in a project and they help me to quickly identify the big challenges. Whether I will be working on the project myself, or simply reviewing it at some stage, the performance budgets give me something concrete to focus on. But I think I’m ahead of myself. I haven’t told you what I mean by performance budgets. They’re nothing more than a statement of the maximum cost that a particular feature or unit in your project can afford to pay against each of the key performance goals. For example, if your performance goals call for your application to be initialized in less than ten seconds then you might budget a maximum of one second to each of your ten modules. Or, if your application is a server and it must do 3000 transactions per second per CPU then the total time per transaction cannot exceed 333 microseconds. Three hundred and thirty-three microseconds is a very liberating number if you’re an engineer. That number is going to help you a lot. Maybe your boss wanted “HyperTrans” in his server but, knowing that your budget is 333 microseconds, you can now confidently stare him down and say “Yo boss, everyone knows that a HyperTran takes 300 microseconds… that leaves only 33 microseconds to do the other useful work and we all know that isn’t happening…” Obviously the HyperTran approach is right out. In fact, dozens of other approaches are probably also right out as well. That budget has provided you with great guidance as to what you can reasonably do. You can quickly eliminate a variety of options and focus on the winners. Now, don’t go the other way and micro-tune the winners, but do conduct a suitable number of experiments up front to verify your choices. Do your homework. At this point I’m often asked “How much up front work should I do?” and sadly I don’t have a terribly useful answer for you. I usually answer the question with a glib phrase like “You should do exactly as much as is called for and not one shred more.” Well in the interest of actually trying to be helpful I do have some advice. I look at this from a risk-management perspective. If we’re talking about only a few hours worth of work to build the new code then you probably shouldn’t spend a week doing an investigation. On the other hand if the project will require several man-years to complete I dare say that more than 5 minutes of up-front planning is warranted. The more work is at stake the greater the need to reduce the risk of failure down the road. The planning should put you in a situation where you are taking the proper amount of risk. With the perfect amount of planning done, the budget still is going to keep working for you. While development goes along you can check your work against your goals and create tests to make sure the work is on track and stays there. You and your testing organization are well armed to find performance issues because they’ll know what to measure. Measure your work early and often, but don’t just measure, pay attention and adjust your plans. If things went great then as you are going along you’ll be able to periodically (don’t overdo this) verify your progress and reassure yourself that things are converging as you intended them to. If things start going badly, you mustn’t just plod along like a mindless zombie. Take advantage of the planning you did to see where and why things are not going as they should. Which aspects are more costly than anticipated? Is it a design problem or is it just tuning that’s needed? If it’s just tuning perhaps there isn’t a problem at all, but if it’s more you may have to go redesign or it may be time to cut your losses. Whatever you do, don’t just blindly finish on a course that is doomed to fall short of the projects requirements, that helps no-one. The worst kind of Sloppy Engineer is one that inflicts his/her work on the world at large. It may sometimes be difficult to remember to take the planning steps. In the software business we’re often under tremendous time-pressure. I can only emphasize that the greater the pressure of the situation the more important it is that we do good engineering because we have less time to fix things up later. Ultimately good planning saves you time. In summary: And most important of all: Thanks for listening.
http://blogs.msdn.com/ricom/archive/2003/12/12/43245.aspx
crawl-002
refinedweb
1,708
68.1
Django Pagination The amount of content on the blog and its pages has become substantial (in length only) enough to make it a worthwhile idea to paginate it (spread the content over multiple pages). Django makes it very easy! There are some nice objects available for paginating. The amount of content on the blog and its pages has become substantial (in length only) enough to make it a worthwhile idea to paginate it (spread the content over multiple pages). Django makes it very easy! There are some nice objects available for paginating. First, query your objects, and put them into a Paginator object that gives you some paginatory functions. (How many times do you think I can use a form of paginate on this page?). I query mine, then use a util function to put them into a paginator: # in view.py from aprilandjake.blog import util def home(request): entries = util.paginate(request, Entry.objects.filter(active=True).order_by("-date_created")) # ... # in util.py def paginate(request, obj_list, num_per_page=10): paginator = Paginator(obj_list, num_per_page) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: objects = paginator.page(page) except (EmptyPage, InvalidPage): objects = paginator.page(paginator.num_pages) return objects Note: - You can pass your result set straight into the paginator. - I’ve defaulted the results per page to 10. - The first try/catch is to make sure that the page number is an integer. - The second try/catch makes sure that the page number doesn’t go out of range You’ll have to change your iteration of your object in your template to look for the entry.object_list. That is because your object is really a paginator object now. {% for e in entries.object_list %} {{ e.stuff_to_print }} {% endfor %} Finally, we have to put the paginator UI on the page. Again, we can use the paginator object’s very nice functions to help us here. Because I want to reuse this pagination control and use it on many different objects, I’m going to make an inclusion tag for it: # in my template tags file: blog/templatetags/aprilandjake_tags.py from django import template register = template.Library() def paginator(object): return {'object': object} register.inclusion_tag('includes/_paginator.html')(paginator) To use it, load the custom tag for your template, place it where you want your pagination controls to appear, and pass in your object collection: {% load aprilandjake_tags %} <!-- ... --> {% paginator galleries %} The included html (_paginator.html) is thus: {% if object.object_list %} <div class="pagination"> {% if object.has_previous %} <a href="?page={{ object.previous_page_number }}" class="prev">« Previous</a> {% endif %} <span class="current"> Page {{ object.number }} of {{ object.paginator.num_pages }} </span> {% if object.has_next %} <a href="?page={{ object.next_page_number }}" class="next">Next »</a> {% endif %} <div class="clr"></div> </div> {% endif %} Note: - The check for object.object_list is just precautionary for if you have this inclusion tag included on a page that isn’t actually using a paginated object. To me, it’s amazing how awesome this pagination object is that is built into django. With a few quick and easy changes, pagination is added with very little pain to us. w00t! Go, Django!
https://jaketrent.com/post/django-pagination/
CC-MAIN-2018-30
refinedweb
518
50.94
Symbol tables are generated by the compiler from AST just before bytecode is generated. The symbol table is responsible for calculating the scope of every identifier in the code. symtable provides an interface to examine these tables. A namespace table for a block. The constructor is not public. A namespace for a function or method. This class inherits SymbolTable. A namespace of a class. This class inherits SymbolTable. An entry in a SymbolTable corresponding to an identifier in the source. The constructor is not public. Return True if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. For example: >>> table = symtable.symtable("def some_func(): pass", "string", "exec") >>> table.lookup("some_func").is_namespace() True Note that a single name can be bound to multiple objects. If the result is True, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.
https://docs.python.org/2.6/library/symtable.html
CC-MAIN-2016-40
refinedweb
163
62.04
? You can implement Calendar class in java.util package and use get(Calendar.DAY_OF_WEEK) method to retrive the day. You could do soemthing like this: import java.util.*; public class calendardemo{ Calendar cal=new Calendar(); cal.set(int year, int month, int date, int hour, int minute); int day_of_the_week=cal.get(Calendar.DAY_OF_WEEK); # this will return an integer 0-6 for Sun-Mon } Hope you got the general idea, I am not sure about the script part- maybe someone else from the forum will post for it. Bye Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?137640-Sundays-!&p=407096
CC-MAIN-2014-35
refinedweb
106
51.24
Serge E. Hallyn wrote:> Quoting a> container, but I have to use the process to identify the> container/namespace, well I can't uniquely specify the process by pid> anymore...> > -serge> Well we first can agree that througout all processes/tasks of a containerthe namespaces used are the same.Hence looking at the init_task of each container is sufficient.Restricting visibility to the default container makes sense to me,because one is not supposed to be able to look into another container.However, in the global context we do have pid that we can use.-- Hubertus-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2006/2/8/193
CC-MAIN-2014-49
refinedweb
124
55.24
Subject: Re: [boost] different matrix library? From: DE (satan66613_at_[hidden]) Date: 2009-08-15 05:38:14 on 15.08.2009 at 13:14 joel wrote : > Well, the problem is not the design per itself. What usually happens > with such lib is that you have tons of different user types > that all want disjoint set of features. use DRY (don't repeat yourself) idiom i got it > Matrix lib always looks easy to do. Except they are not. I can toss you > tons of questions : will you support openMP, well it seems trivial to me > threading, i dream about a way like #include <the_lib/lib.h> #include <the_lib/threading.h> //enabling threading for the_lib that would be perfect for me > MPI, possibly > SIMD definitely yes > extensions, there must be a common way for common users > will you embed loop level optimization based on expression > introspection ? sooner or later > Will you interface looks like matlab, maple or > mathematica ? i prefer to model STL interfaces where appropriate in general: as common as possible > etc ... Not even counting the things we barely scratched > like storage mode, allocation mode etc... of course it is such a missingd feature it must be there > That's why I'm avoiding to comment your code cause I'm developing > something similar but for a somehow different audience than yours and my > view will prolly be radically different than yours. but i can get some useful stuff from a radically different design and utilize it to make the design better > I can also only reiterate the fact that I have a somehow large code base > for such a thing that's maybe worth reusing. sorry but i didn't get the point > Three heads are better than two I think. indeed -- Pavel Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2009/08/154980.php
CC-MAIN-2019-22
refinedweb
316
64.3
It can be difficult to write unit tests for methods like print() that don’t return anything but have a side-effect of writing to the terminal. You want to ensure that what you expected to print to the terminal actually got printed to the terminal. The unittest.mock library can help you test functions that have calls to print(): def greet(name): print('Hello ', name) from unittest.mock import patch @patch('builtins.print') def test_greet(mock_print): # The actual test greet('John') mock_print.assert_called_with('Hello ', 'John') greet('Eric') mock_print.assert_called_with('Hello ', 'Eric') # Showing what is in mock import sys sys.stdout.write(str( mock_print.call_args ) + '\n') sys.stdout.write(str( mock_print.call_args_list ) + '\n')
https://realpython.com/lessons/mocking-print-unit-tests/
CC-MAIN-2021-17
refinedweb
113
51.55
0 i received some help but when i implimented it into the program it came up with an error. if anyone could help me fix this problem i will greatly appreciate it. here is the program. it is a guessing game. the error message says: error C2064: term does not evaluate to a function taking 1 arguments. it is talking about the following line: srand((unsigned)time(0)) #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () { int num; int guess; bool done; int noOfGuesses=0; int ncount; int sum=0; int noofgamesplayed; int avgNoOfGuesses; int time; sum += noOfGuesses; avgNoOfGuesses=sum/noofgamesplayed; srand((unsigned)time(0)) ;num = (rand() % 1000); done = false; while ((noOfGuesses < 10) && (!done)) { cout << "Enter an integer greater" << " than or equal to 0 and " << "less than 1000: "; cin >> guess; cout << endl; noOfGuesses++; if (guess == num) { cout << "you guessed the correct " << "number." << endl; done = true; } else if (guess < num) cout << "Your guess is lower " << "than the number. \n" << "Guess again!" << endl; else cout << "Your guess is higher " << "than the number.\n" << "guess again!" << endl; cout <<"Total gueses equal " << noOfGuesses << endl; } return 0; }
https://www.daniweb.com/programming/software-development/threads/96484/error-message-on-program
CC-MAIN-2016-40
refinedweb
185
73.68
Document Status and errata Copyright © 1999 W3C (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply. This document is a Working Draft of the World Wide Web Consortium. Please send detailed comments on this document to www-html-editor@w3.org before 2359Z, June 1st 1999. We cannot guarantee a personal response, but we will try when it is appropriate. Public discussion on HTML features takes place on the mailing list www-html@w3.org (archive). The W3C staff contact for work on HTML is Dave Raggett. This document has been produced as part of the W3C HTML Activity. The goals of the HTML Working Group (members only) are discussed in the HTML Working Group charter (members only). This specification is a revision of the working draft dated 4th March 1999 incorporating suggestions received during review, comments and further deliberations of the W3C HTML Working Group. The detailed differences are available for reviewers to compare.. XHTML is a reformulation of HTML 4.0 [HTML] as an application of XML 1.0 [XML]. XHTML 1.0 specifies three DTDs corresponding to the HTML 4.0 DTDs, and an XML namespace identified by a unique 1.0 1.0 namespace using the xmlns attribute [XMLNAMES]. The namespace for XHTML 1.0" ""> XHTML Documents may be labeled with the Internet Media Type text/html or text/xml." ""> <html xmlns=""> <head> <title>Virtual Library</title> </head> <body> <p>Moved to <a href="">vlib.org</a>.</p> </body> </html> The XHTML 1.0> In attribute values, user agents will strip leading and trailing white-space from attribute values and. Don't include more than one isindex element in the document head. The isindex element is deprecated in favor of the input element. Use both the lang and xml:lang attributes when specifying the language of an element. The value of the xml:lang attribute takes precedence.. This appendix is informative. This specification was written with the participation of the members of the W3C HTML working group: This appendix is informative.
http://www.w3.org/TR/1999/xhtml1-19990505/
CC-MAIN-2013-20
refinedweb
342
60.11
Want to see the full-length video right now for free? React Native is a project from Facebook that allows developers to use React to build native mobile applications. This presents an amazing opportunity as now we can use the same tools, workflows, and approach to build for both web and mobile, without sacrificing the native look and interactions users expect on mobile. Join thoughtbot iOS developer Giles Van Gruisen as he guides us into the world of React Native and explains why this is so exciting. At the core, React Native is just React. There are many additional pieces that have been added to make React run on the native Android and iOS platforms, but at its core, this is still just React. The same component-based, declarative approach to building UIs that React popularized for the web is now available in the realm of mobile. This is great for two reasons. One, React is a very interesting framework that brings a lot of great ideas forward, particularly the idea of designing dynamic web applications using a declarative, functional approach. Your UI is a function of the current state of the application data model, and that simplicity does wonders for helping us manage complexity and keep our applications as straightforward and maintainable as possible. Check out our Weekly Iteration episode on React for more detail on the core philosophy of React and why we like it. Second, React Native makes it possible for developers who historically have stuck to the web to now build for mobile. React Native abstracts away most of the specifics of the mobile platforms and lets developers use the same approach they've used with React on the web, while still accessing and using platform specific UI elements and interactions as needed. The philosophy is summed up well in this quote from the React Native blog:." React Native also makes designing mobile applications much more straightforward and familiar, very similar to what it does for developing the applications. The combination of the HTML-like JSX syntax and the use of CSS-like styling (including support for flexbox layout!) makes designing React Native mobile applications a much more familiar and approachable task for designers with a web background. This is very different from how design and layout work on the mobile platforms by default, and is a welcome change. Again, the power here comes from using the same techniques and thinking to build applications across both web and mobile. While we're certainly excited about what React Native represents, its worth noting that it may not be an ideal choice in all situations. It's great for straightforward data-driven applications, but likely not an ideal choice when you need highly customized UI elements, interactions, animations, hardware-access, etc. Much of the native platform is exposed via React Natives core components, but not everything. For example, with React Native you have access to vibration functionality on both platforms, but it is currently not possible to create a vibration pattern. That said, while you may hit some limitations like this, it is possible to build custom wrapper components to access more of the native platform functionality, so it is not an all-or-nothing proposition. React Native is a novel approach to building mobile applications using JavaScript and web technology. It's certainly not the first, with platforms like Phonegap and Cordova having paved the way. Those frameworks took a different approach in which they wrap a native frame around a webview, and then run a web (HTML, CSS, and JS) application in the webview. This is referred to as a "hybrid" application. React Native instead runs your application code in a background thread, executing your JavaScript and then sending layout commands to a main thread, calling into native platform APIs to build and arrange truly native UIs. User interactions are communicated from this main thread to the background thread where any updates to the UI are computed (using Reacts wonderful declarative virtual DOM magic) and then updates are communicated back to the main thread. A nice feature of this is that all interactions are automatically handled off the main thread, which means that the UI remains responsive, even while handling more complex computation. As discussed above, one of the core benefits of React Native is that it opens up the world of mobile application development to developers and designers who historically had focused on the web. By bringing a common approach to both platforms, we now have a common way to build applications. Another great benefit of React Native is code reuse across the various versions of an application. In a post discussing the process of building the Android version of their mobile ad manger (for which they had already built a React Native iOS version), Facebook shared that they were able to reuse ~85% of the code across the two platforms. That sounds like a nearly ideal ratio. Re-use the vast majority, but still allow for customizing that last ~15% to ensure solid integration and alignment with native platform interactions. Lastly, since React Native is using JavaScript to run the application, there is no longer a need to continually re-compile the application with each change. In fact, with each release React Native improves the development workflow with steps like removing the need to open Xcode, supporting live reloading, and the recent addition of support for hot reloading. To dive in a bit deeper, we'll take a look at a very simple React Native app that displays three boxes, and allows the user to hide or show the boxes by pressing a button. We can run the application with two commands: # start the JS file watcher process to # build and bundle the application code $ react-native start # start the iOS simulator to interact # with out application $ react-native run-ios To start, we'll take a look at the main component of the application: import React, { AppRegistry, Component, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; class WeeklyIterationDemo extends React.Component { constructor(props) { super(props) this.state = { boxesHidden: false, } } toggleBoxes() { console.log(this.state) this.setState({ boxesHidden: !this.state.boxesHidden }) } renderBoxes() { if (this.state.boxesHidden) { return ( <View style={styles.boxesContainer}> <View styles={styles.box} /> <View styles={styles.box} /> <View styles={styles.box} /> </View> ) } else { return null; } } render() { var buttonText = this.state.boxesHidden ? "Show" : "Hide"; return ( <View style={styles.container}> <TouchableHighlight onPress{() => this.toggleBoxes()} style={styles.button}> <Text style={styles.buttonText}>{buttonText} boxes</Text> </TouchableHighlight> {this.renderBoxes()} </View> ); } } To highlight a few of the interesting features at play in this example: import- importis a part of ES6 (check out our Weekly Iteration episode on ES6), but the nice thing is React Native handles all the compilation for you React native includes support for flexbox style declarations, and will automatically convert those flexbox styles into the platform specific variant. Flexbox was a very welcome addition to the world of web design, making it drastically easier to build and style applications. The mobile world benefits perhaps even more so from the ability to use flexbox as the native platform layout and styling functionality is an often highlighted as being difficult to work with. Check out our Weekly Iteration episode on Flexbox if you need a refresher. Another area where web developers will feel at home is that React Native allows us to use the Chrome Developer Tools for debugging. console.log and even debugger statements will just work, which makes building and debugging React Native applications very approachable for those new to the platform. From its initial release, React Native has had a great story around rapid iteration and feedback cycles thanks to not needing to compile. It took things a step further with the addition of live reloading where the simulator would automatically reload the application when a file was updated. And now, with the addition of hot reloading, they've taken things to the next level. With hot reloading, each time you save a component, the live code running in the simulator will update while maintaining the application state like the current view or the boxesHidden property in our demo. This may not read as that amazing, but in practice hot reloading can totally change the way in which we build applications, making tiny changes and immediately getting feedback. Now we can dive a little deeper and take a look at an application the targets both Android and iOS from a single codebase. The majority of components available on React Native will abstract away the differences between the platforms. In this application, all but one of the components used will work on either platform without our code needing to handle the distinctions at all. Looking at the code used, we can see that we're using the Navigator, ListView, Text, and View components, all without needing to worry about platform distinctions. The only component in our application that has platform specific implementations is our Button component. The nice thing is that React Native makes it very easy to opt into platform specific versions of components by simply naming the files with a platform specific file extension: // button.ios.js file import React, { TouchableHighlight } from 'react-native' export default class Button extends React.Component { render() { return <TouchableHighlight {...this.props} underlayColor={'#eee'} /> } } import React, { TouchableNativeFeedback } from 'react-native' export default class Button extends React.Component { render() { return <TouchableNativeFeedback {...this.props} /> } } Between the two, we can see that the only difference is in the touch specific implementation for Android vs iOS. With these two files defined, the code that uses this component can now be blissfully unaware of the platform distinctions, and simply import and use the component like any other. import React, { StyleSheet, Text, View, } from 'react-native' import Button from './button' import Quote from './quote' export default class Row extends React.Component { // ... other functions omitted render() { return ( <View> <Button onPress={this.navigateTo.bind(this)}> <View style={styles.rowContainer}> <Text style={styles.text} numberOfLines={1}>{this.truncatedQuote()}</Text> </View> </Button> </View> ) } } The children are passed as a prop to our Button component, allowing us to define the platform specific implementation only where needed, and then use it via the abstracted component we've created. Nice! While React starting as a project for building web applications, it very quickly was ported to a whole variety of platforms including canvas, server rendering, and even custom implementations like Netflix's Gibbon system which allows them to render React applications on a whole variety of embedded TV systems. Not with React Native, we can target Android and iOS, but the momentum is only growing with Microsoft recently announcing React Native on the Universal Windows Platform. There is even a React Native for the Web project (which is not a joke, much as it sounds like one). This speaks to the power of the abstractions introduced by React, and the value of the "learn once, write anywhere" philosophy. If you're interested in giving React Native a shot, the best place to start is the projects own Getting Started guide.
https://thoughtbot.com/upcase/videos/react-native
CC-MAIN-2020-45
refinedweb
1,838
51.18
I am doing the exercises in "The C Programming Language" The following program works, except for the backspace '\b'. Can someone help me to get this to work. Using the shell in windows xp to run the program. I tried using the del key ascii code also but it does not work. Please ignore the use of the if statements, it's temporary. for some reason the console simply does not recognize \b backspace. #include <stdio.h> Code:main() { int c, d, bs; bs = 0; while((c = getchar()) != EOF) { d = 0; if(c == '\t') { putchar('\\'); putchar('t'); d = 1; } if(c == '\b') { putchar('\\'); putchar('b'); d = 1; bs++; } if(c == '\\') { putchar('\\'); putchar('\\'); d = 1; } if(d == 0) { putchar(c); } } printf("Backspace: %d", bs); }
https://cboard.cprogramming.com/c-programming/102998-can-someone-try-getchar-please.html
CC-MAIN-2017-30
refinedweb
123
82.75
There has been much discussion recently on the Fedora mailing list about how to improve Linux's ease of use in scenarios like printer setup. (Thank you, everyone, for picking up on the content of my rant so constructively when you very well might have dismissed it as carping.) I have just become aware of a technology which could represent a long step towards addressing the usability problem. It is a set of small patches to the IP infrastructure that support zero-configuration networking -- you just plug in an IP-capable device and it self-configures an IP address, becomes available in a local DNS namespace, and other devices automatically discover its presence and the services it offers. This technology is called "zeroconf", and is described at. The first component of Zeroconf, self-assigned link-local addresses, has been shipping since Mac OS 8.5 in 1998, and the other two components, Multicast DNS and Service Discovery, shipped starting in OS X 10.2, a year and a half ago. Since then almost every maker of IP-over-Ethernet-capable printers printers has adopted Zeroconf and incorporated it into their firmware, and just about any network printer you can buy today has it. There is a mature open-source implementation which is part of the Darwin/OS X codebase. The zeroconf stuff uses existing services like DHCP and DNS if they exist -- and, just as importantly, doesn't mess them up when you plug a zeroconf-enabled device into a normal, manually-configured network -- but it doesn't need them. It uses a few simple, clever multicasting tricks and a technique for detecting IP address collisions. The total volume of code is not large, basically consisting of one zeroconf responder daemon and a handful of small patches to other services. Less than 100K all told, and that's *with* multihoming and IPv6 and all the bells and whistles. The effect is a lot like the Chooser application on the Mac (this is not accidental; zeroconf was written to replicate Chooser's behavior in a TCP/IP world). You plug Ethernet cables together and stuff just works -- no more complicated ritual dances with ifconfig, DHCP, and DNS. Your IP-enabled devices even magically appear in your DNS namespace, with a DNS name ending in ".local". Home networks using Linux would become zero-administration; Aunt Tille would love it. The inventor of zeroconf, Stuart Cheshire, tells me the technical problems are all solved and the solutions well tested, but he doesn't understand the politics of getting the Linux community to generally adopt zeroconf. He's anxious to help. I suggest that full integration of zeroconf should be added to Fedora's to-do list. For this to actually happen, somebody will need to step forward and become zeroconf's champion. Any volunteers? The source code (which already runs on Linux -- just do a "make os=linux; sudo make install") can be checked out from Apple's Darwin repository. Check out top-of-tree; Stuart tells me the tarball is a little out of date doesn't contain the latest fixes: <> The documentation in the mDNSPosix folder should be fairly clear. If not, Stuart Cheshire requests that you email him <cheshire apple com> and Marc Krochmal <marc apple com> with any questions, or you can ask on the public Rendezvous list: <> -- <a href="">Eric S. Raymond<, "Abbey's Road", 1979
http://www.redhat.com/archives/rhl-devel-list/2004-March/msg00117.html
crawl-002
refinedweb
568
50.67
package blah.blah.blah; import blah.Log; public void addLeadType(LEAD_TYPE type) { _leadTypes.add(type); } // ** PROTECTED METHODS // ** PRIVATE METHODS // ** ACCESSORS // ** INNER CLASSES } [download] #!/usr/bin/perl undef $/; sub fileContainsWord() { my $file = $_[0]; my $word = $_[1]; my $found = 0; open FILE, "<$file"; while(<FILE>) { my $filecontents = $_; if($filecontents =~ /$word/smg) { $found = 1; } } close FILE; return $found; } my $file = "SearchSet.java"; my $word = "LEAD_TYPE."; my $flag = &fileContainsWord($file, $word); print $flag . "\n"; [download] You get back 1 because you return $found from fielContainsWord. Remember that regex special characters in interpolated strings are still special, and a dot with the /s flag matches any character. You don't need /s unless you use the dot as a special character, and you don't need /m unless you are using the string anchors. The /g flag isn't doing you much code here either since you're only matching the string once. To quote possible special characters, you can use the \Q sequence (or quotemeta beforehand). if($filecontents =~ /\Q$word/) { [download] The '.' is a special character inside of regular expressions, signifying 'anything except newline' (usually). You probably want to use quotemeta like this: my $word = quotemeta( $_[1] ); [download] This should 'escape' (with a leading '\' character) anything that could be interpreted as a special character. Dave if($filecontents =~ /$word/smg) { [download] if($filecontents =~ /\Q$word/smg) { [download] /\Q$word/E/ or /\Q$word/ (The \E can actually be omitted, it's there so that you can enclose a subset of the regex) The content of $word is used as a regular expression string. So the dot is a wildcard for a single character. With $word = "LEAD_TYPE." the match is like $filecontents =~ /LEAD_TYPE./smg which matches the line in the java function declaration (dot matches space character). It follows that $found=1 being returned by your sub, ending up as the value of $flag For taking your input literally in the match see the quotemeta builtin sub or the \Q (+ \E) perlre metacharacters. You may also have a look into perlop to check that your usage of the s- m- and g-modifiers in the match have no influence on your result in the context you perform your match. #! /usr/bin/env perl use strict; use warnings; BEGIN { die "usage: $0 <file> <word>" unless @ARGV==2 } sub file_has_word { my ($fn, $w) = @_; open my $f, $fn or die "$fn: $!"; local $/ = undef; # but why do you want this? return unless <$f> =~ /\Q$w/; 1 } print "found it!\n" if file_has_word(@ARG
http://www.perlmonks.org/?node_id=529567
CC-MAIN-2015-48
refinedweb
418
64.61
Post your Comment Java 8 expected release date Java 8 expected to be release on 18th, March 2014 Get ready for the latest version of Java 8, as Java 8 is expected to be released on 18th March 2014... the multi-core cpus. The planned date for the release of JDK 8 ( Java development JDK 8 Release Candidates Available JDK 8 Release Candidates Available Java 8 includes new features... which is also very important feature of Java 8. This is the first release... to compare extracted key objects. The Java 8 RC2 release also includes a read Java EE 8 Takes Off Finally its good news for Java developers as Java EE 8 Takes Off The future version of Java EE 8 officially launched as JSR 366 via the JCP (Java Community... to be introduced in the JEE8. The primary focus of Java EE 8 will be providing Oracle to release Java 8 in March 2014 Oracle to release Java 8 in March 2014 - Get ready for the next exciting version of JDK. Oracle is planning to release the JDK 8 ( Java development Kit 8... candidate built might be released on January 23. The JDK 8 is the next release of Java Java EE 8 Takes Off and this is started within one year of the release of Java EE 8 platform which was a great... in this article I am briefing out the major features of the Java EE 8. This release... of the Java SE 8 are repeating annotations, lambda expressions, the Date/Time Java 8: Java 8 is officially released and it can be downloaded Java 8 officially released Java 8 is finally available for download - Download the latest Java 8 SDK and start developing next generation applications for your client. Java 8 comes with many new features including Lambda expression equal symbol expected in jsp - JSP-Servlet equal symbol expected in jsp Hi frndz i am using following code...(); String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); String strDateNew = sdf.format(now) ; String Spring Framework 4.1 - First Release candidate available implemented. Other features of the Spring 4.1 Frameworks are: Java 8 Support... Spring Framework 4.1 First Release candidate is available It is a good news... Framework 4.1's first release candidate is available. This version JEE 8 - Java Enterprise Edition 8 JEE 8 - Java Enterprise Edition 8 Tutorials, Examples and latest updates... about the JEE 8: The Java Community Process (JCP) team has started the development of next generation JEE 8 Java EE 8 Takes Off Windows 8 Operating System Windows 8 is the latest innovation, which has been launched to make easy handling of the Windows operating system. Launched by the Microsoft it is expected... the launching of Window 8 is that making easy operating system's especially Learn the Java 8 and master the new features of JDK 8 Preview Released Oracle to release Java 8 in March 2014 Lambda...JDK 8 - Java 8 Tutorial and examples: Learn JDK 8 with the help of examples... bug fixes. Here we are giving the news, articles and updates of Java 8 JDK 8 - Developer Preview Released JDK 8 Developer preview release and share you comments with community Java... of the JDK 8 is to provide an open source context for the utilization of the Java SE... another important features which required to be enhanced as in java SE 8 How Windows 8 will benefit Business? these not so distinct categories, Windows as expected was sure to come up..., Windows 8 will benefit business in numerous ways. From low booting time... in corporate network, Windows 8 as a operating platform has many wonders to offer About Java 8 Java 8 is slated to be released in March 2014 but the debate has already begun... for Java developers or not. This debate has made Java 8 update as the most..., streams, functional interfaces and others. Some of the features Java 8 might have expected error expected error expected error print(" import java.util.*; public class Person{ Queue<Person> busQ = new LinkedList<Person>(); busQ.addLast(homer); busQ.addLast(marge); busQ.addLast(maggie); busQ.addLast Date format - Date Calendar Date format please convert dd-mmm-yy date format to gregorian calendar date format. Hi friend, Code related your Problem: import...:00 (Pacific Standard Time) String[] ids = TimeZone.getAvailableIDs(-8* 60 * 60 date print date print how can i print the date in jsp page in the following formate month-date-year. (example. march 8 2012 Date prorblem = tokens[8]; .... (the date from source into local java filed...Date prorblem HI all, i have date comming from one text file into string filed in java code. once the date is available in filed ( of type String Apache MyFaces Core 1.2.0 (New Release) applications. Announcement Date : The announcement date for the release of MyFaces...Apache MyFaces Core 1.2.0 (New Release) MyFaces is free and open source reached end of file while parsing and while expected NSDateformatter format Date NSDateFormatter in string format. Thanks. For current Date in NSDate Format -(void) setCurrentDate:(NSDate* newDate){ [self.currentDate release...; In objective c, we use NSDate to show the Current Date and Time Release or Stripes 1.5 Release or Stripes 1.5 (18 Aug 2008) Stripes is an open source and action-based Java framework of presentation layer developed to create web applications using the latest Java based technologies. Stripes is developed java yesterday - Date Calendar java yesterday Afternoon,Yesterday i have a question that how to make date sustract, the result is to make 1 month and 1 day like this, right. now how about 1 year and 1 month? And Can help me to using Date Calender what Post your Comment
http://www.roseindia.net/discussion/50378-Java-8-expected-release-date.html
CC-MAIN-2014-52
refinedweb
961
55.74
Agenda See also: IRC log <Tom> Previous: Jeremy: introduces himself. ... representing TopQuadrant. Participation mainly for CR. Guus: long telecon last time. ... some things being revisited on the list. Also possibly ... actions that are long gone. Guus: propose to accept minutes ... no objections. ... next telecon 5th Aug. Guus regrets ... Two objectives in mind for these telecons. To get to LC for SKOS and PR for RDFa Guus: Action items. ACTION: Ed to investigate what text could be added to primer re. concept co-ordination [recorded in] [CONTINUES] Guus: My action re primer text. Is this still required? Antoine: Can't quite recall. ACTION: Guus to write primer text re: broaderGeneric and equivalence w/r/t subclass [recorded in] [CONTINUES] ACTION: Alistair to check the old namespace wrt dereferencing [recorded in] [DONE] Alistair: Sent email some four weeks ago. <Antoine> ACTION: Antoine and Ed to add content to Primer about irreflexivity [recorded in] [DONE] <aliman> email on old skos namespace dereference ACTION: Alistar to update the history page adding direct link to latest version of rdf triple [recorded in] [CONTINUES] ACTION: SKOS Reference Editors to specifically flag features at risk for Last Call. [recorded in] [CONTINUES] ACTION: Sean to draft response to comment about namespace. [recorded in] [DONE] -> <scribe> ACTION: Sean to post comment to OWL WG re annotation requirements. [recorded in] [CONTINUES] ACTION: SKOS Reference Editors to propose a recommended minimum URI dereference behaviour [recorded in] [DONE] -> ACTION: Guus to mail his position on issues 72, 73 and 75 to the list [DROPPED] [recorded in] ACTION: Alistair and Sean to propose text to implement the resolution of issue-72 [recorded in] [DONE] <aliman> Guus: Which issues to we need to discuss here. Namespace and broader/transitive ... would like to see if we need more discussion there. Also ... talk about LC schedule. When will drafts be available and reviewers. ... Discussion of namespace issue. ... Is there reason to review our decision? Alistair: Sent an email last week. ... Trying to think what pros and cons of each approach are. ... -> ... A move to a new namespace has little upside and a lot of downside. ... stick to old has advantages. All the existing stuff can be claimed as implementations of ... SKOS. Also tools that are there already. A new namespace means we have to wait for implementation ... plus there will be a period of time while people migrate, which could take years. ... Realistically means tool developrs have to maintain multiple implemetations. ... Bottom line is that there is little gain from a new namespace and a cost involved. ... Assumed that the LC would use the new namespace, but marked as "at risk". ... Would appreciate comments. Guus: I see objections, but no need to reopen the issue. Alistair: Under what circumstances would we need to reopen the issue? Guus: if we reopen, we can't go to LC. ... saw one comment that the change in semantics requires a new namespace (Simon Spero) Alistair: unsure whether to take this comment. There may be some misunderstanding of transitive. Guus: Happy to mark it as "at risk". Alistair: Ok Antoine: Would like to discuss ISSUE 83. Semantics of concept scheme containment ... some problems with the implementation. Alistair proposes a new property to capture the ... semantics. Guus: This seems rather drastic at this point. <Antoine> <Antoine> -> start of the thread Alistair: I think this is less drastic. <aliman> <aliman> ex:cs skos:hasTopConcept ex:c. Alistair: Email above contains resolution to the issues. Email merely states an entailment. <aliman> entails the graph: <aliman> ex:c skos:inScheme ex:cs Alistair: want to follow this entailment, but resolution doesn't state how we go about making this happen. ... Spent some time thinking and what we're trying to say is that skos:hasTopConcept has an inverse which is a ... subproperty of skos:inScheme ... Most obvious way to express this is to name the inverse and then state it explicitly. ... if we don't name it then it requires an anonymous property. This ... could be a potential problem. Would appreciate input from Jeremy. Jeremy: OWL2 may be about to allow anonymous properties. One issue is that it pushes ... you out of OWL DL. Can't use the anonymous property in a triple (not as predicate). ... so in terms of describing the relationships, there's nothing particularly wrong, but implementations ... may find it difficult. Procedurally, putting in an anonymous property may cause trouble, ... but a new property might also cause problems. Guus: But other things are not stated in the data model. Alistair: There are two constraints expressed as prose, but there is no way to do that in ... RDF or OWL. Here, it *is* possible to do it. ... Would avoid complication of anonymous properties. Guus: Only require inverse of hasTopConcept or inScheme. ... topConceptOf would do the trick. Alistair: Called it topConceptInScheme in Ref. Guus: awful name! Alistair: Subjective view. Not really worried about the naming. Jeremy: is the intention to document the relationship within OWL. Could one include this in ... a separate file with a seeAlso. Alistair: If we can do it without jumping through hoops, why not do it? Guus: Surprised that other constraints can be expressed in RDF. Alistair: All but two current. Would be three with this one. Guus: WHat's the problem with three rather than two? Alistair: For this one, we could do it. Guus: But only at the cost of new vocabulary. Alistair: But non-standard semantics is also costly. Antoine: Can't see why my axiom is not valid OWL Alistair: Entailments that follow are not valid RDF. Jeremy: There is a bug with RDF (ter Horst). Significant problems and adding an anonymous ... property would exercise that bug. Would advise against it. Antoine: That's the argument I was looking for. ... Also assume a bug in the OWL specification then. Jeremy: There is a need for a bug fix. But will not be done any time soon. Guus: We're not going there. Jeremy: Cost of new predicate vs. non-standard. New predicate is cheaper. ... preference would be to say nothing. Guus: small cost with a small group. Sean: preference for new predicate. Guus: Suggest that Reference Editors make a proposal for this. ... Will reopen ISSUE 83, but expect a proposal to close with a new property. Alistair: Do we need to open the issue? Guus: yes, need documented rationale. ... alternative is to open new issue and immediately propose closing it. ... That might be better. ... for me topConceptOf would be an appropriate name. ... Propose a new issue which is then closed. ACTION: Alistair to open issue relating to topConceptOf and propose a resolution. [recorded in] Guus: Any more w.r.t content? Antoine: happy Guus: Margherita reviewed, but reviewed the old draft. ... chance for a new draft next week? Alistair: Think so. Resolutions to things are done. Need to mark at rsik and some editorial stuff. Guus: Earliest possible for LC decision is August 19th. ... problem for Guus as on holiday. Could review but only in next two days. Alistair: Have to finish this week. Guus: Could do it if it's there by Friday. Alistair: Could provide a link which will be pretty much the version we publish. Guus: Can expect cmments by the 12th, one week for discussion and a decision about LC ... on the 19th. ... would be preferable if at the same point we have a primer draft consistent with the Reference. Antoine: Feasible apart from action on co-ordination. ... Version of the primer for the 19th? Guus: Would also like to take a decision about publishing primer on 19th. ... agenda item for next week will be scheduling. ... also need to discuss LC period given that ... publishing will take a few days. 5-6 week period is appropriate. ... end September/beginning October. Sean: some traffic on the list about broader/broaderTransitive. Guus: no new arguments there. No real evidence to reopen this. Alistair: i'd agree. Concerned about how many people misunderstand this. ... not a technical problem, but perhaps some confusion with names. ... its a shame that people are misunderstanding this. Sean: Question of education rather than technical details. Antoine: Whatever the names, the pattern will be the same, and that's ... hard for people to get. Guus: Will pay attention to this. Jeremy: Is a simple example more accessible? Parent/Ancestor etc? Sean: is the reference an appropriate place for this? Antoine: Could put some drawings in the primer. Alistair: Antoine's slide at the SKOS event was very clear. Antoine: Animated. Guus: Could make snapshots. Guus: Parent/ancestor is already a long way towards this. Guus: nobody here Guus: nobody here <aliman> ISKO event with link to antoine's slides ACTION: Ben to prepare draft implementation report for RDFa (with assistance from Michael) [recorded in] [CONTINUES] Guus: Recipes? Diego: Document is ready to be published. Ralph has not had time ... to do it. ... will try to publish asap ACTION: Ralph/Diego to work on Wordnet implementation [of Recipes implementations] [recorded in] [CONTINUES] ACTION: Jon and Ralph to publish Recipes as Working Group Note [recorded in] [CONTINUES] Jeremy: back to RDFa, at call on Thursday, hope to get WG approval on 19th. ... reviewers to be appointed for 5th. Guus: Only need review for implementation report. WG should check that we've met the conditions. ... not like reviewing a regular document Jeremy: Only major change was on Primer. HTML vs XHTML issue. Guus: useful background ... next telecon 5th August, then 19th August
http://www.w3.org/2008/07/29-swd-minutes.html
CC-MAIN-2019-47
refinedweb
1,568
70.5
CDI Conversations Part 2 CDI Conversations Part 2 Join the DZone community and get the full member experience.Join For Free This article will look at using the Conversation scope defined in JSR 299 (Java Contexts and Dependency Injection), and released as part of Java EE 6. For now, we’ll stick to non-data driven examples as we explore the ins and outs of the Conversation scope. We’ll finish up by creating a workspace manager so we can list all the active conversations and switch between them. A Conversation is like a numbered bucket in the session that exists until either the end of the users session, the conversation times out, or the server side code deliberately ends the conversation. The benefits of a conversational scope are many, letting us easily create pages that can be opened in multiple tabs without having to juggle the state on the client without filling the session with data that will last as long as the user session should we forget to remove it. We’ll start by creating a project from the knappsackjee6-servlet-basic archetype. This gives us all the features of Java EE 6 without too much code to get in the way. We’ll start by creating a backing bean that is request scoped and looking at how that is used and what effect request scope has. import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Named; @Named("bean") @RequestScoped public class BackingBean implements Serializable { private Long value = new Long(0); public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getMessage() { return "The value is : "+value; } } Simple enough, now lets add a page called listEdit.xhtmlthat lets us enter the value, post the value back and see what the message is. <?xml version="1.0" encoding="UTF-8"?> <ui:composition <ui:define <h:form Value : <h:inputText <h:commandButton <br /> <br /> Message : #{bean.message} </h:form> </ui:define> </ui:composition> Edit home.xhtml to include a link to this page : <a href="listEdit.jsf">Start New List</a> Open up the home page and click the link to go to the listEdit page. If we enter a value in the input box and click the submit button, predictably, our message says that the value is whatever we entered. What is happening here is that when the form is posted back, the value in the input box is sent back to the bean.value attribute. When the page is rendered back to the user and the message is rendered, it is rendered using this value that we passed back to the server. We pass the state of the attribute from the server to the client, and then back to the server, and we can do that all day long using just the request scope without any problems. This is a stateless page and doesn’t require any state to be held on the server. Let’s add something a bit more stateful to the page such as a list of values that we have added previously. In our backing bean, add the following field and getter method and a method to add the value. private List<Long> values = new ArrayList<Long>(); .. .. .. public List<Long> getValues() { return values; } public void addToList() { values.add(value); } Now we will add the list of values to our page to be displayed. <ui:define <h:form Value : <h:inputText <h:commandButton <br /> <br /> Message : #{bean.message} <h2>Added Values</h2> <ui:repeat #{v_value}<br /> </ui:repeat> </h:form> </ui:define> If we refresh our page, enter a number and click submit, you will see that the number appears at the bottom of the page where it should. When we click the submit button on the form the value is assigned to the value attribute. When the addToList method is called, the value attribute is added to the list. When the page is rendered, the latest value is used to generate the message and for the list of items we return the list containing one item, the new value. So far so good. Let’s enter a new number and add it to the list. When we click the button the second time, the only number in the list of numbers is the one we just entered. The first value is gone! The problem is that the second time we posted the value the bean was re-constructed from scratch and had no idea whatsoever about the first value we added to the list. There was nothing on the form to tell the bean about the first number even though we displayed it on the page. The backing bean keeps forgetting our list of numbers from one request to the next, or in other words, our application is missing some state. As per part 1, there are a number of ways we can get around this problem. We could save the list to the database each time we post, which is over kill for this simple task. We could push the state down to the client, say using a comma delimited list of existing numbers pushed into a hidden field. When the form is posted, the comma delimited list is sent back to the server where the numbers are unpacked and the list is rebuilt on the server side and the state is restored. Both of these two methods are doable but what happens when we have more information on the server that we need to keep hold of? Do we have to keep adding add each piece of information to the client state manually, including passing it around from one page to the next for multi-page processes? What if it is a list of entity objects we want to hold on to? Do we just save the Ids on the client and keep re-loading them from the database each time? These solutions are impractical from the perspective of building a maintainable app quickly. However, note that these solutions are completely possible with JSF and CDI. It just offers better alternatives, but the opportunity to get under the hood and use more lower level solutions in the interests of optimizing the application are always there. This is an important factor since if you have a widely used conversational page that is creating a bottle neck, you can refactor it down to use a more stateless approach. Since this article is all about conversations, obviously, we are going to solve our problems using the conversation scope. We will change our bean to be @ConversationScoped and @Inject a Conversation instance we’ll be using. We’ll then start the conversation for the page when our bean is constructed. This is an example and typically you don’t start conversations in bean construction but it serves our purpose here. Tip : Conversations are typically started at specific points on certain initialization methods, starting it on bean construction is bad because you never know when another task might use an instance of that bean @Named("bean") @ConversationScoped public class BackingBean implements Serializable { ... ... ... @Inject private Conversation conversation; ... ... @PostConstruct public void postConstruct() { conversation.begin(); } public Conversation getConversation() { return conversation; } ... ... } Reload our page and you can see how you can enter and submit as many numbers as you want to the page and the list state is managed. Conversations are just a natural extension of the existing scopes in current web applications. They also become very natural to use. Let’s add another page that lets us review our list of numbers before ‘confirming’ them. Add the following new button at the bottom of our page : <h:commandButton Because the action attribute is set to review we will create a new page called review.xhtml that will display the numbers. Our first concern obviously is ‘where does it get the list of numbers from?’, well the answer is, from the same place it got the numbers from last time, using the expression #{bean.values}. review.xhtml <?xml version="1.0" encoding="UTF-8"?> <ui:composition <ui:define <h:form <h1>Please Confirm The Values : </h1> <h2>Added Values</h2> <ui:repeat #{v_value}<br /> </ui:repeat> <h:commandButton </h:form> </ui:define> </ui:composition> The way to think about this is to imagine what happens when the page is rendered. JSF will look for the value beans.values which the CDI implementation can provide. Since this page is being rendered in an active conversation, CDI will look in the active conversation ‘bucket’ for a bean called bean. Since we are coming from the page that adds the numbers, this bean will already exist in the conversation and so the same instance is returned. Should we render this page without an active conversation, by typing in the URL manually, the page will render, but this time, the instance of beans.xml will not already exist and so CDI will create a new instance of it that doesn’t contain any items. Tip : There are ways to prevent pages rendering without an active conversation which can also help with duplicate form submissions Getting back to the page, we just want to add our confirm method to our backing bean. This method ends the conversation and redirects to the home page which is going back to the number entry page. public void confirm() { conversation.end(); try { FacesContext.getCurrentInstance().getExternalContext().redirect("home.jsf?faces-redirect=true"); } catch (IOException e) { e.printStackTrace(); } } Add the following at the top of either the review or list edit page to see the conversation Id you are currently in : Conversation : #{bean.conversation.id}If you run the application, you can add numbers and when you click review, you get a list of all the numbers you just entered on a separate page. If we were managing state ourselves, we would have to pass something to the review page to let is know what the list of numbers was, either a database row key, or the comma delimited values. Again, the more state you have to pass around the less verbose and maintainable the application becomes. CDI is automatically passing our key (the conversation id) around for us. Under the review button the list edit page, add the following GET link : <h:link If you look at the link URL it is where xxx is some number. CDI automatically creates a URL that propagates the conversation for us. If we didn’t want to propagate the conversation, we can just add a blank cid parameter and CDI will leave it alone. This can be useful when you want to launch a page without a conversation from a page that is in a conversation. Add the following link : <h:link <f:param </h:link>This lets you start a fresh new list in a separate window (since we didn’t specify an outcome it defaults to the current page). If you create a new list and add some numbers you can see that you can manage separate lists independently without doing anything to handle multiple browser windows. When you have multiple windows open, set the url of one window to the url of other (i.e. where xxx is the other conversation ID) when you load this page, you see the list from the other conversation so you can just switch conversations using GET requests by specifying a different conversation id. Workspace Management One cool feature of Seam that had a lot of potential was workspace management which lets you see a list of active conversations and select one. We are going to implement a version of that here by providing the user with a set of links that takes us to the active conversation. Create a new bean that is session scoped that will keep a track of our conversation ids. import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class WorkspaceBean implements Serializable { private List<String> conversations = new ArrayList<String>(); public List<String> getConversations() { return conversations; } } This is just a bean that keeps a list of the conversation Ids currently active. When we start a conversation, we need to add that id to the list and when we end a conversation, we need to remove it from the list. We will inject this session scoped bean into our backing bean and change the postConstruct and confirm methods in the BackingBean class to add and remove the conversation from the list. @Inject private WorkspaceBean workspace; ... ... @PostConstruct public void postConstruct() { conversation.begin(); workspace.getConversations().add(conversation.getId()); } public void confirm() { workspace.getConversations().remove(conversation.getId()); conversation.end(); try { FacesContext ctx = FacesContext.getCurrentInstance(); ctx.getExternalContext().redirect("home.jsf?faces-redirect=true"); } catch (IOException e) { e.printStackTrace(); } } Now we need some view code to display the list of conversations and provide links to them. Simply add this to the home.xhtml page, and even the listEdit.xhtml or review.xhtml pages if you want : <h1>Workspaces</h1> <ui:repeat <h:link <f:param </h:link> <br /> </ui:repeat> This just loops through the conversations and creates a link to the listEdit page and passes the conversation Id as a parameter. Because we pass a value for cid CDI will not try to add the current conversation as the cid value. That’s all you need for a workspace demonstration. You can create new lists and if you jump back to the home page, you will see the available conversations and be able to click the link and jump back into the conversation. When you review the list and confirm it and the conversation ends, when you end up back on the front page, that conversation is longer listed. This is a fairly powerful mechanism that is built upon the simplicity of CDI Conversations. There is very little work that is required to use conversations, just inject the Conversation instance and call the begin() and end() methods when you need to start and end the conversation. Conversations also have a minimal impact on our code, mainly just an annotation since the getters and settings and other methods don’t change. We can also easily revert back to a stateless request scoped solution should we have to which would cause additional code to be required to read/write the list to the client. Conversations should be used with care, especially in terms of making sure you have strict demarcation boundaries, and careful consideration should be given to determining what you include in a conversation. You can download the maven project source code for this demo (Conversation Demo ), just unzip it and enter mvn jetty:run and navigate to. From Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/cdi-conversations-part-2
CC-MAIN-2020-05
refinedweb
2,466
61.16
Since we also now have Python APIs, it might be a good idea to consider hosting them too along with javadocs. Here is a link to our current documentation: This documentation can be generated using following steps: $ cd src/main/python $ sphinx-apidoc --full --force --output-dir docs systemml $ cd docs Add following lines to conf.py import sys sys.path.append('...FULL PATH...src/main/python/') autodoc_mock_imports = ['pyspark', 'py4j.java_gateway', 'pyspark.mllib.common', 'pyspark.context', 'pyspark.sql', 'pyspark.ml', 'pyspark.ml.feature'] $ make singlehtml As an FYI, Spark moved to Sphinx in version 1.2.0 (please see SPARK-3420). Thanks, Niketan Pansare IBM Almaden Research Center From: Frederick R Reiss/Almaden/IBM@IBMUS To: dev@systemml.incubator.apache.org Date: 09/30/2016 04:33 PM Subject: Re: Enhancing SystemML JavaDocs Wow, I was not aware that those empty JavaDocs were put in -- and left in -- on purpose! To me they are the epitome of useless comments. At best they convey exactly the same information as the line of code immediately below them. Much of the time they end up conveying an incorrect, out-of-date version of the same. And all of the time they limit the amount of useful code that can be on screen at once. Are there many people on the project who actually like the current JavaDoc policy? Fred Luciano Resende ---09/30/2016 03:18:41 PM---On Fri, Sep 30, 2016 at 1:42 PM, Deron Eriksson <deroneriksson@gmail.com> wrote: From: Luciano Resende <luckbr1975@gmail.com> To: dev@systemml.incubator.apache.org Date: 09/30/2016 03:18 PM Subject: Re: Enhancing SystemML JavaDocs On Fri, Sep 30, 2016 at 1:42 PM, Deron Eriksson <deroneriksson@gmail.com> wrote: > I do not see how these automatically generated javadocs are useful. For > instance: > > /** > * > * @param pb > * @param ec > * @return > * @throws DMLRuntimeException > */ > public static double getTimeEstimate(ProgramBlock pb, ExecutionContext ec, > boolean recursive) > throws DMLRuntimeException > > Here, someone has automatically generated a javadoc comment. The developer > has failed to correct the missing 'recursive' parameter. If a developer has > not created a blank javadoc comment in the first place, then the recursive > parameter mistake never would have been made because there never would have > been a blank javadoc comment to update in the first place. > > If automatically generated javadoc comments are decided to be part of our > coding standard, then they should be applied to all methods, not just > random methods. > > Deron > > Completely agree Deron, these are becoming stale and obsolete with the APIs being enhanced and the javadocs being left behind. In the past I actually tried to fix some, but as you mentioned there is a lot and we need a community effort here. Another approach is to make javadocs update MANDATORY for PR acceptance, meaning that, if you touch a given file, you fix any javadoc related to that file. Thoughts ? -- Luciano Resende
http://mail-archives.apache.org/mod_mbox/systemml-dev/201610.mbox/%3COF2DE1C794.D09A9655-ON00258040.0071A9F7-88258040.0071B661@notes.na.collabserv.com%3E
CC-MAIN-2019-26
refinedweb
480
54.22
Revision history for Perl extension Catalyst::Plugin::PageCache 0.31 2010-11-09 - Fixed config in test apps to silence warnings from tests. - Fixed module version number. - Require File::Path 2.07. - Made t/15busy_lock.t test more robust 0.30 2010-11-03 16:03 r13688 - Updated tests to use Cache::FileCache instead of the deprecated ::FileCache. Report and patch by Rod Taylor, RT#53304 & RT#47373. - Fixed t/04critic.t to not fail if Test::Perl::Critic is not installed. - Updated test app code to avoid deprecated constructs. - Only serve GET and HEAD requests (instead of all except POST). RT#53307. - Allow key_maker to be the name of a method to be called on $c. RT#53529. - Assorted performance optimizations. - Add cache_dispatch_hook and cache_finalize_hook to config. RT#53503. - Refactored page cache storage logic, inspired by RT#53303. - Use SHA1 to create cache key to limit length and charset. RT#62343. - Treat the order of repeated URL parameter values as significant. Changes to page index logic used by clear_cached_page(): - Documented race-hazard risks with page index concept. - Reduced the race-hazard risk in one scenario. - Added app class name to index key for added safety. - clear_cached_page() now returns the number of entries matched. - page index keys are original /path?query not altered by key_maker or sha1. - Now warns if disable_index is not explicitly set in config. - disable_index may default true in a future release. 0.22 2009-06-25 10:38:00 - Update to use MRO::Compat 0.21 2008-10-02 10:45:00 - Check for FileCache in new test to avoid test failures. 0.20 2008-10-02 00:15:00 - Config option 'cache_headers' to cache HTTP headers. This is needed if operating behind edge caches such as Akamai. (Chris Alef) - Config option 'busy_lock' borrowed from Mason, avoids the "dog-pile" effect where many concurrent requests can generate and cache the same page. See the documentation for details. - The ability to call clear_cached_page can be disabled to improve performance (a cache index will not be created/updated). 0.19 2008-08-22 13:00:00 - Change config namespace to $c->config->{'Plugin::PageCache'}, old namespace will still continue to work. - key_maker method, allows custom cache keys to be used. (Martin Ellison) 0.18 2008-04-25 11:30:00 - cache_hook method, run a method before returning a cached page. (J. Shirley) 0.17 2007-07-29 22:00:00 - If using C::P::I18N, allow caching of different versions of a single URI based on the page language. (Roberto Henríquez) 0.16 2007-07-24 10:30:00 - Fixed a bug where pages with query strings but no params did not have the cache key created properly. - Switched to Module::Install. 0.15 2006-12-31 20:04:03 - Don't cache pages with errors. 0.14 2006-10-19 22:15:00 - Support newer C::P::Cache modules. 0.13 2006-08-12 14:43:00 - Add optional support to check Authentication plugin if user is logged in. (marcus) 0.12 2006-03-09 16:30:00 - Fixed race condition in HTTP header test. - Fixed Content-type to retain charset (moseley) - Send cache headers on all requests (was not sending on first request) (moseley) - Added ability to pass in a DateTime object to expire at a specific time (moseley) - Added ability to pass in an options list to set the cache expires time separately from the expires time sent to client. (moseley) - Test If-Modified-Since headers on request that loads the page cache. Was only testing when returning a page already in the page cache. (moseley) - Now sends Expires and Cache-Control headers on 304 to reset client cache. (moseley) - Allow setting a zero expires to allow just page caching. (moseley) 0.11 2005-09-13 14:50:00 - Fixed MANIFEST. 0.10 2005-09-13 14:00:00 - Fixed bug in cache key generation that ignored duplicate key names. - Fixed bug where clear_cached_page called with a regex did not properly remove the page from cache. - Fixed bug where cache metadata was not set properly if content-type or content-encoding was missing. - Added test suite. - Code cleanup per Best Practices. 0.09 2005-06-27 11:25:00 - Removed dependence on HTTP::Date. - Make sure the same cache key checked during the dispatch phase is used during the finalize phase. This avoids problems if the user adds or deletes request parameters. 0.08 2005-06-16 00:20:00 - Debug is now enabled by default if in Catalyst -Debug mode. - Expires now properly defaults to undef for Cache::Memcached backend. 0.07 2005-06-13 23:15:00 - Bugfix: Define auto_cache to an empty arrayref if not specified. 0.06 2005-06-07 23:40:00 - Die if no cache plugin is loaded. (chansen) - Changed to isa() for cache backend detection. (chansen) 0.05 2005-06-06 23:15:00 - Fixed bug in clear_cached_page when cache index is not available. - Added cache backend detection in order to properly keep the cache index from expiring when possible. - Remove page from cache index when it has expired. 0.04 2005-06-05 16:20:00 - Removed unnecessary prepare_request method. 0.03 2005-06-04 22:30:00 - Switched to Class::Accessor::Fast. (chansen) - Preserve Last-Modified time of the cached data. (chansen) 0.02 2005-06-04 18:13:00 - Preserve Content-Type and Content-Encoding of cached data. (chansen) - Send 304 Not Modified header when a browser or proxy requests If-Modified-Since and the data is still cached. (chansen) - Don't check the auto list if the page will already be cached. 0.01 2005-06-04 12:00:00 - initial release
https://metacpan.org/changes/distribution/Catalyst-Plugin-PageCache
CC-MAIN-2016-26
refinedweb
948
68.87
Google Stock Price Prediction using RNN – LSTM Prediction of Google Stock Price using RNN In this we are going to predict the opening price of the stock given the highest, lowest and closing price for that particular day by using RNN-LSTM. Ref- What is RNN? - Recurrent Neural Networks are the first of its kind State of the Art algorithms that can memorize/remember previous inputs in memorywhen a huge set of Sequential data is given to it. -NNs Some examples are- - One to one It is used for Image Classification. Here input is a single image and output is a single label of the category the image belongs. - One to many(Sequence output) It is used for Image Captioning. Here the input is an image and output is a group of words which is the caption for the image. - Many to One(Sequence input) It is used for Sentiment Analysis. Here a given sentence which is a group of words is classified as expressing positive or negative sentiment which is a single output. - Many to Many(Sequence input and sequence output) It is Machine Translation. A RNN reads a sentence in English and then outputs a sentence in French. - Synced Many to Many(Synced sequence input and output) It is used for Video Classificationwhere we wish to label each frame of the video. The Problem of Long-Term Dependencies Vanishing Gradient - Information travels through the neural network from input neurons to the output neurons, while the error is calculated and propagated back through the network to update the weights. - During the training, the cost function(e) compares your outcomes to your desired output. - If the partial derivation of error is less than 1, then when it gets multiplied with the learning rate which is also very less won’t generate a big change when compared with previous iteration. - For the vanishing gradient problem, the further you go through the network, the lower your gradient is and the harder it is to train the weights, which has a domino effect on all of the further weights throughout the network. Exploding Gradient - We speak of Exploding Gradients when the algorithm assigns a stupidly high importance to the weights, without any reason. - Exploding gradients are a problem where large error gradients accumulate and result in very large updates to neural network model weights during training. - This has the effect of your model being unstable and unable to learn from your training data. -. - LSTMs are explicitly designed to avoid the long-term dependency problem. Remembering information for long periods of time is practically their default behavior, not something they struggle to learn! Dataset You can download the dataset from here The data used in this notebook is from 19th August,2004 to 7th October,2019. The dataset consists of 7 columns which contain the date, opening price, highest price, lowest price, closing price, adjusted closing price and volume of share for each day. Steps to build stock prediction model - Data Preprocessing - Building the RNN - Making the prediction and visualization We will read the data for first 60 days and then predict for the 61st day. Then we will hop ahead bt one day and read the next chunk of data for next sixty days. The necessary python libraries are imported here- numpyis used to perform basic array operations pyplotfrom matplotlibis used to visualize the results pandasis used to read the dataset MinMaxScalerfrom sklearnis used scale the data import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler read_csv is used to load the data into the dataframe. We can see the last 5 rows of the dataset using data.tail(). Similarly data.head() can be used to see the first 5 rows of the dataset. date_parser is used for converting a sequence of string columns to an array of datetime instances. data = pd.read_csv('GOOG.csv', date_parser = True) data.tail() Here we splitting the data into training and testing dataset. We are going to take data from 2004 to 2018 as training data. Subsequently we are going to take the data of 2019 as testing data. data_training = data[data['Date']<'2019-01-01'].copy() data_test = data[data['Date']>='2019-01-01'].copy() We are dropping the columns Date and Adj Close from the training dataset data_training = data_training.drop(['Date', 'Adj Close'], axis = 1) The values in the training data are not in the same range. For getting all the values in between the range 0 to 1 we are going to use MinMaxScalar().This improves the accuracy of prediction. scaler = MinMaxScaler() data_training = scaler.fit_transform(data_training) data_training array([[3.30294890e-04, 9.44785459e-04, 0.00000000e+00, 1.34908021e-04, 5.43577404e-01], [7.42148227e-04, 2.98909923e-03, 1.88269054e-03, 3.39307537e-03, 2.77885613e-01], [4.71386886e-03, 4.78092896e-03, 5.42828241e-03, 3.83867225e-03, 2.22150736e-01], ..., [7.92197108e-01, 8.11970141e-01, 7.90196475e-01, 8.15799920e-01, 2.54672037e-02], [8.18777193e-01, 8.21510648e-01, 8.20249255e-01, 8.10219301e-01, 1.70463908e-02], [8.19874096e-01, 8.19172449e-01, 8.12332341e-01, 8.09012935e-01, 1.79975186e-02]]) As mentioned above we are going to train the model on data of 60 days at a time. So the code mentioned below divides the data into chunks of 60 rows. data_training.shape[0] is equal to 3617 which corresponds to the length of data_traning. After dividing we are converting X_train and y_train into numpy arrays. X_train = [] y_train = [] for i in range(60, data_training.shape[0]): X_train.append(data_training[i-60:i]) y_train.append(data_training[i, 0]) X_train, y_train = np.array(X_train), np.array(y_train) As we can see X_train now consists of 3557 chunks of data having 60 lists each and each list has 5 elements which correspond to the 5 attributes in the dataset. X_train.shape (3557, 60, 5) Building LSTM Here we are importing the necessary layers to build out neural network from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, LSTM, Dropout - The first layer is the LSTM layer with 60 units. - We will be using reluactivation function. - The rectified linear activation function or ReLU for short is a piecewise linear function that will output the input directly if it is positive, otherwise, it will output zero. return_sequencewhen set to Truereturns the full sequence as the output. input_shapeis set to (X_train.shape[1],5)which is (60,5) Dropout layeris used to by randomly set the outgoing edges of hidden units to 0 at each update of the training phase. - The value passed in dropout specifies the probability at which outputs of the layer are dropped out. - The last layer is the Dense layeris the regular deeply connected neural network layer. - As we are predicting a single value the unitsin the last layer is set to 1. regressor = Sequential() regressor.add(LSTM(units = 60, activation = 'relu', return_sequences = True, input_shape = (X_train.shape[1], 5))) regressor.add(Dropout(0.2)) regressor.add(LSTM(units = 60, activation = 'relu', return_sequences = True)) regressor.add(Dropout(0.2)) regressor.add(LSTM(units = 80, activation = 'relu', return_sequences = True)) regressor.add(Dropout(0.2)) regressor.add(LSTM(units = 120, activation = 'relu')) regressor.add(Dropout(0.2)) regressor.add(Dense(units = 1)) regressor.summary() Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm (LSTM) (None, 60, 60) 15840 _________________________________________________________________ dropout (Dropout) (None, 60, 60) 0 _________________________________________________________________ lstm_1 (LSTM) (None, 60, 60) 29040 _________________________________________________________________ dropout_1 (Dropout) (None, 60, 60) 0 _________________________________________________________________ lstm_2 (LSTM) (None, 60, 80) 45120 _________________________________________________________________ dropout_2 (Dropout) (None, 60, 80) 0 _________________________________________________________________ lstm_3 (LSTM) (None, 120) 96480 _________________________________________________________________ dropout_3 (Dropout) (None, 120) 0 _________________________________________________________________ dense (Dense) (None, 1) 121 ================================================================= Total params: 186,601 Trainable params: 186,601 Non-trainable params: 0 _________________________________________________________________ Here we are compiling the model and fitting it to the training data. We will use 50 epochs to train the model. An epoch is an iteration over the entire data provided. batch_size is the number of samples per gradient update i.e. here the weights will be updates after 32 training examples. regressor.compile(optimizer='adam', loss = 'mean_squared_error') regressor.fit(X_train, y_train, epochs=50, batch_size=32) Train on 3557 samples Epoch 45/50 3557/3557 [==============================] - 26s 7ms/sample - loss: 6.8088e-04 Epoch 46/50 3557/3557 [==============================] - 25s 7ms/sample - loss: 6.0968e-04 Epoch 47/50 3557/3557 [==============================] - 25s 7ms/sample - loss: 6.6604e-04 Epoch 48/50 3557/3557 [==============================] - 25s 7ms/sample - loss: 6.2150e-04 Epoch 49/50 3557/3557 [==============================] - 25s 7ms/sample - loss: 6.4292e-04 Epoch 50/50 3557/3557 [==============================] - 25s 7ms/sample - loss: 6.3066e-04 Prepare test dataset These are the first 5 entries in the test data set. To predict opening on any day we need the data of previous 60 days. data_test.head() past_60_days contains the data of the past 60 days required to predict the opening of the 1st day in the test data set. past_60_days = data_training.tail(60) We are going to append data_test to past_60_days and ignore the index of data_test and drop Date and Adj Close. df = past_60_days.append(data_test, ignore_index = True) df = df.drop(['Date', 'Adj Close'], axis = 1) df.head() Similar to the training data set we have to scale the test data so that all the values are in the range 0 to 1. inputs = scaler.transform(df) inputs array([[0.93805611, 0.93755773, 0.92220906, 0.91781776, 0.0266752 ], [0.91527437, 0.91792904, 0.91350452, 0.90892169, 0.01425359], [0.90103881, 0.91343268, 0.89872289, 0.90204445, 0.02331778], ..., [0.93940683, 0.93712442, 0.93529076, 0.9247443 , 0.01947328], [0.92550693, 0.93064972, 0.92791493, 0.9339358 , 0.01954719], [0.93524016, 0.94894575, 0.95017564, 0.95130949, 0.01227612]]) We have to prepare the test data like the training data. X_test = [] y_test = [] for i in range(60, inputs.shape[0]): X_test.append(inputs[i-60:i]) y_test.append(inputs[i, 0]) X_test, y_test = np.array(X_test), np.array(y_test) X_test.shape, y_test.shape ((192, 60, 5), (192,)) We are now going to predict the opening for X_test using predict() y_pred = regressor.predict(X_test) As we had scaled all the values down, now we will have to get them back to the original scale. scaler.scale_ gives the scaling level scaler.scale_ array([8.18605127e-04, 8.17521128e-04, 8.32487534e-04, 8.20673293e-04, 1.21162775e-08]) 8.186 is the first value in the list which gives the scale of opening price. We will multiply y_pred and y_test with the inverse of this to get all the values to the original scale. scale = 1/8.18605127e-04 scale 1221.5901990069017 y_pred = y_pred*scale y_test = y_test*scale Visualization # Visualising the results plt.figure(figsize=(14,5)) plt.plot(y_test, color = 'red', label = 'Real Google Stock Price') plt.plot(y_pred, color = 'blue', label = 'Predicted Google Stock Price') plt.title('Google Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show() As we can see from the graph we have got a decent prediction of the opening price with a good accuracy.
https://kgptalkie.com/google-stock-price-prediction-using-rnn-lstm/
CC-MAIN-2021-17
refinedweb
1,846
64.51
_lwp_cond_reltimedwait(2) - change access permission mode of file #include <sys/stat.h> int chmod(const char *path, mode_t mode); int fchmod(int fildes, mode_t mode); int fchmodat(int fd, const char *path, mode_t mode, int flag);,)): the user owns the file the user owns the directory the file is writable by the user effective action and returns successfully. Upon successful completion, chmod() and fchmod() mark for update the st_ctime field of the file. The fchmodat() function is equivalent to chmod() except in the case where path specifies a relative path. In this case the file to be changed isperform the check. Values for flag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h> If path names a symbolic link, then the mode of the symbolic link is changed. If fchmodat() is passed the special value AT_FDCWD in the fd parameter, the current working directory is used. If flag is also 0, the behavior shall be identical to a call to chmod(). Upon successful completion, 0 is returned. Otherwise, -1 is returned, the file mode is unchanged, and errno is set to indicate the error. The chmod(), fchmod(), and fchmodat() functions will fail if: file referred to by path resides on a read-only file system. The chmod() and fchmod() functions will fail if: An I/O error occurred while reading from or writing to the file system. The chmod() and fchmodat()functions will fail if: Search permission is denied on a component of the path prefix of path. The privilege {FILE_DAC_SEARCH} overrides file permissions restrictions in that case.. A component of the prefix of path is not a directory. The chmod() function will fail if: The path argument points to an illegal address. The fildes argument points to a remote machine and the link to that machine is no longer active. The fchmod() function will fail if: The fildes argument is not an open file descriptor The path argument points to a remote machine and the link to that machine is no longer active. The fchmod chmod(), fchmod(), and fchmodat() functions may fail if: A signal was caught during execution of the function. The value of the mode argument is invalid. The chmod() and fchmodat() functions. The fchmodat() function may fail if: The value of the flag argument is invalid The path argument is not an absolute path and fd is neither AT_FDCWD nor a file descriptor associated with a directory The AT_SYMLINK_NOFOLLOW bit is set in the flag argument, path names a symbolic link, and the system does not support changing the mode of a symbolic link. permissions. :
http://docs.oracle.com/cd/E23824_01/html/821-1463/fchmodat-2.html
CC-MAIN-2013-20
refinedweb
437
61.16
By Dumitru - Topcoder member Discuss this article in the forums. Introduction Straight-forward problems that don’t require a special technique Breadth First Search (BFS) Flood Fill< Brute Force and Backtracking Brute Force Backtracking Dynamic Programming Hard Drills Maximum Flow Optimal Pair Matching Linear Programming (Simplex) Conclusion Introduction With many Topcoder problems, the solutions may be found instantly just by reading their descriptions. This is possible thanks to a collection of common traits that problems with similar solutions often have. These traits serve as excellent hints for experienced problem solvers that are able to observe them. The main focus of this article is to teach the reader to be able to observe them too. Straight-forward problems that don’t require any special technique (e.g. simulation, searching, sorting etc.) In most cases, these problems will ask you to perform some step by step, straight-forward tasks. Their constraints are not high, and not too low. In most cases the first problems (the easiest ones) in topcoder Single Rounds Matches are of this kind. They test mostly how fast and properly you code, and not necessarily your algorithmic skills. Most simple problems of this type are those that ask you just to execute all steps described in the statement. BusinessTasks – SRM 236 Div 1: N tasks are written down in the form of a circular list, so the first task is adjacent to the last one. A number n is also given. Starting with the first task, move clockwise (from element 1 in the list to element 2 in the list and so on), counting from 1 to n. When your count reaches n, remove that task from the list and start counting from the next available task. Repeat this procedure until one task remains. Return it. For N<=1000 this problem is just a matter of coding, no special algorithm is needed – do this operation step by step until one item is left. Usually these types of problems have a much smaller N, and so we’ll not consider cases where N is very big and for which complicated solution may be needed. Remember that in topcoder competitions even around 100 millions sets of simple operations (i.e. some multiplications, attributions or if statements) will run in allowed time. This category of problems also includes those that need some simple searches. TallPeople – SRM 208 Div 1: A group of people stands before you arranged in rows and columns. Looking from above, they form an R by C rectangle of people. Your job is to return 2 specific heights – the first is computed by finding the shortest person in each row, and then finding the tallest person among them (the “tallest-of-the-shortest”); and the second is computed by finding the tallest person in each column, and then finding the shortest person among them (the “shortest-of-the-tallest”). As you see this is a really simple search problem. What you have to do is just to follow the steps described in the statement and find those 2 needed heights. Other TC problems may ask you to sort a collection of items by respecting certain given rules. These problems may be also included in this category, because they too are straight-forward – just sort the items respecting the rules! You can do that with a simple O(N^2) sorting algorithm, or use standard sorting algorithm that exist in your coding language. It’s just a matter of coding. Other example(s): MedalTable – SRM 209 Div 1. Breadth First Search (BFS) Problems that use BFS usually ask to find the fewest number of steps (or the shortest path) needed to reach a certain end point (state) from the starting one. Besides this, certain ways of passing from one point to another are offered, all of them having the same cost of 1 (sometimes it may be equal to another number). Often there is given a N x M table (formed of N lines and M columns) where certain cells are passable and others are impassable, and the target of the problem is to find the shortest time/path needed to reach the end point from the start one. Such tables may represent mazes, maps, cities, and other similar things. These may be considered as classical BFS problems. Because BFS complexity is in most cases linear (sometimes quadratic, or N logN), constraints of N (or M) could be high – even up to 1 million. SmartWordToy – SRM 233 Div 1: A word composed of four Latin lowercase letters is given. With a single button click you can change any letter to the previous or next letter in alphabetical order (for example ‘c’ can be changed to ‘b’ or ‘d’). The alphabet is circular, thus ‘a’ can become ‘z’, and ‘z’ can become ‘a’ with one click. A collection of constraints is also given, each defining a set of forbidden words. A constraint is composed of 4 strings of letters. A word is forbidden if each of its characters is contained in corresponding string of a single constraint, i.e. first letter is contained in the first string, the second letter – in the second string, and so on. For example, the constraint “lf a tc e” defines the words “late”, “fate”, “lace” and “face”. You should find the minimum number of button presses required to reach the word finish from the word start without passing through forbidden words, or return -1 if this is not possible. Problem hints: Words can be considered as states. There are at most 26^4 different words composed of 4 letters (thus a linear complexity will run in allowed time). There are some ways to pass from one state to another. The cost of passing from a state to another is always 1 (i.e. a single button click). You need to find the minimum number of steps required to reach the end state from start state. Everything indicates us that it’s a problem solved by the help of a BFS. Similar things can be found in any other BFS problems. Now let’s see an interesting case of BFS problems. CaptureThemAll – SRM 207 Div 2 (3rd problem): Harry is playing a chess game. He has one knight, and his opponent Joe has a queen and a rook. Find the minimum number of steps that Harry’s knight has to jump so that it captures both the queen and the rook. Problem hints: At first sight this may seem like dynamic programming or backtracking. But as always, take a look into the text of the statement. After a while you should observe the following things: A table is given. The knight can jump from one cell to some of its neighbors. The cost of passing from a cell to another is always 1 (just one jump). You need to find the minimum number of steps (jumps). Given this information we can see that the problem can be easily solved by the help of BFS. Don’t get confused by the fact that connected points are represented by unconnected cells. Think of cells as points in a graph, or states (whatever you want) – and in order to pass from one point to another, the knight should be able to jump from the first to the second point. Notice again that the most revealing hint about the BFS solution is the cost of 1 for any jump. Train yourself in finding the hints of a BFS problem in following examples: Other example(s): RevolvingDoors – SRM 223 Div 1. WalkingHome – SRM 222 Div 1. TurntableService – SRM 219 Div 1. Flood Fill Sometimes you may encounter problems that are solved by the help of Flood Fill, a technique that uses BFS to find all reachable points. The thing that makes them different from BFS problems described above is that a minimum path/cost is not needed. For example, imagine a maze where 1 represents impassable cells and 0 passable cells. You need to find all cells that are reachable from the upper-left corner. The solution is very simple – take one-by-one a visited vertex, add its unvisited neighbors to the queue of visited vertices and proceed with the next one while the queue is still populated. Note that in most cases a DFS (Depth First Search) will not work for such problems due to stack overflows. Better use a BFS. For inexperienced users it may seem harder to implement, but after a little training it becomes a “piece of cake”. A good example of such problem would be: grafixMask – SRM 211 Div 1: A 400 x 600 bitmap is given. A set of rectangles covers certain parts of this bitmap (the corners of rectangles have integer coordinates). You need to find all contiguous uncovered areas, including their sizes. Problem hints: What do we have here? A map (table) Certain points are impassable (those covered by given rectangles) Contiguous areas need to be found It is easy to understand that a problem with such a statement needs a Flood Fill. Usually problems using it are very easy to detect. Brute Force and Backtracking I have placed these 2 techniques in the same category because they are very similar. Both do the same thing – try all possible cases (situations) and choose the best one, or count only those that are needed (depending on the problem). Practically, Backtracking is just more advanced and optimized than Brute Force. It usually uses recursion and is applied to problems having low constraints (for example N<=20). GeneralChess – SRM 197 Div 1: You are given some knights (at most 8), with their positions on the table (-10000<=x, y<=10000). You need to find all positions to place another one, so that it threatens all given pieces. Problem hints: Well, this is one of the easiest examples. So which are the hints of this statement? You need to find all possible situations (positions) that satisfy a certain rule (threatens all given pieces). The limits are very low – only 8 knights are at most given. It’s a common Brute Force problem’s statement. Note that x and y limits are not relevant, because you need only try all positions that threaten one of the knights. For each of these positions see if the knight placed at that position threatens all others too. Another interesting problem would be: LargestCircle – SRM 212 Div 2 (3rd problem): Given a regular square grid, with some number of squares marked, find the largest circle you can draw on the grid that does not pass through any of the marked squares. The circle must be centered on a grid point (the corner of a square) and the radius must be an integer. Return the radius of the circle. The size of the grid is at most 50. Problem hints: And again one of the most important hints is the low limit of the size of the grid – only 50. This problem is possible to be solved with the help of the Brute Force because for each cell you can try to find the circle whose center is situated in that cell and that respects the rules. Among all of these circles found, select the one that has the greatest radius. Complexity analysis: there are at most 50×50 cells, a circle’s radius is an integer and can be at most 25 units, and you need a linear time (depending on your implementation) for searching the cells situated on the border of the circle. Total complexity is low and thus you can apply a simple Brute Force here. Other example(s): Cafeteria - SRM 229 Div 1 WordFind - SRM 232 Div 1 Backtracking This technique may be used in many types of problems. Just take a look at the limits (N, M and other main parameters). They serve as the main hint of a backtrack problem. If these are very small and you haven’t found a solution that’s easier to implement – then just don’t waste your time on searching it and implement a straight-forward backtracking solution. Usually problems of this kind ask you to find (similarly to Brute Force): Every possible configuration (subset) of items. These configurations should respect some given rules. The “best” configuration (subset) that respects some given rules. BridgeCrossing – SRM 146 Div 2 (3rd problem): A group of people is crossing an old bridge. The bridge cannot hold more than two people at once. It is dark, so they can’t walk without a flashlight, and they only have one flashlight! Furthermore, the time needed to cross the bridge varies among the people in the group. When people walk together, they always walk at the speed of the slowest person. It is impossible to toss the flashlight across the bridge, so one person always has to go back with the flashlight to the others. What is the minimum amount of time needed to get all the people across the bridge? There are at most 6 people. Problem hints: First look at the constraints – there are at most ONLY 6 people! It’s enough for generating all possible permutations, sets etc. There are different possible ways to pass the people from one side to another and you need to find the best one. This is of course a problem solved with a backtracking: at the beginning choose any 2 people to pass the bridge first, and after that at each step try to pass any of those that have been left on the start side. From all these passages select the one that needs the smallest amount of time. Note that among persons that have passed over the bridge, the one having the greatest speed should return (it’s better than returning one having a lower speed). This fact makes the code much easier to implement. After having realized these things – just code the solution. There may be others – but you will lose more time to find another than to code this one. MNS – SRM 148 Div 1: 9 numbers need to be arranged in a magic number square. A magic number square is a square of numbers that is arranged such that every row and column has the same sum. You are given 9 numbers that range from 0 to 9 inclusive. Return the number of distinct ways that they can be arranged in a magic number square. Two magic number squares are distinct if they differ in value at one or more positions. Problem hints: Only 9 numbers are given at most; and every distinct way (configuration) to arrange the numbers so that they form a magic number square should be found. These are the main properties of a Backtracking problem. If you have observed them – think about the code. You can generate all permutations of numbers and for each of them check if it forms a magic square. If so – add it to the answer. Note that it must be unique. A possible way to do that – is to have a list of earlier found configurations, thus for each new magic square check if it exists in that list and if it doesn’t – add it to the answer. There will not be many distinct magic squares, thus no additional problems will appear when applying this method. Other example(s): WeirdRooks - SRM 234 Div 1 Dynamic Programming Quite a few problems are solved with the help of this technique. Knowing how to detect this type of problem can be very valuable. However in order to do so, one has to have some experience in dynamic programming. Usually a DP problem has some main integer variables (e.g. N) which are neither too small, nor too big – so that a usual DP complexity of N^2, N^3 etc. fits in time. Note that in the event that N is very small (for TC problems usually less than 30) – then it is likely the problem is not a DP one. Besides that there should exist states and one or more ways (rules) to reach one greater state from another lower one. In addition, greater states should depend only upon lower states. What is a so-called state? It’s just a certain configuration or situation. To better understand dynamic programming, you may want to read this article. Let’s analyze a simple classic DP problem: Given a list of N coins with their values (V1, V2, … ,VN), and the total sum S. Find the minimum number of coins the sum of which is S (you can use as many coins of one type as you want), or report that it’s not possible to select coins in such a way that they sum up to S. Let N <= 1,000 and S <= 1,000. Problem hints: Two main integer variables are given (N and S). These are neither too small, nor are they too big (i.e. a complexity of N*S fits in time). A state can be defined as the minimum number of coins needed to reach a certain sum. A sum (state) i depends only on lower sums (states) j (j<i). By adding a coin to a certain sum – another greater sum is reached. This is the way to pass from one state to another. Thus all properties of a DP problem are uncovered in this statement. Let’s see another (slightly harder) DP problem: ZigZag – 2003 TCCC Semifinals 3: A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence. Given a sequence of integers, return the length of the longest subsequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Assume the sequence contains between 1 and 50 elements, inclusive. Problem hints: There are N numbers given (1<=N<=50), thus N isn’t too small, nor too big. A state (i,d) can be defined as the length of the longest zig-zag subsequence ending with the i-th number, for which the number before the last one is smaller than it for d=0, and bigger for d=1. A state i (i.e. a subsequence ending with the i-th number) depends only on lower states j (j<i). By adding a number to the end of a subsequence – another bigger (greater) subsequence is created. This is the way to pass from one state to another. As you can see – this statement has almost the same traits (pattern) as in the previous problem. The most difficult part in identifying a DP problem statement is observing/seeing the states with the properties described above. Once you can do that, the next step is to construct the algorithm, which is out of the scope of this article. Other example(s): ChessMetric - 2003 TCCC Round 4 AvoidRoads - 2003 TCO Semifinals 4 FlowerGarden - 2004 TCCC Round 1 BadNeighbors - 2004 TCCC Round 4 Hard Drills: Maximum Flow In many cases it’s hard to detect a problem whose solution uses maximum flow. Often you have to create/define graphs with capacities based on the problem statement. Here are some signs of a Maximum Flow problem: Take a look at the constraints, they have to be appropriate for a O(N^3) or O(N^4) solution, i.e. N shouldn’t be greater than 500 in extreme cases (usually it’s less than 100). There should be a graph with edges having capacities given, or you should be able to define/create it from data given in the statement. You should be finding a maximum value of something. Sample problem: You are given a list of water pipes, each having a certain maximum water flow capacity. There are water pipes connected together at their extremities. You have to find the maximum amount of water that can flow from start junction to end junction in a unit of time. Let N<=100. As you can see – it’s a straight-forward maximum flow problem: water pipes represent edges of the graph, their junctions – vertices; and you have to find the maximum value of amount of water that can flow from start to end vertex in a unit of time. Optimal Pair Matching: These problems usually have a list of items (from a set A) for which other items (from a set B) should be assigned under some rules, so that all (or a maximum possible number of) items from set A have to each be assigned to a certain item from set B. Mixed: Some problems need other techniques in addition to network flows. Parking - SRM 236 Div 1: N cars and M parking lots are given. They are situated on a rectangular surface (represented by a table), where certain cells are impassable. You should find a way to assign each car to a parking lot, so that the greatest of the shortest distances from each car to its assigned parking lot is as small as possible. Each parking lot can have at most one car assigned to it. Problem hints: By reading this problem one can simply understand the main idea of the solution – it should be something similar to optimal pair matching, because each car (point from a set A) should be assigned to a parking lot (point from a set B) so that all are assigned and that there is at most one car assigned to a parking lot. Additionally, there can be cars that can’t reach certain parking lots, thus some pairs of points (one point from A and the other from B) are not connected. However a graph should be created for optimal pair matching. The way to make it is clear – an edge exists between a car and a parking lot if only there is a path between them, and its cost is equal to the shortest distance needed for the car to reach the parking lot. The next step of the solution is a binary search on the longest edge. Although it may be out of the scope of this article, I will provide a short explanation: At each step delete those edges of the initial graph that have costs greater than a certain value C (Note that you’ll have to save the initial graph’s state in order to repeat this step again for other C values). If it’s possible in this case to assign all the cars to parking lots – then take a smaller C, and repeat the same operation. If not – take a greater C. After a complete binary search, the smallest C for which a complete assignment is possible will be found. This will be the answer. Linear Programming (Simplex) Most of the common traits of problems solved with the help of the linear programming technique are: You are given collection of items having different costs/weights. There is a certain quantity of each item that must be achieved. A list of sets is given. These sets are composed of some of the available items, having certain quantities of each of them. Each set has a certain cost. The goal of the problem is to find an optimal combination (the cheapest one) of these sets so that the sum of quantities of each of the items they have is exactly the one needed to achieve. At first it may seem confusing, but let’s see an example: Mixture - SRM 231 Div 1: A precise mixture of a number of different chemicals, each having a certain amount, is needed. Some mixtures of chemicals may be purchased at a certain price (the chemical components for the mixture might not be available in pure form). Each of them contains certain amounts of some of the chemicals. You need not purchase the available mixtures in integral amounts. Hence if you purchase a 1.5 of a mixture having a price of 3 and amounts of “2 0 1”, you’ll pay 4.5 and get “3 0 1.5” amounts of chemicals. Your task is to determine the lowest price that the desired mixture can be achieved. Problem hints: A collection of items (chemicals). A list of sets (available mixtures), each containing certain amounts of each of the items, and having a certain cost. You need to find the lowest price of the desired collection of items achieved by the combination of the available sets. More than that – you can take also non-integral amounts of mixtures. These are exactly the traits described above. Conclusion If you have found this article interesting and you have learned new things from it – train yourself on any of the problems in the topcoder Algorithm Arena. Try hard to see the hints and determine the type of the solution by carefully reading through the problem statement. Remember, there are still many problems that may not be included properly in any of the categories described above and may need a different approach.
https://www.topcoder.com/community/competitive-programming/tutorials/how-to-find-a-solution/
CC-MAIN-2021-17
refinedweb
4,203
70.43
public class Singleton { private Singleton() {} private static Singleton instance_ = null; (1) public static Singleton instance() { if (instance_ == null) { (2) synchronized(Singleton.class) { if (instance_ == null) instance_ = new Singleton(); } } return instance_; } } What is Double Checked Locking Problem in Multi-Threading? Carvia Tech | May 05, 2019 | 4 min read | 229 views Double-Checked Locking Problem In earlier times (prior to JDK 1.6) a simple un-contended synchronization block was expensive and that lead many people to write double-checked locking to write lazy initialization code. The double-checked locking idiom tries to improve performance by avoiding synchronization over the common code path after the helper is allocated. But the DCL never worked because of the limitations of previous JMM. This is now fixed by new JMM (JDK 1.5 onwards) using volatile keyword. Why above code idiom is broken in current JMM ? DCL relies on the un synchronized use of _instance field. This appears harmless, but it is not. Suppose Thread A is inside synchronized block and it is creating new Singleton instance and assigning to _instance variable, while thread B is just entering the getInstance() method. Consider the effect on memory of this initialization. Memory for the new Singleton object will be allocated; the constructor for Singleton will be called, initializing the member fields of the new object; and the field resource of SomeClass will be assigned a reference to the newly created object. There could be two scenarios now Suppose Thread A has completed initialization of _instance and exits synchronized block as thread B enters getInstance(). By this time, the _instance is fully initialized and Thread A has flushed its local memory to main memory (write barriers). Singleton’s member fields may refer other objects stored in memory which will also be flushed out.. While Thread B may see a valid reference to the newly created _instance, but because it didn’t perform a read barrier, it could still see stale values of _instance’s member fields.. Fixed double-checked Locking using volatile in new JMM (multi-threaded singleton pattern JDK 1.5) The following code makes the helper volatile so as to stop the instruction reordering. This code will work with JDK 1.5 onwards only. class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) helper = new Helper(); } } return helper; } }. Better Alternatives to DCL Now a days JVM is much smarter and the relative expense of synchronized block over volatile is very less, so it does not really make sense to use DCL for performance reasons. The easiest way to avoid DCL is to avoid it. We can make the whole method synchronized instead of making the code block synchronized. Another option is to use eager initialization instead of lazy initialization by assigning at the creation time Here is the example demonstrating eager initialization Eager instantiation using static keyword class MySingleton { public static Resource resource = new Resource(); } Using Initialization On Demand Holder idiom Inner classes are not loaded until they are referenced. This fact can be used to utilize inner classes for lazy initialization as shown below public class Something { private Something() {} private static class LazyHolder { private static final Something INSTANCE = new Something(); } public static Something getInstance() { return LazyHolder.INSTANCE; } } Enum for Thread-Safe And finally we can use Enum developing for Thread-Safe Singleton class. public enum Singleton{ INSTANCE; } References Wikipedia java Double Checked Locking Explaining the various aspects of double checked locking. Top articles in this category: - Producer Consumer Problem using Blocking Queue in Java - What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications - What is Immutable Class in Java - Troubleshooting Deadlock in Java - What is purpose of Collections.unmodifiableCollection - What is difference between sleep() and wait() method in Java? - Difference between Callable and Runnable Interface
https://www.javacodemonk.com/what-is-double-checked-locking-problem-in-multi-threading-17daeca6
CC-MAIN-2021-21
refinedweb
639
52.6
10 November 2010 17:37 [Source: ICIS news] BARCELONA (ICIS)--Ambitious plans to expand ?xml:namespace> In a speech to delegates, Mohammad Hossein Navid Family, consultant to the managing director of Zagros Petrochemical Company (ZPC), outlined nine pipeline projects, with a total capacity of more than 15m tonnes/year, which would take Iran’s total to more than 20m tonnes/year. Timelines were not given for all nine projects; but four of the projects, with a total capacity of over 6m tonnes/year, were expected to be completed by 2014. However, analysts were doubtful over the plans. “I can’t see it happening; it’s too much [new capacity]. I think they’re over selling themselves. Besides, if all that new methanol came online, prices would go way down,” one analyst said. When asked how current international sanctions against Yet he was confident that as the holder of the world’s second largest proven natural gas reserves, ZPC currently operates two methanol plants of equal size
http://www.icis.com/Articles/2010/11/10/9409195/analysts-sceptical-over-iranian-methanol-production-projects.html
CC-MAIN-2014-15
refinedweb
166
60.24
. This package also provides a new GHCi-command, :printHeap, which allows you to inspect the current heap representation of a value, including sharing and cyclic references. To enable the command, you need to load the included ghci script or add it to ~/.ghci, as explained by cabal install. Once it is set up, you can do this: > let let x = (value, if head value == 'A' then value else "", cycle [True, False]) > :printHeap x let x1 = _bco x21 = [] in (x1,_bco,_bco) > length (take 100 (show x)) `seq` return () -- evaluate everything > :printHeap x let x1 = "A Value" x16 = True : False : x16 in (x1,x1,x16) You can change the maximum recursion depth using :setPrintHeapDepth: > :setPrintHeapDepth 3 > :printHeap x let x1 = C# 'A' : ... : ... in (x1,x1,True : ... : ...) If the view is impaired by blackholes (written _bh), running System.Mem.performGC usually helps. The work on this package has been supported by the Deutsche Telekom Stiftung (). - No changelog available Properties Modules - GHC Flags Use -f <flag> to enable a flag, or -f -<flag> to disable that flag. More info Downloads - ghc-heap-view-0.4.1.0.tar.gz [browse] (Cabal source package) - Package description (included in the package) Maintainers' corner For package maintainers and hackage trustees
http://hackage.haskell.org/package/ghc-heap-view-0.4.1.0
CC-MAIN-2015-06
refinedweb
204
60.95
On 10/05/06, Jonathan Underwood <jonathan underwood gmail com> wrote: So - can anyone come up with a better naming scheme than the one above? I hope so :) To answer my own question - here's a proposal: I could rename the muse package to emacsen-muse, such that the binary rpms are: emacsen-muse (containing the common stuff, and required by the packages below) emacs-muse xemacs-muse emacs-muse-el xemacsen-muse.el The SRPM would be emacsen-muse, and that would also then be the module name in bugzilla etc. Terrible idea? Should this be the guideline specific to (x)emacs packages which build for both flavours? If the FESCO could reach a decision on this it would be useful - then I can move the emacs muse package out of the way, and let the packagers of the other two muse programs fight over the vacant namespace :) J
https://www.redhat.com/archives/fedora-extras-list/2006-May/msg00297.html
CC-MAIN-2015-22
refinedweb
150
60.58
1. Basic Plotting with Pylab¶ - Download the full notebook [v2] - Download the teaching notebook [v2] Use the “v2” files in older versions of IPython, e.g. 0.12 Matplotlib Tutorial: 1. Basic Plot Interface In this notebook, we will explore the basic plot interface using pylab.plot and pylab.scatter. We will also discuss the difference between the pylab interface, which offers plotting with the feel of Matlab. In the following sections, we will introduce the object-oriented interface, which offers more flexibility and will be used throughout the remainter of the tutorial. Setting up IPython IPython has a built-in mode to work cleanly with matplotlib figures. There are a few ways to invoke it: On startup, you can add a command line argument: ipython [notebook] --pylab or: ipython notebook --pylab inline The first can be used with the notebook or with the normal IPython interpreter. The second specifies that figures should be shown inline, directly in the notebook. This is not available with the standard IPython interpreter. After starting IPython, the same can be accomplished through the %pylab magic command: %pylab or: %pylab inline The first works in either the interpreter or the notebook; the second should be used in the notebook. This is useful if an IPython session has already started. We'll take the second route here, and tell IPython we want figures plotted inline: %pylab inline Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'. A first plot: the Pylab interface Now we're ready for a plot. The %pylab mode we entered above does a few things, among which is the import of pylab into the current namespace. For clarity, we'll do this directly here. We'll also import numpy in order to easily manipulate the arrays we'll plot: import pylab import numpy as np Let's make some simple data to plot: a sinusoid x = np.linspace(0, 20, 1000) # 100 evenly-spaced values from 0 to 50 y = np.sin(x) pylab.plot(x, y) [<matplotlib.lines.Line2D at 0x2f723d0>] Customizing the plot: Axes Limits Let's play around with this a bit: first we can change the axis limits using xlim() and ylim() pylab.plot(x, y) pylab.xlim(5, 15) pylab.ylim(-1.2, 1.2) (-1.2, 1.2) Customizing the plot: Axes Labels and Titles We can label the axes and add a title: pylab.plot(x, y) pylab.xlabel('this is x!') pylab.ylabel('this is y!') pylab.title('My First Plot') <matplotlib.text.Text at 0x3261390> Labels can also be rendered using LaTeX symbols: y = np.sin(2 * np.pi * x) pylab.plot(x, y) pylab.title(r'$\sin(2 \pi x)$') # the `r` before the string indicates a "raw string" <matplotlib.text.Text at 0x2f7d310> Customizing the plot: Line Styles We can vary the line color or the line symbol: pylab.plot(x, y, '-r') # solid red line ('r' comes from RGB color scheme) pylab.xlim(0, 10) pylab.ylim(-1.2, 1.2) pylab.xlabel('this is x!') pylab.ylabel('this is y!') pylab.title('My First Plot') <matplotlib.text.Text at 0x38957d0> Other options for the color characters are: 'r' = red 'g' = green 'b' = blue 'c' = cyan 'm' = magenta 'y' = yellow 'k' = black 'w' = white Options for line styles are '-' = solid '--' = dashed ':' = dotted '-.' = dot-dashed '.' = points 'o' = filled circles '^' = filled triangles and many, many more. For more information, view the documentation of the plot function. In IPython, this can be accomplished using the ? functionality: pylab.plot? Also see the online version of this help: Cusomizing the Plot: Legends Multiple lines can be shown on the same plot. In this case, you can use a legend to label the two lines: x = np.linspace(0, 20, 1000) y1 = np.sin(x) y2 = np.cos(x) pylab.plot(x, y1, '-b', label='sine') pylab.plot(x, y2, '-r', label='cosine') pylab.legend(loc='upper right') pylab.ylim(-1.5, 2.0) (-1.5, 2.0) Exercise: Linestyles & Plot Customization Below are two sets of arrays x1, y1, and x2, y2. Create a plot where x1 and y1 are represented by blue circles, and x2 and y2 are represented by a dotted black line. Label the symbols "sampled" and "continuous", and add a legend. Adjust the y limits to suit your taste. x1 = np.linspace(0, 10, 20) y1 = np.sin(x1) x2 = np.linspace(0, 10, 1000) y2 = np.sin(x2) pylab.plot(x1, y1, 'bo', label='sampled') pylab.plot(x2, y2, ':k', label='continuous') pylab.legend() pylab.ylim(-1.5, 2.0) (-1.5, 2.0)
http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
CC-MAIN-2014-52
refinedweb
775
68.47
PROBLEM LINK: Author: Jatin Nagpal Tester: Raja Vardhan Reddy Editorialist: Akash Bhalotia DIFFICULTY: Cakewalk PREREQUISITES: None PROBLEM: A penalty shoot-out between two teams, A and B, taking N shots each, alternating in between shots, in which the result of each shot is known. A goes first. Find the earliest shot, after which the result of the shoot-out can be determined, irrespective of the results of the remaining shots. HINTS: Not the full solution. Just some hints to help you if you are stuck at some point. As soon as you encounter a hint that you had not thought of, go back to solving the problem. Hint 1: There can be three possible results: - A is the winner, or - B is the winner, or - It’s a draw. Is it possible to determine a drawn state before all the 2*N shots have been taken? Hint 2: If A has scored, say, 5 goals after a particular number of shots, and B has scored 2 goals after the same number of shots, and both have, say, 2 shots remaining, is it still possible for B to catch up to and defeat A? QUICK EXPLANATION: show The result of the shoot-out can be known as soon as one of the teams has a score which is greater than - the score of the other team + the number of shots remaining for the other team. If all turns are over without a clear winner, it will be a draw. We can only know be sure of a draw after all 2N shots have been taken. EXPLANATION show Consider the following states in the shoot-out, where: X is the number of goals scored by A till now, Y is the number of goals scored by B till now, LeftA is the number of shots still left for A to take, and LeftB is the number of shots still left for B to take. N is the total number of shots to be taken, per team. State 1: X > (Y+LeftB) State 2: Y > (X+LeftA) State 3: X \leq (Y+LeftB) and Y \le (X+LeftA) and total number of shots taken <2*N State 4: (LeftA=LeftB=0) Let’s consider the above states one by one. In state 1, as X > (Y+LeftB), this implies that X>Y, so A is clearly ahead of B right now. But is it still possible for B to catch up to A and beat it? In the best case scenario for B, A shall miss all their remaining shots, and B shall score in all of them. But since B has only LeftB shots remaining, the maximum score it can achieve is (Y+LeftB), which is < X. Thus, it is not possible to defeat A if such a state is reached. In state 2, as Y > (X+LeftA), this implies that Y>X, so B is clearly ahead of A right now. But is it still possible for A to catch up to B and beat it? In the best case scenario for A, B shall miss all their remaining shots, and A shall score in all of them. But since A has only LeftA shots remaining, the maximum score it can achieve is (X+LeftA), which is < Y. Thus, it is not possible to defeat B if such a state is reached. In state 3, irrespective of whether X<Y or Y<X or X=Y, the teams have enough shots left to catch up to or defeat the other team. Thus, we need to wait for the results of more shots, before we can determine who’s going to win the shoot-out. In state 4, the teams have no more shots left. Thus, we’ll be able to determine the result of the shoot-out, based on their current scores. If, right now, X>Y, then A is the winner, if Y>X, then B is the winner, and if X=Y, then it’s a draw. In every case, we can be sure of the result now, as no more shots are left. Thus, if the result of the shoot-out is one of the teams winning, it can be known as soon as one of the teams has a score which is greater than : the score of the other team + the number of shots remaining for the other team. This is because the other team won’t be able to catch up with the former team even if it manages to score in all its remaining turns and the former team misses in all its remaining turns. While, if the result of the shoot-out is a draw, it can only be known after all the 2*N shots have been taken. This is because in a draw, the scores are equal. This implies that if A scored in it’s N^{th} shot, and the score of B was equal to the score of A before A's final shot, we’ll only be sure of the result after B's final shot, i.e., whether it will be able to equalise the score or not. On the other hand, if A misses its final shot, B still has a chance to win the game, if it scores in its final shot. Thus, to solve the problem: - Iterate through the shots one by one, maintaining X, Y, LeftA and LeftB, - If after any shot, X > (Y+LeftB) or Y > (X+LeftA), we now know that one of the teams can no longer be defeated, irrespective of the results of the remaining shots. Thus, the result of the shoot-out can be known after this shot. - If we couldn’t predict the result even after 2*N-1 shots, we can be sure of it after the 2*N^{th} shot, as no more shots are remaining for either of the teams. Thus, whatever is the score after the 2*N^{th} shot, will be the final result. SOLUTIONS: Setter #include <bits/stdc++.h> using namespace std; int si(int a) { if(a==0) return 0; if(a<0) return -1; return 1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); //freopen("input.doc","r",stdin); //freopen("output.doc","w",stdout); int t; cin>>t; while(t--) { int n; string s; cin>>n>>s; int a[2]={0,0}; int b[2]={n,n}; int ans=2*n; for(int i=0;i<2*n;i++) { int j=i%2; if(s[i]=='1') { a[j]++; } b[j]--; int sig[2]={si((a[0]+b[0])-(a[1]) ),si( (a[0])-(a[1]+b[1]) )}; if(sig[0]==sig[1] && sig[0]!=0) { ans=i+1; break; } } cout<<ans<<'\n'; } } Tester //raja1999 //#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2") #include <bits/stdc++.h> #include <vector> #include <set> #include <map> #include <string> #include <cstdio> #include <cstdlib> #include <climits> #include <utility> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <iomanip> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //setbase - cout << setbase (16)a;; using namespace __gnu_pbds; sz(a) a.size() > > #define int ll typedef tree< int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; //std::ios::sync_with_stdio(false); main(){ std::ios::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; //t=1; while(t--){ int n,a=0,b=0,i,rema,remb; string s; cin>>n; cin>>s; rema=n; remb=n; rep(i,s.length()){ if(s[i]=='1'){ if(i%2==0){ a++; } else{ b++; } } if(i%2==0){ rema--; } else{ remb--; } if(a>remb+b){ cout<<i+1<<endl; break; } if(b>rema+a){ cout<<i+1<<endl; break; } if(a==b&&remb==0){ cout<<i+1<<endl; break; } } } return 0; } Editorialist //created by Whiplash99 import java.io.*; import java.util.*; class A { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N,scA,scB,leftA,leftB; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while(T-->0) { N=Integer.parseInt(br.readLine().trim()); String s[]=br.readLine().trim().split(""); int a[]=new int[2*N+1]; for(i=0;i<2*N;i++) a[i+1]=Integer.parseInt(s[i]); scA=scB=0; //scores of both the teams leftA=leftB=N; //number of turns left per team for(i=1;i<=2*N;i++) //turns { if(i%2==1) { scA+=a[i]; leftA--; } else { scB+=a[i]; leftB--; } // Is it no longer possible to beat A? // Is it no longer possible to beat B? // Can no team win now (draw)? if((scA>scB+leftB)||(scB>scA+leftA)||(scA==scB&&i==2*N)) break; } sb.append(i).append("\n"); } System.out.println(sb); } } Feel free to share your approach if it differs. You can ask your doubts below. Please let me know if something’s unclear. I would LOVE to hear suggestions
https://discuss.codechef.com/t/pshot-editorial/54383
CC-MAIN-2022-33
refinedweb
1,492
77.87
Java Exercises: Generate and show the first 15 narcissistic decimal numbers Java Numbers: Exercise-6 with Solution Write a Java program to generate and show the first 15 narcissistic decimal numbers. A Narcissistic decimal number is a non-negative integer, n that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. - if n is 153 - then m , (the number of decimal digits) is 3 - we have 13 + 53 + 33 = 1 + 125 + 27 = 153 - and so 153 is a narcissistic decimal number . Narcissistic numbers in various bases : The sequence of base 10 narcissistic numbers starts: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, …… The sequence of base 8 narcissistic numbers starts: 0, 1, 2, 3, 4, 5, 6, 7, 24, 64, 134, 205,…. Sample Solution: Java Code: // public class Example6 { public static void main(String[] args){ for(long n = 0, ctr = 0; ctr < 15; n++){ if(is_narc_dec_num(n)){ System.out.print(n + " "); ctr++; } } System.out.println(); } public static boolean is_narc_dec_num(long n){ if(n < 0) return false; String str1 = Long.toString(n); int x = str1.length(); long sum_num = 0; for(char c : str1.toCharArray()){ sum_num += Math.pow(Character.digit(c, 10), x); } return sum_num == n; } } Sample Output: 0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 Flowchart: Java Code Editor: Contribute your code and comments through Disqus. Previous: Write a Java program to find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500). Next: Write a Java program to display first 10 lucus numbers. What is the difficulty level of this exercise? New Content: Composer: Dependency manager for PHP, R Programming
https://www.w3resource.com/java-exercises/numbers/java-number-exercise-6.php
CC-MAIN-2019-18
refinedweb
310
53.31
I'm having a problem with using templates, and since I'm completely at a loss as to what's wrong, I'm simply going to dump the (I think) relevant sections of code here. Here is the problem code: The bolded line is the one throwing the error. Here is the compiler error:Here is the compiler error:Code:#include <vector> #include <algorithm> using namespace std; template<class client_type> class ServiceList { public: /* blah blah blah... */ // move a client off the to-serve list void signOut(client_type & targ) { signOut(&targ); }; void signOut(client_type * const targ) { // find the given client pointer in our list vector<client_type *>::iterator where = find(client_list.begin(),client_list.end(), targ); // if it's in there, delete it! if (where != client_list.end()) client_list.erase(where); }; /* more blah... */ protected: // the list of pointers to clients vector<client_type *> client_list; }; The bolded line refers to the bolded bit in the code segment I posted.The bolded line refers to the bolded bit in the code segment I posted.Code:In file included from KeyDispatcher.hpp:7, from ProtPlay.hpp:4, from Follower.hpp:4, from Follower.cpp:1: ServiceList.hpp: In member function `void ServiceList<client_type>::signOut(client_type*)': ServiceList.hpp:26: error: expected `;' before "where" ServiceList.hpp:30: error: `where' undeclared (first use this function) ServiceList.hpp:30: error: (Each undeclared identifier is reported only once for each function it appears in.) By the way, I'm using Dev-C++ 4.9.9.2. As I said, I don't know what's wrong at all. Help me, please? And if you have some clever suggestions about the implementation in general, feel free to state them. This class is a template class to use in creating a message-dispatching class. Specifically, I'm currently using it to dispatch keyboard messages to a bunch of character queues. The class keeps a vector of pointers to the client character queues, and the child class of ServiceList will specify a function to actually dispatch the messages by iterating through the vector. I decided on a vector because I don't care (at least, not now) about signin/signout speeds, just the time it takes to dispatch a message. So, yeah. You.Help(Me); ?
https://cboard.cprogramming.com/cplusplus-programming/63457-template-related-problems.html
CC-MAIN-2017-09
refinedweb
369
58.28
Edit file through telnet possible? Is it possible to edit files using Telnet? @jmarcelino Oh yes, I forgot the connect command of rshell. You can also edit through that tool, with edit filename - jmarcelino last edited by jmarcelino @misterlisty I've had great success using the MicroPython rshell tool from over telnet After running rshell just do: connect telnet your IP address and you should then see the LoPy filesystem on /flash Note that you the board must be in the REPL, if it's running a script you must terminate it @misterlisty I'm correcting my notes: Used this little script for step a) import sys def getfile(path): print("Send file contents line by line, finish with Crl+C-Enter.") with open(path, "w") as f: while 1: try: l = sys.stdin.readline() except KeyboardInterrupt: break f.write(l) print(".", end="") It does not echo, but you have to end it with an error. b) use the command getfile("name") and then paste it from Teraterm (alt-v). In teraterm's special settings, use a long value for delay between lines for paste, like 100m. That way, I was able to upload a ~900 line python file (the editor). @misterlisty You might be able to upload a file in two steps a) Upload a script which received data & puts it into a file: def newfile(path): print("Type file contents line by line, finish with EOF (Ctrl+D).") with open(path, "w") as f: while 1: try: l = input() except EOFError: break f.write(l) f.write("\n") Push Ctrl-E, paste the few lines about, and push Ctrl-D. Then you have the function newfile in RAM. b) You can use that to upload another file. But that must be done slow. TeraTerm has an ASCII-Upload feature, which sends files line-by-line with an delay between the lines. You could use that to upload the changed files. I have an editor which works on the board. It is here:. I normally have it in flash. The editor is too large for devices w/o PSRAM to be executed from RAM. But you may be able to send your file the way sketched above. Edit: Just tried my suggestion myself. Works not really well. Uploading the newfile() function works, but TeraTerm does not work well in an attempt to send that file, or the LoPy stalls, at least if it's more than a few lines of code. i forgot to open ftp port on the router on remote site. @misterlisty How did you disable ftp, and can you enable it again though repl? I have deployed some devices in the filed and have only enabled telnet instaead of telnet/ can i edit a file using REPL until i get access to them again. - jmarcelino last edited by jmarcelino It’s possible but very cumbersome, you’d have to do it using Python on the REPL. Why not use FTP instead which is also available?
https://forum.pycom.io/topic/2621/edit-file-through-telnet-possible/1
CC-MAIN-2019-22
refinedweb
499
81.53