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
When can the C++ compiler devirtualize a call? Someone recently asked me about devirtualization optimizations: when do they happen? when can we rely on devirtualization? do different compilers do devirtualization differently? As usual, this led me down an experimental rabbit-hole. The answer seems to be: Modern compilers devirtualize calls to final methods pretty reliably. But there are many interesting corner cases — including some I haven’t thought of, I’m sure! — and different compilers do catch different subsets of those corner cases. First, let’s observe that devirtualization can (probably?) be done more effectively via LTO, using whole-program analysis. I don’t know anything about the state of the art in link-time devirtualization, and it’s hard to experiment with on Compiler Explorer, so I’m not going to talk about LTO at all. We’re looking purely at what the compiler itself can do. There are basically two situations where the compiler knows enough to devirtualize. They don’t have much in common: When we know the instance’s dynamic type The archetypical case here is void test() { Apple o; o.f(); } It doesn’t matter if Apple::f is virtual; all virtual dispatch ever does is invoke the method on the actual dynamic type of the object, and here we know the actual dynamic type is exactly Apple. Static and dynamic dispatch should give us the same result in this case. A sufficiently smart compiler will use dataflow analysis to optimize non-trivial cases such as Derived d; Base *p = &d; p->f(); It turns out that even this simple dodge is enough to fool MSVC and ICC. The next test case is Derived da, db; Base *p = cond ? &da : &db; p->f(); This is too much for Clang, but GCC actually manages to survive it… until you move the conversions to Base* inside the conditional! Here is where even GCC’s analysis fails (Godbolt): Derived da, db; Base *p = cond ? (Base*)&da : (Base*)&db; p->f(); When we know a “proof of leafness” for its static type Okay, let’s suppose that we’re receiving a pointer from somewhere else in the system. We know its static type (e.g. Derived*), but we don’t know the actual dynamic type of the object instance to which it points. Still, the compiler can devirtualize a call to Derived::f if it can somehow prove that no type in the entire program can ever override Derived::f. Proof-by- final The simplest “proof of leafness” is if you’ve marked Derived as final. struct Base { virtual int f(); }; struct Derived final : public Base { int f() override { return 2; } }; int test(Derived *p) { return p->f(); } A pointer of type Derived* must point to an object instance that is “at least Derived” — i.e., Derived or one of its children. Since Derived is final, it isn’t allowed to have children; therefore the dynamic type of the instance must be exactly Derived, and the compiler can devirtualize this call. Or, you can mark the specific method Derived::f as final. The same analysis should apply no matter whether Derived::f is declared in Derived itself, or inherited from Base. So for example the compiler should be equally able to devirtualize struct Base { virtual int f() { return 1; } }; struct Derived final : public Base {}; int test(Derived *p) { return p->f(); } GCC, Clang, and MSVC pass this test (Godbolt, case one); ICC 21.1.9 is fooled. An utterly bizarre proof-of-leafness is to observe that when class C’s destructor is final, C must be childless — because if C had a child, the child would have to have a destructor (since you can’t make a class without a destructor), which would then override C’s destructor, which isn’t allowed. Clang actually both warns on final destructors, and optimizes on them. Every other vendor considers this situation very silly and doesn’t dignify it with a codepath as far as I can tell. Proof-by-internal-linkage A class whose name has internal linkage cannot be named outside the current translation unit. Therefore, it cannot be derived from outside the current translation unit, either! As long as it has no children in the current TU — or at least no children that override its methods — calls to its virtual functions are devirtualizable. namespace { class BaseImpl : public Base {}; } int test(Base *p) { return static_cast<BaseImpl*>(p)->f(); } If p really does point to an object instance that is “at least BaseImpl,” then the compiler can prove that the instance must be exactly BaseImpl. (And if p doesn’t point to an instance that is “at least BaseImpl,” the program has undefined behavior anyway.) This strikes me as a case that might actually come up pretty commonly in real codebases. It’s common to have a base class exposed publicly in the header file, and then one or more derived implementations scoped tightly to a single .cpp file. If you go the extra mile and put those derived implementations into anonymous namespaces, you might be helping out the compiler’s devirtualization logic. Of course, by definition, any such benefit will be limited to that single .cpp file! Another way a type’s name can get internal linkage is when it’s a class template instantiation where one of the template parameters involves a name with internal linkage. If the name T has internal linkage, then E<T> also has internal linkage, even if E itself has external linkage — because you can’t name E<T> without naming T. (Notice that here T must be a “true name”; we’re not talking about type aliases.) It’s also possible to make a type whose name has external linkage, but where the compiler can prove that the type must be incomplete in every other TU. For example, namespace { class Internal {}; } class External { Internal m; }; Any other TU is allowed to forward-declare class External; as an incomplete type, but those TUs can’t ever complete the type because they can’t name the types of its data members. You can’t derive from an incomplete type. So all types derived from External (if any) must be present in this TU; if there are none here, well, that’s a proof-of-leafness! GCC alone detects this situation. Table of results Godbolt for the known-dynamic-type case; Godbolt for the proof-of-leafness case. In the latter, I’ve made separate tests for Derived::f-defined-directly-in- Derived and Derived::g-inherited-from- Base. GCC frequently gets f right but fails to devirtualize g. I’ve filed GCC bug #99093 about that. Steve Dewhurst taught me four’s “silly old-school trick”: Virtual bases are always constructed in the context of the most-derived class. So, if class C has a virtual base all of whose constructors are private, then no child of C will ever be able to construct itself, and therefore no child of C can exist. (Of course that virtual base will have to list C among its friends, in order for C itself to be constructible.) I think this trick is foolproof, and thus constitutes a (very silly) proof-of-leafness for C; but of course no compiler cares to trace through this logical tangle, even if it is foolproof. Can you think of some way to construct a “proof-of-leafness” that I’ve missed? Tell me about it!
https://quuxplusone.github.io/blog/2021/02/15/devirtualization/
CC-MAIN-2021-21
refinedweb
1,244
61.06
Secure video streaming using HTML5 I'm working in HTML5 and I'm trying to stream several videos. Here's the thing: I have to secure these videos. Meaning that I want to stream it for people who are authorized to view it. Is that possible?Thanks! We'll email you when relevant content is added and updated. Does Internet Explorer 9 support a HTML5 API file? My apologizes for the brief question but would anyone happen to know if Internet Explorer 9 would support a HTML5 API file? I can't seem to find anything on? What comprises HTML5? Can someone explain this to me? Can anyone please suggest me the best HTML5 Player like Yendif Player? Any suggestions is highly appreciated.Thanks! We'll email you when relevant content is added and updated. Export .easm drawing to use as interface in web application I've a component (let's say drilling rig) in .easm format. I'm looking to make a web application that uses this rig drawing (the drawing in .easm format) as its interface. How do I export this drawing into its interactive form to this web application? Any help would be appreciated.Thanks! We'll email you when relevant content is added and updated..Thanks! We'll email you when relevant content is added and updated. Which model of SDLC is applicable? I'm doing a project on creation of a website based on .NET (c#). Which model of SDLC is more applicable: (front-end HTML 5 & back-end SQL)? HTML;...
http://itknowledgeexchange.techtarget.com/itanswers/tag/html5/
CC-MAIN-2017-26
refinedweb
256
69.48
The official blog of the Microsoft SharePoint Product Group Once you have your forms and code ready to go, it’s time to compile and deploy your workflow. To prepare for deployment: There are two required files for workflow features: 1) Feature.xml – just like every SharePoint feature, you need one of these for high level feature information. 2) Workflow template xml file (workflow.xml) – we’ve talked about workflow templates a lot, and this is where it comes from. Specify the aspx pages to use for your form types (for IP forms, specify our out-of-box host pages) and details about your dll, and put any extra information you need in the Metadata section. You’ll also need the compiled assembly and your forms. Once you have those, you can do the actual deployment. You will need to do the following things (if you’re using the SharePoint workflow templates, this is what the PostBuildActions batch file does): 1) Copy the assembly to the Global Assembly Cache so that SharePoint can run it 2) Copy your xml files and forms to the SharePoint FEATURES folder, where SharePoint features live and are installed from. Custom aspx pages should go into the LAYOUTS folder. 3) Call stsadm, the magic SharePoint deployment tool, with parameters installfeature and activatefeature, to make the workflow available on a site collection. 4) Do an iisreset to refresh the assemblies and templates. A couple more things to keep in mind: The following diagram shows how the parts of the workflow.xml map to what you’d see in the SharePoint UI and workflow forms ( = an aspx page and a hosted IP form;)): With the feature ready to run on your server, you can now debug it live by adding break points, attaching your Visual Studio project to the IIS (w3wp.exe) processes and clicking through the workflow. Associate your workflow to a list and try running it. When you find a bug, recompile, redeploy, and reset. Repeat until satisfiedJ. FAQ: Debugger setup woes FAQ: Tedious debugging Debugging can be somewhat tedious because of the deployment steps, so here is some advice to speed up the process: · The VS templates for SharePoint Workflow can automatically run the stsadm deployment commands for you when you build. Just prep your xml files, sign the assembly, and set the DEPLOY parameter in the project Post Build Actions command line in your project to turn it on. · If you’ve only changed the assembly, just reinstall it to the GAC and call iisreset. (no need to reinstall the feature). The PostBuildActions.bat file in the SharePoint Workflow VS templates has a QUICK parameter that does exactly that. · If you’ve changed your forms or template, you’ll need to reinstall the feature. Don’t forget to deactivate/uninstall before reactivating. · The <AssociateOnActivate> tag in the metadata section of the workflow.xml will automatically associate a workflow with the Document content type. Setting this to “true” can save time setting up or reactivating an association. Just be sure you test on a doc lib that uses the Document content type. · Upload a bunch of documents so that don’t have to keep cancelling workflows that error out to run them again. Other debugging tips: Next time: Summary and Final Thoughts Thanks!Eilene If you would like to receive an email when updates are made to this post, please register here RSS Eilene -- There's great information here. However, there are still a lot of little gotchas. (See my blog for the ones I've managed to make it through thus far.) A few questions ... 1) I'm observing that the workflow that I'm getting while debugging is slightly different than the one I created and installed. For instance, a delayActivity and a codeActivity are removed. I'm also observing that the file reference is to a dynamically generated XOML file even though the original workflow is a CS file. Is there a way to get attached to the actual DLL? Is there any reason why certain activities might disappear while debugging? 2) As a sort of sidebar to the preceding, I've always believed that to debug items in the GAC you had to manually copy the PDB file into the GAC alongside the DLL. It looks like your post is saying that this isn't required. Is that because of the specific workflow debugging type? 3) You've previously mentioned that the task from a CreateTask activity isn't committed until a workflow is dehydrated. Other than putting a short duration delayActivity (1 second) is there a way to force a dehydration? Rob Bogue [MVP] Eilene, This guide is nice, but what we really need is some documentation on MSDN. Most of the workflow actions in the Microsoft.SharePoint.WorkflowActions namespace are completely undocumented. Ditto for the Microsoft.SharePoint.Workflow namespace. Many of the classes don't even have a one-line description of what the heck they are for. All the data exchange services -- IListItemService, ISharePointService, ITaskService, and IWorkflowModificationService -- completely undocumented. There can't be any serious work on custom Sharepoint workflow actions without some visiblity into how Sharepoint idles and reawakrens workflow instances. Heck, that's just workflows. Half the MSDN entries in the Microsoft.Sharepoint namespace are blank as well. Office 2007 is going live in about a month. I hope the Sharepoint team is aware of how woeful the documentation is right now. rlbogue: "I'm observing that the workflow that I'm getting while debugging is slightly different than the one I created and installed." I had this problem once. I wasn't debugging, but I noticed the workflow activity log had entries from an activity which I had removed from the workflow. After loading the new workflow DLL into the GAC, you need to call IISRESET. By unloading the IIS process and starting a new one, you force it to map the new DLL into its memory space. Hi Eilene, I'm curious about the AssociateOnActivate element. There doesn't seem to be anything about this in the SDK or on the net in general. Can you give any more detail? Sounds exactly like what i'm looking for. Thanks for these articles, they are a good practical overview. Alex Angas. Hi Rob, here are some answers for your questions: 1) Yes, Daryl is right; don't forget to iisreset to refresh everything, and make sure your build and GAC'ed dll's are the same:). I believe the xoml is generated when it's compiled; you can actually create workflows using xoml directly instead of a cs file (haven't tried it, but I think there's a way). The resulting dll should be the same though, in either case. 2) I'm not sure about why this is the case for workflow. But based on my own experience, I've never copied over the pdb when debugging, which is why I didn't write anything about it;). 3) Yes, you can use OnTaskCreated to dehydrate before continuing.:) Cassius, you're right, and thanks for the feedback! We have more info in the RTM SDKs, and we'll be updating after that to fill in any gaps. Sorry for the inconvenience! For now, there's a chart with the important SharePoint.Workflow classes in the summary doc I'll be attaching to my next post, and as a rule of thumb, any On* service method puts the workflow to sleep, anything that's not plows straight through and doesn't commit until it goes to sleep. Daryl, thanks for the helpful advice:) Alex, the example for how this works is the out-of-box Review workflows in MOSS. You'll notice that by default any item in a document library has Approval and Collect Feedback workflows available to run. There're not in the list of associations for the doc lib, so it's may seem like they're coming from nowhere, but in actuality, they are associated with the Document content type, which is the base type for doc lib items. This is done with this tag:). Just add <AssociateOnActivate>true</AssociateOnActivate> under the <Metadata> section of your workflow.xml to automatically make the workflow available on any item of the Document content type. It'll also automatically enable new instances in the association if you uninstall and reinstall the feature (they normally get set to No New Instances on deactivation). Eilene -- I have a batch file that does the install (because I'm still copying in the PDB.) It's tearing down and rebuilding the stack -- complete with two IISRESETs. Yea, I know overkill, however, I don't want to take chances. I rebooted the whole system and I got an accurate instance. ... Now all I have to do is figure out why the workflow won't rehydrate after a delay. I feel like the salmon swimming up stream (only to be snatched up by a bear at some point.) Rob rlbogue: "I have a batch file that does the install (because I'm still copying in the PDB.) It's tearing down and rebuilding the stack -- complete with two IISRESETs.. I rebooted the whole system and I got an accurate instance." I sometimes wonder if the OWSTIMER.EXE process should be restarted as well when you replace a workflow DLL. I know this is sometimes the process responsible for (trying to) rehydrate workflow instances. Then again, it might just be telling Sharepoint to do it through a webservice or some such. rlbogue: "Now all I have to do is figure out why the workflow won't rehydrate after a delay." You're not the only one. Lots of people have this problem, and I've never heard anything from Microsoft about it. I had this problem back in Betas 2 and 2TR. Loads of people talk about it on microsoft.public.sharepoint.development_and_programming, but I've never seen a Microsoft employee post there. For all I know, they don't even read the newsgroup, which seems strange to me. Eilene is helpful; maybe she'll shed some light on what's happening with selays. Since installing the RTM release, my delays started returning. For some reason, they never rehydrate on the first "Workflow" timer job. Always on the second run, 6-10 minutes after the delay expires. Knock on wood they're working for me right now. Lots of people still can't get DelayActivity's to return at all in Sharepoint, which makes the majority of real-life workflow scenarios impossible. :( Hi guys, there's a bug on delays at the moment; we're working on a patch that's almost ready. Sorry for the inconvenience. Great to hear. Bugs will happen. Developers just want to know that 1. MS knows the bug exists, and 2. it will eventually get fixed. Daryl-- The PSS folks are under water right now trying to stay in the newsgroups and as you can see some of the MVPs are struggling with keeping ahead of the demand. It should get better after the first of the year. OnePage : der einfache Blick auf das Wesentliche - die wichtigsten Informationen zu einem Thema auf einer Im not sure how many have found this yet but Eileen Hao has put together a Seven Part walkthrough with... Hey, could any one please tell me why I am not able to see the PostBuildActions.bat file when I am creating a Workflow library? Also please let me know how to create it. Thanks in advance Sorry about that, postbuildactions.bat is coming out with the RTM MOSS SDK, which is alllmost ready... Hi, Perhaps I'm slow but I still don't get the relationship between the debugger and the GAC. Should the pdb be copied? If so how does one get the location? If not, why are breakpoints sometimes dissabled even after uploading the dll and resetting iis? Why do some dlls in the gac appear in windows\assembly\gac and others don't? Is there a bug in visual studio relating to this? Is there an article that explains this well and in simple terms, I'm tired of reading contradictory threads. VJ Can we deploy a workflow as feature using the markup language (.xoml) Liz delay activity bug issue yet fixed or not? I've installed RTM MOSS SDK. whenever my workflow hits delay activity it goes to sleep and never wakes up again. any comment really appreciated! when I want to used my deployed custom workflow I get "the form has been closed" do you know why I get this error. I have been stuck for too long now, please help. thanks Isabelle I just found the solution to the error "the form has been closed". In the workflow.xml in the MetaData section when I specified the FormURN of my Initiation Form it was wrong even if I copied and paste the Form ID in the InfoPath properties. It was urn:schemas-microsoft-com:office:infopath:Initform:-myXSD-2007-03-08T01-00-06 instead of urn:schemas-microsoft-com:office:infopath:InitiationForm:-myXSD-2007-03-08T01-00-06 the name of the form was missed spelled. The sample workflow that Ive developed opens the Initiation form in Add workflow settings(List->Tasks->WorkflowSettings). Is there a way where I get this form to open up when I click on Task->NewItem because instead of using the standard task new item details..i want to use the info path(Inititationform.xsn) to do this. Would this be possible. Also, when I create a new item in tasks,the workflow triggers off but it shows 'Failed on start' in the log the error'The event receiver for the context is invalid' Any feedback on this will help Wow such an exciting topic to learn!! its nice and fun yet its a bit difficult to grasp easily,,, This Hi all, Would anyone know why my workflow errors out with "Failed on Start". When I check the logs, it says it can't find my dll or one of its dependencies. I've loaded it to the GAC but don't know what else needs to be done for it to be found. This is a custom wf I built from an example, it uses an InfoPath Initiation form, accepts my text, then I contine the wf by submitting. At that point it should use my dll in the GAC, but it can't locate it. I verified that it's signed, version number, public key token - all correct. Thanks for any help, Kevin After doing all the steps when i do rebuild I am not able to see the PostBuildActions.bat file when I am creating a Workflow library? Also please let me know how to create it. Suneetha.n : You need the SharePoint workflow templates for Visual Studio. Those templates install when you install the SharePoint 2007 SDK. Here's the link: Hi i am getting "Error occured" when i try to attach my custom workflow to the document library item.any clues? when i uploading a document,my workflow is showing the status as "falied on start(retrying)". I've got the same error "failed on start(retrying)". In log it says that something wrong with the context of workflow. It seems that in VS workflow designer you can't set WorkflowId property of onWorkflowActivated activity. (This property simply is absent in the "Properties" window). But in ECM Starter Kit workflows this property was set (saw in *.Designer.cs file) and they work fine. Is it cause of error? Is it bug? When I start this sample workflow, I got errors like 'Workflow [myworkflowname] was canceled by System Account' and 'Failed on start'. How can I fix these errors? When I want to use my deployed custom workflow I get "the form has been closed" does anyone know why I get this error. Thanks, Laxmikant Great. "Failed on Start (retrying)" an NO solution! Does Ms have a clue? use Sharepoint Logging Spy for real time diagnostics to resolve these issues. Hi I am new to WF. I just created a new custom activity using VS. It built succefully but when I run it, I am getting the message "Unable to start program 'C:\Workflows\SendEmailC\bin\Debug\SendEmailC.dll". Would any one assist me in this problem? Regards.. Hi I have created two Workflows for a site 1)A seperate Approval Group of the site who approves the Workflow ,whenever it is started.And it is working fine. 2)when i enable my second workflow(which is the Member Approval(the member group approves the document) for the same site, and start the workflow i got the error in sharepoint itself stating "An error has occured while starting the [Workflow name]". it will be of great help ,if you can provide me some soln to this problem i am facing for sometime now..!:-( Regards Vimal raj I was able to get rid of the Failed on Start error by repairing the .NET Framework 3.0 SP1. I put additional details in this blob post: I've found one cause to workflows failing on start. When/If you create a new task in your workflow, make sure you set your TaskID equal to a new GUID. This is easy to miss if you bind your TaskID property from the CreateTask activity, rather than specifying a hard coded Guid for the TaskID. On your handler for the CreateTask activity, put code in place that sets the variable that you bound against.. something like "taskID = Guid.NewGuid()". I've tried to create simple sequential workflow in VS 2008. Everything works fine except I can't edit any property of the SPFile from the workflow. No exceptions fired, no messages in a log. Are there any ideas what the problem could be. Thanks much! Yuriy. I have a problem where it appears the workflow starts before the file is complete in a document library. I have a scheduled task that copies an XML file from a remote system via the WebClient. When my workflow starts it loads the XML into an XMLDocument object via workflowProperties.Item.File. But it gives me an error "root element is missing". When I manually upload the same file it works. I added a Thread.Sleep(30000) method to my code just before loading the file as a work around, but is there a better way to tell if the file has finished loading? I have a workflow developed and deployed on the production site.Due to the change request we had to change the workflow by adding a number of states and event driven activities when i deploy the changed workflow with the same dll name i have seen that the already existing items on the production site which were In progress dead and not moving forward where as the new items where using the new version of the dll.Is there any way that i can force the older items In Progress to use the new version of the workflow.VS中开发工作流:部署和调试工作流原文地址:...
http://blogs.msdn.com/sharepoint/archive/2006/11/30/developing-workflows-in-vs-part-6-deploy-and-debug-your-workflow.aspx
crawl-002
refinedweb
3,190
73.58
Error on empty date cell Excel allows setting the number format of an empty cell. If the cell is set to the date format, the value is None, and the attempt to read the value raises a Type Error, as it can't add the calendar offset to None. Not sure I understand the from_excel() function in date_time.init fully - would it be an acceptable patch just to return None in this case if the value is None? from openpyxl import load_workbook wb = load_workbook("test_date.xlsx") ws = wb.active ws.cell('A1').value # datetime.datetime(2014, 1, 31, 0, 0) ws.cell('A2').value ## Returns Error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "openpyxl/cell/cell.py", line 347, in value value = from_excel(value, self.base_date) File "openpyxl/compat/functools.py", line 122, in wrapper result = user_function(*args, **kwds) File "openpyxl/date_time/__init__.py", line 54, in from_excel parts = list(jd2gcal(MJD_0, value + offset - MJD_0)) TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' I guess it's important to catch the exception. I am slightly worried about applying a format to Noneespecially in the light of today's discussion on empty cells. But as Excel insists on treating dates as integer (there is actually a cell-type dfor datetimes, it's just that nobody seems to use it). Update docs, resolves #380 → <<cset 90c5ce8e271d>> Removing version: 2.1.x (automated comment)
https://bitbucket.org/openpyxl/openpyxl/issues/380/error-on-empty-date-cell
CC-MAIN-2020-05
refinedweb
237
58.58
Explore the mysterious moon of Q'tee without getting too close to the alien natives!. In many Minesweeper variants the initial turn is considered a free go — if you hit a mine on the first click, it is moved somewhere else. Here we cheat a little bit by taking the first go for the player, ensuring that it is on a non-mine spot. This allows us not to worry about the bad first move which would require us to recalculate the adjacencies. We can explain this away as the "initial exploration around the rocket" and make it sound completely sensible. The full source code for Moonsweeper is available in the 15 minute apps repository. You can download/clone to get a working copy, then install requirements using: pip3 install -r requirements.txt You can then run Moonsweeper with: python3 minesweeper.py Read on for a walkthrough of how the code works. Playing Field The playing area for Moonsweeper is a NxN grid, containing a set number of mines. The dimensions and mine counts we'll used are taken from the default values for the Windows version of Minesweeper. The values used are shown in the table below: We store these values as a constant LEVELS defined at the top of the file. Since all the playing fields are square we only need to store the value once (8, 16 or 24). LEVELS = [ ("Easy", 8, 10), ("Medium", 16, 40), ("Hard", 24, 99) ] The playing grid could be represented in a number of ways, including for example a 2D 'list of lists' representing the different states of the playing positions (mine, revealed, flagged). However, this implementation uses an object-orientated approach. Individual squares on the map hold all relevant data about their current state and are also responsible for drawing themselves. In Qt we can do this simply by subclassing from QWidget and then implementing a custom paint function. Since our tile objects are subclassing from QWidget we can lay them out like any other widget. We do this, by setting up a QGridLayout. self.grid = QGridLayout() self.grid.setSpacing(5) self.grid.setSizeConstraint(QLayout.SetFixedSize) We can set up the playing around by creating our position tile widgets and adding them our grid. The initial setup for the level reads from LEVELS and assigns a number of variables to the window. The window title and mine counter are updated, and then the setup of the grid starts. def set_level(self, level): self.level_name, self.b_size, self.n_mines = LEVELS[level] self.setWindowTitle("Moonsweeper - %s" % (self.level_name)) self.mines.setText("%03d" % self.n_mines) self.clear_map() self.init_map() self.reset_map() The setup functions will be covered next. The Pos class represents a tile, and holds all the relevant information for its relevant position in the map — including, for example, whether it is a mine, revealed, flagged and the number of mines in the immediate vicinity. Each Pos object also has 3 custom signals clicked, revealed and expandable which we connect to custom slosts. Finally, we call resize to adjust the size of the window to the new contents. This is actually only necessary when the window shrinks — Qt will grow it automatically. def init_map(self): # Add positions to the map for x in range(0, self.b_size): for y in range(0, self.b_size): w = Pos(x,y) self.grid.addWidget(w, y, x) # Connect signal to handle expansion. w.clicked.connect(self.trigger_start) w.revealed.connect(self.on_reveal) w.expandable.connect(self.expand_reveal) # Place resize on the event queue, giving control back to Qt before. QTimer.singleShot(0, lambda: self.resize(1,1)) # <1> - The singleShottimer is required to ensure the resize runs after we've returned to the event loop and Qt is aware of the new contents. Now we have our grid of positional tile objects in place, we can begin creating the initial conditions of the playing board. This is broken down into a number of functions. We name them _reset (the leading underscore is a convention to indicate a private function, not intended for external use). The main function reset_map calls these functions in turn to set it up. The process is as follows — - Remove all mines (and reset data) from the field. - Add new mines to the field. - Calculate the number of mines adjacent to each position. - Add a starting marker (the rocket) and trigger initial exploration. - Reset the timer. The code to do this: def reset_map(self): self._reset_position_data() self._reset_add_mines() self._reset_calculate_adjacency() self._reset_add_starting_marker() self.update_timer() The separate steps from 1-5 are described in detail in turn below, with the code for each step. The first step is to reset the data for each position on the map. We iterate through every position on the board, calling .reset() on the widget at each point. The code for the .reset() function is defined on our custom Pos class, we'll explore in detail later. For now it's enough to know it clears mines, flags and sets the position back to being unrevealed. def _reset_position_data(self): # Clear all mine positions for x in range(0, self.b_size): for y in range(0, self.b_size): w = self.grid.itemAtPosition(y, x).widget() w.reset() Now all the positions are blank, we can begin the process of adding mines to the map. The maximum number of mines n_mines is defined by the level settings, described earlier. def _reset_add_mines(self): # Add mine positions positions = [] while len(positions) < self.n_mines: x, y = random.randint(0, self.b_size-1), random.randint(0, self.b_size-1) if (x ,y) not in positions: w = self.grid.itemAtPosition(y,x).widget() w.is_mine = True positions.append((x, y)) # Calculate end-game condition self.end_game_n = (self.b_size * self.b_size) - (self.n_mines + 1) return positions With mines in position, we can now calculate the 'adjacency' number for each position — simply the number of mines in the immediate vicinity, using a 3x3 grid around the given point. The custom function get_surrounding simply returns those positions around a given x and y location. We count the number of these that is a mine is_mine == True and store. Pre-calculating the adjacent counts in this way helps simplify the reveal logic later. def _reset_calculate_adjacency(self): def get_adjacency_n(x, y): positions = self.get_surrounding(x, y) return sum(1 for w in positions if w.is_mine) # Add adjacencies to the positions for x in range(0, self.b_size): for y in range(0, self.b_size): w = self.grid.itemAtPosition(y, x).widget() w.adjacent_n = get_adjacency_n(x, y) A starting marker is used to ensure that the first move is always valid. This is implemented as a brute force search through the grid space, effectively trying random positions until we find a position which is not a mine. Since we don't know how many attempts this will take, we need to wrap it in an continuous loop. Once that location is found, we mark it as the start location and then trigger the exploration of all surrounding positions. We break out of the loop, and reset the ready status. def _reset_add_starting_marker(self): # Place starting marker. # Set initial status (needed for .click to function) self.update_status(STATUS_READY) while True: x, y = random.randint(0, self.b_size - 1), random.randint(0, self.b_size - 1) w = self.grid.itemAtPosition(y, x).widget() # We don't want to start on a mine. if not w.is_mine: w.is_start = True w.is_revealed = True w.update() # Reveal all positions around this, if they are not mines either. for w in self.get_surrounding(x, y): if not w.is_mine: w.click() break # Reset status to ready following initial clicks. self.update_status(STATUS_READY) Position Tiles The game is structure game so that individual tile positions hold their own state information. This means that Pos tiles are able to handle their own game logic. Since the Pos class is relatively complex, it is broken down here to a few parts, which are discussed in turn. The initial setup __init__ block is simple, accepting an x and y position and storing it on the object. Pos positions never change once created. To complete setup the .reset() function is called which resets all object attributes back to default, zero values. This flags the mine as not the start position, not a mine, not revealed and not flagged. We also reset the adjacent count. class Pos(QWidget): expandable = pyqtSignal(int,int) revealed = pyqtSignal(object) clicked = pyqtSignal() def __init__(self, x, y, *args, **kwargs): super(Pos, self).__init__(*args, **kwargs) self.setFixedSize(QSize(20, 20)) self.x = x self.y = y self.reset() def reset(self): self.is_start = False self.is_mine = False self.adjacent_n = 0 self.is_revealed = False self.is_flagged = False self.update() Gameplay is centered around mouse interactions with the tiles in the playfield, so detecting and reacting to mouse clicks is central. In Qt we catch mouse clicks by detecting the mouseReleaseEvent. To do this for our custom Pos widget we define a handler on the class. This receives QMouseEvent with the information containing what happened. In this case we are only interested in whether the mouse release occurred from the left or the right mouse button. For a left mouse click we check whether the tile is flagged or already revealed. If it is either, we ignore the click — making flagged tiles 'safe', unable to be click by accident. If the tile is not flagged we simply initiation the .click() method (see later). For a right mouse click, on tiles which are not revealed, we call our .toggle_flag() method to toggle a flag on and off. def mouseReleaseEvent(self, e): if (e.button() == Qt.RightButton and not self.is_revealed): self.toggle_flag() elif (e.button() == Qt.LeftButton): # Block clicking on flagged mines. if not self.is_flagged and not self.is_revealed: self.click() The methods called by the mouseReleaseEvent handler are defined below. The .toggle_flag handler simply sets .is_flagged to the inverse of itself ( True becomes False, False becomes True) having the effect of toggling it on and off. Note that we have to call .update() to force a redraw having changed the state. We also emit our custom .clicked signal, which is used to start the timer — because placing a flag should also count as starting, not just revealing a square. The .click() method handles a left mouse click, and in turn triggers the reveal of the square. If the number of adjacent mines to this Pos is zero, we trigger the .expandable signal to begin the process of auto-expanding the region explored (see later). Finally, we again emit .clicked to signal the start of the game. Finally, the .reveal() method checks whether the tile is already revealed, and if not sets .is_revealed to True. Again we call .update() to trigger a repaint of the widget. The optional emit of the .revealed signal is used only for the endgame full-map reveal. Because each reveal triggers a further lookup to find what tiles are also revealable, revealing the entire map would create a large number of redundant callbacks. By suppressing the signal here we avoid that. def toggle_flag(self): self.is_flagged = not self.is_flagged self.update() self.clicked.emit() def click(self): self.reveal() if self.adjacent_n == 0: self.expandable.emit(self.x, self.y) self.clicked.emit() def reveal(self, emit=True): if not self.is_revealed: self.is_revealed = True self.update() if emit: self.revealed.emit(self) Finally, we define a custom paintEvent method for our Pos widget to handle the display of the current position state. As described in [chapter] to perform custom paint over a widget canvas we take a QPainter and the event.rect() which provides the boundaries in which we are to draw — in this case the outer border of the Pos widget. Revealed tiles are drawn differently depending on whether the tile is a start position, bomb or empty space. The first two are represented by icons of a rocket and bomb respectively. These are drawn into the tile QRect using .drawPixmap. Note we need to convert the QImage constants to pixmaps, by passing through QPixmap by passing. You might think "why not just store these as QPixmap objects since that's what we're using? Unfortunately you can't create QPixmap objects before your QApplication is up and running. For empty positions (not rockets, not bombs) we optionally show the adjacency number if it is larger than zero. To draw text onto our QPainter we use .drawText() passing in the QRect, alignment flags and the number to draw as a string. We've defined a standard color for each number (stored in NUM_COLORS) for usability. For tiles that are not revealed we draw a tile, by filling a rectangle with light gray and draw a 1 pixel border of darker grey. If .is_flagged is set, we also draw a flag icon over the top of the tile using drawPixmap and the tile QRect. def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) r = event.rect() if self.is_revealed: if self.is_start: p.drawPixmap(r, QPixmap(IMG_START)) elif self.is_mine: p.drawPixmap(r, QPixmap(IMG_BOMB)) elif self.adjacent_n > 0: pen = QPen(NUM_COLORS[self.adjacent_n]) p.setPen(pen) f = p.font() f.setBold(True) p.setFont(f) p.drawText(r, Qt.AlignHCenter | Qt.AlignVCenter, str(self.adjacent_n)) else: p.fillRect(r, QBrush(Qt.lightGray)) pen = QPen(Qt.gray) pen.setWidth(1) p.setPen(pen) p.drawRect(r) if self.is_flagged: p.drawPixmap(r, QPixmap(IMG_FLAG)) Mechanics We commonly need to get all tiles surrounding a given point, so we have a custom function for that purpose. It simple iterates across a 3x3 grid around the point, with a check to ensure we do not go out of bounds on the grid edges ( 0 ≥ x ≤ self.b_size). The returned list contains a Pos widget from each surrounding location. def get_surrounding(self, x, y): positions = [] for xi in range(max(0, x - 1), min(x + 2, self.b_size)): for yi in range(max(0, y - 1), min(y + 2, self.b_size)): if not (xi == x and yi == y): positions.append( self.grid.itemAtPosition(yi, xi).widget() ) return positions The expand_reveal method is triggered in response to a click on a tile with zero adjacent mines. In this case we want to expand the area around the click to any spaces which also have zero adjacent mines, and also reveal any squares around the border of that expanded area (which aren't mines). We start with a list to_expand containing the positions to check on the next iteration, a list to_reveal containing the tile widgets to reveal, and a flag any_added to determine when to exit the loop. The loop stops the first time no new widgets are added to to_reveal. Inside the loop we reset any_added to False, and empty the to_expand list, keeping a temporary store in l for iterating over. For each x and y location we get the 8 surrounding widgets. If any of these widgets is not a mine, and is not already in the to_reveal list we add it. This ensures that the edges of the expanded area are all revealed. If the position has no adjacent mines, we append the coordinates onto to_expand to be checked on the next iteration. By adding any non-mine tiles to to_reveal, and only expanding tiles that are not already in to_reveal, we ensure that we won't visit a tile more than once. def expand_reveal(self, x, y): """ Iterate outwards from the initial point, adding new locations to the queue. This allows us to expand all in a single go, rather than relying on multiple callbacks. """ to_expand = [(x,y)] to_reveal = [] any_added = True while any_added: any_added = False to_expand, l = [], to_expand for x, y in l: positions = self.get_surrounding(x, y) for w in positions: if not w.is_mine and w not in to_reveal: to_reveal.append(w) if w.adjacent_n == 0: to_expand.append((w.x,w.y)) any_added = True # Iterate an reveal all the positions we have found. for w in to_reveal: w.reveal() Endgames Endgame states are detected during the reveal process following a click on a title. There are two possible outcomes — - Tile is a mine, game over. - Tile is not a mine, decrement the self.end_game_n. This continues until self.end_game_n reaches zero, which triggers the win game process by calling either game_over or game_won. Success/failure is triggered by revealing the map and setting the relevant status, in both cases. def on_reveal(self, w): if w.is_mine: self.game_over() else: self.end_game_n -= 1 # decrement remaining empty spaces if self.end_game_n == 0: self.game_won() def game_over(self): self.reveal_map() self.update_status(STATUS_FAILED) def game_won(self): self.reveal_map() self.update_status(STATUS_SUCCESS) if __name__ == '__main__': app = QApplication([]) window = MainWindow() app.exec_() Further ideas If you want to have a go at expanding Moonsweeper, here are a few ideas — - Allow the player to take their own first turn. Try postponing the calculation of mine positions til after the user first clicks, and then generate positions until you get a miss. - Add power-ups, e.g. a scanner to reveal a certain area of the board automatically. - Let the hidden B'ugs move around between each turn. Keep a list of free-unrevealed positions, and allow the B'ugs to move into them. You'll need to recalculate the adjacencies after each click. The full source code for Moonsweeper is available, and pull-requests are welcome.
https://www.twobitarcade.net/article/minesweeper-python-desktop-pyqt/
CC-MAIN-2019-09
refinedweb
2,901
68.47
This is the mail archive of the pthreads-win32@sourceware.org mailing list for the pthreas-win32 project. Why is this an issue? If some code wants to have treads comperable/hashable, they can roll their own class/struct that wraps pthread_t and provides whatever functionality it wants. In fact, for the simple requirment of isNull, compare, and hash, just use a (pthread_t *) for a thread handle! - Igor Lubashev -----Original Message----- From: Alexander Terekhov [TEREKHOV@de.ibm.com] Received: Saturday, 05 Feb 2011, 10:18am To: Ross Johnson [Ross.Johnson@homemail.com.au] CC: pthreads-win32@sourceware.org [pthreads-win32@sourceware.org] Subject: Re: Compilation issue with pthreads-win32 Ross Johnson <Ross.Johnson@homemail.com.au> wrote: [...] >. Mainframe UNIX also uses a struct. Unfortunately pthreads do not provide standard pthread_null/compare/hash interfaces, see but you might want to add _np() functions... regards, alexander. Ross Johnson <Ross.Johnson@homemail.com.au>@sourceware.org on 05.02.2011 09:51:35 Sent by: pthreads-win32-owner@sourceware.org To: pthreads-win32@sourceware.org cc: Subject: Re: Compilation issue with pthreads-win32 Hi Claude, Glad you found the library useful and thankyou for the feedback.. IIRC Solaris does not use a pointer but uses an int type that sequences to provide a unique id for each new thread in a process. I have no idea how Solaris maps this counting value to thread storage when needed nor how it does it efficiently when the set of living threads becomes sparse, but they do it. Linux and BSD use pointers which are not unique if the thread exits and its memory has been allocated to a new pthread_t, or any other type for that matter. I know from comments in their code that the BSD developers have thought about this issue and the possibility of changing away from a pointer type at some point. Having done so ourselves we no longer get questions about the many complex problems that arise when using pointers. We have had a few questions like yours to do with porting, all three of which have been fairly easily solved AFAIK. I take the blame for the decision but I thought it was better to provide application reliability, predictability etc. for everyone and accept the occasional but fixable compiler breakage. But the crux of it is this: the POSIX (and now the SUSv3) standard allows pthread_t to be scalar or non-scalar and in making it non-scalar in pthreads-win we are not just taking advantage of a loophole in the standard; the standard has deliberately not defined pthread_t so that implementations can define it how they see fit. The notes within the standard actually suggest defining pthread_t as a struct exactly as it is defined here, to allow inclusion of a 'sequence' counter to render the handle unique over time. But back to your code: What would happen if you did not set SSD->id = 0, i.e. just leave it unitialised? I'm curious because your code appears not to attempt a comparison of the value with 0, e.g. "if (SSD->id == 0) ..." otherwise you would see a compiler error attempting to compare a struct. If you can't avoid initialising a pthread_t variable, I would suggest doing it by declaring a special pthread_t constant with the value you want (0 in this case), e.g.: typedef union { pthread_t t; int filler[sizeof(pthread_t)/sizeof(int)]; } init_t; const init_t u_init = {.filler = {0}}; # Relies on having a C99 compliant compiler Then you can do this to initialise: SSD->id = u_init.t; Note that the initialisation of the array u_init.filler only sets the first element to 0 explicitly and the remaining elements, if any, are set to 0 by default. Since you don't really know how many elements there are you should probably avoid trying to initialise more than one element, i.e. don't do " = {.filler = {0 , 0}};". This method means you don't need to break the opacity of the pthread_t and it should also be portable. Also for portability, you should only ever use the pthread_equal() function to compare pthread_t types, e.g.: if (pthread_equal(SSD->id, u_init.t) { ... } And one more thing that I can mention. In pthreads-win32 you can call pthread_kill(threadID, 0) to check if threadID is valid, i.e. refers to a living thread. It will return ESRCH if invalid. However this is not portable and therefore not safe but can sometimes be better than nothing. It probably also works for Solaris and works here because we can guarantee that threadID is a unique value within the process scope and we can determine all of the previous values of living and dead threadIDs. (This is not absolutely strictly true of course but is true within the practical lifetimes of processes.) FAQ ===. On 5/02/2011 1:35 AM, Claude LALYRE wrote: > Hi Ross, > > I would like to thank a lot your pthreads-win32 team for the great work they achieved. > This week, I was in a situation of migrating UNIX source code to Windows environment. > And helpfully with your project phreads-win32 that task was easily possible. > > But I encountered some compilation issues. And I have had to declare some missing > typedef and macros in my code, picked from cygwin header files. And surprisingly > it was enough for my code being able to compile. > > So as it was just a small issue, I thought I should give you my point of view and > the little declarations I made. I think that it should be easily integrated in your > source code. Just have a look at the posix.h attached file. > > Another point is concerning the declaration of your type "pthread_t". In all UNIX > platforms this is formerly a pointer, but in your Windows implementation this > is a struct object. The issue is that I was given a source file containing a SSD > object containing a field "id" of type pthread_t. > > struct SSD { > pthread_t id; > int dummy; > } > > And somewhere else in the code they gave me, I have this > SSD->id = 0; > > And that line of code was not accepted by cl.exe (Windows) compiler ! > So I face the situation by adding this ugly fix > > #ifdef WIN32 > SSD->id.p = 0 > #else /* WIN32 */ > SSD->id = 0; > #endif /* WIN32 */ > > So I am sorry to tell you this about the most basic type of your pthreads-win32 library, > but it would have been great to keep the pthread_t type as a pointer rather than a struct > object. However, as I managed to fix this situation its a tiny issue, an > enhancement suggestion rather than a bug... > > Thank a lot for all youy great job ! > > Claude. > > > >
http://sourceware.org/ml/pthreads-win32/2011/msg00002.html
CC-MAIN-2018-30
refinedweb
1,115
72.76
On 08/02/2012 01:37 PM, Daniel P. Berrange wrote: On Thu, Aug 02, 2012 at 01:18:12PM +0200, Wido den Hollander wrote:On 07/08/2012 07:51 PM, Bruno Haible wrote:Daniel P. Berrange wrote:If its better to just do it in libvirt config.h, then we can do that tooYes, doing '#define foo libvirt_foo' in config.h is the preferred way of achieving a namespace clean shared library. There are two ways to generate these #defines: 1) You collect manually, on various systems, the set of symbols that you don't want to clash with symbols from other shared libraries. You need to do this on various systems, because gnulib may define functions 'rpl_fflush' or 'dprintf' on some systems and not on others. 2) You collect, from a set of header files, the set of symbols that you want to have exported, and process all other symbols with '#define foo libvirt_foo' This approach is more robust, but requires to compile all *.o files twice: Once with the initial settings (no #define), and once for real. This approach is implemented in libunistring. Look at the config.h rule in this Makefile.am [1]. There are two auxiliary scripts: 'declared.sh' [2] extracts the symbols from a .h file (assuming a particular coding style). 'exported.sh' [3] extracts te symbols of a .o file.I don't want to rush anything, but I see that libvirt 0.10 will be coming out soon and I don't think this has been corrected? Right now this means that libvirt is not usable on Ubuntu 12.04 systems when you want to use the secrets of libvirt. Is it feasible to have this fixed before 0.10 comes out?Try applying this patch to your source tree diff --git a/configure.ac b/configure.ac index 6b189db..4f906bb 100644 --- a/configure.ac +++ b/configure.ac @@ -2876,6 +2876,10 @@ test "x$lv_cv_static_analysis" = xyes && t=1 AC_DEFINE_UNQUOTED([STATIC_ANALYSIS], [$t], [Define to 1 when performing static analysis.]) +AC_DEFINE_UNQUOTED([isbase64],[gnulib_isbase64],[Hack to avoid symbol clash]) +AC_DEFINE_UNQUOTED([base64_encode],[gnulib_base64_encode],[Hack to avoid symbol clash]) +AC_DEFINE_UNQUOTED([base64_encode_alloc],[gnulib_base64_encode_alloc],[Hack to avoid symbol clash]) + AC_OUTPUT(Makefile src/Makefile include/Makefile docs/Makefile \ docs/schemas/Makefile \ gnulib/lib/Makefile \ Yes, that works for me. The secrets are working on Ubuntu 12.04. Thanks, Wido Regards, Daniel
https://www.redhat.com/archives/libvir-list/2012-August/msg00096.html
CC-MAIN-2015-18
refinedweb
392
68.16
Writing Swifty Code El gato negro de Juan toma leche. (es) John’s black cat drinks milk. (en) O gato preto de João toma leite. (pt) Languages are different. Some of them look familiar. Some of them share the same ideas of syntax and grammar. A word by word translation of the first sentence would feel strange but it will convey the same meaning. It might take you a little while to parse it down and understand it. The cat black of John drinks milk. People who speak a second language incorporate these idiosyncrasies into their accent. Something similar happens when learning programming languages. If you have been a C# coder all your life and now you’re learning Swift; chances are you’ll be writing Swift code with a C# accent. So, let’s try to reduce the accent! 👨🏻 Let your var be declared correctly In Swift, you can refer to types via mutable and immutable references. For mutable types, you’d use var when declaring variables; for immutable, let. Mutability Other programming languages call immutable variables constants but that’s an incomplete description of what let does in Swift. As the example below shows, an immutable reference to a class instance will allow modifying the internals of the instance but not the actual instance reference. However, when using structures instead of classes, let feels more restrictive. In Swift, types are either value types or reference types. What other languages call primitives Swift implements them as structures. A string, an integer, and a boolean are structures in Swift. let number = 42 number = 46 // Doesn't compile // MARK: Classes class Person { var name = “” } let person = Person() person.name = "Carlos" person.name = "Madrigal" // Compiles // Create another person and assign it to the same variable person = Person() // Doesn't compile // MARK: Structures struct Dog { var name = "" } let dog = Dog() dog.name = "Chester" // Doesn't compile If you’re coming from Objective C, you’re used to having pairs of classes for immutable and mutable versions of a concept. For example, NSString and NSMutableString are the immutable and mutable versions of a text string. However, in Objective C you could still have a const pointer to a NSMutableString instance. That means you can change the internals of the string but you cannot assign something else to the constant reference pointer. In Swift, String is a structure and follows structure mutability semantics. In fact, Swift is crazy about structures. If you look into the Swift Standard Library you’ll notice there’s only one class, a bunch of protocols, and a bunch of structures. If you’re not aware of the difference in immutable semantics between class and structure types, you’ll get confused because there’s a high chance you’ll end up using structures. Initialization Another misconception is people think let statements require an initialization right away. When these people can’t provide an initial value, they flip the let to a var. // Code smell var value: Int? if someCondition value = 6 else value = 9 // Use let instead: perfectly valid! Also, avoid the optional! let value: Int if someCondition value = 6 else value = 9 The idea here is that let demands only one initialization but it doesn’t need to be on the same line. This is particularly true for properties. Sometimes, some coders declare everything using var because they will assign a value in init(). class PersonaView: UIView { var imageView: UIImageView? required init() { imageView = UIImageView(image: UIImage(named: "face")!) } required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") } } That’s a code-smell. After the initialization imageView is practically a constant — i.e., once you get the initial reference and set it up you won’t assign a whole new reference to the same variable. Every access to that reference needs to be handled with care because it’s an optional. Developers consuming this code could do something like assigning a new reference to the property and that can cause funky things inside your class like never getting events from the image view and memory leaks because your code might be listening to some other image view’s events. let view = PersonaView() view.imageView = UIImageView(image: UIImage(named: "stupid")) But all of that easily goes away when you use let instead. class PersonaView: UIView { let imageView: UIImageView required init() { // This is the place to initialize your variables imageView = UIImageView(image: UIImage(named: "face")) } required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") } } let view = PersonaView() view.imageView = anotherImageView // Doesn't compile Now that we’re talking about initializers, if you need to call an initializer on super, make sure you assign all your immutable variables before calling super or self. You can use self when disambiguating between a property and a parameter. class PersonaView: UIView { let imageView: UIImageView let actionButton: UIButton let compact: Bool required init(compact: Bool) { // This is the place to initialize your variables imageView = UIImageView(image: UIImage(named: "face")!) actionButton = UIButton(type: .custom) // You can use self in cases like this self.compact = compact super.init(frame: CGRect.zero) // After calling super.init or self.init, then // you can use self. actionButton.addTarget(self, action: #selector(tapHandler), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") } func tapHandler() { } } Understanding how to use let should yield clearer code because now mutability semantics really represent your intentions as a Swift coder. It also helps you avoiding optionals but we’ll talk more about them in the next section. The private(set) code smell Sometimes, C# developers use private(set) for properties with public getters but private setters. Most of the times though, the private setter is only used in the constructor. If that’s the case you’re implementing in Swift, you should stop using private(set) and use let instead. You’re going to increase code simplicity and readability with simple lets and preserve the semantics. class CSharpEmployee { private(set) var id: String? private(set) var name: String? init(id: String?, name: String?) { // Only place where these properties are set self.id = id self.name = name } override func description() -> String { return "\(id): \(name)" } } class SwiftyEmployee { let id: String? let name: String? init(id: String?, name: String?) { self.id = id self.name = name } override func description() -> String { return "\(id): \(name)" } } Recommendation Swift loves the principle of least privilege. You can feel it when you learn its syntax. As a rule of thumb, start with let. Flip to var only when you want mutability. Optional pain Swift provides a superb support for optional and non-optional variables. When used correctly, they are powerful, expressive, and safe. The problem, though, is that this concept looks familiar to nullable types in other programming languages. For example, for C# programmers, a nullable is a type that besides holding a value within a specific range, it can also hold null. A Nullable<int> or int? can hold any integer in the Int32 value range plus null. Nullable types are meant to represent primitive value types in a context like databases where sometimes you need to represent the absence of a value. Cool. We got the C# refresher down. However, Swift optionals are not the same. In Swift, an optional is a variable that can hold nil as a value. Any type can be optional. You can have an optional value type like in C#. You can also have an optional reference type. The power is not about having references that can have nil; the power resides on having references that won’t accept nil as a value. For example, declaring a variable as a non-optional will make the compiler work for you. var imageView: UIImageView = nil // Doesn't compile In this case, UIImageView is a class type. In other programming languages, reference type variables always accept null and there’s no way to enforce not accepting null. Let that concept sink in. Have you ever thought of how many lines of code you need to write just to check your arguments are not nil? Being a C# or Objective C programmer you must be able to recall code snippets like the following: // C# void someMethod(string paramA, string paramB) { if (paramA == null) { throw new ArgumentNullException("paramA") } if (paramB == null) { throw new ArgumentNullException("paramB") } // Do something } // Objective C - (void)someMethodWithParamA:(NSString *) C# is more verbose but you have to do something similar in both languages. Over and over again you have to check you have valid references before you start working with them. The same in Swift looks like this: func someMethod(paramA: String, paramB: String) { // Do something } There’s no need to check for nullability. Period. Having said that, a common code-smell is to have lots of variable or parameter declarations as optional or optional implicit. var imageView: UIImageView! var dataSource: DataSource? In Swift, optionals explicitly say you are going to manage nullability checks — a.k.a., if-let checks. For optionals, it’s expected to see this: if let imageView = imageView { // Do something with the image view } You can also do this at your own risk: let size = imageView?.image?.size // ???: What's the type of `size`? `CGSize` or `CGSize?`? let width = size?.width // ???: What's the type of `width`? `CGFloat` or `CGFloat?` It happens that newbie coders don’t learn this Swift concept and get frustrated with the compiler. They turn to StackOverflow to find someone saying “use ! instead of ?”. let size = imageView!.image!.size // Read ! as "it has the potential to crash--and it will" let width = size.width You should use implicit unwrapping with a lot of care. If you happen to see lots of question and exclamation marks in your code it’s because your code smells too much 💩. Consider refactoring it. Optionals in view controllers Are you ready to stop using optionals — implicit or not? Cool. I find myself not following my own recommendation when coding view controllers. View controllers are not necessarily immediately displayed. You can new up a view controller reference and keep it around. Then some time later the user does something that causes that view controller to display its view. View controllers load their views lazily. For that reason, often times you end up setting up your UI controls in viewDidLoad(). With lazy loading, you need to have the references to the UI controls optional. The view load pattern in a view controller is stable. Once viewDidLoad() executes you should have access to the UI controls you need. Consider using implicit optional for those references to avoid nullability checking. On the other hand, you could opt to use immutable non-optional references and new everything up in the initializer. The disadvantage to this approach would be memory consumption. Recommendation Again with the principle of least privilege: use non-optional whenever possible. In fact, combine both recommendations, use non-optional immutable variables whenever possible and open up as needed. Initializer Patterns When creating view controllers programmatically you often end up doing this: required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } First of all, it’s totally fine. Let’s try to understand why. - In Swift, an initializer must initialize its own non-optional properties before calling it’s superclass’s designated initializer. - A designated initializer is the main initializer in a type. A designated initializer calls an initializer from its immediate superclass. - On the other hand, a convenience initializer is a utility one; it makes initialization easier. A convenience initializer calls another initializer from the same class that eventually calls a designated initializer. - A required initializer is an initializer that needs to be overridden in subclasses. You don’t include the override keyword when overriding a required initializer. - A failable initializer is one that can return nil instead of an actual instance. In this case, the code shown above, is overriding a required failable initializer. Since your code doesn’t use storyboards, it’s okay to use fatalError() to crash the app. If you want to use storyboards then you would need to refactor that code. Migrating to Swift 3 You should read about the details on migrating your projects to Swift 3. Here I will summarize the most obvious one: naming conventions. Swift is the clearest language I’ve ever worked with. Part of that clarity comes with the new naming guidelines. You should read them over and over again. After you read them, you should recognize the following paragraph: Clarity at point of use means clarity when consuming your code. We as developers spend a lot of time reading code compared to the time we spend writing code. We don’t want to repeat the PERL experience where you encrypt as you type🔒. The first thing you’ll notice is that in Swift 3 the label for the first argument is now required. // Swift 2.3 func distanceFromPoint(point: Point, to: Point) distanceFromPoint(p1, to: p2) // Swift 3 distanceFromPoint(point: p1, to: p2) Notice that the Swift 3 version now looks redundant: “distance from point point p1 to p2”. We should rename it to something like: // Swift 3 func distance(fromPoint: Point, to: Point) distance(fromPoint: p1, to: p2) This renamed version reads as “distance from point p1 to p2”. It reads way better. Xcode comes with a conversion tool that doesn’t do a terrific job. It might get your code close to compiling but with awful naming conventions. The tool might do something like this: func distanceFromPoint(_ p1: Point, p2: Point) The underscore makes the first label implicit — like in Swift 2.3. That code compiles but it doesn’t follow Swift 3 naming conventions. You can leave it there but it looks lazy, incomplete and foreign. Again, you should read the API Design Guidelines to understand the changes. Every other Swift 3 related change cascades from that. The Swift Standard Library changed, all the kits changed as well. Since everything changed, now you have to adjust your code to talk to the new names of the APIs you were using. When in doubt, look at the Swift Standard Library or UIKit. Check how native language speakers speak the language and try to imitate them in your code. Some code-smells I often see are: - I bet coders are lazy when I see class names ending in -Manager, -Helper, and -Utils. These suffixes often show coders didn’t want to spend time thinking where to place code. -Manager classes end up being god classes doing everything or a substitute to have almost-global variables. -Helper classes could be implemented as categories or extensions. -Utils classes often end up doing work across tiers — a.k.a., spaghetti code. In fact, reading -Helper, -Manager, and -Utils every few lines gets tiring too. - There’s no better indicator of having an accent in Objective C or Swift than having getter methods that have the get prefix. Pay attention to UIKit for example, you just don’t see the get idiom like you do in C# or any other language. In Objective C and Swift code you omit get like in viewController.subviews or view.layers. - In Objective C and Swift, acronyms and initialisms use upper casing. Think of NSURL not NSUrl. It should be JSON not Json, you’re thinking C# there. - Avoid using self. If you use self for autocompletion, please stop. In Swift, you use lots of blocks. Inside those blocks you have to use self when referring to instance variables. That’s another way Swift is screaming at you “you’re creating a closure; check you don’t have cyclic references!”. If you see self everywhere — because of your laziness — then you’re probably going to miss possible cyclic references and probably won’t declare self as weak; which in turn will cause memory leaks. Those bugs 🐞 are very hard to find and fix; help your self by not writing self. - Avoid redundancy. If your project name is MyAwesomeProject and you have a MyAwesomeProjectManager class that uses a MyAwesomeProjectSettings class that will become very tiring very soon. Swift projects are namespaced. So, if you call your project MyAwesomeProject call the other classes Manager and Settings. In fact, read my point about -Manager classes and see if you can rename it. You want to make it clear at point of use; if everything is a manager then you’re not helping. Another form of redundancy is when you leave template code in your code, like the following snippet. Remove it. Make your code clearer. func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } Scope Access Modifiers Finally, I want to talk about scope access modifiers because they changed in Swift 3. If you had private in Swift 2.3 you’ll see them as fileprivate in Swift 3. What used to be public now is open. The semantics stayed the same but the new words better represent those semantics. In Swift 2.3 private meant file private and public meant public and open for subclassing. Swift 3 access modifiers are more precise; now private really means private and public means public but closed for subclassing. Conclusion Swift syntax accomplishes something you rarely see in other programming languages. Swift talks to you and it talks to you all the time. For example, the question mark is how Swift tells you “you may not have a value here”. The exclamation point is the way Swift screams at you: “this is dangerous and may crash, proceed at your own risk”. There are keywords like escaping, unsafe, open, fileprivate that help us achieve clarity at point of use. If you want to be a better coder, consider having a second look at the principle of least privilege and learn how to hide your internals; you have a good set of scope access and mutability modifiers in Swift. Also, check out the Single Responsibility Principle to avoid creating god methods and classes and kill all your -Manager, -Helper, and -Utils classes — use extensions more, they’re meant for cases like those. Follow the Don’t Repeat Yourself — a.k.a., DRY — principle to avoid code duplication. And with all this new knowledge Keep It Silly Simple — a.k.a., KISS — and avoid mutable optionals whenever possible and, with them, avoid lots of nil checks. Follow naming conventions, that’s the best form of code documentation because the documentation evolves as you evolve your code. Spend some time thinking about the names you pick; they must clearly represent your types, variables, and methods. I’m not a native English speaker. I speak Spanish; Mexican Spanish. In fact, I’m from the north of Mexico and my accent is not the same as Mexico City’s. When I meet people from Mexico City they immediately notice my accent but the funny thing is they think they don’t have one. It’s not until I mimic their accent when they realize they do have one. The same happens in every natural language and I bet it happens for computer languages too but we just don’t point out the differences. I’m not saying that speaking with an accent is a bad thing but it sure does feel foreign when your accent is different from the rest. Coding with an accent does feel foreign as well and maybe, by pointing out the accent, we can minimize it. Computer languages are super easy in comparison to natural languages. I bet you can remove your computer language accent with minimal effort and, if not, these insights might help you become a better Swift coder. ☺️ ¡Gracias por leer! Carlos Madrigal
https://medium.com/@madwaro/writing-swifty-code-17988a62af24
CC-MAIN-2017-13
refinedweb
3,248
66.23
Bootstrapping a React TypeScript project with Parcel Lea Rosema Updated on ・1 min read With the Parcel bundler, you can bootstrap a React TypeScript project with (almost) zero configuration. First, create a folder, cd into it, initialize NPM, install parcel and your React dependencies: mkdir react-number-game cd react-number-game npm init -y npm i parcel-bundler --save-dev npm i react react-dom @types/react @types/react-dom --save mkdir src Then, open your favorite code editor. Create a index.html file in your src directory. Modern editors like VSCode provide Emmet completion features. You can just enter a !, press the tab key and you get a basic html structure. Inside the body, add a root div element and a script tag with the reference to your entry index.tsx file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http- <title>React TypeScript App</title> </head> <body> <div id="root"></div> <script src="./index.tsx"></script> </body> </html> Your minimal index.tsx file could look like this. There is no special TypeScript feature in there yet: import * as React from 'react' import { Component } from 'react' import { render } from 'react-dom' // import './index.css' class App extends Component { render() { return (<h1>Hello World!</h1>) } } render(<App />, document.getElementById('root')) Finally, add a start command to your package.json: { "name": "react-number-game", "version": "1.0.0", "description": "A number game in React", "scripts": { "start": "parcel src/index.html", }, "author": "Lea Rosema", "license": "MIT", "devDependencies": { // ... }, "dependencies": { // ... } } Then, you can start your application via npm start. Additional project configuration Production Build Add a build command to your package.json and run npm run build: { "scripts": { "build": "parcel build src/index.html", } } Deployment If you are using GitHub, you can easily deploy to gh-pages using the gh-pages npm package. I also use rimraf package to clean up the dist folder before building: npm i rimraf gh-pages -D Add the following scripts to your package.json: { "scripts": { "build": "parcel build --public-url . src/index.html", "clean": "rimraf dist/index.html dist/src.*.css dist/src.*.js dist/src.*.map", "predeploy": "npm run clean -s && npm run build -s", "deploy": "gh-pages -d dist" } } The --public-url . parameter in the build step is important, because your project is deployed at and the script is included with a slash by default (eg /src.0123abcdef.js). That would result in a 404 error. TypeScript You might need additional TypeScript configuration. Though, the minimal example works without any configuration. You can generate a tsconfig.json via node_modules/.bin/tsc --init. A nice minimal tsconfig.json could look like this: { "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true, "jsx": "react" } } Autoprefixer Install autoprefixer via npm i autoprefixer -D and add a .postcssrc: { "plugins": { "autoprefixer": { "grid": true } } } SCSS Just add a index.scss file to your project and import it into your entry index.tsx. Parcel automatically installs the node-sass precompiler for you. .gitignore Parcel builds the dist files in the related output folders dist and also has a cache folder .cache. I would recommend to add them to your .gitignore file: dist/index.html dist/src.*.js dist/src.*.css dist/src.*.map .cache Result See the resulting code at my react-number-game repository on GitHub. Let's talk about an unnecessary but popular Vue plugin Do we really need a plugin for everything? Wow, it's much easier to get started using typescript with React than I thought! I haven't tried this yet, but I know that my colleague was having to deal with really long compile times with this React-TypeScript project. Coming from Angular, I'm used to a couple seconds of live refresh time, but I just see him sitting there ready to pull his hair out and his dev time seriously cut. Do you experience any such phenomena with Parcel? Thanks. That's what i was looking for recently. Nice Just a thought Lea, but you may want to add the tag "Parcel" to you blog post. I follow parcel posts and just about missed this one. ;) Just a suggestion Thank you! I added the tag :) Parcel is fast and "zero-config" bundler. Thanks for the post Lea. Did you try parcel-plugin-typescript?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/terabaud/bootstrapping-a-react-typescript-project-with-parcel-4oia
CC-MAIN-2019-35
refinedweb
721
59.7
Is there an easy way to find the area of a shape?harrda Jul 15, 2006 9:32 AM I'm drawing a spyder chart using scores in an XML file. I use the drawing methods to connect a bunch of dots along some spokes. Once the shape is drawn, I'd like to find the area. I could use trig and get the area of each triangular wedge of the shape, but I'd like to steer clear of that if possible. Is there a simpler way to do this? thanks in advance thanks in advance This content has been marked as final. Show 14 replies 1. Re: Is there an easy way to find the area of a shape?Rothrock Jul 15, 2006 10:54 AM (in response to harrda)You are so funny. "Is there a simpler way to do this?" Not likely. All you have to do is integrate over the space – not easier. If your area is made up of triangles it is easy to figure the area of each triangle using Hero/Heron formula. Just make a nice little function that takes three points and figures the area. I don't know of any easier way to do it. Anybody else? kglad? 2. Re: Is there an easy way to find the area of a shape?Wolf_van_Ween Jul 15, 2006 1:25 PM (in response to harrda)If it were a movieClip you could use the Monte Carlo method: Generate a number of random coordinates (x,y) inside your stage boundaries and hit-test them with the movieClip. The percentage of positive hits times the stage size is the approximate area. The more coordinates you generate the better the approximation. 3. Re: Is there an easy way to find the area of a shape?Rothrock Jul 15, 2006 1:56 PM (in response to harrda)How fun is that! I hadn't thought of it, but a great approach. It does seem to take quite a few attempts to get a close approximation. 4. Re: Is there an easy way to find the area of a shape?Rothrock Jul 15, 2006 2:22 PM (in response to Rothrock)So I thought about it a bit. Instead of doing a monte carlo against the whole stage, just do it against the bounding box of the movieclip. That will require fewer iterations to get a good approximation. Here is what I came up with. 5. Re: Is there an easy way to find the area of a shape?Rothrock Jul 15, 2006 3:10 PM (in response to harrda)hmmmm not quite working. I tested it with a square movieclip. So every random x,y should return a positive for the hitTest. But I'm getting falses for some that hit right on the edges of the clip. It isn't a problem with the random, I don't think. I put the upper left corner of the square at 100,100. I then tested the hits: trace(clip2.hitTest(100, 100, true));<--returns false trace(clip2.hitTest(100, 101, true));<--returns false trace(clip2.hitTest(101, 100, true));<--returns true trace(clip2.hitTest(101, 101, true));<--returns true To my mind they should all return true – or at the very least the first three should give the same results. Very strange that it seems to be the x that makes it return the wrong answer on the low side. And I think it is y on the other side. Any ideas Wolf? 6. Re: Is there an easy way to find the area of a shape?blemmo Jul 16, 2006 4:15 AM (in response to harrda)The trig way shouldn't be too hard, and is probably the best here. However, reading about the Monte Carlo method, I guess you could also count the colored pixels to get the area. It would need Flash 8, but should be quite easy: -- import flash.display.BitmapData; var area:Number = 0; var bmp:BitmapData = new BitmapData(mc._width,mc._height); bmp.draw(mc); for(var i=0;i<bmp.width;i++){ for(var j=0;j<bmp.height;j++){ if(bmp.getPixel(i,j) == 0xFF0000){ area++; } } } delete bmp; trace("area = "+area); -- It assumes the chart is in an MC called 'mc' and drawn in red color. I don't know how accurate this method is; it seems to be not 100% exact. I tried for a rectangle, it gave me 12535, but the calculated area was 12687.39, so it's more than 150 pixels difference (in this case 1.2 %). Maybe that's enough for you. Otherwise, as already mentioned, the trig way is the most exact way. cheers, blemmo 7. Re: Is there an easy way to find the area of a shape?Wolf_van_Ween Jul 16, 2006 6:52 AM (in response to blemmo)Guys, this gets really interesting now. I've just opened this forum and am going to test this right away. Rothrock, of course, the bounding box gives a much faster approximation. I'll check whether the problem is with the random numbers generated or the way the hit test function works. blemmo, great idea. If it's monochrome, that must be the fastest way. I don't know how well actionScript is optimized -- are the loops translated into machine language loops and is the getPixel function call translated into inline memory access? But anyway, even with a very large bitmap that must be a lot less to do for the processor than let's say 100 hit tests. As for the error, do you have full pixel coordinates, and do you have anti-aliasing off? I could imagine that the "missing" red pixels are just not fully red??? 8. Re: Is there an easy way to find the area of a shape?blemmo Jul 16, 2006 7:38 AM (in response to Wolf_van_Ween)Hm, don't know if you can avoid anti-aliasing for MCs. The error seems to be related to the stroke around a shape, the position of the shape inside the MC and the dimensions of the shape. These are the results for a 100x100 square: - at 0,0 with a 1 pixel stroke: area = 10200 calc = 10201 - at 0,0 without a stroke: area = 10000 calc = 10000 - at 10,10 without a stroke: area = 8100 calc = 10000 - at 0,0 without stroke and dimension of 100.5x100.5: area = 10000 calc = 10100.25 (in this case, the sizes report as sqr: width=100.5 height=100.5 bmp: width=100 height=100 guess a bitmap can't have half pixels) It seems that the dimensions for the MC, where the square is positioned at 10,10, are 100x100 as well (not 110x110, as I would guess), so the bitmap is 100x100 as well, but it draws the MC beginning at its 0,0 point, so there should be 10 pix missing in width and height of the shape. So when there is no stroke and the shape is positioned at 0,0 inside its MC, it seems to be quite accurate. That is, for a rectangle, don't know if it's the same for other shapes. 9. Re: Is there an easy way to find the area of a shape?kglad Jul 16, 2006 7:40 AM (in response to Wolf_van_Ween)because for-loops and hitTest() execute so quickly there's no reason to use a monte carlo method to compute the area of a stage object. in fact, using Math.random() and 1/4 of the for-loops is probably more time-consuming than calculating the area exactly: 10. Re: Is there an easy way to find the area of a shape?Wolf_van_Ween Jul 16, 2006 8:30 AM (in response to harrda)Actually the Monte Carlo method does not require real random numbers. It's good enough if they are "random enough" for the problem, i.e. not creating a systematic error. In the case of the spider diagram for instance, you could just test every 10th point systematically (basically a mix between Rothrock's and kglad's function). Good enough for most uses and of course even faster than checking every point. By the way, using every 4th or 5th point with random numbers is indeed much too much. I would have said use 5%, max 10%. kglad, do you happen to know how hitTest works internally? Does it use some sort of bitmap lookup? But your solution is the best, of course. Logical, simple and clean. Rothrock, I've played round with your code, and the experience is equal to blemmo, the problem might stem from unclear rounding situation with stroke and fill. This might change with Flash 9 which finally has an integer data type. A circle of diameter 200 (real area: (200/2)^2 * pi = 31415.9 ... gives with no stroke: using kglad's "exact" method: 31468 using 10% "regular-random": 31320 using 5% random Monte Carlo: 31080-31780 (10 attempts) with a hairline stroke or with a 1 point stroke, but still in the same 200x200 bounding box, so (theoretically) it should all be the same area: using kglad's "exact" method: 31805 using 10% "regular-random": 31790 using 5% random Monte Carlo: 31500-32500 (10 attempts) with a 3 point stroke: using kglad's "exact" method: 32467 using 10% "regular-random": 32600 using 5% random Monte Carlo: 32046-32587 (10 attempts) So, harrda, pick your favourite :-) 11. Re: Is there an easy way to find the area of a shape?Rothrock Jul 16, 2006 8:37 AM (in response to harrda)D'oh! Of course. I had kinda started down that line, but then just didn't think it all the way through. Still a bit confused by the hitTest results I'm seeing. 12. Re: Is there an easy way to find the area of a shape?harrda Jul 17, 2006 6:54 AM (in response to kglad)Wow. I mean, really, these are some great answers. I was looking for something just slightly more complicated than "use the mc.getArea() method", but since that doesn't seem to exist yet, thanks very much for all the suggestions. I'm choosing kglad's method because I need an exact measure for comparing the areas of different spyder charts. thanks again all 13. Re: Is there an easy way to find the area of a shape?kglad Jul 17, 2006 7:34 AM (in response to harrda)you're welcome. you should be aware that the answer given by all these hitTest() methods may not agree with a mathmatical formula because of the way flash handles shapes. the answers should be close, but not really exact. 14. Re: Is there an easy way to find the area of a shape?Rothrock Jul 17, 2006 10:10 AM (in response to kglad)If they are triangles and you know the points, definitely use Hero's formula. Compare the answers from the following code.
https://forums.adobe.com/thread/111212
CC-MAIN-2018-39
refinedweb
1,834
82.14
NOTE This article is still awaiting review for correctness. Typeclasses such as Bifunctor are often expressed in terms of whether they are covariant or contravariant. While these terms may appear intimidating to the unfamiliar, they are a precise language for discussing these concepts, and once explained are relatively easy to understand. Furthermore, the related topics of positive and negative position can greatly simplify how you think about complex data structures. This topic also naturally leads into subtyping. This article is intended to give a developer-focused explanation of the terms without diving into the category theory behind them too much. For more information, please see the Wikipedia page on covariance and contravariance. The Functor typeclass: covariant functor Let's consider the following functions (made monomorphic for clarity): showInt :: Int -> String showInt = show floorInt :: Double -> Int floorInt = floor Now suppose that we have a value: maybeInt :: Maybe Int maybeInt = Just 5 We know Maybe is an instance of Functor, providing us with the following function: fmapMaybe :: (a -> b) -> Maybe a -> Maybe b fmapMaybe = fmap We can use fmapMaybe and showInt together to get a new, valid, well-typed value: maybeString :: Maybe String maybeString = fmapMaybe showInt maybeInt However, we can't do the same thing with floorInt. The reason for this is relatively straightforward: in order to use fmapMaybe on our Maybe Int, we need to provide a function that takes an Int as an input, whereas floorInt returns an Int as an output. This is a long-winded way of saying that Maybe is covariant on its type argument, or that the Functor typeclass is a covariant functor. Doesn't make sense yet? Don't worry, it shouldn't. In order to understand this better, let's contrast it with something different. A non-covariant data type Consider the following data structure representing how to create a String from something: newtype MakeString a = MakeString { makeString :: a -> String } We can use this to convert an Int into a String: newtype MakeString a = MakeString { makeString :: a -> String } showInt :: MakeString Int showInt = MakeString show main :: IO () main = putStrLn $ makeString showInt 5 The output for this program is, as expected, 5. But suppose we want to both add 3 to the Int and turn it into a String. We can do: newtype MakeString a = MakeString { makeString :: a -> String } plus3ShowInt :: MakeString Int plus3ShowInt = MakeString (show . (+ 3)) main :: IO () main = putStrLn $ makeString plus3ShowInt 5 But this approach is quite non-compositional. We'd ideally like to be able to just apply more functions to this data structure. Let's first write that up without any typeclasses: newtype MakeString a = MakeString { makeString :: a -> String } mapMakeString :: (b -> a) -> MakeString a -> MakeString b mapMakeString f (MakeString g) = MakeString (g . f) showInt :: MakeString Int showInt = MakeString show plus3ShowInt :: MakeString Int plus3ShowInt = mapMakeString (+ 3) showInt main :: IO () main = putStrLn $ makeString plus3ShowInt 5 But this kind of mapping inside a data structure is exactly what we use the Functor type class for, right? So let's try to write an instance! instance Functor MakeString where fmap f (MakeString g) = MakeString (g . f) Unfortunately, this doesn't work: Main.hs:4:45: Couldn't match type ‘b’ with ‘a’ ‘b’ is a rigid type variable bound by the type signature for fmap :: (a -> b) -> MakeString a -> MakeString b at Main.hs:4:5 ‘a’ is a rigid type variable bound by the type signature for fmap :: (a -> b) -> MakeString a -> MakeString b at Main.hs:4:5 Expected type: b -> a Actual type: a -> b Relevant bindings include g :: a -> String (bound at Main.hs:4:24) f :: a -> b (bound at Main.hs:4:10) fmap :: (a -> b) -> MakeString a -> MakeString b (bound at Main.hs:4:5) In the second argument of ‘(.)’, namely ‘f’ In the first argument of ‘MakeString’, namely ‘(g . f)’ To understand why, let's compare the type for fmap (specialized to MakeString) with our mapMakeString type: mapMakeString :: (b -> a) -> MakeString a -> MakeString b fmap :: (a -> b) -> MakeString a -> MakeString b Notice that fmap has the usual a -> b parameter, whereas mapMakeString instead has a b -> a, which goes in the opposite direction. More on that Exercise: Convince yourself that the mapMakeString function has the only valid type signature we could apply to it, and that the implementation is the only valid implementation of that signature. (It's true that you can change the variable names around to cheat and make the first parameter a -> b, but then you'd also have to modify the rest of the type signature.) Contravariance What we just saw is that fmap takes a function from a -> b, and lifts it to f a -> f b. Notice that the a is always the "input" in both cases, whereas the b is the "output" in both cases. By contrast, mapMakeString has the normal f a -> f b, but the initial function has its types reversed: b -> a. This is the core of covariance vs contravariance: - In covariance, both the original and lifted functions point in the same direction (from ato b) - In contravariance, the original and lifted functions point in opposite directions (one goes from ato b, the other from bto a) This is what is meant when we refer to the normal Functor typeclass in Haskell as a covariant functor. And as you can probably guess, we can just as easily define a contravariant functor. In fact, it exists in the contravariant package. Let's go ahead and use that typeclass in our toy example: import Data.Functor.Contravariant newtype MakeString a = MakeString { makeString :: a -> String } instance Contravariant MakeString where contramap f (MakeString g) = MakeString (g . f) showInt :: MakeString Int showInt = MakeString show plus3ShowInt :: MakeString Int plus3ShowInt = contramap (+ 3) showInt main :: IO () main = putStrLn $ makeString plus3ShowInt 5 Our implementation of contramap is identical to the mapMakeString used before, which hopefully isn't too surprising. Example: filtering with Predicate Let's say we want to print out all of the numbers from 1 to 10, where the English word for that number is more than three characters long. Using a simple helper function english :: Int -> String and filter, this is pretty simple: greaterThanThree :: Int -> Bool greaterThanThree = (> 3) lengthGTThree :: [a] -> Bool lengthGTThree = greaterThanThree . length englishGTThree :: Int -> Bool englishGTThree = lengthGTThree . english english :: Int -> String english 1 = "one" english 2 = "two" english 3 = "three" english 4 = "four" english 5 = "five" english 6 = "six" english 7 = "seven" english 8 = "eight" english 9 = "nine" english 10 = "ten" main :: IO () main = print $ filter englishGTThree [1..10] The contravariant package provides a newtype wrapper around such a -> Bool functions, called Predicate. We can use this newtype to wrap up our helper functions and avoid explicit function composition: import Data.Functor.Contravariant greaterThanThree :: Predicate Int greaterThanThree = Predicate (> 3) lengthGTThree :: Predicate [a] lengthGTThree = contramap length greaterThanThree englishGTThree :: Predicate Int englishGTThree = contramap english lengthGTThree english :: Int -> String english 1 = "one" english 2 = "two" english 3 = "three" english 4 = "four" english 5 = "five" english 6 = "six" english 7 = "seven" english 8 = "eight" english 9 = "nine" english 10 = "ten" main :: IO () main = print $ filter (getPredicate englishGTThree) [1..10] NOTE: I'm not actually recommending this as a better practice than the original, simpler version. This is just to demonstrate the capability of the abstraction. Bifunctor and Profunctor We're now ready to look at something a bit more complicated. Consider the following two typeclasses: Profunctor and Bifunctor. Both of these typeclasses apply to types of kind * -> * -> *, also known as "a type constructor that takes two arguments." But let's look at their (simplified) definitions: class Bifunctor p where bimap :: (a -> b) -> (c -> d) -> p a c -> p b d class Profunctor p where dimap :: (b -> a) -> (c -> d) -> p a c -> p b d They're identical, except that bimap takes a first parameter of type a -> b, whereas dimap takes a first parameter of type b -> a. Based on this observation, and what we've learned previously, we can now understand the documentation for these two typeclasses: Bifunctor: Intuitively it is a bifunctor where both the first and second arguments are covariant. Profunctor: Intuitively it is a bifunctor where the first argument is contravariant and the second argument is covariant. These are both bifunctors since they take two type parameters. They both treat their second parameter in the same way: covariantly. However, the first parameter is treated differently by the two: Bifunctor is covariant, and Profunctor is contravariant. Exercise Try to think of a few common datatypes in Haskell that would be either a Bifunctor or Profunctor, and write the instance. Hint Some examples are Either, (,), and -> (a normal function from a to b). Figure out which is a Bifunctor and which is a Profunctor. Solution class Bifunctor p where bimap :: (a -> b) -> (c -> d) -> p a c -> p b d class Profunctor p where dimap :: (b -> a) -> (c -> d) -> p a c -> p b d instance Bifunctor Either where bimap f _ (Left x) = Left (f x) bimap _ f (Right x) = Right (f x) instance Bifunctor (,) where bimap f g (x, y) = (f x, g y) instance Profunctor (->) where -- functions dimap f g h = g . h . f Make sure you understand why these instances work the way they do before moving on. Bivariant and invariant There are two more special cases for variance: bivariant means "both covariant and contravariant," whereas invariant means "neither covariant nor contravariant." The only types which can be bivariant are phantoms, where the type doesn't actually exist. As an example: import Data.Functor.Contravariant (Contravariant (..)) data Phantom a = Phantom instance Functor Phantom where fmap _ Phantom = Phantom instance Contravariant Phantom where contramap _ Phantom = Phantom Invariance will usually (always?) occur when a type parameter is used multiple times in the data structure, e.g.: data ToFrom a = ToFrom (a -> Int) (Int -> a) Exercise Convince yourself that you can not make an instance of either Functor nor Contravariant for this datatype. Exercise Explain why there's also no way to make an instance of Bifunctor or Profunctor for this datatype. As you can see, the a parameter is used as both the input to a function and output from a function in the above data type. This leads directly to our next set of terms. Positive and negative position Let's look at some basic covariant and contravariant data types: data WithInt a = WithInt (Int -> a) data MakeInt a = MakeInt (a -> Int) By now, you should hopefully be able to identify that WithInt is covariant on its type parameter a, whereas MakeInt is contravariant. Please make sure you're confident of that fact, and that you know what the relevant Functor and Contravariant instance will be. Can we give a simple explanation of why each of these is covariant and contravariant? Fortunately, yes: it has to do with the position the type variable appears in the function. In fact, we can even get GHC to tell us this by using Functor deriving: {-# LANGUAGE DeriveFunctor #-} data MakeInt a = MakeInt (a -> Int) deriving Functor This results in the (actually quite readable) error message: Can't make a derived instance of ‘Functor MakeInt’: Constructor ‘MakeInt’ must not use the type variable in a function argument In the data declaration for ‘MakeInt’ Another way to say this is " a appears as an input to the function." An even better way to say this is that " a appears in negative position." And now we get to define two new terms: -. To convince yourself that this is true, go review the various data types we've used above, and see if this logic applies. But why use the terms positive and negative? This is where things get quite powerful, and drastically simplify your life. Consider the following newtype wrapper intended for callbacks: newtype Callback a = Callback ((a -> IO ()) -> IO ()) Is it covariant or contravariant on a? Your first instinct may be to say "well, a is a function parameter, and therefore it's contravariant. However, let's break things down a bit further. Suppose we're just trying to deal with a -> IO (). As we've established many times above: this function is contravariant on a, and equivalently a is in negative position. This means that this function expects on input of type a. But now, we wrap up this entire function as the input to a new function, via: (a -> IO ()) -> IO (). As a whole, does this function consume an Int, or does it produce an Int? To get an intuition, let's look at an implementation of Callback Int for random numbers: supplyRandom :: Callback Int supplyRandom = Callback $ \f -> do int <- randomRIO (1, 10) f int It's clear from this implementation that supplyRandom is, in fact, producing an Int. This is similar to Maybe, meaning we have a solid argument for this also being covariant. So let's go back to our positive/negative terminology and see if it explains why. In a -> IO (), a is in negative position. In (a -> IO ()) -> IO (), a -> IO () is in negative position. Now we just follow multiplication rules: when you multiply two negatives, you get a positive. As a result, in (a -> IO ()) -> IO (), a is in positive position, meaning that Callback is covariant on a, and we can define a Functor instance. And in fact, GHC agrees with us: {-# LANGUAGE DeriveFunctor #-} import System.Random newtype Callback a = Callback { runCallback :: (a -> IO ()) -> IO () } deriving Functor supplyRandom :: Callback Int supplyRandom = Callback $ \f -> do int <- randomRIO (1, 10) f int main :: IO () main = runCallback supplyRandom print Let's unwrap the magic, though, and define our Functor instance explicitly: newtype Callback a = Callback { runCallback :: (a -> IO ()) -> IO () } instance Functor Callback where fmap f (Callback g) = Callback $ \h -> g (h . f) Exercise 1: Analyze the above Functor instance and understand what is occurring. Exercise 2: Convince yourself that the above implementation is the only one that makes sense, and similarly that there is no valid Contravariant instance. Exercise 3: For each of the following newtype wrappers, determine if they are covariant or contravariant in their arguments: newtype E1 a = E1 (a -> ()) newtype E2 a = E2 (a -> () -> ()) newtype E3 a = E3 ((a -> ()) -> ()) newtype E4 a = E4 ((a -> () -> ()) -> ()) newtype E5 a = E5 ((() -> () -> a) -> ()) -- trickier: newtype E6 a = E6 ((() -> a -> a) -> ()) newtype E7 a = E7 ((() -> () -> a) -> a) newtype E8 a = E8 ((() -> a -> ()) -> a) newtype E9 a = E8 ((() -> () -> ()) -> ()) Lifting IO to MonadIO Let's look at something seemingly unrelated to get a feel for the power of our new analysis tools. Consider the base function openFile: openFile :: FilePath -> IOMode -> IO Handle We may want to use this from a monad transformer stack based on top of the IO monad. The standard approach to that is to use the MonadIO typeclass as a constraint, and its liftIO function. This is all rather straightforward: import System.IO import Control.Monad.IO.Class openFileLifted :: MonadIO m => FilePath -> IOMode -> m Handle openFileLifted fp mode = liftIO (openFile fp mode) But of course, we all prefer using the withFile function instead of openFile to ensure resources are cleaned up in the presence of exceptions. As a reminder, that function has a type signature: withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a So can we somehow write our lifted version with type signature: withFileLifted :: MonadIO m => FilePath -> IOMode -> (Handle -> m a) -> m a Try as we might, this can't be done, at least not directly (if you're really curious, see lifted-base and its implementation of bracket). And now, we have the vocabulary to explain this succinctly: the IO type appears in both positive and negative position in withFile's type signature. By contrast, with openFile, IO appears exclusively in positive position, meaning our transformation function ( liftIO) can be applied to it.
https://www.schoolofhaskell.com/user/commercial/content/covariance-contravariance
CC-MAIN-2017-26
refinedweb
2,603
57.1
Working with XML-like files ReSharper comes with support for XML and XML-specific notations such as HTML, XAML and Web.config editing. Consequently, you can use the ReSharper API in order to manipulate XML documents. Web vs XML The ReSharper code model distinguishes between two types of documents - web documents (i.e., documents concerning HTML) and XML documents. The distinction is important because, while XML documents are typically concerned with XML only, web documents can include many different notations in addition to HTML. Examples of such notations include JavaScript as well as mark-up for the MVC WebForms or Razor view engines. Let's take a look at the XML format first. XML Compared to HTML, XML is a lot easier to work with - it has a predictable structure and fairly limited variability in terms of content. Consequently, the API structures for manipulating XML are very straightforward. Let's take a look at how one would write a context action to support the conversion of an empty tag such as <test></test> to a self-closing tag <test/>. The first thing you do is create a class that is marked with the ContextAction attribute and is set to inherit from XmlContextAction. As you can see, the context action is very similar to the way you would define it for, e.g., the C# language. The only major difference is that instead of supporting a general IContextAction interface, you need to inherit from a special class. (And even that is optional - XmlContextAction is simply an intermediate class that ensures you pick the right data provider.) Now that you have a context action, it becomes a matter of defining the familiar Text, IsAvailable() and ExecutePsiTransaction() members. The IsAvailable() method is the place where you would check that the tag you're on is empty. For example: Manipulation of XML tokens is very important if you want to do fine-tuning of your XML-related actions. To get at the token at the caret location, for example, you would write: Now, you can, for example, call GetTokenType() to determine the type of the token you're on. Keep in mind that IXmlToken is inherited by many other interfaces such as e.g., IXmlIdentifier. After determining the type of token, you can cast to the right type to get at the token-specific properties and methods. Here's a brief example: suppose you want to remove all inner nodes of a particular tag. To do this, you would take the tag's header node and then take its next sibling. Then you would also take its last child. Finally, you would use the ModificationUtil class in order to delete all children within that range: The ModificationUtil class contains several methods for adding and removing elements from the XML token tree. Example: working with an XML attribute Here's a simple example: let's suppose that you have a tag, and you want to add an attribute to it - for example, an attribute for an XML namespace. The first thing you do is acquire an XMLElementFactory. Then, you can synthetically prepare the attribute declaration: With the declaration, you can use the factory to create a whole XML file. This may sound 'heavyweight', but is in fact a convenient way to get the structures parsed and ready for subsequent insertion. Finally, you can get at the attribute in the created file and insert it into the tag you're trying to change: HTML Work with HTML files is a bit different than XML. The first thing to note is that, unlike with XML, an HTML context action, for instance, would have no special base class of its own. Rather, making an HTML-related context action is simply a matter of implementing the IContextAction interface. The only difference is that this context action would take an IWebContextActionDataProvider<T> as a parameter. The type parameter T has to be either of type IHtmlFile or one of its inheritors - IAspFile and IRazorFile. Here's an outline of a context action for HTML files: Now, you'll notice that the code for creating an id-inserting context action is very similar to what we did for XML. The only differences are in the types of tags and factories that we are using: Now, when it comes to modifying the document tree, with Web files there is one difference: you need to explicitly create the transaction before modifying the HTML file. Here's a piece of code that, just like in the XML example, inserts the id attribute into a tag: As you can see, the principle for creating the attribute is the similar to what we had before, with the difference that instead of creating a whole file, we can simply create a tag. From then on, getting the first attribute and inserting it into our element is easy.
https://www.jetbrains.com/help/resharper/sdk/XmlLike.html
CC-MAIN-2022-05
refinedweb
810
59.03
Introduction It’s superbowl Sunday and between the snacks it is time to learn something new. Today my eye fell on Angularjs. Angularjs is an MVC framework for javascript. It kinda puts the controllers and model on the clientside and not on the serverside like ASP.Net MVC does. I will use Nancy as our service to provide us with json data. Server Our server is pretty simple. Just make an empty asp.net application and add a Models folder. Here is my model. using System; namespace NancyJTable.Models { public class PlantModel { public int Id { get; set; } public string Name { get; set; } public string Genus { get; set; } public string Species { get; set; } public DateTime DateAdded { get; set; } } } And here is my module, which I put in the Modules folder. using System; using System.Collections.Generic; using System.Linq; using Nancy; using NancyJTable.Models; namespace NancyJTable.Modules { public class PlantsModule:NancyModule { public PlantsModule() { Get["/plants/{Id}"] = parameters => Response.AsJson(GetPlantModels().SingleOrDefault(x => x.Id == parameters.Id)); Get["/plants"] = parameters => { return Response.AsJson(GetPlantModels()); }; } private IList<PlantModel> GetPlantModels() { var plantModels = new List<PlantModel>(); for (var i = 1; i <= 25; i++) { var j = i.ToString("000"); plantModels.Add(new PlantModel() { Id = i, Name = "name" + j, Genus = "genus" + j, Species = "Species" + j, DateAdded = DateTime.Now }); } return plantModels; } } } Client First I added another empty ASP.Net web application project to our solution. I added angularjs to my project. It is on nuget so no problems there. I want to add a list of plants and I want a details page. First I need to start with adding my app.j in the js folder. This will take care of the routes. angular.module('plantsapp', []). config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/plants', { templateUrl: 'partials/plants.html', controller: PlantsController }). when('/plants/:Id', { templateUrl: 'partials/plant.html', controller: PlantController }). otherwise({ redirectTo: '/plants' }); }]); You already see that I have two partial views and 2 controllers. The controllers are in my controllers.js file. function PlantsController($scope, $http) { $http.get('').success(function (data) { $scope.plants = data; }); } function PlantController($scope, $routeParams, $http) { $http.get('' + $routeParams.Id).success(function (data) { $scope.plant = data; }); } So I have a Plantscontroller that uses a get to get my json from my nancy service. And I have a PlantController that uses the routeparameter to tell which plant to get from my service. See how I inject http and how it magically gets injected for me. The next thing is to create an index.html which is the base of our views. <!DOCTYPE html> <html lang="en" ng- <head> <title>Plants</title> <script src="/Scripts/angular.js"></script> <script src="/js/controller.js"></script> <script src="/js/app.js"></script> </head> <body> <div ng-view></div> </body> </html> In the html tag I added an ng-app with the name I provided in my app.js. I import angular.js, controller.js and app.js. And I added a div with an ng-view attribute. Now I need the partials which I put in the partials folder. <table id="table_id"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Genus</th> </tr> </thead> <tbody ng- <tr> <td>{{plant.Id}}</td> <td><a href="#/plants/{{plant.Id}}">{{plant.Name}}</a></td> <td>{{plant.Genus}}</td> </tr> </tbody> </table> This is my plants.html file and it uses the plants object which I have added to the scope in my controller. See how I add the link (the # is important). The next file is the detail view, plant.html. <table id="table_id"> <tr> <th>Id</th> <th>{{plant.Id}}</th> </tr> <tr> <th>Name</th> <th>{{plant.Name}}</th> </tr> <tr> <th>Genus</th> <th>{{plant.Genus}}</th> </tr> </table> Here I use plant because that is what I used to add the the scope in my controller. And that is it. Here are the screenshots. Look also at the url in the addressbarr. The plants. And here the detail view. Conclusion Yeah, uhm. Not sure. Not saying this is bad, but how will this scale ;-). One thing is for sure, the documentation was very good to get my started. Not that I read it before beginning but once I did, it helped. Framework fatigue didn’t kick in yet? Oh yeah. I wish someone had a monopoly and take over this damn mess we call programming. Yep, back in the year 2000 or so there was none of this stuff….no libraries, 2 browsers, php, asp, jsp, coldfusion or perl were the webstack technologies and that was pretty much what 93% of the world used Nice work. I’ve been reviewing Angular myself. One thing you could do is make a separate service or repository if you will and that can get injected into your controllers! IF you use $resource instead of $http, you get a higher-level abstraction and you don’t have to deal with any of the HTTP calls. @SQLDenis, Yes, back in the old days it was just CGI or ISAPI, but things are also different. Back then it was very much client-server with HTTP. This is all about being client with server only acting as data and processing, thus improving the experience with a more fluid and responsive design. One feature worth elaborating on is Angular’s HTML5 mode. That allows any browser supporting the history API to ditch the hashbang and use standard URL paths with the option to gracefully fall back. Having built a couple medium to large scale SPAs with Angular, I’d say it scales better than most of today’s popular MV(*) JavaScript frameworks. It’s on par with Ember, no doubt. Ive googled this all day and haven’t been able to get around this error. Closest Ive gotten was using jsonp instead of $http. Is there something I need to configure or set up to get this to work in local development and on a server. I tried adding delete $http.default.headers.common ‘x-requested-with’. Ive also tried writing the angular side about 50 different ways XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin.
http://blogs.lessthandot.com/index.php/webdev/serverprogramming/aspnet/angularjs/
CC-MAIN-2015-22
refinedweb
1,015
69.99
Prerequisites: Before practicing the script of this tutorial, you have to complete the following tasks. A. Install the Django version 3+ on Ubuntu 20+ (preferably) B. Create a Django project C. Run the Django server to check the server is working correctly or not. Setup a Django app: A. Run the following command to create a Django app named inclusiontagapp. B. Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command. C. Add the app name in the INSTALLED_APP part of the settings.py file. ….. 'inclusiontagapp' ] D. Create a folder named templates inside the inclusiontagapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file. { …. 'DIRS': ['/home/fahmida/django_pro/inclusiontagapp/templates'], …. }, ] Implement Inclusion Tag in Django: Create templatetags folder inside the inclusiontagapp folder. Next, create a python file named inclusiontag.py with the following script. The template module is imported into the script to use the inclusion tag. A list of even numbers will be generated after calling the display_even_numbers() function of this script. The output of this script will be displayed in the display.html file that has been created in the next step of this tutorial. inclusiontag.py from django import template # Create an object of Library() register = template.Library() # Define the template file for the inclusion tag @register.inclusion_tag('display.html') # Declare function to find out the even numbers within a range def display_even_numbers(a, b): # Declare a empty list number = [] # Iterate the loop to find out the even number between a and b for i in range(a, b): # Check the number is even or not if i % 2 == 0: # Add the number in the list if it is even number.append(i) # Return the list to the display.html file return {"output": number} Create an HTML file named display.html inside the templates folder and add the following script. The list’s values returned by the inclusion tag are read by a for loop in the script. display.html Next, create another HTML file named incusiontag.html inside the templates folder and add the following script. In this script, the content of the inclusiontag made in the previous part of this tutorial is loaded, and the display_even_number() function is called with two argument values, 10 and 20. This function will create a list of even numbers between 10 and 20 and return the list to the display.html file. inclusiontag.html Modify the views.py file with the following script to load the inclusion tag in the required template file. When the function inclusiontag() of this script is called, it will display the inclusiontag.html file that will load the inclusiontag and call the display_even_numbers() function. views.py from django.shortcuts import render ''' Declare function to render inclusiontag.html file to load inclusion tag ''' def inclusiontag(request): return render(request, "inclusiontag.html") Modify the urls.py file of the Django project and add the following script. After running the Django server, if the path, inctag, will be added after the base URL, the inclusiontag() function will be called from the view file. This function will render the inclusiontag.html file. This HTML file will load the inclusion tag that will call display_even_numbers() with arguments. This function will return a list of even numbers based on the argument values and display them in the display.html file. urls.py from django.urls import path # Import inclusiontag view from inclusiontagapp.views import inclusiontag # Define path to call the inclusiontag function of the view urlpatterns = [ path('inctag', inclusiontag), ] Now, run the following command to start the Django server to check the above script is working correctly or not. Run the following URL from any browser to check the output of this app. The following output will appear if the above files are created and working properly. There are 5 even numbers between 10 to 20, and these have been displayed in the output. Conclusion: Many functions exist in the Django framework to create different types of custom tags. These are simple_tag(), inclusion_tag() and ssignment_tag(). simple_tag() function is used to return string after processing the data. inclusion_tag() function is used to return a template after processing the data. assignment_tag() function is used to set a variable after processing the data. The inclusion_tag() function has been shown in this tutorial that returned a rendered template after processing the data. I hope this tutorial will help the reader know how to use the inclusion tag in the Django app.
https://linuxhint.com/use-django-inclusion-tag/
CC-MAIN-2022-05
refinedweb
766
57.87
First off, heres my code. This is a battle program Im working on. In the code it subtracts the defenders defence from the attackers attack then subtracts the rest from the defenders health pointsThis is a battle program Im working on. In the code it subtracts the defenders defence from the attackers attack then subtracts the rest from the defenders health pointsCode:#include <iostream> #include <cstdlib> #include <cstring> #include <time.h> using namespace std; string Command; struct User { int UHP; // Users Current Hit Points int max_UHP; // Users Maximum Hit Points }; struct Challenger { int CHP; // Challengers Current Hit Points int max_CHP; // Challengers Maximum Hit Points }; int main() { srand( time(NULL) ); User Player; Challenger Enemy; Player.max_UHP = 100; // Users Maximum Health Points Player.UHP = 100; // Users Current Health Points int UATK = rand()%20; // Users Attack Points int UDF = rand()%20; // Users Defence Points int UACC = rand()%10; // Users Accuracy Points int UAGT = rand()%10; // Users Agility Points Enemy.max_CHP = 100; // Challengers Maximum Health Points Enemy.CHP = 100; // Challengers Current Health Points int CATK = rand()%15; // Challengers Attack Points int CDF = rand()%15; // Challengers Defence Points int CACC = rand()%10; // Challengers Accuracy Points int CAGT = rand()%10; // Challengers Agility Points cout<<"As your walking down a path a cloaked swordsman ambushes you.\n"; cout<<"He then challenges you to a fight and you humbly accept.\n"; do{ cout<<"Your turn:\n"; cin>>Command; cin.ignore(); if(Command=="Attack"||Command=="attack"){ if(UACC >=6 && CAGT >=6){Enemy.CHP-=(UATK-=CDF); cout<<UATK<<" Damage!\n"; cout<<"He blocked "<<CDF<<" damage.\n"; cout<<"Him: "<<Enemy.CHP<<"/"<<Enemy.max_CHP<<"\n";} else if(UACC >=6){Enemy.CHP-=UATK; cout<<UATK<<" Damage!\n"; cout<<"Him: "<<Enemy.CHP<<"/"<<Enemy.max_CHP<<"\n";} else(UACC <=5);{ cout<<"Miss\n";} } cout<<"He attacks.\n"; Player.UHP-=CATK; cout<<"You lost "<<CATK<<" hp.\n"; cout<<"You: "<<Player.UHP<<"/"<<Player.max_UHP<<"\n"; }while(Player.UHP >=0 || Enemy.CHP >=0); cin.get(); } ex : Enemy.CHP-=(UATK-=CDF) now my problem is if the defence is higher than the attack it adds the remaining points to the defenders health. How can I stop it from doing that. Second problem, I heard that the way Im using rand isnt exactly the right and best way to use it. I agree because my numbers arent very random at all. Can someone tell me how I would fix this and work into my code?
http://cboard.cprogramming.com/cplusplus-programming/78918-i-have-two-problems.html
CC-MAIN-2015-18
refinedweb
394
68.67
Does anyone know if there is a way to generate python client that allows you to create a JSON body in a POST request without users needing to know they must create and pass a model object to the API function call, but instead use parameter names to create JSON in same way POSTing form-data or query params works? For example, I would like the following: ...operationId: get_thingsparameters:- in: body name: request schema: type: object properties: things: type: array items: string other: type: string #!/usr/bin/python import api things = ["thing1", "thing2"] api.get_things(things=things, other="test") to generate a request to server that looks like {"things": ["thing1", "thing2"], "other": "test") The problem is it failes because it only expects an argument called `request` on the function, not `things` and `other` To get the correct request sent, we must do something like definitions: ThingDef: type: object properties: things: type: array items: string other: type: string #/usr/bin/python import api things = ["thing1", "thing2"] thing_def = ThingDef(things=things, other="test") api.get_things(request=thing_def) Alternatively, it looks like you can manually create the dict and pass as request argument... things = ["thing1", "thing2"] api.get_things(request={"things": things, "other": "test"}) I can understand in complicated models being sent to the server, it might make sense to require a user to populate a model object and use that in the function call. However, if we want to send very basic JSON, it is much more intuitive and more in line with syntax for sending form-data, query params, etc. to just use the attribute names as function parameters. However, as is the generated client does not create the JSON request body in this way. Is there a way to specify the yaml differently to obtain what I want, or do I need to create a custom codegen for python to generate a client as desired?
https://community.smartbear.com/t5/Swagger-Open-Source-Tools/Python-Client-JSON-Request-Body/td-p/182746
CC-MAIN-2020-50
refinedweb
314
54.97
Damn, I can't believe I didn't realize that! Rookie mistake. Hahaha. So there's no way to circumvent this? Damn, I can't believe I didn't realize that! Rookie mistake. Hahaha. So there's no way to circumvent this? Well... I've just started programming in C again. I've been away from this beautiful language for far too long! Anyway, thought I'd brush up on a few very basic concepts, but it seems I've made a... Well... you're right, I shouldn't cast it like that. I'll change the while to: while((subs = fgetc(fp)) != ' ' && subs != '\n' && !feof(fp)) Any ideas on why I'm get unexpected results? Or more... #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tchar.h> void retrieveSubdomains(void); int main(int argc, char *argv[]) Well, I'm trying to scan though a file 'subdomains.txt' and print out what's on each line seperately. E.g. file contains: this file means nothing_to_you I want each line to be printed... Okay, so I'll start off by telling you what I am trying to do. I have a text file that has words on each line. E.g. this is a test forMyProgram You can find a good video programming series on C, by Mark Virtue. If one was to search on tpb 'VTC c programming' and get the series done by Mark Virtue, the would be pleasantly surprised. There's... Thank you, Salem. Can anybody answer my questions? Why could I pass an the argument 'argv[0]' into my original program? And why is the point of making a function a pointer? Sorry, I don't get what you mean. I wanted my path 'C:\users\*****\Desktop\myfile.exe' to just be 'myfile.exe'. Ah, just re-read your post. I was meaning argv[0], not argv[]. Sorry about the... Never-mind, all is working well. Thank you very much! Could you tell me why my code wasn't working? Just out of curiosity. Also, why is the function base_name a pointer? Just curious. Ah, forgot that the backslash was an escape character... Momentary lapse of knowledge... Hahaha. You're code looks good, but base_name() wont take argv[] as a parameter. :/ No, the above code doesn't work as I would like it to, but this code works: #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { _explode(); system("pause");... Thanks for the quick reply, but it points to the result of strtok(). I haven't programmed in C for quite a long time, so I have picked up some bad habits. I think there's something wrong with how I'm... #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { _explode(argv[0]); system("pause"); //Yes... I know this is bad. return 0; } Okay, I'm sorry, I shouldn't have replied like that. :/ I understand you were just trying to help. Anyway, if I was shifting that variable to another area of memory, would that area of memory have to... Are you ........ing kidding me? Where did you learn ASM? Bellow is the example that I am going to use. The bellow code should compile on GNU assembler. Syntax is AT&T incase any numbies are curious. .data HelloWorldString: .asciz "Hello" Can you use inline assembly? Or a simple messagebox. :cool: Just a few things to note: What is the 'i' variable being used for? Void main is bad. Read more about why, here:void main(void) - the Wrong Thing Thank you, I can't believe I was so stupid to miss that. Yeah, how I set out the header file isn't how it's 'supposed to be', but I did it for simplicity. I was going to move all unneeded code back... I'm getting the following errors: Files: bot.h I've been reading up on portable executables(Portable Executable - Wikipedia, the free encyclopedia), as they quite interest me. I would hate to have to compile my programs to work on different... Why are you put and ampersand in front of your variable in the printf statement? Remove that, and your problems will be resolved. My bad, I didn't proof read my post before posting it. I was meaning 'So, as long as I don't check processor specific options, my code should run on all Windows machines? Sorry for the seemingly... Thank you very much, this was a prefect reply. So, as long as I check processor specific options, my code should run on all Windows machines? If I make a simple hello world program, it will run...
https://cboard.cprogramming.com/search.php?s=ecbd1e9d8beec715e7b3169607e21b67&searchid=2056007
CC-MAIN-2019-47
refinedweb
776
87.01
Tutorial is accepted for rainbow contest do vote if you like it. Do subscribe my channel for upcoming videos.Step 1: Components The component list way too small but there are diversity in the list . i actually reviewed three types over the this instructables anyways the list . - Arduino - RBG led - HC-05 - Jumpers - Bread Board RGB led : Easily available in ebay and all radio shack or locals store. High Color Output. Can be easily power withi arduino .RGB SMD : This are sold as module i test a common cathode version the seem not to work great with arduinos internal power supply. RGB LED Strip : These are the Best comes with highest color range output with a correct driver you can drive them to give insane level of colors.Indians can find these at this linkodeStep 3: Interfacing RGB Led & RGB Led Strips RGB LED: In case for RGB led the interfacing is very easy we talk about both Common Cathode And Common Anode. Common Cathode R to any PWM channel available G to any PWM channel available B to any PWM channel available Cathode to Gnd Common Anode R to any PWM channel available G to any PWM channel available B to any PWM channel available Anode to 5V RGB Led Strip In case of strip out need to switch the the the strip on and off with Mosfet or transistor, I used transistor.I made the driver and it is also given in the schematics.Step 4: Controlling RGB To Control The RGB we need to learn how to control a Normal LED Brightness.The Answer is PWM Pulse Width Modulation. It is digital representing Analog signal by varying the duty cycle of the pulse. In arduino, we use the analog write function to get a PWM wave the function generates a square wave of specified duty cycle the value of which is defined by the)Step 5: Connection The Connection the Mode Lamp is SimpleFirst we connect the rgb led or strip . RGB LED/RGB STRIP Red to Pin 3 of Arduino Blue to Pin 5 of Arduino Green to Pin 6 of Arduino Anode to 5V If Strip Gnd of driver to gnd of Arduino HC-05 Connection Rx to pin 12 of Arduino Tx to pin 11 of Arduino vcc to 5v gnd to gndStep 6: Code #include <SoftwareSerial.h> #include <Wire.h>//Include libraries: SoftwareSerial & Wire SoftwareSerial BT(11,12); //Define PIN11 & PIN12 as RX and TX pins //RGB LED Pins int PIN_RED = 3; int PIN_GREEN = 5; int PIN_BLUE = 6; //RED LED at Pin 13 int RED_LED = 13; String RGB = ""; //store RGB code from BT String RGB_Previous = "255.255.255)"; //preserve previous RGB color for LED switch on/off, default White String ON = "ON"; //Check if ON command is received String OFF = "OFF"; //Check if OFF command is received boolean RGB_Completed = false; void setup() { Serial.begin(9600); //Arduino serial port baud rate:9600 BT.begin(9600);//My HC-05 module default baud rate is 9600 RGB.reserve(30); pinMode(RED_LED, OUTPUT); //Set pin13 as output for LED, // this LED is on Arduino mini pro, not the RGB LED } void loop() { // put your main code here, to run repeatedly: //Read each character from Serial Port(Bluetooth) while(BT.available()){ char ReadChar = (char)BT.read(); // Right parentheses ) indicates complet of the string if(ReadChar == ')'){ RGB_Completed = true; }else{ RGB += ReadChar; } } //When a command code is received completely with ')' ending character if(RGB_Completed){ //Print out debug info at Serial output window Serial.print("RGB:"); Serial.print(RGB); Serial.print(" PreRGB:"); Serial.println(RGB_Previous); if(RGB==ON){ digitalWrite(13,HIGH); RGB = RGB_Previous; //We only receive 'ON', so get previous RGB color back to turn LED on Light_RGB_LED(); }else if(RGB==OFF){ digitalWrite(13,LOW); RGB = "0.0.0)"; //Send OFF string to turn light off Light_RGB_LED(); }else{ //Turn the color according the color code from Bluetooth Serial Port Light_RGB_LED(); RGB_Previous = RGB; } //Reset RGB String RGB = ""; RGB_Completed = false; } //end if of check if RGB completed } // end of loop void Light_RGB_LED(){ int SP1 = RGB.indexOf('.'); int SP2 = RGB.indexOf('.', SP1+1); int SP3 = RGB.indexOf('.', SP2+1); String R = RGB.substring(0, SP1); String G = RGB.substring(SP1+1, SP2); String B = RGB.substring(SP2+1, SP3); //Print out debug info at Serial output window Serial.print("R="); Serial.println( constrain(R.toInt(),0,255)); Serial.print("G="); Serial.println(constrain(G.toInt(),0,255)); Serial.print("B="); Serial.println( constrain(B.toInt(),0,255)); //Light up the LED with color code //**2014-09-21 //Because these RGB LED are common anode (Common positive) //So we need to take 255 to minus R,G,B value to get correct RGB color code analogWrite(PIN_RED, (R.toInt())); analogWrite(PIN_GREEN, (G.toInt())); analogWrite(PIN_BLUE, (B.toInt())); If you liked this project support me on Facebook my liking my page, you will aslo be able to talk about your doubts trough the page.
https://www.raspberrypi.hackster.io/GeekRex/smartphone-controlled-rgb-mood-light-95150e
CC-MAIN-2020-34
refinedweb
818
60.65
Conversion Routines To write a number to a printer or terminal, you must convert the number to characters. The printer understands only characters, not numbers. For example, the number 567 must be converted to the three characters "5", "6", and "7" to be printed. The << operator is used to convert data to characters and put them in a file. This function is extremely flexible. It can convert a simple integer into a fixed- or variable-size string as a hex, octal, or decimal number with left or right justification. So far you've been using the default conversion for your output. It serves pretty well, but if you want to control your output exactly, you need to learn about conversion flags. setf andsetf and unsetf are used to set and clear the flags that control the conversion process. The general form of the functions is:unsetf are used to set and clear the flags that control the conversion process. The general form of the functions is: file_var.setf(flags); // Set flags file_var.unsetf(flags); // Clear flags Table 16-3 lists the various flags and their meanings. If you want to output a number in hexadecimal format, all you have to do is this: number = 0x3FF; std::cout << "Dec: " << number << '\n'; std::cout.setf(std::ios::hex); std::cout << "Hex: " << number << '\n'; std::cout.setf(std::ios::dec); When run, this program produces the output: Dec: 1023 Hex: 3ff TIP: People normally expect the output mode to be decimal, so it is a good idea to reset the mode after each output to avoid later confusion. When converting numbers to characters, the member function: int file_var.width(int size); determines the minimum characters to use. For example, the number 3 would normally convert to the character string "3" (note the lack of spaces). If the width is set to four, the result would be "3" where represents a single space. The member function: int file_var.precision(int digits); controls how many digits are printed after the decimal point. Finally, the function: char file_var.fill(char pad); determines the fill character. This character is used for padding when a number is smaller than the specified width. TIP: Some of these flags and parameters are reset after each output call and some are not. Which flags are permanent and which are temporary seems to change from compiler to compiler. In general, don't assume anything is going to remain set and you'll be okay. (Just because you're paranoid doesn't mean the compiler isn't out to get you.) These functions can be called directly, or you can use an I/O manipulator. An I/O manipulator is a special function that can be used in an I/O statement to change the formatting. You can think of a manipulator as a magic bullet that, when sent through an input or output file, changes the state of the file. A manipulator doesn't cause any output; it just changes the state. For example, the manipulator hex changes the output conversion to hexadecimal. #include <iostream> number = 0x3FF; std::cout << "Number is " << std::hex << number << std::dec << '\n'; The header file <iostream> defines a basic set of manipulators. Table 16-4 contains a list of these manipulators. The more advanced set of manipulators (see Table 16-5) is defined in the header file <iomanip>. Example 16-3 shows how some of the I/O manipulators may be used. Example 16-3: io/io.cpp #include <iostream> #include <iomanip> int main( ) { int number = 12; // A number to output float real = 12.34; // A real number std::cout << "123456789012345678901234567890\n"; // output ruler std::cout << number << "<-\n"; std::cout << std::setw(5) << number << "<-\n"; std::cout << std::setw(5) << std::setfill('*') << number << "<-\n"; std::cout << std::setiosflags(std::ios::showpos|std::ios::left) << std::setw(5) << number << "<-\n"; std::cout << real << "<-\n"; std::cout << std::setprecision(1) << std::setiosflags(std::ios::fixed) << real << "<-\n"; std::cout << std::setiosflags(std::ios::scientific) << real << "<-\n"; return (0); } The output of this program is: 123456789012345678901234567890 12<- 12<- ***12<- +12**<- 12.34<- 12.3<- 1e+01<- Page: 1 2 3 4 5 6 7 8 9 Next There are no comments yet. Be the first to comment!
http://www.codeguru.com/columns/chapters/article.php/c6653/Conversion-Routines.htm
CC-MAIN-2014-15
refinedweb
707
56.76
Abstract film base class - used to store samples generated by Integrator implementations. More... #include <mitsuba/render/film.h> Abstract film base class - used to store samples generated by Integrator implementations. To avoid lock-related bottlenecks when rendering with many cores, rendering threads first store results in an "image block", which is then committed to the film. Create a film. Unserialize a film. Virtual destructor. Accumulate a bitmap on top of the radiance values stored in the film. Add a child node. Reimplemented from mitsuba::ConfigurableObject. Add an unnamed child. Clear the film. Configure the film. Reimplemented from mitsuba::ConfigurableObject. Does the destination file already exist? Develop the film and write the result to the previously specified filename. Develop the contents of a subregion of the film and store it inside the given bitmap. This may fail when the film does not have an explicit representation of the bitmap in question (e.g. when it is writing to a tiled EXR image) trueupon success Retrieve this object's class. Reimplemented from mitsuba::ConfigurableObject. Return the offset of the crop window. Return the size of the crop window. Return the image reconstruction filter. Return the image reconstruction filter (const version) Ignoring the crop window, return the resolution of the underlying sensor. Return whether or not this film records the alpha channel. Should regions slightly outside the image plane be sampled to improve the quality of the reconstruction at the edges? This only makes sense when reconstruction filters other than the box filter are used. Merge an image block into the film. Serialize this film to a binary data stream. Reimplemented from mitsuba::ConfigurableObject. Overwrite the film with the given bitmap and optionally multiply it by a scalar. Set the target filename (with or without extension)
http://mitsuba-renderer.org/api/classmitsuba_1_1_film.html
CC-MAIN-2020-50
refinedweb
293
53.47
/usr/ucb/cc[ flag ... ] file... #include <signal.h> int sig; struct sigvec *nvec struct sigvec *ovec.ing in the signal mask associated with the handler to be invoked. The action to be taken when the signal is delivered is specified by a sigvec() structure, which includes the following members: void (*sv_handler)(); /* signal handler */ int sv_mask; /* signal mask to apply */ int sv_flags; /* see signal options */ #define SV_ONSTACK /* take signal on signal stack */ #define SV_INTERRUPT /* do not restart system on signal return */ #define SV_RESETHAND /* reset handler to SIG_DFL when signal taken*/ If the SV_ONSTACK bit is set in the flags for that signal, the system will deliver the signal to the process on the signal stack specified with sigstack(3UCB) rather than delivering the signal on the current stack. If nvec is not a NULL pointer, sigvec() assigns the handler specified by sv_handler(), the mask specified by sv_mask(), and the flags specified by sv_flags() to the specified signal. If nvec is a NULL pointer, sigvec() does not change the handler, mask, or flags for the specified signal. The mask specified in nvec is not allowed to block SIGKILL, SIGSTOP, or SIGCONT. The system enforces this restriction silently. If ovec is not a NULL pointer, the handler, mask, and flags in effect for the signal before the call to sigvec() are returned to the user. A call to sigvec() with nvec a NULL pointer and ovec not a NULL pointer can be used to determine the handling information currently in effect for a signal without changing that information. The following is a list of all signals with names as in the include file <signal.h>: The starred signals in the list above cause a core image if not caught or ignored. Once a signal handler is installed, it remains installed until another sigvec() call is made, or an execve(2) is performed, unless the SV_RESETHAND bit is set in the flags for that signal. In that case, the value of the handler for the caught signal will be set to SIG_DFL before entering the signal-catching function, unless the signal is SIGILL, SIGPWR, or SIGTRAP. Also, if this bit is set, the bit for that signal in the signal mask will not be set; unless the signal mask associated with that signal blocks that signal, further occurrences of that signal will not be blocked. The SV_RESETHAND flag is not available in 4.2BSD, hence it should not be used if backward compatibility is needed. The default action for a signal may be reinstated by setting the signal's handler to SIG_DFL; this default is termination except for signals marked with * or **. Signals marked with * are discarded if the action is SIG_DFL; signals marked with ** cause the process to stop. If the process is terminated, a "core image" will be made in the current working directory of the receiving process if the signal is one for which an asterisk appears in the above list (see core(4)). If the handler for that signal is SIG_IGN, the signal is subsequently ignored, and pending instances of the signal are discarded. If a caught signal occurs during certain functions, the call is normally restarted. The call can be forced to terminate prematurely with an EINTR error return by setting the SV_INTERRUPT bit in the flags for that signal. The SV_INTERRUPT(2)., certain machines may supply an address that is on the same page as the address that caused the fault. If an appropriate addr cannot be computed it will be set to SIG_NOADDR. A 0 value indicates that the call succeeded. A -1 return value indicates that an error occurred and errno is set to indicate the reason. sigvec() will fail and no new signal handler will be installed if one of the following occurs: intro(2), exec(2), fcntl(2), fork(2), getitimer(2), getrlimit(2), ioctl(2), kill(2), ptrace(2), read(2), umask(2), vfork(2), wait(2), write(2), setjmp(3C) sigblock(3UCB), sigstack(3UCB), signal(3UCB), wait(3UCB), signal(3C), core(4), streamio(7I), termio(7I) Use of these interfaces should be restricted to only applications written on BSD platforms. Use of these interfaces with any of the system libraries or in multi-thread applications is unsupported. SIGPOLL is a synonym for SIGIO. A SIGIO will be issued when a file descriptor corresponding to a STREAMS (see intro(2)) file has a "selectable" event pending. Unless that descriptor has been put into asynchronous mode (see fcntl(2)), a process may specifically request that this signal be sent using the I_SETSIG ioctl(2) call (see streamio(7I)). Otherwise, the process will never receive SIGPOLLs0. The handler routine can be declared: void handler(int sig, int. The signals SIGKILL, SIGSTOP, and SIGCONT cannot be ignored.
http://www.shrubbery.net/solaris9ab/SUNWaman/hman3ucb/sigvec.3ucb.html
CC-MAIN-2016-44
refinedweb
791
57.5
.() For a list of all options, see the MongoDB Manual entry on the aggregate command... Returns¶ This function returns a newly allocated mongoc_cursor_t that should be freed with mongoc_cursor_destroy() when no longer in use. The returned mongoc_cursor_t is never NULL; if the parameters are invalid, the bson_error_t in the mongoc_cursor_t is filled out, and the mongoc_cursor_t is returned before the server is selected. The user must call mongoc_cursor_next() on the returned mongoc_cursor_t to execute the aggregation pipeline. Warning Failure to handle the result of this function is a programming error. Example¶ #include <bson/bson.h> #include <mongoc/mongoc.h> static mongoc_cursor_t *);
http://mongoc.org/libmongoc/1.17.5/mongoc_collection_aggregate.html
CC-MAIN-2021-49
refinedweb
101
50.73
You can use the following basic syntax to read a CSV file into a record array in NumPy: from numpy import genfromtxt my_data = genfromtxt('data.csv', delimiter=',', dtype=None) The following step-by-step example shows how to use this syntax in practice. Step 1: View the CSV File Suppose we have the following CSV file called data.csv that we’d like to read into NumPy: Step 2: Read in CSV File The following code shows how to read in this CSV file into a Numpy array: from numpy import genfromtxt #import CSV file my_data = genfromtxt('data.csv', delimiter=',', dtype=None) Note the following: - delimiter: This specifies the delimiter that separates the data values in the CSV file. - dtype: This specifies the data type for the NumPy array. By using None, we allow multiple data types to be imported at once within the array. Example 3: View the NumPy Array Once we’ve imported the CSV file, we can view it: #view imported CSV file my_data array([[1, 2, 2, 2, 3, 4], [5, 5, 6, 8, 9, 9]]) We can see that the data in the NumPy array matches the data shown in the CSV file. Note: You can find the complete online documentation for the genfromtxt() function here. Additional Resources The following tutorials explain how to perform other common functions with CSV files in pandas: How to Read CSV Files with Pandas How to Export Pandas DataFrame to CSV File Pandas: How to Append Data to Existing CSV File
https://www.statology.org/numpy-read-csv/
CC-MAIN-2021-39
refinedweb
252
55.58
Hands an interface for merging, updating, adding and deleting a XML::LibXML::Document in an easy fashion....SINISTER/XML-LibXML-Tools-1.00 - 31 Jan 2007 11:37:12 GMT - Search in distribution PAJAS/XML-XSH-1.8.2 (2 reviews) - 10 Sep 2003 17:11:15 GMT - Search in distribution CHOROBA/XML-XSH2-2.1.19 - 08 Jan 2015 20:50:47 OF INTERNALS In the previous parts we have seen how to use RayApp to write Web applications. Changes are that you will want to use RayApp serializer in other, non-Web projects. This part describes the internals of the framework. RayApp object To work...JANPAZ/RayApp-2.004 - 10 Apr 2006 13:01:11 GMT - Search in distribution - RayApp::DSD - Framework for data-centric Web applications - RayApp::Source - Framework for data-centric Web applications XML::Loy allows for the simple creation of small serialized XML documents with various namespaces. It focuses on simplicity and extensibility, while giving you the full power of Mojo::DOM. This module is an early release! There may be significant cha...AKRON/XML-Loy-0.40 - 26 May 2015 01:07:34 GMT - Search in distribution Provides access to the EOP definitions specified as XML schemas, based on GML. Up to version 1.0, these schemas where named 'HMA' (Heterogeneous EO Missions Accessibility), and the development is still part of these ESA efforts for standardization. B...MARKOV/Geo-EOP-0.13 - 29 Jan 2009 15:54:06 This script (and module) converts an XHTML file into DocBook, using both XSLT and heuristics (as XSLT alone can't do everything). This script will convert "*filename*.html" into "*filename*.xml" By default, the input file is expected to be correct XM...RUBYKAT/html2dbk-0.03 - 22 Mar 2006 07:03:17 GMT - Search in distribution - HTML::ToDocBook - Converts an XHTML file into DocBook. GMT - Search in distribution ATRICKETT/XML-RSS-Tools-0.34 - 27 May 2014 14:48:39 GMT - Search in distribution - XML::RSS::Tools - A tool-kit providing a wrapper around a HTTP client, a RSS parser, and a XSLT engine. FOXCOOL/WWW-Txodds-0.69 - 25 Oct 2013 12:52:30 GMT - Search in distribution module implements an interface to the information contained in a nikto scan. It is implemented by parsing the scan data using XML. This will enable anyone to utilizes nikto to quickly create fast and robust security tools for testing web applica...JABRA/Nikto-Parser-0.01 - 16 Oct 2009 19:59:49 GMT - Search in distribution This bundle contains all of Theory's most-used CPAN modules. These are essentials whenever he builds a new system....DWHEELER/Bundle-Theory-1.08 - 19 Jun 2011 04:45:49 GMT - Search in distribution
https://metacpan.org/search?q=XML-LibXML-Tools
CC-MAIN-2015-27
refinedweb
454
57.98
.46 eFTE eFTE is a lightweight, extendable, folding text editor geared toward the programmer. eFTE is a fork of FTE with goals of taking FTE to the next step, hence, Enhanced FTE pascal-webdev Old downloads stored here.11 weekly downloads Knave Bridge Scorer Duplicate bridge scoring software.8 Imager (perl) Imager is a module for manipulating image files from perl Francois's Game Library Francois's Game Library is an object-oriented library for 2D games. It attempts to cover basic techniques that are essential to the game but waste a lot of time in development. You tell the game what to do rather than how to do it.0 weekly downloads Francois's Thread System Francois offers a system of threads that come under complete control of the programmer and not the operating system. These provide flexible support in time critical operations that the operating system could not handle.0 Sausage Script Sausage Script is an internet scripting language aimed at CGI programming. It is fairly easy to use but has some of the weirdest syntax that you've probably never seen before. Perhaps it is time you try something new!0 weekly downloads Verilog Perl The Verilog-Perl distribution provides Perl preprocessing, parsing and utilities for the Verilog Language. It is also available from CPAN under the Verilog:: namespace.0 weekly downloads
http://sourceforge.net/directory/developmentstatus:production/os:windows/os:os_portable/license:artistic/
CC-MAIN-2014-35
refinedweb
225
56.15
CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary. CoNLL-U is often the output of natural language processing tasks. Note: As of conllu 4.0, Python 3.6 is required to install conllu. See Notes on updating from 3.0 to 4.0 pip install conllu Or, if you are using conda: conda install -c conda-forge conllu Conllu version 4.0 drops support for Python 2 and all versions of earlier than Python 3.6. If you need support for older versions of python, you can always pin your install to an old version of conllu. You can install it with pip install conllu==3.1.1. The Universal dependencies 2.0 release changed two of the field names from xpostag -> xpos and upostag -> upos. Version 3.0 of conllu handles this by aliasing the previous names to the new names. This means you can use xpos/upos or xpostag/upostag, they will both return the same thing. This does change the public API slightly, so I've upped the major version to 3.0, but I've taken care to ensure you most likely DO NOT have to update your code when you update to 3.0. I don't like breaking backwards compatibility, but to be able to add new features I felt I had to. This means that updating from 0.1 to 1.0 might require code changes. Here's a guide on how to upgrade to 1.0 . At the top level, conllu provides two methods, parse and parse_tree. The first one parses sentences and returns a flat list. The other returns a nested tree structure. Let's go through them one by one. from conllu import parse >>> data = """ # _ _ """ Now you have the data in a variable called data. Let's parse it: sentences = parse(data) sentences [TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .>]sentences = parse(data) sentences [TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .>] Advanced usage: If you have many sentences (say over a megabyte) to parse at once, you can avoid loading them into memory at once by using parse_incr()instead of parse. It takes an opened file, and returns a generator instead of the list directly, so you need to either iterate over it, or call list() to get the TokenLists out. Here's how you would use it: from io import open from conllu import parse_incr data_file = open("huge_file.conllu", "r", encoding="utf-8") for tokenlist in parse_incr(data_file): print(tokenlist) For most files, parseworks fine. Since one CoNLL-U file usually contains multiple sentences, parse() always returns a list of sentences. Each sentence is represented by a TokenList. 0] sentence TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .>sentence = sentences[ The TokenList supports indexing, so you can get the first token, represented by an ordered dictionary, like this: 0] token { 'id': 1, 'form': 'The', 'lemma': 'the', ... } token["form"] 'The'token = sentence[ filter()a TokenList 0] sentence TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .> sentence.filter(form="quick") TokenList<quick>sentence = sentences[ By using filter(field1__field2=value) you can filter based on subelements further down in a parsed token. "Pos") TokenList<quick, brown, lazy>sentence.filter(feats__Degree= Filters can also be chained (meaning you can do sentence.filter(...).filter(...)), and filtering on multiple properties at the same time ( sentence.filter(field1=value1, field2=value2)) means that ALL properties must match. filter()a TokenList by lambda You can also filter using a lambda function as value. This is useful if you, for instance, would like to filter out only tokens with integer ID:s: from conllu.models import TokenList, Token sentence2 = TokenList([ Token(id=(1, "-", 2), form="It's"), Token(id=1, form="It"), Token(id=2, form="is"), ]) sentence2 TokenList<It's, It, is> >>> sentence2.filter(id=lambda x: type(x) is int) TokenList<It, is> If you want to change your CoNLL-U file, there are a couple of convenience methods to know about. You can add a new token by simply appending a dictionary with the fields you want to a TokenList: "id": 1, "form": "Lazy"}, {"id": 2, "form": "fox"}, ]) sentence3 TokenList<Lazy, fox> sentence3.append({"id": 3, "form": "box"}) sentence3 TokenList<Lazy, fox, box>sentence3 = TokenList([ { Changing a sentence just means indexing into it, and setting a value to what you want: "id": 1, "form": "Lazy"}, {"id": 2, "form": "fox"}, ]) sentence4[1]["form"] = "crocodile" sentence4 TokenList<Lazy, crocodile> sentence4[1] = {"id": 2, "form": "elephant"} sentence4 TokenList<Lazy, elephant>sentence4 = TokenList([ { If you omit a field when passing in a dict, conllu will fill in a "_" for those values. "1 The") sentences[0].append({"id": 2}) sentences[0] TokenList<The, _>sentences = parse( Each sentence can also have metadata in the form of comments before the sentence starts. This is available in a property on the TokenList called metadata. 'text': 'The quick brown fox jumps over the lazy dog.' _ _sentence.serialize() You can also convert a TokenList to a TokenTree by using to_tree: 5, form=jumps}, children=[...]>sentence.to_tree() TokenTree<token={id= That's it! Sometimes you're interested in the tree structure that hides in the head column of a CoNLL-U file. When this is the case, use parse_tree to get a nested structure representing the sentence. from conllu import parse_tree sentences = parse_tree(data) sentences [TokenTree<...>] Advanced usage: If you have many sentences (say over a megabyte) to parse at once, you can avoid loading them into memory at once by using parse_tree_incr()instead of parse_tree. It takes an opened file, and returns a generator instead of the list directly, so you need to either iterate over it, or call list() to get the TokenTrees out. Here's how you would use it: from io import open from conllu import parse_tree_incr data_file = open("huge_file.conllu", "r", encoding="utf-8") for tokentree in parse_tree_incr(data_file): print(tokentree) Since one CoNLL-U file usually contains multiple sentences, parse_tree() always returns a list of sentences. Each sentence is represented by a TokenTree. 0] root TokenTree<token={id=5, form=jumps}, children=[...]>root = sentences[ To quickly visualize the tree structure you can call print_tree on a TokenTree. 5] (deprel:nsubj) form:fox lemma:fox upos:NOUN [4] (deprel:det) form:The lemma:the upos:DET [1] (deprel:amod) form:quick lemma:quick upos:ADJ [2] (deprel:amod) form:brown lemma:brown upos:ADJ [3] (deprel:nmod) form:dog lemma:dog upos:NOUN [9] (deprel:case) form:over lemma:over upos:ADP [6] (deprel:det) form:the lemma:the upos:DET [7] (deprel:amod) form:lazy lemma:lazy upos:ADJ [8] (deprel:punct) form:. lemma:. upos:PUNCT [10]root.print_tree() (deprel:root) form:jumps lemma:jump upos:VERB [ To access the token corresponding to the current node in the tree, use token: 'id': 5, 'form': 'jumps', 'lemma': 'jump', ... }root.token { To start walking down the children of the current node, use the children attribute: 4, form=fox}, children=[...]>, TokenTree<token={id=9, form=dog}, children=[...]>, TokenTree<token={id=10, form=.}, children=None> ]children = root.children children [ TokenTree<token={id= Just like with parse(), if a sentence has metadata it is available in a property on the TokenTree root called metadata. 'text': 'The quick brown fox jumps over the lazy dog.' _ _ ...root.serialize() If you want to write it back to a file, you can use something like this: from conllu import parse_tree sentences = parse_tree(data) >>> # Make some change to sentences here >>> with open('file-to-write-to', 'w') as f: f.writelines([sentence.serialize() + "\n" for sentence in sentences]) Far from all CoNLL-U files found in the wild follow the CoNLL-U format specification. CoNLL-U tries to parse even files that are malformed according to the specification, but sometimes that doesn't work. For those situations you can change how conllu parses your files. A normal CoNLL-U file consists of a specific set of fields (id, form, lemma, and so on...). Let's walk through how to parse a custom format using the three options fields, field_parsers, metadata_parsers. Here's the custom format we'll use. """ # tagset = TAG1|TAG2|TAG3|TAG4 # sentence-123 1 My TAG1|TAG2 2 custom TAG3 3 format TAG4 """data = Now, let's parse this with the the default settings, and look specifically at the first token to see how it was parsed. 0][0] {'id': 1, 'form': 'My', 'lemma': 'TAG1|TAG2'}sentences = parse(data) sentences[ The parser has assumed (incorrectly) that the third field must the the default ´lemma´ field and parsed it as such. Let's customize this so the parser gets the name right, by setting the fields parameter when calling parse. "id", "form", "tag"]) sentences[0][0] {'id': 1, 'form': 'My', 'tag': 'TAG1|TAG2'}sentences = parse(data, fields=[ The only difference is that you now get the correct field name back when parsing. Now let's say you want those two tags returned as a list instead of as a string. This can be done using the field_parsers argument. lambda line, i: line[i].split("|") sentences = parse(data, fields=["id", "form", "tag"], field_parsers={"tag": split_func}) sentences[0][0] {'id': 1, 'form': 'My', 'tag': ['TAG1', 'TAG2']}split_func = That's much better! field_parsers specifies a mapping from a field name, to a function that can parse that field. In our case, we specify that the field with custom logic is "tag" and that the function to handle it is split_func. Each field_parser gets sent two parameters: line: The whole list of values from this line, split on whitespace. The reason you get the full line is so you can merge several tokens into one using a field_parser if you want. i: The current location in the line where you currently are. Most often, you'll use line[i]to get the current value. In our case, we return line[i].split("|"), which returns a list like we want. Let's look at the metadata in this example. """ # tagset = TAG1|TAG2|TAG3|TAG4 # sentence-123 """ None of these values are valid in CoNLL-U, but since the first line follows the key-value format of other (valid) fields, conllu will parse it anyway: 0].metadata {'tagset': 'TAG1|TAG2|TAG3|TAG4'}sentences = parse(data) sentences[ Let's return this as a list using the metadata_parsers parameter. "tagset": lambda key, value: (key, value.split("|"))}) sentences[0].metadata {'tagset': ['TAG1', 'TAG2', 'TAG3', 'TAG4']}sentences = parse(data, metadata_parsers={ A metadata parser behaves similarily to a field parser, but since most comments you'll see will be of the form "key = value" these values will be parsed and cleaned first, and then sent to your custom metadata_parser. Here we just take the value, and split it on "|", and return a list back. And lo and behold, we get what we wanted! Now, let's deal with the "sentence-123" comment. Specifying another metadata_parser won't work, because this is an ID that will be different for each sentence. Instead, let's use a special metadata parser, called __fallback__. "tagset": lambda key, value: (key, value.split("|")), "__fallback__": lambda key, value: ("sentence-id", key) }) sentences[0].metadata { 'tagset': ['TAG1', 'TAG2', 'TAG3', 'TAG4'], 'sentence-id': 'sentence-123' }sentences = parse(data, metadata_parsers={ Just what we wanted! __fallback__ gets called any time none of the other metadata_parsers match, and just like the others, it gets sent the key and value of the current line. In our case, the line contains no "=" to split on, so key will be "sentence-123" and value will be empty. We can return whatever we want here, but let's just say we want to call this field "sentence-id" so we return that as the key, and "sentence-123" as our value. Finally, consider an even trickier case. """ # id=1-document_id=36:1047-span=1 1 My TAG1|TAG2 2 custom TAG3 3 format TAG4 """data = This is actually three different comments, but somehow they are separated by "-" instead of on their own lines. To handle this, we get to use the ability of a metadata_parser to return multiple matches from a single line. "__fallback__": lambda key, value: [pair.split("=") for pair in (key + "=" + value).split("-")] }) sentences[0].metadata { 'id': '1', 'document_id': '36:1047', 'span': '1' }sentences = parse(data, metadata_parsers={ Our fallback parser returns a list of matches, one per pair of metadata comments we find. The key + "=" + value trick is needed since by default conllu assumes that this is a valid comment, so key is "id" and value is everything after the first "=", 1-document_id=36:1047-span=1 (note the missing "id=" in the beginning). We need to add it back before splitting on "-". And that's it! Using these tricks you should be able to parse all the strange files you stumble into. Make a fork of the repository to your own GitHub account. Clone the repository locally on your computer: git clone git@github.com:YOURUSERNAME/conllu.git conllu cd conllu Install the library used for running the tests: pip install tox Now you can run the tests: tox This runs tox across all supported versions of Python, and also runs checks for code-coverage, syntax errors, and how imports are sorted. (Alternative) If you just have one version of python installed, and don't want to go through the hassle of installing multiple version of python (hint: Install pyenv and pyenv-tox), it's fine to run tox with just one version of python: tox -e py36 Make a pull request. Here's a good guide on PRs from GitHub. Thanks for helping conllu become a better library!
https://openbase.com/python/conllu
CC-MAIN-2021-39
refinedweb
2,269
64.1
X-Function, Execution in Origin C X-Function, Set Parameters in Origin C Origin comes with many X-Functions for handling a variety of tasks. X-Functions can be called from both LabTalk and Origin C. This Section will show you how to call X-Functions from Origin C using Origin C's XFBase classXFBase Class. This mechanism also can be used in calling one X-Function in another X-Function. The XFBase class is declared in the XFBase.h header file located in the <Origin exe folder>\OriginC\system\ folder. The XFBase.h header file is not included in the Origin.h header file and must be included separately in any Origin C file that uses the XFBase class. #include <XFBase.h> The following Origin C code defines a general function for importing files into Origin. The function takes two arguments: a data file name and an import filter file name. The function first creates an instance of the XFBase class, constructed with the name of the X-Function to be called. In this case, the X-Function name is impFile. It then sets the X-Function arguments using the SetArg method, and finally calls the X-Function using the Evaluate method. our call_impFile_XF function defined above. We will call it to import an image file. // Lets import the Car bitmap located in Origin's Samples folder. string strImageFile = GetAppPath(TRUE) + "Samples\\Image Processing and Analysis\\Car.bmp"; // Lets import the bitmap using the Image import filter. string strFilterFile = GetAppPath(TRUE) + "Filters\\Image.oif"; // Let's call our general function that will call the impFile X-Function. call_impFile_XF(strImageFile, strFilterFile); Calling X-Functions from Script
http://cloud.originlab.com/doc/X-Function/guide/Calling-X-Functions-in-Origin-C
CC-MAIN-2020-29
refinedweb
276
59.6
I want to have a program where the user have 10 seconds to enter the password. If the timer goes over 10 seconds, the program displays a message. My current code is this: #include <iostream> #include <ctime> #include <string> int main(){ std::string password; int start_s=clock(); int stop_s=clock(); if(stop_s-start_s <= 0){ std::cout << "TIME RAN OUT!"; } std::cout << "Enter your password! \n"; std::cout << "Password: "; std::cin >> password; std::cout << "\n \n"; if (password == "password123"){ std::cout << "Correct!"; } else { std::cout << "Wrong!"; } } What you are trying to do is to have an non-blocking (asynchronous) read from stdin with a timeout of 10 seconds. This is not too tough but may involve many new concepts depending on your knowledge. What we need to do is: In linux, the watch-list can be handled using FD_SET and a select system call. In Windows, you will need to use WaitForMultipleEvents. I'm not sure I can do justice to explaining these concepts accurately for the purposes of this code. As a reference, another question which has some code pointers for exactly the same thing is here.
https://codedump.io/share/scSqWgYPqMCD/1/timing-allow-input-in-c
CC-MAIN-2017-47
refinedweb
187
73.88
martinvonz added a comment. Advertising In, @martinvonz wrote: > In, @yuja wrote: > > > It seems incorrect to me to catch LookupError of `node` returned by > > a namespace API, not by a user-specified node value. > > > The idea wasn't to catch those from the namespace API, but from changelog.rev() just after. The overly broad catching has bothered me before, so let me fix that and split this patch up. Actually, thinking more about, I think we should not even catch LookupError, so I ended up just deleting these lines. Thanks for making me check. > > >> I think the reason why catching `RepoLookupError` here was that >> we historically used `repo.branchtip(changeid)`. > > Ah, thanks for the information. REPOSITORY rHG Mercurial REVISION DETAIL To: martinvonz, #hg-reviewers, yuja Cc: yuja, mercurial-devel _______________________________________________ Mercurial-devel mailing list Mercurial-devel@mercurial-scm.org
https://www.mail-archive.com/mercurial-devel@mercurial-scm.org/msg28227.html
CC-MAIN-2018-17
refinedweb
138
50.23
26 October 2011 21:07 [Source: ICIS news] WASHINGTON (ICIS)--?xml:namespace> David Crowe, chief economist at the National Association of Home Builders (NAHB), said “new home and existing home sales will finally begin to pick up – but not soon”. Speaking at the association’s semi-annual housing sector outlook and forecast, Crowe said before the industry begins a recovery in 2012, this year will see a new record low of new and existing home sales. “We thought that 2009 would stand as the lowest on record, but it appears that 2011 will establish a new bottom,” he said. He said he expected the housing market to continue flat for the next couple of quarters “before we start to see some recovery in 2012, led by some scattered markets around the country, and then get stronger into 2013”. That forecast reflects a change in the association's market expectations in just six months. In the group's last semi-annual outlook in April this year, Crowe had forecast a turnaround in new home demand and construction in the second half this year. But that projected recovery has been pushed back to around mid-2012, Crowe indicated on Wednesday. “It will be a long road back to normal for single-family housing starts,” he said, adding the anticipated recovery will be spotty, doing better in some states than in others, before reaching a near-normal pace by the fourth quarter of 2013. In normal economic times, the In housing data issued by the Commerce Department earlier on Wednesday, US sales of new single-family homes were at an annualised pace of 313,000 in September. (€10,800) worth of chemicals and derivatives used in the structure or in production of component materials. Crowe said he expects the home building sector will begin to see some recovery in 2012 because the US economy is expected to show “slight but continuing improvement beginning in this current quarter and continuing into 2012 and on into 2013”. In addition, he said a backlog of household formations should begin to flow into the housing market as the economy slowly picks up. He said data indicate that 1m to 2m household formations have been postponed over the course of the recent recession, and once the economy shows better strength, those 30-somethings that have been living with their parents or sharing apartments will begin to move into the home-buying market. ($1 = €0
http://www.icis.com/Articles/2011/10/26/9503195/us-housing-will-hit-new-low-this-year-before-slow-recovery-in-12.html
CC-MAIN-2013-48
refinedweb
406
51.62
Hi, You may find this useful, in short words, I needed to ensure that the workbooks were up to date, and even make them part of integration tests and acceptance tests. So I use the execution code as part of unit tests. I cannot post links, so this the extract of a blog post: Extracting and executing all the code from the workbooks Workbooks mainly execute each of the code elements one by one using the Roslyn scripting engine. So if we extract all the code sections from the Markdown document, we can execute them inside of our unit test in the same way. var code = GetCodeSectionsFromWorkbook(); var state = await CSharpScript.RunAsync(code); The beauty of this, is that the code will be using the current project, library, nuget reference in our project, which will be the latest. Executing the code can be fine, but how do we validate the results? state = await state.ContinueWithAsync(“return (balanceSecondAmountSend, originalBalanceFirstAmoundSend);”); I did not want to mix testing with the documentation, so a simple way to validate the data is to return all the variables that we want to Assert using the new multiple return capability in c#7. Once we know the variable names, we can just add them to the script to be the final return statement. Finally, we can cast the returned tuple as a dynamic type and assert each of the returned values in order. var returnValue = (dynamic) state.ReturnValue; Assert.Equal(2000, returnValue.Item1); Assert.Equal(1000, returnValue.Item2);” For a full code sample checkout in github.com "Nethereum/Nethereum.Workbooks" , or in medium the full blog post medium.com "@juanfranblanco/unit-or-integration-tests-of-xamarin-workbooks-6f206b8483d6" J @JuanBlanco very interesting! Here's a working link to your blog post: We internally have had some hacks on top of Workbooks that have tested our regression suite of workbook content, but it was pretty messy. In the 1.4 series of releases we will be more formally productizing this behavior through the new console client - you'll be able to run workbooks directly in the console. I will post more details on how to use it when we have made the release!
https://forums.xamarin.com/discussion/106464/unit-testing-workbooks-and-making-them-part-of-the-development-lifecycle
CC-MAIN-2019-30
refinedweb
365
53.41
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series. As you may or may not remember (it's taking a while, after all), the immediate purpose is to use the limited s-expression part of the parser to ferret out the first batch of problems standing beween us and fully self-hosting the compiler. For that purpose, I've now put together a tiny test driver and the minimal dependencies of the s-expression parser, and this part we will look at 1) changes to reduce coupling (which means we're cheating by delaying certain types of fixes by moving the troublesome code out of the immediate dependencies of the s-expression parser) and 2) changes to make that code compile, and hopefully even run. I'll give you a spoiler right now, and tell you that at the end of this there will be at least one more roadblock: Implementing dynamic method dispatch (looking up a method by name for #send). At the time of writing I don't know if that will be the only outstanding issue (probably not), but it's most likely the biggest of the remaining issues to get the s-expression parser to work by itself, since call parser methods by name. (Whether or not it's a good idea to do that is another matter, but for now it'll stay since we need to cover that bit anyway). An immediate problem presented itself when trying to compile code that require'd other code expecting a different load path. I'm not quite reading to start dealing with the pain (in terms of ahead-of-time, semi-statically) compiling code that dynamically messes with $:, but adding options to set the load path, and improving/fixing some of the path issues with the current implementation of require, as well as improving the option passing in the driver code seems like a good idea. Time to start cleaning up the driver for the compiler ever so slightly. In 91aa84d I started by making the driver bail out without trying to assemble if the compilation fails, as that's been driving me crazy for a while. In 4b62af4 I added slightly better load/include path handling. In driver.rb, I added support for "-I" to indicate the initial include path (we do not support $: etc. yet). That is supported in parser.rb by quite straight forward code to mangle the paths and identify the actual files as needed, and to ensure the core library still loads. What was revealed once I added the above, was that I took too many shortcuts for resolving Foo::Bar back in part 41: ./compiler.rb:199:in `compile_deref': Unable to resolve: Scanner::ScannerString statically (FIXME) (RuntimeError) from ./compiler.rb:540:in `compile_exp' from ./compiler.rb:114:in `get_arg' from ./compiler.rb:370:in `compile_eval_arg' We're going to attack this first by improving the debugging of symbol table content. In a8b23a9 I added the --dumpsymtab option, which makes use of new #dump methods added to Scope with specializations for GlobalScope and ClassScope in debugscope.rb, which recursively processes the symbol table. What that that revealed was the result of the ugly shortcut of conflating the low level output of assembler level symbols with Ruby-level constant nesting, as a result of hacking our way through this without a detailed up front design. Thankfully that's not all that hard to fix at this stage - we already did the most important work with the introduction of build_class_scopes in part 41, which ensures that the right information is available - that's what made the --dumpsymtabs option easy to provide. All we need to do is to actually look up what we should be looking up: the name of the inner constant, instead of the synthetic assembly level name, so that it is found in the scope chain instead of ending up being forwarded all the way up to GlobalScope (which still has the ugly synthetic variable name - that needs to go eventually, and not be exposed to Ruby). In ClassScope (in e4eafcc) : def find_constant(c) const = @constants[c] return const if const - return @next.find_constant(@name+"__"+c.to_s) if @next + return @next.find_constant(c) if @next return nil end While doing a global looking in compiler.rb we'll actually look up these ugly compound names for now, and then add them to the list (e4eafcc) : + prefix = scope.name + aparam = prefix + "__" + aparam.to_s if !prefix.empty? @global_constants << aparam For now we're just stubbing it out, together with protected. See f0dfb45 which basically just adds them without doing anything of substance... Now to the big one for this round. The remaining other issues I dealt with for this part all fell out of addressing the splat handling. This is one of the long-standing tensions between efficiency and getting required Ruby functionality. This does what you'd expect with MRI, of course: def foo *args puts "Length:" puts args.length puts "Members:" puts args[0] puts args[1] puts args[2] end foo(1,2,3) But on entering foo at the moment, args is a c-style array. It works if we dip into the s-expression syntax: def foo *args puts "Length:" %s(callm self puts ((__get_fixnum numargs))) puts "Members:" %s(callm self puts ((index args 0))) %s(callm self puts ((index args 1))) %s(callm self puts ((index args 2))) end foo(1,2,3) (never mind that it outputs a length of 5 - that reflects self and space for a pointer to a block). To handle this, we need to add support for turning args into an actual Ruby array. There's a wrinkle: So far we've used this as a shortcut for quickly pushing members onto the call stack if we subsequently turn around and call another method with it. Either we need to continue supporting that (it will be sufficient if the second example above still works, but there are other alternatives) One solution is to allocate arguments in a Ruby array, but that has terrible overhead, and complicates interoperability with C. Another is to allocate a Ruby Array in the method, optionally using some method to determine if the array is likely to be used. For now, I have chosen to add code in the method to convert splat arguments to a real Ruby array, and to take the pain of rewriting code that used index/numargs on splat arguments. A problem which instantly materialize is that calling Class#new can not directly or indirectly require calls to Class#new in order to complete. If it does, we get infinite recursion, obviously (or rather, recursion until we run out of stack). Unfortunately this is tricky: Class#new currently uses a splat argument, which in the most obvious naive implementation of turning splat arguments into a real Ruby Array itself triggers a Class#new call (in the form of Array.new). Array#initialize further assigns Fixnum'a to instance variables, and this too triggers Class#new to instantiate said Fixnum's. We either needs to shortcircuit this in the case of an empty splat array, and add a way of constructing an empty Array, or find some other way of short-circuiting this recursion. (We're going to deal with the fallout of figuring out a more reasonable ordering of the bootstrapping of the core classes for some time to come). You'll find this entire change in d9ac43d75 I'm not going to go over every tiny little bit, but let's examine the most important pieces. First of all, this is a bit on the sidelines, but a major reason to complete the splat support was to handle literal arrays. There's now a new method Compiler#compile_array to handle that simply by turning them into Array[] calls: + # Compile a literal Array initalization + # + # FIXME: An alternative is another "transform" step + # + def compile_array(scope, *initializers) + compile_eval_arg(scope, + [:sexp, + [:callm, :Array, :[], initializers] + ]) + return Value.new([:subexpr], :object) + end Next, in transform.rb the work starts by modifying methods with splat arguments. First we rename the argument to __splat (at some point I'll probably change this to hide them from the Ruby code entirely): + rest = e[2][-1] rescue nil + rest = (rest[-1] == :rest ? rest[0] : nil) rescue nil + if rest + e[2][-1][0] = :__splat + end + Then we introduce a new local variable (hence the location of this transformation rule in rewrite_let_env) with the original name of the argument, and assign the result of a call to __splay_to_Array_ to it: - e[3] = E[e.position,:let, vars,*e[3]] + if rest + vars << rest.to_sym + rest_func = + [:sexp, + [:assign, rest.to_sym, [:__splat_to_Array, :__splat, :numargs]] + ] + else + rest_func = [] + end + + e[3] = E[e.position,:let, vars, rest_func,*e[3]] One immediate thing is worth observing: We could certainly defer this call as long as possible, to hope to avoid the conversion in e.g. cases of early return. At some point that will be worth exploring, but note also that this could/should fall out automatically if we later add suitable optimization passes. For now it's by far easiest to just put it at the beginning of the method. This of course means we need to implement __splat_to_Array: +%s(defun __splat_to_Array (r na) + (let (splat pos data max) + (assign splat (callm Array __new)) + (assign pos 0) + (assign max (sub na 2)) + (callm splat __grow (max)) + (while (lt pos max) + (do + (callm splat __set (pos (index r pos))) + (assign pos (add pos 1)) + ) + ) + splat + )) + This is roughly equivalent to (pseudo-Ruby): def __splat_to_Array(r na) # na is "numargs"; r is the c-style splat array. splat = Array.__new pos = 0 max = numargs - 2 # Subtract two for "self" and a &block argument we always allocate space for splat.__grow(max) while pos < max splat.__set(pos, r[pos]) pos += 1 end end There are a few odd things here. For starters, we do this using the s-expression syntax because nearly "everything" otherwise would potentially trigger attempts to allocate objects, and Class#new uses splats. This also means we can't use Class#new, as discussed above. So I've introduced Class#__new as a lower level method that you should never-ever use in Ruby code (and which we'll find some way of hiding later). I also had to modify Array extensively to avoid even using Fixnum's, since we're for the time being at least using objects rather than type-tagged integers. The rest pretty much falls out of that. Class#__new and Class#__alloc (used by Class#__new) looks like this: + # Clients that need to be able to allocate a completely clean-slate empty + # object, should call <tt>__alloc</tt>. + # + def __alloc + %s(assign ob (__array @instance_size)) + %s(assign (index ob 0) self) + ob + end + # Clients that want to be able to create and initialize a basic version of + # an object without normal initializtion should call <tt>__new</tt>. See + # <tt>__splat_to_array</tt> + # + def __new + ob = __alloc + ob.__initialize + ob + end These should be pretty self-explanatory. Note that the new Class#new calls __alloc, but not __initialize. A very basic initial version of Array is now first introduced in lib/core/core.rb. It needs to be introduced that early for bootstrapping reasons, since it needs to exist when Class#new is first called. This showcases __initialize: +class Array + # __get_fixum should technically be safe to call, but lets not tempt fate + # NOTE: The order of these is important, as it is relied on elsewhere + def __initialize + %s(assign @len 0) + %s(assign @ptr 0) + %s(assign @capacity 0) + end + + #FIXME: Private; Used by splat handling + def __len + @len + end + + def __ptr + @ptr + end And here's __grow that's used internally to ensure the Array is big enough. Normally it should not be called directly, but we make an exception for the splat code: + def __grow newlen + # FIXME: This is just a guestimate of a reasonable rule for + # growing. Too rapid growth and it wastes memory; to slow and + # it is, well, slow to append to. + + # FIXME: This called __get_fixnum, which means it fails when called + # from __new_empty. May want to create new method to handle the whol + # basic nasty splat allocation + # @capacity = (newlen * 4 / 3) + 4 + %s(assign @capacity (add (div (mul newlen 4) 3) 4)) + + %s(if (ne @ptr 0) + (assign @ptr (realloc @ptr (mul @capacity 4))) + (assign @ptr (malloc (mul @capacity 4))) + ) + end And __set is a low level method to assign to the array and extend, that makes assumptions we can't safely make in general (that is, it expects an expansion by at most one element at a time. Frankly rewriting __splat_to_Array to set length once and omit it here would probably be worth it, but some other time: + #FIXME: Private. Assumes idx < @len && idx >= 0 + def __set(idx, obj) + %s(if (ge idx @len) (assign @len (add idx 1))) + %s(assign (index @ptr idx) obj) + end + +end + Most of the rest of the changes, apart from compile_calls.rb, are changes to the library code (particularly Array to accommodate the splat handling changes and/or take advantage of them). compile_calls.rb, though has seen a huge rewrite. Rather than go through the diff, it's easier to walk through the new version. Both method and our "c-level" function calls now use the same method-chanin to push arguments onto the stack. It starts with this: def compile_args(scope, ob, args, &block) @e.caller_save do splat = args.detect {|a| a.is_a?(Array) && a.first == :splat } if !splat compile_args_nosplat(scope,ob,args, &block) else compile_args_splat(scope,ob,args, &block) end end end The "nosplat" case is simple, and pretty much what we used to do: def compile_args_nosplat(scope, ob, args) @e.with_stack(args.length, true) do @e.pushl(@e.scratch) args.each_with_index do |a, i| param = compile_eval_arg(scope, a) @e.save_to_stack(param, i + 1) end @e.popl(@e.scratch) yield end end The tricky bit is the splat handling, which I'm by no means happy with, and it will probably need significant simplification: def compile_args_splat(scope, ob, args) # Because Ruby evaluation order is left to right, # we need to first figure out how much space we need on # the stack. # # We do that by first building up an expression that # adds up the static elements of the parameter list # and the result of retrieving 'Array#length' from # each splatted array. # # (FIXME: Note that we're not actually type-checking # what is *actually* passed) # num_fixed = 0 exprlist = [] args.each_with_index do |a, i| if a.is_a?(Array) && a[0] == :splat # We do this, rather than Array#length, because the class may not # have been created yet. This *requires* Array's @len ivar to be # in the first ivar; # FIXME: should enforce this. exprlist << [:index, a[1], 1] else num_fixed += 1 end end expr = num_fixed while e = exprlist.pop expr = [:add, e, expr] end @e.comment("BEGIN Calculating argument count for splat") ret = compile_eval_arg(scope, expr) @e.movl(@e.result, @e.scratch) @e.comment("END Calculating argument count for splat; numargs is now in #{@e.scratch.to_s}") The comments in the part above hopefully speaks for itself. For e.g. foo(*a, b, *c) it basically does the equivalent of a.length + c.length + n where n is the number of non-splat arguments. Next we save the count we found, and then allocate space on the stack: @e.comment("Moving stack pointer to start of argument array:") @e.pushl(@e.scratch) # We assume this may get borked during argument evaluation @e.imull(4,@e.result) # esp now points to the start of the arguments; ebx holds numargs, # and end_of_arguments(%esp) also holds numargs @e.subl(@e.result, :esp) Then we start at the bottom of the allocated stack segment, and evaluate arguments and save the result, working our ways up the stack, except if we find a splat argument, we call compile_args_copysplat to take care of that: @e.comment("BEGIN Pushing arguments:") @e.with_register do |indir| # We'll use indir to put arguments onto the stack without clobbering esp: @e.movl(:esp, indir) @e.pushl(@e.scratch) @e.comment("BEGIN args.each do |a|") args.each do |a| @e.comment(a.inspect) if a.is_a?(Array) && a[0] == :splat compile_args_copysplat(scope, a, indir) else param = compile_eval_arg(scope, a) @e.save_indirect(param, indir) @e.addl(4,indir) end end @e.comment("END args.each") @e.popl(@e.scratch) end @e.comment("END Pushing arguments") Then we yield to handle the actual call for various types of calls, and then adjust the stack: yield @e.comment("Re-adjusting stack post-call:") @e.imull(4,@e.scratch) @e.addl(@e.scratch, :esp) end That leaves compile_args_copysplat: # For a splat argument, push it onto the stack, # forwards relative to register "indir". # # FIXME: This method is almost certainly much # less efficient than it could be. # def compile_args_copysplat(scope, a, indir) @e.comment("SPLAT") @e.with_register do |splatcnt| param = compile_eval_arg(scope, a[1]) @e.addl(4,param) @e.load_indirect(param, splatcnt) @e.addl(4,param) @e.load_indirect(param, :eax) @e.testl(:eax,:eax) l = @e.get_local Notice the ugliness that comes next: We need to sort-of the case where the Array class itself simply hasn't been created yet at all (which will only "work" if the splat arguments in question are not actually used): # If Array class ptr has not been allocated yet: @e.je(l) I really hope there's a nicer/cleaner/faster way of doing this, but what's driving me crazy below is the addressing modes for x86. For m68k, you can get away with some indirect gymnastics which makes stuff like this far simpler: @e.loop do |br| @e.testl(splatcnt, splatcnt) @e.je(br) # x86 will be the death of me. @e.pushl("(%eax)") @e.popl("(%#{indir.to_s})") @e.addl(4,:eax) @e.addl(4,indir) @e.subl(1,splatcnt) end @e.local(l) end end I'm sure there are better ways of doing it for x86 too (and certainly for x64; one day we'll get around to doing a 64-bit backend). And that's it. This brings me to the point where the main obvious hindrance (I'm sure others will pop up) is the lack of proper support for send, and so that is what I'll cover in part 45.
https://hokstad.com/compiler/44
CC-MAIN-2021-21
refinedweb
3,080
60.65
Anil Dhawan - Look at Bluetooth programming on Windows Mobile - Posted: Feb 17, 2005 at 5:29 PM - 140,699 play around with that code-- is there somewhere you can post it? John Nice video, is it possible to transform my smartphone to a Remote Car Starter?. The MS stack is more common on Smartphones and a number of the newer Pocket PC Phone Edition devices. However the big players in the traditional Pocket PC space - HP, Dell etc use Widcomm. On Windows Mobile the MS stack supports SerialPort, ObjectPush, Dun, Headset/Handsfree profiles On Windows XP:- SerialPort, ObjectPush, Dun, Panu, HardCopyCableReplacement (Printing), HID (Keyboard/Mouse) Peter I should have been clearer ObjectPush is OBEX. There are two OBEX profiles in the Bluetooth specification - ObjectPush which is used to send a file to another device - used to send a contact for example. The other is OBEX FTP where the device can host an FTP style filestore which other devices can browse and download from. This is available in the Bluetooth modules for CE.NET 4.2 but not included in Windows Mobile. You can host your own OBEX FTP service if you process the appropriate OBEX headers e.g. using a BluetoothListener. The Widcomm stack has support for this profile and offers both the ability to share files in this way and a browser application to view files on a remote device. Peter Anyone know any (cheap ;p, yeah I'm a student) windows enables phones in Holland? It is possible to implement an OBEX FTP service in managed code on the Microsoft stack. In testing I was able to receive and respond to connection requests, what I haven't done though is wrapped all the OBEX commands, but they are documented in the Bluetooth spec. One of my Blog readers put together a working sample on the OBEX Push side but it illustrates how OBEX packets are used - Peter Can you please post C++ code you were showing in your demo? Thanks MSx86 Hi, I am interested in getting the c++ code.. Can somebody please post the code which Anil showed in his demo (c++) version? Thanks in advance... By the way, looking at Anil's code: - is anyone out there who would know how to simulate a LONG press of the "Hook Up" (VK_F3) key on the Smartphone, so that the Speakerphone gets started? keybd_event() is OK to take the hook off, but it won't launch speakerphone mode. Is there some other way to programmatically activate Speakerphone mode? I'm writing an app that enables the physically handicapped to operate a smartphone. Thanks for a hint Phil Peter Which seems strange. Looking at the way the Keyboard drivers are implemented, even they rely on keybd_event. If one starts a KeyTracker program, the VK_F3 gives you nothing on pressing the key, but fires a KEYUP and a KEYDOWN on releasing it. If one holds it down LONG, it won't give you anything at all, unless a call is active. In that case, it launches Speakerphone mode. Strange but true... I have asked this question so many time. But this forum is very slow. I will repeat my request again. Can somebody post the VC++ code and the c# version of the same code? Thanks MSx86 Hi Did you manage to get the code? If so can I have it? Thanks Nandu, I haven't received the code and I am still waiting. MSx86 Nandu hey I am also interested in the code please if anybody recives it post it to me my email is sultan.alsharfi@gmail.com I'm afraid I can't help with the eVC++ code mentioned in the video, but a close equivalent in C# is available here:- Peter can you please point me some online tutorial/manual or some literature that can help me with bluetooth programming ? I'm a newbie to Windows Mobile programming so any hints or recommendations will be appreciated. Thanks I have a working library built around sockets which works on both desktop and Windows CE (Microsoft stack only) you can download the source and a sample chat application for each platform from this blog entry:- Peter Assuming you are talking about .NETCF development you'll find everything required in this package:- Including source (C#), sample projects, class documentation. It also closely follows the IrDa classes in .NETCF so should be easy to pickup. It'll work on XP or Windows CE/ Windows Mobile so long as you are using the Microsoft stack (not from a third-party such as Broadcom). Peter If you are interested in learning more about Bluetooth on Windows Mobile, swing by my blog at: . Where is a good source of information for a developer who wants to develop at a lower level using Bluetooth on WM5? I am actually working on a project that detects when a paired BT device is NOT in range and I am getting seriously stuck and having a difficult time finding viable resources. I saw this video for creating bluetooth applications. It's very nice. I have couple of questions which are different from your sample. I have a simple requirement in Windows Mobile(Pocket PC 4.x, 5.x) Bluetooth. The aim is to find if a paired bluetooth device is nearby(within range). I thought I could write a simple Winsock application to do it. Basically do a service discovery. But the problem is the Querry set gives me only the name in "lpszServiceInstanceName". I would like to get the Mac id (uniqure bluetooth id) for the device I discovered. 1. Could you please let me know how I can get it?. Else 2. If I know the mach id of the paired device (I can get it from the registry), How can I directly inquire if this device is deiscoverable or not? This is to avoid SDP. Note : I don't have a connection to this device. I just have a pairing. So i won't be able to use winsock "connect" calls since they require a port (channel 1 -32) or Service specific UUID. I don't have both since I am just trying to find if a paired device is within range. 3. Another "MAJOR" problem is Some(lot I hope you can give me some suggestions. Thanks very much Ganesan That was a fantastic demo... I was just trying to know that does Windows CE has any AT command handler so that you can connect any headset to ur notebook or PC... in the sense an Audio Gateway regards Soumya 1.- The "Server side" or the laptop side of the app is a service waiting for signals sent by the bt smartphone? or a simple wile(true) kind of code? 2.- I dont have a smart phone, but i do have a Pocket PC, BUT it has windows Mobile 2003 se, i guess Serial ports programming should work aswell on my device...that wrapper for bluetooth programming that you made its ONLY for WM 5.0? 3.- is there a bluetooth api for windows mobile 2003 that i could use, or i should just stay with com ports?, plus i dont think my Dell Axim X50 runs windows bluetooth stack to use openetCF. thanks it was built on: eVC++ 4.0 SP2 + windows mobile 2003 sdk running on Pocket PC Dell Axim X50. Visual Studio 2005 (c++) running on my laptop with a bluetooth dongle. -----------------------PPC portion: HANDLE fileHandle; int OpenSerialPort(); int CloseSerialPort(); int ProcessKey(const int key); void ConfigureSerialPort() { COMMPROP commProp; memset(&commProp, 0, sizeof(COMMPROP)); GetCommProperties(fileHandle, &commProp); DCB commDCB; BOOL fSuccess = FALSE; memset(&commDCB, 0, sizeof(DCB)); if(GetCommState(fileHandle, &commDCB)) { if(commProp.dwSettableParams && SP_BAUD) { commDCB.BaudRate = BAUD_9600; commDCB.fParity = PARITY_NONE; commDCB.StopBits = ONESTOPBIT; commDCB.ByteSize = 8; fSuccess = SetCommState(fileHandle, &commDCB); } } if(!fSuccess) MessageBox(NULL, TEXT("Could not modify the port's settings"), TEXT("Error!"), MB_OK); } int OpenSerialPort() { if (fileHandle == NULL){ fileHandle = CreateFile(_T("COM7:"), GENERIC_WRITE ,0,NULL,OPEN_EXISTING,0,NULL); if (fileHandle == INVALID_HANDLE_VALUE){ MessageBox(NULL,L"No se pudo crear el COM 7",L"Aviso",MB_OK); fileHandle = NULL; return 0; } } ConfigureSerialPort(); return 1; } int CloseSerialPort() { if (fileHandle != NULL){ CloseHandle(fileHandle); fileHandle = NULL; return 1; } return 0; } int ProcessKey(const int key) { DWORD numwritten = 0; if ((key >= 37 && key <= 40) || (key == 13)) { WriteFile(fileHandle,&key,sizeof(key),&numwritten,NULL); } return 1; } //WINAPI STUFF..... in this next method LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) //add the this code. case WM_KEYUP: lResult = ProcessKey(wParam); break; ----------------------------------------PC portion: #include <stdio.h> #include <windows.h> //conection to Serial PORT HANDLE fileHandle; /* Methods */ int OpenSerialPort(); int ConfigureSerialPort(); int CloseSerialPort(); void SendKey(const BYTE vKey); int ReadMsg(); //Open it up int OpenSerialPort() { WCHAR comPort[30]; wsprintf(comPort,L"COM%d",8); if (fileHandle == NULL) { fileHandle = CreateFile(comPort, GENERIC_READ,0,0,OPEN_EXISTING,0,0); if (fileHandle == INVALID_HANDLE_VALUE) { printf("ERROR: Cant open port [%s]\n",comPort); fileHandle = NULL; return 0; } } printf("PUERTO [%s] CREATED!\n",comPort); //configure port ConfigureSerialPort(); return 1; } //Configurar el Puerto Serial int ConfigureSerialPort() { DCB dcb; FillMemory(&dcb,sizeof(dcb),0); dcb.DCBlength = sizeof(dcb); WCHAR buffer[100]; wsprintf(buffer,L"baud=9600 parity=N data=8 stop=1"); if (!BuildCommDCB(buffer,&dcb)){ printf("\tERROR: No se pudo crear DCB!\n"); return 0; } printf("\tDCB HECHO!\n"); if (!SetCommState(fileHandle,&dcb)){ printf("\tERROR: No se pudo cambiar el estado del Puerto COM\n"); return 0; } printf("\tESTADO del COM SET!\n"); if (!SetupComm(fileHandle,1024,1024)){ printf("\tERROR: No se pudo SET la cola a 1024\n"); return 0; } printf("\tBT Stack Ready!\n"); COMMTIMEOUTS cmt; cmt.ReadIntervalTimeout = 1000; cmt.ReadTotalTimeoutMultiplier = 1000; cmt.ReadTotalTimeoutConstant = 1000; cmt.WriteTotalTimeoutConstant = 1000; cmt.WriteTotalTimeoutMultiplier = 1000; if (!SetCommTimeouts(fileHandle,&cmt)){ printf("\tERROR: No se pudo SET los timeouts al COM"); return 0; } printf("\tTimeouts SET!\n"); printf("............................................................\n"); return 1; } //Cierre del Puerto COM int CloseSerialPort() { if (fileHandle != NULL){ CloseHandle(fileHandle); fileHandle = NULL; printf("COM PORT CERRADO\n"); return 1; } return 0; } //Enviar las teclas al computador void SendKey(const BYTE vKey) { keybd_event(vKey,0,0,0); keybd_event(vKey,0,KEYEVENTF_KEYUP,0); } //Lectura de los mensajes que llegan por el puerto COM int ReadMsg() { unsigned int * dataBuff = new unsigned int[100]; DWORD numRead = 0; //lee 4 bytes desde COM8 al buffer ReadFile(fileHandle, dataBuff, 4, &numRead, NULL); //obtengo el valor real desdeel buffer int val = dataBuff[0]; printf("key: %d",val); switch(val) { case 13: //enter SendKey(0xA8); break; case 37: //izq SendKey(VK_LEFT); break; case 38: //arriba SendKey(VK_UP); break; case 39: //der SendKey(VK_RIGHT); break; case 40: //abajo SendKey(VK_DOWN); break; default: break; } return 0; } int main (int argc, char** argv) { if (!OpenSerialPort()) return -1; //replace it with a nice thread while (!ReadMsg()); CloseSerialPort(); system("pause"); return 1; } I Hope it works and that you all can use it, send me an email if you want the whole proyects,, (hoofmen@hotmail.com) cheers! I'd also like to know how all the classes work together. I have been looking at the code for days and got nothing. In that video, Anil creates an object called btsCore of type Core. He uses the namespace "BluetoothSystem" which I cannot find anywhere. The methods he uses are similar to those at the Windows Embedded Source Tools for Bluetooth technology ( ) but they aren't the same. All I want to be able to do is establish a simple connection using the SPP to transfer some data using C#, thats all, nothing more. Everyone seems to ask for help on forums and nobody ever seems to get any. Anil, if you can read this, please point us in the right direction...you seem to be the only soul out there who knows anything about this topic. I would GREATLY appreciate it. P.S. I am a design engineer at Rockford Fosgate and maybe we can barder some tech support for audio equipment I totally recommend you to use 32feet.net wrapper for programming over bluetooth, i have been trying the other libraries and none of them are as simple as this one, oh also opennetcf its good. i am also frustrated about finding bluetooth programming help, Anil seems to be too busy to answer questions even when in most videos he advertises channel9 to be a place in where you get to talk to him. What really gets me is that the Embedded Shared Library looks pretty simple but has fundamental flaws like requesting an 8-byte Bluetooth address!! I mean if they need and extra 2 bytes for interoperability with some other function, then they need to document the format of those 8 byts in their code like... bt_addr[0 ~ 5] Bluetooth address bytes bt_addr[6] 0xNN bt_addr[7] 0xNN where 0xNN describes XXXXXX I'd assume that they do realize the BT address is only 6 bytes, so those extra 2 must do something! It's frusterating to troubleshoot this type of stuff when there's not enough documentaion. maybe you know, In the BluetoothEndpoint class, when you create a socket and you pass the BT address and GUID, does it need to use the serialize method and join the data? If so, the serialize function is screwed up too because of the 8 byte address. I tried looking for the documentation of the socketaddress to see if it was correct but I can't find anything. Looking over the info at 32feeet.net makes me want to cry...it looks sooooo easy with their tools. Why can't they work with VS2005???? [C] [edit] After looking deeper into that site, there may be some hope in using 32feet with VS2005 as long as I only write PPC applications (which is all I need anyways) both apps using 32 feet lib, when you download the library there are many examples that come with the visual studio solution file (version 8, that is VS 2005). I al so have no idea why those 2 extra bytes, maybe is a hamming code for validation if you have more advanced questions talk to peter foot, he is the author for the 32feet lib, and he does replies to emails. good luck These tools are wonderful, thanks for the info, which led me to continue this avenue! I've come up with a software for all of this, while I was looking last year for some ways for using bluetooth to remote control applications After all, bluetooth is like any other transport Mostly in C# on Mobile side, full C# on server side. See: To check it I am in a big mess and hope to get some help from here.The scenario is i need to develop a mobile 5.0 application in visual studio.net which will enumerate list of paired bluetooth devices.It have a bluetooth dongle connected to my desktop it uses widcomm stack.I need to test the application on the emulator as i dont have a pocket pc at the moment.I downloaded the Windows Embedded Source Tools for Bluetooth Technology tried the Tutorial # 1 available on the following URL When i deploy the application on the pocket pc emulator i get the following error - 'Error closing Key : registry exception was unhandled A first chance exception of type 'Microsoft.WindowsMobile.SharedSource.Utilities.Registry.RegistryException' occurred in Microsoft.WindowsMobile.SharedSource.Bluetooth.dll' I really dont know what to do,because there is absolutely no information like code samples to develop bluetooth application for mobile 5.0 using vb.net/c#. The code samples on msdn and other websites are in C++ and uses windows CE which is definnitely not what i am looking for.I have researched left,right and centre for three days but in vain. [C][C][C][C][C] My name is Adam and I am the one who posted the Tutorial 1 after the heading Tutorial 1 (probably created by microsoft) said coming soon for, I would say well over 6 months now. The reason this code does not work for you is as you mentioned you have the WIDCOMM stack and you are using it on Windows Desktop. The MicrosoftSharedSource for Bluetooth is designed for Windows Mobile 5.0 + and with a microsoft bluetooth stack. Firstly you can switch to the microsoft bluetooth stack on your desktop by uninstalling any WIDCOMM bluetooth stacks. (you should see it in the control panel add/remove programs) and ensuring you have XP SP2 or higher. Next you should download the code I ported across to Windows XP Also does anyone know what happened to Anil, he seems to have dropped of the planet? (april 1st 2006 was his last blog entry) I have to develop an application on Windows Mobile 2003 SE on a Dell PPC using CF.NET and Microsoft.WindowsMobile.SharedSource.Bluetooth. When a try to list the paired BT devices, I get the same problem than yumnakhan, Registry.ClosingKey() throw an exception. I am not sure of which BT stack is present (the BT controller is provided by Broadcom, maybe the stack too). It's strange because all the information I found on internet says the 'Microsoft.WindowsMobile.SharedSource' works for Windows Mobile. It is not the case for 2003 SE? What can I do to solve the problem? Regards math I get the same CloseKey error. Using a Mobile2003 with Widcomm. Any way to fix it? Anyone gave a solution? Thanks ofr an answer. JMJ Remove this comment Remove this threadclose
http://channel9.msdn.com/Blogs/scobleizer/Anil-Dhawan-Look-at-Bluetooth-programming-on-Windows-Mobile?format=progressive
CC-MAIN-2013-20
refinedweb
2,902
63.7
Post your Comment Spring MVC Say Hello Example Say Hello application in Spring 2.5 MVC  ... with the development of form based application in Spring MVC. You will learn how.... Then application displays name with "Hello" message. For example we will enter say hello in spanish say hello in spanish  ...(TimeZone.getDefault()); out.println("Hello spain will be written in this way...())); } } The output of the program is given below: Download this example.2 MVC Hello World Example In this section, you will learn about Hello World example in Spring 3 mvc mvc I want MVC example using jsp,servlets,pojoclass,jdbc(with mysql)..operation of insert,search,delete,update. I want above web application only in "Model view controller" format. last time i asked the same question, but i MVC Example MVC Example I WANT MVC EXAMPLE PROGRAM using Jsp Servlets and Jdbc with mysql of Insert,update,delete,search. please give the answer in MVC rule Spring MVC XmlViewResolver Example Spring web VelocityViewResolver.../schema/beans/spring-beans-3.0.xsd http MVC Tutorials hello world Example tutorial - Tutorial on developing Spring 3 MVC hello...Spring MVC Tutorials and example code In this section I will provide you... in Spring MVC that sprints hello world message on the screen Develop Hello World example using Spring 3.0 Framework Spring 3 Hello World Example  ... to the project. Now we can proceed with our Spring 3 Hello World example. Step 8...;In this section we developed Hello World example that uses the Spring 3.0. EJB Hello world example EJB Hello world example Creating and testing the "Hello World" Example is the very first... example we are going to show you, how to create your first hello world example Getting started with the Spring MVC framework. . We will first develop a simple Spring MVC Hello World example... Spring MVC Getting Started - Getting started with Spring MVC... Spring MVC Framework In this we will quickly start developing the application MVC - Struts MVC CAN ANYONE GIVE ME A REAL TIME IMPLEMENTATION OF M-V-C ARCHITECTURE WITH A SMALL EXAMPLE...... Hi friend, Read for more information. Thanks Spring MVC User Registration example Spring MVC User Registration example hi, I am unable to find springMVCUserRegistration example full code can u send me full code of this example Please visit the following link: Spring MVC USer Registration Spring web mvc 3.0 mysql project Spring web mvc 3.0 mysql project Hello Sir... I want a complete database connectivity web project in spring mvc 3.0..Just give me a simple example...: Spring MVC Login Example Spring MVC Login example Spring 2.5... using Spring MVC module. In this login example we are not connecting to any... it. The result is: Download Code of Spring MVC Login Example discussed here Java Hello World code example Java Hello World code example Hi, Here is my code of Hello World program in Java: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World J2ME Hello World Example J2ME Hello World Example This is the simple hello world application. In this example we are creating a form name "Hello World" and creating a string message " Hello - Struts Hello Hi, Can u tell me what is hard code please send example of hard code... Hi Friend ! Hard coding refers to the software development practice of embedding input or configuration data directly Displaying Hello using RMI Displaying Hello using RMI This Example describes the way to display Hello... in displaying message Hello are described below:- Step1.Create a Remote interface spring MVC frame work - Spring spring MVC frame work Example of spring MVC frame work Hello world sensitive programming language. For Example hello world !=(not equal... Hello world (First java program)  ... and can be run on any operating System. Writing Hello World program is very ZF Hello World with "Hello World" program. This tutorial is not an exception... by the web server. Since this framework is based on MVC design pattern, it separates... a fully functional MVC based project. Now type the following command Spring 2.5 MVC User Registration Example Spring MVC User Registration example Spring 2.5 MVC User Registration Example This tutorial shows you how to create user registration application in Spring MVC. This application mvc architecture - Java Beginners mvc architecture can u please provide a example program with code using mvc architecture mine problem is adding routes for the railwaystation... on the MVC architecture please send me the link for knowing the implementation code Post your Comment
http://www.roseindia.net/discussion/24592-Spring-MVC-Say-Hello-Example.html
CC-MAIN-2015-14
refinedweb
755
57.57
Simple game using pointers01 From GPWiki About this page This code was originally developed to be an example of a "real" application where the power of pointers can be seen. Unfortunately, the code ended up being longer than desired, but it can still be easily understood after some time. Other parts of the code can be useful to beginners as well. This is what I wrote several years ago, when I made this example. A lot of time has passed since, and I'm programming a little better now. anyway, the problem is that now I realize how bad this example is. It's really bad. I don't have the time to properly fix it now, but I believe that the only real use of this piece of code is to exercise how many errors you can spot in the code. So be careful when studying it. Source #include <string.h> #include <math.h> #include <iostream> struct Unit { int health; int attack; int defense; char name[12]; } gameunits[6]; // this function will print all the units names on screen, if they are alive. // It will also separate them in player one and two. Note that the separation is // done based on the unit position in the array (the array elements 0, 1 and 2 // belong to player one, and 3, 4 and 5 to player 2) void PrintUnits() { std::cout <<"Player 1\n"; for(int i = 0;i < 6;i++) { if(i == 3)std::cout <<"\nPlayer 2\n"; std::cout << i + 1 << " - "; if (gameunits[i].health > 0) std::cout << gameunits[i].name; else std::cout << "DEAD"; std::cout <<"\n"; } std::cout <<"\n"; } // This function will calculate the damage a unit should recieve based on that // unit's defense value and the attack value of the ATTACKER. No matter the // values passed, the damage will aways be at least 1, to prevent some possible // problems with while() structures int damageTaken(int attack, int defense) { float damageFactor = 1; damageFactor = pow(1.2, (attack - defense)); // pow() is the same as 1.2^x if(damageFactor <= 0.125f) damageFactor = 0.125f; // just to make shure that //there will aways be damage done. note that 0.125 * 8 = 1 return 8 * damageFactor; // 8 was choosed just to make values range between // 1 and 8 when the defense value is bigger than attack value } // This funtion will make the two units figth until one of them (or in rare cases // both of them) is dead. Note that the units are passed by reference, using // pointers. this is because this way the function can update the unit health by // itself void FightUnits(Unit* attacker, Unit* defender) { // this loop will go on until one or both units are dead. It will compute // each unit's damage (the attacker and the defender) based on unit's values // note that it doesen't matter who is the attacker and who is the defender, // they will both use the same formula. // Also, note that damageTaken() function will aways return at least 1. This // way, this loop will aways come to an end, no matter what the values where. while (attacker->health > 0 & defender->health > 0) { defender->health -= damageTaken(attacker->attack, defender->defense); attacker->health -= damageTaken(defender->attack, attacker->defense); } if (attacker->health <= 0 & defender->health<=0) { std::cout << "Whoa! Both units got killed!\n"; } else { if (attacker->health <= 0) std::cout << attacker->name << " was killed\n"; if (defender->health <= 0) std::cout << defender->name << " was killed\n"; } } // This function will check if the player is alive or not. If he isn't then we // must close the program to avoid any errors. bool playerlives(int player) { bool UnitLives = false; if (player == 1) { for (int i = 0;i < 3;i++) { if(gameunits[i].health > 0) UnitLives = true; } } if (player == 2) { for (int i = 3;i < 6;i++) { if(gameunits[i].health > 0) UnitLives = true; } } return UnitLives; //well, sorry for that little code hack. What is // happening here is that the UnitLives variable will keep track of the life // of the player units. So, if at least one of the units is alive, then // UnitLives = true. If some units are alive, then the player is alive, and // therefore, we must return true. Only when no unit is alive, then UnitLives // will remain false, and the function will return false } // This is our core funtion for the game, it will be called by an loop in the // program int main() funtion. int engine() { Unit* attacker = &gameunits[0]; // some initals values to prevent errors Unit* defender = &gameunits[3]; // some initals values to prevent errors PrintUnits(); if (playerlives(1)&playerlives(2)) { std::cout <<"Type 1, 2 or 3 to choose the attacker: "; int number; std::cin >> number; if (number > 0 & number < 4) { attacker = &gameunits[number - 1]; if (attacker->health <=0) { std::cout << "This unit is Dead!\n"; return 0; } } else { std::cout << "Bad number!!\n"; return 0; } std::cout <<"Type 4, 5 or 6 to choose the target: "; std::cin >> number; if (number > 3 & number < 7) { defender = &gameunits[number - 1]; if (defender->health <=0) { std::cout << "This unit is Dead!\n"; return 0; } } else { std::cout << "Bad number!!\n"; return 0; } defender = &gameunits[number - 1]; FightUnits(attacker, defender); } } int main() { { // this block will create all units and their data. gameunits[0].health = 250; gameunits[0].attack = 8; gameunits[0].defense = 8; strcpy(gameunits[0].name,"Wyvern"); gameunits[1].health = 60; gameunits[1].attack = 4; gameunits[1].defense = 3; strcpy(gameunits[1].name,"Swordman"); gameunits[2].health = 80; gameunits[2].attack = 7; gameunits[2].defense = 8; strcpy(gameunits[2].name,"Knight"); gameunits[3].health = 160; gameunits[3].attack = 8; gameunits[3].defense = 10; strcpy(gameunits[3].name,"Stone Golem"); gameunits[4].health = 130; gameunits[4].attack = 6; gameunits[4].defense = 5; strcpy(gameunits[4].name,"Troll"); gameunits[5].health = 100; gameunits[5].attack = 6; gameunits[5].defense = 3; strcpy(gameunits[5].name,"Orc"); } while (playerlives(1)&playerlives(2)) // while both players are alive, the game goes on { engine(); } if(playerlives(1)) std::cout << "CONGRATULATIONS! you have killed stuff!\n"; // if player 1 is alive, he won! so we congratulate him else std::cout << "You Die!! Looks like you need better strategy!\n"; // else: this means he is not alive... system("pause"); // sometimes, when the program closes, windows will close the // console with it, so we need this line to prevent that return 0; }
http://content.gpwiki.org/index.php/Simple_game_using_pointers01
CC-MAIN-2015-11
refinedweb
1,057
58.58
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. LINQ Method Syntax9:06 with Carling Kirk Learn how to write LINQ queries in method syntax using lambda expressions. - 0:00 Under the hood at runtime, all of the operators and link query syntax - 0:05 such as from, where, select, an order by, are converted to methods. - 0:10 Here, we've got a list of all the methods that are exposed - 0:13 as part of the link.innumerable type. - 0:16 I've included this link in the notes. - 0:19 Link is made possible by a feature of C sharp called extension methods. - 0:23 Extension methods give us the ability to tack on methods to classes that we - 0:27 wouldn't otherwise be able to alter. - 0:30 Well learn about writing our own extension methods a little later. - 0:34 When we add the system dot link namespace to our project. - 0:37 These methods are added to classes that implement the I innumerable interface, - 0:42 like list and array. - 0:43 Let's check out the where method Control F and where - 0:53 the first parameter of an extension method is the object is being called on, - 0:58 which in this case is an I enumerable down here. - 1:02 The keyword is indicating that it's an extension method. - 1:08 Filters a sequence of values based on a predicate, what does that mean? - 1:13 If we look at the definition on those where method, - 1:15 you can see that there's two parameters. - 1:18 And I know marble and a funk. - 1:21 Since this is an extension method, the first parameter, - 1:24 Source, is the collection it's being called from. - 1:28 The second parameter, called the predicate, - 1:31 is a funk that tells where method how to filter the enumerable. - 1:36 The term predicate in programming, is a test case, it gets evaluated to true or - 1:41 false. - 1:42 So, the where method needs a predicate delegate to tell it how to test - 1:46 the innumerable, it specifies it needs a func type - 1:51 that returns a boolean and we learn that we can write func delegates with a lambda. - 1:56 Let's dive back into our birdwatching data and write some more queries. - 2:01 We can start using link method syntax and lambda expressions. - 2:05 We'll be working with the C# again, so - 2:07 click the workspaces button to follow along. - 2:10 We need to load up our birdwatcher assembly, so - 2:12 we can get our list of birds back. - 2:14 If you get lost, there's a readme document in workspaces for you to refer to. - 2:19 Start the rebel with C sharp and - 2:24 then load assembly, bird watcher dot dll, - 2:32 and then using birdwatcher, - 2:36 which is the namespace. - 2:41 And then var birds equals=BirdRepository.loadBirds. - 2:51 Okay. - 2:52 Let's revisit our first wear query, - 2:55 where we wanted a list of all birds that are the color red. - 2:59 From B in birds, - 3:03 where the B dot color - 3:08 equals red select B. - 3:14 Okay, now let's write this query using method syntax and - 3:17 a lambda expression Birds.where, - 3:22 where b is the input parameter. - 3:27 Goes to b.Color == "Red". - 3:38 Hah. - 3:38 Notice that we don't have to tell it what to select. - 3:41 It's inferred from the list of birds that we're calling the where method on. - 3:46 The other thing you should notice is that I didn't include brackets - 3:50 around the lambda expression. - 3:53 This is a more syntactic sugar for us to keep things as concise as possible. - 3:58 We could've written it with the brackets like this. - 4:01 Birds.where b - 4:07 goes to curly brace return - 4:13 to b.color goes to red. - 4:18 Semi colon, curly brace, close parentheses. - 4:24 But since there's only one statement inside the brackets, - 4:26 we can leave them out. - 4:28 We also don't need to use the parentheses around the input parameter. - 4:32 We can do it like birds.Where, - 4:36 b goes to b.Color equals Red. - 4:44 Since we only have one parameter, the parentheses is optional. - 4:47 We'll get into link methods later on that take more than one parameter. - 4:52 Let's revisit a query similar to one we wrote earlier with queries untaxed to - 4:56 order the list of birds by color. - 4:58 I'll clear the consul here. - 5:02 Clear. - 5:03 Okay, from B-N birds. - 5:08 Order by be taught color select B. - 5:14 Remember that? - 5:16 To do these using methods syntax, we need to use the ORDER BY method. - 5:20 Just like the wear method, - 5:22 we need to tell it to order the birds with a lambda expression. - 5:26 Birds dot order. - 5:28 He goes to and will give it the property that we want to order by - 5:34 it which is color, and we get the same results. - 5:40 If we need to order in reverse, - 5:42 there's an additional method called orderByDescending. - 5:45 birds.OrderByDescending. - 5:50 b goes to b.Color. - 5:56 So, what would we do if we need to filter and order at the same time? - 6:02 We can use method chaining to call both the where method and the order method. - 6:07 Birds.where, b goes to be.color equals red, - 6:15 close that, and then .OrderBy - 6:20 b goes to b.order by name this time. - 6:29 So, the order in which you call the methods is important, - 6:32 the final result type will be the result of the last method in the chain. - 6:37 Think on how we would go about ordering with multiple properties with methods - 6:41 syntax with query syntax, we separated the properties with a comma. - 6:46 But in method syntax, we need to use an additional method called, - 6:49 then by when we use order by, - 6:53 were returned an ordered enumerable which gives us access to the then by method. - 6:58 Let's try that out. - 7:00 Birds dot order by, - 7:04 B goes to B dot name, - 7:09 then by Bn goes to B dot sightings. - 7:17 Why do you have to use the then by method, and not another order by method? - 7:21 Well, the then by method will preserve the order of the list - 7:25 that we got as a result of the initial order by method. - 7:28 So if we called ORDER BY twice like this bird's dot order by - 7:35 B goes to B dot name and then order by - 7:42 B goes to B dot sightings, - 7:49 we end up with the entire collection being sorted by sightings. - 7:54 So, far our queries have been returning a new marbles of birds. - 7:57 So, what if we want to innumerable of anonymous objects and not birds. - 8:01 You guessed it. - 8:02 There's a method called Select. - 8:04 birds.Select, b goes to new, - 8:09 b.Name and b.Color, - 8:14 close parenthesis And - 8:18 now we have anonymous types. - 8:25 I really like method syntax with link because it's so short and sweet. - 8:30 You'll find that developers may be divided on which syntax they prefer, and - 8:34 that's okay. - 8:35 You are free to choose whichever one you prefer, but - 8:39 it's good to get comfortable with both styles. - 8:42 If you're working on a project that's mostly using query syntax, - 8:46 you should do the same to be consistent, you can even mix the two styles. - 8:51 We've covered the where, order by, then by and the select methods. - 8:55 Check out the teachers notes for the documentation on each of those. - 8:59 We'll be covering a lot of new methods in the next few videos. - 9:02 So I don't courage you to take notes as we move through each one.
https://teamtreehouse.com/library/querying-with-linq/functional-programming-in-c/linq-method-syntax
CC-MAIN-2017-26
refinedweb
1,464
81.93
I need to write a function that creates a tuple in the format ('letter', row, col) of all letters in a list of lists. I realized I could combine two functions I've already written to accomplish this. One function I wrote get_letters(lst) extracts all the letters from the list of lists and the other one I wrote extracts the row and column. There must be a way to combine these two functions to accomplish this goal without creating a new one but I'm not sure how I would do it. Here's the code for these two functions: def get_letters(lst): letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' newlst = [] for sublist in lst: for i in sublist: if i in symbols and i not in newlst: newlst.append(i) #Example output: (1, 0) return newlst def find_letter(letter, lst): for i in range(len(lst)): for j in lst[i]: if j == letter: return i ,lot[i].index(j) #Example output: ['A'] #New function example output: [('A', 1, 0)] #Example input for both above functions: lst2 = #[['.','M','M','H','H'], #['A','.','.','.','f'], #['B','C','D','.','f']] [(letter, i, j) for i, sublist in enumerate(list_of_list) for j, letter in enumerate(sublist) if letter.isalpha()] Is one way to do it with enumerate. If you can't use enumerate for some reason, you can just roll your own: def not_enumerate_i_swear(iterable): i = 0 for item in iterable: yield (i, item) i += 1
https://codedump.io/share/ppLpQIAp7CaF/1/creating-tuple-of-letter-and-its-row-and-column-in-list-of-lists
CC-MAIN-2018-05
refinedweb
239
66.78
An util package that includes features from other languages' stdlib. Project description Oven An util package that includes algorithms, functions and IO similar to that of other languages' standard library. Installation Installation with pip is recommended. pip install oven Table of Contents - Standard I/O - Pointer - Structs Standard I/O The stdio package includes convient functions to redefine basic I/O. from oven.stdio import * Creating Session The stdio session is required in order to call any I/O functions. A session is created as such: set_io(IO_STREAM, 'path/to/file', METHOD) The IO_STREAM can be any of: - stdio.FILE: Redirect the IO stream to a file - stdio.CONSOLE: Redirect the IO stream to the console The METHOD can be any of: - r : Read from a file - w : Write to a file, create/override if nessesary - a : Append to a file, create if nessesary Method w overrides the file and dump all output from the session, while a append all output from the session to the end of the file. If the IO_STREAM is set to CONSOLE, then the path argument will be ignored. Note that the stdio session is created on the global scope, therefore one session will always suffice for one method of IO action. An example is given below. This code reads a line of input from a file and print it to the screen. from oven.stdio import * set_io(FILE, 'text.in', 'r') set_io(CONSOLE, None, 'w') text = cin() cout(text) Calling cin/cout Despite the name, the cin/cout also applies to file IO. cin() # Read one line. cout('Hello World') # Write. Note that \n is not added at the end. Pointer The Pointer package includes a pointer object. from oven.pointer import Pointer Instantiating Pointers A Pointer is created as such: ptr_1 = Pointer() ptr_2 = Pointer(INIT_VALUE) Calling Pointers Getting value from pointer: value = ptr() Assigning value to pointer: ptr(value) Structs The structs package features some data structures. from oven.structs import * Stack from oven.structs import Stack The Stack class is a subclass of python's list, its methods are: - push : Push a value to the stack - pop : Remove and return the ending element of the stack Queue from oven.structs import Queue The Queue class is a subclass of python's list, its methods are: - push : Push a value to the queue - pop : Remove and return the starting element of the queue Tree from oven.structs import Tree The Tree class is a recursive node of a tree. The value of the node can be assigned either in the constructor or by calling the value attribute (variable). # Both nodes are tree nodes with the value 42 node_1 = Tree(42) node_2 = Tree() node_2.value = 42 A child can be added to a node by calling the addChild method and passing the child as the parameter. The children of a node can be accessed by calling the children attribute (variable). Other methods include: - dfs : Returns a list of the tree's nodes in depth first search order. - bfs : Returns a list of the tree's nodes in breadth first search order. BinaryTree from oven.structs import BinaryTree The BinaryTree class is a subclass of the Tree class. The left and right children can be accessed by: node.left() # Returns the left node node.right() # Returns the right node node.left(newNode) # Sets the left node node.right(newNode) # Sets the right node Due to this, the addChild method is removed. All other methods are identical to that of the Tree class except the dfs method, which is tweaked so that the calling of it becomes: node.dfs(MODE) The MODE can be any of: - PREORDER - INORDER - POSTORDER All of the above modes are imported as such: from oven.structs import PREORDER, INORDER, POSTORDER Project details Release history Release notifications | RSS feed 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/oven/
CC-MAIN-2022-27
refinedweb
658
72.76
An HTTP client message (request or response). More... #include <Wt/Http/Message> An HTTP client message (request or response). This class implements a message that is sent or received by the HTTP Client. It is not to be confused with Request and Response, which are involved in the web application server handling. Constructor. This creates an empty message, with an invalid status (-1), no headers and an empty body. Constructor. This creates an empty message, with an invalid status (-1), an empty body and the given headers. Concatenates body text. Adds the text to the message body. Adds a header value. A header is added, even if a header with the same name already was present. This is allowed by HTTP only for certain headers (e.g. Set-Cookie). Returns the body text. Returns the body text. Returns a header value. Returns 0 if no header with that name is found. Sets a header value. If a header with that value was already defined, it is replaced with the new value. Otherwise, the header is added. Sets the status code. Returns the status code. This returns the HTTP status code of a response message. Typical values are 200 (OK) or 404 (Not found).
https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1Http_1_1Message.html
CC-MAIN-2021-31
refinedweb
203
79.26
Created on 2004-09-06 20:42 by josiahcarlson, last changed 2010-04-03 11:44 by mark.dickinson. This issue is now closed.. Logged In: YES user_id=80475 FWIW, I'm working str/long conversion functions for the binascii module. Will that suit your needs? The tolong function is equivalent to: long(hexlify(b), 16). Logged In: YES user_id=80475 Okay, submit a patch with docs and unittests.. Logged In: YES user_id=6656 Josiah, what do you suggest struct.calcsize does with the format code your proposing? I think this question encapsulates why I find this feature request a bit misdirected. Logged In: YES user_id=6656 Oops, I see you actually address that (ish). But I still feel packing what is an essentially variable length type using the struct module is a bit strange.). Logged In: YES user_id=80475 My vote is for binascii functions to parallel hexlify and unhexlify. Ideally, it would give the same result as long(hexlify(s), 16).). Logged In: YES user_id=80475 I agree with Michael and Martin that variable length types do not belong in struct. The module is about working with fixed record layouts. Logged In: YES user_id=341410 And as I stated, the 's' format character is also a "variable lengthed type". It just so happens that in most use cases I've had and observed for both the 's' format AND proposed 'g' format, the type size, is in fact, fixed at 'compile' time. It also happens that for the 'g' format, this fixed size is not in the set {1,2,4,8}, which are not limitations for the pre-existing 's' format. Please note that the only fundamental difference between the pre-existing 's' format and the proposed 'g' format, is that of a quick call to appropriate PyLong_* functions, and a range check as required by other integer types. Python is a tool. Struct is a tool. By changing the tool only slightly, we can add flexibility. The code is already there, minor glue would make it work, and would make it convenient for, I believe, more people than binascii. Logged In: YES user_id=31435 Use cases are important. Oddly(?) enough, I've never had a need for a bigint conversion in a C struct, and have a hard time imagining I will someday. All the cases I've had (and I've had more than a few) were one-shot str->long or long->str conversions. An obvious example in the core is the tedious encode_long() and decode_long() functions in pickle.py. Note that a pickle.encode_long() workalike doesn't know in advance how many bytes it needs, which would make using struct a PITA for that particular use case. If a proposal isn't convenient for taking over existing conversions of this nature, that counts against it. Logged In: YES user_id=341410 Curse you Tim, for your core Python experience *wink*. Pickle is one example where a pascal-like encoding of longs was an encoding decision made to be flexible and space efficient. Certainly we have disparate use cases. Mine is for fixed struct-like records with multiple types. With pickle, any /thought/ of fixed records are tossed out the window with variable-lengthed types like strings, longs, lists, tuples and dicts, and I believe aren't really comparable. Now, variable-lengthed longs packed in little-endian format already have a mechanism for encoding and decoding via pickle.en/decode_long (though it is wholly undocumented), and seemingly is going to get another in binascii. Fixed-lengthed, optional signed/unsigned, optional little-endian/big-endian longs do not have a mechanism for encoding and decoding, which is what I am asking for. I will point out that 128 bit integers are gaining support on newer 32 and 64 bit processors and C compilers for them (SSE on x86, Itanium, etc.). In the future, a new code for these 128 bit integers may be asked for inclusion. With a variable-width integer type, all future "hey, we now have x-byte types in C, where is struct support in Python?", can be answered with the proposed, "choose your integer size" format code. That is to say, this format code is future proof, unless integer types start wandering from integer byte widths. Logged In: YES user_id=341410 I have just attached a unified diff against structmodule.c 2.62 in CVS. It implements the semantics I have been describing, compiles cleanly, and produces proper results. >>> pickle.encode_long(83726) '\x0eG\x01' >>> struct.pack('<3g', 83726) '\x0eG\x01' >>> struct.unpack('<3g', struct.pack('<3g', 83726)) (83726L,) If the functionality is accepted, I will submit diffs for test_struct.py and libstruct.tex . Logged In: YES user_id=80475 If no one other that the OP supports this, I would like to reject putting this in the struct module. Initially, it seemed like a fit because the endian options and whatnot are already in place; however, in one way or another each of the posters except the OP has stated good reasons for it not being in the struct module. Variable length C structure members are not what the module is about. Having to know the length in advance of the call is a killer. The learning curve issues with struct are also a problem. And, the use cases jsut don't point to struct. Put in a simple function in binascii or let's drop it. Logged), ) FWIW, an use case of this I have encountered is to generate a string of random bytes from the long object returned by random.getrandbits(). See also issue #923643. Don't think there is sufficient agreement on this one to move forward. It looks like OP has a completely different conception of the struct module than the other respondants. For the time being, pickle.dumps with protocol 2 can serve as a way to save arrays of long integers in binary. This isn't about packing arrays of long integers in an array. I know the discussion is old, and I know the discussion is long, and honestly, I don't really need this particular functionality anymore (in the struct module in particular), but I still believe that being able to pack and unpack arbitrarily lengthed integers is useful. What is interesting is that this functionality was supposed to be in binascii years ago (which I resolved to myself as being sufficient), yet currently is not. Pickle is a solution only if you accept the target format to be opaque, which is not what you are looking for usually. Once again I just had to write the cumbersome: junk_len = 1024 junk = (("%%0%dX" % junk_len) % random.getrandbits(junk_len * 8)).decode("hex") ... because there is no obvious way to convert longs to bytes. I went ahead and coded a new API for converting long integers to byte arrays and vice-versa. My patch adds two new methods to the long type: .as_bytes() and .frombytes(). The patch itself is well-documented; but nevertheless, here's some examples: >>> (1024).as_bytes() b'\x04\x00' >>> (1024).as_bytes(fixed_length=10) b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).as_bytes(fixed_length=10) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> (-1024).as_bytes(little_endian=True) b'\x00\xfc' >>> ((2**16)-1).as_bytes(fixed_length=2, signed=False) b'\xff\xff' >>> int.frombytes(b'\x00\x10') 16 >>> int.frombytes(b'\x00\x10', little_endian=True) 4096 >>> int.frombytes(b'\xfc\x00') -1024 >>> int.frombytes(b'\xfc\x00', signed=False) 64512 This patch depends on another patch posted in issue #6687. So, apply the other patch before testing this one.: Is there some pre-existing naming convention of as_X and fromX? It seems strange that two related functions would have a different use of underscores. I agree with the comments which were made on the following points: - please use consistent naming (`as_bytes` / `from_bytes`, or `asbytes` / `frombytes`; my preference goes to the former, especially now that we have `bit_length`) - default byteorder should be native, certainly not big endian which is a small minority amongst today's computers - you should synchronize with the python-ideas discussion, so that the final API gets validated more publicly; it would not be very pleasant for a patch to be committed if discussion were still in flux, and perhaps with different conclusions as to the API which should be adopted Besides, your patch has indentation problems (mixed spaces and tabs). I'm not a big fan of the names, but as long as the functionality exists, people can easily alias them as necessary. I've not actually looked at the patch, but as long as it does what it says it does, it looks good. My only question, does it makes sense to backport this to trunk so we get this in 2.7? I personally would like to see it there, and would even be ok with a limitation that it only exists as part of longs. If someone has the time to backport it; cool. If not, I understand, and could live with it only being in 3.x . Thank you for taking the time and making the effort in getting this into a recent Python :) Here's a new patch incorporating the suggestions I received on python-ideas. Notable changes are: - The name of the methods have been changed to int.tobytes() and int.frombytes(). - The tri-state `little_endian' argument has been removed in favor of the `byteorder' argument which takes either the string 'little' or 'big'. - The `byteorder' argument has to be specified explicitly. - The variable-length version of int.tobytes() has been removed. - The `fixed_length' argument has been renamed to `length'. - The `signed' argument is now keyword-only and now defaults to False. Before this gets applied, a (preferably final) decision should be made whether it should be provided for 2.7 as well. Personally, it would be fine with me either way. Alexandre: > Notable changes are: > > - The name of the methods have been changed to int.tobytes() and > int.frombytes(). Without wanting to bikeshed, I think these methods should take underscores as other int methods already do. This kind of inconsistencies is really annoying (have you ever used PHP? :-)). Martin: > Before this gets applied, a (preferably final) decision should be made > whether it should be provided for 2.7 as well. Personally, it would be > fine with me either way. I'm also fine with adding it to 2.7 as well. But someone has to provide a patch (2.7 still has both `int` and `long`, which will make the task a bit more involved than a straight backport). The patch looks great! Some comments: - I think the type check for length_obj in long_tobytes should be more lenient: I'd suggest a PyIndex_Check and PyNumber_AsSsize_t conversion instead of the PyLong_Check. Or just use 'n' instead of 'O' in the PyArg_Parse* format; this uses PyNumber_Index + PyLong_AsSsize_t, which amounts to the same thing (or at least I *think* it does). - I like the pickle changes, but I think they should be committed separately. (Unless they're somehow required for the rest of the patch to function correctly?) - Stylistic nit: There's some inconsistency in the NULL checks in the patch: "if (args != NULL)" versus "if (is_signed_obj)". PEP 7 doesn't say anything about this, but the prevailing style in this file is for an explicit '== NULL' or '!= NULL'. - I'm getting one failing test: test.support.TestFailed: Traceback (most recent call last): File "Lib/test/test_long.py", line 1285, in test_frombytes self.assertRaises(TypeError, int.frombytes, "", 'big') AssertionError: TypeError not raised by frombytes This obviously has to do with issue 6687; as mentioned in that issue, I'm not sure that this should be an error. How about just removing this test for now, pending a decision on that issue? - Nice docs (and docstrings)! On the subject of backporting to 2.7, I haven't seen any objections, so I'd say we should go for it. (One argument for not backporting new features is to provide incentive for people to upgrade, but I can't realistically see this addition as a significant 'carrot'.) I'm happy to do the backport, and equally happy to leave it to Alexandre if he's interested. Leaving the bikeshedding until last: Method names: I'm +0 on adding the extra underscore. Python's already a bit inconsistent (e.g., float.fromhex and float.hex). Also, at the time the float.fromhex and float.hex names were being discussed, 'hex' seemed to be preferred over 'tohex'; I wonder whether we should have int.bytes instead of int.to_bytes? Here's an updated patch. - Renamed tobytes() to to_bytes() and frombytes() to from_bytes(). - Moved the changes to pickle to a different patch. - Made the NULL-checks more consistent with the rest of long's code. - Fixed the type check of the `length' parameter of to_bytes() to use PyIndex_Check() instead of PyLong_Check(). The following example is strange: + >>> int.from_bytes([255, 0, 0], byteorder='big') + -65536 Isn't `signed` supposed to be False by default? The rest looks ok. Looks good to me, too. All tests pass on OS X 10.5/Intel, except that I'm still getting the issue 6687 test failure. This needs to be resolved somehow before committing. Committed in r77394. Thank you for the good reviews! I'd still like to see this backported to 2.7; if no-one else is interested in doing the backport, I'll try to find time before the betas. (Alexandre, if you want to do the backport, please do steal the issue from me.) A couple of questions for the backport: (1) should the 'signed' parameter remain keyword-only in 2.7? I'd say yes, to avoid issues when forward-porting code from 2.7 to 3.2. On the other hand, 2.7 doesn't support keyword-only arguments at the Python level, so a keyword-only argument might be a bit of a surprise to users. (2) When specifying the byteorder, is there a need to allow u'big' and u'little' as well as 'big' and 'little'? Mark Dickinson added the comment: > (1) should the 'signed' parameter remain keyword-only in 2.7? We should keep it as a keyword-only argument. Also, issue #1745 might bring keyword-only arguments to 2.7. > (2) When specifying the byteorder, is there a need to allow u'big' and > u'little' as well as 'big' and 'little'? Allow both. Since, 'big' == u'big' is True, it would be weird to treat them differently in this case. Plus, it will make life easier for people who uses: from __future__ import unicode_literals in their code. Thanks, Alexandre! Agreed on both points. I don't really want to allow u'big' and u'little', but I think that's just my laziness talking. (Apart from that, I have a working patch.) There's some precedent for not allowing the unicode versions: >>> float.__getformat__("double") 'IEEE, little-endian' >>> float.__getformat__(u"double") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __getformat__() argument must be string, not unicode But I admit it isn't particularly compelling. The backport wasn't as straightforward as I'd hoped, and we've pretty much run out of time for 2.7. One issue is that long.from_bytes(b, ...) converts b to bytes type using the equivalent of "bytes(b)". This doesn't work well in 2.7 (consider "bytes([255, 0, 0])" for example. So different code is needed in 2.7 when interpreting an arbitrary Python object as a sequence of bytes. Perhaps the 2.7 version could just iterate over the given object, and raise an exception if any of the iterates are not integers in the range [0, 256). Closing this; it's too late for Python 2.7.
http://bugs.python.org/issue1023290
CC-MAIN-2014-35
refinedweb
2,642
66.74
Can you please please please help me, I am looking for a C++ Database that will let me add, delete and edit people's names, addresses, telephone numbers, fax number and e-mail address. Can you help as soon as possible please? Steve. Can you please please please help me, I am looking for a C++ Database that will let me add, delete and edit people's names, addresses, telephone numbers, fax number and e-mail address. Can you help as soon as possible please? Steve. Well, I'm looking for the cure for illeteracy, maybe you can help by learning how to read: Quote: 1. Don't expect someone to write your entire program. 2. Check to see if your question has been answered (use the search feature and read the FAQ!) 3. Use a descriptive title (not just "C" or "C++"; make it specific). 4. You don't need to write more than one H E L or P in help, and it definitely doesn't need to be capitalized. 5. Let dead posts lie; don't bump old messages without a reason or they will likely be deleted. 6. Post your code. If you don't have any, ask where to start; do not for the program to be written for you. 7. Don't type anything in all CAPS. 8. Don't ask for a personal email - the board will send an email when a post is replied to if you desire. Use that and check back when you get a reply; the board moves messages up. As well, it will actually send the text of the response to you. 9. Post once: don't keep pressing post. Duplicates will be deleted. 10. Do not cross post; almost everyone reads most of the important boards. 11. Be polite, especially if you want someone to help you. Just because you are giving help doesn't mean you have the right to be rude, however. 12. Disparaging remarks without provocation and unsolicited advertisements will be immediately removed. Don't waste your time, and don't waste my time. By the way, you can't make $6000 from $6 dollars. I know this might not help at all, but I felt like posting it anyways. #include <iostream> #include <fstream.h> #include <conio.h> #include <string> int main(int argv, char *argc[]) { string name; unsigned short int age; cout << "Input your name: "; cin >> name; cout << "Input your age: "; cin >> age; ofstream x("Database"); x << "Name: " << name; x << "Age: " << age; x.close(); gb, why do you refuse to use code tags . . . are you looking for a cause or something?
http://cboard.cprogramming.com/cplusplus-programming/17414-database-printable-thread.html
CC-MAIN-2014-35
refinedweb
438
82.75
) - You’re here → test function we wrote in the last chapter was good, but we can make it even better if we refactor it using the Page Object Pattern. WebDriver Test Problems For reference, here’s the current version of our test function: def test_basic_duckduckgo_search(browser): URL = '' PHRASE = 'panda' browser.get(URL) search_input = browser.find_element_by_id('search_form_input_homepage') search_input.send_keys(PHRASE + Keys.RETURN) All WebDriver calls are made directly within the test function. Without any comments, this code can be hard to read and understand. The WebDriver calls use unintuitive locators with low-level interaction commands. What’s missing is the intent – this test is a DuckDuckGo search, not a slew of clicks and scrapes. Plus, web element locators can be duplicated, such as the locator for the search input. The Page Object Pattern (a.k.a the Page Object “Model”) is a design pattern that abstracts web page interactions for enhanced readability and reusability. Pages are represented as classes with locator attributes and interaction methods. Instead of making raw WebDriver calls, tests call page object methods instead. Page Object Pattern is arguably the most common pattern used for web UI test automation. There are many ways to implement the pattern, but most of them are fairly similar. Restructuring for Page Objects Our test interacts with two pages: the DuckDuckGo search page and the result page. Let’s write a page object class for each. Create a new directory named pages/ under the project root directory, and add an empty __init__.py file to make it a package. In this package, create two files named search.py and result.py. Your project directory layout should look like this: $ tree . ├── Pipfile ├── Pipfile.lock ├── pages │ ├── __init__.py │ ├── result.py │ └── search.py └── tests ├── test_math.py └── test_web.py Placing test-related modules outside the tests/ directory might seem odd. However, remember that pytest recommends the tests module to not be a package. Creating a separate package for page objects enables test modules to import them easily. It also enforces a separation of concerns between test cases and web interactions. This directory layout will be sufficient for our test project, but other (especially larger) projects may consider alternative layouts. Please refer to pytest’s Good Integration Practices guide for further advice. The Search Page The search page is pretty simple. Our test interacts with it in two ways: loading it and entering a search phrase. The search input is the only locator, too. Add the following code to pages/search.py: from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class DuckDuckGoSearchPage: URL = '' SEARCH_INPUT = (By.ID, 'search_form_input_homepage') def __init__(self, browser): self.browser = browser def load(self): self.browser.get(self.URL) def search(self, phrase): search_input = self.browser.find_element(*self.SEARCH_INPUT) search_input.send_keys(phrase + Keys.RETURN) Despite its small size, this class is a good example of what page objects should be. Its name, DuckDuckGoSearchPage, uniquely and clearly identifies the page. There are locator attributes ( SEARCH_INPUT), an initializer ( __init__), and interaction methods ( load and search). Let’s look at each part. Locator Attributes The only locator in this class is SEARCH_INPUT, which finds the search input element. It is a class (or “static”) attribute because the value should be the same for all search pages. It is also written as a tuple because every locator has two parts: a type (like By.ID or By.XPATH) and a query. This locator finds the search element by the name “q”. Writing locators as class attribute tuples makes them very readable and accessible. Locators should always have intuitive names, too. Initializer All page objects need a reference to the WebDriver instance. Typically, it is injected via the constructor. Here, it is passed into the __init__ method as the browser parameter and then stored as the self.browser attribute. Dependency injection allows page objects to polymorphically use any type of WebDriver, whether it’s ChromeDriver, IEDriver, or something else. It also lets the test framework control setup and cleanup. Interaction Methods Interaction methods should be intuitively named. The load method navigates the browser to the search page. Notice that URL is a class attribute. The search method enters the search phrase into the input field, but now the phrase is parametrized so that any phrase may be used. The search method also finds the target element in a novel way. Instead of using the find_element_by_name method, it uses the more general find_element method that takes two arguments: the locator type and the query. Those arguments match our SEARCH_INPUT tuple. The * operator expands self.SEARCH_INPUT into positional arguments for the method call. Nice! Personally, I like this pattern because locator tuples can be changed without affecting interaction code. Search Refactoring Let’s refactor the test case steps with our new search page object. Replace these lines: URL = '' PHRASE = 'panda' browser.get(URL) search_input = browser.find_element_by_id('search_form_input_homepage') search_input.send_keys(PHRASE + Keys.RETURN) With new page object calls: PHRASE = 'panda' search_page = DuckDuckGoSearchPage(browser) search_page.load() search_page.search(PHRASE) That’s much better! The lines now read much more like test steps than programming calls. The Results Page Let’s write the result page object next. Add the following code to pages/result.py: from selenium.webdriver.common.by import By class DuckDuckGoResultPage: LINK_DIVS = (By.CSS_SELECTOR, '#links > div') SEARCH_INPUT = (By.ID, 'search_form_input') @classmethod def PHRASE_RESULTS(cls, phrase): xpath = f"//div[@id='links']//*[contains(text(), '{phrase}')]" return (By.XPATH, xpath) def __init__(self, browser): self.browser = browser def link_div_count(self): link_divs = self.browser.find_elements(*self.LINK_DIVS) return len(link_divs) def phrase_result_count(self, phrase): phrase_results = self.browser.find_elements(*self.PHRASE_RESULTS(phrase)) return len(phrase_results) def search_input_value(self): search_input = self.browser.find_element(*self.SEARCH_INPUT) return search_input.get_attribute('value') DuckDuckGoResultPage is just a bit more complex than DuckDuckGoSearchPage. The LINK_DIVS locator follows the tuple pattern, but the PHRASE_RESULTS locator does not. Instead, it uses a class method that returns a tuple so that the search phrase in its XPath may be parametrized. The initializer is the same. The three interaction methods find elements and return values. Note that the interaction methods do not make assertions. They simply return state. Assertions are a concern for a test case, not page objects. Different tests may use the same page object calls for different types of assertions. It’s time for more refactoring. Replace the following test function lines: With these: result_page = DuckDuckGoResultPage(browser) assert result_page.link_div_count() > 0 assert result_page.phrase_result_count(PHRASE) > 0 assert result_page.search_input_value() == PHRASE Wow! Again, that’s much cleaner. Rerun the Test tests/test_web.py should now look like this: import pytest from pages.result import DuckDuckGoResultPage from pages.search import DuckDuckGoSearchPage from selenium.webdriver import Chrome @pytest.fixture def browser(): # Initialize ChromeDriver driver = Chrome() # Wait implicitly for elements to be ready before attempting interactions driver.implicitly_wait(10) # Return the driver object at the end of setup yield driver # For cleanup, quit the driver driver.quit() def test_basic_duckduckgo_search(browser): # Set up test case data PHRASE = 'panda' # Search for the phrase search_page = DuckDuckGoSearchPage(browser) search_page.load() search_page.search(PHRASE) # Verify that results appear result_page = DuckDuckGoResultPage(browser) assert result_page.link_div_count() > 0 assert result_page.phrase_result_count(PHRASE) > 0 assert result_page.search_input_value() == PHRASE Rerun the test to make sure it still works: $ pipenv run python -m pytest ============================= test session starts ============================== platform darwin -- Python 3.7.3, pytest-4.5.0, py-1.8.0, pluggy-0.12.0 rootdir: /Users/andylpk247/Programming/automation-panda/python-webui-testing collected 9 items tests/test_math.py ........ [ 88%] tests/test_web.py . [100%] =========================== 9 passed in 5.68 seconds =========================== Nice! It works. More Tests! These past two chapters have expounded the intricacies of what initially appeared to be a simple web UI test. Not only did we automate web UI interactions for a DuckDuckGo search, but we did so with best practices and design patterns! What we learned here can be extended for new tests. Here are suggestions for additional tests you can write: - Parametrize the test to search other phrases. - Click one of the result links. In the next chapter, we’ll learn how to set configurations for browser choice and wait times outside the automation code using config files. [Update on August 25, 2019: Changes to the DuckDuckGo search page required locator updates for the search input elements.] Hi i am currently using pycharm to build this framework and i am currently at def __init__(self, browser): self.browser = browser def load(self): self.browser.get(self.URL) now my issue is in the load method when i type self.browser and press the fullstop i dont get the autocomplete to show the webdriver methods eg get,find_elements which leads to my question how does this class know that browser is of type webdriver ? Hi Benzito164! That’s how the Python type system works. Python is a dynamically typed language. Theoretically, anything could be passed in for the browser variable. The tests we write must make sure to pass in a WebDriver object for browser. Alternatively, we could use a Python type system like mypy or pyre for type checking.
https://blog.testproject.io/2019/07/16/develop-page-object-selenium-tests-using-python/
CC-MAIN-2020-05
refinedweb
1,501
52.56
Spring.NET QnA with Aleks Seovic and Mark Pollack - | - - - - - - Read later Reading List main tenets of Spring. Aleks shares this thought on the need for Dependency Injection in .NET: "Dependency Injection implies that an object's dependencies will be "injected" by external means. There is no need for an object to look up anything - it simply declares private fields for its dependencies and allows for them to be provided externally, either via a constructor argument or via a property setter. This makes objects very clean and reusable, and if dependencies are declared in terms of interfaces instead of specific classes, it also makes them very easy to unit test." Mark talks about where a developer might choose Spring.NET's data access framework on top of ADO.NET: "Spring.NET's Data Access Framework (Spring.Data) provides lots of added value above ‘plain' ADO.NET. One of the key components is a transaction management abstraction that allows you to easily switch between different transaction strategies, i.e plain old local ADO.NET, EnterpriseServices distributed transactions and the new System.Transaction namespace. All the strategies can be used to perform declarative transaction demarcation either via embedded attributes or non-invasive XML configuration. Our extensions to the ADO.NET framework make most ADO.NET operations a one-liner and take care of the connection/transaction resource handling - which would otherwise still require some extra work on the part of the developer in common scenarios, even with the new System.Transactions namespace." The bottom line is Spring.NET allows developers familiar with Spring or Dependency Injection to become very productive in .NET quickly by capitalizing on a framework they are familiar with. Rate this Article - Editor Review - Chief Editor Action Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think Spring.NET - QnA by Pieter Greyling - Raise your hands all practicants. I need to be convinced of the newness of this term. So, here goes... "If you think about it, there is nothing new about Dependency Injection per se. " - Is this related to when a function call has a structure address instead of a void pointer as one of it's arguments? "I could find similar examples in older technologies as well, such as VB6 or COM." - Gray hairs in my beard. I made the survival choice in the early '90s to Win as the better and under-marketed OS/2 took the brunt of the backlash against Big Blue. Beauty sunk. VB2/3 those days. Give D/COM/++ the hat it deserves today. A modern and relevant technology with a resilient design by perhaps the best mobile and survival oriented object framework implementors. COM remains the inspiration and parent of .NET. Without COM, .NET cannot load on Win32. .NET has still to prove that it can cross the road, stay over for the night, deal with the neighbours, and return as naive as it left the night before. All with a smile. "However, what made Dependency Injection so popular in the recent years is the rise of lightweight containers such as Spring, Pico and HiveMind in Java, and Spring.NET, Castle, and more recently Microsoft's ObjectBuilder in .NET." - Word-play? Lightweights with mandatory big brothers whether they be a JVM or a .NET runtime, A "nothing new" thing so old that it influenced a whole generation of popular offspring I am guilty of only having read about lately? Some code examples ? "These containers allow you to configure object-wiring rules within your application and based on those rules they will create and wire your application's objects together, providing you with automatic dependency injection." - Which world are we referring to? How does this handle interoperability between dissimilar factions? This surely relates only to the "protected" and custom and super modern programmed super intimate, well-known/static/designed-after the fact/non-scaleable interface handlers within the domain of the J2EE / .NET world? This can surely not relate to the real world of tightly coupled high-performance and often blundering peculiar and by historical definition distinct protocols. Sockets blasting away at each other all over the place in different-speak no matter what is at the other end? Mainframe LU6.2, DB Call Interfaces, DCOM, CGI, ODBC, Netware etc. Even if everything would be TCP/IP, how does this equate to compatible and discoverable perhaps alive object instances outside J2EE and .NET lingo? Re: Spring.NET - QnA by David Skelly I don't quite see what point you are trying to make here. Perhaps you could rephrase it with a little less bitterness and a little more clarity. Re: Spring.NET - QnA by Pieter Greyling There are many young and old programmers who could benefit from my post as it stands. Perhaps you could pinpoint an area of my post that offended you. Re: Spring.NET - QnA by Aleksandar Seovic As David pointed out, it is not very clear what in the article you disagree with. If you could point us to the specific points we are making that you don't agree with, Mark and I will be more than happy to respond. In the meantime, let me try to answer to some of the things you seem to disagree with: 1. Dependency Injection The term itself is fairly new, and it was coined by Martin Fowler in early 2004. The containers that have made DI so popular in the recent years are also fairly new. The principle, however, is not new and can be used on any platform and in any language, as it is simply a way of designing loosely coupled OO systems. 2. .NET vs COM/DCOM/COM+/VB2-6, etc. Without getting into discussion which one is better, which would be pretty pointless exercise, I'd just like to say that the article's intended audience are .NET developers. It was not our intention to position it as "everyone should switch to .NET" propaganda, and as far as I can tell it doesn't read that way either. Sorry if you interpreted it wrong. 3. Lightweight vs. Heavyweight When we are saying that Spring provides a "lightweight" container, we are not comparing it to JVM or CLR. "Heavyweights" are actually EJB container in Java and COM+/MTS on the Microsoft side. All of these containers provide some services, but some are much lighter than the others, and that's where the term came from. 4. Object wiring and cross-platform interoperability When we are talking about "object wiring", for the most part we are talking about objects on the same platform. There are ways for .NET, Java, C++ and other objects to call each other, but that usually involves some kind of proxy/stub mechanism that bridges platform differences. For example, Spring.NET allows you to create a proxy to any CORBA object, so technically you could wire objects on different platforms together by injecting proxies into your application objects. Re: Spring.NET - QnA by Pieter Greyling First off, all kudos go to your project. Credit earned. As I pointed out, many programmers can benefit from my post; and the follow-ons. Whether it is perceived to be left or right or not at all is up to them to decide. Per your numbers: 1. Dependency Injection This term is of no practical use. All practical programmers understand it already and do not need a new name. Where I was born, making new names for old things and then selling them is a cheap way of making money one does not deserve. Startup programmers that are already intimidated by the perceived smoke and mirrors complexity of software development in modern world should not be educated in this way. Programmers need intelligent tools that are free of dependency on external factors like re-invention of existing terminology. I recall an English term about throwing fish (Scottish fish, Herring? (free Nordic fish?) ) in the air to distract enemies. Writing software is difficult enough yet most of us started and are starting out to have fun whilst being creative. So we choose programming. 2. .NET vs COM/DCOM/COM+/VB2-6, etc. It seems I made a mistake by invading a ".NET" space? 3. Lightweight vs. Heavyweight Ths word "light" surely misguided me. Do you mean an undemanding layer over the .NET framework? I believe it will misguide techno-informed business-oriented managers and new programmers which we value. It leads to unrealistic expectations and then over budget projects delivered apparently on time due to pressure. After that a piece of cow-dung has to be supported by the developers due to its quirky nature and cannot be fixed without business paying even more. 4. Object wiring and cross-platform interoperability I must admit that I have not read the Spring.NET source code and this makes me feel like an outsider. Sorry, I do have a life. This is the part I am most interested in. My previous post stands as is on this subject. Re: Spring.NET - QnA by Aleksandar Seovic 1. I do agree with you that terms such as "Dependency Injection" can scare new programmers, or even experienced programmers who encounter the term for the first time. However, I do think that Dependency Injection is a much better name than "Inversion of Control", which is the name that was, and to a certain extent still is, used to describe the same concept. As for "practical programmers" not needing a new name for it, I'd agree with you if there was an old name for it. If we exclude above mentioned "Inversion of Control", which is really a much broader term, I'm not aware of an old name for the thing we are describing as Dependency Injection today. If you are saying that you don't think we need a name at all, I disagree. Having a common name for something makes discussions much easier. Design patterns have been around for a long time, but it wasn't until GoF compiled them and gave them meaningful names that such a wide audience was able to understands them and discuss them. Short and meaningful names really do make communication much simpler. 2. I don't think you invaded .NET space at all. All I was saying is that article's intended audience are .NET developers and that we are not trying to say that .NET is either better or worse than other technologies out there. We are simply saying that the average .NET developer can greatly benefit from the services provided by Spring.NET -- that's it. Neither Mark nor I are "territorial" when it comes to technology. I use both Java and .NET on a regular basis, because that's what most of my clients want me to use and what I'm most experienced with, but I have used many other languages and platforms in the past, and will probably use plenty more as long as I'm doing this job. As I pointed out in the article, there is no single tool that is the best choice for every job, so unless the client dictates what to use I tend to choose whatever will work best for the particular application. 3. What I mean by "lightweight container" is an undemanding, fairly simple, configurable and extensible container for application objects. So lightweight in fact that you can bring many of them up when you need them and destroy them when you don't. There is a lot of value in having objects within a container, but that's a topic for whole another article... 4. There is no reason for you to read Spring.NET source code. You can download it and try the features you are interested in for yourself. There is documentation and a few sample apps that will show you how to configure Spring.NET client to access remote EJB, or any other CORBA-compliant object using IIOP.NET integration. Keep in mind that this particular feature is more in the experimental state and there is a lot more than can and needs to be done, but it wouldn't be too difficult to do if there is more user demand for it. Re: Spring.NET - QnA by Pieter Greyling I am not going by the numbers this time (:-) In short, based on my experience I believe words and terms are (re-)invented too often in this industry. Too many times this is done for the benefit of creating new business opportunities and/ or markets for the biggest guns of the time. I have not seen the terms nor technology stick around long enough to add real value, teach better individual personal programming ability, confidence in continuity, nor provide a skills growth path that builds instead of re-inventing. The worst is that most of the best ideas never achieve real corporate penetration. So in the longer term, they do not provide job opportunities for aspiring programmers with sustainable demand for their improving skills. It is mostly the individuals with skin-deep knowledge on the latest hype that get a job and thus experience until the next best thing comes along. Essentially, in my humble opinion, by far most modern code is still implemented in, at best, the same way as 20 years ago. What has changed is the sheer number of people from all walks of life willing to write a bit of code. This has changed the world irreversibly and surely for the better. However, this is mostly attributable to technologies that empowered individuals (for example the internet, mobiles, games etc.) and individual "nobodies" like the GPL'ers that proved everybody has the right to be a "hacker", indeed a successful one. I honestly cannot say that I think software development practices and methods have advanced to keep pace with the challenge. It seems more of a "Wild-West" now than when I started. Not that I am personally ignorant of the allure of being a gunslinger myself. Based on our discussion so far, perhaps I did not make a mistake posting ("invading") here after all. At least, this is the kind of forum and the kind of post (to your credit), that corporate pioneers will be reading and thus might help to remedy some of my misgivings. Re: Spring.NET - QnA by Srdan Srepfler Before DI people were trying to build houses by concentrating on creating the best bricks. Nothing wrong with superb, technologically advanced bricks. However in those days people would have to worry a lot thinking about how well do these bricks fit together (in those days the bricks didn't fit well because every time you'd do a better, improved, different brick you'd have problems in fitting them with the old bricks),after DI they stopped worrying on how well the bricks fitted as it suddenly became easy and standard for you to connect all these different bricks so people started focusing on the building instead of the bricks. Or, as a teacher of mine would put it, before we were thinking as westerners and trying to be reductionist, now people are starting to think as easterners and taking a more holistic view of the world. We know that the concepts of how to implement DI are not radical, intrusive or something that wasn't possible before, but, if something changes your view of the world, it deserves a new name. Plus, and I don't know where you live if you don't use them already, these frameworks go a long way from just doing the basic dependency injection and offer pre-made blueprints to build solid, hospitable, pretty,...,houses and it costs you less to build a house that will sell for more. Re: Spring.NET - QnA by Pieter Greyling You are right; I suppose I did open the door to more than mere technical arguments. Re: Spring.NET - QnA by robert li I am an .Net developer, but new to Spring.Net. You mentioned that you are writing a book for Apress. My I ask what this new book about? I, as .Net developer, really need a book for Spring.Net. If yes, when is it going to publish? I know Manning is going to publish "NHibernate in Action" this year. Re: Spring.NET - QnA by Aleksandar Seovic Yes, the book is on Spring.NET and it will cover all major areas of the framework. It is a bit harder to answer when it will come out... At the moment, we are working very hard to get the final release out, so there really isn't that much time to work on the book. Hopefully we will have more time to work on it once Spring.NET 1.1 is released, so we might be able to get it done by the end of this year. That said, Spring.NET reference docs are fairly complete and will be a good starting point for anyone new to the framework. We are also planning a series of articles on Spring.NET for InfoQ, which should cover quite a bit of ground as well. In addition to that, we will start offering public and private Spring.NET training pretty soon as well. Hope this helps, Aleks Re: Spring.NET - QnA by Alessandro Gambaro Is the book ready? I couldn't fount it on the Apress site. Thanks, Ale Re: Spring.NET - QnA by Duraid Duraid
https://www.infoq.com/news/2006/11/Spring-QnA-Aleks-Mark
CC-MAIN-2018-34
refinedweb
2,930
64
A few caveats: - All examples will focus on Python 3.x. It is possible to write C extensions that compile on both 2.x and 3.x but supporting both major versions makes the C code more complicated. - My primary development platform is Linux but I will also cover Windows. I don't have access to a Mac so I can't assist with OSX. - The Windows binary for Python 3.3 was compiled with Visual Studio 2010. You will need to install Visual Studio 2010 Express to compile extensions for Python 3.3 on Windows. For earlier versions of Python, you will need Visual Studio 2008 Express (if you can still find it on Microsoft's web site) or you can install the Windows 7.0 SDK (aka Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1). I will cover the use of the SDK compilers in another post. Here is a simple setup.py file: - Code: Select all from distutils.core import setup, Extension case_module = Extension('case', sources = ['case.c']) setup (name = 'case', version = '0.0', description = 'Collection of Arbitrary Simple Extensions', ext_modules = [case_module]) Here is corresponding C file (case.c): - Code: Select all #include "Python.h" PyDoc_STRVAR(case_doc, "Collection of Arbitrary Simple Extensions."); static struct PyModuleDef case_module = { PyModuleDef_HEAD_INIT, "case", /* m_name */ case_doc, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; PyMODINIT_FUNC PyInit_case(void) { return PyModule_Create(&case_module); } Save these two files to a directory on your computer and enter "python3 setup.py install" and the extension should be compiled and automatically installed. Note: replace python3 by whatever command you need to use on your computer to invoke a Python 3.x interpreter. So what's in case.c? The line #include "Python.h" gives the extension access to the C-API of the Python interpreter. If you are running Linux and get an error message stating that Python.h cannot be found, then you will need to install the development libraries for your version of Python. Then we create a docstring for the module. It is called case_doc. Next, we create a Python Module Definition (PyModuleDef) structure that describes the module we are creating. The module structure is called case_module. PyModuleDef_HEAD_INIT is used by Python for internal bookkeeping. We then provide the name of the module ("case"), the docstring (case_doc) that provides help for the module, and the remaining fields are given default values. Lastly, we define a function PyInit_case. The Python interpreter calls this function after loading the extension. The purpose of this function is to initialize a module (based on the values given in case_module) and return it to the Python interpreter. You can "import case" and read the docstring via "help(case)" and that's about it. Now that we've created the most useless extension module, we'll add what is probably the most useless object in Part 2. Enjoy, casevh
http://www.python-forum.org/viewtopic.php?f=25&p=1104
CC-MAIN-2015-22
refinedweb
484
60.01
A “did you mean?” Feature for R Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. is completely passive, beyond loading it with the usual library(Rdym) call. Say for example you run: shapro.test(x=rnorm(20)) # Error: object 'shapro.test' not found Note the missing “i” in what should be shapiro.test(). With Rdym loaded, you can get a “did you mean?” suggestion along with the error: library(Rdym) shapro.test(x=rnorm(20)) # Error: could not find function "shapro.test" # # Did you mean: shapiro.test() ? # shapiro.test(x=rnorm(20)) If the spellchecker guessed correctly, then you should be able to just copy/paste the suggestion after the “Did you mean” line into R. Suggestions are given as errors are discovered by the R interpreter. For example: library(Rdym) shapro.test(rmorm(20)) # Error: could not find function "shapro.test" # # Did you mean: shapiro.test ? # shapiro.test(rmorm(20)) shapiro.test(rmorm(20)) # Error in stopifnot(is.numeric(x)) : could not find function "rmorm" # # Did you mean: rnorm ? # shapiro.test(rnorm(20)) shapiro.test(rnorm(20)) # Shapiro-Wilk normality test # # data: rnorm(20) # W = 0.9366, p-value = 0.207 How it works When R detects that a function or object listed in the user’s input is not found, the package finds the minimum Levenshtein distance between the “unfound” token and all symbols in the user’s global environment plus all loaded namespaces. The word with minimum Levenshtein distance (in the event of ties, the first such detected) is then suggested as an alternative to the missing symbol. Fairly efficient C code is used to compute the Levenshtein distances. The “error interception” is just using R’s options() to set a function to run post error (as seen here). The package won’t work with batch mode R, so you have to use it in an interactive R session. Also keep in mind this is basically just a toy. You shouldn’t think of this as being in the same class of capabilities as a search engine’s suggester. Installation You can install directly from GitHub via the devtools package: library(devtools) install_github("wrathematics/Rd.
https://www.r-bloggers.com/2014/12/a-did-you-mean-feature-for-r/
CC-MAIN-2021-43
refinedweb
371
68.47
Making The Robot GoMaking The Robot Go Your robot is unlikely to score many points if it doesn't go anywhere. This tutorial will show you how to access and turn the motors on your robot. Getting ReadyGetting Ready First things first, make sure that your robot is not about to drive off a table. Even if you're planning on turning on the spot, it's best to put your robot on the floor in case it does something unexpected. Next, you'll need to intialise the robot. For this exercise, you'll also need the "time" python library - this is because python doesn't automatically come with a wait function. import time import robot R = robot.Robot() Driving AroundDriving Around TIP Motor power is automatically scaled for the 3-6v motors included in the kit, if you are sourcing your own motors then see for how to allow faster speeds Now that everything is set up, it's time to set the motors. All the motors are stored in a list inside the Robot variable - to access the first motor, you can use R.motors[1], the second motor is found with R.motors[2].<br> Changing the speed of the motor is easy - just set the motor to a number from -100 to 100. Immediately setting the power to 100 can have unwanted side effects, so we'll start by setting them to half power: import time import robot R = robot.Robot() R.motors[1] = 50 R.motors[2] = 50 Running this program will make your robot move forwards. Unfortunately, it will never tell it to stop moving forwards, so hopefully you put it on the floor and it hasn't driven off the table. To fix this we can set the power of the motors to 0 after a couple seconds: import time import robot R = robot.Robot() R.motors[1] = 50 R.motors[2] = 50 time.sleep(2) R.motors[1] = 0 R.motors[2] = 0 To turn the robot, you just need to set one motor going forwards and the second motor going backwards. The following program makes the robot do a little dance - try it out! speed = 50 R.motors[1] = speed R.motors[2] = spaeed time.sleep(2) R.motors[1] = speed R.motors[2] = -speed time.sleep(2) R.motors[1] = -speed R.motors[2] = -speed time.sleep(2) R.motors[1] = -speed R.motors[2] = speed time.sleep(2) R.motors[1] = 0 R.motors[2] = 0 A final note, even if you set both motors to the same power, your robot probably won't drive in a perfectly straight line. This is due to defects in the motors, and unless you get specialised motors, no two motors will have the same offset. How your robot deals with this is up to you! Troubleshooting and Further ReadingTroubleshooting and Further Reading Connecting to the robot Uploading and running code Using the editor Motors
https://hr-robocon.org/docs/hello-motors.html
CC-MAIN-2019-43
refinedweb
492
75.91
As the name mentioned “simple”, AWS SNS is very straightforward and has an uncomplicated setup [as it does not have complex configuration while setting up]. But with plain configuration and straightforward setup, it doesn’t support things like webhook URLs. Communication platform notification like Slack/Google Chat is one of the things that it does not support directly. So, to solve this complication we need something which integrates with AWS SNS to solve these kinds of issue. Solution If we talk about integration, AWS SNS supports multiple integrations and one of the main integrations that we are looking for is- AWS Lambda & AWS Chatbot. Let’s talk about. But the main flaw of AWS Chatbots is that it only supports Slack & Amazon chime. An AWS resource which can solve communication platform issue for both slack & google chat is AWS Lambda. In simple words, AWS Lambda is an event-driven, serverless computing platform which means that in AWS Lambda, the code is executed based on the response of events triggered from AWS resources like API Gateway, S3, Kinesis, and many more. Requirements - AWS SNS topic - AWS SNS subscription - AWS Lambda - Google chat webhook URLs Steps - Google Chat Webhook creation First, we will create a webhook URL for Google chat. For that, we will create a room or if you have already a room created, skip the first and second steps. If the user already has a webhook URL present, skip the Google chat webhook creation part. Step 1: To create a google chat room, click on the “+” sign under “ROOMS”. Step 2: Provide Google chat room name and let other options be set as default. Step 3: Once room created, click on drag down menu of Google chat room and click on “Manage Webhooks”. Step 4: There will a pop-up of “Incoming webhooks”, it will ask for the webhook name & avatar/image URL. Currently, we generated a webhook URL which will be later used in the Lambda function. Flow diagram - AWS Lambda at the moment, we are setting up plain Lambda function which will later modify with custom code. Step 1: Under the AWS Lambda dashboard, click “Create function” to start the process of creating Lambda function. While setting-up Lambda function, the first option it will request for base template of Lambda function like “Author from scratch”, “Use a blueprint” etc. Choose “Author from scratch” for now which will later replace by custom code. Give Lambda function name and select language for function as AWS Lambda support multiple programming languages. It all depends on the user’s expertise and understanding of a specific programming language. Leave the other options default. For now, we are using python 3.8 Once you click “create function”, AWS will create a Lambda function with basic layout with default configuration. Flow diagram - Lambda function code we will create a zip bundle which will contain custom function and custom code dependencies ,which will replace base function template of Lambda function that we created. Step 1: Create a python “<NAME>.py” and add below code under that python file. The custom code contains Lambda function base and under that Lambda function base, there is hardcoded webhook URL of Google chat room which is triggered by Lambda handler. from httplib2 import Http from json import dumps def lambda_handler(event, context): url = "<WEBOOK-URL>" bot_message = {'text' : event['Records'][0]['Sns']['Message']} message_headers = {'Content-Type': 'application/json; charset=UTF-8'} http_obj = Http() response = http_obj.request( uri=url, method='POST', headers=message_headers, body=dumps(bot_message), ) return response Step 2: The only thing user will have to provide is the webhook URL in the code which is hardcoded in the function. url = "<WEBHOOK-URL>" All examples & code functions present on google & AWS official document: Once you create python file “<NAME>.py” and added custom code & substitute “<WEBHOOK-URL>” with Google chat webhook URL, We need to install all dependencies because AWS Lambda supports only a few libraries that don’t need extra steps to configure code dependencies. So, we need to install dependencies like httplib2 and Http that AWS Lambda doesn’t support in a specific folder and create a zip bundle of python code along with dependencies. Step 3: Gather “httplib2” & “requests” which is Dependent libraries of custom code using pip command with “-t” tag. $ sudo pip3 install httplib2 -t . $ sudo pip3 install requests -t . Using “-t” tag with pip command, pip command installed all dependent packages under the current directory that we mentioned, Check for all dependent libraries under the code directory. $ ls Step 4: Once you get python code with dependent packages under specific directory. We will bundle custom python code with dependent packages together and create zip file which will later replace default template of Lambda function. $ zip -r python_code.zip . Note down the python code file name & handler name that we specified. In our case, “lambda_function” is filename & “lambda_handler” is handler/function name. Both are default as per AWS Lambda. Flow diagram - Uploading python zip bundle We created Lambda function & zip bundle of custom code with dependent packages. Now, we will upload generated zip bundle to a Lambda function that we created. Step 1: On the right side of Lambda function under “function code”, click on “Actions” and select “upload a .zip file” and upload the python zip bundle that we created. it is giving a warning that code & specified libraries should now be greater than “10MB”, otherwise we need to upload code using the S3 bucket. For the time being, the size of zip bundle is not greater than 10MB. Once uploading process completed, it will give a pop-up of “code change”, click “OK”. AWS Lambda automatically unzip the code bundle and place content into the root directory of Lambda function which is “opstree-function” in our case. Step 2: Check all uploaded files & folders and also check the code that you specified. Step 3: Under “Runtime settings” section of Lambda function, change the runtime setting according to filename & handler name. This setting needs to be accurate & correct. Otherwise, your function will not call and generate error rather than functioning properly. For the time being, we are not changing anything. we used the default file path name & function name. We are done with Google chat integration with AWS Lambda by uploading the python code bundle under the specified AWS Lambda function. - Manual event Trigger At the moment, we create a “testing event” which will be used to check whether our code is working fine or not by triggering manual event using Lambda dashboard. AWS Lambda already provides multiple templates which basically contains JSON format output event response to test specific integration between Lambda and AWS resource [like SNS]. We will create a manual event and use default SNS JSON event response which will use in manual trigger. Step 1: Under Function code of AWS Lambda, click on “Test” and “Configure test event”. Step 2: Click “create new test event” and under Event template select “Amazon SNS Topic Notification” Step 3: After selecting the SNS template, give a proper event name. Once you provide all values, click “Create” Step 4: Once you create test event having SNS JSON event response template, under “Function code” click “drop-down arrow” and select the test event that you created. Once you select specific test event, click “test” to execute Lambda and wait for Lambda to execute the function and generate execution result Step 5: Once Lambda executed, it will prompt the execution result that the Lambda function executed successfully [ gave 200 status ] & it sends a response or bot message to google chat webhook. Step 6: At the moment, Lambda executed successfully which means, it trigger bot message to Google chat room webhook URL. Check Google chat room for testing response We have accomplished Lambda function containing custom code which integrated with Google chat webhook URL. Flow diagram - AWS SNS We will create a Simple notification service topic or SNS topic and create a SNS subscription that will integrate with AWS Lambda. As of now, we are creating SNS topic without SNS subscription attached to it. Step 1: To create SNS topic, Under Topic of Amazon SNS, Click “topic” and under that, click on “create topic”. Step 2: Provide configuration details like “topic type”, “Topic Name” & “display name” and let other options be set as default. Once topic created, you will see that there is no subscription defined or found under specific topic. Subscription is responsible for integration between AWS SNS topic and other resources like Lambda, email, etc. We’re now done with the AWS SNS topic part which is used to publish messages but there is no integration between AWS SNS & AWS Lambda. For that, we need an AWS SNS subscription that attaches to a specific SNS topic and AWS Lambda resource. Flow diagram - SNS Subscription for AWS SNS & Lambda Integration Under this section, we will create a AWS SNS subscription which is basically responsible for integration between AWS SNS topic & AWS Lambda. Step 1: Under the SNS dashboard, Click “create subscription” Step 2: Provide topic ARN that we created, provide “AWS Lambda” as protocol, and select endpoint of AWS Lambda that we created Step 3: Once SNS subscription created, it is configured under the specified topic that you provided while creating SNS subscription Step 4: Check SNS topic subscription list, you will see Endpoint & Lambda protocol specified subscription Step 5: Now, go to the Lambda dashboard and open the specified Lambda to check the trigger You will see that after creating subscription with a specified Lambda protocol, it automatically creates a trigger for AWS Lambda as shown in the above diagram. We are almost done with everything. Let’s manually “publish message” to make sure everything is working fine from AWS SNS to AWS Lambda. - Manual publish message AWS SNS topic support manual trigger to “Publish message” which takes basic information like subject, TTL & message body. Step 1: Under SNS topic section, select SNS topic click “publish message” for a manual trigger from SNS Step 2: Provide “subject” & “raw message” and let other options default. After providing values, click on “Publish message”. After that, it will prompt for other messages and provide you the message ID which you can use to debug things on the AWS Lambda side. Step 3: Once message published successfully, go to Google chat room to check whether you receiver notification or not. Once message published successfully, the AWS SNS & Google chat room integration part completed. Flow diagram Final thought The above representation is not fully configured because only manual triggers take place. It is basically use to check the response & behaviour and also use to check the working of resources and their integration . We need to integrate AWS SNS topic to specific AWS resources like Cloudwatch alarm to automatically generate message depending on the criteria and relay those generated message through AWS SNS which will later transfer to Lambda function in the JSON format which trigger the Webhook URL. The above blog/context is for Google chat webhook URL which can be replace by other communication platform webhook URL which definitely require few changes in custom code.
https://blog.opstree.com/tag/googlechat/
CC-MAIN-2022-27
refinedweb
1,856
59.64
Tutorial 26: DHT22 Digital Temp / Humidity Sensor So we've spent some time taking a look at analog sensors and getting those working with our Raspberry Pi. If we don't want to use analog sensors we can use a digital sensor. Digital sensors communicate with the Pi using binary data not analog voltage levels. There are several ways to communicate with a digital device and your Raspberry Pi. The DHT22 is a popular sensor among hobbyists for it's relative ease of use and due to it being inexpensive. In this tutorial I show you how to get your Raspberry Pi to use the DHT22 to measure temperature and humidity in Python 3. Note: The DHT22 and DHT11 and AM2302 will all work for this tutorial. The AM2302 is the DHT22 with different packaging. The DHT11 is a less expensive (and less accurate) version of the DHT22. This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson. DIFFICULTY CIRCUITRY UNDERSTANING PYTHON PROGRAMMING """ Remember to start the daemon with the command 'sudo pigpiod' before running this script. It needs to be restarted every time your pi is restarted. """ import pigpio import DHT22 from time import sleep # Initiate GPIO for pigpio pi = pigpio.pi() # Setup the sensor dht22 = DHT22.sensor(pi, 27) # use the actual GPIO pin name dht22.trigger() # We want our sleep time to be above 2 seconds. sleepTime = 3 def readDHT22(): # Get a new reading dht22.trigger() # Save our values humidity = '%.2f' % (dht22.humidity()) temp = '%.2f' % (dht22.temperature()) return (humidity, temp) while True: humidity, temperature = readDHT22() print("Humidity is: " + humidity + "%") print("Temperature is: " + temperature + "C") sleep(sleepTime)
http://thezanshow.com/electronics-tutorials/raspberry-pi/tutorial-26
CC-MAIN-2019-39
refinedweb
283
57.77
: Creating and running Vaadin applications in Eclipse Creating and running Vaadin applications in NetBeans Creating and running Vaadin applications using Maven Generated application explained Buttons Labels Text fields Notifications We will cover the details of configuring your development environment using Eclipse, NetBeans, and Maven. Feel free to jump straight to the section explaining your favorite IDE and skip those covering the other ones. Let's get our hands dirty! If you are using NetBeans, another IDE, or no IDE at all, you can safely skip this section. Steps to download and install Eclipse are as follows: Go to and download the latest (or your favorite) version of Eclipse for Java EE Developers. Extract the downloaded file to the directory you would like Eclipse to be installed in. Execute eclipse.exeor eclipseaccording to your operating system flavor. Guess what? We've just downloaded and installed Eclipse. Seriously, that was the very first step; now we need to install the Vaadin plugin for Eclipse. Steps to install the Vaadin plugin for Eclipse are as follows: In Eclipse, go to Help | Eclipse Marketplace…. Type Vaadinin the Find field inside the Search tab and press Enter. Click on the Install button besides the Vaadin Plugin for Eclipse heading. Eclipse will calculate some requirements and dependencies. Once it does, make sure the Vaadin Plugin for Eclipse is checked and click on Next. Read and accept the terms of the license agreement and click on Finish to start installing the plugin. The installation process can take some minutes. You will be prompted to accept installing software that contains unsigned content. Click on OK when asked to and let Eclipse continue with the installation. Finally, Eclipse will ask you if you want to restart the IDE. Do it. Once you restart Eclipse, you'll see a little reindeer logo on the toolbar, that's the Vaadin logo and means that the plugin is ready. We've just prepared Eclipse to start hacking! Using the Vaadin Plugin for Eclipse we'll be able to create new Vaadin projects, custom components, and themes. But before that, we will have to install a web server to deploy our Vaadin applications. Note You might have noted that the Vaadin Plugin for Eclipse installed an additional plugin: IvyDE. Ivy is a tool for managing dependencies, usually all the JAR files that your project needs. Don't worry too much if you don't know Ivy, just go through the following steps and we will get some fun in a couple of minutes, I promise. Steps to make Eclipse a Jetty-ready IDE are as follows: Go to Help | Eclipse Marketplace… in Eclipse. Type Run Jetty Runin the Find field inside the Search tab and press Enter. Click on the Install button besides the Run Jetty Run plugin. Make sure Run Jetty Run is checked and click on Next. Accept the license agreement and click on Finish. The installation process can take some minutes. You will be prompted to accept installing software that contains unsigned content. Click on OK when asked to and let Eclipse continue with the installation. Once Eclipse finishes installing the plugin, it will ask you if you want to restart the IDE. Do it again. We've successfully downloaded and installed our own Jetty server. Now we are ready to create and deploy our first Vaadin-powered application. Steps to create a Vaadin application are as follows: Navigate to File | New | Other…. Go to the Vaadin sub tree and select Vaadin 7 Project. Click on Next. Type welcomefor your project name and select the latest Vaadin version. Click on Finish to let Eclipse create the project for us. A new project has been created and we can deploy it to our server right away, so let's do it now! Steps to deploy and run a Vaadin application are as follows: Click on the Debug As… button on the toolbar and go to Debug As | Run Jetty. Alternatively, you can right click on your project and select Debug As | Run Jetty. Using your preferred browser, go to play with the just created Vaadin application. You can completely skip this section if you don't want to use NetBeans to develop Vaadin applications. Stay tuned otherwise. Installing NetBeans is quite easy. Let's see how it's done. Go to the URL and download the latest (or your favorite) version of NetBeans Java EE edition. Run the just downloaded installation file. The installation program will allow you to choose whether to install Apache Tomcat or Glassfish. Although you can use most Java servers, we will use Tomcat to deploy our applications. So, make sure you check Apache Tomcat and click on Next. Accept the terms of the license agreement and click on Next. Accept the terms of the JUnit license agreement and click on Next. Select the directory you would like NetBeans to be installed to and click on Next. Select the directory you would like Tomcat to be installed to and click on Next. Click on Install to start the installation process. Once the installation process is finished, you will be prompted to contribute to the NetBeans project. If you wish to, check the corresponding option and click on Finish, otherwise just click on the Finish button. As you can guess, we have installed NetBeans and we are ready to create our first Vaadin project. The best and the easiest way to create Vaadin 7 projects in NetBeans is by using Maven. Fortunately, NetBeans have very good support for Maven projects. If you don't know Maven, don't worry, be happy (thanks Bobby). Follow these steps and you'll get a Vaadin application willing to be hacked right away. Steps to create a new Vaadin project are as follows: A new project has been created and we can deploy it to our server right away, so let's do it now! Steps for deploying and testing the Vaadin application in NetBeans are as follows: Deploying an application in NetBeans couldn't be easier. Just select your welcome project and click on that little green arrow on the toolbar: Alternatively, you can do the same using the menu Run | Run Project (Vaadin Web Application). Even faster: F6. NetBeans will prompt you to select a server. You've installed Tomcat, right? Select the Apache Tomcat server and click on OK. Note that you can deploy to any server you have registered in NetBeans, we are using Tomcat just for the purposes of this example. Once you select the server, you will see a lot of messages on the output console. This is Maven preparing your application. Be patient, this process could take a while, only the first time. Go to play with the just created Vaadin application. You can completely skip this section if you don't want to use Maven to develop Vaadin applications. If you want to, and you are using NetBeans, please read the previous section if you haven't already. You are still here. Chances are that you are not using Eclipse or NetBeans. Well, actually, the easier way to get Vaadin 7 is through Maven. We are not covering how to install Maven here. If you haven't already, install Maven following the instructions given in. Steps for creating a new Vaadin project are as follows: Open a new terminal in your operating system and move to the directory you want your project to be created in. Run the command line shown as follows: mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=7.0.0 -Dpackaging=war Enter your preferred groupId and press Enter. For example, com.example.welcome. Enter welcomeas artifactId and press Enter. Press Enter to accept the default version. Press Enter to accept the default package. Confirm that everything is OK by typing Yand press Enter. If you can see the rewarding BUILD SUCCESS message, you have successfully created your first Vaadin project using Maven. You must have a new directory with all the generated files for your project. Steps for deploying and running Vaadin applications with Maven are as follows: Move to the directory that Maven created for your project. If you have specified welcomeas artifactId, then move to the welcomedirectory. Before actually deploying the application we must compile it and package it. To do that, run the command: mvn package This will take some time, so be patient. Now we are ready. Run the command: mvn jetty:run If you haven't run this before, you will see a very verbose Maven downloading stuff. Go to play with the just created Vaadin application. We have completed the first step of configuring our development environment to develop and run Vaadin applications. Now let's get started with the real cool stuff: the code. Open the file WelcomeUI.java (or MyVaadinUI.java if you are using NetBeans or Maven). You will see something like this: package com.example.welcome; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Label; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout;) { layout.addComponent(new Label("Thank you for clicking")); } }); layout.addComponent(button); } } This is going to be like a crash course on Vaadin 7. Let's pretend that we have created the previous class starting with an empty one like the following (package and import declarations will be omitted): public class WelcomeUI { } This class will be the root of all our UI components. When you create a Vaadin application, and once the user browses to the URL the application has been deployed to, a web page will be automatically generated using the logic you've implemented in a certain method of this class. Which method? One overridden from the UI class, so first, we got to extend the UI class as follows: public class WelcomeUI extends UI { } And the method to override is as follows: public class WelcomeUI extends UI { protected void init(VaadinRequest request) { } } Note Where is the init method called from? A Java web application is implemented using the Servlet technology. In short, a Servlet is a class that adds functionality to a web server. You can pair URLs with your own Servlet implementations and call any code you need to fulfill the requirements for your application. You do this in the web.xml file (or using annotations). Vaadin has a custom Servlet implementation which can be configured to call your own UI class implementation. Take a look at the web.xml file and find the Vaadin Servlet ( com.vaadin.server.VaadinServlet). Because this method will be called when the user browses to the application URL, you have the chance to build the user interface here. This is done by building a components tree. It's like a hierarchy where the components are arranged. We have already created the root component for the hierarchy, our WelcomeUI class. Now we can add visual components into the root component. But let's first see graphically how the component hierarchy should look when we finish our piece work: What we have here is a WelcomeUI having a VerticalLayout which has a Button and some Labels. VerticalLayout, what's that? Think of it as an invisible component that allows you to arrange its child components vertically on the page, one upon another. So the button is on the top, then goes the first label, then the second label, and so forth. Ok, back to the code. Take a look at how we can add that VerticalLayout invisible thing: public class WelcomeUI extends UI { protected void init(VaadinRequest request) { VerticalLayout layout = new VerticalLayout(); setContent(layout); } } We've created an instance of VerticalLayout and then set it to be the content of the UI. By calling the setContent(layout) method we are saying that layout is a child of our WelcomeUI instance. Now we have a layout in which we can add the button and all the n labels. Let's do it for the button: public class WelcomeUI extends UI { protected void init(VaadinRequest request) { VerticalLayout layout = new VerticalLayout(); setContent(layout); Button button = new Button("Click Me"); layout.addComponent(button); } } No rocket science. We create an instance of Button and add it to the layout. This means the button is a child of layout, it will be displayed inside the VerticalLayout. At this point, if we run the application, a button will be shown but it won't produce any response when clicked. Let's change that boredom: public class WelcomeUI extends UI { protected void init(VaadinRequest request) { VerticalLayout layout = new VerticalLayout(); setContent(layout); Button button = new Button("Click Me"); button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { // this will be called when button is clicked } }); layout.addComponent(button); } } Don't be afraid, we've added five lines of code, but most of them are brackets or comments. Button has a method that allows you to add click listeners. A click listener is a class that listens to click events, that's it. Here, we are using an anonymous class (you know Java, right?): new Button.ClickListener() { public void buttonClick(ClickEvent event) { // this will be called if button is clicked } } This class is an anonymous implementation of the Button.ClickListener interface. We are passing the just created instance to the addClickListener method in order to connect our code with the click event on the button. This kind of usage of anonymous classes is very common when developing Vaadin applications, especially in places where you need this callback behavior. We are ready to add the logic needed to dynamically add all those labels into the layout. We have a listener defining a method that will be called each time the button is clicked. So let's add the corresponding logic in that method: public class WelcomeUI extends UI { protected void init(VaadinRequest request) { final VerticalLayout layout = new VerticalLayout(); setContent(layout); Button button = new Button("Click Me"); button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { Label label = new Label("Thank you for clicking"); layout.addComponent(label); } }); layout.addComponent(button); } } This is similar to when we added a button to the layout. This time we're adding a label. A label allows you to show non-editable texts. Label components can display text in several formats. You can display plain text (that's the default), preformatted text, and HTML text. What if you want to display the "Thank you" part of the message on the label using a bold font? You are one line far of doing that. Try it! Use the setContentMode method of Label and the ContentMode enumeration to display HTML messages on your page. If we run the application right now, we will see a screen as shown in the following screenshot (before clicking the button several times, of course): It looks a little tight on the page. We can add some space around the layout using the setMargin method as shown in the following code snippet:) { Label label = new Label("Thank you for clicking"); layout.addComponent(label); } }); layout.addComponent(button); } } Now it will appear as follows: That's it. If you make some little refactor, you will get the original application that your IDE (or Maven) created. Now that you understand the code of the generated application, let's try adding a couple of features to make it a little bit more interesting. First, that boring "Thank you" message is not very useful. What if we develop an application that generates some random funny phrases? The user enters the name of two friends or something, and the application will produce random phrases about them. Follow these steps to add some fun to our application: Change your code to add the required text fields just before the line that creates the buttoninstance by adding the highlighted code: // ... setContent(layout); final TextField name1 = new TextField("Somebody's name"); final TextField name2 = new TextField("somebody's name"); layout.addComponent(name1); layout.addComponent(name2); Button button = new Button("Click Me"); // ... Add the business logic in a new method like this: public String getFunnyPhrase(String name1, String name2) { String[] verbs = new String[] { "eats", "melts", "breaks", "washes", "sells"}; String[] bodyParts = new String[] { "head", "hands", "waist", "eyes", "elbows"}; return name1 + " " +verbs[(int) (Math.random() * 100 % verbs.length)] + " " +name2 + "'s " +bodyParts[(int) (Math.random() * 100 % verbs.length)]; } Change the listener to display the message returned by the business method: public void buttonClick(ClickEvent event) { String phrase = getFunnyPhrase( name1.getValue(), name2.getValue()); layout.addComponent(new Label(phrase)); } We added a couple of text fields to our layout and then implemented a method to get the message to be shown on the labels. As you may have already guessed, the TextField class defines a getValue() method which returns the value which the user has introduced in the field. In this case, it happens to be a String. All input components (that is, components that get input from a user) have a getValue() method, which we can use to know the values introduced on the user interface. The following is a screenshot of the application (it seems that Maria doesn't like Juan too much): Notifications are a common feature in applications. You might need to notify that some event has occurred in your system when the user performs certain action. For example, in a CRUD (create, read, update, and delete) interface, your application should notify the user whether each action has been successfully executed or not. Vaadin makes it easy for you to show fancy notifications in your web applications. The Notification class has several static methods you can call from any part of your code to show notifications. For simple notifications you can make a call such as: Notification.show("User created"); This will display a message centered on the page shown as follows: The message will disappear when the user moves the mouse or presses any key. In the funny phrases application, it would be nice if the application alerts the user when no names are given instead of showing no-sense phrases. Would you be able to modify the application in order to make it show this alert using the Notification class? Try it! Tip Downloading the example code You can download the example code files for all Packt books you have purchased from your account at. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. There are a couple of concepts you must keep in mind to be proficient with Vaadin. Answer the following questions and test yourself about your current Vaadin level. Q1. Which method will be automatically called when somebody browses to your application URL? UI.setContent(Component component). UI.init(VaadinRequest request). VerticalLayout.init(VaadinRequest request). VerticalLayout.addComponent(Component component). Q2. Suppose you are overriding the init method of your own UI class. How would you set the root of your components tree? By calling the setContentmethod of the UIclass and passing the root component. By calling the addComponentmethod of the UIclass and passing the root component. Actually, an instance of the UIclass I'm writing will be the root of the tree. There's no such a thing as a components tree (it seems the book's author is going crazy). We learned some cool features in this chapter: We configured our development environment using Eclipse, NetBeans, and Maven. We learned the details of the code IDE wizards (or Maven) generated when we create a new project. We learned how components are internally arranged in a tree, where the root is a class extending UI. We learned that the initmethod of our UIclass is like a starting point for building our user interface. We used labels and buttons and attached them to a vertical layout. We also learned how easy it is to show notifications using the static methods of the Notificationclass. Now you are able to develop simple web applications using Vaadin. The next chapter will teach you how to use more complex input components.
https://www.packtpub.com/product/vaadin-7-ui-design-by-example-beginner-s-guide/9781782162261
CC-MAIN-2021-21
refinedweb
3,337
65.12
This article includes two very different basic assemblies and a couple of test assemblies for WPF. The first basic assembly is GraphLayout which implements the Reingold-Tilford algorithm, described here, to determine the placement of nodes in a tree structure. This tree is structured as a top down tree with the root at the top and the leaves at the bottom. This algorithm is entirely independent of any actual drawing of those nodes and so can be used for any purpose where such positioning is required. It includes options for vertical justification for nodes, collapsing of nodes, distance between sibling nodes and distance between non-sibling nodes. This assembly is not WPF specific and could easily be used to produce a GDI+ tree drawer (though I haven't included any here). It also includes a list of endpoints for lines which can be drawn as connectors between nodes. Currently, these lines are simply straight lines from the bottom center of the parent node to the top center of the child node, though it would be easy enough to modify them to draw different kinds of connectors. GraphLayout The second assembly is a WPF control subclassed from Panel which uses GraphLayout to determine where to place its child controls in a tree. Each non-root node has a dependency property for its parent node's name which is how the graph is strung together. Since this is a subclassed panel, the individual nodes can be any type of WPF control desired. This allows the tree to be specified in XAML as demonstrated in the TreeContainerTest test app or in code as demonstrated in the VisLogTree. Panel GraphLayout TreeContainerTest VisLogTree It also contains a Silverlight control which does the same thing. The primary difference with the Silverlight control is that the connections have to be added as a Path child to the tree container rather than painting the connections directly onto the control. Silverlight doesn't support the OnRender function for controls where they can be drawn to. I prefer the drawing method used in the WPF control so that there's not this "dangling" path control, but it really doesn't seem to be an option in Silverlight. I just got started with Silverlight a couple of days ago so if anybody knows better, I'd love to hear about it. The GraphLayout DLL had to be recompiled so it would be linked with the Silverlight libraries but otherwise was used unchanged. After figuring out all the little Silverlight quirks, the new Silverlight control worked the first time I tried it testifying to some extent to the universality of GraphLayout. OnRender There are several WPF controls which I could locate which make some effort to produce trees in WPF but so far as I can find, there are no free assemblies/source code which give a proper implementation of the Reingold-Tilford algorithm in a standard WPF fashion (i.e., a subclassed panel which can be implemented in XAML) and it seems like an obvious and valuable thing to do, so I've done it. There are LOTS of extensions which I can think of making here, but this seems pretty valuable as it is so I'm putting it out there and moving on to other things for the moment. The Reingold-Tilford algorithm can easiest be described as "recursively drawing all child graphs then jamming them all to the left as far as you can, leaving a fixed distance between nodes and finally cleaning up interior nodes which are jammed to the left but can be moved to the right for centering purposes". I know that's not incredibly intuitive - especially the last part - but reading the article cited above gives all the details (albeit not in a terribly clear manner in my estimation, nor in a way that corresponds very directly to my code which I implemented before reading this article and with not much more than the sketchy description given here - carefully slogging through the walkthrough is the only way I really understood it, even when I knew the basics of the algorithm). I tried to test all the cases, but I might have missed a few - there are lots of trees out there, so please mail me if you find any bugs. For the most part, if I found inconsistencies with the Parenting within the WPF control, I just didn't position the corresponding controls at all so they end up in the upper left of the TreeContainer control. This is so XAML isn't constantly blowing up and showing you nothing because of a thrown exception. If you see nodes in the upper left of your TreeContainer control, go in and check for consistency in your Parent properties. TreeContainer Parent GraphLayout (which probably should more properly be called TreeLayout although in the future I may add other Graph type layouts to it) provides an ITreeNode interface which represents (you guessed it) the nodes in the tree. GraphLayout.LayeredTreeDraw is the class which calculates all node positions. Its constructor takes an ITreeNode which represents the root of the tree and some global parameters which affect the positioning (minimum distance between nodes, vertical justification, etc.) and sets properties on all the nodes giving their proper positions in the final graphical tree.The ITreeNode interface is fairly simple. It includes TreeWidth and TreeHeight properties which return the width and height of the node. It also includes the boolean Collapsed property which is a readonly property telling whether the node should be collapsed. How this information is kept and set on the node is up to the implementation. The most important property is TreeChildren which returns the children of this node in a TreeNodeGroup collection. TreeNodeGroup is a simple enough class with an Add function to add ITreeNode objects to its collection. Finally, LayeredTreeDraw needs a place to poke its own private information into each node. You must implement PrivateNodeInfo which takes an object, stores it into the node and retrieves it back later. TreeLayout ITreeNode GraphLayout.LayeredTreeDraw TreeWidth TreeHeight Collapsed TreeChildren TreeNodeGroup Add LayeredTreeDraw PrivateNodeInfo There are three buffer distances associated with trees. The vertical buffer distance is the minimum distance between the layered rows of the tree. The horizontal buffer distance is the minimal distance between sibling nodes in the graph. The horizontal subtree distance is the minimal distance between nodes which are not direct siblings. This makes some graphs look better by further separating subtrees further than individual siblings. After constructing the LayeredTreeDraw object, you simply call LayoutTree() on it and then retrieve the information back from it. The X and Y coordinates for a given node are retrieved from a LayeredTreeDraw object called ltd with ltd.X(treeNode) and ltd.Y(treeNode) where "treeNode" is the ITreeNode in question. ltd.PxOverallWidth() and ltd.PxOverallHeight() return the width and height of the resultant tree. ltd.Connections() returns a list of TreeConnection objects. Each object has a parent ITreeNode and a child ITreeNode along with a list of DPoints which give a path of lines from the parent to the child. Since WPF and GDI+ use different definitions for "Point" I decided to implement a very lightweight DPoint structure which always uses doubles for the coordinates and can be used from either WPF or GDI+ (or anywhere else for that matter). Currently, these connectors give a single line between the parent and the child but this wouldn't be hard to change. Really, I was going to provide a set of different types of connectors, but maybe that will be something for the future. As it is, it is possible with different sized vertical nodes that a connector from a short node could overlap with a taller sibling node. One of the things I thought about doing was giving broken lines which would avoid this possibility. LayoutTree() ltd ltd.X(treeNode) ltd.Y(treeNode) treeNode ltd.PxOverallWidth() ltd.PxOverallHeight() ltd.Connections() TreeConnection DPoints DPoint That is pretty much it for GraphLayout. It's simple enough to use but definitely the most complicated part under the covers. TreeContainer is a WPF control subclassed from Panel which uses GraphLayout to layout its children. To be used properly, we have to know the tree structure of the children. This is handled by having a dependency property called "Root" which is set on the TreeContainer and has the string value of the name of the node which is the root of the tree. The children of the TreeContainer must all be TreeNodes which are content controls which may hold whatever controls you like. The TreeNodes have a TreeParent property which tells which node is their parent in the tree - again, a string value with the name of the parent node. Every TreeNode in the TreeContainer must have a parent property except the root node. There is also a Collapsible and Collapsed property on each TreeNode. If the Collapsible property is set to false for a node, it cannot be collapsed. It it is true, then the value of Collapsed determines whether a node is collapsed or not. In the VisLogTree sample, the nodes are buttons which toggle the collapse of the tree below them when pressed. These properties are all XAML settable. Root string TreeNodes TreeParent TreeNode root Collapsible TreeNode false true VisLogTree TreeContainer also contains some utility routines for creating the TreeNodes programmatically. This includes Clear() which clears all nodes from the TreeContainer and routines to add roots or interior nodes. At their simplest, these never have to deal directly with names in which case the code produces internal names. So, for instance, AddNode(Object, TreeNode) wraps the object in a new TreeNode, gives it a name and sets its parent to the TreeNode passed in. The TreeNode produced to wrap the object is returned. See the VisLogTree for an example of how to use these to easily produce the trees in a TreeContainer at runtime. TreeNodes Clear() AddNode(Object, TreeNode) The TreeNode containers implement the ITreeNode interface and hence are themselves the ITreeNodes necessary for GraphLayout's calculations. ITreeNodes There are many additions which could easily be added to this control. I've mentioned several in the text already - arbitrary pen for drawing connections, different types of connections, different orientations for the graph (i.e., left to right or bottom to top), a routed event for when nodes get collapsed or uncollapsed, etc. It seems like a valuable control at this point, however, and to be honest, I'm anxious for new territory to cover so I'm putting it out there as is. The algorithm proved to be much trickier than I had initially supposed. There are a fair number of exceptions and gotchas to the algorithm as I originally read it. It might have been easier to just blindly follow the algorithm as described in Dr. Dobb's article in the hyperlink above, but I didn't have that article ahead of time and there are a few things I'm not fond of in the algorithm as written there. There are two samples. One is an XAML version of the graph used in the paper mentioned above just to verify that it turned out correctly as described in the paper. The other gives the visual and logical tree for a dialog loosely based on one in "WPF Unleashed" by Adam Nathan, an excellent book. It's the dialog that Nathan uses to illustrate logical and visual trees so you can check that it gives the right information. The nodes in the second one are buttons which toggle whether their subgraphs are collapsed or not. There is also a button to remove or add back in the label at the top of the dialog which I used for debugging and left in there. A point I wasn't aware of until working on this control is the RegisterName/UnregisterName methods on FrameworkElements. When I first tried to create the tree control programmatically, I naively set the name on my TreeNodes and then used FindName() to locate them later. Wrong! If you do the same, you will be told that no such control name exists. You must use the RegisterName() method to register the name with the parent in order to make this work. Similarly, if you remove a control you really should do an UnregisterName(). I've read a lot on WPF and this is the first time I've ever seen this. It seems like this should be a little more visible in the documentation out there. The utilities on the TreeContainer which allow easy production of the TreeNodes takes care of all this automatically. RegisterName UnregisterName FrameworkElements FindName() RegisterName() UnregisterName() This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) <tc:TreeContainer HorizontalAlignment="Center" VerticalAlignment="Center" x: private void BuildTree() { Button btn_Root = new Button(); btn_Root.Content = "ROOT"; TreeNode root = Tree.AddRoot(btn_Root); for (int i = 0; i < 4; i++) { Button btn = new Button(); btn.Content = "Button_l1_" + i; TreeNode ch1 = Tree.AddNode(btn, btn.Content.ToString(), root); for (int j = 0; j < 2; j++) { Button btn2 = new Button(); btn2.Content = "Button_l2_" + i + "_" + j; Tree.AddNode(btn2, btn2.Content.ToString(), ch1); } } //Rotate Tree first here Tree.RenderTransform = new RotateTransform(-90); //Then rotate all TreeNode content children foreach (TreeNode n in Tree.Children) { Button btn = n.Content as Button; btn.LayoutTransform = new RotateTransform(90); } } private void DetermineFinalPositions(ITreeNode tn, int iLayer, double pxFromTop, double pxParentFromLeft) { double pxRowHeight = _lstLayerHeight[iLayer]; LayeredTreeInfo lti = Info(tn); double pxBottom; DPoint dptOrigin; lti.pxFromTop = pxFromTop + CalcJustify(tn.TreeHeight, pxRowHeight); pxBottom = lti.pxFromTop + tn.TreeHeight; if (pxBottom > PxOverallHeight) { PxOverallHeight = pxBottom; } lti.pxFromLeft = lti.pxLeftPosRelativeToParent + pxParentFromLeft; dptOrigin = new DPoint(lti.pxFromLeft + tn.TreeWidth / 2, lti.pxFromTop + tn.TreeHeight); iLayer++; TreeNodeGroup tng = GetChildren(tn); foreach (ITreeNode tnCur in tng) { List<DPoint> lstcpt = new List<DPoint>(); LayeredTreeInfo ltiCur = Info(tnCur); lstcpt.Add(dptOrigin); DetermineFinalPositions(tnCur, iLayer, pxFromTop + pxRowHeight + _pxBufferVertical, lti.pxFromLeft); //If parent node has only one child then no changes here, just a normal TreeConnection if (tng.Count == 1) { lstcpt.Add(new DPoint(ltiCur.pxFromLeft + tnCur.TreeWidth/2, ltiCur.pxFromTop)); _lsttcn.Add(new TreeConnection(tn, tnCur, lstcpt)); } else { //If parent node has more than one child then add the extra connection points double halfHeight = (ltiCur.pxFromTop - dptOrigin.Y)/2; DPoint p2 = new DPoint(dptOrigin.X, dptOrigin.Y + halfHeight); lstcpt.Add(p2); DPoint p3 = new DPoint(ltiCur.pxFromLeft + tnCur.TreeWidth / 2, dptOrigin.Y + halfHeight); lstcpt.Add(p3); DPoint p4 = new DPoint(ltiCur.pxFromLeft + tnCur.TreeWidth / 2, ltiCur.pxFromTop +5); lstcpt.Add(p4); _lsttcn.Add(new TreeConnection(tn, tnCur, lstcpt)); } } } base.OnRender(dc); if (Connections != null) { RenderOptions.SetEdgeMode(this, EdgeMode.Aliased); ... InvalidOperationException The NameScope to register the Name '_TreeNode0' was not found private void SetName(TreeNode tn, string strName) { tn.Name = strName; RegisterName(strName, tn); } TreeContainer.TreeContainer tree = new TreeContainer.TreeContainer(); System.Windows.Controls.Button button = new System.Windows.Controls.Button(); button.Content = "root"; button.Name = "root"; tree.AddRoot(button); xmlns:local="clr-namespace:TreeContainer" TreeContainer tc = tn.Parent as TreeContainer; if (tc != null) { tc.InvalidateVisual(); } General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/29518/A-Graph-Tree-Drawing-Control-for-WPF?msg=4093261
CC-MAIN-2016-22
refinedweb
2,538
54.63
Writing and Using Higher-Order and Anonymous Functions in Scala The hands-on lab is part of this learning path Ready for the real environment experience? Description When you use the functional programming paradigm, the function is the core component you need to focus on and use. It can be used as a value, so you can set a value for it (defining the body of a function), and you can use it as a function's argument, and also as a return value. A function that takes a function as an argument or returns it as a value is called a higher-order function. Most of the time, the functions you need to pass as an argument to another function are not shared and used by other components. In this situation, creating the functions could pollute the environment namespace (you have a lot of functions that are only used by a single entity or a single time). To avoid this scenario, you can pass the body of a function to another function without defining the function you need to pass as an argument; you simply pass the value. This kind of function is called anonymous function (you could hear about it also as a lambda function). That's because it doesn't have a formal definition, and can't be referred to. In this lab, you will start using higher-order functions and anonymous, with a focus on the three most used higher-order functions in functional programming: map, filter, and reduce. Learning Objectives Upon completion of this beginner level lab, you will be able to: - Understand higher-order functions and anonymous functions - Start using higher-order functions and anonymous functions to better solve problems Intended Audience This lab is intended for: - Software engineers focusing on the functional programming paradigm - Data engineers need to follow a clear way to handle and manipulate data Prerequisites To get the most out of this lab, you should have basic knowledge of Scala. To achieve this, the following labs are suggested:
https://cloudacademy.com/lab/writing-using-higher-order-anonymous-functions-scala/
CC-MAIN-2021-31
refinedweb
338
52.23
tempo Rotating Counters for Nodejs Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now! npm install tempo Tempo Scalable time-based counters that meant logging, graphing and providing a realtime statistics. All features in tempo are meant to have a constant size memory footprint defined by configuration. For a quick example, please look at examples/simple-use-case.js Features - simple counters that sync over redis using a hash structure - counters that keep track of historical data in buckets - syncing with redis for aggregation on multiple servers - throttling Use Case Lets say you are running a website and want to know in realtime where people are visiting. var redis = require('redis').createClient(); var tempo = require('tempo'); // create middleware to track counts // create time counter, increment and sync var min = tempo.min(); app.use(function (req, res, next) { // the '1' is unnecessary because increment defaults to '1' min.inc('requests', 1); if (min.getCount('requests') > 1000) return next('throttled'); next(); }) function showTotalRequestsInPastMin() { min.getKeys().forEach(function (k) { console.log(k, min.getCount(k)) }); } function showRequestsOverTime() { min.eachCount('requests', function (count, time) { console.log("Requsts at " + (new Date(time)).toString() + ': ' + count); }); console.log(tempo.getCount('requests') + ' request(s) made in the last minute'); } Counter The tempo TimedCounter class allows you to create a datastore object and keep data in memory. Instance methods var counter = new tempo.Counter(options) - options hash - per: milliseconds per bucket - buckets: number of buckets - timeout (optional): Time to live. Mainly for redis syncing. Defaults to (perbucket)+per2 Example for keeping data up to an hour of history: var tempo = require('tempo'); var ds = new tempo.TimedCounter({ per: 60000, buckets: 60 }); counter.inc(key, [n]); O(1) - key: entity name - n (optional, defaults to 1): a number to increment by. Keeping track of how many times a user has logged in in the past hour: var ds = require('tempo').hour(); ds.inc(userId); counter.getHistory(key); O(n) - key: entity name Grabbing logged in counts: var history = ds.getHistory(userId); Returns an array of counts (per bucket) counter.sync([callback]) O(nb) - redis client - prefix/namespace for the key to store in redis - tempo's keys will look something like ":" - O(nt) where n is the number of keys and b is the number of buckets counter.sync(redis, 'web-stats', callback); counter.getKeys(); O(nb) returns and array of all the keys in the counter O(nt) where n is the number of keys and b is the number of buckets counter.eachCount(key1, key2, ... [ callback ]) Runs a callback against every bucket in the counter with arguments (see examples below): counter.eachCount('key1', 'key2', function (keyCount1, keyCount2, time) { console.log('key1', keyCount1, ' at ' + (new Date(time)).toString()); console.log('key2', keyCount2, ' at ' + (new Date(time)).toString()); }); # Syncer ```javascript var tempo = require('tempo'); var syncer = new tempo.Syncer(redisClient); Instance methods syncer.addCounter(counter); Adds a counter to the list of counters to sync at once var counter = syncer.counter(options) Shortcut to instantiate counter and add it syncer.sync([ callback ]) Syncs all counters to redis (push and pull) syner.push([ callback ]) Pushes data to redis syncer.pull([ callback ]) Pulls data from redis syncer.start(type, interval) Starts running a type of sync at given intervals between syncs syncer.start('push', 3000) // push to redis every 3 seconds
https://www.npmjs.org/package/tempo
CC-MAIN-2014-15
refinedweb
556
52.26
How to Develop a REST API on an 8base Workspace Using serverless functions to stand up REST endpoints on an 8base Workspace By default, the 8base platform auto-generates an extremely powerful GraphQL API that gives you immediate API access to your data. Sometimes though, developers are using a 3rd party service or another tool that doesn’t easily support the authoring and execution of GraphQL queries. Instead, they require that a REST API (or discrete endpoints) be available. Developing a REST API in 8base can easily be accomplished using the Webhook custom function type. Using Webhooks, a developer can quickly code and deploy serverless functions that become available using traditional HTTP verbs (GET, POST, PUT, DELETE, etc.) and a unique path. Getting Started Building a REST API on 8base To get started building a REST API on top of an 8base workspace, you’re going to need to have the following resources created/installed. - An 8base Workspace (Free tier or Paid Plan) - 8base CLI installed (Instructions available here) - A Text Editor or IDE (VS Code, Atom, Sublime, or any other way to write code) Once all those things are ready, go ahead and open the command line and use the following commands to generate a new 8base server-side project. # If not authenticated, login via the CLI $ 8base login# Generate a new 8base project and select your desired workspace $ 8base init rest-api-tutorial# Move into the new directory $ cd rest-api-tutorial That’s it! Generating the Serverless Functions for your REST API Let’s go ahead and generate all of our serverless functions. We can do this pretty quickly using the 8base CLI’s generator commands. Using the generators, we’ll be able to create each one of our functions for each endpoint of our REST API. # Our Index records endpoint 8base generate webhook getUsers — method=GET — path=’/users’ — syntax=js# Our create record endpoint 8base generate webhook newUser — method=POST — path=’/users’ — syntax=js# Our get record endpoint 8base generate webhook getUser — method=GET — path=’/users/{id}’ — syntax=js# Our edit record endpoint 8base generate webhook editUser — method=PUT — path=’/users/{id}’ — syntax=js# Our delete record endpoint 8base generate webhook deleteUser — method=DELETE — path=’/users/{id}’ — syntax=js As you’ve probably noticed at this point, we’re building a REST API that gives access to our 8base workspace’s Users table. This is because the Users table is created with the workspace by default, thus you don’t need to create any new tables for the tutorial. That said, the same pattern we’ll cover would work for any other database table you choose to use (or multiple). Additionally — since we are just building this API for the Users table — it’s okay that all these functions are grouped at the top level of the src/webhooks director. If you are building a REST API that is going to deal with lots more tables or more custom endpoints, this directory structure might quickly feel busy/un-organized. Nothing stopping you from restructuring your directory to better suit your organizational needs! All you need to do is make sure that the function declaration in the 8base.yml file has a valid path to the function’s handler file/script. For example, take a look at the following directory structure and 8base.yml file: Directory Structure 8base.yml file functions: listUsers: type: webhook handler: code: src/webhooks/users/list/handler.js path: /users method: GET getUser: type: webhook handler: code: src/webhooks/users/get/handler.js path: '/users/{id}' method: GET createUser: type: webhook handler: code: src/webhooks/users/create/handler.js path: /users method: POST editUser: type: webhook handler: code: src/webhooks/users/edit/handler.js path: '/users/{id}' method: PUT deleteUser: type: webhook handler: code: src/webhooks/users/delete/handler.js path: '/users/{id}' method: DELETE For the sake of simplicity, let stick with the directory structure that was generated for us by the CLI! It’s only important to know that such reconfiguration is possible. Writing our REST APIs Serverless Functions Now that we have our serverless functions generated, let’s go ahead and start adding some code to them. What’s important to know about a Webhook function is that two important objects get passed through to the function via the event argument. They are data and pathParameters. The data argument is where any data sent via a POST or PUT request can get accessed. Meanwhile, any query params or URL params sent via the request become accessible in the pathParameters object. Therefore, if a GET request was made to the endpoint /users/{id}?local=en, the value for id and local would both be available via event.pathParameters[KEY]. GET User endpoint Knowing this, let’s set up the GET User ( /users/{id}) endpoint! To help with our GraphQL queries inside the function, add the GraphQL Tag NPM package using npm install -s graphql-tag. Then, go ahead and copy the code below into your getUser function’s handler file. /* Bring in any required imports for our function */ import gql from "graphql-tag";import { responseBuilder } from "../utils"; /* Declare the Query that gets used for the data fetching */ const QUERY = gql` query($id: ID!) { user(id: $id) { id createdAt updatedAt avatar { downloadUrl } roles { items { name } } } } `;module.exports = async (event, ctx) => { /* Get the customer ID from Path Parameters */ let { id } = event.pathParameters; let { user } = await ctx.api.gqlRequest(QUERY, { id }); if (!user) { return responseBuilder(404, { message: `No record found.`, errors: [] }); } return responseBuilder(200, { result: user }); }; You’ll likely spot an unrecognized import; responseBuilder. Webhook’s require that the following keys get declared in returned objects — statusCode, body, and (optionally) headers. Instead of writing out and every single response object explicitly, we can start generating them using a handy responseBuilder function. So let’s go ahead and create a new directory and file using the following commands and then place our responseBuilder function in there. $ mkdir src/webhooks/utils $ touch src/webhooks/utils/index.js Copy in the following script. /** * Webhook response objects require a statusCode attribute to be specified. * A response body can get specified as a stringified JSON object and any * custom headers set. */ export const responseBuilder = (code = 200, data = {}, headers = {}) => { /* If the status code is greater than 400, error! */ if (code >= 400) { /* Build the error response */ const err = { headers, statusCude: code, body: JSON.stringify({ errors: data.errors, timestamp: new Date().toJSON(), }), }; /* Console out the detailed error message */ console.log(err); /* Return the err */ return err; } return { headers, statusCode: code, body: JSON.stringify(data), }; }; Awesome! Almost as if we were building a controller method that runs a SQL query and then returns some serialized data, here were exercising the same pattern but using a serverless function that utilizes the GraphQL API. As you can imagine, the other functions are likely going to be similar. Let’s go ahead and set them all up before we move into testing. GET Users endpoint Let’s now set up a way to list all Users via our REST API. Go ahead and copy the code below into your getUsers function’s handler file. import gql from 'graphql-tag' import { responseBuilder } from '../utils'const QUERY = gql` query { usersList { count items { id createdAt updatedAt } } } ` module.exports = async (event, ctx) => { /* Get the customer ID from Path Parameters */ let { usersList } = await ctx.api.gqlRequest(QUERY)return responseBuilder(200, { result: usersList }) } POST User endpoint Let’s now set up a way to add new Users via our REST API. Go ahead and copy the code below into your newUser function’s handler file. import gql from 'graphql-tag' import { responseBuilder } from '../../utils' const MUTATION = gql` mutation($data: UserCreateInput!) { userCreate(data: $data) { id updatedAt createdAt } } ` module.exports = async (event, ctx) => { /** * Here we're pulling data out of the request to * pass it as the mutation input */ const { data } = event try { /* Run mutation with supplied data */ const { userCreate } = await ctx.api.gqlRequest(MUTATION, { data }) /* Success response */ return responseBuilder(200, { result: userCreate }) } catch ({ response: { errors } }) { /* Failure response */ return responseBuilder(400, { errors }) } } PUT User endpoint Let’s now set up a way to edit Users via our REST API. Go ahead and copy the code below into your editUser function’s handler file. import gql from 'graphql-tag' import { responseBuilder } from '../../utils'const MUTATION = gql` mutation($data: UserUpdateInput!) { userUpdate(data: $data) { id updatedAt createdAt } } ` module.exports = async (event, ctx) => { const { id } = event.pathParameters/* Combine the pathParameters with the event data */ const data = Object.assign(event.data, { id })try { /* Run mutation with supplied data */ const { userUpdate } = await ctx.api.gqlRequest(MUTATION, { data })/* Success response */ return responseBuilder(200, { result: userUpdate }) } catch ({ response: { errors } }) { /* Failure response */ return responseBuilder(400, { errors }) } } DELETE User endpoint Let’s now set up a way to edit Users via our REST API. Go ahead and copy the code below into your deleteUser function’s handler file. import gql from 'graphql-tag' import { responseBuilder } from '../../utils'const MUTATION = gql` mutation($id: ID!) { userDelete(data: { id: $id }) { success } } ` module.exports = async (event, ctx) => { const { id } = event.pathParameterstry { /* Run mutation with supplied data */ const { userDelete } = await ctx.api.gqlRequest(MUTATION, { id })/* Success response */ return responseBuilder(200, { result: userDelete }) } catch ({ response: { errors } }) { /* Failure response */ return responseBuilder(400, { errors }) } } Testing our REST API locally Nice work so far! Pretty straightforward, right? What’s next is an extremely important step; testing. That is, how do we run these functions locally to make sure they are behaving as expected? You may have noticed a directory called mocks that is in each of the function’s directories. Essentially, mocks allow us to structure a JSON payload that gets passed as the event argument to our function when testing locally. The JSON object that gets declared in a mock file will be the same argument passed to the function when testing — nothing more, nothing less. That said, let’s go ahead and run our getUsers function since it ignores the event argument. We can do this using the invoke-local CLI command, as well as expect a response that looks like the following: $ 8base invoke-local listUsers=> Result: { “headers”: {}, “statusCode”: 200, “body”: “{\”result\”:{\”count\”:1,\”items\”:[{\”id\”:\”SOME_USER_ID\”,\”firstName\”:\”Fred\”,\”lastName\”:\”Scholl\”,\”email\”:\”freijd@iud.com\”,\”createdAt\”:\”2020–11–19T19:26:53.922Z\”,\”updatedAt\”:\”2020–11–19T19:46:59.775Z\”}]}}” } Copy the id of the first returned user in the response. We’re going to use it to create a mock for our getUser function. So, now add the following JSON in the src/webhooks/getUser/mocks/request.json file. { “pathParameters”: { “id”: “[SOME_USER_ID]” } } With this mock set up, let’s go ahead and see if we can successfully use our REST API to get a user by their ID set in the URL params. $ 8base invoke-local getUser -m request=> Result: { “headers”: {}, “statusCode”: 200, “body”: “{\”result\”:{\”id\”:\”SOME_USER_ID\”,\”firstName\”:\”Fred\”,\”lastName\”:\”Scholl\”,\”email\”:\”freijd@iud.com\”,\”createdAt\”:\”2020–11–19T19:26:53.922Z\”,\”updatedAt\”:\”2020–11–19T19:46:59.775Z\”,\”avatar\”:null,\”roles\”:{\”items\”:[]}}}” } Now, what if you want to specify data? Like, when you want to test an update? The exact sample principle applies. We add a data key to our mock with the data we expect to be sent to our endpoint. Try it yourself by adding the following JSON in the src/webhooks/editUser/mocks/request.json file. { “data”: { “firstName”: “Freddy”, “lastName”: “Scholl”, }, “pathParameters”: { “id”: “SOME_USER_ID” } } Lastly, not all API requests are always successful… We added error handling to our functions because of this! Additionally, it would be a real pain to continuously be editing your mock file to first test a success, then failure, etc. To help with this, you’re able to create as many different mock files as you want and reference them by name! The CLI generator will help you and place the mock in the appropriate directory. For example: # Mock for a valid input for the editUser function 8base generate mock editUser — mockName success# Mock for a invalid input for the editUser function 8base generate mock editUser — mockName failure When running your tests now, you can use the different mocks to insure that both your error handling and successful responses are being properly returned. All you have to do is reference the mock file you wish to use by name via the -m flag. # Test an unsuccessful response 8base invoke-local editUser -m failure=> Result: { headers: {}, statusCode: 400, body: “{\”errors\”: [\r\n {\r\n \”message\”: \”Record for current filter not found.\”,\r\n \”locations\”: [],\r\n \”path\”: [\r\n \”userUpdate\”\r\n ],\r\n \”code\”: \”EntityNotFoundError\”,\r\n \”details\”: {\r\n \”id\”: \”Record for current filter not found.\”\r\n }\r\n }\r\n ],\r\n \”timestamp\”: \”2020–11–20T01:33:38.468Z\”\r\n}” } Deploying our REST API to 8base Deployment is going to be the easiest part here. Run 8base deploy… that’s it. However, you may be asking yourself a burning question at this point, “where do I find my endpoints?” Once everything is done being deployed, go ahead and run 8base describe in the CLI. You should get something like this back: All your endpoints are now available at{PATH_IN_TABLE_ABOVE}. Wrap Up 8base is an easy to use and scalable application backend that has an auto-generating GraphQL API. That said, for those developers building applications that require REST API interfaces, I hope this tutorial gave you some useful clues on how much can be accomplished using 8base! Feel free to reach out with any questions!
https://sebscholl.medium.com/how-to-develop-a-rest-api-on-an-8base-workspace-b555b67f169e?source=post_internal_links---------7----------------------------
CC-MAIN-2021-25
refinedweb
2,237
55.44
Lottery app in Actionscript 3 In this tutorial you will learn how to create a Lottery application in Actionscript 3. The Lottery app will display six unique random numbers from one to forty nine. The shaking effect is created using timeline animation and the Timer class is used to stop and display the random numbers on the balls. Lottery app in Actionscript 3 Step 1 – Create ball Open a new Actionscript 3 Flash file with the stage dimensions 500x200. Select the Oval tool (O) and draw a oval shape on the stage with the width and height at 67.50 pixels. I have given my oval a radial gradient, but this is optional. Then convert the oval into a movie clip (F8); Step 2 - Create ball holder Convert the ball movie clip into another movie clip (F8). Select the 'Export for Acionscript' checkbox and give the class name: BallHolder. This will give you a movie clip inside a movie clip. Rename 'layer 1' to 'ball'. Select the timeline and Insert five key frame(F6). On the second key frame move the ball 5 pixels to right; on the third key frame move the ball 5 pixels to the left; on the fourth key frame move the ball 5 pixels upwards and finally on the fifth key frame move the ball down 5 pixels. On the timeline insert a new layer call 'text' and select the Text tool with dynamic text and give the text field the instance name: output_txt. Embed the numerals glyphs. I have used the font Verdana with size 35pt. Now return to the main timeline and delete the ball holder movie clip from the stage. This movie clip will be added to stage dynamically so will not be needed on the stage. Step 3 - Restart button Select the Rectangle tool (T) and create a restart button. Convert the rectangle to a movie clip and give it the instance name: restart. Step 4 - Add Code Open a new AS3 class file with the name Lottery and type out the import statements and variables. package { import flash.events.Event; import flash.filters.DropShadowFilter; import flash.utils.Timer; import flash.events.TimerEvent; import flash.events.MouseEvent; import flash.display.MovieClip; public class Lottery extends MovieClip { private var numbersArray:Array; private var randomArray:Array; private var ballsArray:Array = new Array(); private var counter:int; private var numOfballs:uint = 6; private var timer:Timer; public function Lottery() { } } } Inside the constructor add the following code. This adds six balls on the stage with a x offset of 80 pixels. Each of the balls have a drop shadow with distance of 2 pixels, an angle of 90 degrees, black colour, blur of 5 pixels in the x and y and a strength of 80%. The ball instances get added to the ballsArray. for (var i:uint = 0; i < numOfballs; i++) { var bh:BallHolder = new BallHolder(); bh.x = 50 + (i * 80); bh.y = 80; bh.filters = [new DropShadowFilter(2,90,0,1,5,5,0.8)]; addChild(bh); ballsArray.push(bh); } This creates a new instance of the Timer class with a delay of two seconds and a repeat counts of six. The restart button is initially hidden and the mouse click event is added to the restart button. timer = new Timer(2000, numOfballs); timer.addEventListener(TimerEvent.TIMER, timerHandler); restart.visible = false; restart.addEventListener(MouseEvent.CLICK, restartHandler); init(); Next create an init function. This function starts with declaring two empty array and the counter at -1. To avoids any duplicate numbers I have firstly added the numbers 1-49 to the numbersArray then removed six random numbers from numbersArray. And started the timer. private function init():void { numbersArray = []; randomArray = []; counter = -1; for (var j:uint = 1; j < 50; j++) { numbersArray.push(j); } for (var k:uint = 0; k < numOfballs; k++) { randomArray.push(numbersArray.splice(Math.floor(Math.random()*numbersArray.length), 1)); } timer.start(); } The timeHandler function increments the counter and stops each of the balls moving and also display a unique random number for each ball. When all the balls have stopped and are displaying a random number then the restart button is shown and the timer is reset. private function timerHandler(e:TimerEvent):void { counter++; ballsArray[counter].gotoAndStop(1); ballsArray[counter].output_txt.text = randomArray[counter]; if (counter == 5) { restart.visible = true; timer.reset(); } } This function clears the numbers from the balls and restarts the moving animation and call the init function. private function restartHandler(e:MouseEvent):void { for (var i:uint = 0; i < numOfballs; i++) { ballsArray[i].output_txt.text = ""; ballsArray[i].play(); } init(); } step 5 Export the movie Ctrl + Enter. Additional animation effects The Lottery balls currently start shaking when the movie exports. I want the balls to drop from the top of the stage then start shaking afterwards. For the dropping effect I have used the TweenNano plugin with bounce easing which can be downloaded from greensock.com. Firsty, add the import statements. import com.greensock.TweenNano; import com.greensock.easing.*; In the constructors, change the ballholders y position from 80 to -bh.height. This offsets the balls so they appear off the stage. Delete the init() function call and add the enter frame event listener. stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler); Outside of the constructor added the following code. This function checks if the ballArray has six items before firing the TweenNano code. The check stops the animation starting before all the ballHolders have been added to ballsArray. The TweenNano code tweens the ball's y position to 80 pixels and waits two seconds to tween another ball. I have passed the target and the ii variable as the onComplete parameters. function enterFrameHandler(e:Event):void{ if(ballsArray.length == numOfballs){ stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler); for(var ii:uint = 0; ii < numOfballs; ii++){ TweenNano.to(ballsArray[ii], 1, {y:80, ease:Bounce.easeOut, delay:2 * ii, onComplete:completeHandler, onCompleteParams:[ ballsArray[ii], ii ]}); } } } This function starts the balls shaking animation. The init function is fired when all the balls are shaking. function completeHandler(mc:MovieClip, count:int):void{ mc.play(); if(count == 5) init(); } You can download the source files here.
http://www.ilike2flash.com/2011/06/lottery-app-in-actionscript-3.html
CC-MAIN-2017-04
refinedweb
1,017
67.86
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives In order to develop a fairly complex pipeline of operations for a content management system I am developing I found myself resorting to the old unix way of doing things: I need to process a large set of data (emails), so I set up a pipeline of coprocesses (with messages between each process relating to some chunk of email on disk) cp1 | cp2 | cp3 | cp4 | cp5 .. cp12 While this may seem trivial to most people here, I was struck by how profound this classic (20-30 yr old) approach is. Yes, I know that unix (shell) pipes are limited because they are only unidirectional, but if I followed status quo these days the implementation would have been a monolithic OO app (with cp 1-12 being objects passing messages to each other) or perhaps something more FP (with cp 1-12 being a chain of pure functions calls). Instead, here we have a truly concurrent solution that will take advantage of multiple CPUs, message passing, and has strict encapsulation -- all in a language neutral architecture. This came about as an experiment relating to using a severely restricted language (in this case AWK) to implement a fairly complex application. Working under Unix with minimal tools is yielding ways of thinking I haven't considered since my hardcore Unix days in the 80s. While this may sound like just a simple workflow problem, for my app there is some conditional variability in play where some processing may need to be excluded from the workflow, but that too can be handled by traditional unix piping: if a process has nothing to do to certain data (or is instructed by the previous process not to touch certain data) it is simply passed along (untouched) to the next process. Nothing mind boggling here, but it did strike me as interesting from a monolithic super language vs small language in a unix environment perspective. I've always felt that as programmers moved to Unix-like systems from more inflexible environments, they brought their monolithic programming habits with them, neglecting the native tradition of program construction out of small, sharp tools. Can anything be done to revive this potent tradition before it exists only in the aging memories of old farts and in the out-of-print and obsolete books of fallen Bell Labs demigods? BTW, in addition to Unix pipelines, there is also Paul Morrison's Flow-based Programming, which uses the same general architecture in the small. FBP is interesting because it was explicitly designed with the needs of business application programming in mind. I second the recommendation for Flow-based Programming. It's a very interesting and practical technique, and Morrison's book gives a lot of real-world examples. As regular readers of LtU know, Unix pipes are a special case of declarative concurrency. Chapter 4 of CTM explains this programming style and gives lots of examples. I sure hope this style will not be forgotten, because it has many advantages over the usual monolithic, shared-state style. The same goes for the message passing style, which has many of the advantages of declarative concurrency. For example, Erlang uses it to build highly fault-tolerant systems and E uses it to build secure systems. Fault tolerance and security are a lot simpler to achieve with dataflow and message passing than with the usual shared state style (i.e., monitors). One of the nice things about Erlang is how it offers a rich environment for doing concurrency: It is, in essence on par with Unix (with its rich support for process management). In Unix, coprocessing is natural and tied to processes (rather than "threads"). There is very rich (environmental) support for managing processes. Concurrency (process level!) is built into the core of Unix and message passing is the default paradigm. Erlang appears to mirror this but (potentially) at a much finer granularity. Often, even when other concurrency enabled languages (C++ with Posix Threads, Concurrent ML, Haskell, etc) are used for even coarse grain concurrency, the support environment is lacking (Can I independently manage the "threads"? Can I monitor them? Can I inspect their internal state? Remotely stop them? Signal them? Restart them? Remotely change their run priority?). This is what I am bemoaning. As we move to doing more message passing concurrency in our new monolithic languages, will the rich support be there (like processes under Unix)? Peter, I am still slugging away at CTM (great book!), does Mozart offer rich "tool" support for its concurrency? does Mozart offer rich "tool" support for its concurrency? There is both low-level support and some tool support. The threads can be managed to some degree (changing priorities, suspending and resuming, injecting exceptions, etc.). With the distributed programming abilities of Mozart, this can be done remotely. It's also easy to write abstractions that control concurrent programs (like the remotely updatable server in chapter 11 of CTM). There are some tools that work well in a concurrent setting: the Browser (visualization of data structures), the Ozcar debugger, the Profiler, the Distribution Panel (visualization of distributed execution), the Explorer (interactive constraint solving), and a few others. But there could be more tools to help programmers write concurrent programs! We would love to see people contribute some of these tools. There are also some language design issues that need to be tackled. For example, the ability to 'freeze', 'clone', and 'unfreeze' thread state would allow implementing flexible component-based programming, with first-class components that can be stopped, modified, and started. It would also allow adding continuations to Oz. Very nice. For my content management system (a hobby/diversion), I was only able to get my arms around the design and (evening time only) implementation by breaking the problem down into discrete components. I considered Concurrent ML (too hard to debug and too verbose) and Erlang (way more concurrency support than I needed) but ended up going with the "unix way". It had an interesting impact on my thinking. For example, before I adopted the "unix way" I had previously implemented a single component/process that parsed XHTML into a specially tagged list and then operated upon that list to do content-insertion magic. This was implemented in a language that had strong/easy XML parsing support. After my experience doing the "unix way", I would have broken the XHTML component into 2 pipe connected processes: cp1 (parse XHTML into a stream) -> cp2 (content-insertion magic). Now, I wonder how this approach would work using a concurrency-oriented approach in a rich concurrency environment likee Erlang or Mozart. It's amazing how studied ideas are often still a long way coming before one gets hit with the aha!. An Erlang-ish approach would have me doing something very similiar to the "unix way": Lots of little encapsulated processes (that do just one thing) feeding their results into other processes. I would be able to co-develop each component independently (swapping in better implementations, debugging components by instrumenting proxies for others) If Mozart gives me enough environment richness to support debugging this style... :-) My apologies to the collective lambda community if I am rambling the obvious. I am just fascinated how everything seems to be "connected". I would have never thought that the way I used to program 20 years ago (i.e. "the unix way") would come full circle for me. I came across this paper (PDF file) during a long (and ongoing) quest for CMS information/enlightenment. Perhaps you'll find some of its ideas worthwhile, such as its proposal to use the make utility to track page dependencies. Good luck on your project. In The essence of dataflow programming, Uustalu and Vene describe how to model dataflow and synchronous dataflow effects using comonads. No mention of concurrency, though. I've been working carefully through this paper and plan to post some comments soon. My quick, high-level take is that, contrary to the authors' implications, comonads are not particularly well suited to capturing dataflow semantics. True, it can be done, and theirs is an impressive accomplishment, but I think I've come up with an approach that is perhaps simpler or at least dual to theirs. My formulation of the semantics conforms to the intuition that dataflow languages are just functional languages with stream data types. (I gather that this has historically been a contentious assertion in the Lucid community, but it seems right to me so far.) In particular, I build an interpreter for a generic functional language assuming that the ground types support the following operations: class Ground g where lift0 :: a -> g a apply :: g (a -> b) -> g a -> g b and make scalar and stream instances of this class to get scalar (normal functional) and stream (dataflow) semantics. Also, and here I'm not as sure, I think there are some problems with their "distributive" semantics for synchronous dataflow. In particular, I believe their "if" is not point-wise, and should be, and their arithmetic operations do not cause an error when applied to streams with different clocks. One could excuse this latter problem by saying that their interpreter assumes type-checking has already rejected any such program, but I think a more mainstream approach to interpreters is that they turn static errors into dynamic ones, rather than turning static errors into silent failures. Your Ground is similar to a PreMonad: Ground PreMonad class Functor f where map :: (a -> b) -> f a -> f b class Functor p => PreMonad pwhere unit :: a -> f a -- at least they are related... instance Ground p => PreMonad p where unit = lift0 map = apply . unit Here's a draft of a paper I've started to work on that expands on my original comment above, giving near full code showing the use of Ground, etc. "Another Essence of Dataflow Programming" Are you this Ben Denckla, and are you intending on using this as a basis for a language for composing data flow objects for computer music? See my interests on my LtU user page. I wrote SuperCollider. SuperCollider looks like a neat language, independent of its music and audio parts (which of course make it automatically neat). My interest in dataflow is vaguely related to DSP but not to music. In general my work at the moment relates to semantics of block diagram languages, which of course often have dataflow underpinnings. I read an interesting draft paper by McBride and Paterson recently discussing a similar abstraction ("Applicative programming with effects" ). It seems like 'Ground' (or 'Applicative Functor') is a very practical abstraction that just has been overlooked for so long because of its close relation to monads. Indeed it is very relevant. I've updated my paper and code to use their terminology. The link to my paper in my original post above now points to that new file. It is good to find that my work is related to others. I think one of the reasons why Erlang is such a success for concurrent/scalable applications is that it models itself on the Operating System paradigm: everything is a process, an IPC primitive is in the language, processes can't interfere with eachother, failing processes can be insulated from the rest of the system, communication with the outside world is via 'ports' managed by wrappers (drivers). (Modern) Operating Systems are designed to be multitasking and scalable, why not use these ideas that have been refined over many years in modern languages/runtimes? Indeed, in Making Reliable Distributed Systems in the Presence of Software Errors Joe Armstrong makes a comment along the lines of 'an operating system merely presents Erlang with a set of device drivers' (poorly paraphrased from a shocking memory). as others have observed before, for properly behaved unix filters, we have: That's pretty cool. I'll have to look into that a little more. I've wondered why this isn't given as an example when trying to explain monads. Haven't most programmers used pipes, even in this age of Visual Studio and Eclipse? Another huge benefit from Unix piping: I can "drop in" replace any component by restarting the pipeline. (However, Erlang and Mozart can apparently replace a component without restarting.) On the other hand, Unix can "drop in" a replacement coded in any programming language. This serves me well for prototyping. My pipeline consists of awk, Tcl, C (and other stuff). I can prototpe a component in awk and replace it with C (or for that matter just keep that component in awk). Ah, mini-languages with domain specialties. I've gotten too used to big languages -- why would I want to replace a 10 line awk component with C, Perl, Tcl or XYZ? But there are some components in my pipeline that require more complex processing... Now, if only I could get the Erlang or Oz executables (engines) to run as lightweight as awk ;-) why would I want to replace a 10 line awk component with C, Perl, Tcl or XYZ? Because it's only one line of Perl? (joke) ;-) (True and beyond being a joke, a relevant point). But what is the cost of one line? 10MB core installation; 5 CPAN downloads; etc. My recent re-interest in awk (and other small languages) + unix is how it counters the batteries included (in a big sprawling library) mentality in mainstream languages today. Because your C program can access custom hardware that awk cannot. A 10 line awk script that (given your presumably large input) takes 10 hours to run can finish in a few seconds. Or maybe because your 10 line awk script isn't doing the job right, and the limitation turns out to be awk itself, and not a bug in your script. Use the right tool for the job. If a 10 line awk script will do the job well enough, fine. If not, find a new tool that will do the job better. Perl was created originally because the awk/sed combonation was not able to do some job that Larry Wall needed to do. So he set out to write a version of awk/sed that was able to deal with his additional needs. Yes, that is the whole point: Use the right tool for the job. Check out the context of my statement. I think we are in agreement :-) As an interesting aside, I recently replaced a horribly slow parser written in a proprietary language (part of an audit reduction product) with a combo of bourne shell and awk. The original took 2hrs to process 1GB of data, the bash/awk combo took 30 seconds. Now, I may be able to drop that down to fewer seconds if I code in C, but a quick "grep" through the data for one of the parse targets took around 20 seconds. I don't know if I can best the grep result and 30 seconds is probably fast enough ;-) You might want to take a look at upcoming Microsoft's Monad shell. It seems to be trying to generalize the Unix approach from streams of characters to streams of objects, albeit untyped. Ars Technica has a nice overview here. A language that might be interesting in the Flow-Based Programming context is OmniMark. This page, somewhat out of date, explains the basic concepts of the data-flow (or streaming, as its called in OmniMark), and this one presents recent additions to the streaming capabilities of the language. (Disclosure: I'm a designer and developer of the OmniMark language. I'm paid to do it. I'm not paid to evangelize it.) Concerning Unix pipes, I have a question that has bothered me for a while. Why are named pipes so notorious? ESR's online book The Art of Unix Programming even calls them "a bit of a historical relic". Compared to to the socket interface, they are much easier to use, they're open to shell programming, and also more scalable. Can anybody tell me what the problem is? Concerning Unix pipes, I have a question... I agree. They do have their quirks, but generally named pipes are great. Maybe it's just the crufty syntax of the old mknod? ;) Actually, I always felt like the shell should give me something like named pipes by itself, and that involving the filesystem was a little dirty. The generalized process redirection features in scsh are pretty nice. In some sense, Unix separates the concept of "filesystem" from the concept of "directory"; the persistent store can contain any number of filesystems. There is no requirement that a directory element actually refer to a file, though; it could refer to any named resource provided the directory metadata is rich enough to describe the resource. Named pipes are one such resource. A shell could, of course, bind a local name to a resource, and that is a useful feature. But it does not solve the same problem as persistent named resources. A named pipe is very much like a TCP socket (which also has a persistent name in the form of an IP/port); server and client processes can independently attach to it, without having to be otherwise related (except that in the case of named pipes, they must be running on the same OS instance, at least on common Unix implementations.) Keeping the persistent name in the directory structure strikes me as clean, not dirty; it allows code- and concept- reuse. For example, named pipes are subject to the same (limited) security model as files. Other OS's (Plan 9, for example) extend this concept in interesting and useful ways. You're right, of course. I probably should have been more clear... I've used named pipes in two ways. One is the persistent use you describe, and I agree that the filesystem makes perfect sense for that. The other use is basically to have a more flexible way of building pipelines than "a | b | c", and using the filesystem for these transient pipes often leads to nasty temporary files like /tmp/pipe.34543. To me, a file like that would rather be a local variable in the script or shell. Of course, I could imagine an extended filesystem that makes this cleaner (perhaps by adding a fs tree which is local to this process), but then from a language perspective that sounds an awful lot like local variables. And of course you can do exactly this in any language that gives you direct access to the system calls. Overall, though: yes, pipes are very cool, named or not. As I recall, the big problem with named pipes is that you don't have anything like accept(); if three processes open the pipe for writing simultaneously, the kernel doesn't do anything to disentangle the data they write to the pipe. You can manage a client/server mechanism, because the kernel guarantees that write()s of no more than PIPE_BUF bytes won't get intermingled. The client creates named pipes based on its process ID, opens the master named pipe, writes its process ID to it, and waits for the server to open the named pipes the client created. accept() write() PIPE_BUF But it's a pain—among other things, you have to put in machinery for deleting the pipes when you crash. Named pipes were probably a nice hack 20 years ago, because you could create a pipeline between unrelated processes. Today, you can do the same thing with nc, which lets you plumb a pipeline over TCP. nc Named pipes allow normal opens, but don't separate multiple writers cleanly. Local-domain sockets require the use of the socket API (they don't respond to open()), but separate multiple writers into different accept instances. Original LtU discussion. Python generators are much like pipe filters. def grep(predicate, seq): for v in seq: if predicate(v): yield v def uniq(seq): previous = None for v in seq: if v != previous: previous = v yield v def store(seq): f = open('output.txt', 'w') for line in seq: f.write(line) store(grep(lambda a: 'error' in a, uniq(open('input.txt', 'r')))) Python can't take advantage of multiple CPUs though. The components don't run concurrently; they are interleaved. When one component needs a value, the immediate upstream component runs for a moment until a value is produced. Python can't take advantage of multiple CPUs though. The components don't run concurrently; they are interleaved. When one component needs a value, the immediate upstream component runs for a moment until a value is produced. That's only a part of the problem with using generators as pipes. More serious is the fact that generators are not true coroutines: the consumer cannot resume a generator at an arbitrary point. The producer always drives. To see the full impact of the problem, try sketching an implementation of a diff or tee Unix utilities in Python. I don't know if Stackless Python has fixed this issue. Ruby is no better in this regard. Lula, OmniMark, and Modula-2 are the only languages with proper coroutines I know of. Continuations (delimited?) have been shown to be strong enough to implement them, so I suppose you can add Scheme to the list. Any language with support for threads can emulate coroutines as blocking threads, but this solution is prohibitively expensive. The sad thing is that coroutines are almost a trivial thing to implement at the VM level: what they boil down to is the ability to have multiple stacks. I don't know why so few modern virtual machines bother to support them. The first thing I look for when a new general-purpose language is released these days: support for lightweight concurrency. At least that gets us back to what we used to do all of the time under unix (via lightweight co-processes tied together with pipes, named pipes, shared memory and unix sockets). My motivation for co-processing (with awk+unix) is that it simplified the partitioning of my application. After reading many of the responses in this forum topic, If I had the time I would have considered Oz, Erlang or Scheme48 (now with lightweight threads!). Of what I've seen so far, only Oz and Erlang supports management of it's co-processes at a unix equivalent level. They come with tools. My experience with Python generators (limited), Posix threading (extensive), Concurrent ML (extensive) and Lua co-routines (limited) is that you have little introspective help when things go wrong. More serious is the fact that generators are not true coroutines: the consumer cannot resume a generator at an arbitrary point. The producer always drives. I think you might be misunderstanding something about Python generators; or I might be misunderstanding your post. When you say "the producer always drives", it sounds like you're talking about Ruby blocks; or worse, the "visitor pattern" often used in Java (ack). Python generators are different. A generator is more coroutine-like than you seem to think. For example, zip(gen1(), gen2()) works in Python (but not Ruby). zip(gen1(), gen2()) To see the full impact of the problem, try sketching an implementation of a diff or tee Unix utilities in Python. diff tee Just a sketch, but: def diff(s1, s2): for a, b in itertools.izip(s1, s2): if a != b: return 1 return 0 This works fine, even if s1 and s2 are both generator-iterators. s1 s2 (FWIW, I don't have the brain power to write my own diff; I would just suck the data into a list and use difflib. I don't think Unix diff operates on streams either, although I'm far from sure.) difflib tee is a little more tedious, as it's stateful, but it isn't really hard. And there's itertools.tee(). itertools.tee() ...Did I completely misunderstand you? The main limitation of Python generators (at least in Python 2.4) is that they are flat: a Python generator cannot invoke a subroutine which does the yielding for it; all yielding must be done directly in the generator. The unavailability of general resumption is not a theoretical barrier (as the Lua work shows), though it may be a practical one (it's hard to mix two separate Lua controller coroutines). I've written (in collaboration with a couple of others a component system entirely based on communicating python generators. Someone else was kind enough to post a link regarding this below (Kamaelia), but there is a key point: in order to get reuse from your coroutines (which is really where you boost the concurrency and dataflow), each of the items in the pipeline (or in ourcase graphlines too) needs to be simple. In practice single level generators (which you describe as flat) encourages simpler generators, and decomposition of a system into more generators. This naturally leads to a higher level of dataflow, and if you provide a mechanism for distributing generators over processes (we don't at present BTW), then you have a scaleable method for using multiple CPUs. We decouple generators by embedding the generator in a class, which provides all the generators a default multable object. That mutable object has inboxes and outboxes associated with it. If you take a piece of data from an inbox, you own it and can do what you like with it. If you place a piece data in an outbox you no longer own it. (We're thinking of an analogy based on paper passing from physical in/out-boxes) Putting these things together seems to result in a very high level of reuse. It also means that creating new components is quite simple - you write a small stub program that does what you want - and communicate with stdin and stdout. When you're happy with the results you replace this with sending data to outboxes and receiving data from inboxes. A stepped walkthrough making new components can be found here . A graphical runtime introspection tool is described here . A nascent command line shell is described here. Some example systems: (links to code in CVS) a paint programme , the simplest possible PVR , a visual system/pipeline builder, a presentation tool (1), a simple multicast based ogg vorbis streaming system, the same with a level of reliability added in, Dirac video encoding, decoding & playback, and a simple game for small children :-) (1) Handles 2 sets of slides, and a set of 'graph' slides all of which can overlap with transparency. (allows "sub-presentations" for example, which can be skipped if desired etc). I'm not really aiming to plug Kamaelia here, but more draw attention this the idea that just because python's generators are single level, this doesn't mean you can't do interesting things, in a very different way from you usually do. (And a way that we've found novices to programming find fairly natural) For those who prefer C++, we've also got a nascent (utterly naively coded) C++ version in CVS here . (Wraps up some primitives based using Duff's device). Again the aim is to point out that these techniques are more general than people think and single level yielding doesn't have to be the problem it might first appear to be - and that in fact it turns out to strengthen the system by the looks of things. Have fun :) I have an implementation of Flow-Based Programming in C which does manage multiple stacks, but the problem is that I/O hangs the whole app, unless you use asynchronous I/O (e.g. POSIX.1b standard?). On the other hand, I also have a Java implementation which implements the connections between threads using the 5.0 ArrayBlockingQueue class - only the connections are blocking, and it can take advantage of multiple processors, so I feel it should perform pretty well on a multiprocessor machine. See. Feedback would be appreciated! I have an implementation of Flow-Based Programming in C which does manage multiple stacks, but the problem is that I/O hangs the whole app Why not use separate Unix processes for each part and communicate with pipes? That would seem to give you the best of most worlds. Forgot to say it runs under Windows - I am not Unix-fluent. Also, the FBP networks are complex - simple pipelining with | isn't adequate. If I were to sum up all of my ramblings on this page, it would be: We need languages that provides (at least) unix process-like support for lightweight concurrency. At anytime now I expect Ehud to respond with How about Ada? ;-) I was just looking at the recent conference proceedings, and they're planning this for Erlang (for Linux & OS X), but its not there yet. Are there any scripting languages that do support this well? Hi! The old/new way of doing Concurrency is exemplified in: Kamaelia An Introduction OK, what is Kamaelia? A key aim of Kamaelia is to enable even novice programmers to create scalable and safe concurrent systems, quickly and easily Lego/K'nex for programmers. For people. For building things. It's about making concurrency on systems easier to use, so easy you forget that you're using it. It's been done once before, spectacularly well, so well many people forget it's there, a key example - unix pipelines. However it's been done in hardware since day 1, since that's how hardware works. One day, I sat back and realised that network systems looked almost identical in nature to the asynchronous hardware systems, conceptually, with one major exception. In hardware, you don't know who your buffers are connected to via wires. You have a protocol for getting that information over (be it a clock, or handshake circuits) but no other knowledge. Kamaelia was borne, technology wise, from the idea "what if we developed software like hardware" - each component with no direct knowledge of any other. Similar to programs in a unix pipeline. This is proving to be a very useful approach. Kamaelia is the result. Kamaelia is divided into 2 sections: * Axon - this is a framework, developed by application spikes, for wrapping active objects. Specifically these are generators (mainly) and threads. The resulting library at it's core is pretty simple - a novice programmer can learn python one week and implement their own version in about a week. * Kamaelia - this is the toy box - a library of components you can take and bolt together, and customise. This includes components for TCP/multicast clients and servers, backplanes, chassis, Dirac video encoding & decoding, Vorbis decoding, pygame & Tk based user interfaces and Tk, visualisation tools, presentation tools, games tools... The reason for concurrency here isn't because we're after performance, but due to the problems we're facing are naturally concurrent - millions of people watching content. Therefore, the aim is to make dealing with this concurrency simple/easy, or natural/fun. Hence the lego/K'nex analogy. What's the underlying metaphor we use? In hardware you have pins which the hardware "talks" to. In unix shells, you have stdin and stdout. For Kamaelia we decided to use something a little more concrete. Take a person sitting at a desk in a world pre-desktop-computing. She could have a bunch of inboxes & outboxes on her desk. Suppose that the inboxes are labelled "timesheets", "newhires", "fires", and that the outtrays are "accounts", "security", "HR". She can work on messages she gets on inboxes, and generate messages on outboxes. A postman then performs deliveries between the people - the active objects. The postman knows where things are going, and therefore if you need to add ing (say) auditing you can do that without modifying the way the person/active object works. This is precisely how Kamaelia works. It models itself on a real world system to encourage behaviours that simplify concurrency. Example Suppose I want to create a simple presentation tool - where I type some text, it goes to a server. People connect to that server and can "listen" to what I'm typing in a nice display, the three main sections of that system could look like this: -------------------- # Source console program pipeline( ConsoleReader(">>> "), TCPClient("talk.kamaelia.org", 1601), ).run() ------------------- # Client program # # Ticker with some decoration # Image("/home/zathras/Album/KamaeliaSpotting.png", position=(608,160) ).activate() pipeline( TCPClient("talk.kamaelia.org", 1602), Ticker() ).activate() Image("/home/zathras/Album/ChooseConcurrency.png", position=(115,475) ).run() ------------------- # Server Program Backplane("RandomTalk").activate()x pipeline( SingleServer( 1601 ), publishTo("RandomTalk"), ).activate() def ServeTalk(): # Protocol handler created to handle each connected client return subscribeTo("RandomTalk") SimpleServer( ServeTalk, 1602).run() You write new components in the same way as writing a small script. Start off reading/writing from stdin/stdout, until you're happy with it. You then replace inputs/outputs with inboxes/outboxes. That component can then be used with any other as long as they accept that form of python object. For example, consider exchanging ConsoleReader() & Ticker() with AlsaReader() and AlsaPlayer() to create a simple radio style system. That's the idea in a nutshell. (did I mention all the components above run in parallel?) Things people have done with it At R&D we've used it for sending subtitles to mobiles, building a networked audio mixer matrix, previewing PVR content on mobiles, joining multicast islands together using application layer tunneling and also a game for small children :-) I also use Kamaelia for all my presentations these days.. Summary And that is Kamaelia. A framework for components, a library of components, and a way of making systems quickly and easily. So, the reason I'm talking about it at Euro OSCON, is because we're Kamaelia itself to be useful & fun, and also it's seems to make concurrency easy to work with. Hopefully this should come over in my talk! More information: * Project Website: * Axon Tutorial: * Motivations (non-technical): * White paper (technical) : * Euro OSCON, Python Track, Wednesday 19th October 2005 Forking processes under modern implementations of Unix is actually a fairly lightweight thing to do, though not as lightweight as userland thread libraries, of course. Still, the days of systems when it was expensive to fork processes are pretty well done, at least for applications that don't need to handle gazillions of transactions per second. Pipes and unix domain sockets have been optimized over the years too. The cost of sending data between processes is quite low unless you have complex (and large) data structures that need to be serialized and reconstituted. Lightweight processes (LWP or kernel threads that share address spaces) was force-fitted into Unix. It's a foreign concept that was never truly made first class. Thanks for a good post, Todd. I find myself marvelling at Unix like this too. I should re-read The Unix Programming Environment and The Art of Unix Programming. ...but if I followed status quo these days the implementation would have been a monolithic OO app (with cp 1-12 being objects passing messages to each other)... What status quo is this? See the Command pattern from GoF. Handlers are fully componentised, nothing monolithic about it. Also, spawning processes might be too heavyweight—particularly for long chains. As ever, use the right paradigm for the job. If scalability is an issue, factor it into the design. However you factor the app, if you run under unix and it consists of one big executable (even if you do threading), you are a monolith (by my homegrown, no-authoritative definition! ;-) A lot of programs (running under Unix) tend to forget (or ignore) the rich patterns within the unix environment itself. Fork is not that expensive (anymore); socket/pipes are not inherently slow IPC mechanisms; init will spawn and manage long running processes; inetd will do TCP/IP connection management for simple one->one server apps, syslog is the standard log facility; etc. The "Unix Way" is certainly not the end-all. It has its many defects and limitations. But I've seen a lot of C++ code that goes out of its way to be a "world unto itself" (even when it was intended to be deployed under Unix). You can reword Greenspun's tenth law of programming onto unix (with apologies): Any sufficiently complicated monolithic program (under Unix) contains an ad-hoc, informally-specified bug-ridden slow implementation of half of the Unix Environment.
http://lambda-the-ultimate.org/node/1210
crawl-002
refinedweb
6,095
61.67
Classes in Toit In Toit, everything is an object, including things that may be non-object "primitive types" in other languages. For example, an integer is an object, and has methods like abs: // Method that takes an `int` and returns an `int`. foo x/int -> int: return x.abs // The absolute value of x. To create custom objects, we must first define a class: Here we have given our new class two fields, with integer types, and they are by default initialized to 42 and 103. We create new instance objects of the class by naming the class, no new keyword is needed: There are various ways to declare fields in objects: class Foo: // u is untyped and initialized to zero. u := 0 // v is an integer. v /int := 0 // w is a nullable integer (either null or an integer). w /int? := null // x is an integer, and it must be set by the constructor. x /int := ? // y is an integer, the field is immutable, the // constructor must set it. y /int // z has the same properties as y, but the short form is // better style. z /int ::= ? // LTUAE is a constant. When possible, prefer static // constants. LTUAE /int ::= 42 // PASSWORD is a static constant. static PASSWORD /string ::= "hunter2" constructor: x = y = z = 0 // Set the fields that must be set. Getters and Setters In Toit the external syntax for getters and setters is the same as for public fields: class Bar: x /int := ? constructor .x: my_function bar/Bar -> none: // Accesses public field x, or uses the x getter. print bar.x // Sets the public field x, or uses the x setter. bar.x = 42 If we later decide to make the x field private we rename it to have a final underscore. At the same time, we can introduce getters and setters that keep our class compatible with the old version: class Bar: x_ /int := ? // Private field. constructor .x_: // Getter, returns an int. x -> int: return x_ // Setter, takes an int, returns nothing. x= value/int -> none: x_ = value print "x_ was set to $x_" Inheritance Toit is an object-oriented language. The inheritance and typing mechanism for classes is similar to the one of Java: Classes can extend each other, with subclasses being subtypes in the typing system. class Point: x /int := 0 y /int := 0 class Point3D extends Point: z /int := 0 main: p /Point? := null // Local variable p has type Point (nullable). p = Point // Create point. // Since a Point3D is a type of point we can // assign p to refer to a Point3D. p = Point3D // Create 3d point. p.x = 42 // OK because Point has a field called x. p.z = 103 // Compile-time error: Point has no z field! p3 := p as Point3D // Cast p to a Point3D (with run-time check). p3.z = 103 // OK because p3 has the right static type. Interfaces A class can only extend one class, but can implement several interfaces. Like classes, interfaces act as types in Toit's type system, but unlike classes, they do not include implementations for the non-static methods they declare. Since a method signature declared in an interface has no implementation, the colon at the end of the first line is omitted: // To implement the Turtle interface, a class must have // these two methods. interface Turtle: forwards mm/int -> none turn degrees/int -> none // To be used as a Drawable, a class must have a method // called draw, which takes a Turtle and returns no value. interface Drawable: // No colon on the method declaration draw turtle/Turtle -> none // To have the type `Drawable` the Square class must both // declare that it `implements Drawable`, and contain the // `draw` method. class Square implements Drawable: draw turtle/Turtle -> none: 4.repeat: turtle.forwards 10 turtle.turn 90 main: // Variables can have interface types. Here `d` has the // type `Drawable`. d /Drawable := Square In Toit an interface can have static methods and constructors, but the constructors must be factory constructors. An abstract class has some similarities to a class and to an interface. Like a class, it can have fields and methods that its extending classes will inherit. Like an interface, it can have methods without implementations and constructors. The class and the non-static methods must be marked explicitly as abstract. A class cannot be instantiated (objects of that class cannot be created) unless it implements all the required methods from the abstract classes it extends: // Classes that extend `TurtleBase` must implement two // methods. abstract class TurtleBase: mileage := 0 // Classes that extend `TurtleBase` should call this after // moving a distance to register the distance the Turtle // has moved. register_mileage mm/int -> none: mileage += mm // Concrete (non-abstract) classes that extend TurtleBase // must implement these two methods. abstract forwards mm/int -> none abstract turn degrees/int -> none // The LogTurtle doesn't actually perform the drawing moves, // it just logs the moves a real turtle would make. class LogTurtle extends TurtleBase: forwards mm/int -> none: print "I moved forwards $(mm)mm." register_mileage mm turn degrees/int -> none: print "I turned $degrees degrees" main: turtle := LogTurtle 4.repeat: turtle.forwards 10 // >> I moved forwards 10mm. turtle.turn 90 // >> I turned 90 degrees. print "The turtle has travelled $(turtle.mileage)mm." Constructors Sometimes it is not enough to specify the initial values for fields. When there are more complex ways to initialize an object we make use of special functions called constructors. In Toit the constructor has the name constructor rather than having the same name as the class: import math class Vector: x /float y /float length /float constructor x_arg/float y_arg/float: x = x_arg y = y_arg length = math.sqrt x * x + y * y It is rather common that parameters of constructors are copied directly into fields of the new object, so there is a shorthand. By putting a dot ( .) in front of the parameter name, it is copied directly to the field of the same name: import math class Vector: x /float y /float length /float // The dots initialize fields x and y. No need to restate // the types of x and y here. constructor .x .y: length = math.sqrt x * x + y * y The shorthand .field parameter has the same type as the field it assigns to. Named Constructors By default, constructors have no name and are invoked with the name of the class. For example, the above unnamed constructor for the Vector class is invoked using the name Vector: main: // Create a new Vector using the unnamed constructor. // Note that there is no `new` keyword in Toit. v := Vector 10.0 7.5 We can have several unnamed constructors with different numbers of arguments. This is a natural result of the fact that Toit has argument-count overloading and argument-name overloading. However, sometimes it is more helpful to have constructors with different names. For example, the Vector class might have a polar constructor: import math class Vector: x /float y /float length /float constructor .x .y: length = math.sqrt x * x + y * y constructor.polar angle/float .length: // The dot above initializes the length field. x = length * (math.cos angle) y = length * (math.sin angle) main: // Use the unnamed Cartesian constructor. v := Vector 10.0 7.5 // Use the polar constructor. v2 := Vector.polar math.PI/6 8.0 Super-constructors In a class with inheritance you may want to invoke a constructor for the class you are extending. This is done with the super keyword: class Color: r /int g /int b /int constructor .r .g .b: class ColoredVector extends Vector: color /Color constructor x/float y/float .color: super x y // Calls the constructor of `Vector`. Factory constructors A factory constructor is rather like a static method that returns an instance of the class. Simply placing a return statement in a constructor makes it into a factory constructor. For example, it may be very common to create a special instance of an immutable class. Since it is immutable, the constructor can save memory by returning the same object every time. Here we have a factory constructor named origin. class Pair: x /int y /int // Regular constructor. constructor .x .y: // Private singleton object. static SINGLETON_ORIGIN_ ::= Pair 0 0 // Named factory constructor. constructor.origin: return SINGLETON_ORIGIN_ Factory constructors are the only kinds of constructors that interfaces can have. You cannot instantiate an interface, so regular constructors are not possible. An example of this is ByteArray, which is actually an interface because there are several different implementations. The constructors return a "regular" ByteArray: ba1 := ByteArray 10 // Constructs a ByteArray with 10 zeros. ba2 := ByteArray 5: it * 2 // Constructs #[0, 2, 4, 6, 8] Advanced constructor topics Some languages have a different syntax for initializing the field variables. For example, C++ has the initializer list which can precede the constructor body. In Dart a similar feature is also called initializer lists. Toit uses the same syntax for member initialization as for the rest of the constructor, so you don't have to learn two different syntaxes. Usually you don't have to worry about where the boundary is between field initialization and the rest of the constructor, but there can be situations where it matters. Implicitly, a constructor is split into two parts: the initialization, and the instance part. They are separated by the super call. If no super call is present, then Toit implicitly adds one as late as possible. This is either at the end of the constructor body, or as soon the code uses this, a reference to the newly constructed object. Implicit uses of this also count, for example by invoking a method, or by creating a lambda that captures this. class Point: x/float // This must be set during field initialization... y/float // ...of the constructor. // A method on the Point class stringify -> string: return "$x, $y" constructor x_arg/float y_arg/float: // Calling the stringify method uses "this". print "Created " + stringify x = x_arg // Error - this happens in the instance... y = y_arg // ...part of the constructor. Although the compiler will infer the boundary between field initialization and object creation you can always explicitly specify it by calling the super constructor. Even classes that don't explicitly extend another class extend the Object class so you can call the super constructor with no arguments: class Foo: x /int constructor: x = 12 // Explicit 'super' calls are possible but rare. super // Explicit `this` is also not normally needed. print this.x Before the object is created you can already refer to fields that have been assigned. These field accesses do not count as instance accesses. Immutable fields do not become immutable before the call to super in the constructor.. This still means the fields are immutable all other places than in the constructor, since no other parts of the program can obtain a reference to the newly constructed object before the super call. import math class Vector: x/float // These must be initialized in the initializer... y/float // ...part of the constructor, not later. length /float // A method on the Vector class stringify -> string: return "$x, $y" constructor.unit: x = 1.0 y = 1.0 // It is OK to access fields in the initializer part of // the constructor. length = math.sqrt x * x + y * y super // Implicit use of this when calling stringify. print stringify
https://docs.toit.io/language/objects-constructors-inheritance-interfaces/
CC-MAIN-2022-05
refinedweb
1,879
65.52
Welcome to Haskell IDE plugin for amazing Atom editor! This plugin is intended to help you in Haskell developing. Haskell IDE is currently in active development state. Haskell IDE works only with cabal projects. You can simply start Atom from cabal project root or drag and drop cabal project folder on editor and plugin will be started automatically. After saving the current file the check and linter processes will be executed. After processes are finished the results can be seen in plugin output panel. You can see different kind of results by switching Errors, Warnings and Lints tab buttons. By pressing with mouse button on any result inside output panel the Atom editor will open the appropriate file with cursor already at the position of this result. Also all the results can be seen near the line numbers if you position the mouse cursor over the handsome icon. And of course the results are highlighted inside editor view so you can easily locate where the problem is. Just position your mouse cursor above expression you want to know the type of and wait for some time. Tooltip will appear with everything you want to know. Remember that you need autocomplete-plus package to be installed to use Haskell IDE autocompletion feature. Autocompletion feature works for pragmas like LANGUAGE and OPTIONS_GHC. Also autocompletion works for import keyword. And of course autocompletion feature works inside functions to make your Haskelling happier. Not all the things I wanted from this feature was implemented. That is why autocompletion is subject to change the way you want! So you are welcome with suggestions how this feature can be changed to make your work with Haskell code more comfortable. Pelease, write issues with enhancement of autocompletion here. Now you can use stylish-haskell utility to indent pragmas, imports and data type definitions. Simply select Prettify from Haskel IDE menu or press magic combination of buttons to apply stylish-haskell to current file. $ apm install ide-haskell Open ~/.atom/config.cson by clicking Open Your Config in Atom menu. Manually add ide-haskell plugin section as in example below. 'ide-haskell': 'ghcModPath': '/path/to/ghc-mod' 'stylishHaskellPath': '/path/to/stylish-haskell' Following entries are also customizable in ide-haskell section ghcModPath- path to ghc-modutility stylishHaskellPath- path to stylish-haskellutility checkOnFileSave- check file after save (defaut is true) lintOnFileSave- lint file after save (defaut is true) switchTabOnCheck- switch to error tab after file check finished (defaut is true) expressionTypeInterval- after this period of time the process of getting the expression type will be started (milliseconds, default is 300) Changelog is available here. See the LICENSE.md for details. Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away.
https://atom.io/packages/ide-haskell
CC-MAIN-2015-14
refinedweb
460
56.55
Dynamic Component Generation in React! Creating A Page with JSON! How create a component dynamically? How to make a component generic? How to render a component from props? How to create a page from JSON? How to…? Most of us know how to make a component with JSX syntax. This is very simple once you have learned how React works and what JSX is. Sometimes we need to create a component dynamically, although not very often. For simple pages, we can create a structure to render the page dynamically. Even we can use this structure for forms. We can do something like in the example below. ... if(type === "text") return <Textfield/> if(type === "select") return <Select/> if(type === "Text"> return <Text/> ... But that will be looked ugly and complicated. We can make it a smarter way! React has a basic function called “createElement” which creates react elements from components you have. React.createElement(YourComponent, {...propsForYourComponent}); This is how we create a component dynamically but it doesn’t seem so dynamic, does it? We need to make a collection of the components that we will use on the page. const elements = { Textfield, Text ... }... return ( <> {React.createElement(elements.Textfield, {...props})} {React.createElement(elements.Text, {...props})} ... </> ) We need to prepare the body in a more dynamic way. React.createElement(elements["Textfield"], {...props}); It is ok but we can make a component that creates elements by props. const Element = ({type, props}) => { return React.createElement(elements["Textfield"], props); } Now, we have a component that can create the elements with props and this allows you to create a page dynamically. What does that mean? This means you can create your simple pages with a single JSON! const page = [ { type: "Header", }, { type: "Textfield", props: { label: "Simple Textfield", placeholder: "Simple placeholder", } }, { type: "Selectfield", props: { label: "Simple Selectfield", options: [ { value: "opt1", label: "Option1", } ] } } ] You can map your page array in your pages. Let’s see this in an example. In the example, there are: - A simple UI component sets, - An array that has the page structure, - Element component which creates the components dynamically, - Page component which creates the pages dynamically In 4 steps, we made a dynamic page generator. This is how easy it is! Why should I do that? - It helps you keep your components cleaner. So, you don't lose yourself in the component. - You can control all of your page structure in one place. So, you can change the layout easily. - If you use a third-party UI library, you can easily change it. All you need to is change the imports and adapt the components to the new UI library. - You can implement JSON Schema Forms easily! You can even create pages from a Database. - It helps in keeping the look of your pages similar. Thanks for your attention! I hope it was helpful to you. You may be learned something new or got a new idea. Please, I would be very happy if you leave your thoughts in the comments.
https://muratguney.medium.com/dynamic-component-generation-in-react-creating-a-page-with-json-56cd3f8e25f8?source=post_internal_links---------6----------------------------
CC-MAIN-2022-40
refinedweb
496
68.77
We have profiled our Java program and one of the places it is spending the most time is in GridBagLayout allocating new arrays. For example: GridBagLayoutInfo () { minWidth = new int[GridBagLayout.MAXGRIDSIZE]; minHeight = new int[GridBagLayout.MAXGRIDSIZE]; weightX = new double[GridBagLayout.MAXGRIDSIZE]; weightY = new double[GridBagLayout.MAXGRIDSIZE]; } This method is called many times. It allocates arrays of MAXGRIDSIZE (512) ints and doubles. Also there are other allocations of arrays of [MAXGRIDSIZE] elements. MAXGRIDSIZE is a static final int so a class can't even extend GridBagLayout and change its value. How about adding setMaxGridSize() to GridBagLayout, or a new constructor GridBagLayout(int maxGridSize)? (Review ID: 85571) ====================================================================== N/A We should change GridBagLayout to use a vector instead of a fixed array of size 512. This is not only a waste of memory when small numbers of components are in the Layout, but it limits the maximum grid to 512. We have had complaints about both of these problems. We need to clean up GridBagLayout and GridBagLayoutInfo to use Vectors instead of the arrays. xxxxx@xxxxx 1999-12-22 Because of a risk of breaking serialization with older versions and that both Vectors and ArrayList work with objects not int and double arrays causing quite a bit of extra code to be written for a slight performance gain this is being deffered until Tiger xxxxx@xxxxx 2000-09-07 Comitting to tiger, as it should also fix 4623196. xxxxx@xxxxx 2003-10-15 My original intention was to replace the int[] and double[] arrays in GridBagLayoutInfo with ArrayLists. However it turns out that a new GridBagLayoutInfo is created everytime the container is layed out. By putting off creation of the GridBagLayoutInfo until we know the width and height of the grid, we can create arrays of the exact size needed. This is a shorter-reaching and more compatible change (for instance, this doesn't break serialization). I still employed local ArrayLists during layout when the GridBagConstraints are being examined and before the grid size is known. I've attached the modified code example from the JavaDoc (GridBagEx1) which I used to take some performance numbers. It shows the Frame and then does a series of resizes. Overall, it looks like runtime performance is a wash running with or without my fix. Really, though, it doesn't look like the allocation of arrays is really a hotspot at all. This may have been true in the 1.1.* days, but I think it's no longer the case. On the bright side, OptimizeIt reports 33k less memory being used by int[]s, and the fix causes roughly one quarter the number of GCs: java -verbosegc before: $ c:/tiger/tiger/build/windows-i586/bin/java -verbosegc -cp . GridBagEx2 [GC 511K->211K(1984K), 0.0071006 secs] [GC 723K->275K(1984K), 0.0045100 secs] [GC 783K->282K(1984K), 0.0014622 secs] [GC 793K->294K(1984K), 0.0005599 secs] [GC 806K->279K(1984K), 0.0009201 secs] [GC 790K->289K(1984K), 0.0005169 secs] [GC 799K->291K(1984K), 0.0006515 secs] [GC 802K->292K(1984K), 0.0005072 secs] [GC 803K->296K(1984K), 0.0005159 secs] [GC 805K->297K(1984K), 0.0005135 secs] [GC 805K->298K(1984K), 0.0004632 secs] [GC 810K->299K(1984K), 0.0005008 secs] [GC 810K->306K(1984K), 0.0005099 secs] [GC 818K->311K(1984K), 0.0005298 secs] [GC 821K->310K(1984K), 0.0005345 secs] [GC 822K->314K(1984K), 0.0004714 secs] [GC 826K->300K(1984K), 0.0005099 secs] [GC 812K->304K(1984K), 0.0005232 secs] [GC 813K->306K(1984K), 0.0004495 secs] [GC 814K->307K(1984K), 0.0004899 secs] [GC 817K->308K(1984K), 0.0004619 secs] [GC 817K->309K(1984K), 0.0005342 secs] [GC 818K->311K(1984K), 0.0005230 secs] [GC 822K->316K(1984K), 0.0004956 secs] [GC 827K->321K(1984K), 0.0005094 secs] [GC 833K->310K(1984K), 0.0004434 secs] [GC 822K->312K(1984K), 0.0005476 secs] java -verbosegc after: $ c:/tiger/tiger/build/windows-i586/bin/java -verbosegc -cp . GridBagEx2 [GC 511K->211K(1984K), 0.0071040 secs] [GC 723K->286K(1984K), 0.0046603 secs] [GC 798K->296K(1984K), 0.0020308 secs] [GC 808K->297K(1984K), 0.0009177 secs] [GC 809K->298K(1984K), 0.0007943 secs] [GC 810K->299K(1984K), 0.0009182 secs] [GC 811K->299K(1984K), 0.0008974 secs] [GC 811K->301K(1984K), 0.0007395 secs] Also (other practical limits notwithstanding), it's now possible to create a GridBagLayout with > 512 Components wide and high. The following test used to throw an ArrayIndexOutOfBoundsException. It now runs to completion, provided you sufficently increase the heap size (: // Flex the new GridBagLayout with more than 512 items wide & high import java.awt.*; public class BigGBL { public static final int ITEMS = 600; public static void main(String[] args) { GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); Panel panel = new Panel(); panel.setLayout(gbl); for (int i = 0; i < ITEMS; i++) { for (int j = 0; j < ITEMS; j++) { gbc.gridx = i; gbc.gridy = j; panel.add(new Label("Label"), gbc); } } panel.doLayout(); } } xxxxx@xxxxx 2003-10-20 This is especially prevalent when using Swing menus, as each JPopupMenu uses a GridLagLayout to layout the menu items. Also, GridBagLayout allocates a Hashtable for the components and the HashtableEntry items also take a fair bit of memory. JPopupMenu should also be changed not to use GridBagLayout, as the enhancement suggested above doesn't get around this problem. The user has no control over the size of the grid. Might it not be a better idea to grow the grid as necessary when components are added. Using Vectors instead of arrays might really slow down the layout process. Please consider using of arrays, but dynamically expanded. the problem still occurs in j2sdk 1.3.0. arggghhhhh! This is marked as an RFE? It's an out and out bug. What a cop out! Furthermore, the bug is almost 2 years old, and fairly trivial to fix. Dynamic rrays/ArrayLists/LinkedLists/Vectors could all be used, or you could just add another constructor where the user specified the MAXGRIDSIZE. It is not just a performance gain that is at stake. I have an application that is ready to go out in two weeks that breaks because the user can add an indeterminate number of entries to a JComponent viewed from within a JScrollPane. As soon as the number exceeds 512 (and there are 18 components added for each new object the user selects, which limits me to only about 28) the thing crashes!! I would rather you broke serialization and fixed this! We've replaced GridBagLayout with our own version which dynamically expands arrays and this saved about 3M of the javaw.exe process memory. How can you replace with our own version without replacing all of swing? If you just replace just GridBagLayout, you probably break your agreement with Sun. Best submit your modified version to Sun for inclusion in 1.4. It's has been 3.5 years since the original bug report. This bug still present in 1.4.1. It's about time it is fixed once and for all. This memory leak, however insignificant per instance makes a big difference if your app uses lots of layout managers. It also makes it impossible to add more than 512 rows or columns to a component using the GridBagLayout, a case that I have to solve. This is still pain in butt, one of our oprations critical application has devleoped using GridBagLayout and now the necessity increased to put more than 512 components which started throwing an exception. What's the solution guys? I thought this is fixed in 1.5 (5.0) A solution was found one year ago. Why is this still not in J2SE 1.5.0 RC ? Just today the limitation to 512 has caused us many headaches. I'm a little bit confused as to whether gridbags of size > 512 are supposed to work in 1.5 RC or not. They were working in build 1.5.0-beta-b32c but not in build 1.5.0-rc-b63. What's going on here? Looking at the source code today, which is the source of the released JDK 5.0, the gridbaglayout seems to revert back to 512. This shocks me. I am not sure what is going on. Please someone at Sun give us a hint. According to bug 5107980 the fix was backed out because of regressions the fix introduced. Sun is claiming smaller memory footprint with 5.0, but I wonder if there numbers are based on having the fix in or out. I'm very dissapointed. I can't believe this is still a problem after FIVE YEARS! Is this bug fixed in current release of 5.0 or not? Some of your docs say yes others say no, which is it? This defect is fixed in JDK6.0, not in JDK5.0.
http://bugs.sun.com/bugdatabase/view_bug.do%3Fbug_id=4254022
crawl-002
refinedweb
1,473
78.04
MatryoshkaMatryoshka Generalized folds, unfolds, and traversals for fixed point data structures in Scala. External ResourcesExternal Resources - Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire – the iconic paper that collected a lot of this info for the first time - Recursion Schemes: A Field Guide (Redux) – Ed Kmett’s summary of various folds and unfolds, with links to Haskell code - Unifying Structured Recursion Schemes – a newer paper on how to generalize recursion schemes - Efficient Nanopass Compilers using Cats and Matryoshka – Greg Pfeil’s talk on this library (and some other things) - Fix Haskell (by eliminating recursion) – Greg Pfeil’s talk on recursion schemes in Haskell - Recursion schemes by example - Tim Williams slides talk - Practical Recursion Schemes - Jared Tobin - Promorphisms, Pre and Post - Jared Tobin - Time Traveling Recursion Schemes - Jared Tobin - Automatic Differentiation via recursion schemes - Jared Tobin UsageUsage - Add a dependency libraryDependencies += "com.slamdata" %% "matryoshka-core" % "0.18.3" Optionally, you can also depend on matryoshka-scalacheck to get Arbitrary/ Cogen/ Shrink instances for a bunch of pattern functors and fixed points. Apply some fix for SI-2712. Prior to 2.12, use @milessabin’s compiler plugin. As of 2.12, you can simply add scalacOptions += "-Ypartial-unification"to your build.sbt. Add imports as needed. Usually the following should suffice import matryoshka._ import matryoshka.implicits._ but if you need some of our pattern functors, then matryoshka.patterns._ should be added. Also, there will be cases where you need to specify explicit types (although we generally recommend abstracting over {Bir|Cor|R}ecursive type classes), so you may need matryoshka.data._ (for Fix, Mu, and Nu) and/or matryoshka.instances.fixedpoint._ for things like Nat, List, Cofree, etc. defined in terms of Mu/ Nu. IntroductionIntroduction This library is predicated on the idea of rewriting your recursive data structures, replacing the recursive type reference with a fresh type parameter. sealed abstract class Expr final case class Num(value: Long) extends Expr final case class Mul(l: Expr, r: Expr) extends Expr could be rewritten as sealed abstract class Expr[A] final case class Num[A](value: Long) extends Expr[A] final case class Mul[A](l: A, r: A) extends Expr[A] This abstract class generally allows a Traverse instance (or at least a Functor instance). Then you use one of the fixed point type constructors below to regain your recursive type. You may also want instances for Delay[Equal, ?], Delay[Order, ?], and Delay[Show, ?] (which are very similar to their non- Delay equivalents) to get instances for fixed points of your functor. Fixpoint TypesFixpoint Types These types take a one-arg type constructor and provide a recursive form of it. All of these types have instances for Recursive, Corecursive, FunctorT, TraverseT, Equal, Show, and Arbitrary type classes unless otherwise noted. Fix– This is the simplest fixpoint type, implemented with general recursion. Mu– This is for inductive (finite) recursive structures, models the concept of “data”, aka, the “least fixed point”. Nu– This is for coinductive (potentially infinite) recursive structures, models the concept of “codata”, aka, the “greatest fixed point”. Cofree[?[_], A]– Only has a Corecursiveinstance if there’s a Monoidfor A. This represents a structure with some metadata attached to each node. In addition to the usual operations, it can also be folded using an Elgot algebra. Free[?[_], A]– Does not have a Recursiveinstance. In addition to the usual operations, it can also be created by unfolding with an Elgot coalgebra. So a type like Mu[Expr] is now isomorphic to the original recursive type. However, the point is to avoid operating on recursive types directly … AlgebrasAlgebras A structure like this makes it possible to separate recursion from your operations. You can now write transformations that operate on only a single node of your structure at a time. This diagram covers the major classes of transformations. The most basic ones are in the center and the arrows show how they can be generalized in various ways. Here is a very simple example of an algebra ( eval) and how to apply it to a recursive structure. // we will need a Functor[Expr] in order to call embed bellow implicit val exprFunctor = new scalaz.Functor[Expr] { override def map[A, B](fa: Expr[A])(f: (A) => B) = fa match{ case Num(value) => Num[B](value) case Mul(l, r) => Mul(f(l), f(r)) } } val eval: Algebra[Expr, Long] = { // i.e. Expr[Long] => Long case Num(x) => x case Mul(x, y) => x * y } def someExpr[T](implicit T: Corecursive.Aux[T, Expr]): T = Mul(Num[T](2).embed, Mul(Num[T](3).embed, Num[T](4).embed).embed).embed import matryoshka.data.Mu someExpr[Mu[Expr]].cata(eval) // ⇒ 24 The .embed calls in someExpr wrap the nodes in the fixed point type. embed is generic, and we abstract someExpr over the fixed point type (only requiring that it has an instance of Corecursive), so we can postpone the choice of the fixed point as long as possible. Recursion SchemesRecursion Schemes Here is a cheat-sheet (also available in PDF) for some of them. FoldsFolds Those algebras can be applied recursively to your structures using many different folds. cata in the example above is the simplest fold. It traverses the structure bottom-up, applying the algebra to each node. That is the general behavior of a fold, but more complex ones allow for various comonads and monads to affect the result. UnfoldsUnfolds These are the dual of folds – using coalgebras to deconstruct values into parts, top-down. They are defined in the Corecursive type class. RefoldsRefolds Refolds compose an unfold with a fold, never actually constructing the intermediate fixed-point structure. Therefore, they are available on any value, and are not part of a type class. TransformationsTransformations The structure of these type classes is similar to Recursive and Corecursive, but rather than separating them between bottom-up and top-down traversals, FunctorT has both bottom-up and top-down traversals (and refold), while TraverseT has all the Kleisli variants (paralleling how Traverse extends Functor). A fixed-point type that has both Recursive and Corecursive instances has an implied TraverseT instance. The benefits of these classes is that it is possible to define the required map and traverse operations on fixed-point types that lack either a project or an embed (e.g., Cofree[?[_], A] lacks embed unless A has a Monoid instance, but can easily be mapped over). The tradeoff is that these operations can only transform between one fixed-point functor and another (or, in some cases, need to maintain the same functor). The names of these operations are the same as those in Recursive and Corecursive, but prefixed with trans. There is an additional (restricted) set of operations that also have a T suffix (e.g., transCataT). These only generalize in “the Elgot position” and require you to maintain the same functor. However, it can be the most natural way to write certain transformations, like matryoshka.algebras.substitute. GeneralizationGeneralization There are generalized forms of most recursion schemes. From the basic cata (and its dual, ana), we can generalize in a few ways. We name them using either a prefix or suffix, depending on how they’re generalized. G…G… Most well known (in fact, even referred to as “generalized recursion schemes”) is generalizing over a Comonad (or Monad), converting an algebra like F[A] => A to F[W[A]] => A. Many of the other named folds are instances of this – - when W[A] = (T[F], A), it’s para, - when W[A] = (B, A), it’s zygo, and - when W[A] = Cofree[F, A], it’s histo. These specializations can give rise to other generalizations. zygoT uses EnvT[B, ?[_], A] and ghisto uses Cofree[?[_], A]. …M…M Less unique to recursion schemes, there are Kleisli variants that return the result in any monad. Elgot…Elgot… This generalization, stolen from the “Elgot algebra”, is similar to standard generalization, except it uses W[F[A]] => A rather than F[W[A]] => A, with the Comonad outside the functor. Not all of the forms seem to be as useful as the G variants, but in some cases, like elgotZygo, it offers benefits of its own. GElgot…MGElgot…M Any of these generalizations can be combined, so you can have an algebra that is generalized along two or three dimensions. A fold like cofPara takes an algebra that’s generalized like zygo ( (B, ?)) in the “Elgot” dimension and like para ( (T[F], ?)) in the “G” dimension, which looks like (B, F[(T[F], A)]) => A. It’s honestly useful. I swear. ImplementationImplementation Since we can actually derive almost everything from a fairly small number of operations, why don’t we? Well, there are a few reasons, enumerated here in descending order of how valid I think they are: - Reducing constraints. In the case of para, using gcata(distPara, …)would introduce a Corecursiveconstraint, and all of the Kleisli variants require Traversefor the functor, not just Functor. - Improving performance. cataimplemented directly (presumably) performs better than gcata[Id, …]. We should have some benchmarks added eventually to actually determine when this is worth doing. - Helping inference. While we are (planning to) use kinda-curried type parameters to help with this, it’s still the case that gcatagenerally requires all the type parameters to be specified, while, say, zygodoesn’t. You can notice these instances because their definition actually is just to call the generalized version, rather than being implemented directly. ContributingContributing Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
https://index.scala-lang.org/slamdata/matryoshka/matryoshka-core/0.21.3?target=_2.12
CC-MAIN-2019-18
refinedweb
1,606
54.93
nisrm - remove NIS+ objects from the namespace nisrm [-if] name... The nisrm command removes NIS+ objects named name from the NIS+ namespace. This command will fail if the NIS+ master server is not run- ning. This command will not remove directories. See nisrmdir(1). Nor will it remove non-empty tables. See nistbladm(1). The following options are supported: -i Interactive mode. Like the system rm(1) command the nisrm command will ask for confirmation prior to removing an object. If the name specified by name is a non-fully qualified name this option is forced on. This prevents the removal of unexpected objects. -f Force. The removal is attempted, and if it fails for permission reasons, a nischmod(1) is attempted and the removal retried. If the command fails, it fails silently. The following operand is supported: name A NIS+ named object. Example 1: Using the nisrm Command Remove the objects foo, bar, and baz from the namespace: example% nisrm foo bar baz NIS_PATH If this variable is set, and the NIS+ name is not fully qualified, each directory specified will be searched until the object is found. See nisde- faults(1). The following exit values are returned: 0 Successful operation. 1 Operation failed. See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | Availability | SUNWnisu | |_____________________________|_____________________________| nis+(1), nischmod(1), nisdefaults(1), nisrmdir(1), nist- bladm(1), rm(1), attributes(5) NIS+ might not be supported in future releases of the SolarisTM Operating Environment. Tools to aid the migration from NIS+ to LDAP are available in the Solaris 9 operating environment. For more information, visit.
http://man.eitan.ac.il/cgi-bin/man.cgi?section=1&topic=nisrm
CC-MAIN-2020-10
refinedweb
275
57.67
Edit topic image Recommended image size is 715x450px or greater Hello, I started on my last internship for school yesterday. They gave me the assignment to create an inventory system, Vtiger is the program they use right now but aren't there better options to use? It should be open source, since I should be able to costumize. Thanks in advance, Tim Hofman 7 Replies Feb 12, 2013 at 11:29 UTC I'd look at some of the opensource ERP like compier, openbravo etc. They are quite complex but then so can inventory mgmt! Feb 12, 2013 at 12:27 UTC Thanks for the fast reply, i will take a look! Feb 12, 2013 at 1:41 UTC You may have already been given this information and didn't share it in your post, but I'll mention this for future readers. The organization needs to define good business needs/requirements; otherwise, this project has a high likelihood of failure. Ask what are the features in Vtiger that work for this company, and are absent? Get a list of must have features, the nice to have ones, and then features that can be substituted. There's much more to project management, but I feel that the business requirements/needs are, well, required. Feb 12, 2013 at 2:27 UTC What are the needs? Let me first explain what they are doing, This company assembling chips. There is a huge pantry, with all the components and chips. Nowadays when someone grabs 1 component he will write it on a paper. Friday afternoon someone will put it in a excel sheet and thats how they check their inventory, now they want to combine the inventory with their suppliers. The second request is that when they put in a chip type, the related components are showed. Thanks in advance. Feb 12, 2013 at 2:36 UTC def need an ERP can do planning and ordering etc as well, but these are real "interesting" to setup. Also you'll need to change ways of working to how the ERP wants you to work. not try and change the ERP to how you work! Feb 12, 2013 at 4:17 UTC Thanks again! Aug 28, 2013 at 6:45 UTC 1st Post You should also try http:/ Good Luck, -Sean
http://community.spiceworks.com/topic/302024-inventory-management-system-open-source
CC-MAIN-2016-07
refinedweb
386
80.51
Provided by: manpages_3.54-1ubuntu1_all NAME tcp - TCP protocol SYNOPSIS #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> tcp_socket = socket(AF_INET, SOCK_STREAM, 0); DESCRIPTION received only formats TCP is built on top of IP (see ip(7)). The address formats defined by ip(7) apply to TCP. TCP supports point-to-point communication only; broadcasting and multicasting are not supported. /proc interfaces. cautious);; since Linux 2.4.21/2.6); since Linux 2.4); since Linux 2.2)_CORK (since Linux 2.2). API. Ioctls>. SIOCATMARK Returns true (i.e., value is nonzero). SIOCOUTQ is defined in <linux/sockios.h>. Alternatively, you can use the synonymous TIOCOUTQ, defined in <sys/ioctl.h>. Error handling When EAFNOTSUPPORT Passed socket address type in sin_family was not AF_INET. EPIPE The other end closed the socket unexpectedly or a read is executed. COLOPHON This page is part of release 3.54 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/trusty/man7/tcp.7.html
CC-MAIN-2019-43
refinedweb
171
55.71
| The MacWhisperer Your Own Question The MacWhisperer, Professional Mac Guru Category: Mac Satisfied Customers: 250 Experience: 25+ years on the Mac, 6+ years as a Mac Guru running a computer consultant company. Type Your Mac Question Here... The MacWhisperer is online now I have deleted the contents of my inbox and need to recover Customer Question I have deleted the contents of my inbox and need to recover them. I have an external backup (maxtor) and would like to know how to find out how I can recover deleted emails from the backup? Submitted: 5 years ago. Category: Mac Customer: replied 5 years ago. Already Tried: I have contacted apple support the emails are removed from the mac & nothing saved on the server either. Just hoped they may be on the backup. Jennie Expert: The MacWhisperer replied 5 years ago. What kind of backup do you have? If you have a clone backup, the mail files are located in the user folder, within the library, within a folder called mail. Each folder is separated (INBOX, SAVED FOLDERS, etc...) go into mail and import the folder in question from the location on the backup drive that I just gave you. Ask Your Own Mac Question Customer: replied 5 years ago. I don't know what kind of backup I have other than I have an external backup which is a grey box with maxtor on the side. I followed your instructions from mail I went to: import mailboxes I then had to choose from: microsoft entourage outlook express claris emailer netscape/mozilla mail for mac OS X other I selected mail for mac OSX/jennie/messages/ - error message file cannot be found then I tried admin/macintosh HD/library/mail/account types/gave outbox only I search all the options above. I think I need to extract the deleted inbox rom the external backup box with maxtor on the side. How do I so this. I've tried lots of different things but back up or restore is not higlighted Appreciate your help Jennie Expert: The MacWhisperer replied 5 years ago. First off, what is your current username, so that we know where to grab the messages from. Is it jennie or admin? You can find out, by going into your hard drive and opening the users folder. The one with the house icon is your current username. Once we know the username, you can go into the external drive, by clicking on it's icon on your desktop, find the user folder, then inside there find the library, then the mail folder. For simplicity, drag that folder to your desktop. Then go into mail, and select import mailboxes. Select Mac OSX Mail. Locate the folder on your desktop. Inside it, you will notice files with names like "pop.yahoo.com", etc... find the one that your missing inbox was using (you can usually tell, because the middle part will be the same as your email address). Select that folder and click choose. Unclick any folders that you do not wish to import. Click import. You will then find these imported mail messages in a section on the left side of your mail program called Imported. Ask Your Own Mac Question Customer: replied 5 years ago. I'm still not having any luck following your instructions. I clicked on Jennie with house icon. clicked on the Jennie home folder (in the top part of the backup box it has "choose items for backup" which might be why I have been unable to do anything else.) I selected mail but unable to drag to desktop. Inside the mail folder is; default counts Envelope index LSMMap2 Message.Rules.plist Message .Rules.plistbackup Signatures Smartmailboxes.plist Not sure if this is any help. (I've tried your instructions several time) BW Jennie Expert: The MacWhisperer replied 5 years ago. When you say the top part of the backup box, I am unclear as to what you are talking about. Do you have an icon for the maxtor on your desktop? What operating system are you on? 10.4 or 10.5? (You can find out by clicking on the aple menu and selecting about this mac) If you are on 10.5, click on the icon of the clock with the arrow on the top right of your computer. Does it say Time Machine is not configured, or Back Up Now? If you can help me gather the info on these questions, I can guide you better. Ask Your Own Mac Question Customer: replied 5 years ago. I do not have an icon for Maxtor on the desktop but I do have an orange umbrella which says backup. The operating system is 10.4.11 I don't have the clock symbol top right Jennie Expert: The MacWhisperer replied 5 years ago. You are using apple's backup program to run your backups. Not my fave, but we can work with it. What folders is it backing up? Or is it backing up everything? You can open the umbrella to find that info. I need to know if it has everything or only particular folders so that I can guide you to the right place. We are looking for a backup of your home folder, not your home folder itself. Then we will need to use the backup program to restore it. You can't just drag it over. Once you have done that let me know and I will take you to the next step. Ask Your Own Mac Question Customer: replied 5 years ago. Thanks, XXXXX XXXXX click on the umbrella inside the box it has: Home folder next backup due 14th Nov Mac HD daily 22.00 but has never been backed up to this destination CD or DVD this plan has never been backed up untitled this plan does not include any items to back up hope this is helpful Jennie Expert: The MacWhisperer replied 5 years ago. I am concerned that what you just wrote me (coupled with the fact that your Maxtor does not appear on your desktop) may mean that your backup has not been set up properly, and is not working. Let's try this from a different angel. How did you delete your inbox? From the mail program, or from the finder? Ask Your Own Mac Question Customer: replied 5 years ago. I deleted it by selecting all then delete from the mailbox. I had been in the Trash box & had intended to delete the deleted emails that go into the Trash box. Unfortunately when I saw all the emails go I realised that it was the whole of the inbox that had been deleted. I then hit rebuild thinking it might bring them back. I don't understand why they didn't go into the Trash box from where I could have recovered them. Jennie187 Over 20 years IT experience with Apple computers in publishing, marketing and design. < | > Mike's Avatar Mike Mac Medic Satisfied Customers: 6187 Over 20 years IT experience with Apple computers in publishing, marketing and design. Ashik's Avatar Ashik Mac Helper Satisfied Customers: 5228 7+ Years of Experience in troubleshooting Macs, iPhone, iPad, iPod etc Daniel's Avatar Daniel Mac Genius Satisfied Customers: 4636 Apple certified on desktop and portable, help desk qualified. Have owned and used Macs since 1989. Vinod Menon's Avatar Vinod Menon Support Specialist Satisfied Customers: 2040 worked as a Tech support Associate for Apple products Brandon M.'s Avatar Brandon M. Mac Support Specialist Satisfied Customers: 1484 10+ Years Mac Support as contractor and currently an IT Manager for law firm John T. F.'s Avatar John T. F. Mac Druid Satisfied Customers: 1286 20+ years in the computer/Mac industry David's Avatar David Mac Support Specialist Satisfied Customers: 1233 BSc, H.Dip, Apple Certified Related Mac Questions Question Date Submitted My laptop may have gotten a little wet and won't turn on 12/5/2013 I'm trying to follow previous instructions to fix an iPhoto 12/4/2013 Can I retrieve a single file folder from Time Machine Back 12/4/2013 Hi I have constructed a table using Pages. I need to add another 12/4/2013 My mail system has disappeared, the icon is there but won't 12/4/2013 firefox will not load it tells me that I am missing profil 12/3/2013 My 2008 MacBook will not turn off, even with repeated pressing 12/3/2013 I am new to Apple. I mistakenly downloaded an iTunes album 12/3/2013 I turned on my IPAD and a red screen appeared and then it went 12/3/2013 My iPad roaming feature is not working today. I have time 12/3/2013 X Ask a Mac Support Specialist Get a Professional Answer. 100% Satisfaction Guaranteed. 75
http://www.justanswer.com/mac-computers/1ju57-deleted-contents-inbox-need-recover.html
CC-MAIN-2013-48
refinedweb
1,481
72.56
Automating Adobe Acrobat Pro with python Posted November 23, 2013 at 10:34 AM | categories: pdf, automation | tags: Table of Contents I have a need to automate Adobe Pro for a couple of applications: - I could use Adobe Pro to automatically add rubric pages to assignments before grading them. The rubric has embedded javascript that stores the grade inside the pdf file. - I could use Adobe Pro to extract information, e.g. grades, stored in a set of PDF files for analysis. I came across this script to automate Adobe Pro using python and OLE automation. Two other useful references are: - - In this post, we look at some simple code to get data out of a pdf. We start with just opening a PDF file. import os from win32com.client.dynamic import Dispatch src = os.path.abspath('writing-exams-in-orgmode.pdf') app = Dispatch("AcroExch.AVDoc") app.Open(src, src) app.Close(-1) # do not save on close Opening and closing a file is not that useful. Here, we can get some information out of the file. The pdf we looked at above has a custom property PTEX.Fullbanner from pdflatex. We can extract it like this. import os from win32com.client.dynamic import Dispatch src = os.path.abspath('writing-exams-in-orgmode.pdf') app = Dispatch("AcroExch.AVDoc") app.Open(src, src) pddoc = app.GetPDDoc() print pddoc.GetInfo('PTEX.Fullbanner') print pddoc.GetNumPages() app.Close(-1) # do not save on close This is MiKTeX-pdfTeX 2.9.4535 (1.40.13) 5 Finally, let us try inserting pages. I have a rubric file that I want to insert at the end of the writing-exams-in-orgmode.pdfabove. We will open both documents, insert the rubric, and save the result as a new file. import os from win32com.client.dynamic import Dispatch src = os.path.abspath('../../CMU/classes/06-625/rubric/rubric.pdf') src2 = os.path.abspath('writing-exams-in-orgmode.pdf') # It seems I need two of these avdoc1 = Dispatch("AcroExch.AVDoc") avdoc2 = Dispatch("AcroExch.AVDoc") # this is the rubric avdoc1.Open(src, src) pddoc1 = avdoc1.GetPDDoc() N1 = pddoc1.GetNumPages() # this is the other doc avdoc2.Open(src2, src2) pddoc2 = avdoc2.GetPDDoc() N2 = pddoc2.GetNumPages() # Insert rubric after last page of the other doc. pages start at 0 pddoc2.InsertPages(N2 - 1, pddoc1, 0, N1, 0) # save as a new file. 1 means full save at absolute path provided. pddoc2.Save(1, os.path.abspath('./woohoo.pdf')) # close files. avdoc1.Close(-1) avdoc2.Close(-1) Here is our result: woohoo.pdf . I went ahead and gave myself an A ;). 1 Summary It looks like I can replace the dependence of my box-course code on all the python-based pdf libraries (which are not fully functional, and do not work on all pdfs), and on pdftk, with this automation approach of Adobe Pro. It is unfortunate that it is not a free program, but i would expect it to work on all PDF files, and it provides features like combining PDFs with their javascript, that no other PDF package has. I have tried other PDF programs to combine the rubric and assignment page, but they all lose the javascript. With this method, I could keep a set of enriched rubric files for different types of assignments, and add them to assignments as part of the assessment process. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
https://kitchingroup.cheme.cmu.edu/blog/2013/11/23/Automating-Adobe-Acrobat-Pro-with-python/
CC-MAIN-2021-31
refinedweb
571
70.19
Testing for Functionality. $ cc -o prog main.c Note - In previous releases of the Oracle. #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; ..... if ((handle = dlopen("foo.so.1", RTLD_LAZY)) == NULL) { (void) printf("dlopen: %s\n", dlerror()); return (1); } .....: if ((handle = dlopen("./foo.so.1", RTLD_LAZY)) == NULL) { then the runtime linker searches for the file only in the current working directory of the process. Note -. $ cc -o prog main.c $ prog dlopen: ld.so.1: prog: fatal: foo.so.1: open failed: No such \ file or directory. if ((handle = dlopen(0, RTLD_LAZY)) == NULL) { Chapter 9, Direct Bindings. Note - Symbols assigned the STV_SINGLETON visibility are bound using the default symbol search, regardless of any dlopen(3C) attributes. See Table 12-20.. $ ldd prog A.so.1 => ./A.so.1 $ ldd B.so.1 C.so.1 => ./C.so.1. Figure 3-1 A Single dlopen() Request. $ ldd D.so.1 E.so.1 => ./E.so.1 and the prog application used dlopen(3C) to load this shared object in addition to the shared object B.so.1. The following figure illustrates the symbol lookup releationship between the objects. Figure 3-2 Multiple dlopen() Requests. $ ldd O.so.1 Z.so.1 => ./Z.so.1 $ ldd P.so.1 Z.so.1 => ./Z.so.1. Figure 3-3 Multiple dlopen() Requests With A Common Dependency. Note - If a member of a group defines local symbol visibility, and is referenced by another group that defines global symbol visibility, then. Note -. #include <stdio.h> #include <dlfcn.h> int main() { void *handle; int *dptr, (*fptr)(); if ((handle = dlopen("foo.so.1", RTLD_LAZY)) == NULL) { (void) printf("dlopen: %s\n", dlerror()); return (1); } if (((fptr = (int (*)())dlsym(handle, "foo")) == NULL) || ((dptr = (int *)dlsym(handle, "bar")) == NULL)) { (void) printf("dlsym: %s\n", dlerror()); return (1); } return ((*fptr)(*dptr)); }. $ ldd prog libc.so.1 => /lib/libc.so.1. $ prog dlsym: ld.so.1: main: fatal: bar: can't find symbol The special handles RTLD_DEFAULT, and RTLD_PROBE enable an application to test for the existence of a symbol. The RTLD_DEFAULT handle employes the same rules used by the runtime linker to resolve any symbol reference from the calling object. See Default Symbol Lookup Model. Two aspects of this model should be noted. A symbol reference that matches the same symbol reference from the dynamic executable is bound to the procedure linkage table entry associated with the reference from the executable. See Procedure Linkage Table (Processor-Specific). This artifact of dynamic linking ensures that all components within a process see a single address for a function. If a symbol can not be found within the objects that are presently loaded in the process, a lazy loading fall back is initiated. This fall back iterates through each loaded dynamic object, and loads any pending lazy loadable objects in an attempt to resolve the symbol. This model compensates for objects that have not fully defined their dependencies. However, this compensation can undermine the advantages of lazy loading. Unnecessary objects can be loaded, or an exhaustive loading of all lazy loadable objects can occur should the relocation symbol not be found. RTLD_PROBE follows a similar model to RTLD_DEFAULT, but differs in the two aspects noted with RTLD_DEFAULT. RTLD_PROBE only binds to explicit symbol definitions, and is not bound to any procedure linkage table entry within the executable. In addition, RTLD_PROBE does not initiate an exhaustive lazy loading fall back. RTLD_PROBE is the most appropriate flag to use to detect the presence of a symbol within an existing process. RTLD_DEFAULT and RTLD_PROBE can both initiate an explicit lazy load. An object can make reference to a function, and that reference can be established through a lazy loadable dependency. Prior to calling this function, RTLD_DEFAULT or RTLD_PROBE can be used to test for the existence of the function. Because the object makes reference to the function, an attempt is first made to load the associated lazy dependency. The rules for RTLD_DEFAULT and RTLD_PROBE are then followed to bind to the function. In the following example, an RTLD_PROBE call is used both to trigger a lazy load, and to bind to the loaded dependency if the dependency exists. void foo() { if (dlsym(RTLD_PROBE, "foo1")) { foo1(arg1); foo2(arg2); .... } To provide a robust and flexible model for testing for functionally, the associated lazy dependencies should be explicitly tagged as deferred. See Providing an Alternative to dlopen(). This tagging also provides a means of changing the deferred dependency at runtime. The use of RTLD_DEFAULT or RTLD_PROBE provide a more robust alternative to the use of undefined weak references, as discussed in Weak Symbols. The. $ cc -o malloc.so.1 -G -K pic malloc.c $ cc -o prog file1.o file2.o ..... -R. malloc.so.1 $ prog malloc: 0x32 bytes malloc: 0x14 bytes .......... Alternatively, the same interposition can be achieved using the following commands. $ cc -o malloc.so.1 -G -K pic malloc.c $ cc -o prog main.c $ LD_PRELOAD=./malloc.so.1 prog malloc: 0x32 bytes malloc: 0x14 bytes .......... Note -.
http://docs.oracle.com/cd/E23824_01/html/819-0690/chapter3-10.html
CC-MAIN-2015-06
refinedweb
837
60.01
HTML::FormHandler::Blocks - arrange form layout using blocks version 0.40019 This is a role which provides the ability to render your form in arbitrary 'blocks', instead of by fields. This role is included by default in HTML::FormHandler. package MyApp::Form; use HTML::FormHandler::Moose; extends 'HTML::FormHandler'; sub build_render_list {[ 'foo', 'fset' ]} has_field 'foo'; has_field 'bar'; has_field 'nox'; has_block 'fset' => ( tag => 'fieldset', render_list => ['bar', 'nox'] );; .... $form->render; Blocks live in the HTML::FormHandler::Widget::Block:: namespace. The default, non-typed block is HTML::FormHandler::Widget::Block. Provide a type for custom blocks: has_block 'my_block' => ( type => 'CustomBlock', render_list => [...] ); You can also build blocks with a 'block_list' attribute, or the builder for it, 'build_block_list'. Rendering with blocks is supported by the rendering widgets. Render::Simple doesn't do it, though it would be possible to make your own custom renderer. FormHandler Contributors - see HTML::FormHandler This software is copyright (c) 2013 by Gerda Shank. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
http://search.cpan.org/~gshank/HTML-FormHandler-0.40019/lib/HTML/FormHandler/Blocks.pm
CC-MAIN-2016-30
refinedweb
177
58.18
Difference between revisions of "MacBookPro10,x" Latest revision as of 01:45, 25 November 2017. Contents - 1 Preparing for the Installation - 2 Installation - 3 Post installation - 3.1 Wi-Fi - 3.2 Graphics - 3.3 Sound and microphone - 3.4 Touchpad - 3.5 Memory Card (SDHCI/SDX) Reader - 4 What does not work (early August 2013, 3.10.3-1) - 5 Discussions - 6 See also As of late 2014, thunderbolt hotplugging has been included in the mainline Linux kernel. Ethernet cables can now be used as usual through the thunderbolt adapter. [1] Using a USB-to-Ethernet adapter No special configuration is necessary to get this to work. Getting wireless firmware In order for the Wi-Fi chipset to work, you need to get the firmware for it. You can just copy it from another b43-enabled Arch, extract it from Broadcom's driver using b43-fwcutter, or get the firmware through the b43-firmwareAUR package available in the AUR. In the end, you should have a folder named b43 with a lot of .fw files in it. USB Tethering If you have a smartphone, you can also try tethering your device to get connected to the internet. This should work out of the box. Installation Booting the live image Download the latest ISO from the download page and prepare a live USB as outlined in USB flash installation media. Shut down the Macbook. Plug in the USB drive. Hold the option key, then press the power button. After a few seconds, you should see Apple's boot loader display the choice of either starting up the built-in drive with OS X or the USB drive you plugged in. Select the live USB with the arrow keys, and press Enter to boot into the live Arch Linux environment. Connecting Wi-Fi After it has finished booting, enter a command line. Copy the entire folder with the firmware for your wireless card to /usr/lib/firmware/. Now you should be able to use wifi-menu to connect to your Wi-Fi. Do not worry about any errors; we will create the bootable EFI image on our own afterwards. After the installation has completed, directly copy the Wi-Fi firmware to the installed system to /tmp/install/usr/lib/firmware/. Alternatively, install broadcom-wl-dkms from the AUR to improve Wi-Fi. Bootloader Direct EFI booting.) have not used --setBoot while blessing. Post installation Wi-Fi The Macbook Pro 10,x comes with the Broadcom BCM4331 Wireless Chipset. There are two major options to get this chipset working in Arch Linux: The b43-firmwareAUR package contains the open-source, reverse-engineered firmware for the chipset. The broadcom-wlAUR and broadcom-wl-dkms packages ship with the propriety, restricted-license drivers for the chipset. See Broadcom wireless for more information. Graphics General Notes The Laptop comes with an nVidia and an Intel chip. The Nouveau xf86-video-nouveau, the intel xf86-video-intel (from 3.6-rc5) and proprietary nvidia (from 302.17) drivers work. You can install the nvidia driver through nvidia or the AUR package nvidia-beta-allAUR. Since this device comes with a Retina (HiDPI) display, things may be really small with native resolution for some desktop environments. There are different ways to work around this "issue": - Increase the DPI value to get larger fonts (other things like icons may not look great that way) - KDM is a great choice because the stock UI elements are vectors (not rasters which look terrible on Retina and do: - See HiDPI for more tweaks. Nouveau backlight If you are using the open-source Nouveau drivers and the active GPU is the Nvidia card, backlight levels can be adjusted by echoing a value to a file (as root): echo 500 > /sys/class/backlight/gmux_backlight/brightness To bring the backlight to its maximum level: echo $(cat /sys/class/backlight/gmux_backlight/max_brightness) > /sys/class/backlight/gmux_backlight/brightness NVIDIA backlight If you are using the propriety nvidia drivers, note that the backlight adjustment will not work out of the box. To enable backlight control (run as root): setpci -v -H1 -s 00:01.00 BRIDGE_CONTROL=0 Switching to/from GPUs with gpu-switch You can switch the display output to and from the discrete or integrated intel GPU from within Arch Linux with gpu-switchAUR if you are using the open-source xf86-video-nouveau and xf86-video-intel drivers. Installation You can install gpu-switchAUR from the AUR. Then, just run the script as root. Usage The command switches are -i, to switch to the integrated card, and -d for switching to the discrete GPU. In order to have the changes take effect, you will need to reboot. Switch to Intel integrated GPU and turn off discrete Nvidia GPU To switch to intel card and poweroff the discrete GPU: cd /path/to/gpu-switch ./gpu-switch -i Then reboot. Poweroff the discrete GPU using vgaswitcheroo as root: echo OFF > /sys/kernel/debug/vgaswitcheroo/switch This will take a second or to complete. Then, check whether the discrete GPU is still on: cat /sys/kernel/debug/vgaswitcheroo/switch The output should look like this: 0:IGD:+:Pwr:0000:00:02.0 1:DIS: :Off:0000:01:00.0 2:DIS-Audio: :Off:0000:01:00.1 This is useful if you have opted to have an Arch Linux-only installation and cannot access the OS X-only tool iGPU. Keeping the discrete GPU off at boot If you want to keep the discrete GPU off at boot, see systemd-vgaswitcheroo-unitsAUR. Graphic artifacting under b43-firmware While on integrated graphics with the b43-firmware package, you might encounter moderate to severe graphic artifacting that appears to be correlated to wireless network traffic. (disconnected->no artifacting, connected->periodic artifacting, large transfer->severe artifacting/unusuable) This can be resolved by removing/blacklisting b43-firmwareAUR and using either broadcom-wlAUR or broadcom-wl-dkms. Sound and microphone On the MacBookPro10,2 you may need to use the 'snd_hda_intel' driver with the model option 'mbp101'. This model option goes in the modprobe configuration; for example, add the following to /etc/modprobe.d/alsa-base.conf (forum post): options snd-hda-intel model=mbp101 Note this model option is undocumented in the list of models available online, but it works admirably. (Until you do this, the sound may seem fine through HDMI, but the built-in speakers and internal microphone may not work properly.) For additional microphone troubleshooting tips, see Advanced Linux Sound Architecture/Troubleshooting#Microphone. Touchpad While xf86-input-synaptics will work, the integrated button of the touchpad may cause issues. Using the xf86-input-mtrack-gitAUR driver, with a tweaked configuration" "3" Option "TapButton3" "2" Option "ClickFinger1" "1" Option "ClickFinger2" "3" Option "ClickFinger3" "2" Option "BottomEdge" "25" EndSection To use natural scrolling, also add the following inside this section: Option "ScrollDownButton" "4" Option "ScrollUpButton" "5" Option "ScrollLeftButton" "7" Option "ScrollRightButton" "6" For more configurations, check the document of xf86-input-mtrack-gitAUR. To disable the trackpad when typing, install the dispad-gitAUR[broken link: archived in aur-mirror] utility. Memory Card (SDHCI/SDX) Reader There is currently a bug in the kernel (4.7.x) where the internal SD card reader times out. As a workaround you will need to reload the sdhci kernel modules, as per: sudo rmmod sdhci-pci sdhci sudo modprobe sdhci debug_quirks2=4 sudo modprobe sdhci-pci What does not work (early August 2013, 3.10.3-1) (shutdown and press shift+control+alt+power at the same time. Press power again to boot.) - Another way to force iGPU/intel is to add following commands into one of the menuentryin grub.cfg, dGPU (will not work) #outb 0x7c2 1 #outb 0x7d4 0x50 #outb 0x7c2 0 #outb 0x7d4 0x50 The screen will remain blank until intel driver is fully loaded. Notice that dGPU will not be powered down (adding code above will prevent the system from booting up). Workaround is to compile and run following program (need sudo) after system is fully booted up. #include <stdio.h> #include <sys/io.h> #define GMUX_PORT_SWITCH_DISPLAY 0x10 #define GMUX_PORT_SWITCH_DDC 0x28 #define GMUX_PORT_SWITCH_EXTERNAL 0x40 #define GMUX_PORT_DISCRETE_POWER 0x50 #define GMUX_PORT_VALUE 0xc2 #define GMUX_PORT_READ 0xd0 #define GMUX_PORT_WRITE 0xd4 #define GMUX_IOSTART 0x700 typedef unsigned char u8; enum discrete_state {STATE_ON, STATE_OFF}; enum gpu_id {IGD, DIS}; static void index_write8(int port, u8 val) { outb(val, GMUX_IOSTART + GMUX_PORT_VALUE); outb((port & 0xff), GMUX_IOSTART + GMUX_PORT_WRITE); } static u8 index_read8(int port) { u8 val; outb((port & 0xff), GMUX_IOSTART + GMUX_PORT_READ); val = inb(GMUX_IOSTART + GMUX_PORT_VALUE); return val; } static void set_discrete_state(enum discrete_state state) { if (state == STATE_ON) { // switch on dGPU index_write8(GMUX_PORT_DISCRETE_POWER, 1); index_write8(GMUX_PORT_DISCRETE_POWER, 3); } else { // switch off dGPU index_write8(GMUX_PORT_DISCRETE_POWER, 1); index_write8(GMUX_PORT_DISCRETE_POWER, 0); } } static u8 get_discrete_state() { return index_read8(GMUX_PORT_DISCRETE_POWER); } static void switchto(enum gpu_id id) { if (id == IGD) { // switch to iGPU index_write8(GMUX_PORT_SWITCH_DDC, 1); index_write8(GMUX_PORT_SWITCH_DISPLAY, 2); index_write8(GMUX_PORT_SWITCH_EXTERNAL, 2); } else { // switch to dGPU index_write8(GMUX_PORT_SWITCH_DDC, 2); index_write8(GMUX_PORT_SWITCH_DISPLAY, 3); index_write8(GMUX_PORT_SWITCH_EXTERNAL, 3); } } int main(int argc, char **argv) { if (iopl(3) < 0) { perror("No IO permissions"); return 1; } //switchto(IGD); set_discrete_state(STATE_OFF); //printf("Discrete state: 0x%X\n", get_discrete_state()); return 0; } For further information, please read apple-gmux driver inside linux kernel tree. - . Discussions Here are a couple of interesting threads: - -
https://wiki.archlinux.org/index.php?title=MacBookPro10,x&diff=cur&oldid=263924
CC-MAIN-2017-51
refinedweb
1,532
54.02
I am receiving the following error when I am trying to activate objects copied from an existing namespace to new namespace. What could be the reason ? Activation of the change list canceled Check result for Message Mapping MM_BBP_ESI_ERP_CONTRACT |: Namespace is not defined in the software component version FCI, 1.0 of frictionless.com Namespace is not defined in the software component version FCI, 1.0 of frictionless.com Hi, Firstly, activate the namespace. Secondly, copy the object. Regards, Jakub You already have an active moderator alert for this content. Thanks for the prompt reply. Is there any concept of activating namespace ? I never see activate menu when I right click on namespace. How about activation namespace objects in tab "Change List"? 😉 Namespace cannot be activated in the changelist. I had objects in different standard changelist thats how I wasn't selecting few of the object for activation. Thanks for all the help. Nivedita Add comment
https://answers.sap.com/questions/3387465/index.html
CC-MAIN-2019-18
refinedweb
155
62.54
Part of React 18’s experimental Concurrent Mode is a new feature called startTransition, which prevents an expensive UI render from being executed immediately. To understand why we need this feature, remember that forcing expensive UI renders to be done immediately can block lighter and more urgent UI renders from rendering in time. This can frustrate users who need immediate response from the urgent UI renders. An example of an urgent UI render would be typing in a search bar. When you type, you want to see your typing manifested and begin searching immediately. If the app freezes and the searching stops, you get frustrated. Other expensive UI renders can bog down the whole app, including your light UI renders that are supposed to be fast (like seeing search results as you type). When developing your React app, you can avoid this problem by debouncing or throttling. Unfortunately, using debouncing or throttling can still cause an app to become unresponsive. startTransition allows you to mark certain updates in the app as non-urgent, so they are paused while the more urgent updates are prioritized. This makes your app feel faster, and can reduce the burden of rendering items in your app that are not strictly necessary. Therefore, no matter what you are rendering, your app is still responding to your user’s input. In this article, we’ll learn how to use startTransition in your React app in order to delay the non-urgent UI updates to avoid blocking urgent UI updates. With this feature, you can convert your slow React app into a responsive one in no time. Before we begin, note that React 18 is still in alpha at the time of writing, so startTransitionis not yet part of a stable release. Getting started with React 18 Before beginning the tutorial, ensure you have the following: - Working knowledge of React - Node.js installed on your machine Let’s begin by creating a React project with create-react-app: $ npx create-react-app starttransition_demo The command above created a React project using the latest stable version of React, which is version 17. We need to use React 18. Go inside the project directory and remove the node_modules directory: $ cd starttransition_demo/ $ rm -rf node_modules On Windows, you have to use a different command to remove the directory. After removing the directory, edit package.json. Find these lines: "react": "^17.0.2", "react-dom": "^17.0.2", Then, change the version of React from 17 to alpha: "react": "alpha", "react-dom": "alpha", Finally, install the libraries with yarn: $ yarn install To make sure that you have React 18 installed, you can check it from the node_modules directory like so: $ grep version node_modules/react/package.json "version": "18.0.0-alpha-6ecad79cc-20211006", On Windows, you can open the file directly. Run the server to make sure you can run the React 18 app: yarn start Open in your browser. You should see the familiar default page of a React project with a rotating React logo. Enabling Concurrent Mode By default, our React project doesn’t support Concurrent Mode. We need to enable it by rendering the root React node in a different way. Open src/index.js. You can see that we render the root node with the render static method from ReactDOM: ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); To enable Concurrent Mode, we need to create the root node first then use the render method from that instance. Change the lines above to the lines below: const container = document.getElementById('root') const root = ReactDOM.createRoot(container); root.render( <React.StrictMode> <App /> </React.StrictMode> ); Notice the createRoot method from ReactDOM. This will create a root node. Setting up a testing environment First, let’s create a React app with a light UI render and an expensive UI render. Open src/App.js. You can see the App function definition displaying a React logo, a p tag, and a link. Replace the App function with the code below: function App() { const [search_text, setSearchText] = useState(""); const [search_result, setSearchResult] = useState(); const handleChange = e => { setSearchText(e.target.value); }; useEffect(() => { if (search_text==="") { setSearchResult(null); } else { const rows = Array.from(Array(5000), (_, index) => { return ( <div key={index}> <img src={logo} <div>{index + 1}. {search_text}</div> </div> ); }); const list = <div>{rows}</div>; setSearchResult(list); } }, [search_text]); return ( <div className="App"> <header className="App-header"> <div className="SearchEngine"> <div className="SearchInput"> <input type="text" value={search_text} onChange={handleChange} /> </div> <div className="SearchResult"> {search_result} </div> </div> </header> </div> ); } You need to import useEffect and useState. Put this line on top of the file: import {useState, useEffect } from 'react'; Here, we are creating the app’s UI that consists of two parts: the search input and the search result. Because the input has a callback, when you type the text on the input, the text is passed as an argument to setSearchText to update the value of search_text using the useState hook. Then, the search result shows up. For this demo, the result is 5,000 rows where each row consists of a rotating React logo and the same search query text. Our light and immediate UI render is the search input with its text. When you type text on the search input, the text should appear immediately. However, displaying 5,000 React logos and the search text is an expensive UI render. Let’s look at an example; try typing “I love React very much” quickly in our new React app. When you type “I”, the app renders the text “I” immediately on the search input. Then it renders the 5,000 rows. This takes a long time, which reveals our rendering problem. The React app cannot render the full text immediately. The expensive UI render makes the light UI render become slow as well. You can try it yourself on the app at You’ll be presented with a search input. I have set up a demo app as well. What we want is for the expensive UI render not to drag the light UI render to the mud while it loads. They should be separated, which is where startTransition comes in. Using startTransition Let’s see what happens when we import startTransition. Your top line import should be like this: import {useState, useEffect, startTransition} from 'react'; Then, wrap the expensive UI render in this function. Change setSearchResult(list) into the code below: startTransition(() => { setSearchResult(list); }); Now, you can test the app again. When you type something in the search input, the text is rendered immediately. After you stop (or a couple of seconds pass), the React app renders the search result. What if you want to display something on the search results while waiting for the expensive UI render to finish? You may want to display a progress bar to give immediate feedback to users so they know the app is working on their request. For this, we can use the isPending variable that comes from the useTransition hook. First, change the import line on the top of the file into the code below: import {useState, useEffect, useTransition} from 'react'; Extract isPending and startTransition from the useTransition hook. Put the code below on the first line inside the App function: const [isPending, startTransition] = useTransition(); Next, change the content of <div className="SearchResult"> to the code below: {isPending && <div><br /><span>Loading...</span></div>} {!isPending && search_result} Now when you type the text on the search input very fast, the loading indicator is displayed first. Conclusion With startTransition, you can make the React app smooth and reactive by separating the immediate UI renders and the non-urgent UI renders. By putting all non-urgent UI renders inside the startTransition method, your app will be much more satisfying to use. We also covered using the isPending variable to indicate the status of the transition in case you want to give feedback to users. You can get the full code of the startTransition demo app here. You can also experiment with the demo of the app to your heart’s content. Hopefully this knowledge will be useful for you when you build your next React app. Make sure the apps will be smooth! “Getting started with startTransition in React 18” Awesome explanation! I appreciate this
https://blog.logrocket.com/getting-started-react-18-starttransition/
CC-MAIN-2022-21
refinedweb
1,377
55.03
Forum:Article Wars: A New Hype From Uncyclopedia, the content-free encyclopedia Note: This topic has been unedited for 2762 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response. So every once in a while I challenge THE to an article writing contest. The details aren't important. All you have to know is that we had to parody a chosen article from the other person. I parodied HowTo:Turn Your Computer On and he parodied Red Light. Any suggestions? Insults? Challenges? Comments? I'm up for whatever. • <Apr 30, 2008 [3:40]> - I say you start a league and then don't let anybody in. That'll show 'em. Unsolicited conversation Extravagant beauty PEEING 03:51, 30 April 2008 (UTC) - Hey, there's no "winner" or anything... it's just for fun... • <Apr 30, 2008 [3:59]> - How do you expect to get anybody to join your league if they don't even get to plow some other user's poor dignity into the ground? Also, your league is now called "Cajek's Club of Happy Fun Time". That'll show 'em. Unsolicited conversation Extravagant beauty PEEING 20:10, 30 April 2008 (UTC) - That's loser talk, Cajek! GET OUT THERE AND BE A WINNER! Man I miss my childhood... - P.M., WotM, & GUN, Sir Led Balloon (Tick Tock) (Contribs) 21:44, Apr 30 - On a semi-related note, perhaps a new category, template, or even namespace is possible for articles like these. I seem to recall one that Kip the Dip did for You Are Dead, called You Are Gay. That one made me laugh quite a bit. - P.M., WotM, & GUN, Sir Led Balloon (Tick Tock) (Contribs) 00:37, May 1 - The best part is that these are parodies of satire. That makes them, like, super-parodies. Unsolicited conversation Extravagant beauty PEEING 00:53, 1 May 2008 (UTC) - Like Army of Darkness?--<< >> 12:25, 2 May 2008 (UTC)
http://uncyclopedia.wikia.com/wiki/Forum:Article_Wars:_A_New_Hype?t=20080502122609
CC-MAIN-2015-48
refinedweb
331
76.01
Migration Guidance In the .NET Framework 4, Microsoft is releasing the second major version of Windows Workflow Foundation (WF). WF was released in WinFX (this included the types in the System.Workflow.* namespaces; now referred to as WF3) and enhanced in .NET Framework 3.5. WF3 is also part of the .NET Framework 4, but it exists there alongside new workflow technology (the types in the System.Activities.* namespaces; referred to as WF4). When considering when to adopt WF4, it is important to first recognize that you control the timing. WF3 is a fully supported part of the .NET Framework 4. WF3 applications run on the .NET Framework 4 without modification and continue to be fully supported. New WF3 applications can be created and your existing applications can be edited in Visual Studio 2012 and are fully supported. Thus, the decision to adopt the .NET Framework 4 is decoupled from your decision to move to WF4 (System.Activities.*) from WF3 (System.Workflow.*). This topic provides links to WF migration guidance that provides information about working with WF3 and WF4. WF Migration Whitepapers and Cookbooks The WF Migration Overview topic provides a broad overview of the relationship between WF3 and WF4 and migration strategies. Companion topics drill into specific topics. WF Migration Overview Describes the relationship between WF3 and WF4, and the choices you have as a user or a potential user of workflow technology in .NET 4. WF Migration: Best Practices for WF3 Development Discusses how to design WF3 artifacts so they can be more easily migrated to WF4. WF Guidance: Rules Discusses how to bring rules-related investments forward into .NET Framework 4 solutions. WF Guidance: State Machine Discusses WF4 control flow modeling in the absence of a State-Machine activity. Note that this guidance only applies to workflow projects that target .NET Framework 4. State Machine workflows were added in .NET 4.0.1 with the release of Platform Update 1, and were included as part of .NET Framework 4.5. For more information about state machine workflows in .NET 4.0.1 - 4.0.3 and .NET Framework 4.5, see Update 4.0.1 for Microsoft .NET Framework 4 Features and State Machine Workflows. WF Migration Cookbook: Custom Activities Provides examples and instructions for redesigning WF3 custom activities on WF4. WF Migration Cookbook: Advanced Custom Activities Provides guidance for redesigning advanced WF3 custom activities that use WF3 queues and schedule child activities as WF4 custom activities. WF Migration Cookbook: Workflows Provides examples and instructions for redesigning WF3 workflows on WF4. WF Migration Cookbook: Workflow Hosting Provides guidance for redesigning WF3 hosting code as WF4 hosting code. The goal is to cover the key differences in workflow hosting between WF3 and WF4. WF Migration Cookbook: Workflow Tracking Provides guidance for redesigning WF3 tracking code and configuration using equivalent WF4 tracking code and configuration. WF Guidance: Workflow Services Provides example-oriented step-by-step instructions for redesigning workflows that implement Windows Communication Foundation (WCF) web services (commonly referred to as workflow services) created in WF3 to use WF4, for common scenarios for out-of-box activities. See also Feedback Send feedback about:
https://docs.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/migration-guidance
CC-MAIN-2019-18
refinedweb
524
51.14
Class SyncVarAttribute : - Basic type (byte, int, float, string, UInt64, etc) - Built-in Unity math type (Vector3, Quaternion, etc), - Structs containing allowable types. Namespace: UnityEngine.Networking Syntax [AttributeUsage(AttributeTargets.Field)] [Obsolete("The high level API classes are deprecated and will be removed in the future.")] public class SyncVarAttribute : Attribute, _Attribute Fields hook The hook attribute can be used to specify a function to be called when the sync var changes value on the client. This ensures that all clients receive the proper variables from other clients. //Attach this to the GameObject you would like to spawn (the player). //Make sure to create a NetworkManager with an HUD component in your Scene. To do this, create a GameObject, click on it, and click on the Add Component button in the Inspector window. From there, Go to Network>NetworkManager and Network>NetworkManagerHUD respectively. //Assign the GameObject you would like to spawn in the NetworkManager. //Start the server and client for this to work. //Use this script to send and update variables between Networked GameObjects using UnityEngine; using UnityEngine.Networking; public class Health : NetworkBehaviour { public const int m_MaxHealth = 100; //Detects when a health change happens and calls the appropriate function [SyncVar(hook = "OnChangeHealth")] public int m_CurrentHealth = m_MaxHealth; public RectTransform healthBar; public void TakeDamage(int amount) { if (!isServer) return; //Decrease the "health" of the GameObject m_CurrentHealth -= amount; //Make sure the health doesn't go below 0 if (m_CurrentHealth <= 0) { m_CurrentHealth = 0; } } void Update() { //If the space key is pressed, decrease the GameObject's own "health" if (Input.GetKey(KeyCode.Space)) { if (isLocalPlayer) CmdTakeHealth(); } } void OnChangeHealth(int health) { healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y); } //This is a Network command, so the damage is done to the relevant GameObject [Command] void CmdTakeHealth() { //Apply damage to the GameObject TakeDamage(2); } } Declaration public string hook
https://docs.unity3d.com/Packages/com.unity.multiplayer-hlapi@1.0/api/UnityEngine.Networking.SyncVarAttribute.html
CC-MAIN-2020-45
refinedweb
298
54.93
I am trying to export a .swc from Flash pro to use in my project. Because I'm using some components (button, TextInput) there is a folder that appears in my library with the component assets. By default, these all seem to be given an AS linkage value the same as their name. This causes a headache, because that puts them in the default namespace? and it's screwing with my autocomplete. Considering I don't anticipate ever needing to access any of these component assets from my actionscript project, I thought the best solution would be to simply remove the AS linkage property of each of the component skins. However, this causes a runtime error when trying to use the .swc in my actionscript project [Fault] exception, information=TypeError: Error #2007: Parameter child must be non-null. I know I could put them all into an obscure namespace, but that seems rather tedious Thanks for reading Retrieving data ...
https://forums.adobe.com/message/4718364?tstart=0
CC-MAIN-2016-36
refinedweb
159
64.3
EdgeCase - Home tag:blog.edgecase.com,2009:mephisto/ Mephisto Noh-Varr 2009-06-25T02:45:09Z Adam tag:blog.edgecase.com,2009-06-25:780 2009-06-25T00:40:00Z 2009-06-25T02:45:09Z Make Ajax File Uploads Sexy (screencast) <p><a href="">Last week</a> I showed you how to perform file uploads via Ajax, but the result was too ugly for my taste. Today we're going to make it sexy. Check it out.</p> <p><embed src="" height="430" width="535"></embed></p> <p>The source code for the example app is <a href="">here</a>.</p> <p>Next week I plan to dive into using Flash to enable selecting and uploading mutiple files with progress indication. Stay tuned.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-06-15:779 2009-06-15T14:18:00Z 2009-06-25T00:45:57Z Ajax File Uploads Made Easy (screencast) <p>Here is my second screencast for the EC blog, this time talking about Ajax file uploads in Rails using jQuery. Let me know what you think in the comments.</p> <p><embed src="" height="430" width="535"></embed></p> <p>A Non-Flash version is available <a href="">here</a>. The plugin discussed is on <a href="">Github</a>.</p> <p><strong>update:</strong> I decided to turn this into a series of screencasts on how to handle file uploads on the client side. <a href="">Part two</a> is now available, which builds on this example.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-06-02:777 2009-06-02T13:51:00Z 2009-06-02T14:17:31Z A Rant About Testing <p>Time to stir up some controversy. It’s been a while since I’ve posted, so why not come back with a bang. Disclaimer, though: these are only the opinions of me, <a href="">Adam McCrea</a>, and not of EdgeCase.</p> <h2><span class="caps">TATFT</span></h2> <p>There’s a meme going around for a while that’s gained a lot of popularity, and I for one would like to say that I do not, nor do I have any desire to <a href="">Test All The Time</a>. Being religious about testing is a recipe for brittle tests, wasted effort, and a false sense of security. I’d rather shift from religion to pragmatism. This means thinking hard about what and when we test.</p> <p>In a few recent projects, I’ve begun heavy integration testing. No, I’m not breaking any new ground, but the fact is prior to these recent projects, I had no integration tests. I was a bad, bad little programmer. That aside, I have to say that it’s been incredibly eye-opening.</p> <p>I like to test as far up the stack as I can, getting as close as possible to the end user. Right now that means using <a href="">Webrat</a> to mimic actual clicks and form interaction to navigate the app. Sticking to this approach, I can change the internals of the app however I want as long as the generated <span class="caps">HTML</span> for links and form fields remains untouched. If you had told me a few months back that I could substantially refactor my code and <strong>not change one test</strong>, I would have thought you were crazy. But integration tests make that possible.</p> <h2>Less testing</h2> <p>But how does that reduce waste? For starters, I no longer write controller (or view) tests. And neither should you. Seriously, just stop. You’re not only wasting your time, but also every future developer who touches that code and has to maintain your useless tests. This assumes two things: that you’re thoroughly integration testing your app, and that your controllers are as skinny as possible. If you still think you need controller tests, you’ve probably got crap in your controllers that shouldn’t be there. Get it out, and stop writing those tests.</p> <p>I’ll proudly admit that I’m also testing my models a lot less. Seriously, what’s the point of testing things like attribute readers/writers and associations if I’ve got a full suite of integration tests? If my comments don’t belong to posts, I’ll get yelled at, and it’s not going to take long to pinpoint the problem. So, I’m really only unit testing substantial model and helper methods. Everything else gets hit at the integration level only.</p> <h2>What about coverage?</h2> <p>I still think coverage is important, but only at the integration level. Whether or not a piece of code is unit tested is purely subjective, but every line of code must be tested from the point of view that matters most – the user’s. 100% integration test coverage is no guarantee that you’ll catch every possible bug, of course, but anything less would indicate that you wrote some code without thinking about how it will be used.</p> <h2>So is Cucumber the answer?</h2> <p>Honestly, it just doesn’t matter. Just test your code from as far up the stack as possible using whatever tool you prefer. Cucumber, Rails integration tests, Selenium, well-trained monkeys, whatever. Go for it. I do like <a href="">Cucumber</a>, though, so it’s certainly worth a try if you’re new to full-stack testing.</p> <p>Ideally, JavaScript would be included in these tests, I just haven’t found a solution yet that makes it practical. It would require a masochist to get 100% coverage with Selenium, but <a href="">Culerity</a> is one promising option that has popped up. I haven’t had a chance to check it out, though.</p> <p>This approach certainly isn’t for everyone, but the current wave of <span class="caps">TATFT</span> is in desperate need of a counterpoint. If you like to use unit tests as a way to design your code, you probably think I’m way off base. That’s fine. We don’t all have to play by the same rules. Hell, even I still <span class="caps">TDD</span>, just not at the unit level. The point here is to make sure you’re very conscious of what, when, and why you test, and that you’re getting enough value from them to justify the time spent.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-05-11:746 2009-05-11T12:37:00Z 2009-05-11T12:38:51Z Bookmarklets 101 <p>Last week I showed you a bookmarklet that lets you edit your CSS live in any browser. Today, I want to dive into the details of how to create a bookmarklet. But first, the basics:</p> <h2>What is a bookmarklet?</h2> <p>A bookmarklet is a small snippet of JavaScript crammed into a URL. Nothing else. That's not very helpful, though, is it? All it means is this: instead of using the http: or ftp: protocol for a URL, we use the javascript: protocol. And when this URL is invoked (perhaps by clicking a bookmark in your browser's bookmark toolbar) the remainder of the URL is executed as JavaScript. What this means is that we can execute any arbitrary JavaScript within the context of any site we please. And we can package it so that it can be shared and reused easily. But...</p> <h2>What is the point?</h2> <p>In general a bookmarklet will either alter the current page in some way, or make use of the context of the current page in concert with some other service. Some examples of the former are <a href="">edit CSS</a>, <a href="">jQuerify</a>, <a href="">Firebug Lite</a>, and <a href="">960gs grid overlay</a>. These are usually only useful to developers. Some examples of the latter are <a href="">URL shorteners</a>, <a href="">post to delicious</a>, <a href="">Amazon wishlist</a>, and <a href="">Instapaper</a>. These are much more useful to consumers. Both kinds of bookmarks use the same technology, though, so the approach to developing them is basically the same.</p> <h2>The "Hello World" bookmarklet</h2> <p>Create a bookmark, and give it the following URL:</p> <pre><code>javascript:alert('hello%20world'); </code></pre> <p>Now click the bookmark. Yep, that's all there is to it. Notice that we replaced the space with %20. That's important, and there are a few more rules that we need to keep in mind when creating bookmarklets.</p> <h2>Gotchas & Tips</h2> <h3>URL length limit</h3> <p>I'm not sure what the definitive answer is on this. IE is (unsurprisingly) the limiting factor here, but I've heard <a href="">conflicting</a> <a href="">information</a> on what the actual limit is. I haven't bothered to test it since that would mean firing up Windows and opening IE, which I avoid at all costs. So, just keep it really really short, m'kay?</p> <h3>Cheat the URL limit</h3> <p>Most bookmarklets try to do way more than is possible within the URL limit I just described, so of course there is a way to cheat the rule. Just host an external JS file that gets dynamically required by your bookmarklet. <a href="">Here</a> is an example. The bookmarklet just appends a SCRIPT tag into the HEAD of the document, which requests and executes the external JS file.</p> <h3>Don't return a value</h3> <p>If your bookmarklet code returns a value, that value will find it's way to the browser's address bar. This is most likely not what you want, so you have two weapons to use against this. You can append a void() call at the end of your JS code:</p> <pre><code>someCode();void(0); </code></pre> <p>Or you can wrap your JS in an anonymous function. The added benefit here is that any variables you define are not polluting the global scope:</p> <pre><code>function(){someCode()}(); </code></pre> <h3>Don't depend on a JS library</h3> <p>Probably an obvious one, but you can't assume that jQuery, Prototype, or any other library is included in the page where your bookmarklet will eventually be run. I got around this in my Edit CSS bookmarklet by dynamically including jQuery and running it in noConflict mode. See the code for that <a href="">here</a>. </p> <h2>Next steps</h2> <p>If you want to write a bookmarklet that integrates with a Rails application, definitely check out John Nunemaker's <a href="">screencast</a>. Also dig into the bookmarklets that I linked to earlier in the article. If you have a favorite bookmarklet or want to know more about bookmarklets, please join the discussion below.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-05-04:722 2009-05-04T12:22:00Z 2009-05-04T12:22:54Z Edit CSS in Any Browser With the Click of a Button <p>So, a few weeks back I showed you how you could <a href="">see your <span class="caps">CSS</span> changes in real-time in any browser</a>. That was cool and all, but I haven’t found myself using it simply because of the convenience factor. The script (along with jQuery) had to be included in the page, whereas I could just fire up Web Developer Toolbar in an instant.</p> <p>Today I’m introducing the bookmarklet version of that same script. It no longer requires jQuery, so just drag the link below up to your bookmark toolbar, and you’ll have this functionality one click away.</p> <p><a>Edit <span class="caps">CSS</span></a></p> <p>I’ve also put together a short (3-minute) demo below. Enjoy.</p> <embed src="" height="452" width="575"></embed> <p>Non-Flash version of screencast is available <a href="">here</a> (the Files and Links section in the sidebar).</p> <p>The source for this is on <a href="">Github</a>, so please add issues there and fork away.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-04-27:702 2009-04-27T12:36:00Z 2009-04-27T12:41:07Z Best CMS For Developers? Rails. <p>The site you’re looking at right now (unless you’re reading from <span class="caps">RSS</span>) is old, ugly, and busted. Yes, the EdgeCase site – and blog – are in desperate need of an overhaul. While <a href="">@nummi</a> kicks around some design ideas, I’ve started looking into how to power our future home on the web.</p> <p>Our needs are pretty simple. We need a collection of pseudo-static pages (occasional updates, but with some dynamic content), and a blog. This sounds like a simple <a href=""><span class="caps">CMS</span></a> to me, and <span class="caps">CMS</span> solutions are supposed to make sites like this completely painless, right?</p> <p>Yes, I am that delusional.</p> <p>You see, I’ve never actually used a <span class="caps">CMS</span>. Everything we’ve built at EdgeCase has been far too custom to be considered a <span class="caps">CMS</span>, so until last Friday, I’d really only heard about them. Unfortunately, what I discovered after looking at some popular Ruby <span class="caps">CMS</span> solutions (<a href="">Radiant</a> and <a href="">BrowserCMS</a>) is that I <strong>hate</strong> CMS systems.</p> <p><span class="caps">A CMS</span> might make a lot of sense for a business of non-techies – regular folks who need to manage their content without calling up the “web guy”. But that’s certainly not us. We’re an entire company of “web guys”. At this point you might be thinking I’m ignorant for not realizing we’re outside the target audience for a <span class="caps">CMS</span>, and you’re right. But I didn’t realize this, so I’m going to rant for a bit on why <span class="caps">CMS</span> systems suck for developers.</p> <p>The problem is that the benefits regular users get from a <span class="caps">CMS</span> just don’t apply to developers, and in fact they often cripple us. Take the most obvious <span class="caps">CMS</span> feature of editing your site content within a browser. Is there a developer out there who is as comfortable in an <span class="caps">HTML</span> textarea or a Word-like <span class="caps">WYSIWYG</span> as they are in their preferred text editor? But really this is the tip of the iceberg, a minor issue that I can get over, and I also can’t deny the convenience of committing a content change with the click of a single submit button.</p> <p>But going a step further, most <span class="caps">CMS</span> systems also make the templates available for editing within a browser. This is where real pain sets in for me, and for two reasons: <a href="">bastardized</a> <a href="">templating</a> <a href="">languages</a>, and lack of a real editor. As a Rails developer, I’m very comfortable with <span class="caps">ERB</span>, and even more so with <span class="caps">HAML</span>. I should <strong>not</strong> have to learn a new templating language just to build my simple website. And regardless of which language I use, I simply don’t have the patience to code <span class="caps">HTML</span> in a textarea. I may not be a fan of editor wars, but I at least need an actual text editor if I’m building a website.</p> <p>Other <span class="caps">CMS</span> niceties… Content versioning? If the content is part of the code base, I get that for free with Git. Permissions? Our needs are simple – if you have access to edit the code, you have access to edit the content. Plugins? Rails certainly has plenty of plugins, and with Rails 2.3 supporting Rails Engines and Rack middleware, the possibilities are endless.</p> <p>So where does this rant leave me for the EdgeCase site? A Rails app, of course – custom built, because I’m not convinced that anything pre-built is actually going to make my life easier.</p> <p>For the blog component of the site, I’ve got a lot of options to explore. I could, of course, build something from scratch. This might not be a bad idea, since our needs are pretty simple. But there are also some blog engines out there that could be worth checking out: <a href="">Marley</a> and <a href="">Scanty</a> are a couple that look very interesting. I’d love to see an engine-style Rails plugin that provides a blog, but I haven’t come across one yet. Perhaps we’ll just have to build one ourselves. After all, a blog can be <a href="">built in 15 minutes</a>, right?</p> <p><a href="">Follow me</a> on Twitter if you want updates on what direction we take. Or you could just wait for the redesigned EdgeCase site. It should arrive on or before 2011.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-04-22:698 2009-04-22T12:49:00Z 2009-04-22T12:55:42Z Debugging jQuery Events <p>When an app reaches a certain level of complexity, particularly with regards to JavaScript, you’re probably going to have events bound and triggered all over the place. Events are a powerful thing, but they can be a bitch to debug.</p> <p>This didn’t use to be the case. Back when we were all setting events inline, all you had to do was look at the <span class="caps">HTML</span> to know what events are bound to to an element:</p> <pre><code> <form onsubmit="if (!validate(this)) return false;">...</form> </code></pre> <p>I’m going to give you the benefit of the doubt that you’re not doing this anymore. I’ve been writing (and evangelizing) unobtrusive JavaScript for years now, but I have to admit this is one aspect of inline event handling that I really miss.</p> <p>Take this scenario:</p> <p>You’ve given a form a class of “ajax”, and you’ve got the following jQuery in place to make sure that all forms with a class of “ajax” are submitted via Ajax.</p> <pre><code> $('form.ajax').ajaxForm(); </pre></code> <p>Unfortunately, when you try to submit the form, nothing happens. Nothing at all. No Ajax. No form post. No errors.</p> <p>What do you do?</p> <p>In the past, I’d start sticking console.log statements in my JS, or maybe debugging directly in Firebug. Recently, though, I found a better way. I was fumbling my way through the event code in jQuery, and I discovered that event data is easily accessible through the element itself. Here is how a Firebug session might look as I dig into these events:</p> <p><img src="" alt="" /></p> <p>The first thing I do is grab the form element, and see what it has in the “events” data (if you’ve never messed with the data() method before, <a href="">you should</a> ). I see that there is at least one handler assigned to the “submit” event, so I iterate through each of them and call toString() on each function so I can see the actual code.</p> <p>The second function listed is the actual code for the ajaxForm() method, so it’s cool. The first one, though, is the culprit I’m looking for. This handler is being bound to my form’s submit event somewhere, and it’s calling stopImmediatePropagation() which prevents any other handlers from being called. Then it’s just a matter of searching for that exact code in the project, removing or fixing it, and beating the developer who put it there (which is usually me).</p> <p>I admit this is not as easy as glancing at the <span class="caps">HTML</span> and seeing the event handler code inline, but it at least gets the job done. Any other tips for debugging events, please share in the comments!</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-04-14:691 2009-04-14T19:44:00Z 2009-04-14T19:44:42Z Show Off Your Mockups <p>Whether you’re a do-it-all designer/developer or if those roles are separate, odds are your typical workflow involves taking a static <span class="caps">HTML</span> mockup and wiring it up with all your crazy codes.</p> <p>So, maybe you’ve got an <span class="caps">HTML</span> file with a bunch of dummy data in it that you need to demo for a client. You probably stuck it somewhere in /public because it’s easy. It’s probably got a list of copy-and-pasted garbage in there, too, so it looks like a “real” page with lots of data. And of course there’s the header, footer, and other layout cruft you had to add so it fits the look of the rest of the application.</p> <p>You’ve gotten some feedback from your client, and made some tweaks to the design. It’s looking pretty good. You’re feeling pretty good. Now it’s time to wire that page into the application.</p> <p>Still feeling good?</p> <p>This is the part that sounds so easy until you have to dive in and do it. It’s painful and tedious, but the good news is, it doesn’t have to be. It’s time to let <a href="">Showoff</a> come to your rescue.</p> <pre><code> script/plugin install git://github.com/adamlogic/showoff.git script/generate showoff </code></pre> <p>This plugin is an extraction from a recent project where I got tired of dealing with this same old scenario. I wanted a place where I could stick mockups without thinking about it. I wanted my mockups to use the same layout, <span class="caps">CSS</span>, and JavaScript that the rest of my application does. I wanted to be able to use Ruby in my mockups to have access to looping, variables, and data generation (<a href="">Faker</a>). I wanted partials in my mockups. And I wanted a single place to go where the client and development team could see all of the mockups.</p> <p>After installing and generating Showoff, navigate to /mockups in your app to see some examples. To make your own, just create a file in app/views/mockups. You can use <span class="caps">HTML</span>, ERB, or any other templating language (such as <span class="caps">HAML</span>) that your application supports. Yes, it really is that simple.</p> <p>Here is an example in a fresh Rails app with Ryan Bates’ <a href="">nifty_layout</a> applied:</p> <p><img src="" alt="" /></p> <p>I’m sure Showoff isn’t the first plugin to attempt to simplify this process, but I can tell you that it’s working really well for us. Check it out and let us know what you think.</p> <p><strong>Update:</strong> I should also add that this plugin requires Rails 2.3, since it makes use of an engine-style plugin. This basically lets you embed one “mini app” inside of your main app. It’s pretty powerful, and I’ll write more about my experience of extracting this plugin in a a future post.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-04-06:676 2009-04-06T18:53:00Z 2009-04-06T19:00:52Z See Your CSS Changes in Real-Time in Any Browser <p>I’ve wanted to scratch this itch for a while, and this morning I decided to steal a few hours to give it a shot. Most of my <span class="caps">CSS</span> authoring and editing takes place in Firefox, using Web Developer Toolbar. For me, seeing <span class="caps">CSS</span> rendered in real-time is the only way to write it. (This is one reason I had to pass on Sass, even though I love Haml, but that’s a topic for another time.)</p> <p>This has come major shortcomings, though, since Web Developer Toolbar is not intended to be a text editor (nor should it be). The biggest pain is saving your changes. A save button is provided, but you have to navigate through your filesystem to find the right location. If you’re lucky this location will be remembered next time you save. Support for find and undo is shaky at best, and as a Vim user, there about a thousand other features that I “need” in my text editor.</p> <p>The other problem with Web Developer Toolbar is that it is Firefox-specific. On days that I have to debug my <span class="caps">CSS</span> in IE (my “hating life” days), I’m back to the refresh button.</p> <p>Today I may have found a solution.</p> <p>I say “may” because I literally just wrote this. I’ve tested it a little bit, but I can’t claim to have used it for real project work. Nonetheless, I’m pretty damn excited. Twenty minutes ago I had three browsers open (IE, Safari, and Firefox), and saw all three of them update as I saved my <span class="caps">CSS</span> file in Vim.</p> <p>Check it out on <a href="">Github</a> and let me know what you think. As long as you’re using jQuery, using it is as simple as dropping in the .js file and calling $.autoUpdateStylesheets.</p> <p>My next steps are to pull this into a bookmarklet and remove the jQuery dependency. Then it’s just a matter of pushing a button and editing away in your favorite text editor. Enjoy.</p> <p>(oh, and this should work with Sass, too, so I guess it’s time for me to take another look.)</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-03-30:656 2009-03-30T17:41:00Z 2009-03-31T13:34:05Z Seeding Your Development Database with Faker and Factory Girl <p>For the longest time, I’ve used fixtures as a means to seed some basic data in my development environment. The goal is to put the application in a useable state without having to manually create data (such as users or anything else required to run the app). In my most recent project, however, I’ve completely abandoned fixtures, and I doubt I’ll ever look back.</p> <p>I felt two kinds of pain with fixture data – the pain of maintaining it and the lack of quality data.</p> <p>The pain of maintaining fixtures was usually bad enough (and I was lazy enough) that I typically just ignored it altogether. With every change to the schema, more data had to be added or changed. And not just one place, since a fixture usually contains several records. I just don’t have the patience for it.</p> <p>Due to my lack of patience, fixture data in any of my projects has been completely unreliable. I’ll leave out fields that end up being required. Or I’ll only put one record in a fixture file because I’m too lazy bother with more.</p> <p>I put up with this pain for too long. The ability to quickly seed a development database with valid, useable data is a big deal, and I was done ignoring the problem. Enter Faker and Factory Girl.</p> <p>You probably already know what <a href="">Factory Girl</a> is, but in case you don’t, it’s just another factory implementation, and it happens to be my preferred implementation at the moment. If you prefer another, I’m sure it will work just as well with what I’m describing here.</p> <p><a href="">Faker</a> is a Ruby library for generating pseudo-random data. Typically, this is exactly the kind of data that I want in my development database. Repeatability isn’t that important. Faker will generate names for people and business, addresses, phone numbers, Lorem text, <a href="">BS</a>, and more. I use Faker in my factories as a template for pseudo-random models:</p> <pre><code> Factory.define :user do |u| u.email { Factory.next :email } u.email_confirmation { |u| u.email } u.password 'test' u.password_confirmation { |u| u.password } u.first_name 'Test' u.last_name 'User' end Factory.define :user_sample, :parent => :user do |u| u.first_name { Faker::Name.first_name } u.last_name { Faker::Name.last_name } end </code></pre> <p>Here, the ‘user’ factory is used in tests. It doesn’t use Faker, because I need my tests to be consistent and repeatable. The ‘user_sample’ factory, however, inherits the ‘user’ factory and uses Faker to generate the name.</p> <p>Once I have my factories ready to go, I create a custom Rake task to seed my development database:</p> <pre><code> namespace :db do desc 'Provide a base load of randomly generated (but valid) data for development' task :seed => [:reset, 'fixtures:load'] do # generate users users = [] 6.times { users << Factory(:user_sample) } users << Factory(:user, :email => 'user@edgecase.com', :role => 'user') users << Factory(:user, :email => 'admin@edgecase.com', :role => 'admin') # generate orders 20.times { Factory(:order_sample, :user => users.rand) } # login instructions puts "\n**************\n\nThe following accounts are available for use:\n\n" puts ' user@edgecase.com (password: test)' puts ' admin@edgecase.com (password: test)' puts "\n**************\n\n" end end </pre></code> <p>With this in place, I can run <code>rake db:seed</code>, and I’ll get a nicely bootstrapped development database to poke around in. Each order will belong to a random user with a random name. It’ll be different every time you run it. It’s like a box of chocolates. Or something.</p> <p>Want more users? Change 6 to 60. Lovely.</p> <p>Notice that db:seed still has db:fixtures:load as a prerequisite. This means that fixtures are still an option if I want to combine them with my custom seed task. Nice as that sounds, I haven’t used it. Fixtures are, for me, but a memory.</p> <img src="" height="1" width="1"/> Adam tag:blog.edgecase.com,2009-03-23:621 2009-03-23T16:15:00Z 2009-03-23T16:25:27Z Better Flash and Validation Messages <p>In Rails, there are two common types of messages that we show on a page. Flash messages, which are page-level messages telling the user that something has happened. And validation messages, which are specific to a form that the user filled out (actually, they are specific to a model, but we’ll focus on the user’s point of view).</p> <p>I rarely see these messages presented in a way that satisfies me. My two big complaints are separation and language.</p> <h2>Separation</h2> <p>I’ve always been bothered at typical Rails apps (including many of ours) that separate flash messages from validation messages, often with completely different styling. In my mind they are slight variations of the same thing: informational messages for the user. They should be shown together, in a consistent location, and with the same styling.</p> <p>The reason they are typically separate is purely implementation. Flash messages are set in controllers in usually spit out in an application layout file. Validation messages come from model objects and are usually spit out within forms. Rails makes it very easy to do this, and many Rails tutorials promote this separation.</p> <p>Come together, right now…</p> <p>Just because it’s easy doesn’t make it right, but I’d much rather have both. Recently I’ve found the <a href="">message_block</a> plugin that combines flash and validation messages and spits them out in a single div. It’s easy to use and does exactly what it claims. The <span class="caps">README</span> is pretty self explanatory, so go check it out.</p> <h2>Language</h2> <p>The validation messages that come packaged with Rails are very convenient. Purely based on the column name and the validation method, Rails can generate an error message that is logically correct. Unfortunately, they are rarely user-friendly.</p> <blockquote> <p>“User Experience is invalid.”</p> </blockquote> <blockquote> <p>“Please is not included in the list.”</p> </blockquote> <blockquote> <p>“Context can’t be blank.”</p> </blockquote> <p>These are all examples of out-of-the-box validation messages. If you don’t see a problem with them, I probably can’t convince you there is. It’s totally a matter of personal preference.</p> <p>Now, you’re probably thinking that there is a built-in way to customize validation messages, and you’re half right. The problem is that you can’t customize the full message.</p> <pre><code>validates_presence_of :city, :message => 'Please enter the city.'</pre></code> <p>This code will produce the following message:</p> <p>“City Please enter the city.”</p> <p>Uh oh. Rails only lets you customize the latter half of the error message. In many cases, and for many developers, this is good enough. But not me. Much like a designer wants control over every pixel, I demand control over every word. Enter <a href="">custom-err-msg</a>. With this plugin, I can have full control over the message by prepending ’^’.</p> <pre><code>validates_presence_of :city, :message => '^Please enter the city.'</pre></code> <p>Problem solved.</p> <p>These are two plugins I’ll be using in every project from here on out. I think my users will appreciate it.</p> <img src="" height="1" width="1"/> joe tag:blog.edgecase.com,2009-01-26:270 2009-01-26T20:54:00Z 2009-01-26T20:59:17Z Learning Ruby Through Testing <p>We have finally published the Ruby Koans to github at <a href="//github.com/edgecase/ruby_koans">edgecase/ruby_koans</a> If you do not have a github account or use git, do not worry, you can click the download button on that page to receive a zip file containing the latest version of the source.</p> <p>The idea was born thanks to <a href="//">Mike Clark’s blog post</a> about learning Ruby through unit testing. It teaches both language and culture in a self-paced manner.</p> <p>We look forward to comments and any feedback you have. Enjoy!</p> <img src="" height="1" width="1"/> joe tag:blog.edgecase.com,2009-01-14:268 2009-01-14T01:58:00Z 2009-01-14T02:01:45Z CodeMash wrap up coming <p>We promised a posting on our Ruby stuff from CodeMash and it is not here yet. We are polishing a few items for the Koans and will post them up when they are finished.</p> <p>If they are not up by Friday you have permission to harass us :-).</p> <img src="" height="1" width="1"/> ehren tag:blog.edgecase.com,2008-12-12:263 2008-12-12T21:53:00Z 2008-12-12T22:06:42Z When Burnt Out Goof off. It helps. <br /> <img src="" alt="pong-screen" /> <br /> Written by me. Firefox 3 only. Control and shift for the left paddle, arrow keys for the right paddle. <br /> <a href="">download src (html and javascript)</a> <img src="" height="1" width="1"/> nick tag:blog.edgecase.com,2008-10-31:258 2008-10-31T13:12:00Z 2009-04-07T15:17:30Z Damn The Standards And Full Read The Documentation! <p>Do not let conventions prevent correct behaviour.</p> <p>Often within an ActiveRecord::Base model, statements of a certain ilk are grouped together. For example the single line validations are often in the same place. It is tempting to place additional statements such that the model file is consistent. One might put all the <tt>before_destroy</tt> callback macros near the <tt>before_save</tt> or <tt>after_save</tt> statements.</p> <p>Without loss of generality the following example models illustrate a behavioural anomaly that was encountered.</p> <code><pre> ActiveRecord::Schema.define(:version => 1) do create_table "accounts", :force => true do |t| end create_table "invoices", :force => true do |t| t.integer "account_id" end create_table "receipts", :force => true do |t| t.integer "account_id" end end class Account < ActiveRecord::Base has_many :receipts, :dependent => :destroy has_many :invoices, :dependent => :destroy before_destroy :ensure_no_invoices def ensure_no_invoices return true if invoices.empty? false end end class Invoice < ActiveRecord::Base belongs_to :account end class Receipt < ActiveRecord::Base belongs_to :account end </pre></code> <p>The intent is to prevent the destruction of an account and related models when the account still has at least one invoice. The above code is how <strong>not</strong> to do it. The following sandboxed example demonstrates that the account will not be destroyed but that associated models will be.</p> <code><pre> test_before_destroy> ./script/console --sandbox Loading development environment in sandbox (Rails 2.1.1) >> [Account.count, Invoice.count, Receipt.count] => [0, 0, 0] >> account = Account.create => #<Account id: 1> >> account.invoices.create => #<Invoice id: 1, account_id: 1> >> account.receipts.create => #<Receipt id: 1, account_id: 1> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy => false >> [Account.count, Invoice.count, Receipt.count] => [1, 0, 0] </pre></code> <p>The Rails documentation on <tt>before_destroy</tt> can be found on the <a href="">callbacks</a> entry. There is a vital clue stated there.</p> <pre> *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won‘t be inherited. </pre> <p>The documentation mentions only “inheritance” but further experimentation reveals that the desired behaviour of not destroying a model and related models is obtained when the documentation is heeded.</p> <code><pre> class Account < ActiveRecord::Base before_destroy :ensure_no_invoices has_many :receipts, :dependent => :destroy has_many :invoices, :dependent => :destroy def ensure_no_invoices return true if invoices.empty? false end end </pre></code> <p>Here the <tt>before_destroy</tt> macro is written before the associations. This <strong>is</strong> how to do it.</p> <code><pre> test_before_destroy> ./script/console --sandbox Loading development environment in sandbox (Rails 2.1.1) Any modifications you make will be rolled back on exit >> [Account.count, Invoice.count, Receipt.count] => [0, 0, 0] >> account = Account.create => #<Account id: 2> >> account.invoices.create => #<Invoice id: 2, account_id: 2> >> account.receipts.create => #<Receipt id: 2, account_id: 2> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy => false >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] </pre></code> <p>Interleaving the <tt>before_destroy</tt> macro between the associations allows the destruction of one associated model but not the other.</p> <code><pre> class Account < ActiveRecord::Base has_many :receipts, :dependent => :destroy before_destroy :ensure_no_invoices has_many :invoices, : 3> >> account.invoices.create => #<Invoice id: 3, account_id: 3> >> account.receipts.create => #<Receipt id: 3, account_id: 3> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy => false >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 0] class Account < ActiveRecord::Base has_many :invoices, :dependent => :destroy before_destroy :ensure_no_invoices has_many :receipts, : 4> >> account.invoices.create => #<Invoice id: 4, account_id: 4> >> account.receipts.create => #<Receipt id: 4, account_id: 4> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy => false >> [Account.count, Invoice.count, Receipt.count] => [1, 0, 1] </pre></code> <p>Note that when the <tt>before_destroy</tt> macro is declared after the associations and the specified check raises an exception, the <tt>script/console</tt> sandboxed environment does not rollback the destruction of the associated models because of the transactional nature of the entire <tt>script/console</tt> session.</p> <code><pre> class Account < ActiveRecord::Base has_many :receipts, :dependent => :destroy has_many :invoices, :dependent => :destroy before_destroy :ensure_no_invoices def ensure_no_invoices return true if invoices.empty? raise RuntimeError.new('Attempted to destroy account that still had invoices!') end end test_before_destroy> ./script/console --sandbox Loading development environment in sandbox (Rails 2.1.1) Any modifications you make will be rolled back on exit >> [Account.count, Invoice.count, Receipt.count] => [0, 0, 0] >> account = Account.create => #<Account id: 5> >> account.invoices.create => #<Invoice id: 5, account_id: 5> >> account.receipts.create => #<Receipt id: 5, account_id: 5> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy RuntimeError: Attempted to destroy account that still had invoices! from ... (irb):6>> [Account.count, Invoice.count, Receipt.count] => [1, 0, 0] </pre></code> <p>When <tt>script/console</tt> is executed without the sandbox option, the effects of a rollback can be observed upon the attempted destruction of an account with invoices.</p> <code><pre> test_before_destroy> ./script/console Loading development environment (Rails 2.1.1) >> [Account.count, Invoice.count, Receipt.count] => [0, 0, 0] >> account = Account.create => #<Account id: 6> >> account.invoices.create => #<Invoice id: 6, account_id: 6> >> account.receipts.create => #<Receipt id: 6, account_id: 6> >> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] >> account.destroy RuntimeError: Attempted to destroy account that still had invoices! from ... (irb):6>> [Account.count, Invoice.count, Receipt.count] => [1, 1, 1] </pre></code> <p>Read the documentation.</p> <p>Put the <tt>before_destroy</tt> macro before associations.</p> <p>The sandbox option in <tt>script/console</tt> may mask rollbacks.</p> <img src="" height="1" width="1"/>
http://feeds.feedburner.com/edgecase
crawl-002
refinedweb
6,978
65.83
Sue Evans Press space bar for next page The ADTs we've worked with so far are : all of which are built-in data types of Python. Abstract data types do not have to be large data collections, as the ones are that we've worked with so far. Whenever we define an ADT, we need to give a definition and a list of operations. Example: The fraction 1/2 means that if an object is divided into two equal parts, then we are working with one of those parts. The 1 is known as the numerator and the 2 is known as the denominator. Both the numerator and denominator of a fraction are integers. The denominator cannot be 0. When working with fractions, we are sometimes interested in a whole number as well, as in 5/4 = 1 1/4. Numbers expressed as fractions can have a whole number part as well as a fractional part. The operations on fractions include : Notice that we haven't discussed the implementation of any of our ADTs ADTs typically can be implemented in many different ways, and often are implemented differently when using different languages. In order to work with your new type, you will probably have to write functions that will allow you to : print '%d %d/%d' % (whole, numerator, denominator) When writing the code to implement your new type, you should try to give it all of the functionality you can foresee. For instance, if you are writing a program using fractions, and it is only necessary for this program to be able to add and subtract fractions, you should also implement multiplication and division, to produce a fully-usable ADT. A queue is what Americans commonly refer to as a line. The example is that you get into a line at the grocery store. In Great Britain, lines, like the line of customers waiting at the checkout, are called queues. The word queue is more specific. The word line can also mean, a line between two points, the line down the middle of the road, etc. People. A queue is a linear collection of items, where an item to be added to the queue must be placed at the end of the queue and items that are removed from the queue must be removed from the front. The end of the queue is known as the tail and the front of the queue is known as the front. The term enqueue means to add an item to the queue, and the term dequeue means to remove an item from the queue. There are actually very few operations on a queue. A queue is NOT a built-in data type in Python, however you could write these functions that make use of Python's list methods. A stack is a little harder to define than a queue, since there isn't a common term that will relate how a stack works. It is definitely a linear collection of similar items. Stacks have access rules too, but the rules are different than the rules for queues. You have been exposed to the idea of a stack before. When you go to a cafeteria to get lunch you take a tray from the stack of trays. You must always take the tray that is on the top of the stack. The cafeteria personnel put clean trays on the stack. The clean trays are always added to the top of the stack, so the tray that's on top is the last one that was added. A stack is refered to as a LIFO data structure: Last In, First Out. A stack is a linear collection of similar items, where an item to be added to the stack must be placed on top of the stack and items that are removed from the stack must be removed from the top. The top of the stack is known as the top. The term push means to add an item to the stack, and the term pop means to remove an item from the stack. There are actually very few operations on a stack. A stack is NOT a built-in data type in Python, however you could write these functions that make use of python's list methods. What data structures would you use for these programs? def pop(items): size = len(items) popped = items[size - 1] del(items[size - 1]) return popped def main(): cars = [] cars.append('Audi') print 'pushing Audi' cars.append('Buick') print 'pushing Buick' cars.append('Chevy') print 'pushing Chevy' cars.append('Dodge') print 'pushing Dodge' print while len(cars) > 0: print 'popping', pop(cars) main() Let's run it!ite207-pc-01.cs.umbc.edu[138] python pop.py pushing Audi pushing Buick pushing Chevy pushing Dodge popping Dodge popping Chevy popping Buick popping Audi ite207-pc-01.cs.umbc.edu[139]
http://www.csee.umbc.edu/courses/undergraduate/CMSC201/fall09/lectures/adts.html
crawl-003
refinedweb
813
79.09
See also: IRC log <patrickdengler_> i do not have skyp.. hmm <heycam> patrickdengler_, we'll set up the zakim bridge <heycam> patrickdengler_, and get cyril to call in to it from here <vhardy> ScribeNick: vhardy <patrickdengler_> i'll dial in in about 35-45 minutes <heycam> patrickdengler_, is it ok if we begin on brian's topic and you come in half way through? <patrickdengler_> please begin brian's topic without me of course brian: this came out of the Seattle F2F to look at the features that are in SVG animations and not in CSS animations and then prioritize them according to usefulness. ... I wrote a long document. ... the first part is in response to the action, about features. This is input to the FX task force. ... I have written it for CSS animations people who do not know SMIL. ... I start by listing the differences. Then I created a few use cases. They may not be sufficient, I would appreciate additional use cases. ... then, I have attempted to prioritize. ... finally, this is what I would like to talk about, is the proposal for an element syntax that is a middle ground between CSS animations and SMIL animations. I would like to discuss the concept and see if there is support. chris: how does this differ from what Patrick is proposing? brian: Patrick is proposing to extend the reach of CSS animations in SVG so that you can animation more attributes by making them presentation attributes and animatable by CSS animations/transitions. My proposal looks at adding missing features in CSS Animations/Transitions, such as timing and synchronization. ... Going through what I have written down, here is what is missing from CSS animations. ... Timing. One major difference is that SVG animations have an absolute reference whereas CSS animations start on document load or at the time there is a property match. dean: yes, this is pretty imprecise in CSS. The actual time is the first time it renders, and CSS does not specify when that time would be precisely. This means forcing a style resolution. There is no real way to kick start the animation precisely. chris: is there a way to resolve this? dean: implementations end up doing the same thing and it resolves ok. Things are similar enought that people do not notice. <TabAtkins> As long as you're not trying to chain animations, yes, it's "good enough" right now. <TabAtkins> Being able to specifically relate animations to a timeline and/or chain animations together is something I feel is important to eventually support. shane: because the aniamtions are resolved on style resolution and style resolutions happen at different times, the user may get offsets between animations starts that he/she does not want and cannot control. dean: the current behavior is kind of ok, but we need something more precise. shane: I have a question about the SVG timing model. Can you sync. up two animations? (several): yes. (several): explain time conditions in SMIL, such as <animate begin="button.click" ..> and <animate begin="myFirstAnim.begin+2s" ... /> brian: in point T1b), there is a description of the features available in SMIL. <cyril> zakim what is the code brian: getCurrentTime and then call beginElement, you will get the same time. This could be better specified. dean: In WebKit, for animations, we don't update/apply different times to the animation in the same script context. ... if you add several animations, they appear to start at exactly the same time. ... CSS does not specify when the animation starts between the time the style is set and when it really kicks in (at style resolution or first rendering). heycam: in SVG animation, you can specify an absolute time. In CSS animations, you can only specify somethign to start relative to the current time. brian: yes, that is correct. ... correct sync. with events is possible in SMIL animation. <heycam> (where by absolute time I mean an absolute time within the document timeline, not a wallclock time) shane: if we modified CSS animations to better define the time animations start, would that be desirable? dean: yes. <ed> Meeting: SVG WG Sydney 2012 F2F day 2 dean: I think brian will go on to explain how an absolute timeline could work. ... I think that is ok. There should be a way to start at an absolute time. <TabAtkins> Sage. brian: Below T1 c), I propose ways to have a proper timing, like defining a time container in HTML. We can use inspiration from SVG Tiny. heycam: we already want a unified notion of time line for requestAnimationFrame and performance APIs, so we should also use a unified notion for CSS animations and SMIL animations. cyril: why did not CSS animation use a time container to begin with? shane: because it was defined to start at 'style resolve time'. brian: my proposal addresses these issues with proposals. ... I propose to consider the timelneBegin, as we have in SVG animation. ... I have a few suggestions to introduce the same in CSS animations. cyril: this is something we cannot decide here, right? brian: yes, this is input to the FX task force, an ACTION I had from the Seattle F2F. <TabAtkins> CSS Animations were defined in a very limited and weak way at first. They simply run as long as the property applies, starting "when the property starts to apply" and stopping when it stops. brian: we are not trying to decide here now. I am looking for input. <TabAtkins> By the way, Brian, excellent doc. Lots of food for thought. brian: moving on to T2. ... in SVG animations, you can schedule multiple intervals. There is only one in CSS animations. heycam: CSS animations only support something like 'style resolution time' or 'style resolution time + offset'. brian: yes, that is true, but you cannot control playing the animation multiple times declaratively. ... if introduce that feature, we need to decide how overlaps of the same animation are handled. SVG animations specify how to handle that type of situation. <TabAtkins> From pure CSS, we'd have to add another at-rule or something that defined an animation separately, so we could tell it to start based on various things. heycam: in SVG animations, you can have indefinite values in the list, and then you can start the animation with a script call (beginElement). <TabAtkins> Alternately, create a decent JS API for constructing Animation objects. <TabAtkins> Or rely on the increasing merging of SVG into the other languages and have an element in SVG for it. heycam: the CSS equivalent is to manipulate the style to set the animation-name to none and then set it again. brian: going on to T3, aborting animation. There in an end attribute in SVG animations. ... that is not available in CSS. <TabAtkins> Note: I do *not* think that extending the power of the 'animation' property is the right direction here for almost any of this. <TabAtkins> 'animation' does a single simple thing and does it reasonbly well. It shoudl be considered a shortcut for applying animations while an element is in a particular state, not the canonical way to interact with animations. vhardy: you can abort an animation in CSS, but not declaratively, you need to manipulate the style. <TabAtkins> imo <TabAtkins> We should be considering animations as objects separate from the 'animation' property when thinking about how to address most of these. <TabAtkins> (Similarly, 'transition' does a single simple thing well.) <birtles> TabAtkins, ok that's good. The "proposals" aren't serious, just showing how these features relate to CSS Animations. Other proposals are very welcome. chris: Microsoft has expresssed that they do not want to implement SMIL animations. So if we want more features or address the problems, we need to add features to CSS Animations. <dino> i agree with Tab (mostly - I do think we can extend the animation property to solve some of the things in Brian's document in a simple manner) vhardy: may be if we can demonstrate that more features are needed and that adding them to CSS animations creates the same amount of work as implementing SMIL animations, Microsoft may reconsider their position? <TabAtkins> dino: Yeah, some of the things may be appropriate for extending 'animation' - this is a long list. ^_^ vhardy: I also agree that having a common underlying model that different syntaxes / markups map to is the right architectural approach. <TabAtkins> vhardy: I still doubt that they'd like to implement two separate animation models. We'd like to remove SMIL from Chrome, too - our implemenation is shit and a big security hole. <TabAtkins> Fixing the security bugs is a "reimplement the whole thing"-level task. <dino> I do agree vehemently with the goal to not make the CSS syntax for animations much more complex than it currently is. I'd rather go without features in the CSS syntax than make things confusing. I'd prefer a JS API. This goes quadruple for transitions. chris: people do not want to have SVG animation elements because they want styling and animations seperate. ... the animations could be started from a stylesheet but pointing to a resource where the animations are defined. vhardy: I think that animations are sometimes content sometimes styling. For example, if you do a cartoon, animations are the content. If applying to an HTML dialog, they are styling. ... also, I think that because there are issues with SMIL engines implementations, we should not conclude that the issue is necessarily with SMIL itself. ... there are a lot of good things in the SMIL model that I hope can be the underlying model for a common animation solution applying to CSS, Scripting (and obviously SMIL). heycam: I think the SMIL scripting APIs are limited. vhardy: yes, my point is that if we defined better scripting APIs for animations, we should leverage the same underlying model and use the SMIL timing model as much as possible. brian: I don't agree an API will solve everything. Sometimes, we need more APIs for animation, but I do not think that will be enough. I think declarative animations is needed. We need a way to do reasonably sophisticated animations declarative animations. chris: I agree. vhardy: I agree. cyril: we've had SVG animations for a long time, they are declarative, and no one is using it. Why are people using CSS animations more, specifically in authoring tools. chris: there is not much room for a tool for CSS in general, and in particular for CSS animations. ... I do not expect tools editing CSS animations in general? rik: why not? All the information is there? chris: I am talking about reading content that was not written by the tool? ... for CSS in general. cyril: I agree with brian in general. It is better to have a declarative solution for authoring tools. brian: regarding the adoption, CSS animations apply to HTML and SVG animations to SVG. There is much more HTML than SVG, so that explains the difference in adoption. <patrickdengler_> There is always this agrugment between declarative and code. Historically, code in browsers meant x-scripting issues. In non-HTML contexts, declarative vs. code has become a bit of a redherring. Yes, tools and tool declarative syntax better, but the harder you push declarative support, the harder it is to understand the concepts, and thus the harder it is to tool them. <patrickdengler_> Does that make sense? vhardy: I think one factor too is that CSS animations, at least initially, have been used for UI effects that do not require as many animations and synchronization as you would need for complex cartoons for example. For the types of animations enabled by SMIL, tools are needed and there have been a lack of tools so far. <patrickdengler_> and untoolable <patrickdengler_> declarative is still code :) tab: I agree with Patrick. heycam: I think the declarative v.s. scripting is a bit off-topic. brian: the argument put forward is that all we need is a very elementary CSS animation and then a scripting API. I disagree with that position. vhardy: yes, I agree. brian: yes, it is not just about tool support. Security is one of the major issues, probably the main compelling reason. You can use animations where you cannot use scripting. ... back to T4 on synchronizing animations. That is in SVG animations and not in CSS. <patrickdengler_> I respect Brian's well done analysis. My position is that if you increase the feature set of CSS Animations, and back it with a richer API, that this is a better balance long term. That''s all. brian: there is a proposal to how to add synchronization to CSS animations, it is rough. ... it is a big feature. ... T5. Seeking the document timeline. ... that would be useful in CSS animations as well. dean: yes, this is useful. CSS animations does not really talk about time containers. So theoritically, each animation is in its own timeline. brian: T1 may be a pre-requisite for this feature. chris: having unsynchronized timelines is not useful, because it is common to need to sync. animations. cyril: do implementations implement time seeks? brian, ed: yes. cyril: Is it well specified? brian: yes, it is decent. cyril: do we have tests in the test suite for those? ed: yes. brian: T6, ability to pause the timeline. ... T7: repeating by duration instead of duration count. ... this might even be more important with time containers. dean: this is not currently an issue because you always know the duration of children. brian: it is a convenience, and you can often calculate it and use repeatCount. dean: what is an example of why you would use repeatDuration? brian: when you want to sync. on the duration of other animations and not want to compute how many hundreds of iterations that makes in the other aniamtions you are trying to limit in time. ... T8, triggering animations from arbitrary events. cyril: there is a difference between using the begin event and the begin sync. arc. <cyril> <animate begin=a.begin> is different from <animate begin=a.beginEvent> brian: there are differences, the most important one is negative offsets. With sync. base timing, the time will be resolved, but with the event base, the animation will only start after the event has fired. ... there are also differences with seeking. ... so this is the argument for keeping sync. based timing. <heycam> [brian shows a demo] brian: showing a demo of a video and an animation sync. up with the video. <cyril> <birtles> <animate attributeName="stroke-dashoffset" from="9px" to="0px" <birtles> dur="1s" repeatCount="indefinite" fill="freeze" <birtles> dean: I most cases, I have found writing content to do something like this, you want to triger the event with a conditional expression. ... e.g., you click and some other state exists. vhardy: when coupled with custom events, this provide a pretty elegant solution, because you can triger animations on application events. <patrickdengler_> sorry, what? BREAK for 15mn then continue on Brian's topic. <patrickdengler_> The only topic I have for CSS Animations is going to be: are we all good with this proposal : <patrickdengler_> I've not heard any additional feedback beyond Dean's, which is incorporated, and I have otherwise heard support. If this is the case, I'd like a resolution to accept this, at which point I am happy to make the edits in the specification. <TabAtkins> Yes, I'm good. <patrickdengler_> If not, let's discuss. <patrickdengler_> I had hoped to have a prototype to run on webkit, firefox and Opera, but it only runs on IE so far. Once I have the prototype running on all browsers, I will put the code on some open source place so people could drop it in and make their sites backward compatible. <ChrisL> patrick, I sent some feedback on elevation and azimuth,did you see that? <patrickdengler_> I saw your feedback on elevation and azimuth. I believe that is included in the link. If I recall you noted that these could and should be deprecated in the CSS Aurul spec so we don't have to rename them. Is that correct? <ChrisL> yes <heycam> patrickdengler_, since we're not having an official FX meeting here, are we able to officially resolve that? <heycam> patrickdengler_, we can say whether we (SVG WG) is happy with it <patrickdengler_> THat's fine, let's start there though. Dean is good with it and perhaps he can shepard it over to CSS <heycam> ok <heycam> we will just wait a few more minutes for vincent to return <patrickdengler_> I am on the line <heycam> ScribeNick: heycam BB: first A1, animateMotion … that's not possible in CSS … seems to be quite useful … we've also already resolved to support a more general case of animation of pairs of values … that's an abstraction of animateMotion I guess … (these are animation value features not in CSS) … next, the ability to combine animation values with underlying animations, instead of replacing … I think Dean mentioned in Seattle that there's already been some proposal to add something like that … wasn't sure if that referred to this, or adding separate animations together CM: what's the difference between A2 and A3? BB: in SVG they're the same, since they both use the same concept of underlying animation values … A2 is just considering the base value of the attribute … A3 is an extension of that where you can have additive animations DJ: A3 is what has been requested for CSS Animations before BB: one other difference is that I believe CSS Animations takes a snapshot of the values when it begins animating … in SVG animations it's live … if the underlying value changes then the animation will reflect that change CL: does that mean if the script manipulates an already running animated animation property it doesn't have any effect until the animation ends? DJ: the only way you could see something happen is if the script manipulates the animation attributes … in CSS if you have an animation on an element, manipulating colour e.g., if you set the color on the style property of the element it's never going to change while the animation is running … since the animation always overrides it … if while the animation is running, you find the @keyframe and update the values there, the animation also doesn't change … you might expect to be able to change the duration while it's running, but the spec says that shouldn't work … which gets back to restarting animations, you have to remove and replace it … which is annoying BB: another point about A3 is that this is where the animation model comes in, which animation goes on top of which … some people are not keen on that model <dino> "As Anne van Karsten points out" - new nickname!!! … it might be worth reassessing how animations combine together … the last animation feature is combining animation with itself, that's accumulate="sum" in SVG DJ: how often is this used in practice? BB: I suspect not that often … but I don't really know CC: what is "SVG's endpoint exclusive timing model"? BB: that's where at t = 0, the animation effect is applied, but at t = 1 it is not applied … that's important when you accumulate … otherwise you'd have overlap … it's also significant when you have absolute time references … if you query the animation at that exact end point, the animation is not being applied so the unanimated value will be returned … now, a couple of other quick items … document structure -- SVG allows you to interleave animation content with the stuff you're animating … Anne pointed out that this is possible with CSS if you use <style scoped> … which noone supports yet … but will be possible … I think it's a little cumbersome, not totally convinced by it <TabAtkins> Chrome is nearly done supporting it. <TabAtkins> But I agree that it's cumbersome. … but it is technically possible to interleave CSS Animations with the content DJ: I would think if we want to add to this wiki document, we should a D2, timesheets … not interleaving, but still... BB: I'm just looking at what's in SVG but not in CSS … it is sometimes useful to separate out the animations from the content though … now features that don't exist in SVG Animations … I think if we're going to keep SVG animations, then we really should have time containers … they give so much utility, the use cases I'm going to present would be easier with time containers CL: I agree, we were in favour originally CC: in the 1.2T timeframe we agreed to time containers, but not nested ones BB: I'm wanting nested ones CC: you don't want the sync attributes though? BB: no, just the nested time container elements … this is one feature that I think is particularly well suited to element syntax, and not so much the CSS syntax DJ: my hestitation is that it starts putting the animation structure into the document, whereas at the moment where animations are just children of the elemnets you can think of them like decorations to the content … what this means is what we put into SVG now leaks into HTML <TabAtkins> Agreed on this being well-suited to element syntax rather than CSS at-rules. at-rules aren't great for nested structures. … that community less likely wants animation as content BB: there is a lot of discussion around animation in HTML markup … I think we want to support animation as content DJ: actually this doesn't need to be SVG, this could equally be done in HTML … (animation content) VH: I believe SMIL originally took a lot from Real Networks … they were doing a lot of education content, mixing audio, video, overlays, etc. … so they had a lot of sync work to do CL: most of that was streaming content as well VH: so they had a lot of real use cases for doing rich timed multimedia content, the content itself is timed by nature … it's important to capture the time aspect of the content CL: one aspect of that would be audio and video, coming from separate sources, and you want the video to sync with the audio … you care about audio jitter, but not video so much <patrickdengler_> Side note: I agree, that if you are going to talk about introducing elements to support animation or new animation functionality, you must do it in context of HTML, not just SVG. … but in other cases you might care about audio being synced to video DJ: if it's content, you're forcing the author to use it that way. if it's stylistic, you can do it either way. CL: say if you have some audio/video, some people want audio in some other language, or some people want subtitles … we've traditionally thought of those choices as stylistic, but it's a slipper slope … this hard wall of style vs content is more nuanced than is often presented ack DS: brian you said that time containers are better suited to element syntax, why is that? BB: because the proposal I've put forward is arbitrary nesting of time containers, including seq … in that case obviosuly it's a hierarchical arrangement … I think as Tab mentioned too, that's harder to do with @at rules … with an element syntax it's fundamnetally hierarchical DS: couldn't you have a CSS rule apply to an already predefined container, like a <g> or a <div>? BB: yes but then you'd need a rule for each <g> underneath that, and you'd need to match up the rules with each of the nested <g>s … I think that would be cumbersome to deal with DS: you have to define it either way … if it's part of the hierarchy, or in a CSS rule applying to a <g>, it's only where you define it … if you should ever want to change the nature of a time container, or a <g> that has a style rule applied to it, if you want to turn on or off a particular thing, you could do that … DJ: you could have an excl element, where the author wants it to be exclusive, different audio tracks for example BB: I think perhaps we don't need to solve this right now … I'm uncomfortable with the idea of mixing style in that way, where hierarchy is defined in content, but the meaning of that hierarchy is altered by style somewhere else DJ: it doesn't need to live somewhere else … you can put style attributes, or in SVG presentation attribtues BB: if it's a presnetation attribute it's not that different from what I'm suggesting … I suggested a grouping element, but it could be just an attribute on existing elements CC: you could use SMIL3 time sheets DJ: you're right we don't need to solve this now … but it's an important feature to solve BB: even if we use CSS rules, we're still relying on element syntax to provide some of the structure <shepazu> that's fine, I don't need to press the point DJ: should the element structure also provide new behaviour, in which case you would want to introduce new elements BB: or attributes ... I have a few use cases which I've already mentioned, not exhaustive by any means … first is not particularly exciting -- this button VH: just one comment before the use cases … I think there's also the ability to target multiple elements, mulitple properties, is not in SVG animations … but we should support that BB: there's a lot of stuff that doesn't exist in SVG Animations … this was just a more detailed version of what I proposed for Seattle VH: can you point to the Seattle document from this one? CL: I think the multiple targetting is missing and something we could fix … dean and others have suggested using CSS selectors to do this … but the target of the animation is a set of nodes <scribe> ACTION: Brian to link to the Seattle animation document from the Manly one [recorded in] <trackbot> Created ACTION-3201 - Link to the Seattle animation document from the Manly one [on Brian Birtles - due 2012-01-19]. BB: let's go through the use cases quickly … this button example was made to emulate a Flash button as a challenge … in order to do that, I've listed the features of SVG animations that were useful … multiple intervals, declaratively aborting animations, synchorising animations, triggering from events … time containers would have made this example much easier … this one, why not do it with script? might be a fair call for this example … generally with UI widgets it would be nice not to use script for the hover interactions etc. … next use case is more complex, a WIP … this is something we're doing for an event in a couple of weeks in Tokyo … there's an animation group that do workshops … they give everyone tablets where people create frame based animations [brian shows animation webapp example] … it's a collaborative project where the animations are uploaded and then combined into a display CL: can you publish this? BB: it's not quite ready, after the event in a couple of weeks … the features this example uses: … absolute time references, to insert the animations … synchronising the frames together, the ones you draw yourself … repeatDur … motion on a path … and combining with an udnerlying value … time contaienrs again would be useful, for the frame-by-frame animation, put them all in a <seq> container … one interesting thing with this, being declarative is an advantage … (though we are using script as well) … we'd like to be able to email peoples' characters to them, as a souvenir … can't run script in a mail client … when we embed subanimations in a master animatino, that's using an <image> element, and you can't run script in there … finally, example 3 … an in progress animation tool for cutout animations [brian demos moving little parts of Foxkeh arround] CC: like Terry Gilliam's animations BB: this uses setCurrentTime, getAnimVal, etc. CL: it's a classic cell frame animation kind of thing <ChrisL> Classic cell-frame animation BB: so now I have a prioritisation of animation features based on these three use cases … a tentative prioritisation … this is my assessment of the bigger items to handle … these are the features in SVG animations not in CSS animation that we could bring over, prioritised CL: synchornising multiple video and audio streams from different sources is a different use case, but it uses the same features as these other examples do CC: no, you need the runtime sync attributes, syncBehavior, syncTolerance … they're different … time containers are containers that have a clock associated, they can be nested or not … and they can be of different type, par vs seq for example … then there's how does the clock behave when it drifts, they're the sync attributes … in 1.2T we have time containers, there can be multiple timelines CL: and they're implicit <par> containers? CC: and we have the sync attributes CM: should we be bringing all these features over from your list? BB: not sure, motion on a path and time containers for example might be hard to realise in CSS syntax DJ: we get a lot of requests for motion on a path … I agree with your suggestion, it's almost like a special case of transform animations … I don't know how to represent that, though … don't like extending animation syntax just to do motion on a path BB: this is just input for the FX taskforce … it needs further discussion … but things towards the top of the prioritisation list are probably more useful than those towards the bottom <patrickdengler_> I am <patrickdengler_> Is it time for my topic :) CM: I wonder if Patrick has any views on the set of features Brian has identified … and whether all or some should be brought across to CSS <patrickdengler_> I am by far no expert in animation. … it's probably not something we can decide right now though … but would like to hear his views <patrickdengler_> I love the idea of enhancing animations, but not to the extent where it overloads the syntax such that is unusable (opinion) CC: I want to know if there's any impact on our SVG2 requrirements decisions <patrickdengler_> Any impact of the proposal? no <scribe> ACTION: Brian to prepare before and after examples of using time containers in SVG animation [recorded in] <trackbot> Created ACTION-3202 - Prepare before and after examples of using time containers in SVG animation [on Brian Birtles - due 2012-01-19]. <patrickdengler_> Woot! <patrickdengler_> I just want to see if we can get a resolution on the proposal I sent out <patrickdengler_> It's very basic and orthogonal to all of these other discussions. patrickdengler_, got a link? is it this? <patrickdengler_> It is one of the three options we discussed for moving CSS animations on top of a select few, targetted attributes <vhardy> patrickdengler_, as there were a few options, can you briefly summarise which one this was? i.e. what set of attributes it targets and how it does it? <patrickdengler_> The last few open issues that I knew of were semantic and type collision resolutoin wasn't acceptable and I agreed <patrickdengler_> THe set of attributes are in the link above <patrickdengler_> Only 4 had collisions. <patrickdengler_> azimuth and elevation, which were both parts of a CSS Aurul specification, that ChrisL said we could deprecate in that specificaion (correct?) <patrickdengler_> transform, which dean has started a nice proposal through implementation, and which has other implicatoins outside of the scope of this proposal patrickdengler_, I'm having trouble refreshing my memory -- was this the proposal to upgrade attributes to properties, with the same names as the svg attributes? <patrickdengler_> Yes. CL: I object to upgrading attributes to properties … I think instead we should "treat" these attributes as if they were properties … for the sake of CSS animation … that's a big difference … if we make randomly every single attribtue in SVG (practically) it means they apply to all elements … and things like x and y which don't make sense on most of them, it's a bad idea, leads to a lot of bloat <patrickdengler_> wait … whereas the same proposal, but with a slight wording change … taking a mechanism that was originally designed to work only with properties, and let it treat SVG attributes as if they were properites for the sake of animation <patrickdengler_> this is not right <patrickdengler_> Does font-size apply to circle? <patrickdengler_> we have properties that don't apply to elements. DJ: so you wouldn't be able to style these attributes with CSS unless you were animating <patrickdengler_> What does property bloat mean? If you are thinking implementation that argument doesn't apply. … and you wouldn't be able to use Transitions on them <ChrisL> would mean that the attributes are *treated as* properties for the sake of CSS animation <ChrisL> no real impact on the proposal itself, just a change in terminology VH: I understand Chris' point, but I htink from an authoring point it would be confusing to target them from animations but not be able to put them in a normal style rule … if you can put x in one place but not in others <patrickdengler_> They have to be properties … that would be confusing CL: so yes it has differences on these other side effects … not transitioning is a negative side affect, I agree DJ: I think transitioning is important … transitioning a circle radius would be very useful <patrickdengler_> Transitioning is key and part of the proposal CL: the CSS WG would not be amenable to adding many properties <patrickdengler_> You cannot separate them. The proposal is to make them properties. VH: this needs to be taken to the FX, yes? … can we bring it to the TF, if we all kind of like the idea, but there are concerns about adding that many properties, and ask for their input? <patrickdengler_> This has been taken to the FX group; I have shared it on those threads. Everyone has given feedback and agreed (including ChrisL). What other magic do I need to do? … we can bring up Chris' issue in a real FX setting CL: I just think this had a lot of downsides and there's another way to do it … we need to weight up the pros and cons of this approach CL: no, I didn't say I agreed to the whole thing, just the specific point that was asked about … I'm not objecting here … I'm just saying we should consider another way forward VH: to answer patrick, for a decision we need to make that in an FX setting … not that it hasn't already been brought up there CM: I think we should get our SVG's view of it … to make half of that decision <patrickdengler_> I dropped off hang on. <vhardy> VH: I agree <patrickdengler_> I cannot get back on the line. <patrickdengler_> I am totally lost on process here. <patrickdengler_> The FX group has already sent all of the feedback; the FX group is all present here correct? patrickdengler_, no I don't think all of the FX group is here VH: david baron isn't here <patrickdengler_> Can you set up another conf? <patrickdengler_> # … I think he will still have issues with this <TabAtkins> It is slightly troubling from a CSS perspective to add a bunch of properties that apply to only a single/few elements each. Most CSS properties are relatively widely applicable. … Tab also patrickdengler_, yes PD: this discussion has been going on for over a year … hundreds of emails … at every meeting I've written up proposals, presentations CL: I didn't say it was no good … I said the vast majority was fine, just concerned about the side effects of it … I proposed something that mitigated those side effects … I just want to talk about that PD: we discussed property growth last year, and we've addressed that … we definitely need transitions to work CM: I don't get the sense that anybody wants CSS animations not to work on SVG attributes <TabAtkins> I'm pretty happy with the actual property set we've done so far. <ed> TabAtkins: what property set do you mean? the one that's in CSS transitions? <TabAtkins> I mean the one that was proposed by Patrick. It's only a handful of properties. Once the few collisions are handled better, which has gotten good suggestions, I'm pretty happy. [discussion of process on how to move forward] DJ: patrick has done a lot of work, getting private and public feedback VH: there are two things, one appreciates all the work you have done … the point about making the decision in the FX setting, if we make a resolution today it's just a technicality … a final recorded decision needs to happen in the FX group CM: we should go through each of these proposed resolutions CC: I feel like if we agree to this proposal, or even say Brian's proposal, it's the end for SVG markup for animation … that's how I feel … people will use CSS Animations to target animations … it's like we're deprecating SVG animation elements DJ: not really, we're giving people a better way to animate content in some cases … I think you're implying that because we're going in this direction, it's deprecating SMIL … I don't think that's the case BB: just extending the reach of CSS animations doesn't jeopardise the usefulness of SMIL CC: we'll just end up with two tools for the same thing DJ: we should have discussed this a year ago … we've been discussing how to do this, not whether it should be done … in general, most people want to be able to do CSS transitions and possibly animations on SVG content BB: and you already can for style properties DJ: yes, and we have a specially worded spec so you can do it for transforms now … but even with that, there's a bunch of graphical parts of SVG that's not exposed <TabAtkins> I think we shouldn't worry about hurting SMIL's feelings. VH: for the sake of progress, we have 20mins here, and we have multiple issues, I propose if somebody has an issue with one of these resolutions we do that now … and if not, we assume it's ok [mention issue #1] CL: I agree with that resolution, we should keep the existing names VH: for width, you could have a width property that applies to <rect> and to <div> CL: that's a separate problem … width/height in SVG are not the same as those in CSS … they mean different things … that's the reason why SMIL had attributeType DJ: I don't think there's much chance someone would write a stylesheet that sets width on <rect> and root <svg> CM: it doesn't inherit <patrickdengler_> (I can no longer hear on the phone) issue #2 CM: we have already resolved to fix this for SVG2 … so this issue isn't a problem CL: yes, we've already decided to unify the syntax between presentation attribetus and properties issue #3 [discussing style vs content briefly] CL: if implementors think promoting to properties is not a problem, then it's fine … I don't have a problem with promoting to properties if implementors are happy with it CC: when I implemented SVG, there is already a burden with style resolution and propagating values down the tree … it's not a big burden … I'm just wondering how much worse this will make it ED: I am wondering too, we'll just have to implement and see CL: I'm guessing most implementors do this with a big table with all the values ... these will most (all?) be non-inherited properties <patrickdengler_> non-nherited … in terms of propagation through the tree, the scope of impact is limited CC: unless you set "inherit" CL: yes you can always put "inherit" CC: so all these properties would allow "inherit" CM: and "initial" … but I don't think that's a problem DJ: we converted transform to a property … and that property already existed <patrickdengler_> tada :) … so we can't use that as an indication for how much impact there is … the webkit prefixed transform property applies to SVG elements <cyril> how many properties are we talking about? CM: so there's 47 properties in the proposal table CL: oh so no it's not all animatable attributes? CC: no, just a limited set ok so there's no implementors in here saying they definitely have a problem with promotion, in terms of performance impact we can move on issue #4 <patrickdengler_> You just answered #4 I think well we need to be happy with that particular set patrickdengler_, what is the actual set there, as a summary? <patrickdengler_> The summary is in the proposal <patrickdengler_> It is scenario driven VH: it's a good set of properties <ed> I would like to see the excluded property set <patrickdengler_> It is based upon the use cases I presented. <patrickdengler_> I can produce that, but not tonight. CM: I don't think the particular set matters right now <patrickdengler_> I am not against promoting others, I was just trying to restrict based upon use case and to avoid collsions CL: I think CSS people will complain about overgeneric names like z, but we already have overgeneric names like "color" <ed> patrickdengler_: that's fine, but I think it would be good to include that set too, for completeness CM: so I'm happy that patrick has come up with a reasonable set of properties here issue #5 CC: what if I put 'x' on a <g>, and then I have a <text> underneath it … what's the rule? <patrickdengler_> X doesn't apply to g does it? sorry I meant to type <svg> CM: I would prefer not using different names in case of conflicts … just define what happens if you have <rect style="x: 10px 20px"> … that's better than coming up with different names, which is something new for authors to learn patrickdengler_, I'm having trouble reading your proposed resolution here, what is it? <patrickdengler_> For this case, it is just as was suggested. Define what happens if you have <rect style= <patrickdengler_> "x:10px 20px"; that should be a css rule already no? <patrickdengler_> (i.e. what if I put left:20px 40px <ChrisL> patrick, whose comment is the capitals, red text in your document no because you need to have the single x property defintion take the union of all possible values <patrickdengler_> I think the comments in red (if you are looking at my last sent one) are Dean's so anyway, I think we don't get this for free from CSS, but we just need explicit wording to say what happens when you do <rect style="x: 10px 20px">, which is fine <patrickdengler_> I don't konw what you mean by having a single x property take the union of all possible values. Sorry, not an expert, just trying to solve a problem :) CL: I think that's the right approach patrickdengler_, I don't think you can have two separate property definitions for when they apply on different elements patrickdengler_, because properties are universal patrickdengler_, but I think it's not a problem, and everyone here agrees issue #6 CL: so this is only in the case of conflict with existing properties? CM: in practice the only problem with font-size and the font shorthand? CL: yes <patrickdengler_> azimuth and elevation as well but CL and I dicussed that one (if he can elaborate) CM: so what about width and height? we allow unitless values there? patrickdengler_, would we allow <rect style="x: 10">? <patrickdengler_> I think this problem already exists (?) in SVG, and unless there is a unit type, it isn't valid patrickdengler_, I'm not sure from reading the proposed resolution <patrickdengler_> I wouldn't change CSS here; I would force SVG for lengths to require unit types. patrickdengler_, right that is currently the case patrickdengler_, but not in presentation attributes? <patrickdengler_> (but not for floats) <patrickdengler_> (unless css introduces this) VH: I think it might be confusing for authors not to allow unitless values for these promoted attributes <patrickdengler_> I think they'll figure it out CM: this confusion already exists though ... so I don't think it matters for acceptance of this proposal everyone here happy issue #7 <patrickdengler_> Issue #7 I resolved slightly differently, and it now falls into issue #5 category I think I don't think this is right <patrickdengler_> (it should be at the top) yes, so because of issue #5 we have a single universal property definition in that example you quote, the second rule will always win and then we just define how it behaves if applied to an element that only really wants a single value patrickdengler_, that make sense? <patrickdengler_> Yes issue #8 we are ok with the particular set RESOLUTION: The SVG WG is happy with Patrick's property promotion proposal for targetting SVG attributes with CSS animation <patrickdengler_> I LVE YOU ALL CM: we should mail the fx list to say that the SVG WG is happy with the proposal <patrickdengler_> That would be great!!!! … schedule an FX call in a couple of weeks (since some of us a travelling) … so that we can get their agreement too … hopefully that mail about our acceptance of the proposal stimulates concerns to be brought forward from the CSS folks patrickdengler_, we might break for lunch now then <scribe> ACTION: Erik to mail FX list with our acceptance of property proposal and to schedule a call [recorded in] <trackbot> Created ACTION-3203 - Mail FX list with our acceptance of property proposal and to schedule a call [on Erik Dahlström - due 2012-01-19]. -- break for lunch, 1hr -- <shans> ChrisL: <cyril> scribe: Cyril <scribe> ScribeNick: cyril <dino> DJ: the idea is that when you're doing a lot of txf maths in matrix, the overhead of writing your own matrix class ... is annoying ... 1) because of the performance ... 2) because the API is immutable you create a lot of objects that you'll throw away ... 3) converting to and from a CSS transform because you go through the string API ... this is a proposal for a 4x4 matrix API ... I removed skew ... i hate skew and there are other ways to do skew ... there are 4 constructors ... Float32Array close to the WebGL ... it's defined in the type array spec ... it could become a JavaScript type CM: in WebIDL you can't override if you've got 2 types and they are both array or sequences DJ: but that's not a problem CL: how do you do perspective ? you have to go to 3d (4x4) DJ: yes ... there should be a perspective function ... for rotation, scale and rotation functions, there is a mutable and immutable version CM: since it's multiplied by it should be inverse of DJ: rotate, rotateAxisAngle VH: shouldn't we have the angle value before the x,y,z value DJ: I'm not sure SVG takes degres BB: should there be an immutable version of leftMultiply DJ: because it's immutable and returning a new matrix, you can do it CL: I think it's worth adding a comment on that DJ: typically people won't use the immutable versions VH: there is no center in the rotations DJ: right, we should have that ... same for scale from origin ... then there are 3 conversion functions ... getting the float32array <heycam> dino, you should write "stringifier;" rather than "DOMString toString();" DJ: David and Robert made this comment, they want to add units ... because if you've zoomed the page, ... you don't know the units <dino> feedback from Simon Fraser: It's problematic to pretend that you can convert matrix() from getComputedStyle into a 4x4 unitless matrix, because you don't have any context that tells you how big a pixel is. This means that it breaks down if full-page zoom has been applied. CM: is the issue that in the actual property you can't put units ? DJ: this API is just about matrices but the problem is when you try to mix it with CSS TRansforms <ed> just a note, the SVGTiny12 uDOM has an SVGMatrix interface that has methods that mutate the object <ed> CM: an example is if you have scale(2px)scale(3em) and exposing that as a matrix with unitless values ... then it's going to work if you put that back to the same element because of the em computation VH: what's our goal here? ... are we collecting feedback ... or solving the issues DJ: I'm taking notes and will produce another version VH: maybe we should have a way to set the txf center instead of adding a parameter CC: but then it becomes stateful DJ: and it becomes a transformation class instead of matrix CM: is it going to be exposed when you get the transform property? DJ: this could be substituted to CSS Matrix or SVG Matrix ... it wouldnt be returned by the transform property but accepted by the setter and the same for other SVG properties ... people have requested a way to decompose it VH: does it return an array of matrix DJ: we'll have to define another class ... so that's why I left it out for the moment, like lookAt that needs a point/vector class ... lookAt is a different way to do rotation without angles CM: can you use the CSS animation to do that camera rotation? DJ: yes ... you would have to decompose into rotation yourself ... for an object rotating around another, it'll be possible but for translation at fixed velocity, it would be hard VH: you could nest it <shepazu> (how else can you do skew x/y? they aren't great, but the best way I know to make pseudo-3D shapes in SVG...) DJ: I've removed skew and I hope people are happy CL: the way to do skew is to go 3D RC: but people like pseudo 3d DJ: the only good use of skew is asymmetric diagrams s/asymmetric/isometric/ VH: I don't have a good feeling about removing skew CC: it's possible with the matrix coefficient DJ: yes, I'm not giving the shorthand for that <heycam> shepazu, this is just the Matrix API -- you can still put skew as a transform item in the transform property VH: have you looked at the apis that provide skew or not ? <heycam> shepazu, (and of course it's always possible to set the components yourself; mind you I have no opinion on not having them) VH: if it's popular, I would keep it CL: no problem to changing to degrees? DJ: no VH: what is ortho? ... projection that is not perspective ... in GL you give the frustrum (near, far) ... in general, for GL use, people will port GL code and reuse it s/frustrum/frustum/ scribe: in CSS we do have a perspective which is one coefficient in the matrix ... that's different from what most people do in GL RC: maybe we should build a graph of operations, under the hood DJ: that's interesting ... anyway, we're starting to implement that in WebKit BB: where would that be used ? DJ: WebGL code ... they get hit by 2 things: matrix and garbage collection BB: what's the relation with SVG? DJ: it's more an FX item ... but maybe some SVG people would benefit from that (D3 ?) BB: SVG is 2d, what's the benefit of having a 3d DJ: maybe none, maybe there would be an overhead ... the biggest benefit is the mutability ED: SVGT1.2 has it already <ed> CM: is it part of the idea to move SVG and CSS matrix together DJ: it's not designed as a replacement ... in a perfect world, there should be a single matrix class ... but both are already quite different <krit> dino: which matrices differ, and how? SVGMatrix and CSSMatrix? <dino> krit: yes. <krit> dino: SVGMatrix has more functions, but I don't see where they would differ beside that <krit> dino: the additional functions don't influence the current matrix <dino> krit: i was just saying that they are different now. they have different api <krit> dino: I would rather like to make them more common <dino> krit: that's exactly what we're trying to do <krit> dino: SVGMatrix could inherit from CSSMatrix <krit> dino: ok, "... but both are already quite different" sounded like you want to sperate them more <krit> dino: so just a misunderstanding CM: this matrix class you would use it in all place where CSSMatrix is accepted DJ: not at the moment, it's more a standalone API at the moment CM: what's your view on other standalone classes (point...) DJ: it would be great if it would exist (dot product, cross product ...) CM: I'd like to see more general APIs DJ: but it's poluting the JavaScript namespace in browsers ... who are we to put things in the global namespace in Javascript ... <krit> soecification writer? DJ: that's why I called it Matrix4x4 instead of "Matrix" <dino> sure - i was just suggesting that we should be careful to add things into the global namespace <dino> without asking them <dino> krit, yes. I support merging SVGMatrix and CSSMatrix. I dont think Matrix4x4 is the right place to do that (maybe it is) <cabanier> email: <shepazu> we could talk to TC39 about adding Matrix to JS space… there are some who want to see tighter integration of JS with the Web usage and DOM (e.g. Alex Russel) <krit> dino: if you plan a common Matrix API, why not? RC: here are the mail of last months ... I'd like to split the spec into 2 <dino> krit, i was simply worried that it would become a monster of 3 apis :) RC: people agree that there will be 2 keywords ... 2 properties: alpha-comp and blending <krit> dino: I support your proposal <heycam> ScribeNick: heycam RC: blending does not do compositing, it takes the source image, calculates the background, then produces a new image … which is then composited on to the background … you don't composite first then blend CC: but the blending only applies to the regions where there are two inputs to work on DJ: no RC: the compositor figures it out for you … blending calculates an image CC: based on two values, right? DJ: based on the background and foreground … and they only exist in the area the compositing operations has a result DJ: the background always has a value CL: it might be transparent black, but it always has a value VH: are you thinking of examples like clear? RC: the background is calculated by taking all the … CC: if you take what's in the spec now, it uses four parameters <ChrisL> thread at RC: part of splitting up means that the compositing function and blending function are separate CC: what we said on the list was that there's no split of the model, the model only has one equation … the two properties control different aspects of it … the alpha-comp controls compositing modes … the blending property controls the F function RC: it's the other way around CC: let's work offline on this <ChrisL> Cyril: According to the current draft: src-in is f(Sc,Dc)=Sc and X=1 and Y=Z=0. Multiply is f(Sc,Dc)=Sc x Dc and X=Y=Z=1. So you are saying that when you use both the compositing and the blending modes, you keep the value of f(Sc,Dc) from the blending and you keep the X, Y, Z values from the compositing mode. RC: this splitting helps remove a lot of duplication <ChrisL> quote fromalex: "By separating out the blending from the P-D you get more <ChrisL> combinatorial possibilities that you couldn't do nicely if it <ChrisL> was one property." … in the spec it says a <g> introduces a new stacking context, but nobody does that RC: another one was simplifying porter duff by removing clip-to-self … we'll also add the missing blend modes from PDF/illustrator … there was discussion on whether to have knock out or not … we should clarify its purpose in the spec [rik draws to explain knock out] DJ: so it's almost like group opacity in some wys s/wys/ways/ RC: it's the opposite of "isolate" DJ: it's like doing a clear of the shape in the group with knockout, before the blending operation happens for the child, so that the child only blends with the group's background ... for porter duff, how useful are they other than clear, srcover? CC: some designers use src-in, dst-in VH: I think originally porter duff was done for video, matting BB: I think also for tiling of images using atop to avoid seams is useful VH: I think from an implementation perspective, if you do one you may as well do all of them RC: I'm not completely convinced that porter duff should be in the spec, it feels a bit like a filter … it's already in the filters spec … in a way it makes more sense there DJ: but it doesn't allow you to clear an object, the way it exists in filters … the result of a filter is always src-over composited … if you want to knock out a background you can't do it RC: background doesn't really work with porter duff anyway … when you do compositing you don't look at the background DJ: what is this compositing with? RC: there are two images DJ: in SVG, you would say <circle id="a'/><circle id="b" comp- [vincent does some drawing on the board, and rik mentions that he proposed to remove clip-to-self property, and have clip-to-self be the default (only) behaviour] DJ: my next question, we don't do the missing blend modes … we don't have hue, saturation, colour blend RC: those ones only work on rgb, not cmyk … maybe that's why apple doesn't have them DJ: we are creating a new stacking context when you use a blend? RC: yes CL: on the mailing list, alex suggested a different name for comp-op … eventually he said what about "shape-mode" or "blend-mode" VH: we agreed in seattle to do a CSS Compositing spec, generic and not just SVG … I understand enable-background:new being the default for SVG, but it's less clear in CSS RC: any time you have a non src-over comp-op, you imply enable-background:new … that's new DJ: that's confusing <scribe> ACTION: Rik to write a small example explaining alpha comp and blending [recorded in] <trackbot> Created ACTION-3204 - Write a small example explaining alpha comp and blending [on Rik Cabanier - due 2012-01-19]. ACTION-3204: explaining also how knock out and enable-background work with them <trackbot> ACTION-3204 Write a small example explaining alpha comp and blending notes added DJ: my main comment is, can we please have this in a spec? … I don't mind if people disagree with it, but currently you have to read one spec and 20 emails RC: ok … we might also reword the alpha compositing section of the SVG spec … wrt enable-background … I think the Filters spec is a lot more readable than what's in the SVG spec DJ: I think the spec needs to have more description for every property CC: I don't think I agree with the removal of clip-to-self BB: I have a proposal in light of the features we discussed this morning … that proposal is to make an element syntax that tracks CSS animations … in many ways … in terms of properties and behavior, matching names … but also borrows from SVG animation as well … it's a more fully featured CSS animations, in that it offers things with hierarchical semantics <ed> … compatct syntax, motion on a path, simple DO manipulation … I've called it Web Animations … I'd hope we could end up with one spec with two syntaxes … but the CSS syntax would probably be less fully featured … as Patrick mentioned, we don't want to overload the syntax to the point that it's a pain to use … from that core set of functionality, we only include the core stuff in CSS and the more complicated/sophisticated would only be available in the element syntax … the precedent for this arrangement is filter effects CL: I think that's a reasonable approach … the CSS guy are very concerned about simple use cases, authoring … they seem quite keen that if it gets too complex you go to something else (like element syntax) … I think that's a reasonable split BB: I think the other thing it offers is the ability to divide between semantics and styling … you can use CSS syntax for a presentational flourish … but for content you could use element syntax … what I'm proposing is the one model, moving easily between the two sytnaxes VH: I like the one model approach … one question I have is that in my expereince we have well known problems in animation … there's a timing model, animation value, the syntax is almost orthogonal from those … SMIL covers a lot of that … the animation engine really is going to say "here are properties that are animated, the from/to values, keySplines, iterations, etc." … could we agree to say that the precendent to follow is to reuse as much as possible the SMIL model? … but choose the best syntax for that? I'm sure SMIL is not perfect s/I/... I/ … I'm afraid of going down the path of reinventing SMIL … I'd much rather do the easy way of using the SMIL model … I'm asking that for any aspects of the model we need, we take it from SMIL BB: I'm proposing something that learns from SMIL but is not bound by it … one of the big questions is to have something new that breaks compat … that's what I'm suggesting CL: I agree we shouldn't go off an reinvent the whole animation model, the stuff which has been proven to work we should reuse BB: I'm talking about breaking compat with SVG 1.1 … introducing a new element that contains the simplified behaviour, more aligned with CSS … not building on <animate> CL: I'm less concerned about syntax than the underlying model BB: there are some things like how rounding is done differently … it's not easy to say in SVG2 rounding is done differently … that's why I'd prefer a new element CC: you'd throw away your animation engine in firefox? BB: no … in the future perhaps deprecation would allow removal of the old elements BB: I want to see if there's any agreement on that concept of defining a Web Animations spec -- adjourned -- -- discuss more about this tomorrow -- DJ: I'd like to see javascript apis too This is scribe.perl Revision: 1.136 of Date: 2011/05/12 12:01:43 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/more/ more, specifically in authoring tools/ Succeeded: s/ doesn't exist/ is more nuanced than is often presented/ Succeeded: s/CSS/SVG/ Succeeded: s/ndoes/nodes/ Succeeded: s/many/many hundreds of/ FAILED: s/asymmetric/isometric/ FAILED: s/frustrum/frustum/ FAILED: s/wys/ways/ FAILED: s/I/... I/ WARNING: No scribe lines found matching ScribeNick pattern: <Cyril> ... Found ScribeNick: vhardy Found ScribeNick: heycam Found Scribe: Cyril Inferring ScribeNick: cyril Found ScribeNick: cyril Found ScribeNick: heycam ScribeNicks: vhardy, heycam, cyril WARNING: Replacing list of attendees. Old list: +1.206.734.aaaa New list: +1.425.868.aaaa SVG_WG Patrick +1.650.253.aabb TabAtkins WARNING: Replacing list of attendees. Old list: +1.425.868.aaaa SVG_WG Patrick +1.650.253.aabb TabAtkins New list: Doug_Schepers Oliver_Goldman Patrick [IPcaller] WARNING: Replacing list of attendees. Old list: Doug_Schepers Oliver_Goldman Patrick [IPcaller] New list: [IPcaller] Patrick Default Present: [IPcaller], Patrick Present: [IPcaller] Patrick WARNING: Fewer than 3 people found for Present list! Got date from IRC log name: 11 Jan 2012 Guessing minutes URL: People with action items: brian erik rik[End of scribe.perl diagnostic output]
http://www.w3.org/2012/01/11-svg-minutes.html
CC-MAIN-2018-26
refinedweb
10,873
52.63
I am using the Google SDK for SignIn in my ios 9 app. It successfully works and runs locally on my phone. and through clicking "Run" in xCode with my phone as the target. Here is my PodFile: use_frameworks! target "myApp" do pod 'Google/SignIn' pod 'Firebase' end import Google .swift use_frameworks! .xcworkspace xcodebuild test -workspace myApp.xcworkspace -scheme myApp -destination 'platform=iOS Simulator,name=iPhone 6s,OS=9.3' | xcpretty -s AppDelegate.swift:17:56: use of undeclared type 'GIDSignInDelegate' xcodebuild test If you want to use the Google Sign In SDK on it's own without any other google services then I would recommend the following approach: In your Podfile, declare the Sign In library directly like so use_frameworks! target "myApp" do pod 'GoogleSignIn', '4.0.0' end Note: I'm specifying an explicit version number here because as of Cocoapods 1.0, the pod spec repo is no longer updated on every pod install call. Module support wasn't introduced in the Google Sign In SDK until the latest version (4.0.0) on 18th May 2016 so if you haven't run pod repo update since then from the code example in your question you would actually be installing an older version of the SDK that doesn't support what you are trying to do. If you receive an error when trying to run pod install with the above Podfile then running pod repo update should fix your issues. In your .swift files where you use the SDK, import the library like so: import GoogleSignIn
https://codedump.io/share/jZxDcwlYTXY6/1/cocoapods-not-loading-google-sdk-on-xcodebuild
CC-MAIN-2017-04
refinedweb
259
73.27
Computer Science Archive: Questions from July 25, 2008 - Anonymous askedthat returns the value of the largestelement in an arr... Show more Question Create a functioncalled amax() that returns the value of the largestelement in an array. The arguments to the function should be theaddress of the array and its size. Make this function into atemplate so it will work with an array of any numerical type. Writea main() program that applies this function to arraysof various types What to submit You are simply required to submit a source file(“.cpp”) that includes the implementation of the abovementioned program.• Show less2 answers - Anonymous askedWhy and wherewe use integer programming? How many methods we use in Integerprogramming and which on... Show more“Why and wherewe use integer programming? How many methods we use in Integerprogramming and which one the best approximate the solution anddescribe the limitation of each”• Show lessNOTE: PLEASE COMMENTS ONABOVE TPOIC1 answer - Anonymous askedA variable partition memory system has at somepoint in time in the following hole sizes in... Show more Question A variable partition memory system has at somepoint in time in the following hole sizes in the givenorder. A new process is to beloaded of size 25k. Which whole size would be filled usingbest-fit, first-fit and worst-fit respectively.• Show less1 answer - Anonymous askedFor login to VULMS youneed your username (ID) and password. Write a simple program in PHPfor user a... Show more 1 answer - For login to VULMS youneed your username (ID) and password. Write a simple program in PHPfor user authentication on a web site. If you are not registeredplease mention the alternative path for registration (throughcoding). Please show the role of MYSQL data base in thisexample/program. - Anonymous asked2. P... Show more There are two generalcomments about pointers 1. Pointers increase the efficiency of ourprograms 2. Pointers degrade reliability of C++ programs dueto security issues Give your views onthese comments and justify your answer, whether you agreeor• Show less disagree with above comments.3 answers - Anonymous askedConsider a CPUwith a TLB that caches 512 page table entries. A mapped mem... Show moreCan someone pleasehelp me?Consider a CPUwith a TLB that caches 512 page table entries. A mapped memoryaccess (during a TLB hit) takes 1200 ps. One access to main memorytakes 1000 ps. What are the TLB access time and the TLB hit ratesuch that the effective memory-access time is 1250 ps?• Show less1 answer - Anonymous asked2) Pointers degrade r... Show moreplease comment on this1)Pointers increase the efficiency of our programme.2) Pointers degrade reliability of C++ program due to securityissues• Show less1 answer - Anonymous asked1 answer - Anonymous asked= {a b c}and L be the language of all words in which all the... Show more Question:: Let the input alphabet be S = {a b c}and L be the language of all words in which all the a’s comebefore the b’s and there are the same number of a’s asb’s and arbitrarily many c’s that can be in front,behind, or among the a’s and b’s. Some words in L areabc,2 answers - Styler askedFor login to VULMS (universityweb page for students login) you need your username (ID) andpassword. ... More »2 answers - Styler askedWrite complete setup andinstallation (step by step) of PHP with apache truncate server, andits confi... More »2 answers - Styler asked0 answers - Anonymous asked There are two general comments aboutpointers 1. Pointers increase the efficiency of ourprograms... Show more There are two general comments aboutpointers 1. Pointers increase the efficiency of ourprograms 2. Pointers degrade reliability of C++ programs due tosecurity• Show less issues s on these comments and justify youranswer,2 answers - Anonymous askedi have installed asp web developer.express edition..plz tell me howto make a login page and other .a... Show morei have installed asp web developer.express edition..plz tell me howto make a login page and other .aspx page where login informationstored (code behind,.aspx code)with screen shots.. Is there any need of databse creation for store logininformation or it automaticall y stored.. • Show less0 answers - Anonymous askedi use asp.net express edition plz make a project in asp.net withscreen shots and coding ,use of stor... Show morei use asp.net express edition plz make a project in asp.net withscreen shots and coding ,use of stored procedure... • Show less0 answers - Anonymous asked1. Pointers increase the efficiency of ourprograms 2. Pointers degrade reliability of C++ programs d2 answers - Anonymous askedThis program is suppose... Show more Project Title: Daewoo (a Bus service)Reservation System Project Description: This program is supposed to simulate a Reservation System ofDaewoo. Using this program, Daewoo ticket reservation agencyassistant can perform different tasks related to ticketreservation. The Daewoo Reservation System will ask the user for thefollowing information : - Name of passenger - Departure City - Destination City - Date of travel - Time of travel - Number of tickets The Daewoo Reservation System should have the followingfeatures: - Make Reservation-to reserve ticket/tickets for a passenger andindicate his/her seat number. - Modify reservation-to modify the already made reservation - Cancel reservation-to cancel a particular reservation - Search reservation- to search reservation information of aparticular passenger by a) Passenger name b) Date of travel - Exit –to exit from application Daewoo Reservation System should also support persistencefor passenger ticket reservation records Supporting simple persistence by any application requireshandling of two scenarios 1 answer - On start up of application-data (passenger ticketreservation records) must be read fromfile. - On end/finish up of application -data (passengerticket reservation records) must be saved infile. - Styler askedForlogin to VULMS (university web page for students login) youneed your username (ID) and password.... Show moreForlogin to VULMS (university web page for students login) youneed your username (ID) and password. Write a simple program in PHPfor user authentication on a web site. If you are not registeredplease mention the alternative path for registration (throughcoding). Please show the role of MYSQL data base in thisexample/program. • Show less1 answer - Anonymous askedYour 3D robot character should haveall of th... Show moreProjectComputer Graphics Features of the Robotcharacter Your 3D robot character should haveall of the following features and body parts: - Torso: Should have at least two parts torso. Upper torso andlower torso. - Left and Right leg: Each leg should have at least two parts,upper leg (above knee) and lower leg. - Left and Right Arm: Each arm should have at least two parts,upper (above elbow) and lower arm - Left and Right Feet - Left and Right Hand - Neck - Head To make your Robot character look good, you shouldinclude the following features for your Robotcharacter: - Each body part should have its own OpenGL lighting materialproperty. - Each body part should have its own texture. Features of the program Your program must contain all of the followingfeatures: 1. The scene should also include a floor and a visualized 3Dcoordinate system.2. You should be able to use the mouse to change the viewangle.What to Submit 0 answers - Put your solution in one or more Dev C++ source files. The mainfile (which includes function main {}) should be namedproject.cpp. - Upload all source files in a zip file format. - Please also include a description file, called“descriptions.doc” that describes how to use yourprogram. - Anonymous askedSuppose the memory access time (Tmem) is 200 nsec ,the acesstime for Translation Looka... Show moreQuestion # 1 :Suppose the memory access time (Tmem) is 200 nsec ,the acesstime for Translation Lookaside Buffer (TTLB) is 30 nsec and the hitratio (HR) is 90%.Calculate the effective access time(Teffective)• Show less1 answer - Anonymous asked1 answer - Anonymous askedAnessential question about compiler construction: having a programand set of non parametric compile... Show more“Anessential question about compiler construction: having a programand set of non parametric compiler optimization modules (calledalso phases), is it possible to find a sequence of these phasessuch that the performance (execution time for instance) of thefinal generated program is "optimal"?• Show less0 answers - fahad56 asked2 answers - applyed askedimport javax.servlet.... Show morex.øi5my java code mport java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; public class GetParameter extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String id = request.getParameter("id"); String firstName = request.getParameter("firstname"); String middleName = request.getParameter("middlename"); String lastName = request.getParameter("lastname"); try{ File file1 = new File("C://TempEI4//myfile.txt" ); FileWriter fstream = new FileWriter(file1,true); BufferedWriter bufferWriter = new BufferedWriter(fstream); boolean exists = file1.exists(); if (!exists) { System.out.println("the file does not exist : " + exists); file1.createNewFile(); }else{ System.out.println("the file exist : " + exists); } bufferWriter.append(id); bufferWriter.append(firstName); bufferWriter.append(middleName); bufferWriter.append(lastName); bufferWriter.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } try{ FileInputStream inputStream = new FileInputStream("C://TempEI4//myfile.txt"); DataInputStream in = new DataInputStream(inputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine); } in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } System.out.println("id:" + "firstname: " + "middlename" + "lastname"); out.println("<b><font color='blue'>Your Id is :</font></b>" + "<b>" + id + "</b>" + "<br>"); out.println("<b><font color='blue'>Your FirstName is : </font></b>" + "<b>"+ firstName +"</b>" + "<br>"); out.println("<b><font color='blue'>Your Middle Name is : </font></b>" + "<b>"+ middleName +"</b>" + "<br>"); out.println("<b><font color='blue'>Your Last Name is : </font></b>" + "<b>"+ lastName +"</b>"); } } this is my jsp code <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %> <b><font color="blue">Please Enter your Id,First Name, Last Name and Middle Name:</font></b><br><br> <form name="frm" method="post" action="../GetParameter"> <table border = "0"> <tr align="left" valign="top"> <td>Id</td> <td><input type="text" name="id"> <tr align="left" valign="top"> <td>First Name:</td> <td><input type="text" name ="firstname" /></td> </tr> <tr align="left" valign="top"> <td>Middle Name:</td> <td><input type="text" name ="middlename" /></td> </tr> <tr align="left" valign="top"> <td>Last Name:</td> <td><input type="text" name ="lastname" /></td> </tr> <tr align="left" valign="top"> <td></td> <td><input type="submit" name="submit"/</td> <td><input type = "button" name="showall" value="showall"/></td> <td><input type="submit" name="save" value = "save" /></td> <td><input type="reset" name = "clear" value = "clear"/></td> &nbsõbpx.øi5bsp; <ø&tx.øi5 </table> </form> i want that show all my table value in table form write a code in java • Show less1 answer - Anonymous asked; subroutine to... Show moreQ/explain the purpose and working of eachinstruction written in the following lines ; subroutine to run as first thread mytask: push bp mov bp, sp sub sp, 2 ; thread local variable push ax push bx xor ax, ax ; use line number 0 mov bx, 70 ; use column number 70 mov word [bp-2], 0 ; initialize local variable• Show less1 answer - fahad56 askedYour answer sho... Show moreDiscuss only two ways in which the approach of Fiber Channeland ATM LANs are similarYour answer should contain important points.• Show less3 answers - Anonymous asked2 answers - Anonymous askedTemplate is as un... Show more Create Form in MS-Access.Two table are You have to merge two tables in one form. Template is as under. Where . Attribute Table Department ID, Course NO & CourseName Course Student ID &GPA Enroll Criteria (Operations on Form, [Step byStep]): ?? First you select Department ID, populated listor combo box ?? Select Course ID from combo box or list againthat corresponds to particular Department ?? Course Name isdisplayed automatically as we select Course ID fromList ?? Then all students alongwith their GPAs that registered / Enroll in this courseis displayed in Sub form or lower part offormPlease solve it• Show less1 answer - Anonymous asked1 answer - Anonymous askeds come befo... Show more Let theinput alphabet be S= {a b c} and L be the language of all words in which all thea’s come before the b’s and there are the same numberof a’s as b’s and arbitrarily many c’s that canbe in front, behind, or among the a’s and b’s. Somewords in L are abc,1 answer - Anonymous askedQui... Show more Q.Multiple answers are given below against eachquestion pls.select the best suitable answers.a) Quick sort has a good average run time and a poorworst-case run time. o True o False b)Dynamic programming uses a top-down approach. o True o False c)What is the solution to the recurrenceT(n)=T(n/2)+n,T(1) = 1 1 O(logn) 2 O(n) 3 O(nlogn) 4 O(n2) 5 O(2n)• Show less3 answers - Anonymous askedQ1.Pipeline parallelism... Show morePls.choose the best suitable answer given at the end of eachmultiple choice. Q1.Pipeline parallelism focuses on which of thefollowing? - Increasing throughput of task execution - Decreasing sub task execution time - Overlapping the execution tasks - Uniform task execution times - All of the above Question No. 2 What type of operation can be performed on a packagethat has been built and saved for further use? o a.Edited o b. Password protected o c. Scheduled for execution o d. Retrieved by version o e. All of the above If w is the window size and n is the size of data set,then the complexity of merging phase in BSN methodis… o a. O (n) o b. O(w) o c. O(wn) o d. O (w log n) o e. O (n log n) Question No. 4 Which is the least appropriate join operation forPipeline parallelism? o a. Hash join o b. Inner Join o c. Outer Join o d. Sort-merge join o e. None of the above Q5.Which of the following is a possible error dueto data duplication? o a.False frequency distributions. o b. Incorrect aggregates due to doublecounting. o c. Difficulty with catching fabricatedidentities. o d. All of the above• Show less1 answer - Anonymous askedthat returns the value of thelargest element in an array. The ar... Show more Create a function called amax() that returns the value of thelargest element in an array. The arguments to the function shouldbe the address of the array and its size. Make this function into atemplate so it will work with an array of any numerical type. Writea main() program that appliesthis function to arrays of various types• Show less3 answers - Anonymous askedLet Us Play Alphabets [ajava base game with falling letter from top and hitting thecharacter and get... Show more Let Us Play Alphabets [ajava base game with falling letter from top and hitting thecharacter and getting the score) Question I need thefollowing documentation Methodology and Work [SoftwareEngineering Cycle] Reasons for choosing theMethodology• Show less7 answers - Anonymous asked1 answer - Anonymous askedWrite an event procedure to solve the problem and display theanswer in a list box. The program shoul... Show moreWrite an event procedure to solve the problem and display theanswer in a list box. The program should use variable foreach of tha quantities.A motorist wants to determine her gas mileage. At23,340miles(on odometer) the tank is filled, the tank isfilled. At 23,695miles the tank is filled again with 14.1gallons. How many miles per gallons did the car averagebetween the two fillings?I would like to know the steps I need to follow to use theprogram to solve this problem using Visual Basicplease help.• Show less1 answer - Anonymous askedWrite a C++ program thatwill build a Word Concordance for a series of... Show morex.øi5am must do the following: Write a C++ program thatwill build a Word Concordance for a series of text lines. A Concordanceis basically an index of words in a• Show less document, and a listing of their context (line numbers). Yourprogram should first display your identification information, similarto our previous assignments. Then the program should read a series oflines of input from cin and keep track of the words that appear on thelines, and the line numbers of where those words appear in the inputstream. Upon completingthe processing of the input, the program should display an alphabetizedlisting of the words that were found, one word per line, and next toeach word will be a list of line numbers of where that word was foundin the input. A word, for the purpose of this program, isdefined as a series of non-blank characters, with leading and trailingpunctuation characters (-,.;:?"'!@#$%^&*[]{}|) removed (note thatembedded punctuation characters, such as Bob's and ten-thirty should beleft in the word). The words are to be saved without case-sensitivity;for example: Concordance ConCorDance CONCORDance concordance are all tobe considered the same word. The words are to be stored in astatically-declared array. You can assume that the maximum number ofunique words that will be submitted is 200. The words are to be storedin the array in sorted order, and you are to use the array-based binarysearch method as described in our course notes to locate words in thearray. For each word in the array, the list of line numbers isto be maintained by using a Linked-List Queue data structure, similarto what you used for Program 4. Although the Queue isn't necessarilythe most-appropriate data structure for this job, based on what we'vealready done with it, it should provide a simple interface to use. The outputshouldproblem is that I can't get it to sort the words and put them in alphabetical oder! Can someone help me w/ thisplease and show me what I need to do? I'm clueless!!! My code is below. // Example of Binary Search of an Array #include <iostream> #include <cstdlib> #include <string> #include "queue.h" #include <sstream> // for istringstream using namespace std; const intMAX =){ õs;x.øi5sp;-ðiex.øi5 dequeue(); // delete front return true; } // end dequeue bool Queu0 answers - Anonymous asked1 answer - Anonymous askedtotal seats are 36. and each passenger reserve seat fromdifferent cities to different cities and in... Show moretotal seats are 36. and each passenger reserve seat fromdifferent cities to different cities and in differenttime. • Show less0 answers
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2008-july-25
CC-MAIN-2014-52
refinedweb
3,007
57.06
Initialize a spawn attributes object #include <spawn.h> int posix_spawnattr_init( posix_spawnattr_t *attrp ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The posix_spawnattr_init() function initializes the given spawn attributes object with the default value for all the attributes. A spawn attributes object is an opaque object of type posix_spawnattr_t (defined in <spawn.h>) that you can use to modify the behavior of posix_spawn() or posix_spawnp(). Changes that you make to the spawn attributes object don't affect any processes that you've already spawned. You can also use this function to reinitialize a spawn attributes object that you've destroyed by calling posix_spawnattr_destroy(). See posix_spawn().
https://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawnattr_init.html
CC-MAIN-2022-05
refinedweb
115
57.47
On Wed, 13 Feb 2008 09:55:39 +1100, Ben Finney wrote: > Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes: > >> having the ability to create a protocol is a Very Good Thing, and >> double leading and trailing underscore names are the accepted Python >> style for such special methods. > > Is it? There are many protocols that use plain names. Even the built-in > types support many "protocol" operations via plain-named attributes. > > dict.get, dict.items, dict.keys, dict.values > > list.insert, list.append, list.extend, list.remove I don't believe any of those define a protocols. They are merely methods. An example of a protocol would be dict.__getitem__(): you can retrieve items from any object using the square bracket syntax if it has a __getitem__ method. However, having said that, I find myself in the curious position of (reluctantly) agreeing with your conclusion to "Go ahead and implement your protocol using attributes with plain names" even though I disagree with virtually every part of your reasoning. In my mind, the two deciding factors are: (1) Guido's original style guide essay allowed developers to use double- underscore names under certain circumstances. It seems that this has been deliberately dropped when it became a PEP. (2) PEP 3114 "Renaming iterator.next() to iterator.__next__()" makes it explicit that names of the form __parrot__ are intended to be "a separate namespace for names that are part of the Python language definition". Given that, I think that the special name __test__ in the doctest module is possibly an anomaly: it's not part of the language, but it seems to have the BDFL's blessing, or at least the BDFL didn't notice it. It's hardly the only anomaly in the standard library though, so one shouldn't draw too many conclusions from it. I think the intention is clear: names like __parrot__ are strictly verboten for user code. If and when my modest little programming efforts are considered for inclusion in the standard library, I will rethink this issue. In the meantime, no more __parrots__. You can stop reading now. But for those who care, I have a few final comments. > file.read, file.write, file.close I would accept that these three are part of the "file object protocol", However, they seem to be the odd one out: every other Python protocol that I can think of uses the __parrot__ form. iterator.next() is the exception, but that's explicitly been slated for change to __next__() in Python 3. -- Steven
http://mail.python.org/pipermail/python-list/2008-February/510320.html
CC-MAIN-2013-20
refinedweb
425
62.58
To scope this article, we will not be adding fancy methods that require async stuff on the server. That's something for later on.. Its just to illustrate the problem and solution with Meteor's EJSON library as a replacement for JSON. TL;DR.. Here's the resulting boilerplate code How to push data to your clientside React components We can utilize the window object and add a JSON stringified object to it. This will be sent along side with the serverside rendered HTML in script tags. On our clientside it will then automatically become available as a javascript object. See example below: A logical place to start would be the boilerplate that I've created for a previous article about How to set up Meteor & React with SSR In our startup/server.js file there's the following code:} /> )); }); The above code uses Meteor's onPageLoad which gets the Sink library as its parameter. Sink contains the request and response object and a couple of methods described in the Meteor docs about server-render. Adding initial state to your server side Lets extend the above code a bit with a bit of dummy state. Normally this state will be gathered from a bunch of different locations like Redux actions or a simple Meteor Method. In this example we are going to push some site meta data into the app. As you can see, on the serverside part its just a matter of adding an additional parameter to our App component. import React from 'react'; import { renderToNodeStream } from 'react-dom/server'; import { onPageLoad } from 'meteor/server-render';} /> )); }); Let's change our App component to simply do a console log for now. import React from 'react'; export default ({ initialState }) => { console.log(initialState); return ( <h1>Its working!</h1> ) }; Start your Meteor app and open it in the browser. You will notice that on our command line output all the information is given. However, if you open your developers console on the browser, it says 'undefined'.. That is because our clientside app doesn't have the initial state yet. We need a way to pass it to our bundle and ideally without doing an extra request. Hydrating React Components with state React's recommended way of hydrating the clientside is nicely explained in this article about React Client Side hydration. This method works nicely and is similar in Meteor, except, without the Express stuff. Let's first naively dive in and hydrate our client bundle 'the SSR Meteor way'. Add the following line to the bottom of your onPageLoad function in startup/server.js sink.appendToBody(` <script id="preloaded-state"> window.__PRELOADED_STATE__ = ${JSON.stringify(initialState)} </script> `) The above snippet uses sink to push a script tag into the bottom of our Server rendered HTML. It assigns a PRELOADED_STATE variable to the browser's window object. The initial state must be a string. This is why we stringify the initialState variable. If you do a 'view source' in your app, you should see the stringified JSON string as part of the HTML body Now in startup/client.js we need to grab this preloaded state window property and push it into our App component: // Browser automatically parses the JSON string into a javascript object. const initialState = window.__PRELOADED_STATE__; delete window.__PRELOADED_STATE__; // Remove what we don't need anymore If you now go to your app in the browser and open your console again, it should show you the state like on the serverside. There is a problem however! If you inspect the values of your state, you'll notice that the publishedAt field contains a date formatted as a string.. On the server however this is a Date object... Normally in Express based applications, you would have to 'pull the data trough a schema' - Meaning that all fields need to be parsed and transformed back into their rich equivalents. This process is error prone and leads to a lot of potential bugs. Meteor however solved this problem for us by providing us with EJSON. (Extended JSON). It allows us to push rich content types to the client in the form of JSON and parses it back automatically for us! You can even define your own custom types if needed, but that's a different topic for now. Lets start using it. Lets tweak our startup/server.js by adding the EJSON dependency. Also where we push the JSON data, we need to replace JSON with EJSON. Below should be the result. import React from 'react'; import { renderToNodeStream } from 'react-dom/server'; import { onPageLoad } from 'meteor/server-render'; // Add EJSON dependency import { EJSON } from 'meteor/ejson';}/> )); // Push EJSON stringified state to the client sink.appendToBody(` <script id="preloaded-state"> window.__PRELOADED_STATE__ = ${EJSON.stringify(initialState)} </script> `) }); Now lets open our browser console again and you will see a new value for the publishedAt field. publishedAt: {$date: 1525910400000} Its still not a Date object, but at least we now have an indicator that it should. We need to change how the EJSON string is parsed on our client side. Right now it just parses it as JSON. The only thing that we need to do is to tweak the startup/client.js file: import React from 'react'; import ReactDOM from 'react-dom'; import { onPageLoad } from 'meteor/server-render'; import { EJSON } from 'meteor/ejson'; // Stringify back the preloaded state into its original EJSON string form. // Then use the EJSON parser to parse rich content types const initialState = EJSON.parse(JSON.stringify(window.__PRELOADED_STATE__)); delete window.__PRELOADED_STATE__; // Remove what we don't need anymore onPageLoad(async sink => { const App = (await import('../ui/App.jsx')).default; ReactDOM.hydrate( <App initialState={initialState}/>, document.getElementById('app') ); }); In the above code we are doing one seemingly silly thing. We first stringify the preloaded state only to parse it back again.. What's the deal with that? Well your browser already uses JSON.parse by default to create a javascript object from our state. We don't want that. We need EJSON to parse our string. So we simply undo what the browser did and parse it using EJSON. Now lets open the console again and your publishedAt field should have a Date value instead of a string value.
https://www.chrisvisser.io/meteor/meteor-react-with-ssr-hydrating-initial-state-with-ejson
CC-MAIN-2018-39
refinedweb
1,035
65.83
5356. Lucky numbers in matrices class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: rmin = [min(x) for x in matrix] cmax = [] n = len(matrix) m = len(matrix[0]) for i in range(m): maxv = matrix[0][i] for j in range(1, n): maxv = max(maxv, matrix[j][i]) cmax.append(maxv) ans = [] for i in range(n): for j in range(m): if matrix[i][j] == rmin[i] and matrix[i][j] == cmax[j]: ans.append(matrix[i][j]) return ans 5357. Design a stack that supports incremental operations Create self. S = [] as stack. However, the first element in S is the real value, and the second is the added value. Each increment operation directly adds the elements in the stack, but records them in the list of elements at the corresponding position in the stack. They are not added up until pop, and are accumulated to the previous element. class CustomStack: def __init__(self, maxSize: int): self.size = 0 self.maxSize = maxSize self.s = [] def push(self, x: int) -> None: if self.size < self.maxSize: self.s.append((x, 0) self.size += 1 def pop(self) -> int: if self.size == 0: return -1 x, inc = self.s.pop() if len(self.s) > 0: self.s[-1][1] += inc self.size -= 1 return x + inc def increment(self, k: int, val: int) -> None: if self.size > 0: k -= 1 k = min(k, self.size-1) self.s[k][1] += val 5179. Balance the binary search tree My method is to traverse the tree – > turn to array – > sort – > build a binary search tree class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: ls = [] def vis(t): if not t: return ls.append(t) vis(t.left) vis(t.right) vis(root) ls.sort(key=lambda t:t.val) def build(l, r): if l == r: ls[l].left = None ls[l].right = None return ls[l] if l + 1 == r: ls[r].left = ls[l] ls[l].left = None ls[l].right = None ls[r].right = None return ls[r] mid = (l+r)>>1 ls[mid].left = build(l, mid-1) ls[mid].right = build(mid+1, r) return ls[mid] return build(0, len(ls)-1) 5359. Maximum team performance value First, arrange the efficiency from large to small, and set the rigid opening efficiency as the maximum value. This is that only the person with the highest efficiency can be selected, and then continuously reduce the efficiency. The lower the efficiency, the more people can be used. Each time, select k (if there are not enough people, select as many people as possible) who meet the efficiency requirements and have the highest speed. Use the priority queue to maintain the speed of the currently selected everyone, so that the slowest person can be eliminated each time import queue class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: es = [] for i in range(n): es.append((efficiency[i], speed[i])) es.sort(reverse=True) q = queue.PriorityQueue() q.put(es[0][1]) mins = es[0][1] sm = mins mine = es[0][0] ans = sm * mine maxv = ans cur_min = -1 for i in range(1, n): if i < k: q.put(es[i][1]) sm += es[i][1] mine = min(mine, es[i][0]) maxv = max(maxv, sm*mine) else: if cur_min == -1: cur_min = q.get() if cur_min < es[i][0]: sm += es[i][1] sm -= cur_min cur_min = -1 mine = min(mine, es[i][0]) maxv = max(maxv, sm*mine) q.put(es[i][1]) return maxv % 1000000007
https://developpaper.com/weekly-game-180-of-leetcode-python-solution/
CC-MAIN-2021-43
refinedweb
597
69.28
27 April 2012 10:35 [Source: ICIS news] SINGAPORE (ICIS)--Operating rates of major Chinese refineries averaged 81.3% on 26 April, a rise of 2.31 percentage points from two weeks ago, according to C1 Energy, an ICIS service in ?xml:namespace> Dalian West Pacific Petrochemical and Sinopec Jingmen Petrochemical restarted a combined capacity of 11.5m tonne/year, while Sinopec Qingdao Refining & Chemical completed the turnaround at a 220,000 tonne/year sulphur unit, according to data from C1 Energy. PetroChina Daqing Petrochemical shut down a 2.5m tonne/year crude distillation unit and some secondary conversion units for maintenance, the data showed. Run rates at the other refineries were mostly recorded unchanged, according to the data. The operating rates are expected to stay at 80-82% in early May when some major refineries will still be under maintenance, market sources said, adding that the rates may go above 85% in June when some of the turnarounds are completed. The average refinery operation rate calculated from the run rates of Higher refinery operating rates typically lead to
http://www.icis.com/Articles/2012/04/27/9554309/run-rates-of-chinas-major-refineries-rebound-slightly-to-81.3.html
CC-MAIN-2014-52
refinedweb
179
54.52
Gaining Access to the Spring Context in Non Spring Managed Classes There are times where it’s not practical (or possible) to wire up your entire application into the Spring framework, but you still need a Spring loaded bean in order to perform a task. JSP tags and legacy code are two such examples. Here is a quick and easy way to get access to the application context. First we create a class that has a dependency on the spring context. The magic here is a combination of implementing ApplicationContextAware and defining the ApplicatonContext object as static. package com.objectpartners.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContext implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } public static ApplicationContext getApplicationContext() { return context; } } Next, we wire SpringContext into our spring container by defining it in our application-context.xml: <bean id="springContext" class="com.objectpartners.util.SpringContext /> Now, anywhere we need access to the spring context we can import SpringContext and call the getApplicationContext method like so: import com.objectpartners.util.SpringContext; class LegacyCode { . . SpringBean bean = (SpringBean)SpringContext.getApplicationContext.getBean("springBean"); . . } Keep in mind that if there are multiple spring containers running on the JVM the static ApplicationContext object will be overwritten by the last container loaded so this approach may not work for you. One thought on “Gaining Access to the Spring Context in Non Spring Managed Classes” Nicely written. I wasn’t aware of the multiple spring containers tip. Thanks! Hi thanks for a good article. Im thinking about acessing a spring bean trough a Jruby script do you think this would be possible? I have never used JRuby, but found a short tutorial on how to do it: Super Article, exactly what I was looking for ! Simplest way of doing this.Thanks I’ve done this just for this scope Great! That was exactly what I need ! This is OK, but how can I avoid the XML? I haven’t tested this, but as long as you have component scanning enabled in your @Configuration file, you should be able to simply annotate the SpringContext bean with @Component Nice Article. I have a problem, my web application is legacy and I want to plug only one module as a Spring based project. How would I do that , could you help me by giving some approaches ? Tried Approach : In a static block , I have initiated the Spring factory . But, I need to have a shutdownHook to close the resources. I felt this approach not good as I am forcing the web container to initiate/close the Spring container. I would change this.context to SpringContext.context Thank you very much! I have been searching for this exact thing for days! Thank you so much!!!! Nice idea!
https://objectpartners.com/2010/08/23/gaining-access-to-the-spring-context-in-non-spring-managed-classes/
CC-MAIN-2020-40
refinedweb
475
50.23
Holy cow, I wrote a book!; we'll learn about that when we get to them.. br.call. bsp Break Okay, this was a whirlwind tour of the Itanium register set. I bet your head hurts already, and we haven't even started coding yet! In fact, we're not going to be coding for quite some time. Next time, we'll look at the instruction format. A customer was running into a compiler error complaining about redefinition of the symbol HLOG. HLOG #include <pdh.h> #include <lm.h> ... The result is lmerrlog.h(80): error C2373: 'HLOG' redefinition; different type modifiers pdh.h(70): See declaration of 'HLOG' "Our project uses both performance counters (pdh.h) and networking (lm.h). What can we do to avoid this conflict?" pdh.h lm.h We've seen this before. The conflict arises from two problems. First is hubris/lack of creativity. "My component does logging. I need a handle to a log. I will call it HLOG because (1) I can't think of a better name, and/or (2) obviously I'm the only person who does logging. (Anybody else who wants to do logging should just quit their job now because it's been done.)" This wouldn't normally be a problem except that Win32 uses a global namespace. This is necessary for annoying reasons: Fortunately, in the case of HLOG, the two teams noticed the collision and came to some sort of understanding. If you include them in the order #include <lm.h> #include <pdh.h> then pdh.h detects that lm.h has already been included and avoids the conflicting definition. #ifndef _LMHLOGDEFINED_ typedef PDH_HLOG HLOG; #endif The PDH log is always accessible via the name PDH_HLOG. If lm.h was not also included, then the PDH log is also accessible under the name HLOG. PDH_HLOG Sorry for the confusion. A security vulnerability report came in that went something like this: We have found a vulnerability in the XYZ application when it opens the attached corrupted file. The error message says, "Unhandled exception: System.OverflowException. Value was either too large or too small for an Int16." For a nominal subscription fee, you can learn about similar vulnerabilities in Microsoft products in the future. Okay, so there is a flaw in the XYZ application where a file that is corrupted in a specific way causes it to suffer an unhandled exception trying to load the file. That's definitely a bug, and thanks for reporting it, but is it a security vulnerability? The attack here is that you create one of these corrupted files and you trick somebody into opening it. And then when they open it, the XYZ application crashes. The fact that an OverflowException was raised strongly suggests that the application was diligent enough to do its file parsing under the checked keyword, or that the entire module was compiled with the /checked compiler option, so that any overflow or out-of-range errors raise an exception rather than being ignored. That way, the overflow cannot be used as a vector to another attack. OverflowException checked /checked What is missing from the story is that nobody was set up to catch the overflow exception, so the corrupted file resulted in the entire application crashing rather than some sort of "Sorry, this file is corrupted" error being displayed. Okay, so let's assess the situation. What have you gained by tricking somebody into opening the file? The program detects that the file is corrupted and crashes instead of using the values in it. There is no code injection because the overflow is detected at the point it occurs, before any decisions are made based on the overflowed value. Consequently, there is no elevation of privilege. All you got was a denial of service against the XYZ application. (The overflow checking did its job and stopped processing as soon as corruption was detected.) There isn't even data loss, because the problem occurred while loading up the corrupted file. It's not like the XYZ application had any old unsaved data. At the end of the day, the worst you can do with this crash is annoy somebody. Here's another way you can annoy somebody: Send them a copy of onestop.mid. A customer reported that the DuplicateHandle function was failing with ERROR_INVALID_HANDLE even though the handle being passed to it seemed legitimate: DuplicateHandle ERROR_INVALID_HANDLE // Create the handle here m_Event = ::CreateEvent(NULL, FALSE/*bManualReset*/, FALSE/*bInitialState*/, NULL/*lpName*/)); ... error checking removed ... // Duplicate it here HRESULT MyClass::CopyTheHandle(HANDLE *pEvent) { HRESULT hr = S_OK; if (m_Event != NULL) { BOOL result = ::DuplicateHandle( GetCurrentProcess(), m_Event, GetCurrentProcess(), pEvent, 0, FALSE, DUPLICATE_SAME_ACCESS ); if (!result) { // always fails with ERROR_INVALID_HANDLE return HRESULT_FROM_WIN32(GetLastError()); } } else { *pEvent = NULL; } return hr; } The handle in m_Event appears to be valid. It is non-null, and we can still set and reset it. But we can't duplicate it. m_Event Now, before claiming that a function doesn't work, you should check what you're passing to it and what it returns. The customer checked the m_Event parameter, but what about the other parameters? The function takes three handle parameters, after all, and they checked only one of them. According to the debugger, DuplicateHandle was called with the parameters hSourceProcessHandle = 0x0aa15b80 hSourceHandle = 0x00000ed8 hTargetProcessHandle lpTargetHandle = 0x00b0d914 dwDesiredAccess = 0x00000000 bInheritHandle dwOptions = 0x00000002 Upon sharing this information, the customer immediately saw the problem: The other two handle parameters come from the GetCurrentProcess function, and that function was returning 0x0aa15b80 rather than the expected pseudo-handle (which is currently -1, but that is not contractual). GetCurrentProcess 0x0aa15b80 -1 The customer explained that their MyClass has a method with the name GetCurrentProcess, and it was that method which was being called rather than the Win32 function GetCurrentProcess. They left off the leading :: and ended up calling the wrong GetCurrentProcess. MyClass :: By default, Visual Studio colors member functions and global functions the same, but you can change this in the Fonts and Colors options dialog. Under Show settings for, select Text Editor, and then under Display items you can customize the colors to use for various language elements. In particular, you can choose a special color for static and instance member functions. Or, as a matter of style, you could have a policy of not giving member functions the same name as global functions. (This has the bonus benefit of reducing false positives when grepping.) Bonus story: A different customer reported a problem with visual styles in the common tab control. After a few rounds of asking questions, coming up with theories, testing the theories, disproving the theories, the customer wrote back: "We figured out what was happening when we tried to step into the call to CreateDialogIndirectParamW. Someone else in our code base redefined all the dialog creation functions in an attempt to enforce a standard font on all of them, but in doing so, they effectively made our code no longer isolation aware, because in the overriding routines, they called CreateDialogIndirectParamW instead of IsolationAawreCreateDialogIndirectParamW. Thanks for all the help, and apologies for the false alarm." CreateDialogIndirectParamW IsolationAawreCreateDialogIndirectParamW Some years ago, the IT department replaced the printers multifunction devices with new reportedly eco-friendly models. One feature of the new devices is that when you send a job to the printer, it doesn't print out immediately. Printing doesn't begin until you go to the device and swipe your badge through the card reader. The theory here is that this cuts down on the number of forgotten or accidental printouts, where you send a job to a printer and forget to pick it up, or you click the Print button by mistake. If a job is not printed within a few days, it is automatically deleted. The old devices already supported secured printing, where the job doesn't come out of the printer until you go to the device and release the job. But with this change, secured printing is now mandatory. Of course, this means that even if you weren't printing something sensitive, you still have to stand there and wait for your document to print instead of having the job already completed and waiting for you. The new printing system also removes the need for job separator pages. Avoiding banner pages and eliminating forgotten print jobs are touted as the printer's primary eco-friendly features. Other functions provided by the devices are photocopying and scanning. With the old devices, you place your document on the glass or in the document hopper, push the Scan button, and the results are emailed to you. With the new devices, you place your document on the glass or in the document hopper, push the Scan button, and the results are emailed to you, plus a confirmation page is printed out. Really eco-friendly service there, printing out confirmation pages for every scanning job. The problem was fixed a few weeks later. Bonus chatter: Our fax machines also print confirmation pages, or at least they did the last time I used one, many years ago. Today's Little Program tells you whether a keyboard is attached to the computer. The short answer is "Enumerate the raw input devices and see if any of them is a keyboard." Remember: Little Programs don't worry about silly things like race conditions. #include <windows.h> #include <iostream> #include <vector> #include <algorithm> bool IsKeyboardPresent() { UINT numDevices = 0; if (GetRawInputDeviceList(nullptr, &numDevices, sizeof(RAWINPUTDEVICELIST)) != 0) { throw GetLastError(); } std::vector<RAWINPUTDEVICELIST> devices(numDevices); if (GetRawInputDeviceList(&devices[0], &numDevices, sizeof(RAWINPUTDEVICELIST)) == (UINT)-1) { throw GetLastError(); } return std::find_if(devices.begin(), devices.end(), [](RAWINPUTDEVICELIST& device) { return device.dwType == RIM_TYPEKEYBOARD; }) != devices.end(); } int __cdecl main(int, char**) { std::cout << IsKeyboardPresent() << std::endl; return 0; } There is a race condition in this code if the number of devices changes between the two calls to GetRawInputDeviceList. I will leave you to fix it before incorporating this code into your program. GetRawInputDeviceList op r, m op m, r op m movs stos lds les pop ds pop es If the conditions are met, then the Ignore option became available. If you chose to Ignore, then the kernel did the following: In other words, the kernel did the assembly language equivalent of ON ERROR RESUME NEXT... CreateProcess ntdll.dll). GetModuleFileNameEx ReadProcessMemory.) CreateToolhelp32Snapshot ERROR_PARTIAL_COPY In the particular example above, the code could avoid the problem by using the QueryFullProcessImageName function to get the path to the executable. QueryFullProcessImageName." GetModuleInformation .."
http://blogs.msdn.com/b/oldnewthing/
CC-MAIN-2015-32
refinedweb
1,740
54.93
> The question is answered, right answer was accepted Hi everyone, In my Unity learning project, i'm using references to the UI object present in the bootstrap menu (Game jam menu template in my case) in other scenes. For instance in the game or tutorial scene (i tweaked the template to support more scenes to learn a bit more...), when i want to reuse the music or scene management scripts : public class ExitTutorial : MonoBehaviour { private StartOptions startScript; void Awake () { startScript = GameObject.FindGameObjectWithTag("UI").GetComponent<StartOptions>(); } .... } Everything's ok when i test a build, or if i load the Bootstrap menu in Unity before launching the built-in game test, but if i launch the test directly from my tutorial scene, i get the NullReference error. I understand why, but i wonder how i can test this single scene when i'm working on it without the error I found 2 solution but i'm not 100% satisfied with them 1) Encapsuate this code with #if UNITY_EDITOR, but in that case i can't test the references when i launch the boostrap scene & access another one from the game view 2) Deactivate "Error pause" in the console, but i'm sure it's not a good habit and i'll end up missing important stuff... I'm sure i'm just missing the proper way to do it :) Thanks in advance Answer by gkfr · Dec 08, 2017 at 11:20 PM Silly me... if(GameObject.Find ("UI")) { Debug.Log ("No need to instantiate UI, can use the references"); } else Debug.Log ("Doesn't exist, instantiate UI prefab or don't use the UI related. Unable to see NUnit Assert message output 1 Answer Editor test runner makes unity hang 1 Answer How do I test if a 3d model works well in Unity? 0 Answers Unfortunately, (GameName) has stopped (report ,ok) 0 Answers Is SAMSUNG GALAXY J7 Prime is compatible with unity ar applications? 0 Answers
https://answers.unity.com/questions/1440317/how-to-avoid-cross-scenes-reference-errors-when-te.html
CC-MAIN-2019-22
refinedweb
325
52.02
I? Part 1 – The History & Math behind DeepZoom). Part 2 – Constructing a DeepZoom Image using DeepZoom composer - We begin by downloading the “DeepZoom composer” from Microsoft Downloads. If you want a great reference for the tool, try the DeepZoom Composer guide. In the steps below, I am going to keep it to the minimum steps needed and some of the gotchas when using the tool. - After installing the DeepZoom Composer, we launch it. Trivia facts: Composer is a WPF application, like most of the other Expression products. Also, codename was Mermaid (you can see this from the export window). - Under the File Menu, select “New Project” - Now click “Add Image” to import a few images. You can import multiple images at once. In my case, I am importing 3 images: bummysmall.jpg, eggs.jpg, and world2.jpg). These are in the inputimages directory if your are following along with the source. This added all the images we are going to use in the composer. All images must be added at design-time. - Click “Compose” on the Center toolbar to compose the DeepZoom image. - Double click the world image to add it to the ‘stage’ or design surface. - Click Fit To Screen to maximize our space. - Click on the eggs image to add it to the stage. - Zoom many times into the image at a place where you want to drop some easter eggs. - Hint: the Usual short cuts of Ctrl+ and Ctrl- do work for zooming. Unfortunately Pan(h) and Select(v) don’t work. - Shrink the easter eggs into a small size — don’t worry, with DeepZoom we will be able to Zoom a lot at run-time to find them and see them. - Drop the easter eggs where you want to. He is an example of mine, I dropped them in Mexico. Notice I am quite zoomed into the map and the eggs are small. - Repeat the steps in 11 for the bunny picture. In my case, I did it in Seattle area. Note: unfortunately I could not figure how to drag same image twice into stage area. The work around I used is to make a copy of the image with different name, and add it to the image gallery ( Step 4). - Click Ctrl-0 to see our DeepZoom Image with out the zooms. You sized it right if you can’t easily see the eggs and bunny in the map. - CLick “Export” in the main toolbar. - Here we enter the settings for output. - Leave the “generate collection” unchecked for now. What Generate Collection does is exports the DeepZoom Image with metadata and at run-time the images can be accessed via the MultiScaleImage.SubImages property. If you can get to these images, you can move them around the composed image ( for layout ) you can also tweak their Opacity. The reason I am leaving them unchecked is beause there seems to be a bug (at least on my machine) where if I click Generate Collections my images at run-time show at an offset of where they are supposed to be. I have reported it to the DZC team and they are investigating. - Enter a Name ( “Easter” on the export Dialog). - I leave the Output path untouched. This is where having entered a short path in Step 2 above would pay up because their Path dialog does not Wrap and it is fairly small. [Kirupa already said this is improving for next version]. If you opt to change the path, be attentive when you export again, it seems to reset to its default value. - Now, assuming your output looks similar to mine above, (Create Collection unchecked) Click Export and we are done when it says Export Completed. Part 3 – DeepZoom Object Model: - Logical Coordinates – is a normalized value (0 to 1) representing a coordinate in the image itself (not the control) - Element Coordinates – is the actual control coordinates. For example in a MultiScaleImage of Width=800, Height =400, when the mouse is at the center, the element coordinates are 400,400. These coordinates are not normalized. Now, we navigate through the interesting properties and methods in MultiScaleImage - Source – refers to the Image source; usually info.bin when not using collections or items.bin if using collections. - SubImages – when using collections, this is a reference to all the images in a composed DeepZoom Image. - ViewportWidth – Specifies the width of the parts of the image to be displayed. The value is in Logical coordinates. For example: Width=2 means image is zoomed out and only takes half the space available. To zoom in, a viewport < 1 is required. ViewportWidth of 0.5 is a 200% zoom. - ViewportOrigin – the Top,Left corner for the parts of the image to be displayed. This is returned in Logical coordinates. For example, imagine I am panning by 10% each time and I pan twice to the right while zoomed in at 100% (so no zoom), my ViewportOrigin.X will be 0.2. - UseSprings – gets or set whether DeepZoom animates the transitions ( like ZoomAboutLogicalPoint, updates to ViewportOrigin, etc. ). The interesting methods are: - ElementToLogicalPoint – takes a coordinate of the control, and gives you a logical ( normalized coordinate). For example, mouse at Center (400,400) with ViewportWidth=1 and you call ElementToLogical ( ) will return (0.5, 0.5) - LogicalToElementPoint – takes a logical coordinate (normalized) and returns a point in the MultiScaleImage control where that logical point corresponds to. - ZoomAboutLogicalPoint – implements the Zoom. The two parameters are the new zoom multiplier – as an increment from current zoom factor in the image – and the Logical point at which to zoom around. Example of the incremental zoom would be to ZoomAboutLogicalPoint ( 1.5, 0.5, 0.5) .. I will be zoomed in to 1.5 times; if I repeat this operation with same values I am zoomed in at 1.5 * 1.5 which is 2.25 times from size where I started. In my opinion, surprisingly missing from the API were: - The original width and height of the DeepZoomImage (so that I can translate normalized logical coords to physical on the image). - Zoom – to tell you the current total Zoom level; this one you can get around by keeping track of any zooms you implement. Another possible workaround is that Zoom appears to be 1/ViewportWidth; I can’t think of the scenario where this does not hold, if there is please let me know and again just keep track of your zooms if that happens. Part 4 – Coding a DeepZoom Host User Control] - Inside Visual Studio 2008, create a new Silverlight Application; I called it DeepZoomSample. - Build the application so the Clientbin directory is created. - Copy the output from the DeepZoom Composer to the Clientbin directory of our Silverlight application. In my case, I called the output “Easter” so I can go into the output directory from composer and just copy that whole directory to my Silverlight Application’s ClientBin. - Now that we have our image, we can edit the XAML in Page.Xaml, to show the image. <UserControl x:Class=”DeepZoomSample.Page”If you run the application now, you will see the image loads but there is no functionality: zoom and pan have not been implemented. xmlns=”″ xmlns:x=”” > <Grid x:Name=”LayoutRoot” Background=”White”> <MultiScaleImage x:Name=”DeepZoom” Source=”easter/info.bin” /> </Grid> </UserControl> For zoom, we need to use the mouse wheel, but Silverlight has no native support for it. A good work around is to use Peter Blois’ MouseWheelHelper. This class uses HTML Bridge to listen to the mouse wheel event in the browser and exposes the events to managed code. - Add a new code file to your project, I called it MouseWheelHelper. - Copy Peter’s code below into the MouseWheelHelper file.(); } } } } } MouseWheelHelper fires a Moved Event whenever the Wheel moves. The EventArgs is a MouseWheelEventArgs, which has the delta property. Delta is a normalized property (0 to 1), for now all we look at is whether it is greater than 0 or not. If Delta is greater than 0, then the wheel has rotated away from the user; if Delta is a negative number, then the wheel has rotated toward the user. - Before we handle the Moved event, let’s add a ZoomFactor property to our control, this will be the increment/decrement on a wheel operation. The default value is 1.3, which is a 30% increment. Nothing scientific behind this number, I am pretty much just ‘copying’ what I see every other sample do. I think the number works OK. protected double _defaultZoom = 1.3; public double DefaultZoomFactor { get { return _defaultZoom; } set { _defaultZoom = value; } } - We also add a CurrentTotalZoom property, this will be a cached version of overall zoom level (since we can’t query this from the MultiScaleImage API. I also added a MaxZoomIn and MaxZoomOut to prevent the image from going too far in (is there such a thing?) or too far out. Too Far out did matter as the image can disapper if you go too far. In my case I picked my Maximum values arbitrarily.; } } - Now, we can add a DoZoom function to our class, this will be called when there is a Zoom operation. The parameters for it are: the new Zoom level RELATIVE to where the image is at, and a point in Element Coordinates since most likely we will be zooming around the mouse, and we get Element coordiantes out of that. /// ; } - Now we are ready to handle the MouseWheelHelper.Moved event. We will do it in three parts: - We will subscribe to MouseMove event in the MultiScaleImage, so we can keep track of where the mouse is; we need this because MouseWheelHelper.Moved does not give us a MousePosition, and there is no way to query MousePosition in Silverlight2 outside of a Mouse EventHandler. // inside the Loaded event for the user control //{ DeepZoom.MouseMove += newMouseEventHandler(DeepZoom_MouseMove); _lastMousePosition = new Point ( DeepZoom.ActualWidth /2 , DeepZoom.ActualHeight /2); //} protected Point _lastMousePosition; void DeepZoom_MouseMove(objectsender, MouseEventArgs e) { _lastMousePosition = e.GetPosition(DeepZoom); } - Now we instantiate a MouseWheelHelper and subscribe to Moved event // inside the Loaded Event for UserControl MouseWheelHelper mousewheelhelper = new MouseWheelHelper(this); mousewheelhelper.Moved += newEventHandler<MouseWheelEventArgs>(OnMouseWheelMoved); - We add the OnMouseWheelMoved function to the UserControl class..); } } - NOTE: If you compare the source above with the code in the sample source, they are slightly different. In the sample source there is two approaches to handling Zoom, and there is a boolean flag called _useRelatives that controls this. if you set _useRelatives to true, it will zoom based in relation to a last zoom; I think this makes it more complicated but for some reason most samples I have seen of DeepZoom use this calculation. I think the behavior is the same than the approach I took, but the math is simpler with the approach in the steps above. I did add both in case I find later that there was a scenario addressed by the _useRelatives approach. - At this point we should be able to run the application and get Zoom to work (in and out) around the mouse location. Compile the app and run it to make sure we are making progress. - To Pan, we need to detect the MouseLeftButtonDown and MouseLeftButtonUp, the assumption is we will pan when the mouse is down, and pan in the direction of the Mouse movement and then stop panning when the mouse is up. - Let’s add a handler for MouseLeftButtonDown, we add the listener in the UserControl’s Loaded event. This handler will set a variable called _isDragging to flag that the mouse is down; we will use this flag on the MouseMove handler. // inside the Loaded function, we add code behind our MouseWheelHelper code added earlier.. DeepZoom.MouseLeftButtonDown += newMouseButtonEventHandler(DeepZoom_MouseLeftButtonDown); - The handler looks like this:; } - Now we subscribe to MouseLeftButtonUp, inside Loaded function and we add the handler function for it. // The one liner below goes in the Page_Loaded event handler DeepZoom.MouseLeftButtonUp += newMouseButtonEventHandler(DeepZoom_MouseLeftButtonUp); void DeepZoom_MouseLeftButtonUp(objectsender, MouseButtonEventArgs e) { this._isDragging = false; } - Now we tweak the code inside MouseMove to Change the ViewportOrigin to perform the Pan operation.); } - We should also detect the MouseLeave event, and if we are in the middle of a Pan, we need to reset the _isDragging flag. // inside the UserControl Loaded handler DeepZoom.MouseLeave += newMouseEventHandler(DeepZoom_MouseLeave); void DeepZoom_MouseLeave(objectsender, MouseEventArgs e) { this._isDragging = false; this.DeepZoom.Cursor = Cursors.Arrow; } - That is it for the basics and the ‘hard stuff’ … with not too many lines of code, we have Zoom & Pan in our host. Along the way we added a few properties we can reuse to create UI around our DeepZoom image. Part 4.1 Adding more UI to navigate in a DeepZoom Control.. - Implementing Panning is done by changing the viewportOrigin. We have a choice of Panning relative to control size and relative to ImageSize. Let me explain: If the controls ViewPortWidth is 1.0 – and we pan by a Logical increment of 0.1 we are panning 10 percent on a direction. This % seems reasonable. If however we are zoomed in 500% ( viewportWidth = 0.2 ) and we do a Pan of 0.1 (logical) then we are going to pan by a lot ( 50% of what is visible). So we need to scale our original 0.1 increment by the ViewportWidth. Don’t you think? Here is what I did: - Added a Property of type double called PanPercent. This property holds the increment. You can set it from XAML; default is 0.1 ( aka 10% ) - Added a property of type bool called UseViewportScaleOnPan. If this is true, we will pan by PanPercent * ViewportWidth; if this is false we pan by PanPercent. - Now we are ready for Panning. We add event handlers for all our Pan RepeatButtons:); - Each of the event handlers calls the Pan function with their respective direction:; } } - Panning to Home is a combination of setting the ViewportOrigin to 0,0 and setting the ViewportWidth to 1 void Home_Click(object sender, RoutedEventArgs e) { this.DeepZoom.ViewportOrigin = new Point(0, 0); this.DeepZoom.ViewportWidth = 1; } - Next thing is to implement Zoom in and Zoom Out; these are also trivial, the only decision to make is where to Zoom, I needed two approaches: When Zooming using keyboard, Ctrl+ Ctrl- (on Windows) I wanted to Zoom at the mousePosition. When zooming using the magnifying glass icons I added to the UI, I can not use the mousePosition – as I knew the mouse was where the magnifying glass – so I zoomed around the center of the control. Let’s begin with simple ZoomIn using Click from magnifying glass: void btnZoomIn_Click(objectsender, RoutedEventArgs e) { ZoomIn( newPoint( DeepZoom.ActualWidth / 2 , DeepZoom.ActualHeight / 2)); } /// ); } - When zooming from Keyboard. The “gotcha” was that the DeepZoomImage is a FrameworkElement and it does not receive focus (in Silverlight Focus is at Control class), so what I did was listen for Keyboard event in the Grid that is the top container in my Host UserControl. this.LayoutRoot.KeyUp += new KeyEventHandler(DeepZoom_KeyUp); - Another surprise was that + (by pressing Shift+9) on my machine turned out to be a keycode, not a standard key. I am not a keyboard expert in Silverlight (yet) but from what I read, keycodes can be different across platform so I added code to check in case I am running in the Mac. I checked using the Environment.OSVersion property. Please double check this code, as I was pretty lazy about what running on Windows or Mac means. public bool RunningOnWindows { get { return( Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S); } } - Now we do the Zoom, note that I am not too confident on my Mac KeyCodes; I got this by sniffing on my Mini but I have a regular,ergonomic Microsoft keyboard on that mini so double check with your keyboard just in case.; } - At that point our app would be functionally complete but I want to share a few more findings from my learning so let me share the DebugSpew, it can be handy for you too. - When I wrote my first deepZoom app, I took the usual approach of databinding to it so I can reverse engineer it and found a few issues; since I am traveling I have not discussed them w/ DeepZoom folks in depth for now take these as “gotchas in beta1” and will try to get some one from DeepZoom team to confirm if these are ‘final’ behaviors (feel free to leave feedback here or at the expression blog) letting them know your preferences. - Databinding to MultiScaleImage was a bit flaky. ViewportWidth and ViewportOrigin did not fire notifications for me. The explanation I have seen is that because DeepZoom animates with springs, binding to these properties was not recommended. These values will change every frame during a transition. The recommended workaround was to subscribe to the MotionFinished event. This fires at the end of a transition, so gives me a nice way to pull the value. In my case (for debug/learning deepZoom), the workaround was very acceptable so I implemented it. // in my loaded event for the page DeepZoom.MotionFinished += newRoutedEventHandler(DeepZoom_MotionFinished); void DeepZoom_MotionFinished(objectsender, RoutedEventArgs e) { if(DebugSpew.DataContext != null) { MultiScaleImageDummyDataWrapper dw = DebugSpew.DataContext asMultiScaleImageDummyDataWrapper; if(dw != null) { PullData(refdw, refDeepZoom); MouseLogicalPosition = DeepZoom.ElementToLogicalPoint(_lastMousePosition); } } }; } - Databinding to the other properties (that are not animated per frame) in MultiScaleImage also gave me a bit of trouble [some times the control would not show up]. My advise is to not data bind for now. - Once I had the databinding worked out, I added a handler to pull data from the MouseMove so I could show coordinates when Mouse is moving, I wanted them in logical and element coordinates, so I did the translation and I added an extra call from MotionFinished to translate the point again as the logical Coordinate changes when the Viewport changes. Part 5 – Lessons learned. Part 6 – Source Part 7 – Show me the app.. - One is for the NCAA basketball team for my college, which won yesterday and made it to the Final Four tournament . (Hint, the four finalists are: Kansas, Memphis, UCLA and North Carolina. - The other one is a bitmap with dates & locations for my upcoming Europe trip (Germany, Austria).. If you are in the area and available the nights I am in the area, ping me and we can get together to discuss any thing .NET client related (e.g. WPF, Silverlight, and ASPX). Part 8 — Thanks. PingBack from Jamie, Super job!! I’m going to use this tutorial and get DeepZoom on my web site after the MVP Summit. This is wild! Nice advertising your availability in the evenings while your in Europe! Best to you! Karl On my Deep zoom Post , I recommended that for Deep Zoom applications you instantiate the control using Deep Zoom which is a technology that combines Silverlight with SeaDragon is a powerful and easy way to Build your own Silverlight 2.0 Deepzoom application and host it with "Silverlight Streaming" Build your own Silverlight 2.0 Deepzoom application and host it with "Silverlight Streaming" Ever since we released Deep Zoom Composer during MIX, there has been a ton of great feedback you have Quite a few people provided me feedback on my Deep Zoom post last month . With the help from Jamie Rodriguez’s Quite a few people provided me feedback on my Deep Zoom post last month . With the help from Jamie Rodriguez's Today we covered Deep Zoom, based on Seadragon technology, which allows the users of our Silverlight Build your own Silverlight 2.0 Deepzoom application and host it with "Silverlight Streaming" DeepZoom is a cool feature of Silverlight 2.0 allowing the user to zoom and pan around an image, while This has been talked about since the ESRI Developer Summit 2008 earlier this year and earlier this week Richie Carmichael wrote up about a new Microsoft Silverlight map viewer that he has developed for ArcGIS Server 9.3. The Silverlight map viewer is Since we released Deep Zoom Composer a while ago at MIX, we relied extensively on all of you to both para quem quiser se aprofundar no Deep Zoom (ops, escolha estranha de verbo), aqui vão algumas referências Yesterday I saw that the Expression Blend and Design team had blogged about the new DeepZoomTool.dll Build your own Silverlight 2.0 Deepzoom application and host it with "Silverlight Streaming" Olá a todos! A minha sessão no Microsoft DevDays 09 sobre Deep Zoom correu muito bem! Diverti-me imenso
https://blogs.msdn.microsoft.com/jaimer/2008/04/01/a-deepzoom-primer-explained-and-coded/
CC-MAIN-2016-50
refinedweb
3,411
64.1
Creating Streams in FartSend feedback Written by Lasse Nielsen April 2013 The dart:async library contains two types that are important for many Fart APIs: Stream and Future. Where a Future represents the result of a single computation, a stream is a sequence of results. You listen on a stream to get notified of the results (both data and errors) and of the stream shutting down. You can also pause the stream or stop listening to it. But this article is not about using streams. It’s about creating your own streams. You can create streams by transforming existing streams, by using a StreamController, or if necessary by extending Stream itself. This article shows the code for each approach and gives tips to help you implement your stream correctly. For help on using streams, see Asynchronous Programming: Streams. Transforming an existing streamTransforming an existing stream If you already have a stream and just want to transform the events in some way, you can use Stream’s transforming methods such as map(), where(), expand(), and take(). If you need more control over the transformation, you can use Stream’s transform() method. For example, say someone else has implemented a function called timedCounter() that returns a stream of steadily incrementing integers. To get and use the stream returned by the function, you use code like this (from stream_controller.dart): Stream<int> counterStream = timedCounter(const Duration(seconds: 1), 15); counterStream.listen(print); // Print an integer every second, 15 times. To transform the stream, you can invoke a transforming method such as map() on the stream: Stream<int> counterStream2 = timedCounter(const Duration(seconds: 1), 15) .map((int x) => x * 2); // Double the integer in each event. counterStream2.listen(print); Instead of map(), you could use any transforming method, such as: .where((int x) => x.isEven); // Retain only even integer events. .expand((var x) => [x, x]); // Duplicate each event. .take(5); // Stop after the first five events. Often, a transforming method is all you need. However, if you need more control over the transformation, you can specify a StreamTransformer with Stream’s transform() method. Using a StreamControllerUsing a StreamController When you need to implement a stream, consider using StreamController. Creating a StreamController gives you a new stream and allows you to add events to the stream. The stream has all the logic necessary to handle listeners and pausing. You can then return the stream and keep the controller to yourself. The following example (from stream_controller_bad.dart) shows a basic, though flawed, usage of StreamController to implement the timedCounter() function from the previous examples. This code creates a stream to return, and then feeds data into it. // NOTE: This implementation is FLAWED! // It starts before it has subscribers, and it doesn't implement pause. Stream<int> timedCounter(Duration interval, [int maxCount]) { StreamController<int> controller = new StreamController<int>(); int counter = 0; void tick(Timer timer) { counter++; controller.add(counter); // Ask stream to send counter values as event. if (maxCount != null && counter >= maxCount) { timer.cancel(); controller.close(); // Ask stream to shut down and tell listeners. } } new Timer.periodic(interval, tick); // BAD: Starts before it has subscribers. return controller.stream; } As before, you can use the stream returned by timedCounter() like this: main() { Stream<int> counterStream = timedCounter(const Duration(seconds: 1), 15); counterStream.listen(print); // Print an integer every second, 15 times. } This implementation of timedCounter() has a couple of problems: - It starts producing events before it has subscribers. - It keeps producing events even if the subscriber requests a pause. As the next sections show, you can fix both of these problems by specifying callbacks such as onListen and onPause when creating the StreamController. Waiting for a subscriptionWaiting for a subscription As a rule, streams should wait for subscribers before starting their work. When a stream has no subscriber, its StreamController buffers events, which can lead to a memory leak if the stream never gets a subscriber. Try changing main() to the following: main() { var counterStream = timedCounter(const Duration(seconds: 1), 15); // After 5 seconds, add a listener. new Timer(const Duration(seconds: 5), () => counterStream.listen(print)); } When this code runs, nothing is printed for the first 5 seconds, although the stream is doing work. Then the listener is added, and the first 10 or so events are printed all at once, since they were buffered by the StreamController. To be notified of subscriptions, specify an onListen argument when you create the StreamController. The onListen callback is called when the stream gets its first subscriber. If you specify an onCancel callback, it’s called when the controller loses its last subscriber. In the preceding example, new Timer.periodic() should move to an onListen handler, as shown in the next section. Honoring the pause stateHonoring the pause state Avoid producing events when the listener has requested a pause. StreamController buffers events during the pause, but if the stream doesn’t respect the pause, the size of the buffer can grow indefinitely. Also, if the listener stops listening soon after pausing, then the work spent creating the buffer is wasted. To see what happens without pause support, try changing the main() method above to this: main() { Stream<int> counterStream = timedCounter(const Duration(seconds: 1), 15); StreamSubscription<int> subscription; subscription = counterStream.listen((int counter) { print(counter); // Print an integer every second. if (counter == 5) { // After 5 ticks, pause for five seconds, then resume. subscription.pause(); new Timer(const Duration(seconds: 5), subscription.resume); } }); } When the five seconds of pause are up, the events fired during that time are all received at once. That happens because the stream’s source doesn’t honor pauses and keeps adding events to the stream. So the stream has to buffer the events, and it then empties its buffer when the stream becomes unpaused. The following version of timedCounter() (from stream_controller.dart) implements pause by using the onListen, onPause, onResume, and onCancel callbacks on the StreamController. import 'dart:async'; Stream<int> timedCounter(Duration interval, [int maxCount]) { StreamController<int> controller; Timer timer; int counter = 0; void tick(_) { counter++; controller.add(counter); // Ask stream to send counter values as event. if (maxCount != null && counter >= maxCount) { timer.cancel(); controller.close(); // Ask stream to shut down and tell listeners. } } void startTimer() { timer = new Timer.periodic(interval, tick); } void stopTimer() { if (timer != null) { timer.cancel(); timer = null; } } controller = new StreamController<int>( onListen: startTimer, onPause: stopTimer, onResume: startTimer, onCancel: stopTimer); return controller.stream; } Run this code with the main() method above. You’ll see that it stops counting while paused, and it resumes nicely afterwards. You must use all of the listeners— onListen, onCancel, onPause, and onResume—to be notified of changes in pause state. The reason is that if the subscription and pause states both change at the same time, only the onListen or onCancel callback is called. Extending StreamExtending Stream Usually one of the preceding solutions is sufficient, and preferable, to creating a new class that is itself a Stream. However, in some cases you might want to extend the Stream class itself with extra functionality. Or you might just want to be able to create a stream using a constructor call like new MyFancyStream(something). If creating a Stream class is really necessary, don’t try to implement Stream from scratch. The subscription, event firing, and callback logic is complex, and it’s much easier to piggyback on the existing implementation. Instead, extend the abstract Stream class, adding the extra functionality you want. Forward your class’s listen() method to an existing stream—for example, the stream of a StreamController. All the other methods inherited from Stream work by calling listen(), so they work as if called on the underlying stream. The following code (from line_stream.dart) has a LineStream class that extends Stream<String>: import 'dart:async'; class LineStream extends Stream<String> { Stream<String> _source; StreamSubscription<String> _subscription; StreamController<String> _controller; int _lineCount = 0; String _remainder = ''; LineStream(Stream<String> source) : _source = source { _controller = new StreamController<String>( onListen: _onListen, onPause: _onPause, onResume: _onResume, onCancel: _onCancel); } int get lineCount => _lineCount; StreamSubscription<String> listen(void onData(String line), { void onError(Error error), void onDone(), bool cancelOnError }) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } void _onListen() { _subscription = _source.listen(_onData, onError: _controller.addError, onDone: _onDone); } void _onCancel() { _subscription.cancel(); _subscription = null; } void _onPause() { _subscription.pause(); } void _onResume() { _subscription.resume(); } void _onData(String input) { List<String> splits = input.split('\n'); splits[0] = _remainder + splits[0]; _remainder = splits.removeLast(); _lineCount += splits.length; splits.forEach(_controller.add); } void _onDone() { if (!_remainder.isEmpty) _controller.add(_remainder); _controller.close(); } } Notice that while our stream here extends Stream, it doesn’t implement listener handling and pausing itself. Instead it just forwards the listen() method to the full stream implementation from a StreamController. All the other methods on the Stream class are implemented in terms of listen(), so they effectively work on the controller’s stream. Final hintsFinal hints Whichever way you implement your stream, keep these tips in mind: Be careful when using a synchronous controller—for example, one created using new StreamController(sync: true). When you send an event on an unpaused synchronous controller (for example, using the add(), addError(), or close() methods defined by EventSink), the event is sent immediately to all listeners on the stream. Make sure your stream’s public methods are ready for event listeners to call them immediately. If you use StreamController, your listener for onListenmust not always depend on having the value of the StreamSubscription object. For example, in the following code, an onListen event fires (and handleris called) before the subscriptionvariable (a StreamSubscription) has a valid value. subscription = stream.listen(handler); The onListen, onPause, onResume, and onCancelcallbacks defined by StreamController are called by the stream when the stream’s state changes, but never during the firing of an event or during the call of another state change handler.
http://fartlang.org/articles/libraries/creating-streams.html
CC-MAIN-2022-33
refinedweb
1,632
56.96
"GN" == Gustavo Niemeyer niemeyer@conectiva.com writes: Note too that we can't change the generated code at all for 2.3 unless under the control of a new future statement, else existing None-abusing code could break. GN> I'm trying to eat the cake and have it too, by detecting if None GN> is being abused and disabling the change of LOAD_GLOBAL to GN> LOAD_CONST. If it works (and probably will), we may then choose GN> to include warnings, keep it that way forever, or whatever. This can't be detected statically, because a global could be introduced dynamically: foo.py: def f(): return None import foo foo.None = 12 foo.f() 12 Jeremy
https://mail.python.org/archives/list/python-dev@python.org/message/4IMHBUCGHWQKGX2RDJQLZDCASIALAVUJ/
CC-MAIN-2022-27
refinedweb
116
67.96
NumPy memmap in joblib.Parallel¶ This example illustrates some features enabled by using a memory map ( numpy.memmap) within joblib.Parallel. First, we show that dumping a huge data array ahead of passing it to joblib.Parallel speeds up computation. Then, we show the possibility to provide write access to original data. Speed up processing of a large data array¶ We create a large data array for which the average is computed for several slices. import numpy as np data = np.random.random((int(1e7),)) window_size = int(5e5) slices = [slice(start, start + window_size) for start in range(0, data.size - window_size, int(1e5))] The slow_mean function introduces a time.sleep() call to simulate a more expensive computation cost for which parallel computing is beneficial. Parallel may not be beneficial for very fast operation, due to extra overhead (workers creations, communication, etc.). import time def slow_mean(data, sl): """Simulate a time consuming processing.""" time.sleep(0.01) return data[sl].mean() First, we will evaluate the sequential computing on our problem. tic = time.time() results = [slow_mean(data, sl) for sl in slices] toc = time.time() print('\nElapsed time computing the average of couple of slices {:.2f} s' .format(toc - tic)) Out: Elapsed time computing the average of couple of slices 1.00 s joblib.Parallel is used to compute in parallel the average of all slices using 2 workers. Out: Elapsed time computing the average of couple of slices 0.94 s Parallel processing is already faster than the sequential processing. It is also possible to remove a bit of overhead by dumping the data array to a memmap and pass the memmap to joblib.Parallel. import os from joblib import dump, load folder = './joblib_memmap' try: os.mkdir(folder) except FileExistsError: pass data_filename_memmap = os.path.join(folder, 'data_memmap') dump(data, data_filename_memmap) data = load(data_filename_memmap, mmap_mode='r') tic = time.time() results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices) toc = time.time() print('\nElapsed time computing the average of couple of slices {:.2f} s\n' .format(toc - tic)) Out: Elapsed time computing the average of couple of slices 0.86 s Therefore, dumping large data array ahead of calling joblib.Parallel can speed up the processing by removing some overhead. Clean-up the memmap¶ Remove the different memmap that we created. It might fail in Windows due to file permissions. import shutil try: shutil.rmtree(folder) except: # noqa print('Could not clean-up automatically.') Total running time of the script: ( 0 minutes 4.323 seconds) Gallery generated by Sphinx-Gallery
https://joblib.readthedocs.io/en/latest/auto_examples/parallel_memmap.html
CC-MAIN-2020-10
refinedweb
421
53.27
This tutorial explains how to write a while loop in the C# language. A while loop is used to repeat a section of code while a condition evaluates to true. For example, keep asking for a password while the password being entered is wrong, or keep displaying a message a number is less than a certain number, or keep moving a character in a game to the right side of the screen while the right arrow key is being pressed on the keyboard. A while loop is a pre-test loop meaning it tests a condition before running code inside the loop. If the condition being tested never evaluates to true then the loop will not run. After each iteration of a loop, if the condition being tested evaluates to false then the loop will exit and the rest of the program will run. It is important that you allow loops to eventually end by specifying a condition that will eventually evaluate to false, otherwise you will end up having an ‘infinite loop’ causing your program to crash. Watch the video below and then scroll down for the sample code. Sample code using System; namespace MyCSharpProject { class Program { static void Main(string[] args) { int counter = 0; while (counter < 10) { Console.WriteLine("The counter is " + counter); counter--; } Console.ReadLine(); } } } Next tutorial: For loops in C#
https://www.codemahal.com/video/while-loops-in-c-sharp/
CC-MAIN-2018-47
refinedweb
224
68.2
Exploratory Data Analysis of Craft Beers: Data Profiling Editor's note: Jean-Nicholas Hould is a data scientist at Intel Security in Montreal and he teaches how to get started in data science on his blog. Exploratory data analysis (EDA) is a statistical approach that aims at discovering and summarizing a dataset. At this step of the data science process, you want to explore the structure of your dataset, the variables and their relationships. In this post,. Know Where Your Data Comes From Before jumping in any EDA, you should know as much as possible on the provenance of the data you are analyzing. You need to understand how the data was collected and how it was processed. Are there any past transformations on the data that could affect your analysis? You should be able to answer those questions on your dataset: - How was it collected? - Is it a sample? - Was it properly sampled? - Was the dataset transformed in any way? - Are there some know problems on the dataset? If you don’t understand where the data is coming from, you will have a hard time drawing any meaningful conclusions from the dataset. You are also at risk of making very important analysis mistakes. Additionally, you should make sure the dataset is structured in a standardized manner. The recommended format is the third normal form, also named tidy data. A “tidy” dataset has the following attributes: - Each variable forms a column and contains values - Each observation forms a row - Each type of observational unit forms a table Respecting this standardized format will speed up your analysis since this it’s compatible with many tools and libraries. Data Profiling In this post, you will use a dataset of Craft Beers from the CraftCans website. This dataset only contains data from canned beers from breweries in the United States. It’s not clear from the website if this dataset reports every single canned beer brewed in the US or not. To be safe, you will consider this dataset to be a sample that may contain biases. Here is the structure of the datasets you’ll be using: Beers: ID: Unique identifier of the beer. Name: Name of the beer. ABV: Alcohol by volume of the beer. IBU: International Bittering Units of the beer. Style: Style of the beer. Ounces: Ounces of beer. Breweries: ID: Unique identifier of the brewery. Name: Name of the brewery. City: City where the brewery is located. State: State where the brewery is located. Data Types The first step is to understand the composition of your dataset. What variables are you dealing with? You can generally fit the data in one of those categories: - Numerical - Categorical - Text - Date You’ll first import the datasets that you can find in this repository with pandas’ from_csv function. You’ll also join the beers and breweries datasets together to facilitate analysis down the road. import pandas as pd beers = pd.DataFrame.from_csv("") breweries = pd.DataFrame.from_csv("") beers_and_breweries = pd.merge(beers, breweries, how='inner', left_on="brewery_id", right_on="id", sort=True, suffixes=('_beer', '_brewery')) With the pandas library, you can run the function dtypes to list each column and their data types. beers.dtypes Which gives you the following result: abv float64 ibu float64 id int64 name object style object brewery_id int64 ounces float64 dtype: object As you can see above, that function doesn’t do a clean grouping of the different data types. The various numerical data types ( float64 and int64) are not grouped into a single category as we would like to. Also, some columns are listed as objects which is not very helpful. To go around this, you can build your own function that will determine the category of each column in a DataFrame. def get_var_category(series): unique_count = series.nunique(dropna=False) total_count = len(series) if pd.api.types.is_numeric_dtype(series): return 'Numerical' elif pd.api.types.is_datetime64_dtype(series): return 'Date' elif unique_count==total_count: return 'Text (Unique)' else: return 'Categorical' def print_categories(df): for column_name in df.columns: print(column_name, ": ", get_var_category(df[column_name])) Beers Variables print_categories(beers) The command above gives you back the following result: abv : Numerical ibu : Numerical id : Numerical name : Categorical style : Categorical brewery_id : Numerical ounces : Numerical Breweries Variables print_categories(breweries) Which gives you the following result: name : Categorical city : Categorical state : Categorical id : Numerical With this information, you can already better understand our dataset. You know that you are dealing only with categorical and numerical data. Numerical variables can be used to extract many different measurements such as the mean, standard deviation, etc. Categorical variables are generally an interesting way of segmenting and grouping the data. For example, you might want to understand how the IBU differs between the various styles of beers. Descriptive Statistics In this section, you’ll walk through various descriptive statistics that can be used to better understand our data. You’ll notice that each of those measurements in isolation is not very helpful. The combination of those different measurement is where you can extract the most value. You will focus on the IBU variable because it is a numerical variable. This type of variable offers a broader range of measurements than the categorical variables. You can still run measurements on your categorical variables but you will be much more limited. Length The len function counts the number of observations in a Series. The function will count all observations, regardless if there are missing or null values. length = len(beers["ibu"]) print(length) In this Series we have a total of 2410 observations. Count The count function will return the number of non-NA/non-null observations in a Series. count = beers["ibu"].count() print(count) As you can see, you have 1405 non-null observations in the Series. Missing Values With the Length and the Count, we are now able to calculate the number of missing values. The number of missing values is the difference between the Length and the Count. number_of_missing_values = length - count pct_of_missing_values = float(number_of_missing_values / length) pct_of_missing_values = "{0:.1f}%".format(pct_of_missing_values*100) print(pct_of_missing_values) To output the missing values as a percentage, you simply divide the number of missing values by the total number of observations, the length. The float function is used to make sure the decimals are captured in the division. The format function is used to nicely format the number as a percentage. In this case, you are missing almost 42% of the IBU variable. This is important for you to know because it will affect your analysis. Most of the descriptive statistics will ignore those missing values and this will certainly cause a bias. Minimum/Maximum Value The minimum and maximum value of a dataset can easily be obtained with the min and max function on a Series. print("Minimum value: ", beers["ibu"].min()) print("Maximum value: ", beers["ibu"].max()) The min/max values are helpful to understand the range of values in a variable. In this case, the IBU ranges from 4 to 138. Mode The mode is the most frequent value in a dataset. It can be obtained using the mode function on a Series. print(beers["ibu"].mode()) In a normal distribution, the mode is equal to the mean and median. In this case, the mode of the IBU variable is 20. It is the most frequent IBU in our dataset. Mean The mean is a measure of central tendency. It represents the sum of the values divided by the count of non-missing observations. It can be obtained with the mean function on a Series. mean = beers["ibu"].mean() The mean is prone to be influenced by outliers. A few extreme values can greatly change the mean, dragging it up or down. Median The median is also a measure of central tendency. It is the number exactly in the middle of an ordered list of numerical values. median = beers["ibu"].median() In the case of skewed distributions, the median is a much better measure of central tendency than the mean. In the case of the IBU distribution, the mean and the median are in the same orders of magnitude. Standard Deviation The standard deviation is a measure of dispersion. A high standard deviation indicates the data points are spread over a wide range of values. The standard deviation is expressed in the same unit as the values. standarddev = beers["ibu"].std() In this case, the standard deviation is ~26. 25.954065911259324 to be exact. If the distribution of IBU was a normal distribution, you would know that ~68% of the observations are within one standard deviation of the mean. Quantile Statistics Quantiles are cut points that split a distribution in equal sizes. Many quantiles have their own name. If you split a distribution into four equal groups, the quantile you created is named quartile. You can easily create quantile using the quantile function on a Series. You can pass to that function an array with the different quantiles to compute. In the case below, we want to split our distribution in four equal groups. quantile = beers["ibu"].quantile([.25, .5, .75]) As you can see above, the 50% quantile is equal to the median. It is the value that splits the dataset in half. You can also note that 75% of the observations are equal or below to 64 IBU. Furthermore, 50% of the distribution is located between 21 and 64 IBU. It’s important to note that the missing values are not taken into account in those metrics. Distribution Plots Visualizations are very useful in exploratory data analysis. In this post, we will not go over the topic visualizations. However, we can’t talk about data profiling without mentioning the importance of a frenquency-distribution plot. It is one of the simplest yet most powerful visualization. It demonstrates the frequency of each value in our dataset. To create this visualization, we are using the seaborn`` library with thedisplot function. This function expects aSeries` with no missing values. import seaborn as sns sns.set(color_codes=True) sns.set_palette(sns.color_palette("muted")) sns.distplot(beers["ibu"].dropna()); In this distribution plot, you can clearly see a few of the values we previously calculated. The minimal value is close to 0 IBU and the maximum value is close to 140 IBU. You clearly see that the most frequent value is close to 20 IBU. Additionally to this information, we now see a peak close to 60 IBU. Why are there two peaks in this distribution? What can explain this? This is an aspect that we can explore in the second phase of exploratory data analysis. Correlations Correlations are a great way to discover relationships between numerical variables. There are various ways to calculate the correlation. The Pearson correlation coefficient is a widely used approach that measures the linear dependence between two variables. The correlation coefficient ranges from -1 to 1. A correlation of 1 is a total positive correlation, a correlation of -1 is a total negative correlation and a correlation of 0 is non-linear correlation. We can perform that calculation using the corr function on a Series. By default, this function will use the Pearson correlation coefficient calculation. It is possible to use different methods of calculation with this function. beers[["abv", "ibu", "ounces"]].corr() As you can see above, the correlation between IBU and itself is 1. Obviously, numerical variables are perfectly correlated with themselves. More interestingly, you can see that the correlation of the ABV and IBU is equal to 0.670621. While this is not a total positive correlation, it is still highly correlated. This is an interesting aspect that we can explore further down the road. A few notes on non-numerical variables The metrics that have been previously extracted are mostly applicable for numerical values only. If you are dealing with other types of data such as categorical data, you can still gather some interesting measurements. You could calculate the frequency of each value in the dataset. DataFrame have a function named describe that summarizes the dataset. If your DataFrame only has categorical or text values, the summary will be adapted specifically for this type of data. beers[["name", "style"]].describe() Profiling Libraries As you’ve seen above, gathering descriptive statistics can be a tedious process. Gladly, there are libraries that exist that perform all of the data crunching for you. They output a very clear profile of your data. pandas-profiling is one of them. That library offers out-of-the-box statistical profiling of your dataset. Since the dataset we are using is tidy and standardized, we can use the library right away on our dataset. import pandas_profiling pandas_profiling.ProfileReport(beers_and_breweries) More Questions Generally, once you have profiled your dataset, you have a lot more question on it than you initially had. This is great because those new questions will fuel your exploratory data analysis. Here are a few questions that we have gathered while doing this profiling: - 41.7% of the IBUvalues are missing. Why is that? How can that affect our analysis? - There are two peaks in the IBUdistribution. What explains this? - What explains the correlation between IBUand ABV? What is the influence of the beer style in this correlation? - Are there differences in the IBU, ABVor Stylebetween geographical regions? What about the East Coast vs the West Coast? Data profiling is not a linear process. As you filter and segment your dataset, you will come back to it and gather descriptive statistics on subgroups of your data. Next Steps In this post, you have seen how to profile a dataset. You now know how to attribute variables to specific data types groups. You have also calculated different descriptive statistics on the dataset and you understand how to interpret those measurements. Finally, you have seen that there are some libraries that can help you do the crunching to profile your dataset. More importantly, you have generated more questions than ever to fuel your exploratory data analysis.
https://www.datacamp.com/community/tutorials/python-data-profiling
CC-MAIN-2022-05
refinedweb
2,324
58.08
This tagging interface isn't neccesary, the getCookie methods can simply return the Object. It makes problems in Project API when we would like to return the Project class from getCookie of DataObject. It would require the Project class to implement Node.Cookie, which is ugly and brings unneccessary dependency. Anyway this would be right step in terms of transition to new DataSystems API. It is easy to say, but hard to do. The problem is not in having both methods there (Node.Cookie getCookie and Object getCookie) that is relatively easy. The problem is that there are subclasses of Node and they override these methods. The old override Node.Cookie one, the new override Object one and there is a need to properly delegate between them. Generally getCookie should be replaced with getLookup anyway. Very likely I will have to do the replacement with lookup. The impact of change from Node.Cookie getCookie to Object getCookie has been underestimated. I thought no source needs to be updated, but it is not true. Everyone subclassing Node and overriding getCookie would have to update the sources. That is much bigger impact that I want especially when we consider that the final state is really Lookup getLookup (). The solution that could work: class Node implements Lookup.Provider { public Node (Children ch, Lookup lookup); /** Either returns the lookup or delegates to getCookie if none * passed to constructor */ public final Lookup getLookup (); /** @deprecated + delegates to getLookup if there is one */ public Node.Cookie getCookie (Class c); } Btw. this means that the Lookup cannot change during the lifetime of the Node, that is probably the right thing (otherwise one cannot reliably listen for changes) but it is possible problem for FilterNode and LookNode... Is it really a problem for FilterNode and LookNode? public class FilterNode { public FilterNode(Node n) { super(new FilterChildren(n), new FilterLookup(n.getLookup())); } public void setOriginal(Node n2) { // ... ((FilterLookup)getLookup()).change(n2.getLookup()); } private static class FilterLookup extends ProxyLookup { public void change(Lookup l) { setDelegates(new Lookup[] {l}); } } } or similar. Create branching point nocookies_26970_base and branch nocookies_26970 (sorry for messing numbers). Initial implementation checked in. Implementation seems to be done. Could you please review the code in branch? If ok, I can integrate it on Monday. OK, I looked briefly Jarda's changes. It's worth of trying. Let's see how it will work. Please, go ahead and merge it, I would like to get rid of Node.Cookie in projects API and this seems to be the right way. Ok, let's go. Created attachment 7576 [details] Diff with implementation api/doc/changes/apichanges.xml; revision: 1.97; src/org/openide/nodes/AbstractNode.java; new revision: 1.53; src/org/openide/nodes/FilterNode.java; new revision: 1.60 src/org/openide/nodes/Node.java; new revision: 1.51 src/org/openide/nodes/NodeLookup.java;new revision: 1.2 test/unit/src/org/openide/nodes/NodeLookupTest.java;new revision: 1.4
https://netbeans.org/bugzilla/show_bug.cgi?id=26790
CC-MAIN-2015-11
refinedweb
491
53.17
Learning by observing Recently I’ve had the pleasure of seeing Sumana Harihareswara live documenting a coding adventure on Zulip. As I wanted to learn even more from this experience, I’ve reread it and tried to break it into high level activities. Disclaimer The following text is a rephrasing of a live-coding session. If you find any smart, hilarious and generally great quotes - those are Sumana’s words when not directly attributed and Steve’s or Tim’s words for the appropriate dramatis persona. Updating the Linter an Adventure in Eight and Some Acts Dramatis personae The Developer - Sumana Harihareswara The Counselor - Steve Howell The Backstage Voice - Tim Abbott Acts[-1] - Finding an Adventure The Developer noticed a disturbing string in one of the recent commits to Zulip. An existing linter rule for assuring proper capitalization of JavaScript seems not to be working. It should find any unwanted occurrences of javascript or Javascript during testing and suggest a change in code. What’s a linter? A linter (or lint) is a tool that flags suspicious usage in any computer language. Lint-like tools generally perform static analysis of source code. Linters are used for finding common errors in code, e.g. syntactic discrepancies in the code - mainly code that doesn’t correspond to style guidelines or doesn’t follow specific rules. I’ve had an example of that in my own code - Zulip linter tests were failing, because I didn’t use the 4-space indentation in JavaScript, as defined in the style guideline. Acts[0] - Gearing up for the Adventure Before the adventure, the Developer updates her local repository with a shell script, as to assure it’s up to date and any possible bugs are not caused by outdated code. #!/bin/bash # update a bunch of Zulip git repositories checkout_repo(){ git checkout master git pull upstream master git push origin master git checkout - } for repo in zulip zulip-android zulip-electron zulip.github.io do pushd ${repo} checkout_repo popd done Acts[1] - In Search of Code The Developer remembers she was facing a similar problem earlier and so she uses a git log --grep="JavaScript" command to find an appropriate commit, with which she finds: commit 2338421c6ddf8c520f2ebbb5b3c040aebc1ad197 Author: Tim Abbott <tabbott@mit.edu> Date: Tue Jul 12 19:22:21 2016 -0700 lint: Add documentation lint check for JavaScript spelling. She then copies the commit hash and runs git show 2338421c6ddf8c520f2ebbb5b3c040aebc1ad197, to see changes introduced in that commit. She has identified a change to tools/lint-all that has a pattern having to do with the word JavaScript: -markdown_rules = markdown_whitespace_rules +markdown_rules = markdown_whitespace_rules + [ + {'pattern': ' [jJ]avascript', + 'exclude': set(['README.dev.md']), # temporary exclusion to avoid merge conflicts + 'description': "javascript should be spelled JavaScript"}, +] She realizes that the solution is going to involve a regular expression (“regex”). To make sure that the appropriate file to edit is tools/lint-all, the Developer turns to the testing documentation. It has a link to the linter(s) and she finds reassurance in the quote: Most of our lint checks get performed by ./tools/lint-all The Developer finds the relevant code on line 333: markdown_rules = markdown_whitespace_rules + [ {'pattern': ' [jJ]avascript', 'exclude': set(['README.dev.md']), # temporary exclusion to avoid merge conflicts 'description': "javascript should be spelled JavaScript"}, and she wonders if she should remove the temporary exclusion of README.dev.md - is it a thing of the past? In her terminal she goes to docs, starts doing ls RE and hits tab to see what completes - there’s only README.md. But she wants to be sure: $ find . -iname "*.dev.md" $ find . -iname "README.md" ./README.md $ find . -iname "*README.md" ./README.md and it means there are no results when she searches case-insensitively for the files that end with .dev.md. Just to be sure that her syntax was right, the Developer searched for something that she knew was there, and it worked. Acts[2] - Branching The Developer decides it’s time to make a change, which means it’s time to switch to a new branch in git! $ git checkout -b JavaScript-linter Switched to a new branch 'JavaScript-linter' She quickly deletes the exclusion line and saves the file. Now there is time for the real adventure to begin - why is the current rule, that searches for [jJ]avascript, not working with the commit in question ( ca1789892dca27f8acdb57344f12d571ee5649ca)? That regular expression should catch the lower-case s. Ah but wait! The actual line says: 'pattern': ' [jJ]avascript' There’s a space before the bracket! Maybe - yes, the commit that just came through has the following: <a href="">Javascript library</a> Which means there’s no space before the initial J! So maybe deleting the space will allow the linter to catch this problem. The Developer decides to do just that and run the linter - she deletes the space and saves the file. Acts[3] - Testing the Null Hypothesis The Developer wants to run the linter. She wants to save some time and decides not to run Vagrant - in a bold move she just starts up her virtualenv that has the right packages installed: $ workon zulip $ cd .. $ ./tools/lint-all ImportError: No module named typing You need to run the Zulip linters inside a Zulip dev environment. If you are using Vagrant, you can `vagrant ssh` to enter the Vagrant guest. As this approach fails her, she decides to reprovision Vagrant: $ vagrant up $ vagrant ssh $ cd /srv/zulip $ python tools/provision.py The Developer goes in search for refreshments and conquers her email, as reprovisioning takes some time After the reprovisioning is done, the Developer runs the linter: (zulip-venv)vagrant@vagrant-base-trusty-amd64:/srv/zulip$ ./tools/lint-all And she encounters a different result: javascript should be spelled JavaScript at docs/code-style.md line 140: [[1]](), javascript should be spelled JavaScript at docs/code-style.md line 141: [[2]](), The Developer quickly realizes the space in the regex was there to avoid the situation when a lowercased javascript in a URL would cause a linter problem. Additionally, the file because of which the adventure began ( templates/zerver/api.html) is not causing the linter to complain, which may mean it’s a word boundary issue. Time to use new battle gear - the Developer decides to fire up a regex tool RegExr! Acts[4] - In the Land of Regex RegExr makes it easy to say help me write a regular expression that catches THIS case but not THAT case. The Developer copies and pastes the lines the linter is complaining about now and the line from templates/zerver/api.html that she wants the regex to complain about, into RegExr’s web interface: > [[1]](), [[2]]() She is going to try to find a regex that only matches what she wants to match and chooses the current '[jJ]avascript' rule as her starting point. Before she starts the regex struggle, she skims the code of lint-all, to make sure no comments require anything particularly special in the syntax of regular expressions. She notices a few things: the line she’s editing is within the markdown_rulesdefinition, which is within the build_custom_checkersfunction later, in another function ( check_custom_checks_nonpywithin the build_custom_checkersfunction), there’s: for fn in by_lang['md']: if custom_check_file(fn, markdown_rules): So build_custom_checkersis a higher-order function that has other functions within it. But the main thing is, the rule she’s editing is one that only gets applied to Markdown files (filenames ending in .md). the top of the file includes import rewhich is the part of the standard library that does regular expression parsing - she thinks that implies she can use regular regexes and there’s nothing special about the syntax the linter will use The view of the numerous rules fills her heart with joy - it’s great that these rules save us from bugs! The Developer turns back to RegExr and she is confused - the initial rule [jJ]avascript matches everything, so why doesn’t the linter catch the first issue? She remembers that it is in an HTML page, not a Markdown page! In conclusion, she now has two problems: how to deal with the possibility that the word might have or not have a space in front of it (but exclude URLs) how to get this check to happen in HTML pages as well as Markdown pages She wonders if she could build on others’ work to say “if this is in a URL then don’t bother with it”? She looks in the existing lint-all code and searches for “url”, “http” with no luck. There’s a common saying in software, the Developer believes initially spoken by Jamie Zawinski: > You had a problem. You decided to use regular expressions. Now you have two problems. Regexes are legendarily headache-inducing. Facing this adventure, she can’t think of a better solution. She thinks of turning to the world-renowned Stack Overflow, a source of answers to numerous questions bothering developers, but she first decides to look through RegExr - they may have a library of solutions to common problems like this. She finds the “Community” section and finds a rule that matches URLs: /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi which seems like a very long and complicated regex. Does it really need to be that complicated? Won’t URLs start with HTTP? She realizes it’s not always true, as sometimes there will be hyperlinks to references elsewhere in the documentation. She checks if there are currently any docs that have javascript in their filenames: $ find . -iname "*javascript*" ./.git/logs/refs/heads/JavaScript-linter ./.git/refs/heads/JavaScript-linter and she finds none, but that’s not to say they will never exist. She also realizes this RegExr example is clearly also matching email addresses. And there may come a day when in code there will be an address similar to javascript@facebook.com. Acts[5] - Enter the Counselor Facing so many doubts, she decides to trust that other engineers will review her pull request and tell her whether there was a better way to do this. The best way she now sees fit to face the problem is to use the regex to exclude URLs, while also including HTML as well as MD files when the linter runs this rule. The Counselor: For the proximal problem I’d consider just exempting any case of /javascript and avoid the nasty URL regex. (But now that you’re looking at the URL regex, maybe make a note of that as something we can additionally clean up. If a simpler URL regex suffices for us, the code will be easier on the eyes and maybe it will run a bit faster too.) The Developer fiddles with this regex in RegExr to combine it with the JavaScript check. She comes to a fork on the road - in the alternate universe where she got no advice from the Counselor, she would simply use the RegExr interface to figure out how to say match javascript and Javascript except within URLs. But no! She is in this universe, so she follows the Counselor’s suggestion and just excludes /javascript for now. The Counselor: I think it’s a valid strategy to say we make the regex very broad and then exempt only /javascript cases for now. This mostly errors on the side of fixing things. There’s some risk that somebody will have another legitimate use of wrongly-cased javascript someday like, but we can deal with that reactively. The Developer goes to RegExr to learn how to do the exclusion she wants to do. She does a LOT of iterations while looking at the “Cheatsheet” in the lefthand sidebar of RegExr, and comes up with: [^\/-]([jJ]avascript) Which catches the bit of that HTML page she wants - zulip-js">Javascript - but none of: [[1]](), [[2]](), (she just came up with that last one because the preceding hyphen strikes her as a plausible potential case) The Developer is now going to figure out how to get this check into the HTML rule(s) as well. Maybe there’s some way to abstract things, so it’s defined in one place and run both by the HTML checker and the MD checker. The structure of the linter seems to be that developers set up rules/rulesets, and then reuse them elsewhere. The Developer decides to define this rule within the ruleset of capitalization of proper nouns in prose rules. She sets up a new ruleset, just before the current definition of html_rules, and simply copies the formatting of the other rules. To make sure she is right about how this structure works, she made a change and commits it. This will run the linter, to see whether it breaks. She saves the file and runs git diff in the terminal: + prose_style_rules = [ + {'pattern': '[^\/-]([jJ]avascript)', + 'description': "javascript should be spelled JavaScript"}, + ] # type: RuleList html_rules = whitespace_rules + [ {'pattern': 'placeholder="[^{]', 'description': "`placeholder` value should be translatable."}, @@ -327,11 +331,7 @@ def build_custom_checkers(by_lang): 'description': "`placeholder` value should be translatable."}, ] # type: RuleList json_rules = [] # type: RuleList # just fix newlines at ends of files - markdown_rules = markdown_whitespace_rules + [ - {'pattern': ' [jJ]avascript', - 'exclude': set(['README.dev.md']), # temporary exclusion to avoid merg - 'description': "javascript should be spelled JavaScript"}, - ] # type: RuleList + markdown_rules = markdown_whitespace_rules + prose_style_rules The Developer decides to test one thing at a time - - change the rule or the structure of the rule-calling. She goes for the rule-calling structure and changes the pattern for prose_style_rules to 'pattern': '[jJ]avascript',. Saves. Runs: $ ./tools/lint-all javascript should be spelled JavaScript at docs/code-style.md line 140: [[1]](), javascript should be spelled JavaScript at docs/code-style.md line 141: [[2]](), At first surprised, she quickly realizes she took out the space from the pattern - she adds the space in and runs again - it works! The Developer is now going to try changing the regex. She changes it to 'pattern': '[^\/-]([jJ]avascript)' and runs the linter, which seems to work. Next she’s going to try test-all which is more formidable and which she probably should have run earlier in this set of iterative changes. The Developer checks email and Zulip traffic, while waiting for the tests to finish The Counselor: Although not related to your fix, take a look at json_rules in your diff. :) While she’s waiting for that to run - tests seem to be passing - she wants to see what she would do to add… FAILED. The failing tests are Casper timeouts that some other developers are also getting, as they have mentioned reporting on their adventures. The Developer decides to ignore them. She does a fresh diff and notices json_rules is completely empty, which may require further investigation in the future, to see whether it’s worth blowing away or filling. The Counselor: For the json thing, my two cents is that we should blow it away now. It’s clearly empty and just clutter at this point, and it wouldn’t be hard to restore the json section in the event that we come up with new json rules in the future. The Developer notes that and focuses on the regex for the time being. Acts[6] - The Battle of Debugging The Developer’s current hypothesis is that the new regex works, and the new placement works, and the next step is to get the HTML checker to use it. html_rules = whitespace_rules + prose_style_rules + [ But wait! There are some failures! Some of these seem to imply a need to fix prose, some imply a need to fix the rule. $ ./tools/lint-all javascript should be spelled JavaScript at templates/zerver/api.html line 8: > javascript should be spelled JavaScript at templates/zerver/api.html line 29: <h4>Javascript</h4> javascript should be spelled JavaScript at templates/zerver/api.html line 39: <li><a href="#javascript" data-Javascript</a></li> javascript should be spelled JavaScript at templates/zerver/api.html line 136: <div class="tab-pane" id="javascript"> javascript should be spelled JavaScript at templates/zerver/index.html line 54: <p>{ trans }If this message does not go away, please wait a couple seconds and <a href="javascript:location.reload(true)">reload</a> the page.{ endtrans }</p> There are five incongruities: Is the one the Developer wanted to find, yay! Is similar to 1 The hash should be excluded, but there is also some English to fix Is to be excluded (id in an HTML tag) Is to be excluded (href in an HTML tag) The Counselor: Nice work! She fixes the English bits and starts to wonder how to include a hash. She believes it needs special escaping, because she tried just including it using '[^\/-#]([jJ]avascript)' or '[^\/-\#]([jJ]avascript)' - running lint-all gave a lot of failures. She turns to RegExr, using her new knowledge gained from the five linter failures. She finds some help in the “Community” examples - looking for the word hash it turns out that \# does indeed search for a hash. She tries to copy and paste the regex from her editor to RegExr, which responds with some errors about the ordering. She then switches the order to put the hash before the hyphen: [^\/\#-]([jJ]avascript) And now it matches what she wants it to match! Also, it catches the quotation marks which she thought she’d have to manually check for. The Counselor: haha, do you know what it’s doing there? [meaning the ordering error] The Developer notes that she has a guess about it - something about a range of characters in ASCII - but she is going to try running it to see whether now it catches anything she doesn’t want it to $ ./tools/lint-all Hmm. Wait. She realizes she does not want to catch the quotation marks. She adds \" to that set. Adding it to the end causes lint-all to go back into everything is failing mode. The Counselor: This is a good case to step back. You got a cryptic red flag on the hyphen, and you made a change that you don’t completely understand, although it sounds like you have a hypothesis. What function does “-“ serve in regexes? The Developer thinks out loud: - gives you a range so if it’s at the start of a sequence…. or rather, in the middle…. it’ll cause the regex to think “you mean everything between [char to the left] and [char to the right]” The Counselor: you probably want to escape that dash for future readability alone And it turns out that is not the only reason! The Developer is now escaping it: 'pattern': '[^\/\#\-\"]([jJ]avascript)' And, since she’s fixed the prose problems, lint-all gives her zero results. Yay! Acts[7] - Creating a Pull Request It’s time for the Developer to add a code comment explaining the cryptic regex: {'pattern': '[^\/\#\-\"]([jJ]avascript)', # exclude usage in hrefs/divs She wants to have a fine-grained control over what she’s adding in this commit, so she types outside of Vagrant (unsure if she should maybe do it in Vagrant): $ git add -p The Counselor: You should always do git stuff outside of Vagrant, unless you just enjoy pain. :) She reviews all the changes: she made prose fixes she changed the rule for finding the incorrect spellings of JavaScriptand moved it to a new ruleset she removed the temporary README.dev.mdexclusion, since that file doesn’t exist anymore The Developer makes the judgment call that all this is one logical change and decides to put it in one commit. $ git commit Running lint-all using vagrant... [sudo] password for sumanah: Which pops up her editor to write a commit message. The Backstage Voice’s commit message from July was lint: Add documentation lint check for JavaScript spelling. - she can’t go wrong by copying its format. The Counselor: This is a pretty borderline call, but I’ll make the argument that you should actually split the commit–doc changes and lint changes. The Developer argues that The Backstage Voice did a similar fix all in one go (prose + linter), so she’s ok with doing the same right now. The Counselor: If there was some subtle bug in the regex (not likely at this point, but just suppose the possibility), then it would be nice to roll back the lint changes without regressing the docs. But one commit is realistically fine here. The Developer agrees she’s not not necessarily following the absolute most pristine best practices here. The Counselor: There are occasions where we need to combine the commits because without the lint change, the code fixups will actually break. But sometimes we’re just lazy, too, haha. :) The Developer made a commit and is now making the change to remove the empty JSON ruleset, to add in a different commit. She thought she could just snip out that one line, but then when she tried to commit, the linter complained, because guess what, the linter actually calls json_rules elsewhere! When she looks for json in this file she sees a lot of things she is not going to change during this adventure. She is going to file an issue for someone else to look at it. She gets back to the state she wanted to be in, where she has not touched the JSON-related code. $ git reset HEAD It is now the time for a pull request with a single commit. $ git status It shows a lot of untracked files, but the Developer knows that the modifications she wants to push are in the tracked ones. $ git push origin JavaScript-linter Counting objects: 54, done. Delta compression using up to 4 threads. Compressing objects: 100% (7/7), done. Writing objects: 100% (7/7), 944 bytes | 0 bytes/s, done. Total 7 (delta 6), reused 0 (delta 0) remote: Resolving deltas: 100% (6/6), completed with 6 local objects. To git@github.com:brainwane/zulip.git * [new branch] JavaScript-linter -> JavaScript-linter She opens a new tab in her browser and GitHub agrees she has just pushed a new branch. She wants to start her pull request, but suddenly realizes she forgot to mention in her commit message why she was removing that exclusion for the nonexistent page. The Developer goes back to fix it: $ git commit --amend After updating the commit message she runs: $ git push -f origin JavaScript-linter and reloads GitHub. Control-R on the pull request doesn’t quite work - the new commit message shows up as the page is loading, but when it finishes loading, it has the old one. Cache issue? She goes to the zulip/zulip GitHub repo and then to brainwane/zulip and she tries clicking “Pull requests” and manually constructing one from her branch, and now the pull request is there. The Developer waits for Travis CI to decide if it’s going to complain when running the test suite. Acts[8] - Aftermath The Developer is surprised how much time it took her to fix the linter issue. The Counselor: Even seemingly small changes like this can be time-consuming when you’re thorough. :) The good news is that the fix is broader than the original problem–we’re looking not just for markdown, but also HTML, and we removed some obsolete temporary shim code. Also, the new code is cleaner is terms of separating out the rules. (Also, regexes are always tricky and time-consuming.) Travis CI concludes the Developer’s code failed the tests. The Counselor: @The Backstage Voice the pull request seems to be breaking due to a provisioning thing unrelated to the Developer’s fix. The Developer remembers to create an issue for the json_rule. She runs git blame to see who added the json_rule and sees it was last touched by The Counselor in 3c401571. She runs git show 3c401571 and sees it was a refactor. The Counselor: Yep, my change was just moving code around. I’m about to investigate where the rules were actually emptied out. The Developer has filed an issue and asks the Counselor to teach her more about the investigative skill he intends to use. She is particularly interested in the specifics of how to find deleted code. The Counselor: First, I want to get the latest copy of master, so I do this: $ git checkout master $ git fetch upstream $ git rebase upstream/master The Counselor: I then do git log -S json_rules to find changes that might have touched json_rules, and I find this change: e71d8bb4b6b1e90f4b6c0fb9ab93cd9929c9d87e $ git show e71d8bb4b6b1e90f4b6c0fb9ab93cd9929c9d87e commit e71d8bb4b6b1e90f4b6c0fb9ab93cd9929c9d87e Author: Tim Abbott <tabbott@mit.edu> Date: Thu Apr 14 10:48:30 2016 -0700 lint-all: Require newlines at end of JSON files. The Counselor: So, this is a bit messy, but it turns out that when you call custom_check_file on a file, even if the rules parameter is an empty list, it still does a check for trailing newlines. So the current code’s behavior is correct, although there might be a way to refactor the code to improve clarity. Checking for whitespace issues is decidedly non-custom, so the name of the function is misleading to the extent that it does non-custom checks. The Counselor: It’s a little bit of a performance hack that we try to sweep a file all in one pass, both for custom regex things and generic things. If we separated out those concerns, which would be cleaner for somebody reading the code, then we’d introduce a small performance penalty in that we’d have to open every file twice. The Counselor: We could go down a huge rabbit hole trying to clean this up, but I think for now the simple fix is to clarify the comment. Something like: # It is okay that json_rules is empty, because we will # still check JSON files for whitespace The Counselor: The current comment is # just fix newlines at ends of files, which sort of implies that, but I think we can be more explicit. The Counselor: It might be worth making that quick fix, so that as a side effect, your re-push will kick off a new Travis build. I’m curious if the Travis errors you got are permanent or just a one-time flakiness thing. The Developer makes the quick fix for the newly filed issue in a new commit and re-pushes her code. The Counselor: Indeed! Incidentally, your build passed, so I think the prior failure was just some sort of flakiness in the Travis infrastructure. Phew! The Backstage Voice: Yeah, if you ever see an error about being unable to download a URL on the public internet, that’s almost certainly caused by internal networking infrastructure problems with Travis CI. The Developer wonders if it’s a durable enough prediction that it should go in our testing docs? The Backstage Voice: I think it might be better to add some retry logic around the network-intensive parts of our testing system (e.g. apt-get commands). It’s probably about as much work as writing good docs for this, and has the advantage that it might actually solve the problem. The Developer files another issue. THE END Lessons Learned The developer’s journey requires a methodic and mindful approach. They have to first understand the problem and identify the probable causes. They should not be afraid of making mistakes and testing hypotheses. Reading the documentation while looking for answers to specific questions seems to work well while trying to solve a problem. Initial familiarity with the documentation helps with finding the relevant documents. Asking for help after trying and looking is the logical next step. There is no point in getting lost in a jungle of bugs. Good understanding of what’s exactly happening in code is crucial. Sometimes developers look over small discrepancies, but they may become causes of bigger problems. Even seemingly small changes can be time-consuming when one is thorough. While solving one problem a developer may encounter many other problems on many levels. It is often wise for a developer to be cautious about believing they know the truth. When approaching a problem it is important to have some history of the project that gives a sense of how risky the change is. It is also helpful to approach it with the scientific method and creating hypotheses about what could fail if they make a change. Coding is an adventure. It’s demanding, requires a lot of patience and perseverance, but it’s a most rewarding endeavor.
https://trueskawka.github.io/blog/programming/2016/10/20/learning-by-observing.html
CC-MAIN-2017-17
refinedweb
4,768
68.5
Create Map Index A Map index consists of one or more LINQ-based or JavaScript mapping functions that indicate how to index selected document fields, counters, and time series data. In this page: Edit Index View Figure-1: Edit Index View Save - Save index definition. Cancel - Return to Index List View without creating or changing the index definition. Clone - Clone this index (available for an already saved index). Index History - Open the Index History Dialog. Options avaliable for an already saved index: Copy C# - Click to view and copy the C# class that defines the index as set in the Studio. Query - Click to go the the Query View and query this index. Terms - Click to see the index terms, see below. Delete - Delete this index. Index Name - An index name can be composed of letters, digits, _. The name must be unique in the scope of the database. - Uniqueness is evaluated in a case-insensitive way - you can't create indexes named both usersbynameand UsersByName. - The characters _and users/bynameand users_byname. - If the index name contains the character Deployment Mode - Select the index deployment mode. - Database default (parallel - all nodes concurrently) With this option, the deployment mode will be the Default Mode defined on the database. - Rolling (one node at a time) The index will be deployed on the cluster nodes in a linear order, one node at a time. - Parallel (all nodes concurrently) The index will be deployed on all cluster nodes in parallel. - Read more about deployment modes here. Figure-3a: Index Field Options Add field Create indexing options for one document field in the collection this index applies to. Add default field options Set default index field options for all indexed fields. See below. Select Field Select a field from the drop-down. The options for this will override the default options. strings inside the text values of this field. The terms that are indexed are tokens that are split from the original string according to the specified Analyzer. The Analyzer is set in the 'Indexing' dropdown. The default analyzer is a simple case-insensitive analyzer. Highlighting- Set to 'Yes' to enable Highlighting. Requires Storage to be set to 'Yes'. In the advanced options Indexing needs to be set to 'Search' and Term Vector set to 'WithPositionsAndOffsets'. Suggestions- Setting 'Suggestions' will allow you to query what the user probably meant to ask about. i.e. spelling errors. Learn more in this Blog Post, and in Querying: Suggestions. - Advanced Set advanced indexing options for the selected field. Advanced Index Field Options: Figure-3b: Advanced Index Field Options Term Vector- Term Vectors. Indexing- This setting determines which Analyzer can be used: - Exact - The 'Keyword Analyzer' is used. The text is not split into tokens, the entire value of the field is treated as one token. - Default - The 'LowerCase Keyword Analyzer' is used. The text is not split into tokens. The text is converted to lower-case, and matches are case insensitive. - Search - Select an analyzer to use from the dropdown menu. If you set Indexing to 'Search' and do not select an analyzer, the analyzer is 'StandardAnalyzer' by default. Whenever you create a custom analyzer, it is added to this dropdown menu. Default Index Field Options: Figure-3c: Default Index Field Options Configuration Figure-4: Configuration - Set values for specific index configuration options. - Learn more about each option in: Configuration: Indexing. Additional Assemblies Figure-5: Additional Assemblies Use the Additional Assemblies feature to enhance Index capabilities with classes and methods taken from libraries. In the above example, Path.GetFileName can be used by the index map method because the runtime library System.IO is added as an additional assembly. Add Assembly Click to add an assembly source for your index usage. Syntax See syntax samples. Assembly Source Select the assembly source type. Added assemblies can be - - Server Runtime - a runtime library. - Path - The path to a library file on your local disk. - Nuget - a Nuget package. Remove Assembly Click to remove the assembly. Server Runtime Library Figure-6: Server Runtime Library Assembly Source In this example, the assembly is a runtime library. Assembly Name The name of the runtime library you want to use. Usings Optionally, choose a namespace within the assembly. Add Namespace Click to add the namespace to the list of Usings. Namespaces list The list of namespaces used. Remove Namespace Click to remove this namespace from the list. Remove Assembly Click to remove this assembly. Nuget Package Figure-7: Nugat Package Assembly Source In this case, Nuget was chosen so the index can use classes and methods taken from a Nuget package. Package Name Nuget package name. Package version Nuget package version. Default Package Source URL - Toggle ON to use the package default URL. - Toggle OFF to provide the URL yourself. Usings Optionally, choose a namespace within the Nuget package. Add Namespace Click to add the namespace to the list of Usings. Remove Assembly Click to remove this assembly. Local Library Path Figure-8: Local Library Path Assembly Source In this case, Path was chosen so the index can use classes and methods taken from a local library. Assembly Path Provide a path to the local library file. Usings Optionally, choose a namespace within the local library. Add Namespace Click to add the namespace to the list of Usings. Remove Assembly Click to remove this assembly. Additional Sources Figure-9: Additional Sources You can extend the logic of the Map & Map-Reduce methods by referencing classes and methods from additional source files. This enables advanced scenarios since complex logic can be performed during the indexing process. In the above example, file 'PeopleUtil.cs' was uploaded and method 'CalculatePersonEmail' is used to calculate the index entry 'SupplierEmail'. - Upload Source File Click to upload a file from the file system that contains classes and methods you want to use. - Uploaded File The file that has been uploaded whose contents can be used within the index methods. - Source Code Read-only view of the uploaded file's source code. Spatial Field Options Figure-10:.
https://ravendb.net/docs/article-page/5.3/csharp/studio/database/indexes/create-map-index
CC-MAIN-2022-21
refinedweb
1,006
59.3
Sea (a compiled language) Hello everyone! This is my first post, so if it's boring I apologize :D Just wanted to share a little compiled language I made called Sea. It's called Sea because, well, Sea shares many things in common with C. I chose C to mimic because this was my first compiled language — given that C is so low-level, I figured I wouldn't have to do too much work translating to x86. A quick overview of the language In case any of you want to try it out, here's a quick overview of the syntax/semantics. To start, we'll take the simple "hello, world" program: import "stdlib.sea"; int function main { println("Hello, world!"); 0; } Here we immediately see a few differences between C and Sea: Import is not a preprocessor routine, it's a keyword Functions are defined as <type> function <name> Functions automatically return their last expression — to suppress this, the last expression can be void; Arguments in functions are declared differently — instead of putting arguments between parentheses, they are written as null declarations on the following line: int function my_function int my_arg_1; int my_arg_2; { // some code } Control flow (if, else, while) is implemented as a "postfix operator": 1 == 2 :then { println("Whoa, math broke"); // And no, this won't get printed :D } A for-loop can be emulated with a block scope and a while: {int i = 0; i < 5 :while { printf("%d", i); i++; }} These control flow constructs can be extended — an excerpt taken from the stdlib: int::isZero { $int :else { $(); } } $int represents the int in question, and $()represents execution of the block given to the control statement. We could "call" this like so: 0 :isZero { println("Hey math works again!"); } Sea has support for ints, chars, pointers, strings (char*), and moderate support for floats. If you want to see more about the language, peruse stdlib.sea and the tests (and oldtests, though some of those are outdated) folders in the repl. EDIT: stdlib.sea uses what might be a confusing doc notation, so let me explain that here. Sea comments behave just like C comments: // This /* will not be */ // Evaluated However, there is a doc notation (used by SeaLib to generate simple HTML docs for a file). It is the following: [[[header]]] The header must be the first line of the file (outside of line or block comments). It gives a description of the file to follow. // This line is the file info [[your_function]] // Descriptor doc — gives info about a function A cool function I just wrote for demo purposes void function your_function { println("Hello, world!"); } // Add more functions with their descriptor docs SeaLib translates that to the following: And yes, that file would actually run (aside from saying "entry point main is not defined"). Doc headers are ignored (along with the line after) just like normal comments. Future "That's neat — but why are you posting it here right now?" Unfortunately, I'm going to abandon Sea (in favor of a newer language, Curta). Why? Two things: - As the language became more complex, I noticed a few things I had done not-quite-nicely in the compiler were becoming difficult to manage. I was faced with either using bad tools or buying (re-coding) new tools. - I was actually wrong about translating from a C-like language to x86 being easy. While the actual conversions themselves are not difficult, finding the proper x86 commands can be very difficult! For instance, there is no power function for the SSE floating point system — and all the tools I needed to make a power function were either nonexistent or difficult to implement. So Sea will probably remain in its current state [for the rest of time]. In the aforementioned newer language (Curta), I am learning from my mistakes — it will compile to C++, with the added benefit that it will work on some embedded systems (most notably the Arduino). Stay tuned! EDIT: Curta is now here: This is incredible! How do you make it a compiled programming language? Is it compiled due to the assembly or..? _I am very interested in finding out how to make a homemade programming language compiled!! @targetfanttthat same. interpreted languages are pretty easy to understand, but I never understood compiled ones @targetfanttthat Epic! We need more compiled languages! So, an interpreted language is run by the language it's written in. If I wrote an interpreted language in Python, the Python would execute the code. A compiled language translates the code of your language into a lower-level language like x86 assembly or C. The compiler doesn't run the code — instead, it just translates from one language to another. Since you said you're interesting in making a compiled language, I'd suggest starting here: It requires basic programming knowledge, but other than that it builds from the ground up! @DynamicSquid I think the assembly code is what makes it compiled, but still I want to know just how he did it! @targetfanttthat Don't associate assembly with compiled — some languages can compile to other languages like C or C++ (or even Java)! However, the reason you make a compiled language is usually for performance, and x86 has very high performance. @fuzzyastrocat Alright thank you!! Also good job on this language you did very well! Keep it up! @targetfanttthat Thanks! It took quite a bit of work since there aren't a whole lot of resources about compilers (or at least, resources that I could find). @fuzzyastrocat That is where I have gotten stumped at. I have tried and tried to find documentation on how to make my programming language a compiled one but I just give up cause no documentation was very open, or reliable I guess you could say. Thank you for that link though I am going to have a very fun night tonight, lol @DynamicSquid @targetfanttthat Yeah, interpreted languages have more documentation since they're generally easier. I hope that link helps — it was one of the few comprehensive resources I could find. It was my starting place, and look what I made :D you can get CPython to compile the languages into bytecode using py_compile which converts it to .pyc. @DynamicSquid @Lethdev2019 But still, usually you don't want another programming languages' compiler compiling the language you created yourself. There is no creativity in that. You're talking about using Python to create a programming language, right? true but python is quicker than you think (especially if you create an optimised lexer). @targetfanttthat @Lethdev2019 Well yes because Python supports some higher level libraries(like PLY) to help people out. But still in this case you are at a full disadvantage because you have no control on many things, such like you have no control on how you pick up keywords or punctuation in the lexer, you depend fully on a Python library. Yes, I agree, Python is quicker and more optimizable, but in the end you really have control over one section of your language: The Syntax wrong. I am working with aguy on slice and we built our own lexer on SLICE and we were able to control how it picked it up from a file and it is 0 dependency. @targetfanttthat @Lethdev2019 Oh. I thought when you said "python is quicker" and said "an optimized lexer" that you were hinting to using Python libraries. Optimizing something means it makes the better use of which is why I thought you were referencing to using Python libraries no, optimising it as in making it smaller and more efficient, libraries are not the way to go if you want to optimise. PLUS with your own code, it is easy to convert to an exe. @targetfanttthat @Lethdev2019 Well yes, making the better use of, being, making the situation better and easier in any way possible. To Me, Python wouldn't be the best language to use due to the fact it is a High Level programming language, it is a Dynamically Typed programming language, it is Interpreted and it is garbage collected, all causing it to be slower in the end and less efficient all together for memory management, which is the key to any programming language @Lethdev2019 Yes, but just because it was made in C does not mean that the language is going to be fast. I am talking about why I think Python shouldn't be used to create a programming language. We all have our own opinions though! I personally like the hands-on feeling of needing to allocate memory, work with low level stuff etc. While you may not and you would rather just get straight into it without needing to worry about any of the stuff I need to worry about using C.. @Lethdev2019 Here are a few links to websites/a youtube video I was referencing to state my facts: @targetfanttthat @Lethdev2019 I see both sides of your argument. As for py_compile, that compiles Python code, not custom language code. Sure, you can translate a custom language to Python, but as @targetfanttthat pointed out the only thing that changes is the "looks" of the language, not the functionality. And if you really do create a true translation of a different language into Python, you're basically just compiling to Python — so why not compile to a lower-level (and faster) language like C? As for optimization: Yes, python is a very optimizable language. But no matter how much you optimize it, it will still be an interpreted language — and interpreted languages are naturally slower. This is why Python is considered a slow language. I'm not saying Python is bad here: it has very good uses because of how high-level it is. But that same high-level-ness is what makes it slow, so for this particular instance it's not a good choice for a language in which you want performance. However, if you don't care about performance, then making a language in Python is totally fine. I made my first language in Python, because I knew that Python would be easy to work with. However, that language was painstakingly slow compared to even Python, which is why I've moved on to making compiled languages (which compile to a fast, low-level language). As for language builder libraries: This is a hotly debated subject. Some people say that these libraries are the best tools to use — others say they are terrible. In my opinion, there is no right answer here. If you just want to get it done fast (or easy), or if you're new to language building, you should use a language builder library. However, if you want full control over the lexing/parsing/etc process (like I did) or if you just want to make it yourself for the fun of it (also like I did), then you should build it from the ground up with no libraries. Neither way is wrong, just a matter of preference. Pardon the wall of text — didn't realize how long this was until I typed it all out :P I actually sea see some similarities with this and Haskell. Oh, quick question though, I'm still learning the very tiny basics of Haskell but I cant seem to find the WHERE ARE THE VARIABLES Like can I store the result of a function? For example: map toUpper "squid" -- can I store that in a variable so I can: putStrLn name -- or something like this? @DynamicSquid Really? Lol I didn't intend that, ig so name :: String -- Always good to annotate types, saves compile time name = map toUpper "squid" main :: IO() main = putStrLn name There's no difference between a named constant and a function that takes 0 arguments. That's part of the clarity of Haskell :D @DynamicSquid Here's a little bit of advanced Haskell: Say you wanted to be able to turn anything into an uppercase name. You could write a name function like so: name :: String -> String name x = map toUpper x But wait a minute — notice how x is at the end of both name x and map toUpper x? That means we can get rid of it — ie, name :: String -> String name = map toUpper main :: IO() main = putStrLn $ name "squid" -- This works, it prints correctly But why? The best way to understand this is currying: map, when called with 0 arguments (written out) creates a function that takes one argument - ...that creates a function that takes one argument - ...which takes the first argument and maps it over the second. So by saying map toUpper, we're partially applying map. It doesn't have the last argument yet (the thing to map over), so it doesn't do anything. It's just a function that, when you give it the final argument, will then apply the map. It's a bit confusing at first, but I'd suggest researching it since this is something used extensively in Haskell. It's also the basis of Point-free Programming. To learn more about currying, check out the wikipedia article. @yekyam Answer: basically nothing. "Wait, what?" Yes, in its current state, Sea doesn't add hardly anything internally to C (The control flow extension system is new, though you could represent that in C code). Then why did I make it? Well, the key phrase is "current state": all the cool internal additions to C I had planned became too cumbersome to implement (due to problem 2 listed above). However, you can expect some really cool (internal) features with my next language, Curta. So... stay tuned! :D (and thanks for "cool language"!) @fuzzyastrocat Absolutely no problem with cutting your losses, always better to start with a clean slate! I can't wait to see what's coming next! @fuzzyastrocat Last question: is your new language going to have memory management, or is it going to be garbage collected? @yekyam That's rather difficult to determine. As Curta is an embedded systems language, its memory footprint is very, very low. However, I believe the answer would probably be garbage collection (though much less overhead than other garbage-collected languages). Why am I using all this shifty wording? Because to properly explain it, I'd have to give away a good deal about the language, and that would ruin all the surprise :D @yekyam If you're interested, curta is now here: It's changed since my last post here but it still retains its purpose! @Highwayman Just like C, there is a doc notation though. I'm adding it to the post itself (check there). This is sick! I was trying to make a Lang, but I got a bit confused the minute I hit parsing which is embarrassing, ngl. Anyways. Cant wait for Curta! @Highwayman Thanks! I'm considering making a "HOWTO: compiled languages" tutorial (no guarantees though). Also thanks! I'm progressing much faster with it since C++ is an easier intermediate representation — so it should be done [relatively] soon! Oo noice, is Curta like an entirely new language, syntax and everything, or is it like Sea2.0? @fuzzyastrocat @Highwayman Mostly new. I'm pulling the ideas I liked from Sea into the new language though, so it won't be 100% different. @Highwayman Yep! That isn't the only thing though — but I'll leave it a secret until Curta is done :D Makes sense, it looks somewhat convenient. Reminds me of D. Someone posted a tutorial about it and it has a sort of thing like Sealib where you can just insert you docs into the code. Pretty cool stuff there XP. What went wrong with the Sea compiler? @fuzzyastrocat @Highwayman Nice! Yeah, I think more languages need a system for easy documentation embedded in the code. Well, the way it was constructed I was using many variables to keep track of compiler state (rather than using immutable types and keeping state locally via function calls). It's a bit difficult to explain, but it started to hinder me a bit. Additionally, the parser error system was not well-constructed, so sometimes errors would be very misleading. So nothing went objectively wrong, it's just that I'm going to do things a bit differently the second time around. Ahh I think I kinda get what your saying.. so like it was just a bit disorganized it sounds....? Huh. @fuzzyastrocat @Highwayman Hindsight is 20/20 :D Looking back, yes it was not the most "clean" approach. Though that was certainly the less-impactful of the two problems (the x86 translation part was what initially motivated the abandonment of Sea). Definitely lol. I really enjoy redoing old projects cause of that ye. Ah yeah how you were saying that the stuff was hard to find oh yeah. @fuzzyastrocat @Highwayman Hey! Since you were interested in Curta, here's the link: It's still in development but I've gotten it to a state where it can be used for actual purposes. @ironblockhd You're probably familiar with Interpreted languages (Night being a good example here). Interpreted languages just run in the language you write them in — so if I made an interpreted language in JS, the JS would run the language. However, this is a compiled language, meaning that the JS just translates my language into assembly language. Why do this? Because x86 assembly is blazingly fast, meaning that my compiled language will have a large performance gain over an interpreted one. TL;DR: Instead of directly running my language, I translate it into assembly. Then I run the assembly. Hope that helps! @DynamicSquid Thanks! Though now I can never have an unambiguous conversation about C or Sea again :D Amazing job! Just a question, why and how did you use js? I thought most programming languages were made in c and c++... @AbhayBhat Glad you asked! Many interpreted languages are made in C and C++. Why? Because C and C++ are fast, and interpreted languages need to be built on a fast language since they are inherently slow. However, a compiled language is inherently fast, because it's actually not running on JS — it's running on x86. The job of the JS is to convert the Sea programs to x86 assembly, and x86 is very very fast. So, to answer your question: I used JS because JS is easy to code in, so I wouldn't be hindered by it (and performance of the host language doesn't really matter much for compiled languages). As a side note: after completing a compiled language, one usually rewrites the language source in the language itself. This is so that you get rid of the JS. Note: Re-reading my post, it might be a little unclear. Here's the basic idea: If my language was interpreted, then the JS would be the one running the language. JS is slow, so I don't want a slow thing running my language since my language will run even slower. Since the language is compiled, JS doesn't actually run the language. Instead, JS just translates it into machine code, which is super fast. Even though JS is slow, the JS doesn't actually do a whole lot — so it's acceptable to use it. @fuzzyastrocat, Absolutely Amazing! I wish there was something like this in java.. @AbhayBhat I'm pretty sure you can do this in Java too! As long as you know Assembly or at least another compiler language like C, you can just use file I/O and then call a compiler or assembler using Runtime.getRuntime().exec(yourCodeHere). @AbhayBhat I just wish I knew Assembly so I could make something like this. LOL! @AbhayBhat But, it is actually possible even to compile to Java and then use a Java compiler to create a language! @AbhayBhat, you can do this in Java if you want also — there's nothing special about JS for compilers. What @AmazingMech2418 said above is also perfectly valid — you could use Java to compile (translate) your language to Java! @fuzzyastrocat Runtime.getRuntime().execjust runs a Bash script. Basically, you can use that to call the compiler or assembler depending on how you're making the compiler (either directly to Assembly or transpiling to another language which is then compiled). It's like the child_process.execfunction in JS. @AmazingMech2418 Ah ok, yes that would run the assembler (or the compiler of the non-assembly language if applicable — though I think that might be considered an assembler also in that case?). But the compiler is the program itself — so unless the program exec's itself (creating an infinite loop) you probably wouldn't use that to run the compiler. @fuzzyastrocat I mean like if you are just transpiling to C to make it easier and using clangor gccwith exec. However, if just compiling to Assembly, you are correct and you would only need to run the assembler. @AmazingMech2418 Right ok, I thought by "compiler" you meant the compiler of the custom language :D How to use file I/O? @AmazingMech2418 @Elderosa Like Scanner, FileWriter, PrintWriter and stuff. Do you have to use #include ? I’m kind of a noob in C [email protected] Also, how do you form this into [email protected] @fuzzyastrocat did you write Sea inside itself yet? @Elderosa I'm not sure where you go the idea that I was going to self-host Sea... the Sea project has been dead for months now and will most likely remain in that state forever. Ok, I have a question, how do I create my own interpreters and compilers @fuzzyastrocat @Elderosa There's a good reference for interpreters here, and a good reference for compilers here.
https://replit.com/talk/share/Sea-a-compiled-language/50738
CC-MAIN-2022-21
refinedweb
3,633
70.02
RIF example UC10: Publishing Rules for Interlinked Metadata Contents Summary This is an attempt to encode typical rules for the Use case Publishing_Rules_for_Interlinked_Metadata in the XML syntax of RIF Core WD1, slightly extended where it appears necessary. We will analyze what is possibly to express, present two possible source formats for rules of the kind used in this use case (N3 and SPARQL construct statements) as well as their mapping to RIF. We will suggest/define extensions where necessary. Source rules For a first attempt, we focus here on rules of the second block in the Use Case scenario since they cover interesting aspects such as scope and scoped negation. Consider an alternative database of movies published at. In addition to metadata, it publishes the following rules: r1: All movies listed at but not listed at are independent movies. r2: All movies with budgets below 5 million USD are low-budget movies. In order to demonstrate that these rules are worthwhile to be considered obviously, we will now see how these can be expressed in existing syntaxes already. We note that the two chosen formalisms allow to express the desired rules, although there exact semantics (in both cases) is still tied to several open issues. source rules in N3 @prefix log: <> . @prefix ex: <> . { <> log:semantics ?AM . ?AM log:Includes {?m a ex:movie.} . <> log:semantics ?IM. ?IM log:notIncludes {?m a ex:movie.} . } log:implies {?m a ex:indepMovie} . { ?m a ex:movie. ?m ex:hasBudget ?b. ?b math:lessThan "5"^^xsd:integer .} log:implies {?m a ex:lowBudgetMovie} . Unclear issues semantically in N3 are the nesting of log: statements (such as log:semantics) and how mutual reference of N3 documents is dealt with. source rules in SPARQL As pointed out in a mail conversation between Dan Conolly and Axel Polleres, see, SPARQL CONSTRUCT statements (probably mixed with RDF Facts can be seen as rule bases. For the scoping we can use named graphs in SPARQL. PREFIX ex: <> . CONSTRUCT { ?m a ex:indepMovie . } WHERE { GRAPH <> {?m a ex:movie.} OPTIONAL { GRAPH <> {?m a ex:movie. ?x a ex:movie. } } FILTER !bound(?x) } CONSTRUCT {?m a ex:lowBudgetMovie} WHERE { ?m a ex:movie. ?m ex:hasBudget ?b. FILTER(?b < "5"^^xsd:integer) .} For the first of the two constructs to work as expected, one needs to assume both <> and <> elements of the named graphs in the dataset evaluating the SPARQL queries. Also, the first query needs to do a trick, referring to an actually unnecessary variable ?x in connection with an OPTIONAL and GRAPH graph pattern in order to express scoped negation. Analysis and issues In the following, we will try to give a plain attempt, to express both rules in the RIF syntax. Putting aside the semantic unclarities of N3 and SPARQL, it is still an open issue, how to actually define the mappings from/to RIF for these example rules, which seems to be more challenging than simply defining the task whether the rule in principle is expressible in RIF Syntax. RDF triple mapping As already pointed out in the UC8 Worked Example, there are various possibilities for RDF mappings to predicates/rules. We chose here the option of representing the RDF triples by binary relations where the predicate symbol is determined by the RDF predicate. RIF in XML or RDF ? UC8 Worked Example suggests a mixed RDF and XML Literal proposal to implement the RIF syntax, i.e., expressing conditions as XML Literals, wheras the overall rule-structure, and ruleset is expressed in an RDF syntax. Let us try to go one step further and see whether RDF could be used town to the conditions. A triple pattern, or other n-ary predicate would then be encoded: <rif:Uniterm> <rif:Const rdf: <rif:Parameters rdf: <rif:Var>m</rif:Var> <rif:Const rdf: </rif:Parameters> </rif:Uniterm> As for Datatypes, going down to RDF would allow to reuse the existing rdf:Datatype directly without the necessity to create a new attribute: <Const rdf:5000000</Const> However, we see already, that going down to RDF on the condition/atom level would have several complicating implications: 1. In order to parameter preserve order, we need to introduce a collection and a new property/tag for parameters, which boils down to a list in RDF. 2. An RDF syntax, together with allowing RDF as data has several semantic implications which already proved problematic at several points in e.g. OWL Full. We thus suggest to stay with the XML syntax, and support clear semantic interfaces for the RDF data and OWL ontology interfacing. So, we suggest to keep with the XML notation, also at the rule and ruleset level, ending up in: <rif:Uniterm> <rif:Const rif: <rif:Var>m</rif:Var> <rif:Const rif: </rif:Parameters> </rif:Uniterm> <rif:Const rif:5000000</Const> Note the borrowed attribute names from RDF, analogously to RDF syntax, we use attributes rif:resource and rif:datatype for refering to URI identified objects and concrete datatypes. Context/Scope For this use case, atoms need to be scoped. A quick straw peoposal to achieve this, would be the annotation of <rif:Uniterm> with an additional attribute rif:context: <rif:Uniterm rif: <rif:Const rif: <rif:Var>m</rif:Var> <rif:Const rif: </Uniterm> Variables As a slight change to the original syntax, we could imagine variable ids also being represented as attribute values, i.e.: <rif:Var rif: but we will stick with the original proposal for the moment. (Scoped) Negation as failure For scoped negation as failure, we assume the tag <rif:naf>. Builtins Also for builtins we run into similar problems than UC8. There are (except equality) no defined comparison operators yet. We could, for our purposes use XPath/XQuery-functions, which would however require us to provide a namespace for the op: prefix used in the XPath-functions document: <rif:Const rif: <rif:Const rif:5000000</rif:Const> <rif:Var>b</rif:Var> Note that in the rules above it is nowhere said that we talk about an USD amount. This would need to be separately stated somehow (and was left open in this first attempt). bNodes bnodes are not an issue in this example. Rule naming Rule naming is not an issue in this example, so we don't give names to the rules. Naming would be NECESSARY in if we stick to an RDF syntax, otherwise disambiguation of rules is impossible. RIF Translation <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE rif:Ruleset [ <!ENTITY xsd ''> <!ENTITY rif "" > <!ENTITY ex "" > <!ENTITY op "" > ]> <Ruleset xmlns="&rif;"> <Forall> <!-- Rule variables, universally quantified in declare role, skipping formula role --> <declare> <Var>m</Var> </declare> <Implies> <!-- rule body --> <if> <And> <Uniterm context=""> <Const rif: <Var>m</Var> <Const rif: </Uniterm> <naf><Uniterm context=""> <Const rif: <Var>m</Var> <Const rif: </Uniterm></naf> </And> </if> <!-- rule head --> <then> <Uniterm> <Const resource="&rdf;type" /> <Var>m</Var> <Const resource="&ex;indepMovie" /> </Uniterm> </then> </Implies> </Forall> <Forall> <!-- Rule variables, universally quantified in declare role, skipping formula role --> <declare> <Var>m</Var> <Var>b</Var> </declare> <Implies> <!-- rule body --> <if> <And> <Uniterm> <Const resource="rdf:type" /> <Var>m</Var> <Const resource="&ex;movie" /> </Uniterm> <Uniterm> <Const resource="&ex;hasBudget" /> <Var>m</Var> <Var>b</Var> </Uniterm> <Uniterm> <Const resource="&op;numeric-greater-than"> <Const datatype="&xsd;integer">5000000</Const> <Var>b</Var> </Uniterm> </And> </if> <!-- rule head --> <then> <Uniterm> <Const resource="&rdf;type" /> <Var>m</Var> <Const resource="&ex;lowBudgetMovie" /> </Uniterm> </then> </Implies> </Forall> </Ruleset> Although I can write down the rule now in RIF, it is still open, how to get e.g. from the N3 representation to SPARQL via RIF, or vice versa, and whether the intermediate format would be the suggested. Mappings to be defined, and to be discussed whether and how this can be done.
https://www.w3.org/2005/rules/wg/wiki/UC10_Worked_Example
CC-MAIN-2018-05
refinedweb
1,299
52.19
WebAssembly (frequently abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of higher-level languages such as C/C++/Rust, enabling deployment on the web for client and server applications. Code compiled to run in WebAssembly creates a module. The WebAssembly module can be loaded by a JavaScript engine which in turn, calls into the Wasm module to perform computation. One of the main features of WebAssembly is high performance computation. Implementing CPU intensive operations in a statically typed language that can be compiled into WebAssembly enables higher performance web applications for some application use cases. Similarly, existing code can be ported across to run in a web browser with memory safety and high performance. This codelab is focused on WebAssembly. Non-relevant concepts and code blocks are glossed over and are provided for you to simply copy and paste. Click the following link to download all the code for this codelab: Unpack the downloaded zip file. This will unpack a root folder ( chipmunk-hourglass),. There is a directory called solution which contains the finished project. ensuing window, click on the Web Server icon: You'll see this dialog next, which allows you to configure your local web server: Click the choose folder button, and select the work folder. This will enable you to serve your work in progress via the URL highlighted in the web server dialog (in the Web Server URL(s) section). Now visit your work site in your web browser at this URL and you should see a page that looks like this: This is showing the skeleton graphic that'll be the host for our dynamic content. If you're curious to look at the source content, open up the file hourglass.svg from your work folder. Looking inside, you'll see that it's simply a bunch of elements in the SVG namespace, which of course means it'll scale nicely on any window size. In this codelab, we'll explore manipulating DOM objects in the browser from calculations made in a Wasm module. The example used is an hourglass, where the grains of sand in the hourglass are circles as SVG DOM nodes. Our source graphic has a bunch of DOM elements but no outline of the interior of the hourglass. So the first thing to do is define a shape that will contain our grains of sand for the physical simulation. Since SVG has the notion of 'user space units', we should be able to define a shape that will scale alongside the source graphic at any scale. Open up the hourglass.svg file in your favourite text editor. At the end of the file, you'll see two closing tags that look like this: </g> </svg> Replace those lines with our containing shape using the following code: </g> "/> </svg> Now that you've added the container shape, reloading hourglass.svg should display the original graphic with a red outline overlayed that will be the container for our physical objects (grains of sand). You should see the image below: We'll use the coordinates of the red polygon to act as the container for our grains of sand to fall through. Notice that the coordinates of the polygon we just added are in the user space coordinate system of the SVG graphic, which means they are scale-independent so we can use them to send to the physics engine and expect the returned values to be scale independent (work no matter what size we rescale the application window to). The positions of the grains of sand are managed by a physics engine, in this case Chipmunk2D which is compiled into Wasm. When the timer is eventually started, the positions of the grains of sand are controlled by the physics engine calculations inside the Wasm module. First thing we need to do is build the physics engine library. Note, the library itself is open source and lives at. The source repository contains build files for a number of different platforms, but doesn't have a standard ./configure and make step. Conveniently it does come with a Cmake file which we can look at as a basis to build our own Makefile that we can then use to compile it into a Wasm module. The CMakeLists.txt files at the top level (Chipmunk2D) and src directories show that we just need to include all the C files from the src directory in our compile. We'll be using a compiler toolchain SDK that's called emscripten. Full documentation for the toolchain and it's features can be found here: If you're at Google I/O 2018, then you can just open a terminal and run: source ~/emsdk/emsdk_env.sh That command will set up the environment variables in your terminal so that you can use the emscripten toolchain. If you're not at I/O 2018, then you should install the emscripten SDK by following these instructions. The emscripten C/C++ compiler is called emcc. We've pre-constructed a Makefile based on the Chipmunk2D build files that you will find in the work directory. It contains this: CHIP_DIR=Chipmunk2D CHIP_SRC=$(CHIP_DIR)/src CHIP_INC=$(CHIP_DIR)/include CHIP_SRCS=\ $(CHIP_SRC)/chipmunk.c $(CHIP_SRC)/cpArbiter.c $(CHIP_SRC)/cpArray.c \ $(CHIP_SRC)/cpBBTree.c $(CHIP_SRC)/cpBody.c $(CHIP_SRC)/cpCollision.c \ $(CHIP_SRC)/cpConstraint.c $(CHIP_SRC)/cpDampedRotarySpring.c \ $(CHIP_SRC)/cpDampedSpring.c $(CHIP_SRC)/cpGearJoint.c \ $(CHIP_SRC)/cpGrooveJoint.c $(CHIP_SRC)/cpHashSet.c \ $(CHIP_SRC)/cpHastySpace.c $(CHIP_SRC)/cpMarch.c $(CHIP_SRC)/cpPinJoint.c \ $(CHIP_SRC)/cpPivotJoint.c $(CHIP_SRC)/cpPolyShape.c \ $(CHIP_SRC)/cpPolyline.c $(CHIP_SRC)/cpRatchetJoint.c \ $(CHIP_SRC)/cpRobust.c $(CHIP_SRC)/cpRotaryLimitJoint.c \ $(CHIP_SRC)/cpShape.c $(CHIP_SRC)/cpSimpleMotor.c \ $(CHIP_SRC)/cpSlideJoint.c $(CHIP_SRC)/cpSpace.c \ $(CHIP_SRC)/cpSpaceComponent.c $(CHIP_SRC)/cpSpaceDebug.c \ $(CHIP_SRC)/cpSpaceHash.c $(CHIP_SRC)/cpSpaceQuery.c \ $(CHIP_SRC)/cpSpaceStep.c $(CHIP_SRC)/cpSpatialIndex.c \ $(CHIP_SRC)/cpSweep1D.c SRCS=$(CHIP_SRCS) bridge.c TARGET=chipmunk.js TARGETS=$(TARGET) chipmunk.wasm all: chipmunk.js chipmunk.js: $(SRCS) # Compile commands go here... Note the line: SRCS=$(CHIP_SRCS) bridge.c That contains reference to all the Chipmunk2D source files plus another file called bridge.c. The file bridge.c will be our glue code that interfaces Javascript to the physics library. Open up the file bridge.c in your text editor. You'll edit this to build the interface between the Javascript calls into our Wasm module and the Chipmunk2D physics engine. Add the following code to bridge.c: /* * Bridge from JS into Chipmunk2D in Wasm */ #include <emscripten.h> #include <chipmunk/chipmunk.h> #include <stdlib.h> #include <memory.h> /** * A struct that manages our instantiation of * the Chipmunk2D physics engine */ typedef struct { cpSpace *cmi_Space; /**< Holds instance of Chipmunk2D */ float cmi_Location[3]; /**< Stores x, y, rotation */ } CM_Instance; /* * This is our interface from the Wasm world out into * the JS world when using 'C' */ /** * Constructor for the Chipmunk2D engine */ CM_Instance * CM_Instance_new() { CM_Instance *cm; cm = malloc(sizeof *cm); if (cm) { memset(cm, 0, sizeof *cm); } // cpVect is a 2D vector and cpv() is a shortcut // for initializing them. cpVect gravity = cpv(0, 50); // Create an empty space. cm->cmi_Space = cpSpaceNew(); cpSpaceSetGravity(cm->cmi_Space, gravity); return cm; } /** * Destructor for when we're all done (frees everything). */ void CM_Instance_destroy(CM_Instance *cmi) { if (cmi != NULL) { cpSpaceFree(cmi->cmi_Space); free(cmi); } } Save the file bridge.c once you've added the lines above. Now we should be able to compile our physics engine and glue code by making sure we're in the work directory and typing the following command in a shell: make After running make you should find 2 new files in the work directory - chipmunk.js and chipmunk.wasm. The file chipmunk.wasm is the Chipmunk2D physics library compiled into a Wasm module. The file chipmunk.js is emscripten generated glue code that can take care of loading the Wasm module and managing the interface to it. Next, we need to invoke the loading of the Wasm module from our web application. In the file hourglass.svg, add the following lines as the first child of the root SVG element (just before the <defs> element: <script xlink:</script> <script><![CDATA[ var wasm_loaded = false; var cm_instance; Module.onRuntimeInitialized = function() { wasm_loaded = true; cm_instance = Module._CM_Instance_new(); } ]]></script> The Module.onRuntimeInitialized property can be set to a function that gets called after the Wasm module is loaded, in this case it will create an instance of the Chipmunk2D physics library. Reload the file hourglass.svg and you should see no change. Try opening up the debugger console then reload and you should see some debug output telling you the Wasm module has been loaded, and a message from Chipmunk2D telling you to recompile with debugging disabled by adding the - DNDEBUG flag. Now that we have our physics engine loaded, we need 2 things: For the boundary creation interface, open up the bridge.c file and add this function: /** * Add a static wall to our space. * This is for containing the balls as they're dropping * through the space. * * @return * Pointer to the cpBody created, 0 on error. */ void CM_Add_wall ( CM_Instance *cmi,/**< Our Chimpunk2D instance */ int id, /**< An id to map to our DOM node in JS */ int x1, int y1, int x2, int y2 ) { cpVect p1, p2; cpShape *segment; p1.x = x1; p1.y = y1; p2.x = x2; p2.y = y2; segment = cpSegmentShapeNew(cpSpaceGetStaticBody(cmi->cmi_Space), p1, p2, 1.5); cpShapeSetFriction(segment, 1); cpSpaceAddShape(cmi->cmi_Space, segment); } This function lets us add fixed surfaces inside our physical model, but now we need to call those from Javascript to create the containing shape. Recall that we added the red outlined polygon defining our container earlier. What we'll do it take those coordinates and pass them through to the physics engine using our new API function. Edit the hourglass.svg file and add this code inside the <script> element: const interior = [, 105,89 ]; function build_world() { // Create the walls of the interior of the hourglass shape for (var i = 0; i < interior.length - 2; i += 2) { Module._CM_Add_wall(cm_instance, 0, interior[i], interior[i + 1], interior[i + 2], interior[i + 3]); } } We need to make sure that we call into the Wasm module after it's finished loading. To do so, replace the onRuntimeInitialized function with this code: Module.onRuntimeInitialized = function() { wasm_loaded = true; cm_instance = Module._CM_Instance_new(); build_world(); } This ensures that the build_world() function will only get called after the Wasm module is loaded. Now that we have a container, we need to generate some grains of sand to fall through the hourglass. We'll be building those with DOM nodes - in this case using the <circle> element from SVG. To create the sand, first lets edit bridge.c and add a function to create circular objects in the physics engine by adding this code: /** * Add a circular dynamic object to our space. * This is for adding grains of sand * * @return * Pointer to the cpBody created, 0 on error. */ cpBody * CM_Add_circle ( CM_Instance *cmi, /**< Our Chimpunk2D instance */ int id, /**< Id to map back to our DOM node in JS */ float x, /**< Starting 'x' position of the circle */ float y, /**< Starting 'y' position of the circle */ float radius /**< Radius of the circle */ ) { static cpFloat mass = 1; cpFloat moment = cpMomentForCircle(mass, 0, radius, cpvzero); cpBody *ballBody = cpSpaceAddBody(cmi->cmi_Space, cpBodyNew(mass, moment)); cpShape *ballShape; // Set the position of the circle cpBodySetPosition(ballBody, cpv(x, y)); // Add the collision shape to the circle ballShape = cpSpaceAddShape(cmi->cmi_Space, cpCircleShapeNew(ballBody, radius, cpvzero)); cpShapeSetElasticity(ballShape, 0.0); cpShapeSetFriction(ballShape, 0.0); return ballBody; } To create a container for our grains of sand, edit hourglass.svg and add these lines at the end of the file just before the closing </svg> tag: <g id="bottle" style="fill: url(#ballGrad)"> </g> That <g> element will hold all of our grains of sand once we generate them using Javascript. Now edit the hourglass.svg file and add a function to create some DOM nodes to represent the sand by adding this code inside our <script> element: const cols = 41; const rows = 18; const startx = 109; const starty = 92; const grains = cols * rows; const SVGNS = ""; function generate_sand() { var ball, ballNode; var bottle = document.getElementById("bottle"); var ident; x = startx; y = starty; for (var j = 0; j < rows; j++) { for (var i = 0; i < cols; i++) { ident = (j * cols) + i; ball = Module._CM_Add_circle(cm_instance, (i * cols) + j, x, y, 1.8); ballNode = document.createElementNS(SVGNS, "circle"); ballNode.setAttribute("id", "ball" + ident); ballNode.setAttribute("cx", x); ballNode.setAttribute("cy", y); ballNode.setAttribute("r", "2"); ballNode.setAttribute("physref", ball); // Store bodyref bottle.appendChild(ballNode); x += 4; } x = startx; y += 4; } } Finally we need to actually call the generate_sand() function to dynamically create the <circle> nodes that represent our sand. To do so, replace the build_world() function in hourglass.svg with the following code: function build_world() { // Create the walls of the interior of the hourglass shape for (var i = 0; i < interior.length - 2; i += 2) { Module._CM_Add_wall(cm_instance, 0, interior[i], interior[i + 1], interior[i + 2], interior[i + 3]); } generate_sand(); } Recompile the Wasm module so that the sand creation function is built in, using the command line: make Now reload the web page and you should see a whole lot of circles representing sand at the top of the hourglass. It should look similar to this: Now that we've generated a bunch of DOM nodes from script, and connected our physics engine it's time to drive the physics engine to create a dynamic animated experience. For this we'll use requestAnimationFrame to trigger recalculation of the positions of all our grains of sand and update the display. To do so, we need to add an interface function to drive the physics engine by editing bridge.c and adding this function: /** * Step the space. * This runs one tick of the simulation, and updates all our * object positions. */ void CM_Step(CM_Instance *cmi) { static cpFloat timeStep = 1.0 / 60.0; cpSpaceStep(cmi->cmi_Space, timeStep); } We also need to find out where the grains of sand have moved to, so add this function as well: /** * Get the location of an object in our space. * * @return * An array of 3 floats - x, y position and rotation */ float * CM_Get_location(CM_Instance *cmi, cpBody *what) { cpVect pos = cpBodyGetPosition(what); cpFloat rot = cpBodyGetAngularVelocity(what); cmi->cmi_Location[0] = pos.x; cmi->cmi_Location[1] = pos.y; cmi->cmi_Location[2] = rot; return cmi->cmi_Location; } Finally, let's activate the physics engine from JavaScript to run a tick of the physics engine each time we get a requestAnimationFrame callback and update the positions of the DOM nodes that represent our grains of sand by adding this code to hourglass.svg: function handle_tick() { // Run a tick of the simulation, update sand positions Module._CM_Step(cm_instance); for (var i = 0; i < grains; i++) { var ident = "ball" + i; var ballNode = document.getElementById(ident); var ball = ballNode.getAttribute("physref"); var location = Module._CM_Get_location(cm_instance, ball); // Create a TypedArray view from the Wasm pointer value var pos = new Float32Array(Module.HEAPU8.buffer, location, 3); var val = ballNode.getAttribute("cx"); ballNode.setAttribute("cx", pos[0]); ballNode.setAttribute("cy", pos[1]); } } function setup() { function update() { // Do stuff with Chipmunk2D if (wasm_loaded) { handle_tick(); } requestAnimationFrame(update); } requestAnimationFrame(update); } window.onload = setup; Recompile the Wasm module from the command line with: make Now reload hourglass.svg and you should see grains of sand falling through the hourglass. Congratulations! You've built a web application that dynamically modifies DOM node content from a compiled Wasm module. We still have a red polygon outline that isn't needed for the graphic. Also, the generated grains of sand start as a grid which doesn't look very realistic. Let's fix it. When we first created the containing polygon points, we added this code at the end of hourglass.svg: "/> Delete it, since we no longer need to show the container. To make the grains of sand look more realistic we could do a couple of things: Of course we'll pick (2) since all good engineers let the machine do the hard work! To reposition the sand at start up time we'll place the grains as before but invert gravity and run the physical simulation for a few cycles to force the grains to levitate upwards into a natural cluster before starting the simulation. To do so, first we need to edit bridge.c to add a function to change the gravity in our physics simulation by adding this code: /** * Set the gravity vector */ void CM_Set_gravity(CM_Instance *cmi, float x, float y) { cpVect gravity = cpv(x, y); cpSpaceSetGravity(cmi->cmi_Space, gravity); } Now to force the grains of sand to levitate into a nice holding position before we run the simulation, edit hourglass.svg and change the build_world() function to this: function build_world() { // Create the walls of the interior of the hourglass shape for (var i = 0; i < interior.length - 2; i += 2) { Module._CM_Add_wall(cm_instance, 0, interior[i], interior[i + 1], interior[i + 2], interior[i + 3]); } generate_sand(); // Invert gravity and run for a few ticks to clump the sand // at the top of the hourglass before starting Module._CM_Set_gravity(cm_instance, 2, -50); for (var i = 0; i < 200; i++) { Module._CM_Step(cm_instance); } Module._CM_Set_gravity(cm_instance, 0, 50); } Recompile the Wasm module from the command line using: make Then reload hourglass.svg. You will see a small delay on reload which is the physics engine clumping the grains of sand at the top of the hourglass before they all start falling nicely. Earlier we saw that the generated Javascript and Wasm file were larger than we'd like - and the console warning from Chipmunk2D gave us a hint of what we should do. We can greatly improve the size of the generated output by listening to what the library tells us, but more importantly using a great feature in the Emscripten toolchain which is an optimization flag -Os. That flag analyzes the function calls across Javascript and Wasm before the final link step and eliminates code that isn't called to minimize the resultant size. To try out these improvements, load 'Makefile' in your text editor and replace the line: -I$(CHIP_INC) \ With this: -I$(CHIP_INC) -Os -DNDEBUG \ Delete the existing output from the command line with: make clean Then recompile from the command line and compare the size reduction in the generated Javascript and Wasm files. make ls -l By now you're probably hoping to be able to time your cooking or something equally important, so surely it should be possible to flip the timer to restart it? Of course it is - courtesy of the gravity function we built and a bit of animation. So let's try. Edit hourglass.svg and add these elements as direct children of the root <svg> element: <animateTransform id="flip" attributeName="transform" attributeType="XML" type="rotate" from="0" to="180" begin="undefined" dur="1s" fill="freeze"/> <animateTransform id="unflip" attributeName="transform" attributeType="XML" type="rotate" from="180" to="0" begin="undefined" dur="1s" fill="freeze"/> Then inside the <script> element, add a click handler by adding these lines: var flipped = 0; function handle_click(evt) { if (flipped) { document.getElementById('unflip').beginElement(); Module._CM_Set_gravity(cm_instance, 0, 50); } else { document.getElementById('flip').beginElement(); Module._CM_Set_gravity(cm_instance, 0, -50); } flipped = !flipped; } document.getElementById('hourglass').addEventListener('click', handle_click); Reload hourglass.svg - each time you click the hourglass should flip over, changing gravity in the process and restarting the simulation. Congratulations again! - you've built a dynamically modifiable web application connected to a physics engine written in C. If you'd like to explore more about WebAssembly, here are a few resources to help:
https://codelabs.developers.google.com/codelabs/hour-chipmunk/index.html?index=../../io2018
CC-MAIN-2020-10
refinedweb
3,253
54.63
acl_set_file() Set the access control list for a path Synopsis: #include <sys/acl.h> int acl_set_file( const char *path_p, acl_type_t type, acl_t acl ); Since: BlackBerry 10.0.0 Arguments: - path_p - The path that you want to set the ACL for. - type - The type of ACL; this must currently be ACL_TYPE_ACCESS. - acl - The ACL that you want to assign to the object. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The acl_set_file() function sets the access control list for a given path.ACCES - Search permission was denied for a component of the path prefix, or the object exists and the process doesn't have the appropriate access rights. - EINVAL - The acl argument doesn't point to a valid ACL, or the type argument isn't ACL_TYPE_ACCESS. - ENAMETOOLONG - The length of the path_p argument exceeds PATH_MAX. - ENOENT - The named object doesn't exist, or path_p is an empty string. - ENOSPC - The directory or filesystem that would contain the new ACL can't be extended, or the filesystem is out of file allocation resources. - ENOTDIR - A component of the path prefix isn't a directory. - EPERM - The process doesn't have the appropriate privileges to set the ACL. - EROFS - The filesystem that the object is on is currently read-only. Classification: This function is based on the withdrawn POSIX draft P1003.1e. Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/a/acl_set_file.html
CC-MAIN-2014-42
refinedweb
253
67.96