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
In this article series, I would like to show how DotVVM works in more complicated web applications and demonstrate useful features you may appreciate in your next project – an admin site, intranet portal or a CRM/ERP web app. A few months ago, I wrote an article on DotVVM, an open source MVVM framework that allows building ASP.NET web apps without knowledge of JavaScript. I will be using NorthwindStore DotVVM Demo project in this article to demonstrate how DotVVM can be used in real-world scenarios. If you want to try the project, follow the instructions in the README. The sample application consists of 3 layers, The purpose of this article is not to describe how the DAL and BL works. If you are interested in it, you can look at the source code – these projects use Riganti.Utils.Infrastructure library, which is also developed on GitHub. From the DotVVM perspective, there are a couple of important things for the Business Layer: From now on, I will be working with the NorthwindStore.App project. That is where the DotVVM pages and their ViewModels reside. DotVVM contains a control called GridView. This control can render data in a table and supports inline editing, sorting, paging and other useful features. GridView can be bound to any .NET collection, or to a special object called GridViewDataSet<T>. This class is a part of DotVVM and provides everything you may need to implement server-side paging and sorting. The GridViewDataSet<T> contains the following properties: You can work with the GridViewDataSet in two ways, The sample application contains two pages that work with regions – RegionList.dothtml and RegionDetail.dothtml. The viewmodel for a RegionList page looks like this, Notice that the ViewModel constructor receives the instance of the facade for working with Regions. It works because of the Dependency Injection support in ASP.NET Core and DotVVM: all facades are registered in the service collection so they can be injected to constructor parameters. In the constructor, I initialize the dataset with default page size and default sort order. In the PreRender method, I pass the dataset to the facade which loads data in it. The façade belongs to the Business Layer, which shouldn’t reference DotVVM because DotVVM is a presentation library. However, there is a package called DotVVM.Core which contains several interfaces (including IGridViewDataSet) which are useful in the Business Layer. That is why I can pass the dataset to the facade method to have it loaded. I am using RegionDTO objects in my dataset. As I have mentioned before, the BL returns DTO objects, which are plain C# classes. They are JSON-serializable (so they can be placed in DotVVM ViewModels), they don’t depend on Entity Framework context and don’t contain any circular references. In this case, it may look useless not to use the Entity Framework entity directly, as it is pretty much the same. However, there are other entities which are much more complicated, and there will be many differences between the entities and their DTOs. For example, there will be extra properties with data from linked tables, or some properties may be missing from the DTO as they are used in the user interface. I am used to making specialized DTOs every place where they appear. When I display a list of customers, I need to see only some columns. When I am editing a customer, I will probably need all the columns from the Customers table. When I look at the report about the customer, there will also be a slightly different set of columns. Because there are typically more DTOs for every entity, I am using the AutoMapper library in my BL as it makes the mappings easy. The UI of the page looks like this. I am using the GridView control to display the table with data, and the DataPager control to render links to other pages below my table. The sample application uses GridView and DataPager from DotVVM Business Pack because they offer more features. However, if you use the controls from the open source framework, you can. They work the same way – just change <bp:GridView> to <dot:GridView>. Figure 1: List Page with GridView control To generate a link to another page, I am using the RouteLink control. This control can generate URLs based on the route table: you can just specify the name of the route and the parameters (using the Param- prefix): The route URL looks like this. The value of the Id property is not required, so the New Region button is missing the Param-Id attribute. To prevent users from clicking the Delete button accidentally, I am using the ConfirmPostBackHandler. It will display a confirmation window before the postback for the Delete method is made, allowing the user to cancel the action. This mechanism of postback handlers is extensible, so you can write custom postback handlers and render the dialog yourself so it fits the design of your application. If you look at the RegionDetail.dothtml page, there is a simple form that can edit one region. I am using the same page for creating new regions, as well as to edit a region because regions are quite simple. However, some entities may require different forms for insert and edit. The form is very simple as there is only one editable field, The form element has a binding expression on the DataContext property. It means that all bindings in the form will be evaluated on the CurrentItem property in the viewmodel, which contains the region object. Its type is RegionDTO, and it looks like this: Notice the Required validation attribute (from System.ComponentModel.DataAnnotations namespace). DotVVM validates the ViewModel on every button click by default, so when the user tries to save the region with the empty description, he will get the validation error. DotVVM also translates the validation attributes in JavaScript so the emptiness check will be made on the client side. On the top of the page, there are Save and Cancel buttons. Notice that the Cancel button has Validation.Enabled set to false, because I do not want to validate the form when the user does not want to save the data. The ViewModel of the page looks like this, The CurrentItemId property is decorated with FromRoute attribute, which tells DotVVM to place the value of the route parameter named Id in this property. The IsNew property calculates whether we edit or create a new record. If the Id parameter is not present in the route, the CurrentItemId will have the default value (zero). Look how I hide the Id field in the form for new records. You can set Visible property on any HTML element or DotVVM control. The CurrentItem property contains the RegionDTO instance which can be edited by the user. In the PreRender method, I either load this object using the facade or create a new instance with default values, also utilizing a facade. The Save method takes the DTO and passes it back to the facade, which stores it in the database. The validation on the Save button is enabled by default, so when the region description is empty, the Save method is not called, and the validators will appear. Notice that the div element which contains the region description field has the Validator.Value attribute referencing the property that is validated. In my master page, I have set global options for validation. You can set these attributes globally for the entire application as I did. Alternatively, you can set these properties on the div element itself, or on any of its parents. Validator.InvalidCssClass tells DotVVM to add the has-error CSS class to elements marked by Validator.Value when their property is invalid. Validator.SetToolTipText adds the title attribute to these elements so that the user will see the error on mouse hover. Figure 2: Validation errors DotVVM also ships with the ValidationSummary control which can aggregate all errors from the ViewModel (or its part), and display them as a list, which can be styled using CSS. I have tried to show how a trivial CRUD can be implemented in DotVVM. In the next part of this series, I will show how to make a generic CRUD ViewModel that will save quite a lot of code while providing some extensibility points for more complicated scenarios. View All View All
https://www.c-sharpcorner.com/article/dotvvm-in-real-world-apps-part-one-basic-crud/
CC-MAIN-2021-43
refinedweb
1,403
62.68
If I have a User table and a form that displays all my users with a Rank. I want to be able to rank my users and then hit ‘update’ and all users will be parsed by my action into User model obects and then persisted with their new rank to the DB. Using “scaffold :user” in my controller works wonders for Single instance CRUD functionality of my User class, but can it be done with a list? So basically I have this def get_users @user_list = User.find_all() end In my views I’m doing. <% form_tag :action => ‘update_users’ do %> <% for user in @user_list %> <%-- display the user information here as a form --> <% end %> <% end %> <%= submit_tag “Update Users” %> I would love to have the submit button (and associated action call) update ALL the users automatically without ME having to create a complex parser to break all the :params being passed into User objects and save them 1 by 1. (Through a loop of course). I hope my description is clear… it’s crystal in my head.
https://www.ruby-forum.com/t/how-to-update-a-list-of-models-automatically-in-1-action/110899
CC-MAIN-2018-47
refinedweb
174
66.67
Difference between revisions of "Console UI Core Classes - OOP344 20113" Latest revision as of 06:31, 21 March 2012 OOP344 | Weekly Schedule | Student List | Teams | Project | Student Resources Contents - 1 Objective - 2 Student Resources - 3 Releases and Due Dates - 3.1 R0.1 - 3.2 R0.2 - 3.3 R0.3 - 3.4 R0.6 - 3.5 Project makefiles - 3.6 POST YOUR PROBLEM HERE -. Student Resources. Tester R0.2 Dialog and Labels To Do Complete the coding of CField, CLabel and CDialog and then test the project using Test2DialogAndLabel.cpp. Workload estimate out of 100: - CField 30th. 23:59 Tester - Test2DialogAndLabel.cpp - on matrix, with putty (Terminal/keyboard: Xterm R6)Sunday Nov 20th 15:00 Testers - to run the demos on matrix, with putty (Terminal/keyboard: Xterm R6) - On Terminal Window type: - $ ~fardad.soleimanloo/tX <ENTER> where X is the number of the test R0.6 - CText - CCheckList - CMenu To Do - Before starting CText: - Modify Console::edit(char *str....) and add two argument to the argument list; IsTextEditor, ReadOnly: - int Console::edit(char *str, int row, int col, int fieldLength, int maxStrLength, bool* insertMode, int* strOffset, int* curPosition, bool IsTextEditor = false, bool ReadOnly = false) - IsTextEditor: If IsTextEditor is true, then if offset is modified, stop editing and terminate the function returning the last key entered by the user. The easiest way to accomplish this, is as follows: - Save the value of the offset in a local variable at the very beginning of the main processing loop in the edit() function. - At the very end of the processing loop, If IsTextEditor is true, then compare the saved value with the value of offset. If the values are different, then set the termination flag (done) to true. - Also if IsTextEditor is true, ESCAPE should no longer undo the changes in the line. (since in this case, it is responsibility of the Text editor (CText) to undo the changes. - Before starting CCheckList: - Add the following methods to the CCheckMark class - bool radio(); - void radio(bool isRadio); - operator bool(); - operator char*(); - bool operator=(bool flag); - (see CCheckMark description) - Divide and assign tasks. - Branch and Create Mock-ups for the classes - Start coding. Due Dates - Tuesday Dec, 6, 2011 Testers Project makefiles - create a file in the root of cio call it "makefile" and copy the makefile of your test from "cio makefiles" into it. - make sure the lines starting with c++ are tabbed once. - then at command line issue the command "make" to complie; - the name of the executable will bt tX, where X is the number of the test. - Again: here are the project makefiles for Linux POST YOUR PROBLEM HERE - Problem with tester: (resolved) - Problem with CCheckMark. #include "cuigh.h" #include "cframe.h" namespace cio{ the index of added Field in the CDialog object."(); // addition for R0.6 void radio(bool isRadio); // addition for R0.6 operator bool(); // addtion for R0.6 operator char*(); // addition for R0.6MenuItemFe piont theMenu and MNode
https://wiki.cdot.senecacollege.ca/w/index.php?title=Console_UI_Core_Classes_-_OOP344_20113&diff=cur&oldid=72474
CC-MAIN-2022-27
refinedweb
491
54.93
5.7. Deep Convolutional Neural Networks (AlexNet)¶ In nearly two decades since LeNet was proposed, for a time, neural networks were surpassed by other machine learning methods, such as Support Vector Machines. Although LeNet achieved good results on early small data sets, its performance on larger real data sets was not satisfactory. Neural network computing is complex. Although some neural network accelerators were available in the 1990s, they were not sufficiently powerful. Therefore, it was difficult to train a multichannel, multilayer convolutional neural network with a large number of parameters in those years. Secondly, datasets were still relatively small. As a result, deep learning research lay mostly dormant. Key techniques such as parameter initialization, non-convex optimization algorithms, activation functions and effective regularization were still missing. The lack of such research was another reason why the training of complex neural networks was very difficult. One of the key differences to classical computer vision is that we trained the OCR system end-to-end. That is, we modeled the entire data analysis pipeline from raw pixels to the classifier output as a single trainable and deformable model. In training the model end-to-end it does away with a lot of the engineering typically required to build a machine learning model. This is quite different from what was the dominant paradigm for machine learning in the 1990s and 2000s. - Obtain an interesting dataset that captures relevant aspects e.g. of computer vision. Typically such datasets were hand generated using very expensive sensors (at the time 1 megapixel images were state of the art). - Preprocess the dataset using a significant amount of optics, geometry, and analytic tools. - Dump the data into a standard set of feature extractors such as SIFT, the Scale-Invariant Feature Transform, or SURF, the Speeded-Up Robust Features, or any number of other hand-tuned pipelines. - Dump the resulting representations into a linear model (or a kernel method which generates a linear model in feature space) to solve the machine learning part. the really important aspects of the ML for CV pipeline were data and features. A slightly cleaner dataset, or a slightly better hand-tuned feature mattered a lot to the final accuracy. However, the specific choice of classifier was little more than an afterthought. At the end of the day you could throw your features in a logistic regression model, a support vector machine, or any other classifier of choice, and they would all perform roughly the same. 5.7.1. Learning Feature Representation¶ Another way to cast the state of affairs is that the most important part of the pipeline was the representation. And up until 2012, this part was done mechanically, based on some hard-fought intuition. In fact, engineering a new set of feature functions, improving results, and writing up the method was a prominent genre of paper. SIFT, SURF, HOG, Bags of visual words and similar feature extractors ruled the roost. Another group of researchers had different plans. They believed that features themselves ought to be learned. Moreover they believed that to be reasonably complex, the features ought to be hierarchically composed. These researchers, including Yann LeCun, Geoff Hinton, Yoshua Bengio, Andrew Ng, Shun-ichi Amari, and Juergen Schmidhuber believed that by jointly training many layers of a neural network, they might come to learn hierarchical representations of data.. Indeed, it learned good feature extractors in the lower layers. The figure below is reproduced from this paper and it describes lower level image descriptors. Fig. 5.9 Image filters learned by the first layer of AlexNet Higher layers might build upon these representations to represent larger structures, like eyes, noses, blades of grass, and features. Yet higher layers might represent whole objects like people, airplanes, dogs, or frisbees. And ultimately, before the classification layer, the final hidden state might represent a compact representation of the image that summarized the contents in a space where data belonging to different categories would be linearly separable. It should be emphasized that the hierarchical representation of the input is determined by the parameters in the multilayer model, and these parameters are all obtained from learning. Indeed, the visual processing system of animals (and humans) works a bit like that. At its lowest level it contains mostly edge detectors, followed by more structured features. Although researchers dedicated themselves to this idea and attempted to study the hierarchical representation of visual data, their ambitions went unrewarded until 2012. This was due to two key factors. 5.7.1.1. Missing Ingredient - Data¶ A deep model with many layers requires a large amount of data to achieve better results than convex models, such as kernel methods. However, given the limited storage capacity of computers, the fact that sensors were expensive and the comparatively tighter research budgets in the 1990s, most research relied on tiny datasets. For example, many research papers relied on the UCI corpus of datasets, many of which contained hundreds or a few thousand images of low resolution, which were taken in unnatural settings. This situation was improved by the advent of big data around 2010. In particular, the ImageNet data set, which was released in 2009, contains 1,000 categories of objects, each with thousands of different images. This scale was unprecedented. It pushed both computer vision and machine learning research towards deep nonconvex models. 5.7.1.2. Missing Ingredient - Hardware¶ Deep Learning has a voracious appetite for computation. This is one of the main reasons why in the 90s and early 2000s algorithms based on convex optimization were the preferred way of solving problems. After all, convex algorithms have fast rates of convergence, global minima, and efficient algorithms can be found. The game changer was the availability of GPUs. They had long been tuned for graphics processing in computer games. In particular, they were optimized for high throughput 4x4 matrix-vector products, since these are needed for many computer graphics tasks. Fortunately, the math required for that is very similar to convolutional layers in deep networks. Furthermore, around that time, NVIDIA and ATI had begun optimizing GPUs for general compute operations, going as far as renaming them GPGPU (General Purpose GPUs). To provide some intuition, consider the cores of a modern microprocessor. Each of the cores is quite powerful, running at a high clock frequency, it has quite advanced and large caches (up to several MB of L3). Each core is very good at executing a very wide range of code, with branch predictors, a deep pipeline and lots of other things that make it great at executing regular. Compare that with GPUs.. 5.7.2. AlexNet¶ AlexNet was introduced in 2012, named after Alex Krizhevsky, the first author of the eponymous paper. AlexNet uses an 8-layer convolutional neural network and won the ImageNet Large Scale Visual Recognition Challenge 2012 with which removes the quirks that were needed in 2012 to make the model fit on two small GPUs. Fig. 5.10 LeNet (left) and AlexNet (right). This improved convergence during training significantly. Let’s delve into the details below. 5.7.2.1. Architecture¶ In AlexNet’s first layer, the convolution window shape is \(11\times11\). Since most images in ImageNet are more than ten times higher and wider than the MNIST images, objects in ImageNet images take up one GPU only needs to process half of the model. Fortunately, GPU memory has developed tremendously over the past few years, so we usually do not need this special design anymore (our model deviates from the original paper in this aspect). 5.7. 5.7.2.3. Capacity Control and Preprocessing¶ AlexNet controls the model complexity of the fully connected layer by dropout section), preprocessing in detail in a subsequent section. In [1]: import gluonbook as g. In [2]:) 5.7.3. Reading Data¶ Although AlexNet uses ImageNet in the paper, we use Fashion-MNIST. This is simply since training on ImageNet would take hours even on modern GPUs. One of the problems with applying AlexNet directly is that the images are simply too low resolution at \(28 \times 28\) pixels. To make things work we upsample them to \(244 \times 244\) (this is generally not very smart but we do so to illustrate network performance). This can be done with the Resize class. We insert it into the processing pipeline before using the ToTensor class. The Compose class to concatenates these two changes for easy invocation. In [3]: # This function has been saved in the gluonbook) 5.7. In [4]: lr, num_epochs, ctx = 0.01, 5, gb.try_gpu() net.initialize(force_reinit=True, ctx=ctx, init=init.Xavier()) trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr}) gb.train_ch5(net, train_iter, test_iter, batch_size, trainer, ctx, num_epochs) training on gpu(0) epoch 1, loss 1.2859, train acc 0.518, test acc 0.764, time 70.2 sec epoch 2, loss 0.6348, train acc 0.763, test acc 0.815, time 65.5 sec epoch 3, loss 0.5173, train acc 0.808, test acc 0.847, time 65.6 sec epoch 4, loss 0.4530, train acc 0.833, test acc 0.862, time 65.5 sec epoch 5, loss 0.4123, train acc 0.849, test acc 0.868, time 65.6 sec 5.7. 5.7.6. Problems?
http://gluon.ai/chapter_convolutional-neural-networks/alexnet.html
CC-MAIN-2019-04
refinedweb
1,547
57.27
07 March 2012 05:21 [Source: ICIS news] By Helen Yan SINGAPORE (ICIS)--Synthetic rubber (SR) makers in Asia are holding out for further declines in butadiene (BD) values in the hope of regaining margins, placing bids for their main feedstock for production at about $100/tonne (€76/tonne) lower than sellers’ price ideas this week, market sources said on Wednesday. Buying indications fell to $3,350-3,400/tonne CFR (cost and freight) northeast (NE) ?xml:namespace> BD has been on a decline for the third week, with Chinese olefins major Sinopec announcing a yuan (CNY) 1,500/tonne ($238/tonne) reduction to its domestic BD price to CNY26,000/tonne early in the week, traders said. In the week ended 2 March, spot BD prices were assessed at $3,500-3,550/tonne CFR NE Asia, according to ICIS. A sales tender for a late March shipment of a 2,000-tonne parcel last week drew little interest compared with previous sales tenders in February, traders said. “I understand that the some Chinese suppliers and traders may try to offload their stocks as soon as possible as they fear that the BD prices may drop further,” a trader said. BD prices have raced ahead of the derivative butadiene rubber (BR) prices, wiping out the margins of BR producers. In the month of February, feedstock BD prices averaged $3,800/tonne CFR NE Asia, higher than the average BR values of $3,700/tonne CFR NE Asia, according ICIS data. BR has to be priced $600-700/tonne higher than BD for BR producers to generate any margin, industry sources said. “Our buying idea for March shipment of BD is $3,350/tonne CFR NE Asia as the BD prices were higher than the BR prices in February, and our margins were negative,” a major Korean SR producer said. The downstream SR producers have seen their margins being eroded or wiped out by escalating BD costs, which hit $4,000/tonne CFR NE Asia in early February. “We could not absorb the high BD costs and cannot continue to operate at a loss, so a lower BD price helps to ease the costs pressure,” a BR producer said. To stem their losses and regain their margins, several downstream SBR and BR producers in BST Elastomers of Thailand is the latest to join the growing list of SR makers cutting output in response to high BD prices. The Thai company plans to shut its 55,000 tonne/year BR plant in Map Tha Phut from 15-28 March. Other BR and SBR producers that have cut production include TSRC-UBE, Huayu Rubber, Shanghai Gaoqiao and Fuxiang Chemical in China, TSRC of Taiwan and LG Chem and KKPC of South Korea. BR and SBR are used in the manufacture of tyres for the automobile industry. ($1 = €0.76 /
http://www.icis.com/Articles/2012/03/07/9538931/asia-sr-makers-hold-out-for-lower-bd-prices-to-regain-margins.html
CC-MAIN-2014-42
refinedweb
477
60.38
All VM output goes to stderr by default. These routines provide the helpers for such output. #include <windows.h> #include <stdio.h> #include "hyport.h" #include "portpriv.h" #include "hyportpg.h" Determine the number of characters remaining to be read from stdin. Output message to stderr. Output message to stderr. Read characters from stdin into buffer. Write characters to stderr. PortLibrary shutdown. This function is called during shutdown of the portLibrary. Any resources that were created by hytty_startup should be destroyed here. PortLibrary startup. This function is called during startup of the portLibrary. Any resources that are required for the TTY library operations may be created here. All resources created here should be destroyed in hytty_shutdown. Output message to stderr. Genereated on Tue Dec 9 14:12:59 2008 by Doxygen. (c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable.
http://harmony.apache.org/externals/vm_doc/html/hytty_8c.html
CC-MAIN-2015-48
refinedweb
144
64.17
#include "ltwrappr.h" L_BOOL LImageViewerCell::IsTitlebarIconChecked(nSubCellIndex, nIconIndex, uFlags) Determines whether the specific title bar icon of the specific cell or sub-cell is checked or unchecked. A zero-based index into the image list attached to the cell. The status of the icon attached to the sub-cell at this index will be retrieved. Pass -2 to retrieve the status of the icon attached to the active sub-cell. A zero-based index of the icon to retrieve its status. Reserved for future use. Pass 0. To check or uncheck a specific title bar icon, call the LImageViewerCell::CheckTitlebarIcon function. Required DLLs and Libraries For an example, refer to LImageViewerCell::ShowTitlebar. Direct Show .NET | C API | Filters Media Foundation .NET | C API | Transforms Media Streaming .NET | C API
https://www.leadtools.com/help/sdk/v22/imageviewer/clib/limageviewercell-istitlebariconchecked.html
CC-MAIN-2021-43
refinedweb
129
60.51
Details Description. Issue Links - is depended upon by HBASE-1861 Multi-Family support for bulk upload tools (HFileOutputFormat / loadtable.rb) - Closed - relates to - Activity - All - Work Log - History - Activity - Transitions A really cool feature for bulk loading would be artificially lowering the split size so that splits occur really often, at least until there are as many regions as there are regionservers. That way, the load operation could have a lot more parallelism early on..). Actually you wouldn't have to be too concerned with the distribution of splits early on, because even if some of the regions ended up being abnormally small, they would eventually be merged with neighboring regions, no? Eventually that might be true but merging is currently a manually-triggered operation. Also, unless a more intelligent heuristic were in place, a small region would count against a whole region server until it was merged, which would slow down the loading. Would not the best way to do this would be to do a map that formats and sorts the data per column family then a reduce that writes a mapfiles directly to the regions columns? Then that would skip the api and speed up the loading of the data and it would not matter so much if we has 1 region or not sense all we would be doing is adding a mapfile to hdfs. Course the map would have to know if there is 1 region or 1000 and split the data correctly but even if each map only produces a few lines of data per column family the compactor will come along sooner or later and clean up and split where needed. So if we add 100 map files to one column I would assume that it would slow reads down a little bit havening to sort threw all the map files while scanning but that would be a temporary speed problem. Yes. Going behind the API would be the faster way to load hbase. It'd be dangerous to do into a live hbase. Should we write something like TableOutputFormatter except it writes region files directly into hdfs? It'd make a region per reducer instance? It'd know how to write keys, etc. properly and what location in hdfs to place files. In theory, writing directly to HDFS would be the fastest way to import data. However, the tricky part in my mind is that you need all the partitions not just to be sorted internally but sorted amongst each other. This means that the partitioning function you use has to be able to sort lexically as well. Without knowing what the data looks like ahead of time, how can you know how to efficiently partition the data into regions? This doesn't account for trying to import a lot of data into a new table. In that case, it'd be quite futile to write tons of data into the existing regions range, because that would just cause the existing regions would just become enormous, and then all you're really doing is putting off the speed hit until the split/compact stage. What is it that actually holds back the speed of imports? The API mechanics and nothing else? The number of region servers participating in the import? The speed of the underlying disk? Do we even have a sense of what would be a good speed for bulk imports in the first place? I think this issue needs better definition before we can say what we should do. If a new table, make a region per reducer (Configure many reducers if table is big). The framework will have done the sorting (lexigraphically if thats our key compare function) for us (Might have to add to the framework to ensure we don't split a key in the middle of a row). If a table that already exists, would be reducer per existing region and yeah, there'll be a splitting and compacting price to pay. To see difference in speeds going via API versus writing direct to mapfiles, see primitive PerformanceEvaluation and compare numbers writing mapfiles directly rather than going API. Something HBase should have is a BatchUpdate that takes multiple row keys. A simple version of it would be doing many BatchUpdate like we already have but in an iteration. An enhanced version would instead do something like this when there is only a few regions : - Sort the row keys - Sample some rows to get an average row size - Using the existing region(s) with the row keys to insert and the average row size, figure how the splits would be done - Insert the missing rows that would be the new lows and highs - Force the desired splits - Insert remaining data Thinking more on this issue, in particular on Billy's suggestion above ('Billy Pearson - 06/Feb/08 01:07 PM'), bulk uploading by writing store files ain't hard: For a new table (as per Bryan above), its particularly easy. Do something like: + Create table in hbase + Mark it read-only or disabled even. + Start mapreduce job. In its configuration would go to the master to read the table description. + Map reads whatever the input using whatever formatter and ouputs from the map using HStoreKey for key and cell content for value. + Job would use fancy new TableFileReduce. Each reducer would write a region. It'd know what for start and end keys – they'd be the first and last it'd see. Could output these somewhere so a tail task could find them. The file outputter would need to also do sequenceids of some form. + When job was done, tail task would insert regions into meta using MetaUtils. + Enable the table. + If regions are lop-sided, hbase will do the fixup. If table already exists: + Mark table read-only (ensure this prevents splits and that it means memcache is flushed) + Start a mapreduce job that read from master the table schema and its regions (and the master's current time so we don't write records older). + Map as above. + Reducer as above only insert smarter partitioner, one that respected region boundaries and that made a reducer per current region. + Enable hbase and let it fix up where storefiles written were too big by splitting etc. It don't seem hard at all to do. With a read-only option that would simplify things a lot. Do we have this yet I remember reading something about adding it in the past. Been thanking on this one what happens if a region get to many map files written to it and there to large to compaction and we OOME because of lack memory to compact the files or will this not happen? Here is a patch to add to classes to MapReduce: KeyValueSortReducer and HFileOutputFormat. This patch also adds a small test class that runs a MR job that has custom mapper and inputformat. The inputformat produces PerformanceEvaluation type keys and values (keys are a zero-padded long and values are random 1k of bytes). The mapper takes this inputformat and outputs the key as row and then makes a KeyValue of the row, a defined column and the value. KeyValueSortReducer takes as input an ImmutableBytesWritable as key/row. It then pulls on the Iterator to read in all of the passed KeyValues, sorts then, and then starts outputting the sorted key/row+KeyValue. HFileOutputFormat takes ImmutableBytesWritable and KeyValue. On setup, it reads configuration for stuff like blocksize and compression to use. It then writes HFiles of < hbase.hregion.max.filesize size. Next I'll work on a script that takes an HTableDescriptor and some other parameters and that then puts the output of this MR into proper layout in HDFS with an hfile per region making proper insertions into catalog tables. Have HFileOutputFormat handle multiple families. Reducer can pass any number of families and HFO will write hfiles to family named subdirs. Start of a script that will move hfiles into place under hbase.rootdir and that then updates catalog table. Not finished yet. More fixup. Add the script to the patch. Turns out, multiple families is a bit more complicated. Can do that later if wanted. This patch seems to basically work. I took files made by the TestHFileInputFormat test and passed them to the script as follows: $ ./bin/hbase org.jruby.Main bin/loadtable.rb xyz /tmp/testWritingPEData/ The script expects hbase to be running. It ran through the list of hfiles, read their meta info and last key. It then sorted the hfiles by end key. It makes a HTableDescriptor and HColumnDescriptor with defaults (If want other than defaults, then after upload, alter table). It then takes the sorted files and per file moves it into place and adds a row to .META. Doesn't take long. The meta scanner runs after the upload and deploys the regions. Done. I'll not work on this anymore, not till someone else wants to try it. I deleted my last comment. It was duplication of stuff said earlier in this issue a good while ago. I changed title of this issue to only be about bulk upload. The bulk dump is going on elsewhere: e.g. HBASE-1684 On earlier comments about splitting table so at least a region per regionserver, that ain't hard to do now. You can do it via UI – force a split – or just write a little script to add a table and initial region range (for example, see the script in the attached patch). I think criteria for closing this issue is commit of some set of tools that allow writing hfiles either into new tables or into extant tables. Two things. 1. Manish Shah points out that we need to ensure a total ordering of all keys (See pg.218 of hadoop book and on). We need to supply a partitioner that does total ordering AND that ensures we don't partition across rows (Thanks for this Manish). 2. Current patch does not guarantee rows do not span storefiles. Oh, and 3., to do multiple families shouldn't be hard; just rotate all files when one is in excess of maximum (on a row boundary) Updated patch. Rolls hfile now at row boundary. Regards TotalOrderPartitioner, there is no such facility in the new mapreduce package. That said, shouldn't be too hard making a partitioner of our own. Here is the default hash partitioner: /** Use {@link Object#hashCode()} to partition. */ public int getPartition(K key, V value, int numReduceTasks) { return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks; } We could take as inputs a start and end key and then divide the key space using our key bigdecimal math into numReduceTasks partitions? v5 patch does not include ruby script. Posted ruby script is incomplete. Working one was in v4 patch. Will attach new patch shortly. The MR job is working tremendously well for me. I'm able to almost instantly saturate my entire cluster during an upload and it remains saturated until the end. Full CPU usage, lots of io-wait, so I'm disk io-bound as I should be. I did a few runs of a job which imported between 1M and 10M rows, each row containing a random number of columns from 1 to 1000. In the end, I imported between 500M and 5B KeyValues. On a 5 node cluster of 2core/2gb/250gb nodes, I could import 1M rows / 500M keys in 7.5 minutes (2.2k rows/sec, 1.1M keys/sec). On a 10 node cluster of 4core/4gb/500gb nodes, I could do the same import in 2.5 minutes. On this larger cluster I also ran the same job but with 10M rows / 5B keys in 25 minutes (6.6k rows/sec, 3.3M keys/sec). Previously running HTable-based imports on these clusters, I was seeing between 100k and 200k keys/sec, so this represents a 5-15X speed improvement. In addition, the imports finish without any problem (I would have killed the little cluster running these imports through HBase). I think there is a bug with the ruby script though. It worked sometimes, but other times it ended up hosing the cluster until I restarted. Things worked fine after restart. Still digging... I've got this working. Running final tests on branch and trunk and will post patch. Patch that applies cleanly to branch. Includes two modifications to the ruby script. Ignores _log directories (preventing multiple-family error) and copies hfiles into proper region directories, after creating them. Running final test now. v6 patch works as advertised. Just imported 200k rows with avg of 500 columns each for 100M total KVs (24 regions). MR job ran in under 2 minutes into a 4 node cluster of 2core/2gb/250gb nodes. Ruby script takes 3-4 seconds and then about 30 seconds for cluster to assign out regions. I'm ready to commit this to trunk and branch though we need some docs. Will open separate JIRA for multi-family support. This version adds doc to the mapreduce package-info explaining how bulk import works. Committed last patch to trunk and branch (jgray reviewed and tested). Opening new issue for multi-family bulk import. This issue was closed as part of a bulk closing operation on 2015-11-20. All issues that have been resolved and where all fixVersions have been released have been closed (following discussions on the mailing list). Bulk uploader needs to be able to tolerate myriad data input types. Data will likely need massaging and ultimately, if writing HRegion content directly into HDFS rather than going against hbase API – preferred since it'll be dog slow doing bulk uploads going against hbase API – then it has to be sorted. Using mapreduce would make sense. Look too at using PIG because it has a few LOAD implementations – from files on local or HDFS – and some facility for doing transforms on data moving tuples around. Would need to write a special STORE operator that wrote the data sorted out as HRegions direct into HDFS (This would be different than PIG-6which is about writing into hbase via API). Also, chatting with Jim, this is a pretty important issue. This is the first folks run into when they start to get serious about hbase.
https://issues.apache.org/jira/browse/HBASE-48
CC-MAIN-2017-39
refinedweb
2,393
72.36
view raw Im trying to make a troubleshooting system however it comes up with an error saying issue is not defined, how do i correct this? Also could i continue with the array im using to add in more questions and answers e.g 4th could be "sound"? thanks def troubleshooting(): print("Welcome to my phone troubleshooting system...") problem = raw_input("Type the problem with the phone:") problem = ['cracked', 'crack', 'broken'] if problem[0] in issue: print("Replace screen") elif problem[1] in issue: print("Replace screen") elif problem[2] in issue: print("Replace phone") else: print("Replace screen") issue is not defined because you made a little mistake you put what the user typed inside problem instead of issue with that line : problem = raw_input("Type the problem with the phone:")
https://codedump.io/share/7A8EqNeWwI1D/1/how-do-i-define-something-in-python-27
CC-MAIN-2017-22
refinedweb
130
55.78
This is the simple Ticker example which is used to auto scroll the data on the top of the form. It continuously scroll the data. AdsTutorials This is the simple Ticker example which is used to auto scroll the data on the top of the form. It continuously scroll the data. The javax.microedition.lcdui.Ticker has only one constructor that is: Ticker(String str):- This is used to Constructs a new Ticker object, given its initial contents string. And it has two methods: getString():- This is the String type methods which Gets the string currently being scrolled by the ticker. setString(String str):- This is the void type, it Sets the string to be displayed by this ticker. The Application looked as below: Source Code of TickerExample.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TickerExample extends MIDlet implements CommandListener{ private Display display; private Ticker ticker; private Command exit; private Form form; public TickerExample(){ form = new Form("BSE Stock Exchange Ticker"); display = Display.getDisplay(this); ticker = new Ticker ("10/17/2008 3:59:59 PM ACC LTD 489.05 (-6.42%) BHARTI ARTL 676.80 (-7.47%) BHEL 1,194.80 (-9.00%) ACC LTD 489.05 (-6.42%) BHARTI ARTL 676.80 (-7.47%) BHEL 1,194.80 (-9.00%) DLF LTD* 291.30 (-10.34%) GRASIM INDUSTRIES LTD. 1,293.40 (-5.71%) HDFC BANK LT 1,024.05 (-5.82%)"); exit = new Command("Exit", Command.SCREEN, 1); form.addCommand(exit); form.setCommandListener(this); form.setTicker(ticker); } public void startApp(){ display.setCurrent(form); } public void pauseApp(){ } public void destroyApp(boolean unconditional){ notifyDestroyed(); } public void commandAction(Command c, Displayable display){ String label = c.getLabel(); if (label.equals("Exit")){ destroyApp(false); } } } Advertisements Posted on: October 24, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles Advertisements Ads Ads Discuss: J2ME Ticker Example View All Comments Post your Comment
https://www.roseindia.net/j2me/TickerExample.shtml
CC-MAIN-2017-39
refinedweb
321
52.66
In this short post, we are going to learn how to turn the code from blog posts to Jupyter notebooks. Specifically, we will learn how to convert HTML to Jupyter Notebooks (.ipynb). In this post, we are going to use the Python packages BeautifulSoup4, json, and urllib. We are going to use these packages to scrape the code from webpages putting their code within <code></code>. Note, this code is not intended to steal other people’s code. I created this script to scrape my code and save it to Jupyter notebooks because I noticed that my code, sometimes did not work as intended. Install the Needed Packages Now, we need to install BeautifulSoup4 before we continue converting HTML to Jupyter notebooks. Furthermore, we need to install lxml. How to Install Python Packages using conda In this section, we are going to learn how to install the needed packages using the packages manager conda. First, open up the Anaconda Powershell Prompt Now, we are ready to install BeautifulSoup4. conda -c install anaconda beautifulsoup4 lxml How to Install Python Packages using Pip It is, of course, possible to install the packages using pip as well: install beautifulsoup4 lxml See the more recent post about installing packages in Python for more information. How to Convert HTML to a Jupyter Notebook Now, when we have installed the Python packages, we can continue with scraping the code from a web page. In the example, below, we will start by importing BeautifulSoup from bs4, json, and urllib. Next, we have the URL to the webpage that we want to convert to a Jupyter notebook (this). from bs4 import BeautifulSoup import json import urllib url = '' Setting a Custom User-Agent In the next line of code, we create the dictionary headers. This is because many websites (including the one you are reading now) will block web scrapers and this will prevent that from happening. headers = {'} In the next code chunk, we are going to create a Request object. This object represents the HTTP request we are making. Simply put, we create a Request object that specifies the URL we want to retrieve. Furthermore, we are calling urlopen using the Request object. This will, in turn, a response object for the requested URL. Finally, we call .read() on the response: req = urllib.request.Request(url, headers=headers) page = urllib.request.urlopen(req) text = page.read() We are now going to use BeautifulSoup4 to get make it easier to scrape the HTML: soup = BeautifulSoup(text, 'lxml') soup Jupyter Notebook Metadata Now we’re ready to convert HTML to a Jupyter Notebook (this code was inspired by this code example). First, we start by creating some metadata for the Jupyter notebook. In the code below, we start by creating a dictionary in which we will, later, store our scraped code elements. This is going to be the metadata for the Jupyter notebook we will create. Note, .ipynb are simple JSON files, containing text, code, rich media output, and metadata. The metadata is not required but here we will add what language we are using (i.e., Python 3). create_nb = {'nbformat': 4, 'nbformat_minor': 2, 'cells': [], 'metadata': {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3" }}} More information bout the format of Jupyter notebooks can be found here. Getting the Code Elements from the HTML Second, we are creating a Python function called get_code. This function will take two arguments. First, the beautifulsoup object, we earlier created, and the content_class to search for content in. In the case, of this particular WordPress, blog this will be post-content Next, we are looping through all div tags in the soup object. Here, we only look for the post content. Next, we get all the code chunks searching for all code tags In the final loop, we are going through each code chunk and creating a new dictionary (cell) in which we are going to store the code. The important part is where we add the text, using the get_text method. Here we are getting our code from the code chunk and add it to the dictionary. Finally, we add this to the dictionary, nb_data, that will contain the data that we are going to save as a Jupyter notebook (i.e., the blog post we have scraped). def get_data(soup, content_class): for div in soup.find_all('div', attrs={'class': content_class}): code_chunks = div.find_all('code') for chunk in code_chunks: cell_text = ' ' cell = {} cell['metadata'] = {} cell['outputs'] = [] cell['source'] = [chunk.get_text()] cell['execution_count'] = None cell['cell_type'] = 'code' create_nb['cells'].append(cell) get_data(soup, 'post-content') with open('Python_MANOVA.ipynb', 'w') as jynotebook: jynotebook.write(json.dumps(create_nb)) - More about parsing JSON in Python Note, we get the nb_data which is a dictionary from which we will create our notebook. In the final two rows, of the code chunk, we will open a file (i.e., test.ipynb) and write to this file using the json dump method. Here’s a Jupyter notebook containing all code above. Conclusion: How to Convert HTML to Jupyter Noteboks (.ipynb) In this post, we have learned how to convert HTML pages to Jupyter notebooks. Specifically, we used BeautifulSoup, lxml, and Python.
https://www.marsja.se/converting-html-to-a-jupyter-notebook/?share=email
CC-MAIN-2020-24
refinedweb
860
64.81
A bit of history In PHP prior to 5.3 (2009), any class you define lived at the same global level as other classes. Class User, class Contact, class StripeBiller–they’re all together in the global namespace. This may seem simple, but it makes organization tough, which is why PHP developers started using underscores to separate their class names. For example, if I were developing a package called "Cacher", I might name the class Mattstauffer_Cacher so as to differentiate it from someone else’s Cacher–or Mattstauffer_Database_Cacher, to differentiate it from an API cacher. That worked decently, and there were even autoloading standards that separated out the underscores in class names for folders on the file system; for example, Mattstauffer_Database_Cacher would be assumed to live in the file Mattstauffer/Database/Cacher.php. An autoloader is a piece of code that makes it so that, instead of having to requireor include Mattstauffer_Database_Cacher could become class Cacher in the MattstaufferDatabase namespace: <?php class Mattstauffer_Database_Cacher {} is now: <?php namespace MattstaufferDatabase; class Cacher {} And we would refer to it elsewhere in the app as MattstaufferDatabaseCacher. A real examplearaniBilling and KaraniContacts. Let’s make a class or two in each: <?php namespace KaraniBilling; class Receipt {} <?php namespace KaraniBilling; class Subscription{} <?php namespace KaraniContacts; class Donor {} So, we’re picturing a directory structure like this: Karani Billing Receipt Subscription Contacts Donor Referencing other classes in the same namespace So, if a Subscription can send a Receipt, it’s easy to refer to it: <?php namespace KaraniBilling; Donor? <?php namespace KaraniContacts; class Donor { public function sendReceipt() { // This won't work! $receipt = new Receipt; } } You guessed it: This won’t work. We’re in the KaraniContacts namespace, so when we wrote new Receipt, PHP assumes we’re talking about KaraniContactsReceipt. But that class doesn’t exist, and that’s not what we’re looking for. So, you’ll get a Class KaraniContactsReceipt not found error. You might be tempted to modify it to instead say $receipt = new KaraniBillingReceipt–but even that won’t work. Since we’re in the KaraniContacts namespace right now, it’s seeing anything you write as being relative to the namespace you’re in. So that would try to load a class named KaraniContactsKaraniBillingReceipt, which also clearly doesn’t exist. Use blocks and Fully-Qualified Class Names Instead, you have two options: First, you can precede it with a slash to create its FQCN (Fully Qualified Class Name): $receipt = new KaraniBillingReceipt;, which sends the signal to PHP to escape out of the current namespace before looking for this class. If you precede the full namespace with a slash, creating the FQCN, you can refer to this class anywhere in your app without worrying about your current namespace. Or, Second, you can use the class at the top of the file, and then just reference it as Receipt: <?php namespace KaraniContacts; use KaraniBillingReceipt; class Donor { you also have a Receipt class in your current namespace? What if your class needs access to both KaraniContactsReceipt and KaraniBillingReceipt? You can’t just import the KaraniBillingReceipt class, or you won’t be able to use both–they’d both have the same name in this class. Instead, you’ll need to alias it. You can change the use statement to something like use KaraniBillingReceipt Karani namespace to live in my src folder. Here’s my folder structure for a generic, framework-independent project: app public src Billing Contacts vendor As you can see, the src folder represents the Karani": { "Karani\": "src/" } } } So you can see: the left side is the namespace that we’re defining (note that you need to escape the slash separators here by doubling them), and the right side is the directory. Conclude. file. Source link
http://smartsoftware247.com/a-brief-introduction-to-php-namespacing/
CC-MAIN-2019-22
refinedweb
622
61.26
F Sharp Programming/Print version The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at Preface How This Book Came To BeEdit -), that is part of Standard Libraries., its most famous dialect called OCaml which unifies functional programming with object-oriented and imperative styles, and Haskell.. ReferencesEdit Getting Set Up WindowsEdit At the time of this writing, its possible to run F# code through Visual Studio, through its interactive top-level F# Interactive (fsi), and compiling from the command line. This book will assume that users will compile code through Visual Studio or F# Interactive by default, unless specifically directed to compile from the command line. Setup ProcedureEdit F# can integrate with existing installations of Visual Studio 2008 and is included with Visual Studio 2010. Alternatively, users can download Visual Studio Express or Community for free, which will provide an F# pioneer with everything one needs to get started, including interactive debugging, breakpoints, watches, Intellisense, and support for F# projects. Make sure all instances of Visual Studio and Visual Studio Shell are closed before continuing. To get started, users should download and install the latest version of the .NET Framework from Microsoft. Afterwards, download the latest version of F# from the F# homepage on Microsoft Research, then execute the installation wizard. Users should also consider downloading and installing the F# PowerPack, which contains handy extensions to the F# core library. After successful installation, users will notice an additional folder in their start menu, "Microsoft F# 2.0.X.X." Additionally, users will notice that an entry for "F# Projects" has been added to the project types menu in Visual Studio. From here, users can create and run new F# projects. It is a good idea to add the executable location (e.g. c:\fsharp\bin\) to the %PATH% environment variable, so you can access the compiler and the F# interactive environment (FSI) from any location. As of Visual Studio 2012 the easiest way to get going is to install Visual Studio 2012 for Web at [1] (even if you want to do desktop solution). You can then install "F# Tools for Visual Studio Express 2012 for Web" from [2]. Once this is done you can create F# projects. Search Nuget for additional F# project types. Testing the InstallEdit Hello World executableEdit Lets create the Hello World standalone application. Create a text file called hello.fs containing the following code: (* filename: hello.fs *) let _ = printf "Hello world" The underscore is used as a variable name when you are not interested in the value. All functions in F# return a value even if the main reason for calling the function is a side effect. Save and close the file and then compile this file: fsc -o hello.exe hello.fs Now you can run hello.exe to produce the expected output. F# Interactive EnvironmentEdit Open a command-line console (hit the "Start" button, click on the "Run" icon and type cmd and hit ENTER). Type fsi and hit ENTER. You will see the interactive console: Microsoft F# Interactive, (c) Microsoft Corporation, All Rights Reserved F# Version 1.9.6.2, compiling for .NET Framework Version v2.0.50727 Please send bug reports to fsbugs@microsoft.com For help type #help;; > We can try some basic F# variable assignment (and some basic maths). > let x = 5;; val x : int > let y = 20;; val y : int > y + x;; val it : int = 25 Finally we quit out of the interactive environment > #quit;; Misc.Edit Adding to the PATH Environment VariableEdit - Go to the Control Panel and choose System. - The System Properties dialog will appear. Select the Advanced tab and click the "Environment Variables...". - In the System Variables section, select the Path variable from the list and click the "Edit..." button. - In the Edit System Variable text box append a semicolon (;) followed by the executable path (e.g. ;C:\fsharp\bin\) - Click on the "OK" button - Click on the "OK" button - Click on the "Apply" button Now any command-line console will check in this location when you type fsc or fsi. Mac OSX, Linux and UNIXEdit F# runs on Mac OSX, Linux and other Unix versions with the latest Mono. This is supported by the F# community group called the F# Software Foundation. Installing interpreter and compilerEdit The F# Software Foundation give latest instructions on getting started with F# on Linux and Mac. Once built and/or installed, you can use the "fsharpi" command to use the command-line interpreter, and "fsharpc" for the command-line compiler. MonoDevelop add-inEdit The F# Software Foundation also give instructions for installing the Monodevelop support for F#. This comes with project build system, code completion, and syntax highlighting support. Emacs mode and other editorsEdit The F# Software Foundation also give instructions for using F# with other editors. An emacs mode for F# is also available on Github. Xamarin Studio for Mac OSX and WindowsEdit F# runs on Mac OSX and Windows with the latest Xamarin Studio. This is supported by Microsoft. Xamarin Studio is an IDE for developing cross-platform phone apps, but it runs on Mac OSX and implements F# with an interactive shell.. Major FeaturesEdit Fundamental Data Types and Type SystemEditEditEditEdit F# is a mixed-paradigm language: it supports imperative, object-oriented, and functional styles of writing code, with heaviest emphasis on the latter. Immutable Values vs VariablesEditEditEdit F# is a functional programming language, meaning that functions are first-order data types: they can be declared and used in exactly the same way that any other variable can be used. In an imperative language like Visual Basic, there has traditionally been a fundamental difference between variables and functions. Function MyFunc(param As Integer) MyFunc = (param * 2) + 7 End Function ' The program entry point; all statements must exist in a Sub or Function block. Sub Main() Dim myVal As Integer ' Also statically typed as Integer, as the compiler (for newer versions of VB.NET) performs local type inference. Dim myParam = 2 myVal = MyFunc(myParam) End Subroutine routine - return a function as the result of another function Structure of F# ProgramsEdit A simple, non-trivial F# program has the following parts: open System (* This is a multi-line comment *) // This is a single-line comment let rec fib = function | 0 -> 0 | 1 -> 1 | n -> fib (n - 1) + fib (n - 2) [<EntryPoint>] let main argv = printfn "fib 5: %i" (fib 5) 0: [<EntryPoint>] let main argv = // Code to be executed 0 The entry point of an F# program is marked by the [<EntryPoint>] attribute, and following it must be a function that accepts an array of strings as input and returns an integer (by default, 0) Values and Functions Compared to other .NET languages such as C# and VB.Net, F# has a somewhat terse and minimalistic syntax. To follow along in this tutorial, open F# Interactive (fsi) or Visual Studio and run the examples. Declaring VariablesEdit The most ubiquitous, familiar keyword in F# is the let keyword, which allows programmers to declare functions and variables in their applications. For example: let x = 5 This declares a variable called x and assigns it the value 5. Naturally, we can write the following: let x = 5 let y = 10 let z = x + y z now holds the value 15. A complete program looks like this: let x = 5 let y = 10 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z The statement printfn prints text out to the console window. As you might have guessed, the code above prints out the values of x, y, and z. This program results in the following: x: 5 y: 10 z: 15 Note to F# Interactive users: all statements in F# Interactive are terminated by ;;(two semicolons). To run the program above in fsi, copy and paste the text above into the fsi window, type ;;, then hit enter. Values, Not VariablesEdit In F#, "variable" is a misnomer. In reality, all "variables" in F# are immutable; in other words, once you bind a "variable" to a value, it's stuck with that value forever. For that reason, most F# programmers prefer to use "value" rather than "variable" to describe x, y, and z above. Behind the scenes, F# actually compiles the "variables" above as static read-only properties. Declaring FunctionsEdit There is little distinction between functions and values in F#. You use the same syntax to write a function as you use to declare a value: let add x y = x + y add is the name of the function, and it takes two parameters, x and y. Notice that each distinct argument in the functional declaration is separated by a space. Similarly, when you execute this function, successive arguments are separated by a space: let z = add 5 10 This assigns z the return value of this function, which in this case happens to be 15. Naturally, we can pass the return value of functions directly into other functions, for example: let add x y = x + y let sub x y = x - y let printThreeNumbers num1 num2 num3 = printfn "num1: %i" num1 printfn "num2: %i" num2 printfn "num3: %i" num3 printThreeNumbers 5 (add 10 7) (sub 20 8) This program outputs: num1: 5 num2: 17 num3: 12 Notice that I have to surround the calls to add and sub functions with parentheses; this tells F# to treat the value in parentheses as a single argument. Otherwise, if we wrote printThreeNumbers 5 add 10 7 sub 20 8, its not only incredibly difficult to read, but it actually passes 7 parameters to the function, which is obviously incorrect. Function Return ValuesEdit Unlike many other languages, F# functions do not have an explicit keyword to return a value. Instead, the return value of a function is simply the value of the last statement executed in the function. For example: let sign num = if num > 0 then "positive" elif num < 0 then "negative" else "zero" This function takes an integer parameter and returns a string. As you can imagine, the F# function above is equivalent to the following C# code: string Sign(int num) { if (num > 0) return "positive"; else if (num < 0) return "negative"; else return "zero"; } Just like C#, F# is a strongly typed language. A function can only return one datatype; for example, the following F# code will not compile: let sign num = if num > 0 then "positive" elif num < 0 then "negative" else 0 If you run this code in fsi, you get the following error message: > let sign num = if num > 0 then "positive" elif num < 0 then "negative" else 0;; else 0;; ---------^ stdin(7,10): error FS0001: This expression was expected to have type string but here has type int The error message is quite explicit: F# has determined that this function returns a string, but the last line of the function returns an int, which is an error. Interestingly, every function in F# has a return value; of course, programmers don't always write functions that return useful values. F# has a special datatype called unit, which has just one possible value: (). Functions return unit when they don't need to return any value to the programmer. For example, a function that prints a string to the console obviously doesn't have a return value: let helloWorld () = printfn "hello world" This function takes unit parameter and returns (). You can think of unit as the equivalent to void in C-style languages. How To Read Arrow NotationEdit All functions and values in F# have a data type. Open F# Interactive and type the following: > let addAndMakeString x y = (x + y).ToString();; F# reports the data type using chained arrow notation as follows: val addAndMakeString : x:int -> y:int -> string Data types are read from left to right. Before muddying the waters with a more accurate description of how F# functions are built, consider the basic concept of Arrow Notation: starting from the left, our function takes two int inputs and returns a string. A function only has one return type, which is represented by the rightmost data type in chained arrow notation. We can read the following data types as follows: int -> string - takes one intinput, returns a string float -> float -> float - takes two floatinputs, returns another float int -> string -> float - takes an intand a stringinput, returns a float This description is a good introductory way to understand Arrow Notation for a beginner—and if you are new to F# feel free to stop here until you get your feet wet. For those who feel comfortable with this concept as described, the actual way in which F# is implementing these calls is via currying the function. Partial Function ApplicationEdit While the above description of Arrow Notation is intuitive, it is not entirely accurate due to the fact that F# implicitly curries functions. This means that a function only ever has a single argument and a single return type, quite at odds with the previous description of Arrow Notation above where in the second and third example two arguments are passed to a function. In reality, a function in F# only ever has a single argument and a single return type. How can this be? Consider this type: float -> float -> float since a function of this type is implicitly curried by F#, there is a two step process to resolve the function when called with two arguments - a function is called with the first argument that returns a function that takes a float and returns a float. To help clarify currying, lets call this function funX (note that this naming is just for illustration purposes—the function that gets created by the runtime is anonymous). - the second function ('funX' from step 1 above) is called with the second argument, returning a float So, if you provide two floats, the result appears as if the function takes two arguments, though this is not actually how the runtime behaves. The concept of currying will probably strike a developer not steeped in functional concepts as very strange and non-intuitive—even needlessly redundant and inefficient, so before attempting a further explanation, consider the benefits of curried functions via an example: let addTwoNumbers x y = x + y this type has the signature of int -> int -> int then this function: let add5ToNumber = addTwoNumbers 5 with the type signature of (int -> int). Note that the body of add5ToNumber calls addTwoNumbers with only one argument—not two. It returns a function that takes an int and returns an int. In other words, add5toNumber partially applies the addTwoNumbers function. > let z = add5ToNumber 6;; val z : int = 11 This partial application of a function with multiple argument exemplifies the power of curried functions. It allows deferred application of the function, allowing for more modular development and code re-use—we can re-use the addTwoNumbers function to create a new function via partial application. From this, you can glean the power of function currying: it is always breaking down function application to the smallest possible elements, facilitating greater chances for code-reuse and modularity. Take another example, illustrating the use of partially applied functions as a bookkeeping technique. Note the type signature of holdOn is a function (int -> int) since it is the partial application of addTwoNumbers > let holdOn = addTwoNumbers 7;; val holdOn : (int -> int) > let okDone = holdOn 8;; val okDone : int = 15 Here we define a new function holdOn on the fly just to keep track of the first value to add. Then later we apply this new 'temp' function holdOn with another value which returns an int. Partially applied functions—enabled by currying—is a very powerful means of controlling complexity in F#. In short, the reason for the indirection resulting from currying function calls affords partial function application and all the benefits it supplies. In other words, the goal of partial function application is enabled by implicit currying. So while the Arrow Notation is a good shorthand for understanding the type signature of a function, it does so at the price of oversimplification, for a function with the type signature of f : int -> int -> int is actually (when taking into consideration the implicit currying): // curried version pseudo-code f: int -> (int -> int) In other words, f is a function that takes an int and returns a function that takes an int and returns an int. Moreover, f: int -> int -> int -> int is a simplified shorthand for // curried version pseudo-code f: int -> (int -> (int -> int)) or, in very difficult to decode English: f is a function that takes an int and returns a function that takes an int and returns a function that takes an int and returns an int. Yikes! Nested FunctionsEdit F# allows programmers to nest functions inside other functions. Nested functions have a number of applications, such as hiding the complexity of inner loops: let sumOfDivisors n = let rec loop current max acc = if current > max then acc else if n % current = 0 then loop (current + 1) max (acc + current) else loop (current + 1) max acc let start = 2 let max = n / 2 (* largest factor, apart from n, cannot be > n / 2 *) let minSum = 1 + n (* 1 and n are already factors of n *) loop start max minSum printfn "%d" (sumOfDivisors 10) (* prints 18, because the sum of 10's divisors is 1 + 2 + 5 + 10 = 18 *) The outer function sumOfDivisors makes a call to the inner function loop. Programmers can have an arbitrary level of nested functions as need requires. Generic FunctionsEdit In programming, a generic function is a function that returns an indeterminate type t without sacrificing type safety. A generic type is different from a concrete type such as an int or a string; a generic type represents a type to be specified later. Generic functions are useful because they can be generalized over many different types. Let's examine the following function: let giveMeAThree x = 3 F# derives type information of variables from the way variables are used in an application, but F# can't constrain the value x to any particular concrete type, so F# generalizes x to the generic type 'a: 'a -> int - this function takes a generic type 'aand returns an int. When you call a generic function, the compiler substitutes a function's generic types with the data types of the values passed to the function. As a demonstration, let's use the following function: let throwAwayFirstInput x y = y Which has the type 'a -> 'b -> 'b, meaning that the function takes a generic 'a and a generic 'b and returns a 'b. Here are some sample inputs and outputs in F# interactive: > let throwAwayFirstInput x y = y;; val throwAwayFirstInput : 'a -> 'b -> 'b > throwAwayFirstInput 5 "value";; val it : throwAwayFirstInput "thrownAway" 10.0;; val it : float = 10.0 > throwAwayFirstInput 5 30;; val it : int = 30 throwAwayFirstInput 5 "value" calls the function with an int and a string, which substitutes int for 'a and string for 'b. This changes the data type of throwAwayFirstInput to int -> string -> string. throwAwayFirstInput "thrownAway" 10.0 calls the function with a string and a float, so the function's data type changes to string -> float -> float. throwAwayFirstInput 5 30 just happens to call the function with two ints, so the function's data type is incidentally int -> int -> int. Generic functions are strongly typed. For example: let throwAwayFirstInput x y = y let add x y = x + y let z = add 10 (throwAwayFirstInput "this is a string" 5) The generic function throwAwayFirstInput is defined again, then the add function is defined and it has the type int -> int -> int, meaning that this function must be called with two int parameters. Then throwAwayFirstInput is called, as a parameter to add, with two parameters on itself, the first one of type string and the second of type int. This call to throwAwayFirstInput ends up having the type string -> int -> int. Since this function has the return type int, the code works as expected: > add 10 (throwAwayFirstInput "this is a string" 5);; val it : int = 15 However, we get an error when we reverse the order of the parameters to throwAwayFirstInput: > add 10 (throwAwayFirstInput 5 "this is a string");; add 10 (throwAwayFirstInput 5 "this is a string");; ------------------------------^^^^^^^^^^^^^^^^^^^ stdin(13,31): error FS0001: This expression has type string but is here used with type int. The error message is very explicit: The add function takes two int parameters, but throwAwayFirstInput 5 "this is a string" has the return type string, so we have a type mismatch. Later chapters will demonstrate how to use generics in creative and interesting ways.. Pattern Matching SyntaxEditEdit You can add additional parameters to the definition: let getPrice taxRate = function | "banana" -> 0.79 * (1.0 + taxRate) | "watermelon" -> 3.49 * (1.0 + taxRate) | "tofu" -> 1.09 * (1.0 + taxRate) | _ -> nan (* nan is a special value meaning "not a number" *) val getPrice : taxRate:float -> _arg1:string -> float Calling this gives: > getPrice 0.10 "tofu";; val it : float = 1.199 Note that the added parameters in the call come before the implicit parameter against which the match is made. Comparison To Other LanguagesEdit F#'s pattern matching syntax is subtly different from "switch statement" structures in imperative languages, because each case in a pattern has a return value. For example, the fib function is equivalent to the following C#: int Fib(int n) => n switch { 0 => 0, 1 => 1, _ => Fib(n - 1) + Fib(n - 2) }; Like all functions, pattern matches can only have one return type. Binding Variables with Pattern MatchingEditEditEdit. Recursion A recursive function is a function which calls itself. Interestingly, in contrast to many other languages, functions in F# are not recursive by default. A programmer needs to explicitly mark a function as recursive using the rec keyword: let rec someFunction = ... ExamplesEdit) But note that this function as it stands returns 1 for all negative numbers but factorial is undefined for negative numbers. This means that in real production programs you must either design the rest of the program so that factorial can never be called with a a negative number or trap negative input and throw an exception. Exceptions will be discussed in a later chapter.ursionEditEditEdit Faster Fib FunctionEdit Additional ReadingEdit Higher Order Functions A higher-order function is a function that takes another function as a parameter, or a function that returns another function as a value, or a function that does both. Familiar Higher Order FunctionsEdit were a literal value, and call it just likeEdit << : ('a -> 'b) -> ('c -> 'a) -> 'c -> ). There's no reason why the compose function must first applies f and then applies g on the result. The |> OperatorEdit thatEditEdit vary from machine to machine. Currying and Partial FunctionsEditEditEdit. Option Types An option type can hold two possible values: Some(x) or None. Option types are frequently used to represent optional values in calculations, or to indicate whether a particular computation has succeeded or failed. Using Option TypesEdit Let's say we have a function that divides two integers. Normally, we'd write the function as follows: let div x y = x / y This function works just fine, but it's not safe: it's possible to pass an invalid value into this function which results in a runtime error. Here is a demonstration in fsi: > let div x y = x / y;; val div : int -> int -> int > div 10 5;; val it : int = 2 > div 10 0;; System.DivideByZeroException: Attempted to divide by zero. at <StartupCode$FSI_0035>.$FSI_0035._main() stopped due to error div 10 5 executes just fine, but div 10 0 throws a division by zero exception. Using option types, we can return Some(value) on a successful calculation, or None if the calculation fails: > let safediv x y = match y with | 0 -> None | _ -> Some(x/y);; val safediv : int -> int -> int option > safediv 10 5;; val it : int option = Some 2 > safediv 10 0;; val it : int option = None Notice an important difference between our div and safediv functions: val div : int -> int -> int val safediv : int -> int -> int option div returns an int, while safediv returns an int option. Since our safediv function returns a different data type, it informs clients of our function that the application has entered an invalid state. Option types are conceptually similar to nullable types in languages like C#, however F# option types do not use the CLR System.Nullable<T> representation in IL due to differences in semantics. Pattern Matching Option TypesEdit Pattern matching option types is as easy as creating them: the same syntax used to declare an option type is used to match option types: > let isFortyTwo = function | Some(42) -> true | Some(_) | None -> false;; val isFortyTwo : int option -> bool > isFortyTwo (Some(43));; val it : bool = false > isFortyTwo (Some(42));; val it : bool = true > isFortyTwo None;; val it : bool = false Other Functions in the Option ModuleEdit val get : 'a option -> 'a - Returns the value of a Someoption. val isNone : 'a option -> bool - Returns truefor a Noneoption, falseotherwise. val isSome : 'a option -> bool - Returns truefor a Someoption, falseotherwise. val map : ('a -> 'b) -> 'a option -> 'b option - Given None, returns None. Given Some(x), returns Some(f x), where fis the given mapping function. val iter : ('a -> unit) -> 'a option -> unit - Applies the given function to the value of a Someoption, does nothing otherwise. Tuples and Records Defining TuplesEdit A tuple is defined as a comma separated collection of values. For example, (10, "hello") is a 2-tuple with the type (int * string). Tuples are extremely useful for creating ad hoc data structures which group together related values. Note that the parentheses are not part of the tuple but it is often necessary to add them to ensure that the tuple only includes what you think it includes. let average (a, b) = (a + b) / 2.0 This function has the type float * float -> float, it takes a float * float tuple and returns another float. > let average (a, b) = let sum = a + b sum / 2.0;; val average : float * float -> float > average (10.0, 20.0);; val it : float = 15.0 Notice that a tuple is considered a single argument. As a result, tuples can be used to return multiple values: Example 1 - a function which multiplies a 3-tuple by a scalar value to return another 3-tuple. > let scalarMultiply (s : float) (a, b, c) = (a * s, b * s, c * s);; val scalarMultiply : float -> float * float * float -> float * float * float > scalarMultiply 5.0 (6.0, 10.0, 20.0);; val it : float * float * float = (30.0, 50.0, 100.0) Example 2 - a function which reverses the input of whatever is passed into the function. > let swap (a, b) = (b, a);; val swap : 'a * 'b -> 'b * 'a > swap ("Web", 2.0);; val it : float * string = (2.0, "Web") > swap (20, 30);; val it : int * int = (30, 20) Example 3 - a function which divides two numbers and returns the remainder simultaneously. > let divrem x y = match y with | 0 -> None | _ -> Some(x / y, x % y);; val divrem : int -> int -> (int * int) option > divrem 100 20;; (* 100 / 20 = 5 remainder 0 *) val it : (int * int) option = Some (5, 0) > divrem 6 4;; (* 6 / 4 = 1 remainder 2 *) val it : (int * int) option = Some (1, 2) > divrem 7 0;; (* 7 / 0 throws a DivisionByZero exception *) val it : (int * int) option = None Every tuple has a property called arity, which is the number of arguments used to define a tuple. For example, an int * string tuple is made up of two parts, so it has an arity of 2, a string * string * float has an arity of 3, and so on. Pattern Matching TuplesEdit Pattern matching on tuples is easy, because the same syntax used to declare tuple types is also used to match tuples. Example 1 Let's say that we have a function greeting that prints out a custom greeting based on the specified name and/or language. let greeting (name, language) = match (name, language) with | ("Steve", _) -> "Howdy, Steve" | (name, "English") -> "Hello, " + name | (name, _) when language.StartsWith("Span") -> "Hola, " + name | (_, "French") -> "Bonjour!" | _ -> "DOES NOT COMPUTE" This function has type string * string -> string, meaning that it takes a 2-tuple and returns a string. We can test this function in fsi: > greeting ("Steve", "English");; val it : greeting ("Pierre", "French");; val it : greeting ("Maria", "Spanish");; val it : greeting ("Rocko", "Esperanto");; val it : string = "DOES NOT COMPUTE" Example 2 We can conveniently match against the shape of a tuple using the alternative pattern matching syntax: > let getLocation = function | (0, 0) -> "origin" | (0, y) -> "on the y-axis at getLocation (0, -1);; val it : getLocation (5, -10);; val it : getLocation (7, 0);; val it : string = "on the x-axis at x=7" fst and sndEdit F# has two built-in functions, fst and snd, which return the first and second items in a 2-tuple. These functions are defined as follows: let fst (a, b) = a let snd (a, b) = b They have the following types: val fst : 'a * 'b -> 'a val snd : 'a * 'b -> 'b Here are a few examples in FSI: > fst (1, 10);; val it : int = 1 > snd (1, 10);; val it : int = 10 > fst ("hello", "world");; val it : snd ("hello", "world");; val it : fst ("Web", 2.0);; val it : snd (50, 100);; val it : int = 100 Assigning Multiple Variables SimultaneouslyEdit Tuples can be used to assign multiple values simultaneously. This is the same as tuple unpacking in Python. The syntax for doing so is: let val1, val2, ... valN = (expr1, expr2, ... exprN) In other words, you assign a comma-separated list of N values to an N-tuple. Here's an example in FSI: > let x, y = (1, 2);; val y : int val x : int > x;; val it : int = 1 > y;; val it : int = 2 The number of values being assigned must match the arity of tuple returned from the function, otherwise F# will raise an exception: > let x, y = (1, 2, 3);; let x, y = (1, 2, 3);; ------------^^^^^^^^ stdin(18,13): error FS0001: Type mismatch. Expecting a 'a * 'b but given a 'a * 'b * 'c. The tuples have differing lengths of 2 and 3. Tuples and the .NET FrameworkEdit From a point of view F#, all methods in the .NET Base Class Library take a single argument, which is a tuple of varying types and arity. For example: Some methods, such as the System.Math.DivRem shown above, and others such as System.Int32.TryParse return multiple through output variables. F# allows programmers to omit an output variable; using this calling convention, F# will return results of a function as a tuple, for example: > System.Int32.TryParse("3");; val it : bool * int = (true, 3) > System.Math.DivRem(10, 7);; val it : int * int = (1, 3) Defining RecordsEdit A record is similar to a tuple, except it contains named fields. A record is defined using the syntax: type recordName = { [ fieldName : dataType ] + } +means the element must occur one or more times. Here's a simple record: type website = { Title : string; Url : string } Unlike a tuple, a record is explicitly defined as its own type using the type keyword, and record fields are defined as a semicolon-separated list. (In many ways, a record can be thought of as a simple class.) A website record is created by specifying the record's fields as follows: > let homepage = { Title = "Google"; Url = "" };; val homepage : website Note that F# determines a records type by the name and type of its fields, not the order that fields are used. For example, while the record above is defined with Title first and Url second, it's perfectly legitimate to write: > { Url = ""; Title = "Microsoft Corporation" };; val it : website = {Title = "Microsoft Corporation"; Url = "";} It's easy to access a record's properties using dot notation: > let homepage = { homepage.Url;; val it : string = "" Cloning RecordsEdit Records are immutable types, which means that instances of records cannot be modified. However, records can be cloned conveniently using the clone syntax: type coords = { X : float; Y : float } let setX item newX = { item with X = newX } The method setX has the type coords -> float -> coords. The with keyword creates a clone of item and set its X property to newX. > let start = { X = 1.0; Y = 2.0 };; val start : coords > let finish = setX start 15.5;; val finish : coords > start;; val it : coords = {X = 1.0; Y = 2.0;} > finish;; val it : coords = {X = 15.5; Y = 2.0;} Notice that the setX creates a copy of the record, it doesn't actually mutate the original record instance. Here's a more complete program: type TransactionItem = { Name : string; ID : int; ProcessedText : string; IsProcessed : bool } let getItem name id = { Name = name; ID = id; ProcessedText = null; IsProcessed = false } let processItem item = { item with ProcessedText = "Done"; IsProcessed = true } let printItem msg item = printfn "%s: %A" msg item let main() = let preProcessedItem = getItem "Steve" 5 let postProcessedItem = processItem preProcessedItem printItem "preProcessed" preProcessedItem printItem "postProcessed" postProcessedItem main() This program processes an instance of the TransactionItem class and prints the results. This program outputs the following: preProcessed: {Name = "Steve"; ID = 5; ProcessedText = null; IsProcessed = false;} postProcessed: {Name = "Steve"; ID = 5; ProcessedText = "Done"; IsProcessed = true;} Pattern Matching RecordsEdit We can pattern match on records just as easily as tuples: open System type coords = { X : float; Y : float } let getQuadrant = function | { X = 0.0; Y = 0.0 } -> "Origin" | item when item.X >= 0.0 && item.Y >= 0.0 -> "I" | item when item.X <= 0.0 && item.Y >= 0.0 -> "II" | item when item.X <= 0.0 && item.Y <= 0.0 -> "III" | item when item.X >= 0.0 && item.Y <= 0.0 -> "IV" let testCoords (x, y) = let item = { X = x; Y = y } printfn "(%f, %f) is in quadrant %s" x y (getQuadrant item) let main() = testCoords(0.0, 0.0) testCoords(1.0, 1.0) testCoords(-1.0, 1.0) testCoords(-1.0, -1.0) testCoords(1.0, -1.0) Console.ReadKey(true) |> ignore main() Note that pattern cases are defined with the same syntax used to create a record (as shown in the first case), or using guards (as shown in the remaining cases). Unfortunately, programmers cannot use the clone syntax in pattern cases, so a case such as | { item with X = 0 } -> "y-axis" will not compile. The program above outputs: (0.000000, 0.000000) is in quadrant Origin (1.000000, 1.000000) is in quadrant I (-1.000000, 1.000000) is in quadrant II (-1.000000, -1.000000) is in quadrant III (1.000000, -1.000000) is in quadrant IV. Creating ListsEdit Using List LiteralsEdit") OperatorEdit It is very common to build lists up by prepending or consing a value to an existing list using the :: operator: > 1 :: 2 :: 3 :: [];; val it : int list = [1; 2; 3] - Note: the []is an empty list. By itself, it has the type 'T list; since it is.initEditEdit] it's] It's possible to mix the yield and yield! keywords: > [for a in 1 .. 5 do match a with | 3 -> yield! ["hello"; "world"] | _ -> yield a.ToString() ];; val it : string list = ["1"; "2"; "hello"; "world"; "4"; "5"] Alternative List Comprehension SyntaxEdit)] -> is equivalent to the yield operator respectively. While it's still common to see list comprehensions expressed using ->, this construct will not be emphasized in this book since it has been deprecated in favor of yield. Pattern Matching ListsEdit: Reversing ListsEdit. It's] Filtering ListsEdit, it's very common to see List.revcalled immediately before returning a list from a function to put it in correct order. Mapping ListsEditEdit Although a reverse, filter, and map method were implemented above, it's @ OperatorEdit, it'sEditBackEdit. The 'State type represents the accumulated value, it is the output of one round of the calculation and input for the next round. listEditEdit Pair and UnpairEdit ListEditEdit AlgorithmEdit it's split's will be returned as a tuple. The split function doesn't need to sort the lists though. The merge function The next step is merging. We now want to merge the split's together into a sorted list assuming that both split's split's are already sorted. It will make it's implementation a lot easier. Assuming both split's are sorted, we can just look at the first element of both split'sEdit.item 3 intSeq;; intSeq: 1 intSeq: 2 intSeq: 3 intSeq: 4 val it : int = 4 > Seq.item internally and hold only the last generated item in memory at a time. Memory usage is constant for creating and traversing sequences of any length. Iterating Through Sequences ManuallyEditEdit exists in a sequence. > let equalsTwo x = x=2 > let exist = Seq.exists equalsTwo (seq{3..9}) val equalsTwo : int -> bool val it : bool = false val filter : ('T -> bool) -> seq<'T> -> seq<'T> - Builds a new sequence consisting of elements filtered from the input sequence. > Seq.filter (fun x-> x%2 = 0) in a item : int -> seq<'T> -> 'T - Returns the nth value of a sequence. > Seq.item it's, it's preferable to generate sequences using seq comprehensions rather than the unfold. Sets and Maps In addition to lists and sequences, F# provides two related immutable data structures called sets and maps. Unlike lists, sets and maps are unordered data structures, meaning that these collections do not preserve the order of elements as they are inserted, nor do they permit duplicates. SetsEdit A set in F# is just a container for items. Sets do not preserve the order in which items are inserted, nor do they allow duplicate entries to be inserted into the collection. Sets can be created in a variety of ways: Adding an item to an empty set The Set module contains a useful function Set.empty which returns an empty set to start with. Conveniently, all instances of sets have an Add function with the type val Add : 'a -> Set<'a>. In other words, our Add returns a new set containing our new item, which makes it easy to add items together in this fashion: > Set.empty.Add(1).Add(2).Add(7);; val it : Set<int> = set [1; 2; 7] Converting lists and sequences into sets Additionally, the we can use Set.ofList and Set.ofSeq to convert an entire collection into a set: > Set.ofList ["Mercury"; "Venus"; "Earth"; "Mars"; "Jupiter"; "Saturn"; "Uranus"; "Neptune"];; val it : Set<string> = set ["Earth"; "Jupiter"; "Mars"; "Mercury"; ...] The example above demonstrates the unordered nature of sets. The Set ModuleEdit The FSharp.Collections.Set module contains a variety of useful methods for working with sets. val add : 'a -> Set<'a> -> Set<'a> - Return a new set with an element added to the set. No exception is raised if the set already contains the given element. val compare : Set<'a> -> Set<'a> -> int - Compare two sets. Places sets into a total order. val count : Set<'a> -> int - Return the number of elements in the set. Same as "size". val difference : Set<'a> -> Set<'a> -> Set<'a> - Return a new set with the elements of the second set removed from the first. That is a set containing only those items from the first set that are not also in the second set. > let a = Set.ofSeq [ 1 .. 10 ] let b = Set.ofSeq [ 5 .. 15 ];; val a : Set<int> val b : Set<int> > Set.difference a b;; val it : Set<int> = set [1; 2; 3; 4] > a - b;; (* The '-' operator is equivalent to Set.difference *) val it : Set<int> = set [1; 2; 3; 4] val exists : ('a -> bool) -> Set<'a> -> bool - Test if any element of the collection satisfies the given predicate. val filter : ('a -> bool) -> Set<'a> -> Set<'a> - Return a new collection containing only the elements of the collection for which the given predicate returns "true". val intersect : Set<'a> -> Set<'a> -> Set<'a> - Compute the intersection, or overlap, of the two sets. > let a = Set.ofSeq [ 1 .. 10 ] let b = Set.ofSeq [ 5 .. 15 ];; val a : Set<int> val b : Set<int> > Set.iter (fun x -> printf "%O " x) (Set.intersect a b);; 5 6 7 8 9 10 val map : ('a -> 'b) -> Set<'a> -> Set<'b> - Return a new collection containing the results of applying the given function to each element of the input set. val contains: 'a -> Set<'a> -> bool - Evaluates to trueif the given element is in the given set. val remove : 'a -> Set<'a> -> Set<'a> - Return a new set with the given element removed. No exception is raised if the set doesn't contain the given element. val count: Set<'a> -> int - Return the number of elements in the set. val isSubset : Set<'a> -> Set<'a> -> bool - Evaluates to "true" if all elements of the first set are in the second. val isProperSubset : Set<'a> -> Set<'a> -> bool - Evaluates to "true" if all elements of the first set are in the second, and there is at least one element in the second set which is not in the first. > let a = Set.ofSeq [ 1 .. 10 ] let b = Set.ofSeq [ 5 .. 15 ] let c = Set.ofSeq [ 2; 4; 5; 9 ];; val a : Set<int> val b : Set<int> val c : Set<int> > Set.isSubset c a;; (* All elements of 'c' exist in 'a' *) val it : bool = true > Set.isSubset c b;; (* Not all of the elements of 'c' exist in 'b' *);; val it : bool = false val union : Set<'a> -> Set<'a> -> Set<'a> - Compute the union of the two sets. > let a = Set.ofSeq [ 1 .. 10 ] let b = Set.ofSeq [ 5 .. 15 ];; val a : Set<int> val b : Set<int> > Set.iter (fun x -> printf "%O " x) (Set.union a b);; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 val it : unit = () > Set.iter (fun x -> printf "%O " x) (a + b);; (* '+' computes union *) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ExamplesEdit open System let shakespeare = "O Romeo, Romeo! wherefore art thou Romeo?" let shakespeareArray = shakespeare.Split([| ' '; ','; '!'; '?' |], StringSplitOptions.RemoveEmptyEntries) let shakespeareSet = shakespeareArray |> Set.ofSeq let main() = printfn "shakespeare: %A" shakespeare let printCollection msg coll = printfn "%s:" msg Seq.iteri (fun index item -> printfn " %i: %O" index item) coll printCollection "shakespeareArray" shakespeareArray printCollection "shakespeareSet" shakespeareSet Console.ReadKey(true) |> ignore main() shakespeare: "O Romeo, Romeo! wherefore art thou Romeo?" shakespeareArray: 0: O 1: Romeo 2: Romeo 3: wherefore 4: art 5: thou 6: Romeo shakespeareSet: 0: O 1: Romeo 2: art 3: thou 4: wherefore MapsEdit A map is a special kind of set: it associates keys with values. A map is created in a similar way to sets: > let holidays = Map.empty. (* Start with empty Map *) Add("Christmas", "Dec. 25"). Add("Halloween", "Oct. 31"). Add("Darwin Day", "Feb. 12"). Add("World Vegan Day", "Nov. 1");; val holidays : Map<string,string> > let monkeys = [ "Squirrel Monkey", "Simia sciureus"; "Marmoset", "Callithrix jacchus"; "Macaque", "Macaca mulatta"; "Gibbon", "Hylobates lar"; "Gorilla", "Gorilla gorilla"; "Humans", "Homo sapiens"; "Chimpanzee", "Pan troglodytes" ] |> Map.ofList;; (* Convert list to Map *) val monkeys : Map<string,string> You can use the .[key] to access elements in the map: > holidays.["Christmas"];; val it : monkeys.["Marmoset"];; val it : string = "Callithrix jacchus" The Map ModuleEdit The FSharp.Collections.Map module handles map operations. val add : 'key -> 'a -> Map<'key,'a> -> Map<'key,'a> - Return a new map with the binding added to the given map. val empty<'key,'a> : Map<'key,'a> - Returns an empty map. val exists : ('key -> 'a -> bool) -> Map<'key,'a> -> bool - Return true if the given predicate returns true for one of the bindings in the map. val filter : ('key -> 'a -> bool) -> Map<'key,'a> -> Map<'key,'a> - Build a new map containing only the bindings for which the given predicate returns true. val find : 'key -> Map<'key,'a> -> 'a - Lookup an element in the map, raising KeyNotFoundExceptionif no binding exists in the map. val containsKey: 'key -> Map<'key,'a> -> bool - Test if an element is in the domain of the map. val remove : 'key -> Map<'key,'a> -> Map<'key,'a> - Remove an element from the domain of the map. No exception is raised if the element is not present. val tryFind : 'key -> Map<'key,'a> -> 'a option - Lookup an element in the map, returning a Somevalue if the element is in the domain of the map and Noneif not. ExamplesEdit open System let capitals = [("Australia", "Canberra"); ("Canada", "Ottawa"); ("China", "Beijing"); ("Denmark", "Copenhagen"); ("Egypt", "Cairo"); ("Finland", "Helsinki"); ("France", "Paris"); ("Germany", "Berlin"); ("India", "New Delhi"); ("Japan", "Tokyo"); ("Mexico", "Mexico City"); ("Russia", "Moscow"); ("Slovenia", "Ljubljana"); ("Spain", "Madrid"); ("Sweden", "Stockholm"); ("Taiwan", "Taipei"); ("USA", "Washington D.C.")] |> Map.ofList let rec main() = Console.Write("Find a capital by country (type 'q' to quit): ") match Console.ReadLine() with | "q" -> Console.WriteLine("Bye bye") | country -> match capitals.TryFind(country) with | Some(capital) -> Console.WriteLine("The capital of {0} is {1}\n", country, capital) | None -> Console.WriteLine("Country not found.\n") main() (* loop again *) main() Find a capital by country (type 'q' to quit): Egypt The capital of Egypt is Cairo Find a capital by country (type 'q' to quit): Slovenia The capital of Slovenia is Ljubljana Find a capital by country (type 'q' to quit): Latveria Country not found. Find a capital by country (type 'q' to quit): USA The capital of USA is Washington D.C. Find a capital by country (type 'q' to quit): q Bye bye Set and Map PerformanceEdit F# sets and maps are implemented as immutable AVL trees, an efficient data structure which forms a self-balancing binary tree. AVL trees are well-known for their efficiency, in which they can search, insert, and delete elements in the tree in O(log n) time, where n is the number of elements in the tree. Discriminated Unions Discriminated unions, also called tagged unions, represent a finite, well-defined set of choices. Discriminated unions are often the tool of choice for building up more complicated data structures including linked lists and a wide range of trees. Creating Discriminated UnionsEdit Discriminated unions are defined using the following syntax: type unionName = | Case1 | Case2 of datatype | ... By convention, union names start with a lowercase character, and union cases are written in PascalCase. Union basics: an On/Off switchEdit use switchEdit The example above is kept deliberately simple. In fact, in many ways, the discriminated union defined above doesn't appear much different from an enum value. However, let's say we wanted to change our light switch model into a model of a dimmer switch, or in other words a light switch that allowsEdit Discriminated unions can easily model a wide variety of trees and hierarchical data structures. For example, let's consider the following binary tree: Each node of our tree contains exactly two branches, and each branch can either be rec countLeaves = function | Leaf(_) -> 1 | Node(tree1, tree2) -> (countLeaves tree1) + (countLeaves tree2) let main() = printfn "countLeaves simpleTree: %i" (countLeaves simpleTree) Console.ReadKey(true) |> ignore main() This program outputs: countLeaves simpleTree: 5 Generalizing Unions For All DatatypesEdit Note that our binary tree above only operates on integers. It is possible to construct unions that definedEdit Built-in Union TypesEdit F# has several built-in types derived from discriminated unions, some of which have already been introduced in this tutorial. These types include: type 'a list = | Cons of 'a * 'a list | Nil type 'a option = | Some of 'a | None Propositional LogicEdit The ML family of languages, which includes F# and its parent language OCaml, were originally designed for the development of automated theorem provers. Union types allow F# programmers to represent propositional logic remarkably concisely. To keep things simple, let'sEdit Theorem Proving Examples (OCaml). mutable KeywordEditEdit Mutable variables are somewhat limited: before F# 4.0, mutables wereEditEdit -: cell1, cell2, and cell3 are all pointing to the same address in memory. The .contents property of each cell is 7. Let's say, at some point in our program, we execute the code cell1 := 10, this changes the value in memory to the following:Edit Control Flow In all programming languages, control flow refers to the decisions made in code that affect the order in which statements are executed in an application. F#'s imperative control flow elements are similar to those encountered in other languages. Imperative Programming in a NutshellEditEditEditEditEditEdit! Arrays Arrays are a ubiquitous, familiar data structure used to represent a group of related, ordered values. Unlike F# data structures, arrays are mutable, meaning the values in an array can be changed after the array has been created. Creating ArraysEdit Arrays are conceptually similar to lists. Naturally, arrays can be created using many of the same techniques as lists: Array literalsEdit > [| 1; 2; 3; 4; 5 |];; val it : int array = [|1; 2; 3; 4; 5|] Array comprehensionsEditEditEdit array using the .[index] operator, also called indexer notation. Here is the same arrayEditEdit A multi-dimensional array is literally an array of arrays. Conceptually, it's not any harder to work with these types of arrays than single-dimensional arrays (as shown above). Multi-dimensional arrays come in two forms: rectangular and jagged arrays. Rectangular ArraysEdit is very hard to manage, and also can quickly consume all of the available memory on a machine. Jagged arraysEdit A jagged array is an array of arrays, except each row in the array does not necessarilyEditEdit -Edit allocate 20 bytes of memory to hold this array (4 bytes * 5 elements = 20 bytes). The first element in the array occupies memory 100-103, the second element occupies 104-107, and so on. We know that each element in the array is identified by itsman's terms, this means we can access the nth element of an up front,. Mutable Collections The .NET BCL comes with its own suite of mutable collections which are found in the System.Collections.Generic namespace. These built-in collections are very similar to their immutable counterparts in F#. List<'T> ClassEdit The List<'T> class represents a strongly typed list of objects that can be accessed by index. Conceptually, this makes the List<'T> class similar to arrays. However, unlike arrays, Lists can be resized and don't need to have their size specified on declaration. .NET lists are created using the new keyword and calling the list's constructor as follows: > open System.Collections.Generic;; > let myList = new List<string>();; val myList : List<string> > myList.Add("hello");; val it : unit = () > myList.Add("world");; val it : unit = () > myList.[0];; val it : myList |> Seq.iteri (fun index item -> printfn "%i: %s" index myList.[index]);; 0: hello 1: world It's easy to tell that .NET lists are mutable because their Add methods return unit rather than returning another list. Underlying ImplementationEdit Behind the scenes, the List<'T> class is just a fancy wrapper for an array. When a List<'T> is constructed, it creates an 4-element array in memory. Adding the first 4 items is an O(1) operation. However, as soon as the 5th element needs to be added, the list doubles the size of the internal array, which means it has to reallocate new memory and copy elements in the existing list; this is a O(n) operation, where n is the number of items in the list. The List<'T>.Count property returns the number of items currently held in the collection, the List<'T>.Capacity collection returns the size of the underlying array. This code sample demonstrates how the underlying array is resized: open System open System.Collections.Generic let items = new List<string>() let printList (l : List<_>) = printfn "l.Count: %i, l.Capacity: %i" l.Count l.Capacity printfn "Items:" l |> Seq.iteri (fun index item -> printfn " l.[%i]: %s" index l.[index]) printfn "-----------" let main() = printList items items.Add("monkey") printList items items.Add("kitty") items.Add("bunny") printList items items.Add("doggy") items.Add("octopussy") items.Add("ducky") printList items printfn "Removing entry for \"doggy\"\n--------\n" items.Remove("doggy") |> ignore printList items printfn "Removing item at index 3\n--------\n" items.RemoveAt(3) printList items Console.ReadKey(true) |> ignore main() l.Count: 0, l.Capacity: 0 Items: ----------- l.Count: 1, l.Capacity: 4 Items: l.[0]: monkey ----------- l.Count: 3, l.Capacity: 4 Items: l.[0]: monkey l.[1]: kitty l.[2]: bunny ----------- l.Count: 6, l.Capacity: 8 Items: l.[0]: monkey l.[1]: kitty l.[2]: bunny l.[3]: doggy l.[4]: octopussy l.[5]: ducky ----------- Removing entry for "doggy" -------- l.Count: 5, l.Capacity: 8 Items: l.[0]: monkey l.[1]: kitty l.[2]: bunny l.[3]: octopussy l.[4]: ducky ----------- Removing item at index 3 -------- l.Count: 4, l.Capacity: 8 Items: l.[0]: monkey l.[1]: kitty l.[2]: bunny l.[3]: ducky ----------- If you know the maximum size of the list beforehand, it is possible to avoid the performance hit by calling the List<'T>(size : int) constructor instead. The following sample demonstrates how to add 1000 items to a list without resizing the internal array: > let myList = new List<int>(1000);; val myList : List<int> > myList.Count, myList.Capacity;; val it : int * int = (0, 1000) > seq { 1 .. 1000 } |> Seq.iter (fun x -> myList.Add(x));; val it : unit = () > myList.Count, myList.Capacity;; val it : int * int = (1000, 1000) LinkedList<'T> ClassEdit A LinkedList<'T> represented a doubly-linked sequence of nodes which allows efficient O(1) inserts and removal, supports forward and backward traversal, but its implementation prevents efficient random access. Linked lists have a few valuable methods: (* Prepends an item to the LinkedList *) val AddFirst : 'T -> LinkedListNode<'T> (* Appends an items to the LinkedList *) val AddLast : 'T -> LinkedListNode<'T> (* Adds an item before a LinkedListNode *) val AddBefore : LinkedListNode<'T> -> 'T -> LinkedListNode<'T> (* Adds an item after a LinkedListNode *) val AddAfter : LinkedListNode<'T> -> 'T -> LinkedListNode<'T> Note that these methods return a LinkedListNode<'T>, not a new LinkedList<'T>. Adding nodes actually mutates the LinkedList object: > open System.Collections.Generic;; > let items = new LinkedList<string>();; val items : LinkedList<string> > items.AddLast("AddLast1");; val it : LinkedListNode<string> = System.Collections.Generic.LinkedListNode`1[System.String] {List = seq ["AddLast1"]; Next = null; Previous = null; Value = "AddLast1";} > items.AddLast("AddLast2");; val it : LinkedListNode<string> = System.Collections.Generic.LinkedListNode`1[System.String] {List = seq ["AddLast1"; "AddLast2"]; Next = null; Previous = System.Collections.Generic.LinkedListNode`1[System.String]; Value = "AddLast2";} > let firstItem = items.AddFirst("AddFirst1");; val firstItem : LinkedListNode<string> > let addAfter = items.AddAfter(firstItem, "addAfter");; val addAfter : LinkedListNode<string> > let addBefore = items.AddBefore(addAfter, "addBefore");; val addBefore : LinkedListNode<string> > items |> Seq.iter (fun x -> printfn "%s" x);; AddFirst1 addBefore addAfter AddLast1 AddLast2 The Stack<'T> and Queue<'T> classes are special cases of a linked list (they can be thought of as linked lists with restrictions on where you can add and remove items). Stack<'T> ClassEdit A Stack<'T> only allows programmers prepend/push and remove/pop items from the front of a list, which makes it a last in, first out (LIFO) data structure. The Stack<'T> class can be thought of as a mutable version of the F# list. > stack.Push("First");; (* Adds item to front of the list *) val it : unit = () > stack.Push("Second");; val it : unit = () > stack.Push("Third");; val it : unit = () > stack.Pop();; (* Returns and removes item from front of the list *) val it : stack.Pop();; val it : stack.Pop();; val it : string = "First" A stack of coins could be represented with this data structure. If we stacked coins one on top another, the first coin in the stack is at the bottom of the stack, and the last coin in the stack appears at the top. We remove coins from top to bottom, so the last coin added to the stack is the first one removed. Queue<'T> ClassEdit A Queue<'T> only allows programmers to append/enqueue to the rear of a list and remove/dequeue from the front of a list, which makes it a first in, first out (FIFO) data structure. > let queue = new Queue<string>();; val queue : Queue<string> > queue.Enqueue("First");; (* Adds item to the rear of the list *) val it : unit = () > queue.Enqueue("Second");; val it : unit = () > queue.Enqueue("Third");; val it : unit = () > queue.Dequeue();; (* Returns and removes item from front of the queue *) val it : queue.Dequeue();; val it : queue.Dequeue();; val it : string = "Third" A line of people might be represented by a queue: people add themselves to the rear of the line, and are removed from the front. The first person to stand in line is the first person to be served. HashSet<'T>, and Dictionary<'TKey, 'TValue> ClassesEdit The HashSet<'T> and Dictionary<'TKey, 'TValue> classes are mutable analogs of the F# set and map data structures and contain many of the same functions. Using the HashSet<'T> open System open System.Collections.Generic let nums_1to10 = new HashSet<int>() let nums_5to15 = new HashSet<int>() let main() = let printCollection msg targetSet = printf "%s: " msg targetSet |> Seq.sort |> Seq.iter(fun x -> printf "%O " x) printfn "" let addNums min max (targetSet : ICollection<_>) = seq { min .. max } |> Seq.iter(fun x -> targetSet.Add(x)) addNums 1 10 nums_1to10 addNums 5 15 nums_5to15 printCollection "nums_1to10 (before)" nums_1to10 printCollection "nums_5to15 (before)" nums_5to15 nums_1to10.IntersectWith(nums_5to15) (* mutates nums_1to10 *) printCollection "nums_1to10 (after)" nums_1to10 printCollection "nums_5to15 (after)" nums_5to15 Console.ReadKey(true) |> ignore main() nums_1to10 (before): 1 2 3 4 5 6 7 8 9 10 nums_5to15 (before): 5 6 7 8 9 10 11 12 13 14 15 nums_1to10 (after): 5 6 7 8 9 10 nums_5to15 (after): 5 6 7 8 9 10 11 12 13 14 15 Using the Dictionary<'TKey, 'TValue> > open System.Collections.Generic;; > let dict = new Dictionary<string, string>();; val dict : Dictionary<string,string> > dict.Add("Garfield", "Jim Davis");; val it : unit = () > dict.Add("Farside", "Gary Larson");; val it : unit = () > dict.Add("Calvin and Hobbes", "Bill Watterson");; val it : unit = () > dict.Add("Peanuts", "Charles Schultz");; val it : unit = () > dict.["Farside"];; (* Use the '.[key]' operator to retrieve items *) val it : string = "Gary Larson" Differences Between .NET BCL and F# CollectionsEdit The major difference between the collections built into the .NET BCL and their F# analogs is, of course, mutability. The mutable nature of BCL collections dramatically affects their implementation and time-complexity: - * These classes are built on top of internal arrays. They may take a performance hit as the internal arrays are periodically resized when adding items. - Note: the Big-O notation above refers to the time-complexity of the insert/remove/retrieve operations relative to the number of items in the data structure, not the relative amount of time required to evaluate the operations relative to other data structures. For example, accessing arrays by index vs. accessing dictionaries by key have the same time complexity, O(1), but the operations do not necessarily occur in the same amount of time.. Working with the ConsoleEditEdit Edit The System.IO namespace contains a variety of useful classes for performing basic I/O. Files and DirectoriesEditEdit. Exception Handling When a program encounters a problem or enters an invalid state, it will often respond by throwing an exception. Left to its own devices, an uncaught exception will crash an application. Programmers write exception handling code to rescue an application from an invalid state. Try/WithEditEditEditEditEdit Exception Handling ConstructsEdit Operator Overloading Operator overloading allows programmers to provide new behavior for the default operators in F#. In practice, programmers overload operators to provide a simplified syntax for objects which can be combined mathematically. Using OperatorsEdit You've already used operators: let sum = x + y Here + is example of using a mathematical addition operator. Operator OverloadingEditEdit In addition to overloading existing operators, its possible to define new operators. The names of custom operators can only be one or more of the following characters: !%&*+-./<=>?@^|~ F# supports two types of operators: infix operators and prefix operators. Infix operatorsEditEdit. Defining an ObjectEdit Before an object is created, its properties and functions should be defined. You define properties and methods of an object in a class. There are actually two different syntaxes for defining a class: an implicit syntax and an explicit syntax. Implicit Class ConstructionEditEditEdit The do keyword is used for post-constructor initialization. For example, to create an object which represents a stock, it is necessary-separated to need more than one. Explicit Class DefinitionEditEditEdit valfields can be used in the implicit syntax, they must have the attribute [<DefaultValue>]and be mutable. It is more convenient to use letbindings in this case. Public memberaccessors can be added when they need to be public. - In the implicit syntax, the primary constructor parameters are visible throughout the whole class body. By using this feature, it is not necessaryEditEdit Instance and Static MembersEditEditEditEdit Classes which take generic types can be created:Edit> Inheritance Many object-oriented languages use inheritance extensively in the .NET BCL to construct class hierarchies. SubclassesEdit A subclass is, in the simplest terms, a class derived from a class which has already been defined. A subclass inherits its members from a base class in addition to adding its own members. A subclass is defined using the inherit keyword as shown below: type Person(name) = member x.Name = name member x.Greet() = printfn "Hi, I'm %s" x.Name type Student(name, studentID : int) = inherit Person(name) let mutable _GPA = 0.0 member x.StudentID = studentID member x.GPA with get() = _GPA and set value = _GPA <- value type Worker(name, employer : string) = inherit Person(name) let mutable _salary = 0.0 member x.Salary with get() = _salary and set value = _salary <- value member x.Employer = employer Our simple class hierarchy looks like this: System.Object (* All classes descend from *) - Person - Student - Worker The Student and Worker subclasses both inherit the Name and Greet methods from the Person base class. This can be demonstrated in fsi: > let somePerson, someStudent, someWorker = new Person("Juliet"), new Student("Monique", 123456), new Worker("Carla", "Awesome Hair Salon");; val someWorker : Worker val someStudent : Student val somePerson : Person > somePerson.Name, someStudent.Name, someWorker.Name;; val it : string * string * string = ("Juliet", "Monique", "Carla") > someStudent.StudentID;; val it : int = 123456 > someWorker.Employer;; val it : someWorker.ToString();; (* ToString method inherited from System.Object *) val it : string = "FSI_0002+Worker" .NET's object model supports single-class inheritance, meaning that a subclass is limited to one base class. In other words, its not possible to create a class which derives from Student and Employee simultaneously. Overriding MethodsEdit Occasionally, you may want a derived class to change the default behavior of methods inherited from the base class. For example, the output of the .ToString() method above isn't very useful. We can override that behavior with a different implementation using the override: type Person(name) = member x.Name = name member x.Greet() = printfn "Hi, I'm %s" x.Name override x.ToString() = x.Name (* The ToString() method is inherited from System.Object *) We've overridden the default implementation of the ToString() method, causing it to print out a person's name. Methods in F# are not overridable by default. If you expect users will want to override methods in a derived class, you have to declare your method as overridable using the abstract and default keywords as follows: type Person(name) = member x.Name = name abstract Greet : unit -> unit default x.Greet() = printfn "Hi, I'm %s" x.Name type Quebecois(name) = inherit Person(name) override x.Greet() = printfn "Bonjour, je m'appelle %s, eh." x.Name Our class Person provides a Greet method which may be overridden in derived classes. Here's an example of these two classes in fsi: > let terrance, phillip = new Person("Terrance"), new Quebecois("Phillip");; val terrance : Person val phillip : Quebecois > terrance.Greet();; Hi, I'm Terrance val it : unit = () > phillip.Greet();; Bonjour, je m'appelle Phillip, eh. Abstract ClassesEdit An abstract class is one which provides an incomplete implementation of an object, and requires a programmer to create subclasses of the abstract class to fill in the rest of the implementation. For example, consider the following: [<AbstractClass>] type Shape(position : Point) = member x.Position = position override x.ToString() = sprintf "position = {%i, %i}, area = %f" position.X position.Y (x.Area()) abstract member Draw : unit -> unit abstract member Area : unit -> float The first thing you'll notice is the AbstractClass attribute, which tells the compiler that our class has some abstract members. Additionally, you notice two abstract members, Draw and Area don't have an implementation, only a type signature. We can't create an instance of Shape because the class hasn't been fully implemented. Instead, we have to derive from Shape and override the Draw and Area methods with a concrete implementation: type Circle(position : Point, radius : float) = inherit Shape(position) member x.Radius = radius override x.Draw() = printfn "(Circle)" override x.Area() = Math.PI * radius * radius type Rectangle(position : Point, width : float, height : float) = inherit Shape(position) member x.Width = width member x.Height = height override x.Draw() = printfn "(Rectangle)" override x.Area() = width * height type Square(position : Point, width : float) = inherit Shape(position) member x.Width = width member x.ToRectangle() = new Rectangle(position, width, width) override x.Draw() = printfn "(Square)" override x.Area() = width * width type Triangle(position : Point, sideA : float, sideB : float, sideC : float) = inherit Shape(position)) ) Now we have several different implementations of the Shape class. We can experiment with these in fsi: > let position = { X = 0; Y = 0 };; val position : Point > let circle, rectangle, square, triangle = new Circle(position, 5.0), new Rectangle(position, 2.0, 7.0), new Square(position, 10.0), new Triangle(position, 3.0, 4.0, 5.0);; val triangle : Triangle val square : Square val rectangle : Rectangle val circle : Circle > circle.ToString();; val it : triangle.ToString();; val it : square.Width;; val it : float = 10.0 > square.ToRectangle().ToString();; val it : rectangle.Height, rectangle.Width;; val it : float * float = (7.0, 2.0) Working With SubclassesEdit Up-casting and Down-castingEdit A type cast is an operation which changes the type of an object from one type to another. This is not the same as a map function, because a type cast does not return an instance of a new object, it returns the same instance of an object with a different type. For example, let's say B is a subclass of A. If we have an instance of B, we are able to cast as an instance of A. Since A is upward in the class hierarchy, we call this an up-cast. We use the :> operator to perform upcasts: > let regularString.Length;; val it : int = 11 > upcastString.ToString();; (* type obj has a .ToString method *) val it : upcastString.Length;; (* however, obj does not have Length method *) upcastString.Length;; (* however, obj does not have Length method *) -------------^^^^^^^ stdin(24,14): error FS0039: The field, constructor or member 'Length' is not defined. Up-casting is considered "safe", because a derived class is guaranteed to have all of the same members as an ancestor class. We can, if necessary, go in the opposite direction: we can down-cast from an ancestor class to a derived class using the :?> operator: > let intAsObj = 20 :> obj;; val intAsObj : obj > intAsObj, intAsObj.ToString();; val it : obj * string = (20, "20") > let intDownCast = intAsObj :?> int;; val intDownCast : int > intDownCast, intDownCast.ToString();; val it : int * string = (20, "20") > let stringDownCast = intAsObj :?> string;; (* boom! *) val stringDownCast : string System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at <StartupCode$FSI_0067>.$FSI_0067._main() stopped due to error Since intAsObj holds an int boxed as an obj, we can downcast to an int as needed. However, we cannot downcast to a string because it is an incompatible type. Down-casting is considered "unsafe" because the error isn't detectable by the type-checker, so an error with a down-cast always results in a runtime exception. Up-casting exampleEdit open System type Point = { X : int; Y : int } [<AbstractClass>] type Shape() = override x.ToString() = sprintf "%s, area = %f" (x.GetType().Name) (x.Area()) abstract member Draw : unit -> unit abstract member Area : unit -> float type Circle(radius : float) = inherit Shape() member x.Radius = radius override x.Draw() = printfn "(Circle)" override x.Area() = Math.PI * radius * radius type Rectangle(width : float, height : float) = inherit Shape() member x.Width = width member x.Height = height override x.Draw() = printfn "(Rectangle)" override x.Area() = width * height type Square(width : float) = inherit Shape() member x.Width = width member x.ToRectangle() = new Rectangle(width, width) override x.Draw() = printfn "(Square)" override x.Area() = width * width type Triangle(sideA : float, sideB : float, sideC : float) = inherit Shape()) ) let shapes = [(new Circle(5.0) :> Shape); (new Circle(12.0) :> Shape); (new Square(10.5) :> Shape); (new Triangle(3.0, 4.0, 5.0) :> Shape); (new Rectangle(5.0, 2.0) :> Shape)] (* Notice we have to cast each object as a Shape *) let main() = shapes |> Seq.iter (fun x -> printfn "x.ToString: %s" (x.ToString()) ) main() This program has the following types: type Point = {X: int; Y: int;} type Shape = class abstract member Area : unit -> float abstract member Draw : unit -> unit new : unit -> Shape override ToString : unit -> string end type Circle = class inherit Shape new : radius:float -> Circle override Area : unit -> float override Draw : unit -> unit member Radius : float end type Rectangle = class inherit Shape new : width:float * height:float -> Rectangle override Area : unit -> float override Draw : unit -> unit member Height : float member Width : float end type Square = class inherit Shape new : width:float -> Square override Area : unit -> float override Draw : unit -> unit member ToRectangle : unit -> Rectangle member Width : float end type Triangle = class inherit Shape new : sideA:float * sideB:float * sideC:float -> Triangle override Area : unit -> float override Draw : unit -> unit member SideA : float member SideB : float member SideC : float end val shapes : Shape list This program outputs: x.ToString: Circle, area = 78.539816 x.ToString: Circle, area = 452.389342 x.ToString: Square, area = 110.250000 x.ToString: Triangle, area = 6.000000 x.ToString: Rectangle, area = 10.000000 Public, Private, and Protected MembersEdit Interfaces An object's interface refers to all of the public members and functions that a function exposes to consumers of the object. For example, take the following: type Monkey(name : string, birthday : DateTime) = let mutable _birthday = birthday let mutable _lastEaten = DateTime.Now let mutable _foodsEaten = [] : string list member this.Speak() = printfn "Ook ook!" member this.Name = name member this.Birthday with get() = _birthday and set(value) = _birthday <- value member internal this.UpdateFoodsEaten(food) = _foodsEaten <- food :: _foodsEaten member internal this.ResetLastEaten() = _lastEaten <- DateTime.Now member this.IsHungry = (DateTime.Now - _lastEaten).TotalSeconds >= 5.0 member this.GetFoodsEaten() = _lastEaten member this.Feed(food) = this.UpdateFoodsEaten(food) this.ResetLastEaten() this.Speak() This class contains several public, private, and internal members. However, consumers of this class can only access the public members; when a consumer uses this class, they see the following interface: type Monkey = class new : name:string * birthday:DateTime -> Monkey member Feed : food:string -> unit member GetFoodsEaten : unit -> DateTime member Speak : unit -> unit member Birthday : DateTime member IsHungry : bool member Name : string member Birthday : DateTime with set end Notice the _birthday, _lastEaten, _foodsEaten, UpdateFoodsEaten, and ResetLastEaten members are inaccessible to the outside world, so they are not part of this object's public interface. All interfaces you've seen so far have been intrinsically tied to a specific object. However, F# and many other OO languages allow users to define interfaces as stand-alone types, allowing us to effectively separate an object's interface from its implementation. Defining InterfacesEdit According to the F# specification, interfaces are defined with the following syntax: type type-name = interface inherits-decl member-defns end - Note: The interface/end tokens can be omitted when using the #light syntax option, in which case Type Kind Inference (§10.1) is used to determine the kind of the type. The presence of any non-abstract members or constructors means a type is not an interface type. For example: type ILifeForm = (* .NET convention recommends the prefix 'I' on all interfaces *) abstract Name : string abstract Speak : unit -> unit abstract Eat : unit -> unit Using InterfacesEdit Since they only define a set of public method signatures, users need to create an object to implement the interface. Here are three classes which implement the ILifeForm interface in fsi: > Typically, we call an interface an abstraction, and any class which implements the interface as a concrete implementation. In the example above, ILifeForm is an abstraction, whereas Dog, Monkey, and Ninja are concrete implementations. Its worth noting that interfaces only define instance members signatures on objects. In other words, they cannot define static member signatures or constructor signatures. What are interfaces used for and how to use them?Edit Interfaces are a mystery to newbie programmers (after all, what's the point of creating a type with no implementation?), however they are essential to many object-oriented programming techniques. Interfaces allow programmers to generalize functions to all classes which implement a particular functionality, which is described by the interface, even if those classes don't necessarily descend from one another. For example, the Dog, Monkey, and Ninja classes defined above contain behavior that is shared, which we defined in the ILifeForm interface. As the code shows, how the individual classes talk or eat is not defined, but for each class that implements the interface we know that they can eat and speak and have a name. Now we can write a method that accepts just the interface ILifeForm and we need not worry about how it is implemented, if it is implemented (it always is, the compiler takes care of that) or what type of object it really is. Any other class that implements the same interface, regardless of its other methods, is then automatically supported by this method as well. let letsEat (lifeForm: ILifeForm) = lifeForm.Eat() Note that in F#, interfaces are implemented explicitly, whereas in C# they are often implemented implicitly. As a consequence, to call a function or method that expects an interface, you have to make an explicit cast: let myDog = Dog() letsEat (myDog :> ILifeForm) You can simplify this by letting the compiler help find the proper interface by using the _ placeholder: let myDog = Dog() letsEat (myDog :> _) Implementing Interfaces with Object ExpressionsEdit Interfaces are extremely useful for sharing snippets of implementation logic between other classes, however it can be very cumbersome to define and implement a new class for ad hoc interfaces. Object expressions allow users to implement interfaces on anonymous classes using the following syntax: { new ty0 [ args-expr ] [ as base-ident ] [ with val-or-member-defns end ] interface ty1 with [ val-or-member-defns1 end ] … interface tyn with [ val-or-member-defnsn end ] } Using a concrete example, the .NET BCL has a method called System.Array.Sort<T>(T array, IComparer<T>), where IComparer<T> exposes a single method called Compare. Let's say we wanted to sort an array on an ad hoc basis using this method; rather than litter our code with one-time use classes, we can use object expressions to define anonymous classes on the fly: > open System open System.Collections.Generic type person = { name : string; age : int } let people = [|{ name = "Larry"; age = 20 }; { name = "Moe"; age = 30 }; { name = "Curly"; age = 25 } |] let sortAndPrint msg items (comparer : System.Collections.Generic.IComparer<person>) = Array.Sort(items, comparer) printf "%s: " msg Seq.iter (fun x -> printf "(%s, %i) " x.name x.age) items printfn "" (* sorting by age *) sortAndPrint "age" people { new IComparer<person> with member this.Compare(x, y) = x.age.CompareTo(y.age) } (* sorting by name *) sortAndPrint "name" people { new IComparer<person> with member this.Compare(x, y) = x.name.CompareTo(y.name) } (* sorting by name descending *) sortAndPrint "name desc" people { new IComparer<person> with member this.Compare(x, y) = y.name.CompareTo(x.name) };; type person = { name: string; age: int; } val people : person array val sortAndPrint : string -> person array -> IComparer<person> -> unit age: (Larry, 20) (Curly, 25) (Moe, 30) name: (Curly, 25) (Larry, 20) (Moe, 30) name desc: (Moe, 30) (Larry, 20) (Curly, 25) Implementing Multiple InterfacesEdit Unlike inheritance, its possible to implement multiple interfaces: open System type Person(name : string, age : int) = member this.Name = name member this.Age = age (* IComparable is used for ordering instances *) interface IComparable<Person> with member this.CompareTo(other) = (* sorts by name, then age *) match this.Name.CompareTo(other.Name) with | 0 -> this.Age.CompareTo(other.Age) | n -> n (* Used for comparing this type against other types *) interface IEquatable<string> with member this.Equals(othername) = this.Name.Equals(othername) Its just as easy to implement multiple interfaces in object expressions as well. Interface HierarchiesEdit Interfaces can extend other interfaces in a kind of interface hierarchy. For example: type ILifeForm = abstract member location : System.Drawing.Point type 'a IAnimal = (* interface with generic type parameter *) inherit ILifeForm inherit System.IComparable<'a> abstract member speak : unit -> unit type IFeline = inherit IAnimal<IFeline> abstract member purr : unit -> unit When users create a concrete implementation of IFeline, they are required to provide implementations for all of the methods defined in the IAnimal, IComparable, and ILifeForm interfaces. - Note: Interface hierarchies are occasionally useful, however deep, complicated hierarchies can be cumbersome to work with. ExamplesEdit Generalizing a function to many classesEdit open System" let lifeforms = [(new Dog("Fido", 7) :> ILifeForm); (new Monkey(500.0) :> ILifeForm); (new Ninja() :> ILifeForm)] let handleLifeForm (x : ILifeForm) = printfn "Handling lifeform '%s'" x.Name x.Speak() x.Eat() printfn "" let main() = printfn "Processing...\n" lifeforms |> Seq.iter handleLifeForm printfn "Done." main() This program has the following types: val lifeforms : ILifeForm list val handleLifeForm : ILifeForm -> unit val main : unit -> unit This program outputs the following: Processing... Handling lifeform 'Fido' Woof! Yum, doggy biscuits! Handling lifeform 'Monkey!!!' Ook ook Bananas! Handling lifeform 'Ninjas have no name' Ninjas are silent, deadly killers Ninjas don't eat, they wail on guitars because they're totally sweet Done. Using interfaces in generic type definitionsEdit We can constrain generic types in class and function definitions to particular interfaces. For example, let's say that we wanted to create a binary tree which satisfies the following property: each node in a binary tree has two children, left and right, where all of the child nodes in left are less than all of its parent nodes, and all of the child nodes in right are greater than all of its parent nodes. We can implement a binary tree with these properties defining a binary tree which constrains our tree to the IComparable<T> interface. - Note: .NET has a number of interfaces defined in the BCL, including the very important IComparable<T> interface. IComparable exposes a single method, objectInstance.CompareTo(otherInstance), which should return 1, -1, or 0 when the objectInstanceis greater than, less than, or equal to otherInstancerespectively. Many classes in the .NET framework already implement IComparable, including all of the numeric data types, strings, and datetimes. For example, using fsi: > open System type tree<'a> when 'a :> IComparable<'a> = | Nil | Node of 'a * 'a tree * 'a tree let rec insert (x : #IComparable<'a>) = function | Nil -> Node(x, Nil, Nil) | Node(y, l, r) as node -> if x.CompareTo(y) = 0 then node elif x.CompareTo(y) = -1 then Node(y, insert x l, r) else Node(y, l, insert x r) let rec contains (x : #IComparable<'a>) = function | Nil -> false | Node(y, l, r) as node -> if x.CompareTo(y) = 0 then true elif x.CompareTo(y) = -1 then contains x l else contains x r;; type tree<'a> when 'a :> IComparable<'a>> = | Nil | Node of 'a * tree<'a> * tree<'a> val insert : 'a -> tree<'a> -> tree<'a> when 'a :> IComparable<'a> val contains : #IComparable<'a> -> tree<'a> -> bool when 'a :> IComparable<'a> > let x = let rnd = new Random() [ for a in 1 .. 10 -> rnd.Next(1, 100) ] |> Seq.fold (fun acc x -> insert x acc) Nil;; val x : tree<int> > x;; val it : tree<int> = Node (25,Node (20,Node (6,Nil,Nil),Nil), Node (90, Node (86,Node (65,Node (50,Node (39,Node (32,Nil,Nil),Nil),Nil),Nil),Nil), Nil)) > contains 39 x;; val it : bool = true > contains 55 x;; val it : bool = false Simple dependency injectionEdit Dependency injection refers to the process of supplying an external dependency to a software component. For example, let's say we had a class which, in the event of an error, sends an email to the network administrator, we might write some code like this: type Processor() = (* ... *) member this.Process items = try (* do stuff with items *) with | err -> (new Emailer()).SendMsg("admin@company.com", "Error! " + err.Message) The Process method creates an instance of Processor class depends on the Let's say we're testing our Processor class, and we don't want to be sending emails to the network admin all the time. Rather than comment out the lines of code we don't want to run while we test, its much easier to substitute the Emailer dependency with a dummy class instead. We can achieve that by passing in our dependency through the constructor: type IFailureNotifier = abstract Notify : string -> unit type Processor(notifier : IFailureNotifier) = (* ... *) member this.Process items = try // do stuff with items with | err -> notifier.Notify(err.Message) (* concrete implementations of IFailureNotifier *) type EmailNotifier() = interface IFailureNotifier with member Notify(msg) = (new Emailer()).SendMsg("admin@company.com", "Error! " + msg) type DummyNotifier() = interface IFailureNotifier with member Notify(msg) = () // swallow message type LogfileNotifier(filename : string) = interface IFailureNotifer with member Notify(msg) = System.IO.File.AppendAllText(filename, msg) Now, we create a processor and pass in the kind of FailureNotifier we're interested in. In test environments, we'd use new Processor(new DummyNotifier()); in production, we'd use new Processor(new EmailNotifier()) or new Processor(new LogfileNotifier(@"C:\log.txt")). To demonstrate dependency injection using a somewhat contrived example, the following code in fsi shows how to hot swap one interface implementation with another: > #time;; --> Timing now on > type IAddStrategy = abstract add : int -> int -> int type DefaultAdder() = interface IAddStrategy with member this.add x y = x + y type SlowAdder() = interface IAddStrategy with member this.add x y = let rec loop acc = function | 0 -> acc | n -> loop (acc + 1) (n - 1) loop x y type OffByOneAdder() = interface IAddStrategy with member this.add x y = x + y - 1 type SwappableAdder(adder : IAddStrategy) = let mutable _adder = adder member this.Adder with get() = _adder and set(value) = _adder <- value member this.Add x y = this.Adder.add x y;; type IAddStrategy = interface abstract member add : int -> (int -> int) end type DefaultAdder = class interface IAddStrategy new : unit -> DefaultAdder end type SlowAdder = class interface IAddStrategy new : unit -> SlowAdder end type OffByOneAdder = class interface IAddStrategy new : unit -> OffByOneAdder end type SwappableAdder = class new : adder:IAddStrategy -> SwappableAdder member Add : x:int -> (int -> int) member Adder : IAddStrategy member Adder : IAddStrategy with set end Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 > let myAdder = new SwappableAdder(new DefaultAdder());; val myAdder : SwappableAdder Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 > myAdder.Add 10 1000000000;; Real: 00:00:00.001, CPU: 00:00:00.015, GC gen0: 0, gen1: 0, gen2: 0 val it : int = 1000000010 > myAdder.Adder <- new SlowAdder();; Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 val it : unit = () > myAdder.Add 10 1000000000;; Real: 00:00:01.085, CPU: 00:00:01.078, GC gen0: 0, gen1: 0, gen2: 0 val it : int = 1000000010 > myAdder.Adder <- new OffByOneAdder();; Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 val it : unit = () > myAdder.Add 10 1000000000;; Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0 val it : int = 1000000009 Events Events allow objects to communicate with one another through a kind of synchronous message passing. Events are simply hooks to other functions: objects register callback functions to an event, and these callbacks will be executed when (and if) the event is triggered by some object. For example, let's say we have a clickable button which exposed an event called Click. We can register a block of code, something like fun () -> printfn "I've been clicked!", to the button's click event. When the click event is triggered, it will execute the block of code we've registered. If we wanted to, we could register an indefinite number of callback functions to the click event—the button doesn't care what code is trigged by the callbacks or how many callback functions are registered to its click event, it blindly executes whatever functions are hooked to its click event. Event-driven programming is natural in GUI code, as GUIs tend to consist of controls which react and respond to user input. Events are, of course, useful in non-GUI applications as well. For example, if we have an object with mutable properties, we may want to notify another object when those properties change. Defining EventsEdit Events are created and used through F#'s Event class. To create an event, use the Event constructor as follows: type Person(name : string) = let mutable _name = name; let nameChanged = new Event<string>() member this.Name with get() = _name and set(value) = _name <- value To allow listeners to hook onto our event, we need to expose the nameChanged field as a public member using the event's Publish property: type Person(name : string) = let mutable _name = name; let nameChanged = new Event<unit>() (* creates event *) member this.NameChanged = nameChanged.Publish (* exposed event handler *) member this.Name with get() = _name and set(value) = _name <- value nameChanged.Trigger() (* invokes event handler *) Now, any object can listen to the changes on the person method. By convention and Microsoft's recommendation, events are usually named Verb or VerbPhrase, as well as adding tenses like Verbed and Verbing to indicate post- and pre-events. Adding Callbacks to Event HandlersEdit Its very easy to add callbacks to event handlers. Each event handler has the type IEvent<'T> which exposes several methods: val Add : event:('T -> unit) -> unit - Connect a listener function to the event. The listener will be invoked when the event is fired. val AddHandler : 'del -> unit - Connect a handler delegate object to the event. A handler can be later removed using RemoveHandler. The listener will be invoked when the event is fired. val RemoveHandler : 'del -> unit - Remove a listener delegate from an event listener store. Here's an example program:") p.NameChanged.Add(fun () -> printfn "-- Name changed! New name: %s" p.Name) printfn "Event handling is easy" p.Name <- "Joe" printfn "It handily decouples objects from one another" p.Name <- "Moe". -- Name changed! New name: Bo -- Another handler attached to NameChanged! The function NameChanged is invoked effortlessly. - Note: When multiple callbacks are connected to a single event, they are executed in the order they are added. However, in practice, you should not write code with the expectation that events will trigger in a particular order, as doing so can introduce complex dependencies between functions. Event-driven programming is often non-deterministic and fundamentally stateful, which can occasionally be at odds with the spirit of functional programming. Its best to write callback functions which do not modify state, and do not depend on the invocation of any prior events. Working with EventHandlers ExplicitlyEdit Adding and Removing Event HandlersEdit The code above demonstrates how to use the IEvent<'T>.add method. However, occasionally we need to remove callbacks. To do so, we need to work with the IEvent<'T>.AddHandler and IEvent<'T>.RemoveHandler methods, as well as .NET's built-in System.Delegate type. The function person.NameChanged.AddHandler has the type val AddHandler : Handler<'T> -> unit, where Handler<'T> inherits from System.Delegate. We can create an instance of Handler as follows:") let person_NameChanged = new Handler<unit>(fun sender eventargs -> printfn "-- Name changed! New name: %s" p.Name) p.NameChanged.AddHandler(person_NameChanged) printfn "Event handling is easy" p.Name <- "Joe" printfn "It handily decouples objects from one another" p.Name <- "Moe" p.NameChanged.RemoveHandler(person_NameChanged). -- Another handler attached to NameChanged! The function NameChanged is invoked effortlessly. Defining New Delegate TypesEdit F#'s event handling model is a little different from the rest of .NET. If we want to expose F# events to different languages like C# or VB.NET, we can define a custom delegate type which compiles to a .NET delegate using the delegate keyword, for example: type NameChangingEventArgs(oldName : string, newName : string) = inherit System.EventArgs() member this.OldName = oldName member this.NewName = newName type NameChangingDelegate = delegate of obj * NameChangingEventArgs -> unit The convention obj * NameChangingEventArgs corresponds to the .NET naming guidelines which recommend that all events have the type val eventName : (sender : obj * e : #EventArgs) -> unit. Use existing .NET WPF Event and Delegate TypesEdit Try using existing .NET WPF Event and Delegate, example, ClickEvent and RoutedEventHandler. Create F# Windows Application .NET project with referring these libraries (PresentationCore PresentationFramework System.Xaml WindowsBase). The program will display a button in a window. Clicking the button will display the button's content as string. open System.Windows open System.Windows.Controls open System.Windows.Input open System [<EntryPoint>] [<STAThread>] // STAThread is Single-Threading-Apartment which is required by WPF let main argv = let b = new Button(Content="Button") // b is a Button with "Button" as content let f(sender:obj)(e:RoutedEventArgs) = // (#3) f is a fun going to handle the Button.ClickEvent // f signature must be curried, not tuple as govened by Delegate-RoutedEventHandler. // that means f(sender:obj,e:RoutedEventArgs) will not work. let b = sender:?>Button // sender will have Button-type. Convert it to Button into b. MessageBox.Show(b.Content:?>string) // Retrieve the content of b which is obj. // Convert it to string and display by <code>Messagebox.Show</code> |> ignore // ignore the return because f-signature requires: obj->RoutedEventArgs->unit let d = new RoutedEventHandler(f) // (#2) d will have type-RoutedEventHandler, // RoutedEventHandler is a kind of delegate to handle Button.ClickEvent. // The f must have signature governed by RoutedEventHandler. b.AddHandler(Button.ClickEvent,d) // (#1) attach a RountedEventHandler-d for Button.ClickEvent let w = new Window(Visibility=Visibility.Visible,Content=b) // create a window-w have a Button-b // which will show the content of b when clicked (new Application()).Run(w) // create new Application() running the Window-w. b.AddHandler(Button.ClickEvent,d) let d = new RoutedEventHandler(f) let f(sender:obj)(e:RoutedEventArgs) = .... void RoutedEventHandler(object sender, RoutedEventArgs e). So f must have same signature. Present the signature in F# is (obj * RountedEventHandler) -> unit Passing State To CallbacksEdit Events can pass state to callbacks with minimal effort. Here is a simple program which reads a file in blocks of characters: open System type SuperFileReader() = let progressChanged = new Event<int>() member this.ProgressChanged = progressChanged.Publish member this.OpenFile (filename : string, charsPerBlock) = use sr = new System.IO.StreamReader(filename) let streamLength = int64 sr.BaseStream.Length let sb = new System.Text.StringBuilder(int streamLength) let charBuffer = Array.zeroCreate<char> charsPerBlock let mutable oldProgress = 0 let mutable totalCharsRead = 0 progressChanged.Trigger(0) while not sr.EndOfStream do (* sr.ReadBlock returns number of characters read from stream *) let charsRead = sr.ReadBlock(charBuffer, 0, charBuffer.Length) totalCharsRead <- totalCharsRead + charsRead (* appending chars read from buffer *) sb.Append(charBuffer, 0, charsRead) |> ignore let newProgress = int(decimal totalCharsRead / decimal streamLength * 100m) if newProgress > oldProgress then progressChanged.Trigger(newProgress) // passes newProgress as state to callbacks oldProgress <- newProgress sb.ToString() let fileReader = new SuperFileReader() fileReader.ProgressChanged.Add(fun percent -> printfn "%i percent done..." percent) let x = fileReader.OpenFile(@"C:\Test.txt", 50) printfn "%s[...]" x.[0 .. if x.Length <= 100 then x.Length - 1 else 100] This program has the following types: type SuperFileReader = class new : unit -> SuperFileReader member OpenFile : filename:string * charsToRead:int -> string member ProgressChanged : IEvent<int> end val fileReader : SuperFileReader val x : string Since our event has the type IEvent<int>, we can pass int data as state to listening callbacks. This program outputs the following: 0 percent done... 4 percent done... 9 percent done... 14 percent done... 19 percent done... 24 percent done... 29 percent done... 34 percent done... 39 percent done... 44 percent done... 49 percent done... 53 percent done... 58 percent done... 63 percent done... 68 percent done... 73 percent done... 78 percent done... 83 percent done... 88 percent done... 93 percent done... 98 percent done... 100 percent done... In computer programming, event-driven programming or event-based programming is a programming paradig[...] Retrieving State from CallersEdit A common idiom in event-driven programming is pre- and post-event handling, as well as the ability to cancel events. Cancellation requires two-way communication between an event handler and a listener, which we can easily accomplish through the use of ref cells or mutable members: type Person(name : string) = let mutable _name = name; let nameChanging = new Event<string * bool ref>() let nameChanged = new Event<unit>() member this.NameChanging = nameChanging.Publish member this.NameChanged = nameChanged.Publish member this.Name with get() = _name and set(value) = let cancelChange = ref false nameChanging.Trigger(value, cancelChange) if not !cancelChange then _name <- value nameChanged.Trigger() let p = new Person("Bob") p.NameChanging.Add(fun (name, cancel) -> let exboyfriends = ["Steve"; "Mike"; "Jon"; "Seth"] if List.exists (fun forbiddenName -> forbiddenName = name) exboyfriends then printfn "-- No %s's allowed!" name cancel :=
https://en.m.wikibooks.org/wiki/F_Sharp_Programming/Print_version
CC-MAIN-2021-17
refinedweb
15,473
55.95
I have the following code: // in file Globals.scala object Globals { val contex = "hello Global" } // in file FirstClass.scala class FirstClass { import Globals._ println("in FirstClass") } // after paste in file SecondClass class SecondClass { println("in FirstClass") } When I copy the file FirstClass.scala (right mouse click -> copy) then paste it as SecondClass.scala the "import Globals._" is missing. I was expecting a mirror copy of FirstClass. Is this normal? Using Intellij idea 15 CE EAP on iMac osx Yosemite Unused imports can be removed during Copy action. However you can create ticket to save local imports even if it's unused. I think it will be reasonable part of "Copy" feature. Best regards, Alexander Podkhalyuzin.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206633585-copy-and-paste-of-scala-file-is-missing-bits
CC-MAIN-2020-05
refinedweb
117
63.05
- 11 May 2022 14:49:29 UTC - Distribution: Playwright - Module version: 1.210 - Source (raw) - Browse (raw) - Changes - How to Contribute - Repository - Issues (10) - Testers (93 / 0 / 49) - KwaliteeBus factor: 1 - % Coverage - License: mit - Perl: v5.28.0 - Activity24 month - Tools - Download (250.63KB) - MetaCPAN Explorer - Permissions - Permalinks - This version - Latest version++ed by:2 non-PAUSE users - Dependencies - Capture::Tiny - Carp - Cwd - File::Basename - File::ShareDir - File::Temp - File::Which - JSON - JSON::MaybeXS - LWP::UserAgent - List::Util - Net::EmptyPort - POSIX - Proc::ProcessTable - Sereal::Decoder - Sereal::Encoder - Sub::Install - feature - parent - strict - warnings - Reverse dependencies - CPAN Testers List - Dependency graph - NAME - VERSION - SYNOPSIS - DESCRIPTION - Getting Started - Questions? - Documentation for Playwright Subclasses - Selectors - Scripts - Asynchronous operations - Getting Object parents - Firefox Specific concerns - Leaving browsers alive for manual debugging - Taking videos, Making Downloads - Doing arbitrary requests - Perl equivalents for playwright-test - INSTALLATION NOTE - CONSTRUCTOR - METHODS - BUGS - AUTHORS NAME Playwright - Perl client for Playwright VERSION version 1.210 SYNOPSIS use Playwright; my $handle = Playwright->new(); my $browser = $handle->launch( headless => 0, type => 'chrome' ); my $page = $browser->newPage(); my $res = $page->goto(' { waitUntil => 'networkidle' }); my $frameset = $page->mainFrame(); my $kidframes = $frameset->childFrames(); # Grab us some elements my $body = $page->select('body'); # You can also get the innerText my $text = $body->textContent(); $body->click(); $body->screenshot(); my $kids = $body->selectMulti('*'); DESCRIPTION Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright. Checks and automatically installs a copy of the node dependencies in the local folder if needed. Currently understands commands you can send to all the playwright classes defined in api.json (installed wherever your OS puts shared files for CPAN distributions). See and drill down into your relevant version (run `npm list playwright` ) for what the classes do, and their usage. All the classes mentioned there will correspond to a subclass of the Playwright namespace. For example: # ISA Playwright my $playwright = Playwright->new(); # ISA Playwright::BrowserContext my $ctx = $playwright->newContext(...); # ISA Playwright::Page my $page = $ctx->newPage(...); # ISA Playwright::ElementHandle my $element = $ctx->select('body'); See example.pl for a more thoroughly fleshed-out display on how to use this module. Getting Started When using the playwright module for the first time, you may be told to install node.js libraries. It should provide you with instructions which will get you working right away. However, depending on your node installation this may not work due to dependencies for node.js not being in the expected location. To fix this, you will need to update your NODE_PATH environment variable to point to the correct location. Node Versions playwright itself tends to need the latest version of node to work properly. It is recommended that you use nvm to get a hold of this: From there it's recommended you use the latest version of node: nvm install node nvm use node Questions? Feel free to join the Playwright slack server, as there is a dedicated #playwright-perl channel which I, the module author, await your requests in. Documentation for Playwright Subclasses The documentation and names for the subclasses of Playwright follow the spec strictly: Playwright::BrowserContext => Playwright::Page => Playwright::ElementHandle => ...And so on. These classes are automatically generated during module build based on the spec hash built by playwright. See generate_api_json.sh and generate_perl_modules.pl if you are interested in how this sausage is made. You can check what methods are installed for each subclass by doing the following: use Data::Dumper; print Dumper($instance->{spec}); There are two major exceptions in how things work versus the upstream Playwright documentation, detailed below in the Selectorssection. Selectors The selector functions have to be renamed from starting with $ for obvious reasons. The renamed functions are as follows: These functions are present as part of the Page, Frame and ElementHandle classes. Scripts The evaluate() and evaluateHandle() functions can only be run in string mode. To maximize the usefulness of these, I have wrapped the string passed with the following function: const fun = new Function (toEval); args = [ fun, ...args ]; As such you can effectively treat the script string as a function body. The same restriction on only being able to pass one arg remains from the upstream: You will have to refer to the arguments array as described here: You can also pass Playwright::ElementHandle objects as returned by the select() and selectMulti() routines. They will be correctly translated into DOMNodes as you would get from the querySelector() javascript functions. Calling evaluate() and evaluateHandle() on Playwright::Element objects will automatically pass the DOMNode as the first argument to your script. See below for an example of doing this. example of evaluate() # Read the console $page->on('console',"return [...arguments]"); my $promise = $page->waitForEvent('console'); #TODO This request can race, the server framework I use to host the playwright spec is *not* FIFO (YET) sleep 1; $page->evaluate("console.log('hug')"); my $console_log = $handle->await( $promise ); print "Logged to console: '".$console_log->text()."'\n"; # Convenient usage of evaluate on ElementHandles # We pass the element itself as the first argument to the JS arguments array for you $element->evaluate('arguments[0].style.backgroundColor = "#FF0000"; return 1;'); Asynchronous operations The waitFor* methods defined on various classes fork and exec, waiting on the promise to complete. You will need to wait on the result of the backgrounded action with the await() method documented below. # Assuming $handle is a Playwright object my $async = $page->waitForEvent('console'); $page->evaluate('console.log("whee")'); my $result = $handle->await( $async ); my $logged = $result->text(); Getting Object parents Some things, like elements naturally are children of the pages in which they are found. Sometimes this can get confusing when you are using multiple pages, especially if you let the ref to the page go out of scope. Don't worry though, you can access the parent attribute on most Playwright::* objects: # Assuming $element is a Playwright::ElementHandle my $page = $element->{parent}; Firefox Specific concerns By default, firefox will open PDFs in a pdf.js window. To suppress this behavior (such as in the event you are await()ing a download event), you will have to pass this option to launch(): # Assuming $handle is a Playwright object my $browser = $handle->launch( type => 'firefox', firefoxUserPrefs => { 'pdfjs.disabled' => JSON::true } ); Leaving browsers alive for manual debugging Passing the cleanup => 0 parameter to new() will prevent DESTROY() from cleaning up the playwright server when a playwright object goes out of scope. Be aware that this will prevent debug => 1 from printing extra messages from playwright_server itself, as we redirect the output streams in this case so as not to fill your current session with prints later. A convenience script has been provided to clean up these orphaned instances, `reap_playwright_servers` which will kill all extant `playwright_server` processes. Taking videos, Making Downloads We spawn browsers via BrowserType.launchServer() and then connect to them over websocket. This means you can't just set paths up front and have videos recorded, the Video.path() method will throw. Instead you will need to call the Video.saveAs() method after closing a page to record video: # Do stuff ... # Save video my $video = $page->video; $page->close(); $video->saveAs('video/example.webm'); It's a similar story with Download classes: # Do stuff ... # Wait on Download my $promise = $page->waitForEvent('download') # Do some thing triggering a download ... my $download = $handle->await( $promise ); $download->saveAs('somefile.extension'); Remember when doing an await() with playwright-perl you are waiting on a remote process on a server to complete, which can time out. You may wish to spawn a subprocess using a different tool to download very large files. If this is not an option, consider increasing the timeout on the LWP object used by the Playwright object (it's the 'ua' member of the class). Doing arbitrary requests When you either want to test APIs (or not look like a scraper/crawler) you'll want to issue arbitrary requests, such as POST/HEAD/DELETE et cetera. Here's how you go about that: print "HEAD : \n"; my $fr = $page->request(); my $resp = $fr->fetch(" { method => "HEAD" }); print Dumper($resp->headers()); print "200 OK\n" if $resp->status() == 200; The request() method will give you a Playwright::APIRequestContext object, which you can then call whichever methods you like upon. When you call fetch (or get, post, etc) you will then be returned a Playwright::APIResponse object. Differences in behavior from Selenium::Remote::Driver By default selenium has its selector methods obeying a timeout and waits for an element to appear. It then explodes when and element can't be found. To replicate this mode of operation, we have provided the try_until helper: # Args are $object, $method, @args my $element = Playwright::try_until($page, 'select', $selector) or die ...; This will use the timeouts described by pusht/popt (see below). Perl equivalents for playwright-test This section is intended to be read alongside the playwright-test documentation to aid understanding of common browser testing techniques. The relevant documentation section will be linked for each section. Annotations Both Test::More and Test2::V0 provide an equivalent to all the annotations but slow(): - skip or fixme - Test::More::skip or Test2::Tools::Basic::skip handle both needs - - fail - Test::More TODO blocks and Test2::Tools::Basic::todo - - slow - Has no equivalent off the shelf. Playwright::pusht() and Playwright::popt() are here to help. # Examples assume you have a $page object. # Timeouts are in milliseconds Playwright::pusht($page,5000); # Do various things... ... Playwright::popt($page); See for more on setting default timeouts in playwright. By default we assume the timeout to be 30s. Assertions As with before, most of the functionality here is satisfied with perl's default testing libraries. In particular, like() and cmp_bag() will do most of what you want here. Authentication Much of the callback functionality used in these sections is provided by Test::Class and it's fixtures. Command Line Both proveand yathhave similar functionality, save for retrying flaky tests. That said, you shouldn't do that; good tests don't flake. Configuration All the configuration here can simply be passed to launch(), newPage() or other methods directly. Page Objects This is basically what Test::Class was written for specifically; so that you could subclass testing of common components across pages. Parallelizing Tests Look into Test::Class::Moose's Parallel runmode, prove's -j option, or Test2::Aggregate. Reporters When using prove, consider Test::Reporter coupled with App::Prove::Plugins using custom TAP::Formatters. Test2 as of this writing (October 2012) supports formatters and plugins, but no formatter plugins have been uploaded to CPAN. See Test2::Manual::Tooling::Formatter on writing a formatter yourself, and then a Test2::Plugin using it. Test Retry provesupports tests in sequence via the --rules option. It's also got the handy --state options to further micromanage test execution over multiple iterations. You can use this to retry flaking tests, but it's not a great idea in practice. Visual Comparisons Use Image::Compare. Advanced Configuration This yet again can be handled when instantiating the various playwright objects. Fixtures Test::Class and it's many variants cover the subject well. INSTALLATION NOTE If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies. Follow the instructions and things should be just fine. If you aren't, please file a bug! CONSTRUCTOR new(HASH) = (Playwright) Creates a new browser and returns a handle to interact with it. INPUT debug (BOOL) : Print extra messages from the Playwright server process. Default: false timeout (INTEGER) : Seconds to wait for the playwright server to spin up and down. Default: 30s cleanup (BOOL) : Whether or not to clean up the playwright server when this object goes out of scope. Default: true METHODS launch(HASH) = Playwright::Browser The Argument hash here is essentially those you'd see from browserType.launch(). See: There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'. server (HASH) = MIXED Call Playwright::BrowserServer methods on the server which launched your browser object. Parameters: browser : The Browser object you wish to call a server method upon. command : The BrowserServer method you wish to call The most common use for this is to get the PID of the underlying browser process: my $browser = $playwright->launch( browser => chrome ); my $process = $playwright->server( browser => $browser, command => 'process' ); print "Browser process PID: $process->{pid}\n"; BrowserServer methods (at the time of writing) take no arguments, so they are not processed. await (HASH) = Object Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value. pusht(Playwright::Page, INTEGER timeout, BOOL navigation) = null Like pushd/popd, but for default timeouts used by a Playwright::Page object and it's children. If the 'navigation' option is high, we set the NavigationTimeout rather than the DefaultTimeout. By default 'navigation' is false. If we popt to the bottom of the stack, we will set the timeout back to 1 second. popt(Playwright::Page, BOOL navigation) = null The counterpart to pusht() which returns the timeout value to it's previous value. try_until(Object, STRING method, LIST args), try_until_die(...) Try to execute the provided method upon the provided Playwright::* object until it returns something truthy. Quits after the timeout (or 1s, if pusht is not used before this) defined on the object is reached. Use this for methods which *don't* support a timeout option, such as select(). quit, DESTROY Terminate the browser session and wait for the Playwright server to terminate. Automatically called when the Playwright object goes out of scope. BUGS Please report any bugs or feature requests on the bugtracker website When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. AUTHORS Current Maintainers: George S. Baugh <teodes Install Instructions To install Playwright, copy and paste the appropriate command in to your terminal. cpanm Playwright perl -MCPAN -e shell install Playwright For more information on module installation, please visit the detailed CPAN module installation guide.
https://metacpan.org/pod/Playwright
CC-MAIN-2022-21
refinedweb
2,339
54.22
One of the most major forms of chunking in natural language processing is called "Named Entity Recognition." The idea is to have the machine immediately be able to pull out "entities" like people, places, things, locations, monetary figures, and more. This can be a bit of a challenge, but NLTK is this built in for us. There are two major options with NLTK's named entity recognition: either recognize all named entities, or recognize named entities as their respective type, like people, places, locations, etc. Here's an example: import nltk from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer train_text = state_union.raw("2005-GWBush.txt") sample_text = state_union.raw("2006-GWBush.txt") custom_sent_tokenizer = PunktSentenceTokenizer(train_text) tokenized = custom_sent_tokenizer.tokenize(sample_text) def process_content(): try: for i in tokenized[5:]: words = nltk.word_tokenize(i) tagged = nltk.pos_tag(words) namedEnt = nltk.ne_chunk(tagged, binary=True) namedEnt.draw() except Exception as e: print(str(e)) process_content() Here, with the option of binary = True, this means either something is a named entity, or not. There will be no further detail. The result is: If you set binary = False, then the result is: Immediately, you can see a few things. When Binary is False, it picked up the same things, but wound up splitting up terms like White House into "White" and "House" as if they were different, whereas we could see in the binary = True option, the named entity recognition was correct to say White House was part of the same named entity. Depending on your goals, you may use the binary option how you see fit. Here are the types of Named Entities that you can get if you have binary as false: Either way, you will probably find that you need to do a bit more work to get it just right, but this is pretty powerful right out of the box. In the next tutorial, we're going to talk about something similar to stemming, called lemmatizing.
https://pythonprogramming.net/named-entity-recognition-nltk-tutorial/?completed=/chinking-nltk-tutorial/
CC-MAIN-2018-05
refinedweb
325
56.35
Download presentation Presentation is loading. Please wait. Published byJohnathan Birchell Modified over 2 years ago 1 2 In order to start this project, I thought I will also need a pilot’s opinion. I had the pleasure to work with a SFO , Adrian Barzoi, from one of the biggest airline companies at this moment, Etihad Airways 3 Development of Mobile Applications for Pilots public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main) Button b = (Button) findViewById(R.id.button1); ImageView img = (ImageView) findViewById(R.id.imageView3); Enough with the advertising, I shall get back to the subject 4 Contents of the presentation Electronic Flight Bags One Engine Inoperative procedure Aerodynamic and Performance calculations behind OEI Development of OEI Application for Android Platform OEI Application Demo Conclusions 5 EFb = Electronic flight bag Electronic device Helps flight crews Flight management Efficient manner 6 ADVANTAGES – EFB Flight bag mass reduction Time saving instrument Left picture: A classic paper based flight bag can weigh up to 60 kgs while an EFB can reach a maximum of 1 kg. Right picture: a standard procedure...for example the OEI can take up to 19 minutes ( following all the steps and performance calculations). Using an EFB modelled app can take maximum 2 minutes. Flight bag mass reduction Time saving instrument 7 THE CHALLENGEs 1. Find, understand and model a procedure for an Electronic Flight Bag 2. This procedure needs to be complex and not already implemented on EFBs. 8 ONE ENGINE INOPERATIVE The choice is OEI For ETIHAD Airways – Airbus A 9 Oei – airbus a OEI or One Engine Inoperative is a procedure to be followed in case of engine failure (one engine out of two) no matter the reason for which the engine ceased to undertake its normal task. This procedure is part of the Flight Crew Operations Manual and consists of 130 pages of definitions, explanations and performance data tables. This chapter probably represents 3% of the whole FCOM. 10 OEI STRATEGIES STANDARD Strategy OBSTACLE Strategy There are 3 types of strategies which can be used in case of an engine failure: STANDARD Strategy OBSTACLE Strategy FIXED SPEED Strategy 11 Standard strategy The standard strategy is the most used one and it is for the general routine when there are no mountainous areas in the vicinity of the aircraft, or when no speed restrictions are imposed by the air traffic control unit due to air traffic management reasons like high traffic flows in the area. Another speed restriction can appear as a result of structural damage due to an engine explosion which led to the one engine inoperative situation. Also, the speed may need to be increased in ETOPS situations. 12 OBSTACLE STRATEGY The obstacle strategy is used when there are mountainous areas in the vicinity of the aircraft. This strategy is performed using the aircraft in its cleanest configuration and at the green dot speed. This speed provides the best lift to drag ratio, thus making the descent from the occurrence flight level to the LRC as long as possible. Making the descent as long as possible, the mountainous area can be cleared. This strategy becomes very important when flying over areas with high terrain which is extensively spread over large areas. 13 FIXED SPEED STRATEGY If there are no other speed restrictions that need to be applied due to ATM reasons or structural damages, this strategy will be used as stated in the FCOM. This section provides single engine performance data for two fixed speed diversion strategies (fixed descent and cruise speed schedules) recommended for ETOPS operation. According to the ETOPS certification (90 mins, 120 mins, 138 mins, 180 mins or 240 mins) that aircraft is capable of, different speeds will be considered for this strategy. 14 Standard Strategy - SOP In this case, after the occurrence of the failure, before descending, the pilot will set the throttle lever of the working engine to Maximum Continuous Thrust. The MCT is different from the Maximum Take-Off Thrust which represents the maximum thrust available for no more than 5 minutes. The MTO is known to generate high stresses and temperatures in the engine. After the MCT is set, the auto-thrust should be turned off because the pilot would want to maintain the flight level until the decision regarding the strategy is made. The aircraft will certainly not be able to maintain the current speed at the present flight level. So with the A/THR of it will decelerate to green dot aerodynamically, maintaining the flight level. Next step is to declare the emergency to the ATC in order for the unit to clear the flight levels below the aircraft. Up to this step, the aircraft maintains the flight level, but it decelerates, even though the thrust is set to MCT. The pilot should pay attention to the indicated airspeed not to decrease below the green dot speed. The green dot speed is a calculated airspeed for which the aircraft delivers the best lift to drag ratio, given a certain flight level. In this case, decelerating below the green dot speed will result in a dangerous situation, also creating as a consequence an increase in the fuel consumption. These minutes should also be dedicated to the determination of the long range ceiling (i.e. the flight level at which the aircraft will spend most of its cruise to the destination airport). This flight level is carefully computed in order to determine the altitude at which the aircraft is able to provide sufficient lift and not too much drag. The LRC represents a function of mass, the higher the mass of the aircraft, the lower the LRC will be. The last step at this stage is to perform all ECAM actions which besides explaining the chain of failures due to the incapacity of the engine to deliver power, it also presents a list of procedures to be followed in order to correct certain problems. The descent phase is done at Mach 0.82 if the aircraft is above FL 250 or at an IAS of 300 kts if below FL250. The LRC being known from the previous step, now it is introduced in the Flight Control Unit. Because the thrust was set to MCT, the speed is controlled automatically by the elevator, thus the vertical speed will vary. This procedure can lead to a vertical speed which is less than 500 ft/min and wasting too much time between flight levels can be dangerous and inefficient. If the VS drops below 500 ft/min, the vertical speed mode should be selected at more than 500. All this time, the auto-thrust is off. The rest of the flight is performed at a flight level as close as possible to the long range ceiling level and at the long range speed. The long range speed is a speed higher than the maximum range speed. The maximum range speed is the speed at which the maximum number of nautical miles can be covered with a certain amount of fuel. The long range speed is the speed at which 99% of the maximum range can be achieved. So a reduction in range with 1 % can be converted into a speed increase of approximately 5-7 %. In this flight phase, the A/THR must be turned on. The landing part mostly depends upon the ATC procedures and should be performed in accordance with the flight level, at 300 kts or 250 kts until the initial approach point. 15 Standard Strategy – Example – page 1 Initial data: Gross Weight at engine failure moment Kg Flight Level at engine failure moment FL 350 Temperature ISA Distance to Destination Airport 440 NM Wind NO Anti-ice 16 STANDARD STRATEGY – EXAMPLE – Page 2 First step is represented by the selection of the Long Range Cruise Ceiling which is depending on the GW at the engine failure moment. In this case the LRC corresponding to a GW of Kg is close to FL235. Due to ATM reasons, the approximated LRC will be at FL230, because the aircraft may not be able to maintain a higher flight level, like 240. 17 STANDARD STRATEGY – EXAMPLE – Page 3 There are also anti-icing systems which can increase the load on the working engine, thus making the LRC to be even lower. The table determining this case is the following one. It is not the case here to apply icing conditions. 18 STANDARD STRATEGY – EXAMPLE – Page 4 For FL 350: Time increment is : (44.8−43.9) = / kg Fuel increment is: (3595−3576) = / kg Distance increment is: (306−299) = / kg Time at FL 350 and GW = kg is: 44.8− ∗ − =𝟒𝟒.𝟎𝟖 𝒎𝒊𝒏𝒖𝒕𝒆𝒔 Fuel at FL 350 and GW = kg is: ∗ − =𝟑𝟓𝟗𝟏.𝟐 𝒌𝒈 Distance at FL 350 and GW = kg is: 306− ∗ − =𝟑𝟎𝟎.𝟒 𝑵𝑴 The next step represents the distance, fuel and time calculations during the descent phase. As observed in the following table, there are some interpolations that need to be performed in order to find out the correct values. The computation algorithm is based on subtracting the number corresponding to the LRC from the number corresponding to the initial flight level. 19 STANDARD STRATEGY – EXAMPLE – Page 5 For FL 230: Time is 26 minutes Fuel increment is: (2108.5−2049) = / kg Distance is 165 NM Fuel at FL 230 and GW = kg is: ∗ − − =𝟐𝟎𝟗𝟔.𝟔 𝒌𝒈 Descending from FL 350 to FL 230: The time spent will be – 26 = minutes The fuel burnt will be – = kg The distance covered will be: – 165 = NM After the initial descent, the aircraft will have a mass of – = kg and a distance left of 440 – = NM. 20 STANDARD STRATEGY – EXAMPLE – Page 6 The remaining distance is used to calculate the time and fuel which will be wasted during the last phase of flight. The table helping the pilot to determine the time and fuel needed is the following one. 21 STANDARD STRATEGY – EXAMPLE – Page 7 The values corresponding to the present situation are the following ones: Fuel burnt for NM : ( ) * = kg Time spent to cover a distance of NM : ( )* = 1 hour and 1.5 minutes Fuel correction : * ( ) = kg / 1000kg above GW= kg Extra fuel due to increased mass : ( – )*(12.276/1000) = kg Total fuel burnt from LRC to landing : = kg Air Distance Fuel - FL230 Time – FL230 Fuel correction – FL230 300 1.0075 12 350 3998.5 1.09 15 22 STANDARD STRATEGY – EXAMPLE – Page 8 As observed in the table, the long range speed for FL230 and an approximate GW of 188 tons, is 261 kts. This means that the cruise part of the flight will be conducted at an IAS of 261 kts. Considering the above calculations, this example can conclude. In order to cover a distance of 440 NM from an altitude of ft and a mass of kg, an Airbus A will burn = kg of fuel in 1 hour and minutes. The cruise phase of the flight will be performed at a long range speed as specified in the following tables. The theory behind the long range speed will be discussed in the Performance Calculations and Aerodynamics Chapter. 23 Performance calculations and aerodynamics Topics covered in this chapter: Green Dot Speed Conversion from TAS to IAS Maximum Range Maximum Range Speed and Long Range Cruise Speed Long Range Cruise Ceiling I am not going to explain all of them due to time constraints, but they are all described in the paper. 24 Green dot speed – Page 1 Below the green dot speed the induced drag increases and above the green dot speed the parasitic drag increases. The induced drag for a wing with an elliptical lift distribution, which is the case of an airbus A is computed as follows. 𝐶 𝐷 𝑖 = 𝐶 𝑙 2 𝜋∙𝑒∙𝜆 𝐶 𝑙 = 𝐿 1 2 ∙ 𝜌 0 ∙ 𝑉 𝑒 2 ∙𝑆 𝐷 𝑖 = 1 2 ∙𝜌∙ 𝑉 2 ∙𝑆∙ 𝐶 𝐷 𝑖 = 1 2 ∙ 𝜌 0 ∙ 𝑉 𝑒 2 ∙𝑆∙ 𝐶 𝐷 𝑖 Equation 2.3.0 The green dot speed is also known as the clean configuration operating speed with one engine out at which the best lift to drag ratio is provided. This green dot speed is estimated by Airbus to be calculated in the following way. Equation 2.3.1 Equation 2.3.2 25 Green dot speed – Page 2 Considering that the total drag coefficient is equal with the induced drag plus the zero lift drag coefficient, the following relation can be obtained. 𝐿 𝐷 = 𝐶 𝑙 𝐶 𝑑 = 𝐶 𝑙 𝐶 𝐷 𝐶 𝑙 2 𝜋∙𝑒∙𝜆 Differentiating to find out the maximum value: 𝑑( 𝐿 𝐷 ) 𝑑 𝐶 𝑙 = (𝐶 𝐷 𝐶 𝑙 2 𝜋∙𝑒∙𝜆 ) 2 Equation 2.3.5 Equation 2.3.6 26 Green dot speed – Page 3 𝑑( 𝐿 𝐷 ) 𝑑 𝐶 𝑙 =0=> =0=> 𝐶 𝐷 0 − 𝐶 𝑙 2 𝜋∙𝑒∙𝜆 =0 C D 0 = C l 2 π∙e∙λ From Equation it results that the zero lift drag coefficient equals induced drag coefficient in the case of maximum L/D ratio. Also, from the same equation results that the lift coefficient is equal to : 𝐶 𝑙 = C D 0 ∙π∙e∙λ Equation 2.3.8 Equation 2.3.9 27 Green dot speed – page 4 Including equation in equation it results that the maximum lift to drag ratio is equal with: 𝐿 𝐷 𝑚𝑎𝑥 = 1 2 ∙ π∙e∙λ C D 0 Considering the lift equal with the weight of the aircraft during the cruise flight, the speed for maximum lift to drag ratio or the green dot speed is depicted in the following formula. 𝑉=𝐺𝐷𝑆= 2∙𝑊 𝜌∙𝑆∙ C D 0 ∙π∙e∙λ Equation Considering the air density, ρ, at a specific flight level, the above computed speed for maximum lift to drag ratio will be a true airspeed. In the case of an engine failure, the drag coefficient will increase due to the fact that the stopped fan is increasing the overall drag. e is the Oswald Efficiency number which represents a correction due to the fact that a real wing is a three dimensions one , in comparison with the ideal wing. Equation 28 Development of OEI Application for Android Platform 7500 code lines compose the following application. 29 Oei application demo Use Samsung S3 and Team Viewer. 30 conclusions The advantages do not consist only in the reduction of the paper quantity used inside the cockpit, but they are also related to time improvements. It can be deduced that the EFB used for this study has the theoretical capacity to store around 180 Kg of manuals and procedures. The time used to perform the computations with the aid of the application is 6.3 times smaller than the time used to perform the same performance computations, but having available only pen and paper. The overall benefits of using Electronic Flight Bags and in particular, the OEI Application are high. In the next 5 to 10 years, a sustained growth of the EFBs is anticipated. 31 Thank you for your attention !!! 32 Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/3978554/
CC-MAIN-2017-17
refinedweb
2,531
57.5
In using the following two source properties on the originating process and secondary process (formatted exactly the same); they are not translating to the property values on the secondary process (whereas they are translating correctly on the originating): sonar.scm.user.secured=${p:process/sourceConfigs/properties[@name='scmUserName']} sonar.scm.password.secured=${p:process/sourceConfigs/properties[@name='scmPassword']} Answer by ChrisRees (1124) | Feb 16, 2016 at 04:38 PM Secondary processes do not have access to Source Config information because they do not "build", but rather just run additional steps as needed (like running Selenium tests every hour, database tests every night at midnight, assigning additional statuses, etc). That is too bad. I know that I can populate a workspace in the secondary process without issue. We wanted to have a secondary workflow so that we could activate a system property that would have all the builds spin off a sonar scan to the stage sonar instance. The sonar prod runs in the originating process. Having the ability to spin off the stage sonar scan would allow us to let the users see what the application sonar scan results look like before we roll-out upgrades and rule changes to prod. Sonar needs the repository user id and password so as to collect "blame" info for issues. I find that interesting. Secondary processes don't have a source config, so I wouldn't expect a populate to work. It's also not how we intended secondary processes to be used. If you can populate, chances are that the reason you can't resolve the property is because the process namespace refers to build processes. You can check to see if secondaryProcess does anything, but I don't think it exists. I can check in the morning. One way you can get around it is by setting the Sonar username/password as a property on the System -> Properties page so they are global. Another option would be to set them at the Project or Process level 49 people are following this question. How are groups removed from the System Team Administrator Role? 1 Answer Source Config Plugin - subversion - (svn: invalid option: --trust-server-cert) 1 Answer Do Urbancode Build repository trigger codes expire? 1 Answer What is the best strategy for Urbancode Suite deployment? 4 Answers Installing a new plugin error 1 Answer
https://developer.ibm.com/answers/questions/253215/how-can-i-make-source-properties-translate-correct.html
CC-MAIN-2019-26
refinedweb
392
53
Find Questions & Answers Can't find what you're looking for? Visit the Questions & Answers page! Dears, Currently, we are using UI5 landing page implemented with ESS-WDA embedded deployment on ERP6 EHP7. Due to lack of log out option on UI5 landing page, we would like to use Fiori lauchpad as it gives log out option. We are facing error, when the tiles are added and viewed using the url:? Error message: Cannot load tile. Backend error log message: Property (external name) 'Page' not found for entity 'type' Here External name is referring to ZPAGE_BUILDER_PERS Please check if SICF node for this is activated : PAGE_BUILDER_PERS Also please add this odata service in transaction : /iwfnd/maint_service -> Add service -> Give your local system alias and add the service for launchpad. Regards, Tejas Dear Tejas, All the settings have been maintained already...with created Systam alias SAP_ESS. I have changed this system alias to local and tried but its throwing the same error. I have attached the screenshot of services page.. Kindly please suggest. All the services with namespace /UI2/ should have system alias as LOCAL and not pointing to backend. Please correct it for all other services. Please read through this link : Regards, Tejas Also post error screenshot from /IWFND/ERROR_LOG Check the missing authorizations (Su53). Hi Joseph, Thanks for your reply. I have checked su53, actucally to avoid any authorization issue, I have given SAP_ALL as well as maintained catalog details in separate role. Is there anything else that I am missing here...? Make sure your LPD_Cust Application pages are not inside the Inactive Applications folder. Regards, Meghal Shah Dear Meghal, We have checked, LPD_Cust Application pages are not inside the Inactive Applications folder. Any other suggestion you would like to add.,. Kindly please let me know..? Hi Syed , Please run the transaction /n/UI2/FLIA and check the intent status must be green. If not pelase share message detail of that intent. Regards, Meghal Shah did you follow proper document for configuring wda in flp? did you check su53 in frontend server? check the error in console. Hi Raza, If My home is the personalization group, please create a new group and add your WDA tile to ensure that it works before you personalize it. After this, it still shows Cannot load tiles, you will be able to see the error in the console with F12, and you can attach the screen shot here. However, you can follow the links bellow to ensure your configuration: Implementation of WDA though Hi Inoussa, Thanks for the reply. given link does not open: WDA step by step1 Also, I have created new group and added tiles as instructed. It still shows Cannot load tile. I have attached the console error screenshot for more details..fiori-console-error.png Copy the link and past on your browser to open the document WAD step by step
https://answers.sap.com/questions/476538/sap-fiori-launchpad-configuration-with-lpd-cust-to.html
CC-MAIN-2018-30
refinedweb
482
65.93
Greetings, so i'm trying to use vertex buffer objects, however, glGenBuffers is throwing me an access violation Checklist time: i have glew installed. i have freeglut installed included in this order #include <GL/glew.h> #include <GL/wglew.h> #include <GL/freeglut.h> i have a linkers to the appropriate libraries, (glew32, freeglut) unless i missed something i have run glewinit (both before and after glutinit on seperate attempts) genbuffers is run as follows ... GLuint VBO = 0; void init(){ float temp[]={10,10,20,10,10,20}; glGenBuffers(1,&VBO); ... according to the utilities included in glew, my open gl version is version string: 4.2.11931 any help? i can provide more code if needed
http://www.gamedev.net/index.php?app=forums&module=extras&section=postHistory&pid=5034386
CC-MAIN-2014-42
refinedweb
117
60.21
Here is a basic program that computes square feet of a house. It ask how many rooms...then ask for the width and length of each room, and then totals square foot from that. I wrote this program myself, and can do it without functions. But I am working on functions, and I cannot get the values passed right. I just don't really understand how to pass values yet I guess:) I want to pass the value of rooms between 2 functions named HOWMANYROOMS and SQUAREFEET. The program just dies after I enter the rooms (it goes back to dos prompt. I am using the Dos Prompt Command from Visual Studio 2010 by the way. Here is the program. I want to keep is as basic as possible for right now:)...there are probably better more efficient ways of programming it, but I want to just keep it very basic to learn the basics. Thanks for any and all help received. I appreciate it very much. Code: #include <stdio.h> int howmanyrooms(int rooms); int squarefoot(int totalsquare, int rooms); int main(void) { int totalsquare = 0; int rooms = 0; printf("This program computes square footage of a house.\n"); howmanyrooms(rooms); squarefoot(totalsquare, rooms); printf("Total Square Foot is %d", totalsquare); return 0; } int howmanyrooms(int rooms) { printf("How many rooms are in this house?\n"); scanf("%d", &rooms); return rooms; } int squarefoot(int totalsquare, int rooms) { int roomnumber, width, length, roomsquare, i; roomnumber = 1; for (i = 0; i < rooms; ++i) { printf("What are the width of room %d\n", roomnumber); scanf("%d", &width); printf("What is the length of room %d\n", roomnumber); scanf("%d", &length); roomsquare = width * length; totalsquare = totalsquare + roomsquare; ++roomnumber; } return totalsquare; }
http://cboard.cprogramming.com/c-programming/148392-basic-question-about-passing-values-between-functions-printable-thread.html
CC-MAIN-2014-52
refinedweb
287
72.66
PHP Cookbook/Directories From WikiContent Introduction A filesystem stores a lot of additional information about files aside from their actual contents. This information includes such particulars as the file's size, what directory it's in, and access permissions for the file. If you're working with files, you may also need to manipulate this metadata. PHP gives you a variety of functions to read and manipulate directories, directory entries, and file attributes. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. Files are organized with inodes . Each file (and other parts of the filesystem, such as directories, devices, and links) has its own inode. That inode contains a pointer to where the file's data blocks are as well as all the metadata about the file. The data blocks for a directory hold the names of the files in that directory and the inode of each file. PHP provides two ways to look in a directory to see what files it holds. The first way is to use opendir( ) to get a directory handle, readdir( ) to iterate through the files, and closedir( ) to close the directory handle: $d = opendir('/usr/local/images') or die($php_errormsg); while (false !== ($f = readdir($d))) { // process file } closedir($d); The second method is to use the directory class. Instantiate the class with dir( ), read each filename with the read( ) method, and close the directory with close( ) : $d = dir('/usr/local/images') or die($php_errormsg); while (false !== ($f = $d->read())) { // process file } $d->close(); Recipe 19.8 shows how to use opendir( ) or dir( ) to process each file in a directory. Making new directories is covered in Recipe 19.11 and removing directories in Recipe 19.12. The filesystem holds more than just files and directories. On Unix, it can also hold symbolic links. These are special files whose contents are a pointer to another file. You can delete the link without affecting the file it points to. To create a symbolic link, use symlink( ): symlink('/usr/local/images','/www/docroot/images') or die($php_errormsg); This creates a symbolic link called images in /www/docroot that points to /usr/local/images. To find information about a file, directory, or link you must examine its inode. The function stat( ) retrieves the metadata in an inode for you. Recipe 19.3 discusses stat( ). PHP also has many functions that use stat( ) internally to give you a specific piece of information about a file. These are listed in Table 19-1. Table 19-1. File information functions On Unix, the file permissions indicate what operations the file's owner, users in the file's group, and all users can perform on the file. The operations are reading, writing, and executing. For programs, executing means the ability to run the program; for directories, it's the ability to search through the directory and see the files in it. Unix permissions can also contain a setuid bit, a setgid bit, and a sticky bit. The setuid bit means that when a program is run, it runs with the user ID of its owner. The setgid bit means that a program runs with the group ID of its group. For a directory, the setgid bit means that new files in the directory are created by default in the same group as the directory. The sticky bit is useful for directories in which people share files because it prevents nonsuperusers with write permission in a directory from deleting files in that directory unless they own the file or the directory. When setting permissions with chmod( ) (see Recipe 19.4), they must be expressed as an octal number. This number has four digits. The first digit is any special setting for the file (such as setuid or setgid). The second digit is the user permissions — what the file's owner can do. The third digit is the group permissions — what users in the file's group can do. The fourth digit is the world permissions — what all other users can do. To compute the appropriate value for each digit, add together the permissions you want for that digit using the values in Table 19-2. For example, a permission value of 0644 means that there are no special settings (the 0), the file's owner can read and write the file (the 6, which is 4 (read) + 2 (write)), users in the file's group can read the file (the first 4), and all other users can also read the file (the second 4). A permission value of 4644 is the same, except that the file is also setuid. Table 19-2. File permission values The permissions of newly created files and directories are affected by a setting called the umask , which is a permission value that is removed, or masked out, from the initial permissions of a file (0666 or directory (0777). For example, if the umask is 0022, the default permissions for a new file created with touch( ) or fopen( ) are 0644 and the default permissions for a new directory created with mkdir( ) are 0755. You can get and set the umask with the function umask( ) . It returns the current umask and, if an argument is supplied to it, changes the umask to the value of that argument. For example, here's how to make the permissions on newly created files prevent anyone but the file's owner (and the superuser) from accessing the file: $old_umask = umask(0077); touch('secret-file.txt'); umask($old_umask); The first call to umask( ) masks out all permissions for group and world. After the file is created, the second call to umask( ) restores the umask to the previous setting. When PHP is run as a server module, it restores the umask to its default value at the end of each request. Like other permissions-related functions, umask( ) doesn't work on Windows. Getting and Setting File Timestamps Problem You want to know when a file was last accessed or changed, or you want to update a file's access or change time; for example, you want each page on your web site to display when it was last modified. Solution Discussion'])); See Also Documentation on fileatime( ) at, filemtime( ) at, and filectime( ) at. Getting File Information Problem You want to read a file's metadata; for example, permissions and ownership. Solution Use stat( ) , which returns an array of information about a file: $info = stat('harpo.php'); Discussion The function stat( ) returns an array with both numeric and string indexes with information about a file. The elements of this array are in Table 19-3. Table 19-3. Information returned by stat( ) The mode element of the returned array contains the permissions expressed as a base 10 integer. This is confusing since permissions are usually either expressed symbolically (e.g., ls's -rw-r--r-- output) or as an octal integer (e.g., 0644). To convert the permissions to a more understandable format, use base_convert( ) to change the permissions to octal: $file_info = stat('/tmp/session.txt'); $permissions = base_convert($file_info['mode'],10,8); This results in a six-digit octal number. For example, if ls displays the following about /tmp/session.txt: -rw-rw-r-- 1 sklar sklar 12 Oct 23 17:55 /tmp/session.txt Then $file_info['mode'] is 33204 and $permissions is 100664. The last three digits (664) are the user (read and write), group (read and write), and other (read) permissions for the file. The third digit, 0, means that the file is not setuid or setgid. The leftmost 10 means that the file is a regular file (and not a socket, symbolic link, or other special file). Because stat( ) returns an array with both numeric and string indexes, using foreach to iterate through the returned array produces two copies of each value. Instead, use a for loop from element 0 to element 12 of the returned array. Calling stat( ) on a symbolic link returns information about the file the symbolic link points to. To get information about the symbolic link itself, use lstat( ) . Similar to stat( ) is fstat( ) , which takes a file handle (returned from fopen( ) or popen( )) as an argument. You can use fstat( ) only on local files, however, not URLs passed to fopen( ). PHP's stat( ) function uses the underlying stat(2) system call, which is expensive. To minimize overhead, PHP caches the result of calling stat(2). So, if you call stat( ) on a file, change its permissions, and call stat( ) on the same file again, you get the same results. To force PHP to reload the file's metadata, call clearstatcache( ) , which flushes PHP's cached information. PHP also uses this cache for the other functions that return file metadata: file_exists( ), fileatime( ), filectime( ), filegroup( ), fileinode( ), filemtime( ), fileowner( ), fileperms( ), filesize( ), filetype( ), fstat( ), is_dir( ), is_executable( ), is_file( ), is_link( ), is_readable( ), is_writable( ), and lstat( ). See Also Documentation on stat( ) at, lstat( ) at, fstat( ) at, and clearstatcache( ) at. Changing File Permissions or Ownership Problem You want to change a file's permissions or ownership; for example, you want to prevent other users from being able to look at a file of sensitive data. Solution Use chmod( ) to change the permissions of a file: chmod('/home/user/secrets.txt',0400); Use chown( ) to change a file's owner and chgrp( ) to change a file's group: chown('/tmp/myfile.txt','sklar'); // specify user by name chgrp('/home/sklar/schedule.txt','soccer'); // specify group by name chown('/tmp/myfile.txt',5001); // specify user by uid chgrp('/home/sklar/schedule.txt',102); // specify group by gid Discussion The permissions passed to chmod( ) must be specified as an octal number. The superuser can change the permissions, owner, and group of any file. Other users are restricted. They can change only the permissions and group of files that they own, and can't change the owner at all. Nonsuperusers can also change only the group of a file to a group they belong to. The functions chmod( ), chgrp( ), and chown( ) don't work on Windows. See Also Documentation on chmod( ) at, chown( ) at, and chgrp( ) at. Splitting a Filename into Its Component Parts Problem You want to find a file's path and filename; for example, you want to create a file in the same directory as an existing file. Solution Use basename( ) to get the filename and dirname( ) to get the path: $full_name = '/usr/local/php/php.ini'; $base = basename($full_name); // $base is php.ini $dir = dirname($full_name); // $dir is /usr/local/php Use pathinfo( ) to get the directory name, base name, and extension in an associative array: $info = pathinfo('/usr/local/php/php.ini'); Discussion To create a temporary file in the same directory as an existing file, use dirname( ) to find the directory, and pass that directory to tempnam( ) : $dir = dirname($existing_file); $temp = tempnam($dir,'temp'); $temp_fh = fopen($temp,'w'); The elements in the associative array returned by pathinfo( ) are dirname, basename, and extension: $info = pathinfo('/usr/local/php/php.ini'); print_r($info); Array ( [dirname] => /usr/local/php [basename] => php.ini [extension] => ini ) You can also pass basename( ) an optional suffix to remove it from the filename. This sets $base to php: $base = basename('/usr/local/php/php.ini','.ini'); Using functions such as basename( ), dirname( ), and pathinfo( ) is more portable than just separating a full filename on / because they use an operating-system appropriate separator. On Windows, these functions treat both / and \ as file and directory separators. On other platforms, only / is used. There's no built-in PHP function to combine the parts produced by basename( ), dirname( ), and pathinfo( ) back into a full filename. To do this you have to combine the parts with . and /: $dirname = '/usr/local/php'; $basename = 'php'; $extension = 'ini'; $full_name = $dirname . '/' . $basename . '.' . $extension; You can pass a full filename produced like this to other PHP file functions on Windows, because PHP accepts / as a directory separator on Windows. See Also Documentation on basename( ) at, dirname( ) at, and pathinfo( ) at. Deleting a File Problem You want to delete a file. Solution Use unlink( ) : unlink($file) or die ("can't delete $file: $php_errormsg"); Discussion The function unlink( ) is only able to delete files that the user of the PHP process is able to delete. If you're having trouble getting unlink( ) to work, check the permissions on the file and how you're running PHP. See Also Documentation on unlink( ) at. Copying or Moving a File Problem You want to copy or move a file. Solution Use copy( ) to copy a file: copy($old,$new) or die("couldn't copy $old to $new: $php_errormsg"); Use rename( ) to move a file: rename($old,$new) or die("couldn't move $old to $new: $php_errormsg"); Discussion On Unix, rename( ) can't move files across filesystems. To do so, copy the file to the new location and then delete the old file: if (copy("/tmp/code.c","/usr/local/src/code.c")) { unlink("/tmp/code.c"); } If you have multiple files to copy or move, call copy( ) or rename( ) in a loop. You can operate only on one file each time you call these functions. See Also Documentation on copy( ) at and rename( ) at. Processing All Files in a Directory Recursively Problem You want to iterate over all files in a directory. For example, you want to create a select box in a form that lists all the files in a directory. Solution Get a directory handle with opendir( ) and then retrieve each filename with readdir( ): $d = opendir('/tmp') or die($php_errormsg); while (false !== ($f = readdir($d))) { print "$f\n"; } closedir($d); Discussion The code in the solution tests the return value of readdir( ) with the nonidentity operator (!==) so that the code works properly with filenames that evaluate to false, such as a file named 0. The function readdir( ) returns each entry in a directory, whether it is a file, directory, or something else (such as a link or a socket). This includes the metaentries "." (current directory) and ".." (parent directory). To just return files, use the is_file( ) function as well: print '<select name="files">'; $d = opendir('/usr/local/upload') or die($php_errormsg); while (false !== ($f = readdir($d))) { if (is_file("/usr/local/upload/$f")) { print '<option> ' . $f . '</option>'; } } closedir($d); print '</select>'; Because readdir( ) returns only the filename of each directory entry, not a full pathname, you have to prepend the directory name to $f before you pass it to is_file( ). PHP also has an object-oriented interface to directory information. The dir( ) function returns an object on which you can call read( ), rewind( ), and close( ) methods, which act like the readdir( ), rewinddir( ), and closedir( ) functions. There's also a $path property that contains the full path of the opened directory. Here's how to iterate through files with the object-oriented interface: print '<select name="files">'; $d = dir('/usr/local/upload') or die($php_errormsg); while (false !== ($f = $d->read())) { if (is_file($d->path.'/'.$f)) { print '<option> ' . $f . '</option>'; } } $d->close(); In this example, $d->path is /usr/local/upload. See Also Documentation on opendir( ) at, readdir( ) at, and the directory class at. Getting a List of Filenames Matching a Pattern Problem You want to find all filenames that match a pattern. Solution If your pattern is a regular expression, read each file from the directory and test the name with preg_match( ) : $d = dir('/tmp') or die($php_errormsg); while (false !== ($f = $d->read())) { // only match alphabetic names if (preg_match('/^[a-zA-Z]+$/',$f)) { print "$f\n"; } } $d->close(); Discussion If your pattern is a shell glob (e.g., *.*), use the backtick operator with ls (Unix) or dir (Windows) to get the matching filenames. For Unix: $files = explode("\n",`ls -1 *.gif`); foreach ($files as $file) { print "$b\n"; } For Windows: $files = explode("\n",`dir /b *.gif`); foreach ($files as $file) { print "$b\n"; } See Also Recipe 19.8 details on iterating through each file in a directory; information about shell pattern matching is available at. Processing All Files in a Directory Problem You want to do something to all the files in a directory and in any subdirectories. Solution Use the pc_process_dir( ) function, shown in Example 19-1, which returns a list of all files in and beneath a given directory. Example 19-1. pc_process_dir( ) function pc_process_dir($dir { array_push($files,"$dir_name/$f"); } } $d->close(); foreach ($subdirectories as $subdirectory) { $files = array_merge($files,pc_process_dir($subdirectory,$max_depth,$depth+1)); } } return $files; } Discussion Here's an example: if /tmp contains the files a and b, as well as the directory c, and /tmp/c contains files d and e, pc_process_dir('/tmp') returns an array with elements /tmp/a, /tmp/b, /tmp/c/d, and /tmp/c/e. To perform an operation on each file, iterate through the array: $files = pc_process_dir('/tmp'); foreach ($files as $file) { print "$file was last accessed at ".strftime('%c',fileatime($file))."\n"; } Instead of returning an array of files, you can also write a function that processes them as it finds them. The pc_process_dir2( ) function, shown in Example 19-2, does this by taking an additional argument, the name of the function to call on each file found. Example 19-2. pc_process_dir2( ) function pc_process_dir2($dir_name,$func { $func_name("$dir_name/$f"); } } $d->close(); foreach ($subdirectories as $subdirectory) { pc_process_dir2($subdirectory,$func_name,$max_depth,$depth+1); } } } The pc_process_dir2( ) function doesn't return a list of directories; instead, the function $func_name is called with the file as its argument. Here's how to print out the last access times: function printatime($file) { print "$file was last accessed at ".strftime('%c',fileatime($file))."\n"; } pc_process_dir2('/tmp','printatime'); Although the two functions produce the same results, the second version uses less memory because potentially large arrays of files aren't passed around. The pc_process_dir( ) and pc_process_dir2( ) functions use a breadth-first search . In this type of search, the functions handle all the files in the current directory; then they recurse into each subdirectory. In a depth-first search , they recurse into a subdirectory as soon as the subdirectory is found, whether or not there are files remaining in the current directory. The breadth-first search is more memory efficient; each pointer to the current directory is closed (with $d->close( )) before the function recurses into subdirectories, so there's only one directory pointer open at a time. Because is_dir( ) returns true when passed a symbolic link that points to a directory, both versions of the function follow symbolic links as they traverse down the directory tree. If you don't want to follow links, change the line: if (is_dir("$dir_name/$f")) { to: if (is_dir("$dir_name/$f") && (! is_link("$dir_name/$f"))) { See Also Recipe 6.10 for a discussion of variable functions; documentation on is_dir( ) at and is_link( ) at. Making New Directories Problem You want to create a directory. Solution Use mkdir( ) : mkdir('/tmp/apples',0777) or die($php_errormsg); Discussion The second argument to mkdir( ) is the permission mode for the new directory, which must be an octal number. The current umask is taken away from this permission value to create the permissions for the new directory. So, if the current umask is 0002, calling mkdir('/tmp/apples',0777) sets the permissions on the resulting directory to 0775 (user and group can read, write, and execute; others can only read and execute). PHP's built-in mkdir( ) can make a directory only if its parent exists. For example, if /tmp/a doesn't exist, you can't create /tmp/a/b until /tmp/a is created. To create a directory and its parents, you have two choices: you can call your system's mkdir program, or you can use the pc_mkdir_parents( ) function, shown in Example 19-3. To use your system's mkdir program, on Unix, use this: system('/bin/mkdir -p '.escapeshellarg($directory)); On Windows do: system('mkdir '.escapeshellarg($directory)); You can also use the pc_mkdir_parents( ) function shown in Example 19-3. Example 19-3. pc_mkdir_parents( ) function pc_mkdir_parents($d,$umask = 0777) { $dirs = array($d); $d = dirname($d); $last_dirname = ''; while($last_dirname != $d) { array_unshift($dirs,$d); $last_dirname = $d; $d = dirname($d); } foreach ($dirs as $dir) { if (! file_exists($dir)) { if (! mkdir($dir,$umask)) { error_log("Can't make directory: $dir"); return false; } } elseif (! is_dir($dir)) { error_log("$dir is not a directory"); return false; } } return true; } For example: pc_mkdir_parents('/usr/local/upload/test',0777); See Also Documentation on mkdir( ) at; your system's mkdir documentation, such as the Unix mkdir(1) man page or the Windows mkdir /? help text. Removing a Directory and Its Contents Problem You want to remove a directory and all of its contents, including subdirectories and their contents. Solution On Unix, use rm: $directory = escapeshellarg($directory); exec("rm -rf $directory"); On Windows, use rmdir: $directory = escapeshellarg($directory); exec("rmdir /s /q $directory"); Discussion Removing files, obviously, can be dangerous. Be sure to escape $directory with escapeshellarg( ) so that you don't delete unintended files. Because PHP's built-in directory removal function, rmdir( ) , works only on empty directories, and unlink( ) can't accept shell wildcards, calling a system program is much easier than recursively looping through all files in a directory, removing them, and then removing each directory. If an external utility isn't available, however, you can modify the pc_process_dir( ) function from Recipe 19.10 to remove each subdirectory. See Also Documentation on rmdir( ) at; your system's rm or rmdir documentation, such as the Unix rm(1) manpage or the Windows rmdir /? help text. Program: Web Server Directory Listing The web-ls.php program shown in Example 19-4 provides a view of the files inside your web server's document root, formatted like the output of the Unix command ls. Filenames are linked so that you can download each file, and directory names are linked so that you can browse in each directory, as shown in Figure 19-1. Most lines in Example 19-4 are devoted to building an easy-to-read representation of the file's permissions, but the guts of the program are in the while loop at the end. The $d->read( ) method gets the name of each file in the directory. Then, lstat( ) retrieves information about that file, and printf( ) prints out the formatted information about that file. The mode_string( ) functions and the constants it uses turn the octal representation of a file's mode (e.g., 35316) into an easier-to-read string (e.g., -rwsrw-r--). Example 19-4. web-ls.php /* Bit masks for determining file permissions and type. The names and values * listed below are POSIX-compliant, individual systems may have their own * extensions. */ define('S_IFMT',0170000); // mask for all types define('S_IFSOCK',0140000); // type: socket define('S_IFLNK',0120000); // type: symbolic link define('S_IFREG',0100000); // type: regular file define('S_IFBLK',0060000); // type: block device define('S_IFDIR',0040000); // type: directory define('S_IFCHR',0020000); // type: character device define('S_IFIFO',0010000); // type: fifo define('S_ISUID',0004000); // set-uid bit define('S_ISGID',0002000); // set-gid bit define('S_ISVTX',0001000); // sticky bit define('S_IRWXU',00700); // mask for owner permissions define('S_IRUSR',00400); // owner: read permission define('S_IWUSR',00200); // owner: write permission define('S_IXUSR',00100); // owner: execute permission define('S_IRWXG',00070); // mask for group permissions define('S_IRGRP',00040); // group: read permission define('S_IWGRP',00020); // group: write permission define('S_IXGRP',00010); // group: execute permission define('S_IRWXO',00007); // mask for others permissions define('S_IROTH',00004); // others: read permission define('S_IWOTH',00002); // others: write permission define('S_IXOTH',00001); // others: execute permission /* mode_string() is a helper function that takes an octal mode and returns * a ten character string representing the file type and permissions that * correspond to the octal mode. This is a PHP version of the mode_string() * function in the GNU fileutils package. */ function mode_string($mode) { $s = array(); // set type letter if (($mode & S_IFMT) == S_IFBLK) { $s[0] = 'b'; } elseif (($mode & S_IFMT) == S_IFCHR) { $s[0] = 'c'; } elseif (($mode & S_IFMT) == S_IFDIR) { $s[0] = 'd'; } elseif (($mode & S_IFMT) == S_IFREG) { $s[0] = '-'; } elseif (($mode & S_IFMT) == S_IFIFO) { $s[0] = 'p'; } elseif (($mode & S_IFMT) == S_IFLNK) { $s[0] = 'l'; } elseif (($mode & S_IFMT) == S_IFSOCK) { $s[0] = 's'; } // set user permissions $s[1] = $mode & S_IRUSR ? 'r' : '-'; $s[2] = $mode & S_IWUSR ? 'w' : '-'; $s[3] = $mode & S_IXUSR ? 'x' : '-'; // set group permissions $s[4] = $mode & S_IRGRP ? 'r' : '-'; $s[5] = $mode & S_IWGRP ? 'w' : '-'; $s[6] = $mode & S_IXGRP ? 'x' : '-'; // set other permissions $s[7] = $mode & S_IROTH ? 'r' : '-'; $s[8] = $mode & S_IWOTH ? 'w' : '-'; $s[9] = $mode & S_IXOTH ? 'x' : '-'; // adjust execute letters for set-uid, set-gid, and sticky if ($mode & S_ISUID) { if ($s[3] != 'x') { // set-uid but not executable by owner $s[3] = 'S'; } else { $s[3] = 's'; } } if ($mode & S_ISGID) { if ($s[6] != 'x') { // set-gid but not executable by group $s[6] = 'S'; } else { $s[6] = 's'; } } if ($mode & S_ISVTX) { if ($s[9] != 'x') { // sticky but not executable by others $s[9] = 'T'; } else { $s[9] = 't'; } } // return formatted string return join('',$s); } // Start at the document root if not specified if (isset($_REQUEST['dir'])) { $dir = $_REQUEST['dir']; } else { $dir = ''; } // locate $dir in the filesystem $real_dir = realpath($_SERVER['DOCUMENT_ROOT'].$dir); // make sure $real_dir is inside document root if (! preg_match('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/', $real_dir)) { die("$dir is not inside the document root"); } // canonicalize $dir by removing the document root from its beginning $dir = substr_replace($real_dir,'',0,strlen($_SERVER['DOCUMENT_ROOT'])); // are we opening a directory? if (! is_dir($real_dir)) { die("$real_dir is not a directory"); } // open the specified directory $d = dir($real_dir) or die("can't open $real_dir: $php_errormsg"); print '<table>'; // read each entry in the directory while (false !== ($f = $d->read())) { // get information about this file $s = lstat($d->path.'/'.$f); // translate uid into user name $user_info = posix_getpwuid($s['uid']); // translate gid into group name $group_info = posix_getgrgid($s['gid']); // format the date for readability $date = strftime('%b %e %H:%M',$s['mtime']); // translate the octal mode into a readable string $mode = mode_string($s['mode']); $mode_type = substr($mode,0,1); if (($mode_type == 'c') || ($mode_type == 'b')) { /* if it's a block or character device, print out the major and * minor device type instead of the file size */ $major = ($s['rdev'] >> 8) & 0xff; $minor = $s['rdev'] & 0xff; $size = sprintf('%3u, %3u',$major,$minor); } else { $size = $s['size']; } // format the <a href=""> around the filename // no link for the current directory if ('.' == $f) { $href = $f; } else { // don't include the ".." in the parent directory link if ('..' == $f) { $href = urlencode(dirname($dir)); } else { $href = urlencode($dir) . '/' . urlencode($f); } /* everything but "/" should be urlencoded */ $href = str_replace('%2F','/',$href); // browse other directories with web-ls if (is_dir(realpath($d->path . '/' . $f))) { $href = sprintf('<a href="%s?dir=%s">%s</a>', $_SERVER['PHP_SELF'],$href,$f); } else { // link to files to download them $href= sprintf('<a href="%s">%s</a>',$href,$f); } // if it's a link, show the link target, too if ('l' == $mode_type) { $href .= ' -> ' . readlink($d->path.'/'.$f); } } // print out the appropriate info for this file printf('<tr><td>%s</td><td>%3u</td><td align="right">%s</td> <td align="right">%s</td><td align="right">%s</td> <td align="right">%s</td><td>%s</td></tr>', $mode, // formatted mode string $s['nlink'], // number of links to this file $user_info['name'], // owner's user name $group_info['name'], // group name $size, // file size (or device numbers) $date, // last modified date and time $href); // link to browse or download } print '</table>'; Program: Site Search You can use site-search.php, shown in Example 19-5, as a search engine for a small-to-medium size, file-based site. The program looks for a search term (in $_REQUEST['term']) in all files within a specified set of directories under the document root. Those directories are set in $search_dirs. It also recurses into subdirectories and follows symbolic links but keeps track of which files and directories it has seen so that it doesn't get caught in an endless loop. If any pages are found that contain the search term, it prints list of links to those pages, alphabetically ordered by each page's title. If a page doesn't have a title (between the <title> and </title> tags), the page's relative URI from the document root is used. The program looks for the search term between the <body> and </body> tags in each file. If you have a lot of text in your pages inside <body> tags that you want to exclude from the search, surround the text that should be searched with specific HTML comments and then modify $body_regex to look for those tags instead. Say, for example, if your page looks like this: <body> // Some HTML for menus, headers, etc. <!-- search-start --> <h1>Aliens Invade Earth</h1> <h3>by H.G. Wells</h3> <p>Aliens invaded earth today. Uh Oh.</p> // More of the story <!-- search-end --> // Some HTML for footers, etc. </body> To match the search term against just the title, author, and story inside the HTML comments, change $body_regex to: $body_regex = '#<!-- search-start -->(.*' . preg_quote($_REQUEST['term'],'#'). '.*)<!-- search-end -->#Sis'; If you don't want the search term to match text that's inside HTML or PHP tags in your pages, add a call to strip_tags( ) to the code that loads the contents of the file for searching: // load the contents of the file into $file $file = strip_tags(join('',file($path))); Example 19-5. site-search.php function pc_search_dir($dir) { global $body_regex,$title_regex,$seen; // array to hold pages that match $pages = array(); // array to hold directories to recurse into $dirs = array(); // mark this directory as seen so we don't look in it again $seen[realpath($dir)] = true; // if we can get a directory handle for this directory if (is_readable($dir) && ($d = dir($dir))) { // get each file name in the directory while (false !== ($f = $d->read())) { // build the full path of the file $path = $d->path.'/'.$f; // if it's a regular file and we can read it if (is_file($path) && is_readable($path)) { $realpath = realpath($path); // if we've seen this file already, if ($seen[$realpath]) { // then skip it continue; } else { // otherwise, mark it as seen so we skip it // if we come to it again $seen[$realpath] = true; } // load the contents of the file into $file $file = join('',file($path)); // if the search term is inside the body delimiters if (preg_match($body_regex,$file)) { // construct the relative URI of the file by removing // the document root from the full path $uri = substr_replace($path,'',0,strlen($_SERVER['DOCUMENT_ROOT'])); // If the page has a title, find it if (preg_match('#<title>(.*?)</title>#Sis',$file,$match)) { // and add the title and URI to $pages array_push($pages,array($uri,$match[1])); } else { // otherwise use the URI as the title array_push($pages,array($uri,$uri)); } } } else { // if the directory entry is a valid subdirectory if (is_dir($path) && ('.' != $f) && ('..' != $f)) { // add it to the list of directories to recurse into array_push($dirs,$path); } } } $d->close(); } /* look through each file in each subdirectory of this one, and add the matching pages in those directories to $pages. only look in a subdirectory if we haven't seen it yet. */ foreach ($dirs as $subdir) { $realdir = realpath($subdir); if (! $seen[$realdir]) { $seen[$realdir] = true; $pages = array_merge($pages,pc_search_dir($subdir)); } } return $pages; } // helper function to sort matched pages alphabetically by title function pc_page_sort($a,$b) { if ($a[1] == $b[1]) { return strcmp($a[0],$b[0]); } else { return ($a[1] > $b[1]); } } // array to hold the pages that match the search term $matching_pages = array(); // array to hold pages seen while scanning for the search term $seen = array(); // directories underneath the document root to search $search_dirs = array('sports','movies','food'); // regular expression to use in searching files. The "S" pattern // modifier tells the PCRE engine to "study" the regex for greater // efficiency. $body_regex = '#<body>(.*' . preg_quote($_REQUEST['term'],'#'). '.*)</body>#Sis'; // add the files that match in each directory to $matching pages foreach ($search_dirs as $dir) { $matching_pages = array_merge($matching_pages, pc_search_dir($_SERVER['DOCUMENT_ROOT'].'/'.$dir)); } if (count($matching_pages)) { // sort the matching pages by title usort($matching_pages,'pc_page_sort'); print '<ul>'; // print out each title with a link to the page foreach ($matching_pages as $k => $v) { print sprintf('<li> <a href="%s">%s</a>',$v[0],$v[1]); } print '</ul>'; } else { print 'No pages found.'; }
http://commons.oreilly.com/wiki/index.php?title=PHP_Cookbook/Directories&oldid=7331
CC-MAIN-2017-34
refinedweb
5,314
52.6
If you’ve ever wanted to draw fractals in C, here’s some code for you. These come from Misha on his(her?) GitHub page. There are three as you can see. Each has their own program – barnsley.c, sierpinski.c and y-fractal.c. All three programs create an SDL2 window then display the image. Note that this was coded for Linux. I modified the programs so they would run on Windows and the screenshot was done from my machine. I know these images are on the GitHub page. If you want to compile and run, then on all three programs change the SDL include from #include <SDL2/SDL.h> to #include "SDL.h" Also with the barnsley.c you need to give initial values to mx and my in the renderFractals() function (lines 88 and 89) and change these two lines: (114 and 115). No other changes are needed to let them compile. mx_c = mx - win_w / 2; my_c = my - win_h / 2;to mx_c = mx - WIDTH / 2; my_c = my - HEIGHT / 2;
https://learncgames.com/some-pretty-fractals-in-c-sdl2/
CC-MAIN-2021-43
refinedweb
172
85.99
#include <Wt/WCalendar.h> A calendar.t::WDate class. Usage example: Here is a snapshot, taken on 19/01/2010 (shown as today), and 14/01/2010 currently selected. Creates a new calendar. Constructs a new calendar with English day/month names. The calendar shows the current day, and has an empty selection. Signal emitted when the user double-clicks a date. You may want to connect to this signal to treat a double click as the selection of a date. Browses to a date. Displays the month which contains the given date. This does not change the current selection. This will emit the currentPageChanged() signal if another month is displayed. Browses to the next month. Displays the next month. This does not change the current selection. This will emit the currentPageChanged() singal. Browses to the same month in the next year. Displays the same month in the next year. This does not change the current selection. This will emit the currentPageChanged() singal. Browses to the previous month. Displays the previous month. This does not affect the selection. This will emit the currentPageChanged() singal. Browses to the same month in the previous year. Displays the same month in the previous year. This does not affect the selection. This will emit the currentPageChanged() singal. Clears the current selection. Clears the current selection. Will result in a selection() that is empty(). Signal emitted when the user clicks a date. You may want to connect to this signal if you want to provide a custom selection handling. Returns the current month displayed. Returns the month (1-12) that is currently displayed. Signal emitted when the current month is changed. The method is emitted both when the change is done through the user interface or via the public API. The two parameters are respectively the new year and month. Returns the current year displayed. Returns the year that is currently displayed. horizontal header format. Returns whether a date is selected. This is a convenience method that can be used when reimplementing renderCell().. Creates or updates a widget that renders a cell. The default implementation creates a WText You may want to reimplement this method if you wish to customize how a cell is rendered. When widget is 0, a new widget should be created and returned. Otherwise, you may either modify the passed widget, or return a new widget. If you return a new widget, the prevoius widget will be deleted. Selects a date. Select one date. Both in single or multiple selection mode, this results in a selection() that contains exactly one date. Selects multiple dates. Select multiple dates. In multiple selection mode, this results in a selection() that contains exactly the given dates. In single selection mode, at most one date is set. Returns the current selection. Returns the set of dates currently selected. In single selection mode, this set contains 0 or 1 dates. Signal emitted when the user changes the selection. Emitted after the user has changed the current selection. Sets the bottom of the valid date range. The default is a null date constructed using WDate(). Sets the first day of the week. Possible values are 1 to 7. The default value is 1 ("Monday"). Sets the horizontal header format. The default horizontal header format is CalendarHeaderFormat::ShortDayNames. Sets the selection mode. The default selection mode is SingleSelection. Configures the calendar to use single click for activation. By default, double click will trigger activate(). Use this method if you want a single click to trigger activate() (and the now deprecated selected() method). This only applies to a single-selection calendar. If selectionMode() is set to SingleSelection, this will cause the selection to change on a single click instead of a double click. Instead of enabling single click, you can also listen to the clicked() signal to process a single click. Sets the top of the valid date range. The default is a null date constructed using WDate().
https://webtoolkit.eu/wt/doc/reference/html/classWt_1_1WCalendar.html
CC-MAIN-2021-31
refinedweb
658
71.31
by Bob In the first and second parts of this series I introduced the Command-Handler [] and Unit of Work and Repository [] patterns. I was intending to write about Message Buses, and some more stuff about domain modelling, but I need to quickly skim over this first. If you’ve just started reading the Message Buses piece, and you’re here to learn about Application-Controlled Identifiers, you’ll find those at the end of post, after a bunch of stuff about ORMs, CQRS, and some casual trolling of junior programmers. What is CQS ? The Command Query Separation [] principle was first described by Bertrand Meyer in the late Eighties. Per wikipedia [], the principle states:. Referential transparency is an important concept from functional programming. Briefly, a function is referentially transparent if you could replace it with a static value. class LightSwitch: def toggle_light(self): self.light_is_on = not self.light_is_on return self.light_is_on @property def is_on(self): return self.light_is_on In this class, the is_on method is referentially transparent - I can replace it with the value True or False without any loss of functionality, but the method toggle_light is side-effectual: replacing its calls with a static value would break the contracts of the system. To comply with the Command-Query separation principle, we should not return a value from our toggle_light method. In some languages we would say that the is_on method is “pure”. The advantage of splitting our functions into those that have side effects and those that are pure is that the code becomes easier to reason about. Haskell loves pure functions, and uses this reasonability to do strange things, like re-ordering your code for you at compilation time to make it more efficient. For those of us who work in more prosaic languages, if commands and queries are clearly distinguished, then I can read through a code base and understand all the ways in which state can change. This is a huge win for debugging because there is nothing worse than troubleshooting a system when you can’t work out which code-paths are changing your data. How do we get data out of a Command-Handler architecture? When we’re working in a Command-Handler system we obviously use Commands and Handlers to perform state changes, but what should we do when we want to get data back out of our model? What is the equivalent port for queries? The answer is “it depends”. The lowest-cost option is just to re-use your repositories in your UI entrypoints. @app.route(“/issues”) def list_issues(): with unit_of_work_manager.start() as unit_of_work: open_issues = unit_of_work.issues.find_by_status(‘open’) return json.dumps(open_issues) This is totally fine unless you have complex formatting, or multiple entrypoints to your system. The problem with using your repositories directly in this way is that it’s a slippery slope. Sooner or later you’re going to have a tight deadline, and a simple requirement, and the temptation is to skip all the command/handler nonsense and do it directly in the web api. @app.route(‘/issues/ Super convenient, but then you need to add some error handling and some logging and an email notification. @app.route(‘/issues/ with unit_of_work_manager.start() as uow: issue = uow.issues[issue_id] if issue is None: logging.warn("Issue not found") flask.abort(404) if issue.status != 'deleted': issue.delete() uow.commit() try: smtp.send_notification(Issue.Deleted, issue_id) except: logging.error( "Failed to send email notification for deleted issue " + str(issue_id), exn_info=True) else: logging.info("Issue already deleted. NOOP") return "Deleted!", 202 Aaaaand, we’re back to where we started: business logic mixed with glue code, and the whole mess slowly congealing in our web controllers. Of course, the slippery slope argument isn’t a good reason not to do something, so if your queries are very simple, and you can avoid the temptation to do updates from your controllers, then you might as well go ahead and read from repositories, it’s all good, you have my blessing. If you want to avoid this, because your reads are complex, or because you’re trying to stay pure, then instead we could define our views explicitly. class OpenIssuesList: def __init__(self, sessionmaker): self.sessionmaker = sessionmaker def fetch(self): with self.sessionmaker() as session: result = session.execute( 'SELECT reporter_name, timestamp, title FROM issues WHERE state="open"') return [dict(r) for r in result.fetchall()] @api.route(‘/issues/’) def list_issues(): view_builder = OpenIssuesList(session_maker) return jsonify(view_builder.fetch()) This is my favourite part of teaching ports and adapters to junior programmers, because the conversation inevitably goes like this: smooth-faced youngling: Wow, um… are you - are we just going to hardcode that sql in there? Just … run it on the database? grizzled old architect: Yeah, I think so. Do The Simplest Thing That Could Possibly Work, right? YOLO, and so forth. sfy: Oh, okay. Um… but what about the unit of work and the domain model and the service layer and the hexagonal stuff? Didn’t you say that “Data access ought to be performed against the aggregate root for the use case, so that we maintain tight control of transactional boundaries”? goa: Ehhhh… I don’t feel like doing that right now, I think I’m getting hungry. sfy: Right, right … but what if your database schema changes? goa: I guess I’ll just come back and change that one line of SQL. My acceptance tests will fail if I forget, so I can’t get the code through CI. sfy: But why don’t we use the Issue model we wrote? It seems weird to just ignore it and return this dict… and you said “Avoid taking a dependency directly on frameworks. Work against an abstraction so that if your dependency changes, that doesn’t force change to ripple through your domain”. You know we can’t unit test this, right? goa: Ha! What are you, some kind of architecture astronaut? Domain models! Who needs ‘em. Why have a separate read-model? In my experience, there are two ways that teams go wrong when using ORMs. The most common mistake is not paying enough attention to the boundaries of their use cases. This leads to the application making far too many calls to the database because people write code like this: notification = task.as_notification() for assignee in task.assignees: assignee.manager.notifications.add(notification) assignee.notifications.add(notification) assignee.queues.inbox.add(task) ORMs make it very easy to “dot” through the object model this way, and pretend that we have our data in memory, but this quickly leads to performance issues when the ORM generates hundreds of select statements in response. Then they get all angry about performance and write long blog posts about how ORM sucks and is an anti-pattern and only n00bs like it. This is akin to blaming OO for your domain logic ending up in the controller. The second mistake that teams make is using an ORM when they don’t need to. Why do we use an ORM in the first place? I think that a good ORM gives us two things: Taken together, these patterns help us to write rich domain models by removing all the database cruft so we can focus on our use-cases. This allows us to model complex business processes in an internally consistent way. When I’m writing a GET method, though, I don’t care about any of that. My view doesn’t need any business logic, because it doesn’t change any state. For 99.5% of use cases, it doesn’t even matter if my data are fetched inside a transaction. If I perform a dirty read when listing the issues, one of three things might happen: In many systems all these occurrences are unlikely, and will be resolved by a page refresh or following a link to view more data. To be clear, I’m not recommending that you turn off transactions for your SELECT statements, just noting that transactional consistency is usually only a real requirement when we are changing state. When viewing state, we can almost always accept a weaker consistency model. CQRS is CQS at a system-level CQRS stands for Command-Query Responsibility Segregation, and it’s an architectural pattern that was popularised by Greg Young. A lot of people misunderstand CQRS, and think you need to use separate databases and crazy asynchronous processors to make it work. You can do these things, and I want to write more about that later, but CQRS just means that we separate the Write Model - what we normally think of as the domain model - and the Read Model - a lightweight, simple model for showing on the UI, or answering questions about the domain state. When I’m serving a write request (a command), my job is to protect the invariants of the system, and model the business process as it appears in the minds of our domain experts. I take the collective understanding of our business analysts, and turn it into a state machine that makes useful work happen. When I’m serving a read request (a query), my job is to get the data out of the database as fast as possible and onto a screen so the user can view it. Anything that gets in the way of my doing that is bloat. This isn’t a new idea, or particularly controversial. We’ve all tried writing reports against an ORM, or complex hierarchical listing pages, and hit performance barriers. When we get to that point, the only thing we can do - short of rewriting the whole model, or abandoning our use of an ORM - is to rewrite our queries in raw SQL. Once upon a time I’d feel bad for doing this, as though I were cheating, but nowadays I just recognise that the requirements for my queries are fundamentally different than the requirements for my commands. For the write-side of the system, use an ORM, for the read side, use whatever is a) fast, and b) convenient. Application Controlled Identifiers At this point, a non-junior programmer will say Okay, Mr Smarty-pants Architect, if our commands can’t return any values, and our domain models don’t know anything about the database, then how do I get an ID back from my save method? Let’s say I create an API for creating new issues, and when I have POSTed the new issue, I want to redirect the user to an endpoint where they can GET their new Issue. How can I get the id back? The way I would recommend you handle this is simple - instead of letting your database choose ids for you, just choose them yourself. @api.route(‘/issues’, methods=[‘POST’]) def report_issue(self): # uuids make great domain-controlled identifiers, because # they can be shared amongst several systems and are easy # to generate. issue_id = uuid.uuid4() cmd = ReportIssueCommand(issue_id, **request.get_json()) handler.handle(cmd) return "", 201, { 'Location': '/issues/' + str(issue_id) } There’s a few ways to do this, the most common is just to use a UUID, but you can also implement something like hi-lo []. In the new code sample [] , I’ve implemented three flask endpoints, one to create a new issue, one to list all issues, and one to view a single issue. I’m using UUIDs as my identifiers, but I’m still using an integer primary key on the issues table, because using a GUID in a clustered index leads to table fragmentation and sadness [] . Okay, quick spot-check - how are we shaping up against our original Ports and Adapters diagram? How do the concepts map? Pretty well! Our domain is pure and doesn’t know anything about infrastructure or IO. We have a command and a handler that orchestrate a use-case, and we can drive our application from tests or Flask. Most importantly, the layers on the outside depend on the layers toward the centre. Next time I’ll get back to talking about message buses.tags: python - architecture
https://io.made.com/blog/2017-09-13-commands-and-queries-handlers-and-views.html
CC-MAIN-2021-49
refinedweb
2,012
63.09
I am learning scientific computing with python. In the exercise, I am supposed to generate a polynomial by using its roots with this formula: Here is my implementation: def poly(x,roots): #Pass real and/or complex roots x = symbols(x) f = 1 for r in roots: f = f*(x - r) return expand(f) from sympy import expand poly('x',[(-1/2), 5, (21/5), (-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)]) x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0 10*x**5 - 17.0*x**4 - 505.0*x**3 + 1775.0*x**2 - 248.999999999999*x - 630.0 f = 10 While 10x**5 + ... is correct, that is 10 * p(x), which isn't really what is needed. The answer you are getting is fine right now as well and you can test that as for each r in roots, p(r) is 0.
https://codedump.io/share/WH9ib6YPDD7O/1/python-my-polynomial-coefficients-are-off-by-a-factor-of-10
CC-MAIN-2017-17
refinedweb
161
77.87
On Mon, Oct 17, 2016 at 10:33:32PM +0200, Sven R. Kunze wrote: Sorry? You know, I am all for real-world code and I also delivered: Your example shows the proposed: [*. If I were doing this more than once, I'd be strongly inclined to invest in a simple helper function to make this more readable: def filter_and_flatten(language, fulltext): for lang, text in fulltext: if lang == language: yield lang yield text filter_and_flatten('english', fulltext_tuples) In some ways, list comprehensions are a trap: their convenience and ease of use for the easy cases lure us into using them when we ought to be using a generator. But that's just my opinion.
https://mail.python.org/archives/list/python-ideas@python.org/message/2PZHYDHODUCGQJADPSFXQ4TDOJIDMMWM/
CC-MAIN-2021-21
refinedweb
114
66.67
A Unity ID allows you to buy and/or subscribe to Unity products and services, shop in the Asset Store and participate in the Unity community. is there any way to mitigate the download time? Other than switching to sp_human_face_68_for_mobile. Hi, I'm having an issue where the webgl build takes too long to start the camera. Any ideia what could be causing it? It seems like it's... Are there plans for webgl support with AR Foundation? I made a button inside a custom inspector. [CustomEditor(typeof(MyScript))] public class MyScriptEditor : Editor { public... Thanks! I managed to find and destroy this hidden gameobject. Selection.activeGameObject = GameObject.Find("SceneIDMap");... same here, is there any solution? It works in 2018.1. Thanks!
https://forum.unity.com/search/116299889/
CC-MAIN-2019-47
refinedweb
121
62.04
In some recent discussion on Reddit, I claimed that, for cases where I’m already using flake8, it seemed as though 95% of Pylint’s reported problems were false positives. Others had very different experiences, so I was intrigued enough to actually do some measurements. Contents TL;DR If you’re in a rush, see the Running total section which summarises the Good/Neutral/Bad in what Pylint complained about, in my judgement. The setup I took part of the code from a side project where I don’t use Pylint, ran Pylint (with some very basic tuning) and tried to analyse the result in terms of helpful warnings compared to false positives etc. To give some background about the project: - It’s a fairly typical Django app, which means it is a fairly typical Python app — Django has some of its own idiosyncrasies, and as a framework rather than just a library it imposes some additional constraints, but it tries to make your code normal Python, and has been getting better at that in recent years. Some of the “framework-y” problems it brings will apply to many other libraries that use any framework-like patterns (such as callbacks or the template method design pattern). - It has about 22,000 lines of Python, but I only ran the Pylint on just under half of this, 11,000, or about 9000 without spaces. That half did include more than its fair share of view code and test code. - I do use flake8 already on this project, and keep errors to zero. The point of this experiment was for me to assess the benefit of Pylint given that I’m already using flake8. - The project has decent test coverage, but as I’m the only developer it has never had the benefit of peer code review. Hopefully this analysis will be useful to other people in assessing whether to add Pylint to their stack of code quality checks. I’m assuming that if you use something like Pylint, you will generally use it systematically as part of required code quality checks, keeping issues to zero. (Otherwise you will have an ever growing list of issues, won’t take it seriously and won’t spot new problems, defeating any usefulness it might have had.) Overall, Pylint had 1650 complaints about the code I ran it against. Below is my breakdown of that number. More details for all of the error messages can be found in Pylint’s feature list. Bugs Pylint found 1 bug in my code. By ‘bug’, I’m including only things that have observably bad behaviour at runtime, at least potentially. In this case, it was an overly broad except clause — broad-except as Pylint calls it. To be specific it was except Exception, not a ‘bare except’ because flake8 already catches those. This would have caused wrong behaviour in the presence of certain kinds of runtime exceptions. If this bug was ever triggered at runtime (and I don’t have evidence that is has been) in this case the resulting bad behaviour would likely have been trivial to non-existent in terms of consequences, but it could have been worse. TOTAL: 1 Helpful In addition to this one bug, there were other issues that I’ve classified as ‘helpful’ — Pylint found genuine issues with my code, which, while they were not causing immediate runtime problems, could cause problems in terms of future bugs or maintenance issues. 7 of these were too-many-locals / too-many-branches / too-many-local-variables that together related to 3 parts of my code that were badly structured. A better structure is not immediately obvious, but I’m sure I could do better than what is there. The remainder were: - unused-argument × 3 — one of which was an actual mistake compared to what I thought I’d done, where the code only did the right thing by accident, and 2 of which were (unused and unnecessary) keyword args that would have caused problems in the future if I’d tried to use them. - redefined-builtin × 2 - dangerous-default-value × 2 — these weren’t bugs in my usage because I never used the default, but good to get them fixed. - stop-iteration-return × 1 — I learnt something I probably would not have found out otherwise here. - no-self-argument × 1 TOTAL: 16 Cosmetic These are things I considered to be very minor issues that were not causing problems and were unlikely to do so, but on the other hand fixing them certainly wouldn’t hurt. Some of them are debatable stylistic things. Some of them I put in this category while similar errors were in other categories, because of differences in context which made a difference in my judgement. If I was using Pylint, I would fix these issues to keep it happy, but in most cases probably wouldn’t bother otherwise. invalid-name × 192 These were mostly one letter variables, in contexts where they were mostly harmless e.g. for f in glob.glob("some_directory/*.tmp"): os.unlink(f) Or for k in keys: ... Many were in test code. len-as-condition × 20 useless-object-inheritance × 16 (Python 2 leftovers) no-else-return × 11 no-else-raise × 1 bad-continuation × 6 redefined-builtin × 4 inconsistent-return-statements × 1 consider-using-set-comprehension × 1 chained-comparison × 1 TOTAL: 252 Unhelpful These are ones where I regarded the suggestion Pylint was making as unhelpful — there were good reasons for the way it was written, even if a bit unusual, and, in my judgement, the code is better off the way it is — although I could see that other people might make a different judgement, or different choices in coding style and design could potentially have avoided the issues. too-many-ancestors × 76 These were all in test code, where I’m using a bunch of mixins to provide utilities or mocking of certain things. unused-variable × 43 This were almost all in test code, where I was destructuring a tuple on assignment: foo, bar = get_some_stuff() and then not using one of them. There are easy ways to silence Pylint in these cases (e.g. names like unused), but the names as they were enhanced readability, and a future maintainer (including myself) who might need the value would probably do better if I left the code as it is. invalid-name × 26 These were cases where I had chosen decent names in context, but ones that happened to fall foul of Pylint’s naming standards e.g. db (which is a well accepted abbreviation for database), and some other names that ended up being non-standard but more understandable the way they were, in my opinion. If you are a stickler for consistency then you might have disagreed here. redefined-outer-name × 16 Sometimes the right name is the right name, in both inner and outer contexts, and you would never need to use the outer name from the inner context. too-few-public-methods × 14 Examples included data classes of the kind you create with attrs, which might have zero public methods, or a class that was implementing a dictionary interface but actually only needed to provide a single __getitem__ to work correctly. no-self-use × 12 These were all in test code, where I had deliberately added methods to a base class or mixin which didn’t use self, because it was more convenient to import them and make them available to a test case that way. Some of them even wrapped standalone functions that did the same thing. attribute-defined-outside-init × 10 There were good reasons in these cases! Mostly test code. too-many-locals × 6, too-many-return-statements × 6, too-many-branches × 2, too-many-statements × 2 Yes, these functions were long, but having looked at them, I didn’t think there were nice ways of cleaning them up that would be an overall improvement. One of them, while long, was straightforward and had a very clear structure and wasn’t ‘messy’, while any ways of shortening it I could think of would have involved unhelpful layers of indirection or awkward utility functions. arguments-differ × 6 Mostly due to using *args and **kwargs in an overridden method, which is usually actually a good way to protect yourself from changes in method signatures from 3rd party packages (but has downsides too, and in some cases this error could highlight genuine bugs). ungrouped-imports × 4 I already use isort to manage my imports fixme × 4 Yes, I have some TODOs, but I don’t want to fix them right now. duplicate-code × 3 Sometimes you have a small amount of boilerplate that is kind of unavoidable, and if the ‘body’ of the code is small, this warning gets triggered. broad-except × 2 abstract-method × 2 redefined-builtin × 2 too-many-lines × 1 I have tried to think of natural ways to break this module down, and can’t. It’s also one of those places where I think a linter is just the wrong tool. If I have a module with 980 lines of code, and add another 30 so I cross the 1,000 limit, a linter complaining at me is just not helpful. If 980 is OK, why is 1010 so bad? I don’t want to have to refactor that module in order for the build to succeed, and I also want to be keeping my linter silent, so the only thing I can sensibly do at this point is silence the linter somehow, which defeats the purpose. pointless-statement × 1 expression-not-assigned × 1 cyclic-import × 1 The import cycle had already been broken by placing one inside a function. I couldn’t see a better way to structure the code given the constraints. unused-import × 1 I already had a # NOQA to silence this for flake8. too-many-public-methods × 1 If my test class has 35 tests, instead of the maximum 20, is that actually a problem? too-many-arguments × 1 TOTAL: 243 Can’t fix This covers a category of issues that I couldn’t fix, even if I wanted to, due to external constraints, like the fact you might need to provide a callback/class to a third party library or framework that has to satisfy certain requirements. unused-argument × 21 invalid-name × 13 protected-access × 3 Included some access to “documented internals” like sys._getframe in stdlib and Django’s Model._meta (which is documented). too-few-public-methods × 3 too-many-arguments × 2 wrong-import-position × 2 attribute-defined-outside-init × 1 too-many-ancestors × 1 TOTAL: 46 Incorrect These are ones where Pylint was simply making objectively wrong assertions about my code. If the assertion had been correct, it would probably have been something to act upon, but it wasn’t. These are not things you could reasonably file as Pylint bugs — the dynamism of Python makes some of the things Pylint is trying to detect impossible to do reliably. no-member × 395 These were due to a handful of base classes, some from Django, others I created myself, where Pylint was unable to detect the existence of the members due to dynamism/meta-programming. Quite a few of them were due to how I had structured my test code (using the pattern given by django-functest, which in some cases could have been fixed by adding additional base classes with ‘abstract’ methods (i.e. ones that just raise NotImplementedError), or perhaps by renaming many of my test classes (to something that in this case would have been misleading, so I wouldn’t be very inclined to do that). invalid-name × 52 These were mainly due to Pylint applying PEP8’s rule about constants, and thinking that every top-level name defined using an = sign is a ‘constant’. Defining exactly what we mean by a constant is trickier than it sounds, but it certainly doesn’t apply to some things that are constant in nature, such as functions, and shouldn’t apply to less usual ways to create functions e.g. def foo(): pass # etc cached_foo = cache(seconds=100)(foo) Some of the ones in this category are debatable due to the lack of definition of what a constant is e.g. should a module level defined instance of a class, which may or may not have mutable state, be considered a constant? Such as in this common idiom: logger = logging.getLogger(__name__) no-self-use × 23 Pylint incorrectly claimed “Method could be a function” for a bunch of cases where I’m using inheritance to provide different implementations, so couldn’t convert these to functions. protected-access × 5 Pylint incorrectly assessed who was the ‘owner’ (i.e. the current bit of code is creating a ‘protected’ attribute on an object, and using it locally, but Pylint can’t see that). no-name-in-module × 1 import-error × 1 pointless-statement × 1 This statement does indeed have an effect: 1 / 0 I was using it to deliberately throw an unusual error that would be unlikely to be caught, as part of test code. I don’t blame Pylint for not guessing that of course… TOTAL: 477 Running total We haven’t finished yet, but let’s put these groups together at a higher level, namely: - “Good” — the “Bugs” and “Helpful” categories where Pylint would definitely have been a positive help: 17 - “Neutral” — the “Cosmetic” category for things that have very marginal benefit, but can’t hurt (as long as they don’t take too much time): 252 - “Bad” — the “Unhelpful”, “Can’t fix” and “Incorrect” categories where Pylint is wanting us to change code that is better off the way it is, or definitely can’t be changed because of external dependencies, or because Pylint has just plain got the analysis wrong: 766 The Good:Bad ratio here is very low in my book. If Pylint was a co-worker doing code review, I’d be praying for him to leave (mostly likely ‘he’ would be the correct gender here…) To fix the false positives you could silence the entire class of errors (which increasingly makes using Pylint pointless), or add special comments to your code individually. I’m reluctant to do the latter: - It takes time! - I dislike the visual clutter of comments that are just there to silence a linter. I’m happy to add these pragmas when there are compelling benefits from using the linter, but not otherwise — I think comments are important, or should be important, so my code syntax highlighting theme shows them in strong contrast, as recommended by this article. So I do have some NOQA comments to silence flake8, for example, but for this same section of the code they add up to only 5 instances. Docstrings The remainder of issues that Pylint found were missing docstrings. I put these in a separate category because: - They are very debatable, and you as a reader might have a very different policy on this kind of thing. - I didn’t have time to do an analysis on all of them. Overall Pylint found 620 missing docstrings (modules, functions, classes methods). In many cases I feel very justified in not adding docstrings. For example: - When the name is already clear. For example: - if I have feature Foo, I don’t have to guess what FooTests might be about. I also don’t tend to add docstrings to test methods, and prefer a long name instead. - A module foo.utils.html is most likely to contain HTML utilities used by the foo project. - And many other cases where a good name is enough. - When the docstring is effectively defined elsewhere — for example, if I’m implementing an interface like Django’s database router. Adding your own docstring could easily be dangerous here. In other cases, my code certainly could have benefited from more docstrings. Probably in only about 15 to 30% of the cases that Pylint caught would I think “Yes, I should add a docstring here, thank you Pylint for reminding me”. In general I don’t like tools that force you to write docstrings, because I think you almost always end up with bad docstrings when that happens, and they are much worse than nothing, for basically the same reasons as for bad comments: - they waste your time reading them, because they provide no extra information, or incorrect information, - they then make you subconsciously filter out docstrings as a useful source of info, so they make all the docstrings useless, when docstrings can contain useful info. Warnings about docstrings are annoying because to silence them individually would require adding a comment, which is about the same amount of work, and adds the same amount of visual noise, as adding a docstring itself. So it’s pretty much inevitable that you will end up with docstrings that are not necessary or unhelpful (and are therefore actively harmful). I’ve experienced this in practice, and I don’t think it can be solved by “choose better developers” or “try harder” — the problem is the process. Conclusion With these figures, I feel my previous estimates about the usefulness of Pylint (in the context of a code base where I’m already using flake8) were about right. The false positive rate would have to be massively reduced for me to consider using it. In addition to the time and visual noise needed to deal with false positives, I would be reluctant to add something like this to a project because of the problem that junior devs may take a more slavish approach to keeping Pylint happy. This could result in them breaking working code because they didn’t understand that Pylint had got it wrong, or doing big code refactors just to enable Pylint to understand the code. If you use Pylint from the beginning of a project, or in a project with very few third party dependencies, I imagine you might feel differently, as the rate at which you hit false positives might be low. On the other hand, this might simply be concealing the costs of these things. Another approach would be to use Pylint with a very restricted set of errors. However, there were only a handful of errors which were consistently correct, or low enough in false positives (either in relative or absolute terms) that I would want them on my project. (These included: dangerous-default-value, stop-iteration-return, broad-exception, useless-object-inheritance) Anyway, I hope this has been helpful to others in considering the use of Pylint, or in arguing about it with colleagues!
https://lukeplant.me.uk/blog/posts/pylint-false-positives/
CC-MAIN-2019-47
refinedweb
3,111
54.97
Credit: Alex Martelli, AB Strakt, author of forthcoming Python in a Nutshell Object-oriented programming (OOP) is among Python’s greatest strengths. Python’s OOP features keep improving steadily and gradually, just like Python in general. You could write object-oriented programs better in Python 1.5.2 (the ancient, long-stable version that was new when I first began to work with Python) than in any other popular language (excluding, of course, Lisp and its variants—I doubt there’s anything you can’t do well in Lisp-like languages, as long as you can stomach the parentheses-heavy concrete syntax). Now, with Python 2.2, OOP is substantially better than with 1.5.2. I am constantly amazed at the systematic progress Python achieves without sacrificing solidity, stability, and backward compatibility. To get the most out of Python’s OOP features, you should use them “the Python way,” rather than trying to mimic C++, Java, Smalltalk, or other languages you may be familiar with. You can do a lot of mimicry, but you’ll get better mileage if you invest in understanding the Python way. Most of the investment is in increasing your understanding of OOP itself: what does OOP buy you, and which underlying mechanisms can your object-oriented programs use? The rest of the investment is in understanding the specific mechanisms that Python itself offers. One caveat is in order. For such a high-level language, Python is quite explicit about the OOP mechanisms it uses behind the curtains: they’re exposed and available for your exploration and tinkering. Exploration and understanding are good, but beware the temptation to tinker. In other words, don’t use unnecessary black magic just because you can. Specifically, don’t use it in production code (code that you and others must maintain). If you can meet your goals with simplicity (and most often, in Python, you can), then keep your code simple. So what is OOP all about? First of all, it’s about keeping some state (data) and some behavior (code) together in handy packets. “Handy packets” is the key here. Every program has state and behavior—programming paradigms differ only in how you view, organize, and package them. If the packaging is in terms of objects that typically comprise state and behavior, you’re using OOP. Some object-oriented languages force you to use OOP for everything, so you end up with many objects that lack either state or behavior. Python, however, supports multiple paradigms. While everything in Python is an object, you package things up as OOP objects only when you want to. Other languages try to force your programming style into a predefined mold for your own good, while Python empowers you to make and express your own design choices. With OOP, once you have specified how an object is composed, you can instantiate as many objects of that kind as you need. When you don’t want to create multiple objects, consider using other Python constructs, such as modules. In this chapter, you’ll find recipes for Singleton, an object-oriented design pattern that takes away the multiplicity of instantiation. But if you want only one instance, in Python it’s often best to use a module, not an OOP object. To describe how an object is made up, use the class statement: class SomeName: """ You usually define data and code here (in the class body). """ SomeName is a class object. It’s a first-class object like every Python object, so you can reference it in lists and dictionaries, pass it as an argument to a function, and so on. When you want a new instance of a class, call the class object as if it was a function. Each call returns a new instance object: anInstance = SomeName( ) another = SomeName( ) anInstance and another are two distinct instance objects, both belonging to the SomeName class. (See Recipe 1.8 for a class that does little more than this but is quite useful.) You can bind and access attributes (state) of an instance object: anInstance.someNumber = 23 * 45 print anInstance.someNumber # 1035 Instances of an “empty” class like this have no behavior, but they may have state. Most often, however, you want instances to have behavior. Specify this behavior by defining methods in the class body: class Behave: def _ _init_ _(self, name): self.name = name def once(self): print "Hello, ", self.name def rename(self, newName) self.name = newName def repeat(self, N): for i in range(N): self.once( ) Define methods with the same def statement Python uses to define functions, since methods are basically functions. However, a method is an attribute of a class object, and its first formal argument is (by universal convention) named self. self always refers to the instance on which you call the method. The method with the special name _ _init_ _ is known as the constructor for the class. Python calls it to initialize each newly created instance, with the arguments that you passed when calling the class (except for self, which you do not pass explicitly, as Python supplies it automatically). The body of _ _init_ _ typically binds attributes on the newly created self instance to initialize the instance’s state appropriately. Other methods implement the behavior of instances of the class. Typically, they do so by accessing instance attributes. Also, methods often rebind instance attributes, and they may call other methods. Within a class definition, these actions are always done with the self.something syntax. Once you instantiate the class, however, you call methods on the instance, access the instance’s attributes, and even rebind them using the theobject.something syntax: beehive = Behave("Queen Bee") beehive.repeat(3) beehive.rename("Stinger") beehive.once( ) print beehive.name beehive.name = 'See, you can rebind it "from the outside" too, if you want' beehive.repeat(2) If you’re new to OOP in Python, try implementing these things in an interactive Python environment, such as the GUI shell supplied by the free IDLE development environment that comes with Python. In addition to the constructor ( _ _init_ _), your class may have other special methods, which are methods with names that start and end with two underscores. Python calls the special methods of a class when instances of the class are used in various operations and built-in functions. For example, len(x) returns x._ _len_ _( ), a+b returns a._ _add_ _(b), and a[b] returns a._ _getitem_ _(b). Therefore, by defining special methods in a class, you can make instances of that class interchangeable with objects of built-in types, such as numbers, lists, dictionaries, and so on. The ability to handle different objects in similar ways, called polymorphism, is a major advantage of OOP. With polymorphism, you can call the same method on each object and let each object implement the method appropriately. For example, in addition to the Behave class, you might have another class that implements a repeat method, with a rather different behavior: class Repeater: def repeat(self, N): print N*"*-*" You can mix instances of Behave and Repeater at will, as long as the only method you call on them is repeat: aMix = beehive, Behave('John'), Repeater( ), Behave('world') for whatever in aMix: whatever.repeat(3) Other languages require inheritance or the formal definition and implementation of interfaces for polymorphism to work. In Python, all you need is methods with the same signature (i.e., methods that are callable with the same arguments). Python also has inheritance, which is a handy way to reuse code. You can define a class by inheriting from another and then adding or redefining (known as overriding) some of its methods: class Subclass(Behave): def once(self): print '(%s)' % self.name subInstance = Subclass("Queen Bee") subInstance.repeat(3) The Subclass class overrides only the once method, but you can also call the repeat method on subInstance, as it inherits that method from the Behave superclass. The body of the repeat method calls once N times on the specific instance, using whatever version of the once method the instance has. In this case, it uses the method from the Subclass class, which prints the name in parentheses, not the version from the Behave class, which prints it after a greeting. The idea of a method calling other methods on the same instance and getting the appropriately overridden version of each is important in every object-oriented language, including Python. This is known as the Template-Method design pattern. Often, the method of a subclass overrides a method from the superclass, but needs to call the method of the superclass as a part of its own operation. You do this in Python by explicitly getting the method as a class attribute and passing the instance as the first argument: class OneMore(Behave): def repeat(self, N): Behave.repeat(self, N+1) zealant = OneMore("Worker Bee") zealant.repeat(3) The OneMore class implements its own repeat method in terms of the method with the same name in its superclass, Behave, with a slight change. This approach, known as delegation, is pervasive in all programming. Delegation involves implementing some functionality by letting another existing piece of code do most of the work, often with some slight variation. Often, an overriding method is best implemented by delegating some of the work to the same method in the superclass. In Python, the syntax Classname.method(self, ...) delegates to Classname’s version of the method. Python actually supports multiple inheritance: one class can inherit from several others. In terms of coding, this is a minor issue that lets you use the mix-in class idiom, a convenient way to supply some functionality across a broad range of classes. (See Recipe 5.14 for an unusual variant of this.) However, multiple inheritance is important because of its implications for object-oriented analysis—how you conceptualize your problem and your solution in the first place. Single inheritance pushes you to frame your problem space via taxonomy (i.e., mutually exclusive classification). The real world doesn’t work like that. Rather, it resembles Jorge Luis Borges’s explanation in “The Analytical Language of John Wilkins”, from a purported Chinese Encyclopedia, The Celestial Emporium of Benevolent Knowledge. Borges explains that You get the point: taxonomy forces you to pigeonhole, fitting everything into categories that aren’t truly mutually exclusive. Modeling aspects of the real world in your programs is hard enough without buying into artificial constraints such as taxonomy. Multiple inheritance frees you from these constraints. Python 2.2 has introduced an important innovation in Python’s object model. Classic classes, such as those mentioned in this introduction, still work as they always did. In addition, you can use new-style classes, which are classes that subclass a built-in type, such as list, dict, or file. If you want a new-style class and do not need to inherit from any specific built-in type, you can subclass the new type object, which is the root of the whole inheritance hierarchy. New-style classes work like existing ones, with some specific changes and several additional options. The recipes in this book were written and collected before the release of Python 2.2, and therefore use mostly classic classes. However this chapter specifies if a recipe might be inapplicable to a new-style class (a rare issue) or if new-style classes might offer alternative (and often preferable) ways to accomplish the same tasks (which is most often the case). The information you find in this chapter is therefore just as useful whether you use Python 2.1, 2.2, or even the still-experimental 2.3 (being designed as we write), which won’t change any of Python’s OOP features. No credit card required
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch05.html
CC-MAIN-2019-18
refinedweb
1,975
63.39
The AlphaVideo component allows you to show videos with transparency. More... The AlphaVideo component internally uses the MediaPlayer, VideoOutput and ShaderEffect QML components to realize transparency for videos. In order to use this component, it is necessary to correctly set up your videos in a special way. The reason for that is, that many video formats do not support alpha-channels for transparency. Especially important formats for final rendering with high compression rates can't be used. As file sizes and cross-platform compatibility are highly relevant for mobile games and apps, a restriction to only allow formats that support alpha-channels is not a viable solution. But with a simple workaround, it is possible to use all available video formats. The basic idea is to split up the video into a color part and a transparency part. Look at the following example to see what the input video and the rendered video look like: On the left side you can see the original input video. It contains two versions of the same animation: The AlphaVideo component reads the input video and combines both videos parts into a single transparent video. You can show such alpha-videos in your app or game, just like you would show a normal video without transparency. All properties, methods and signals of the Video QML component are also available for the AlphaVideo. This small code snipped shows the alpha-video "AlphaAnimation.mp4" uniformly scaled to the scene size. The playback starts automatically and the video is infinitely looped. import Felgo 3.0 import QtQuick 2.0 import QtMultimedia 5.0 GameWindow { id: gameWindow activeScene: scene screenWidth: 960 screenHeight: 640 Scene { id: scene // the "logical size" - the scene content is auto-scaled to match the GameWindow size width: 480 height: 320 // show alpha video AlphaVideo { source: "../assets/AlphaAnimation.mp4" autoPlay: true anchors.fill: scene loops: MediaPlayer.Infinite // playback loop } } } For the loops property, you can use the enum MediaPlayer.Infinite. That's why the statement import QtMultimedia 5.0 is necessary. For other properties, like playbackState or fillMode, different enum types from the MediaPlayer or the VideoOutput component are used. If you don't need any of these enum-types, you can skip the import and use the AlphaVideo directly. The next section focuses on how to prepare an alpha-video, that can be used by the component. If you already have a video animation, that you wan't to include in your project, several steps are required to correctly set up your alpha-video: You can decide for yourself which software you want to use to create the video. The important thing is, that it's possible to render only the alpha-channel as a single video. The next section gives a step-by-step guide on how to create an alpha-video with Adobe After Effects. The first step is to render your animation just with rgb-colors. Render Queue. Output Module Settings, only select the RGB-channel. Once you rendered the non-alpha part of your video, you can go on with rendering the alpha-channel. The procedure is nearly the same. Render Queue. Output Module Settings, only select the Alpha-channel. Now it's time to combine both videos into a single one. With this you finished preparing your alpha-video, all thats left is to render and use it. When rendering the final video, you can choose any video format or compression setting that you like. But keep in my mind that big file sizes should be avoided for mobile games and apps. You can also use the Adobe Media Encoder for the final rendering. The Media Encoder supports many different formats and gives better control over compression rates and file sizes. One of the most used and best supported formats is MP4, which is also what we recommend to use. This property indicates if loading of the media should begin immediately. The default value is true. If it is set to false, media will not be loaded until playback is started Returns the availability state of the alpha-video instance. This is one of: Because the AlphaVideo type internally uses the MediaPlayer QML component, enumerations from MediaPlayer are used to access the availability state.: Because the AlphaVideo type internally uses the MediaPlayer QML component, enumerations from MediaPlayer are used to access the error state. This property holds a string describing the current error condition in more detail. Set this property to define how the video is scaled to fit the target area. Because the AlphaVideo type internally uses the VideoOutput QML component, it to MediaPlayer.Infinite to enable infinite looping. The value can be changed while the media is playing, in which case it will update the remaining loops to the new value. The default is 1. This property may be used to access the video's meta-data. For more information, see the MediaPlayer documentation page. This property holds whether the audio output is muted. The orientation of the video in degrees. Only multiples of 90 degrees are supported, that is 0, 90, 180, 270, 360, etc. This property holds the rate at which video is played at as a multiple of the normal rate. This read only property indicates the playback state of the media. Because the AlphaVideo type internally uses the MediaPlayer QML component, enumerations from MediaPlayer are used to access the playback state. The default state is MediaPlayer.StoppedState. This property holds the source URL of the media. This property holds the status of media loading. It can be one of: As the AlphaVideo type internally uses the MediaPlayer QML component, enumerations from MediaPlayer are used to access the media loading status. This property holds the volume of the audio output, from 0.0 (silent) to 1.0 (maximum volume). This signal is emitted when playback is paused. The corresponding handler is onPaused. Note: The corresponding handler is onPaused. This signal is emitted when playback is started or continued. The corresponding handler is onPlaying. Note: The corresponding handler is onPlaying. This signal is emitted when playback is stopped. The corresponding handler is onStopped. Note: The corresponding handler is onStopped. Pauses playback of the media. Starts playback of the media. Stops playback of the media.
https://felgo.com/doc/felgo-alphavideo/
CC-MAIN-2021-21
refinedweb
1,039
58.79
I need to offer new users on our system a temporary password that is valid for only 48 hours. This is different than a 60-day password expiration window for existing users' passwords (where a password needs to be changed every 60 days), and is different than a "user expiration date", where you can set a date where the user's account expires and is disabled on that date, and different than the inactivity expiration date where a user becomes active if his account is not used within, say, 30 days. What I need is a password-inactivity expiration date such that if the user does not log for a first time within the time limit (48 hours), then the user account is disabled - but not expired! - and then must be "reset" to a new password (whereupon the cycle begins again, and the user is disabled withint 48 hours if he doesn't log in and change his password!). I'd prefer not to use the user expiration date, as this is not accessible when the user logs in (being in Security.Users in %SYS namespace), and would have to be removed separately. This concept is not quite the same as a Time-based-One-Time-Password, and we don't need two-factor authentication. Does InterSystems 2016 have this sort of setting, or do I need to put it into a password validation or some kind of login authentication routine? Thanks for the help, Laura A task, of course... I'll have to go through the list of users and check their LastLoginTime/CreateTime, Enabled, etc. For future users who are looking for this, I'll use the SQL procedure Security.Users_Detail(). I did not know about the Security.Scan, but I'll take a look, and see what else I should tack on to it. Good idea to run our custom security task after the SecurityScan. Thanks! Getting there. And perhaps InterSystems will add this concept in the 2017 (2018?) release. Laura
https://community.intersystems.com/post/there-temporary-password-concept-cach%C3%A9-2016
CC-MAIN-2019-51
refinedweb
334
58.52
Agenda See also: IRC log <daveL> meeting xliff roundtrip tc <daveL> scribe: daveL clarified that Milan m4loc service does not consume the term annotation and the internal glossary m4loc does the look up internally return a pointer to the target ref in dbpedia (identRef only) agreed - will try using enrycher using html sample as input tadej will update live service with ta instead of disambig. Leroy will add this and then geenrate XLIFF through extraction and segmentation david: what is status of namespace for its-x present; david, dave, tadej, milan, phillip, leroy, ankit namespace: agree to use 'itsx' rather than 'its-x' dave will change XLIFF mapping page to reflect this. <dF> itsx.solas.uni.me or itsx.uni.me <dF> the latter is preferable if available this is atemporary solution -need to hand over namespace responsibility it W3C later in 2013 topic; mt confidence encoding agreed: use origin and match for mt confidence in the alttrans. If the output is copied and unedited in the trans-unit.translate, that is where mt-confidence should be used. note ankit will have to make that change also. dave will update files. <Ankit> okay David suggest in the origin just use 'MT' or 'TM' just to differentiate those. and then the provenance record allows recording of the actual tool infomation milan agree to use this also, i.e. using proveance record rather than xliff tool id note that xliff tool id is deprecated anyway and not in XLIFF 2.0 topic; status of implementations sean: hoping to test with Ankit by the end of the day ... with milan have tested previously, so just need to retest with new annotations Topic; name of domain(s). agreed stick to 'domain' dave to update in files and in mapping page Also, 'its' namespace needs to be included as itsx namespace for domain topic; term markup glossary entry need to be wrapped in an internal file then use itsx namespace for <glossary-entry> i.e. <glossary><internal-file><itsx:glossary-entry> plan: leroy and sean to start testing tuesday start 10am tuesday for leroy and seam thurday next week: 10 sean and milam, 11 for ankit
http://www.w3.org/2013/03/01-mlw-lt_xliff-minutes.html
CC-MAIN-2014-10
refinedweb
361
56.89
returns the asset at path if it can be found, otherwise it returns null. Note that the path is case insensitive and must not contain a file extension. All asset names and paths in Unity use forward slashes, so using backslashes in the path will not work. The path is relative to any folder named Resources inside the Assets folder of your project. More than one Resources folder can be used. If you have multiple Resources folders you cannot duplicate the use of an asset name. For example, a project may have Resources folders called Assets / Resources/ and Assets / Guns / Resources/. The path does not need to include Assets and Resources in the string, for example loading a GameObject at Assets / Guns / Resources / Shotgun.prefab would only require Shotgun as the path. Also, if Assets / Resources / Guns / Missiles / PlasmaGun.prefab exists it can be loaded using Guns / Missiles / PlasmaGun as the path string. If you have multiple Resources folders you cannot duplicate the use of an asset name. T An object of the requested generic parameter type. Loads the asset of the requested type stored at path in a Resources folder using a generic parameter type filter of type T. This method returns the asset at path if it can be found and if its type matches the requested generic parameter type, otherwise it returns null. You can use this overload to reduce type conversion in your code by providing a generic type parameter. This allows Unity to perform the C# type conversion for you. // Loading assets from the Resources folder using the generic Resources.Load<T>(path) method using an optional systemTypeInstance filter. This method returns the asset at path if it can be found and if its type matches the optional systemTypeInstance parameter, otherwise it returns null. You may need to cast the returned object to the actual associated C# type of the asset in order to access its methods and properties, or use it with other Unity APIs. // Loading assets from the Resources folder using the Resources.Load(path); } } // Loading assets from the Resources folder using the Resources.Load(path, systemTypeInstance) using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { // Instantiates a Prefab named "enemy" located in any Resources folder in your project's Assets folder. void Start() { GameObject instance = Instantiate(Resources.Load("enemy", typeof(GameObject))) as GameObject; } }
https://docs.unity3d.com/ScriptReference/Resources.Load.html
CC-MAIN-2021-17
refinedweb
391
57.37
If you find a mistake, or something is unclear, please email per@bothner.com so I can fix the text. We have earlier looked at the values (nodes, primitives, and sequences) that XQuery works with. In this article we will look more deeply into the XQuery/XPath data model and type system. On the way we will touch on a fair bit of background material, including XML Schemas and XML infosets. The XQuery data model is based on the XML Information Set standard (W3C Recommendation 24 October 2001,). It rather abstractly defines the information content of an XML document as a document item that contains nested element items, which in turn contain namespace, attribute, character and other items. This is a conceptual standard: It does not define any file formats or programming interfaces, but rather it defines the interpretation of an XML file. It is intended to be useful for defining other XML-related standards, including the XQuery/XPath data model. XML files that are different at the character level but that have the same information set or infoset are for most practical purposes equivalent. For example: <a b='upcase' ><![CDATA[Hello!]]></a> and <a b="upcase" >Hello!</a> have the same information sets. The "Canonical XML" recommendation is a related standard in that it specifies a unique ("canonical") way to convert an XML infoset (back) into an XML document. Two XML documents that are "logically equivalent" (i.e. have the same infoset) translate to the same canonical XML representation. The Canonical XML for the above example is: <a b="upcase">Hello!</a> A parsed XML file results in an infoset, but there can also be synthetic infosets that are constructed from other sources, such as a database, or created by a program that manipulates a DOM (Document Object Model). A DOM is a popular data structure API used to encode and manipulate XML data - i.e. infosets. The XQuery language also allows you to create infoset items, using element constructor expressions or pre-defined functions. Node values represent the parts of a XML document, or more generally an XML infoset. Nodes are also used to represent document fragments - i.e. stand-alone nodes that are not part of a document (for example, those that might be generated by an element constructor expression). These are the kinds of nodes, most of which are as you would expect: Document nodes represent a complete XML document. Element nodes present XML elements. Attribute nodes represent the attributes of an element. Note that namespace definitions are represented by namespace nodes instead. Namespace nodes represent the in-scope attributes of an element. (You cannot actually "get at" a namespace node in XQuery, though you get at them in XPath using the namespace:: axis, which has been deprecated in XPath 2.0.) Processing instruction nodes represent embedded XML processing instructions. Comment nodes represent XML comments. Text nodes represent character data. Note that an infoset consists of single-character items, but in the node representation multiple contiguous character items are represented in a single text node. The XQuery 1.0 and XPath 2.0 Data Model specification () goes into details about the different kinds of nodes. It also defines a number of functions on nodes, using the prefix dm. For example, the function dm:node-kind takes a Node and returns a string value that represents the node's kind, one of "document", "element", "attribute", "text", "namespace", "processing-instruction", or "comment". Note that these functions are only to explain the data model: You cannot call them from an XQuery program, and the prefix dm isn't actually bound to any namespace. However, in some cases there may be a function in the Functions and Operators document with the same name and behavior. Those are available to your XQuery programs. For example there is a fn:node-kind function which you can use, and which is defined to return the same result as dm:node-kind. Nodes in XQuery are immutable, which means you cannot change any part of a node once it has been created. This makes sense, since XQuery is a pure side-effect-free expression language. However, nodes do have identity: two nodes that were created using different expressions are distinct nodes, even if they contain the same data. You can compare the latter using the standard function fn:deep-equal. The following examples are all true: fn:deep-equal(<a>test</a>, </a>test</a>) <a>test</a> isnot </a>test</a> let $x := <a><b></b></a> return $x/b is $x/* Because nodes have identity, you can talk about making a copy of a node, because you can distinguish the original from the copy. However, atomic values do not have identity: There is no way to copy the string "xyzzy" because there is no way to distinguish the copy from the original. That is the difference between a string atomic value and a text node, which you can copy. A node may have children, which are the nodes below it in the tree hierarchy, but not including attribute or namespace nodes. For example, the children of an element node are the text nodes and nested elements (and occasionally other nodes) that are its contents. The function dm:children takes a node and returns the sequence of its children. (This function only exists in the data model; to get the children of a node N in XQuery use the expression N/node().) Only document and element nodes can have children, so dm:children returns the empty sequence for other node types. For each node X that is a child of Y, the node X has a parent property that is the node Y. Using the data model, you can get at Y using the dm:parent function; in an XQuery program you have to use the expression X/parent::node(). These properties have some surprising consequences. Because nodes are immutable, you have to specify the children of an element or document when you create it. However, those children have to have their parent property set to the new node - but you can't modify them, as they are immutable. This chicken-and-egg problem is solved by creating new copies of the children, with the parent property of the new nodes set to the new parent. Any children of the children also have to be copied. Note, however, that this copying of nodes is part of the specification, but an implementation is free to optimize away the copying if it doesn't change the result. For example, consider the following expression: <a>Some <b/>{<c>text</c>}</a> The specification says that <b> and <c> nodes are created, and then copied when <a> is created. But since there is no way to access the old <b> and <c> nodes, an implementation is free to just re-use the old nodes without copying them, or it can create them in-place at the same time it creates <a>. This is an example of the important difference between specification and (valid) implementation. The lack of side effects in XQuery gives the implementation extra flexibility in choosing how to implement things. A possible disadvantage is that it makes it hard to estimate how much work is done for an XQuery program, unless you are very familiar with your implementation. On the other hand, you usually don't need to know. More generally, an implementation is free to represent nodes in any way compatible with the specification. An obvious choice is to use the standard Node type specified in the W3C's Document Object Model (DOM) (). However, though DOM is a flexible and convenient API, it is quite space-inefficient. As an example of an alternative representation, the Qexo implementation () uses a single TreeList for an entire document. The TreeList contains an internal array, and node objects are identified by indexes into that array. (The Apache Xalan XSLT processor uses a similar Document Array Model representation.) In fact, an implementation may in some cases not create actual node objects at all. Consider that the ultimate result of evaluating an XQuery expression is often written out to a file as a new XML document. In that case the XQuery processor can write out the nodes on-the-fly directly to the output file, without ever creating any nodes. More generally, the XQuery processor can "write" the output to a SAX DocumentHandler or a similar event-driven interface. Sometimes it is useful to take a node, and convert it to a string value. The function fn:string does that. The string value of a text node is the characters in the node. The string value of an element or document node is the concatenation of the text node descendents of the node in document order. The string value of an attribute node is the attribute value. There is also the typed value of an element, attribute, or text node, which you can extract using the fn:data function. This is the value of a node as a sequence of atomic values, as the result of Scheme validation. If an element node has a complex type, then the typed value is undefined. The XQuery and XPath languages are typed expression (functional) languages. This means that programs are made from expressions (which may in turn contain sub-expressions), and that evaluating an expression results in a value, which has a type. Informally, a type is a set of values: those values that are instances of or belong to the type. The type system of a programming language is the collection (vocabulary) of types that the language definition distinguishes, including the rules for determining whether a value is an instance of a type, and for how to create complex types from simple types. A type error occurs when the operands of an operation have types that are not allowed for that operation. For example, in XQuery you can add two numbers using the + operator, but you can't add two nodes, even if the nodes contain integer values. If your program tries to add two nodes, the XQuery processor should give you an error message instead. It is useful to distinguish between the dynamic types and static types: The type of a value is a dynamic type. Dynamic types exist during evaluation (at run-time). Dynamic types are sets of values that are instances of the type. A type specifies the meaning or interpretation of a value. The type of an expression (a program fragment) is a static type. Static types are the types of declarations and program fragments as specified by the programmer or inferred by a compiler. If an expression has a (static) type and you evaluate the expression without a run-time error, then the result is guaranteed to be an instance of the corresponding static type. A dynamically typed language is one that doesn't have static types. Another way to say the same thing is that there is only a single type, which contains all values. In those languages, all type errors are run-time errors. The goal of a static type system is to detect type errors at compile time, before actual execution. This is a process called type checking, and in some languages (including XQuery) is a fairly complicated process. Static type checking lets you detect and fix errors earlier. This is especially valuable for infrequently executed parts of a program, since they are less likely to get much testing. As a side benefit, if the compiler can determine the type of an expression, it may be able to generate more efficient code, and so the query may execute faster. The XQuery and XPath languages specify both dynamic types and static types. The static type checking is optional, both for implementors and users: An XQuery implementation need not implement the static typing feature, and implementations that do implement static typing will have an option to disable it. We will discuss static typing later, but first we will study dynamic typing, including the kinds of values that XQuery and XPath deal with. The data model is part of dynamic typing. The values worked on by an XQuery program are sequences of items. An item is either an atomic value (for example an integer or a string) or a node (for example an element or an attribute). A sequence is a collection of zero or more items. The most important idea to note is that not only are all sequences values, but also all values are sequences, because a sequence of just a single value is in all respects the same as the single value. It follows from this that you cannot nest sequences - you cannot have sequences of sequences, only flat single-level sequences. If you have experience with arrays or lists in other programming languages, you might think it is a strange and limiting restriction that you can't nest sequences. Actually, it isn't really a limitation, because you can always uses nested elements if you need nested data. For example, to represent a two-dimensional array you can use nested elements like this: <list> <list>11 12</list> <list>21 22</list> </list> A major difference between XPath 1 and XPath 2 is that the latter has sequences, while the former does not. Instead, XPath 1 has node sets, which are like sequences, but without duplicates, and in unspecified order. XPath 1 path expressions evaluate to node sets, while in XPath 2 (and XQuery) path expressions evaluate to node sequences. However, the latter sequences are defined to be sorted in document order and with duplicates removed. (These are actually equivalent, in that you can map a set into a sequence that is ordered and without duplicates, and back again, without information loss. Furthermore, any valid XPath 1 expression will behave the same under either model.) The XQuery/XPath primitive types are the same as in XML Schema, which is a standard for specifying element structure of XML data, and associating types with XML data. Atomic values include numbers, values, and booleans. There are two kinds of atomic type: A primitive type is not defined in terms of some other type. A derived type is based on some other type, its base type. A derived atomic type is a restriction of its base type, because it is a restriction (sub-set) of the set of atomic values that belong to the base type. Following is a complete list of the built-in types defined by XML Schema. We will only list them briefly; for more information see the W3C Recommendation (02 May 2001) of XML Schema Part 2: Datatypes (). This specifies for each type its value space (the abstract values that belong to the type), its lexical space (the text representation of values using printable characters), and its facets (properties of the type itself). XML Schema defines the following builtin types: A boolean is one of the two truth values true and false. A string is zero or more Unicode characters. There a various sub-types of string: A normalizedString is a string that does not have any whitespace characters except for space. A token is a normalizedString that has no leading or trailing spaces, and does not have two or more spaces in a row. A language is a token used to specify a natural (human) language. An NMTOKEN is a token consisting of one or more NameChar characters, as defined in the XML standard. A Name is a token used to represent XML names, such as body or html:table. An NCName is a plain Name without a colon, such as body. The types ID, IDREF, and ENTITY are sub-types of NCName used for special kinds of attribute values as specified in the XML standard. The types IDS, IDREFS, ENTITIES, and NMTOKENS are used for space-separated sequences of the corresponding tokens. A NOTATION is used for attributes that specify the notation (encoding) of an element. However, NOTATION is not a sub-type of string. An anyURI represents a Uniform Resource Identifier Reference, such as. A QName represents an XML qualified name, which is a pair of a namespace name, and a local part. Note that in the value space a namespace name is an anyURI (such as), while the lexical representation uses namespace prefixes (as in xhtml:body). Therefore mapping between the two requires a context that contains the needed namespace declaration. A decimal is an arbitrary-precision real number, in base 10. An integer is a decimal without a fractional part. The types nonPositiveInteger, negativeInteger, nonNegativeInteger, and positiveInteger are the obvious sub-types of integer. The types long, int, short, byte, unsignedLong, unsignedInt, unsignedShort, and unsignedByte are sub-types of integer that can be encoded in binary using respectively 64, 32, 16, or 8 bits. The types float and double correspond to 32-bit and 64-bit IEEE binary floating-point real numbers. The standard lexical representation uses decimal format, with an optional exponent, such as -58.45 or 1.25e-10, even though these types are not sub-types of decimal. There are a number of time-related types: A date is a calendar date, such as May 31, 1999 (written 1999-05-31). A time is an instant that occurs every day, like 1:20pm (written 13:20). A dateTime is a specific instant of time, like 1:20pm on May 31 1999 (written as 1999-05-31T13:20). Any of these may have an optional timezone specified. A gYear is a specific year in the Gregorian calendar, while a gMonthYear is a specific year and month. A gMonthDay is a month and day that recurs every year, a gMonth is a month that recurs every year, and a gDay is a day that recurs every month. A duration is a duration of time, like 2 days and 1 hour (written as P2D1H). The XQuery/XPath committee has added two sub-types of duration, which may get added to future Schema revisions: xdt:yearMonthDuration (a duration of some number of years and months) and xdt:dayTimeDuration (a duration of some number of days, hours, minutes, and seconds). The types hexBinary and base64Binary are used to encode arbitrary binary data. The value of either is zero or more octets (8-bit bytes). A hexBinary uses two hexadecimal digits for each octet, so 0FB7 encodes the 16-bit integer 4023. A base64Binary uses the Base64 MIME Content-Transfer-Encoding. The union of all primitive types is anySimpleType. All of these standard types names are in the namespace, conventionally written using the predefined namespace prefix xs, as in xs:string. The XQuery specication adds four types: the duration types xdt:yearMonthDuration and xdt:dayTimeDuration are mentioned above; xdt:anyAtomicType includes all the atomic values; and xdt:untypedAtomic is a type used for untyped data, such as text that has not been validated. All are subtypes of anySimpleType, and are in the namespace. The word schema comes from the database community, and means a description of the structure, types, and relations of a database. In the XML world a schema is a description of the syntax and meaning (types) of a class of XML documents. A schema language is a formalism for specifying the types of documents as schemas. The earliest XML schema language is DTD (Document Type Descriptor), which appears in the original XML specification from 1997, and goes back to the SGML roots of XML. DTD is a simple language that lets you express simple structural constraints. For example, the following: <!ELEMENT tr td*> means that a <tr> element consists of zero or more <td> elements. DTD does not have any mechanism for specifying semantic or type information, except in a very few cases. Other schema definition languages allow you to define and specify types. XML Schema () is a 2001 specification from W3C that can be used to specify structural constrains and associate type information with XML documents. While there are other Scheme language in use, this is the one with most usage and visibility, partly because it is a W3C standard. The type semantics of XQuery/XPath2 are defined in terms of XML Schema. As an example we will use the record of a series of dice throws. Perhaps you want to verify the dice are fair, or you want a source of random numbers, or you want search for mystical patterns. <?xml version="1.0"?> <die-tests> <die-test> <who>Nathan</who> <when>whenever</when> <throws>5 2 2 2 1 3 6 6 2 6</throws> </die-test> <die-test> <who>Per</who> <when>2002-10-09T09:07</when> <throws>6 2 5 2 2 3 3 3 4 1</throws> </die-test> </die-tests> The Schema for this might look like the following: <?xml version="1.0"?> <xsd:schema xmlns: <xsd:element <xsd:complexType> <xsd:sequence> <xsd:element </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:complexType <xsd:sequence> <xsd:element <xsd:element <xsd:element <xsd:simpleType> <xsd:list </xsd:simpleType> </xsd:element> </xsd:sequence> </xsd:complexType> <xsd:simpleType <xsd:restriction <xsd:minInclusive <xsd:maxInclusive </xsd:restriction> </xsd:simpleType> </xsd:schema> This is verbose, and may be a bit intimidating, but it is relatively straightforward. It contains a top-level element declaration for the root element <die-tests>, as well as type definitions for types named die-test-type and die6-result. A simple type (such as die6-result) can only be expressed as character data. A complex type (such as die-test-type) can consist of attribute specifications, and either sub-elements ( complexContent), character data ( simpleContent), or a mixture of these ( complexContent, mixed="true"). The type of an attribute can only be a simple type, while the type of an element can be either a simple type (if it only contains text data), or it can be a complex type. All pre-defined types (such as xsd:integer) are simple. The top-level element declaration for die-tests says that any element with the die-tests tag has the structure and type specified: It is a complex type consisting of a sequence of 0 or more elements that have the tag die-test, and that the content of each such die-test element has the type with the name die-test-type. (It is possible to specify that a given element tag can be have different types in different contexts, but we'll ignore that possibility.) The definition of the complex type die-test-type specifies that any element declared to have that type (in our case die-test) consists of a sequence of a <name> element, a <when> element, and a <throws> element. The latter is a space-separated list of die6-result values. The definition for the simple type die6-result says that a die-result is an integer in the range 1 through 6. To validate an XML document against a schema means to scan the document, verifying that the document satisfies the constraints specified in the schema. The result is a post-schema validation infoset (PSVI), which is an info set (as defined earlier) with additional type annotations. A type annotation is the QName of a type named in a schema. An XQuery processor may optionally implement the Schema import feature. If it does, it must be able to import definitions from external schemas and validate node trees. Each element or attribute in XQuery has a type annotation, which is its dynamic type. If an element has not been validated, or otherwise been given a type annotation, then it has the default type annotation xs:anyType. The corresponding default for an attribute node is the type xs:untypedAtomic. Atomic (non-node) values can also have type annotations. The annotation xsd:untypedAtomic indicates that the type is unknown, typically raw text from an schema-less XML file. Operations that take atomic values may cast xsd:untypedAtomic to a more specific type, such as xs:double, but if the atomic value is of the wrong kind (a string where a number is required, as in the operands of +), then a run-time error may be signaled. An XQuery application can use a validate expression: validate ( EXPR ) This takes a sequence of elements, strips off any existing type annotations, and adds type annotations as specified by the in-context scheme definitions. The latter are all the scheme element declarations and type definitions that are imported by schema import declarations. (You can optionally specify a SchemaContext that can be used with context-dependent schema types.) A schema import declaration appears in the Query Prolog of an XQuery program. For example: import schema "" at "xhtml.xsd" This tells the XQuery processor to look at the location specified (in this case by the relative URL " xhtml.dtd") and add any schema components in the specified namespace () to the set of visible schema components. These now become available for validate expressions. Note that Schema validation and type annotation are conceptually dynamic (run-time) type operations. A type annotation is a QName that is associated with a value, not associated with a static (compile-time) expression. Next we will look at static type-checking. The XQuery language provides operations to check whether a value belongs to a type, as well as mechanisms to declare that a variable or parameter has a specific type. In an XQuery program (static) types are instances of SequenceType. We won't go into detail about SequenceType, but here are some examples: text() — Matches any text node. element() — Matches any element node. element(xhtml:td,*) — Matches any element node whose tag has the local part td and has the same namespace URI that xhtml is bound to. (It does not have to have xhtml as the actual namespace prefix.) element(*, die6-result)— Matches any element of any tag that has a type annotation of die6-result. element(xhtml:title)? — Matches an optional type element - i.e. zero or one items that match element xhtml:title, and whose type annotation matches that declared for xhtml:title in an imported schema definition. node()* — Matches a sequence of zero or more nodes. item()+ — Matches any non-empty sequence. attribute(@ID, *) — Matches any attribute node whose name is ID (in the empty namespace). xs:integer — Matches any integer type or any type derived from it, such a xs:nonNegativeInteger, assuming this is in scope of a namespace declaration that binds xs to, which is normally the case. These types can be used for XQuery's type-checking and -conversion operators. Here is a very brief summary; see the specification or other chapters for details and examples. expr instance of type — Returns true if the value of expr matches (is an instance of) type. cast as type (expr) — Convert the value of expr to a given type, using certain standard conversions. treat as type (expr) — Treat the expr as having static type type. At run-rime, a dynamic error is signaled if the value of expr is not an instance of type. typeswitch (expr) case type1 return expr1 ... default return exprd — Select the first case whose type matches the value of the expr, and evaluate the corresponding expression. An XQuery implementation may optionally implement the Static Typing Feature. This means that the implementation is required to detect static type errors at analysis (compile) time. At the time of this writing, the specification has a number of unresolved issues, and I don't know of any implementation that actually does implement static typing. (However, some of the precursor languages that inspired XQuery do implement static typing.) For these reasons, plus the fact that the specification of static typing is big and formal, I won't go beyond mentioning a few of the concepts. The static type system defined in the XQuery formal semantics () goes far beyond what you can express as a S equenceType. It includes most of the type specification concepts of XML Schema. The formal semantics defines extra declarations define type, define element, and define attribute. These are not in the XQuery source language (i.e. you can't write them directly), but are a formalism used in the formal semantics to express types imported from schemas. The idea is that an XQuery program is translated to core XQuery, which is simpler and more regular (but less convenient) than the actual XQuery program. Part of this translation is that Scheme import declaration are translated into define type, define element, and define attribute declarations. These internal declarations, as well as the whole concept of core XQuery, are purely part of the formal specification of XQuery: There is no requirement that any implementation implement the translation to core XQuery, only that it acts as if it does. Static type checking is done at the level of core XQuery at analysis (or compile) time. There are a whole slew of rules that say things like if the type of expr1 is xsd:boolean, the type of expr2 is type2, and the type of expr3is type3, then the type of if (expr1) then expr2 else expr3 is (type2|type3). Here (type2|type3) is a type expression in the formal semantics, which you cannot write directly in the actual XQuery language. <per@bothner.com> Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, version 1.1.
http://www.gnu.org/software/qexo/XQ-Data-Model.html
crawl-001
refinedweb
4,893
53.31
An easy to use HTTP client Project description urlfetch is a simple, lightweight and easy to use HTTP client for Python. It is distributed as a single file module and has no depencencies other than the Python Standard Library. Highlights Installation $ pip install urlfetch Hello World from urlfetch import get response = get('') print response.content Upload file from urlfetch import post response = post( '', headers = { 'Referer': '', }, files = { 'fieldname1': open('/path/to/file', 'rb'), #'fieldname2': 'file content', # file must have a filename 'fieldname3': ('filename', open('/path/to/file2', 'rb')), 'fieldname4': ('filename', 'file content'), }, data = { 'foo': 'bar' }, ) print response.status, response.content Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/urlfetch/1.0/
CC-MAIN-2018-22
refinedweb
126
51.89
Langton Ants in PyGame Many moons ago I implemented Langton Ants on a ZX Spectrum 48K, and I have been fascinated by it ever since. I thought it would be fun to implement it in PyGame. Langton ants are simple creatures. They live in a grid of squares that can be one of two colors, and follow these two simple rules. - Am I on color 1? Flip the square, turn 90 degrees right, move forward 1 square. - Am I on color 2? Flip the square, turn 90 degrees left, move forward 1 square. That is all they do. They don't ponder the meaning of life or current affairs, they just check the color of the square they are on and then turn and move. You would think that something this simple would quickly get in to a cyclical pattern, but it turns out that Langton ants like to make crazy complex patterns and don't repeat themselves. Humor me, while I write a Python script to test it. First thing we need to do is define a few constants for use in the script, as follows. GRID_SIZE = (160, 120) GRID_SQUARE_SIZE = (4, 4) ITERATIONS = 1 ant_image_filename = "ant.png" The grid will be 160x120 squares, with squares that are 4x4 pixels (so that it fits inside a 640x480 pixel screen). The value of ITERATIONS is the number of moves an ant does each frame, increase it if you want the ants to move faster. Finally we have the filename of an image to represent the ant. I will be using this image: . Next we import PyGame in the usual manner. import pygame from pygame.locals import * We will represent the grid with a class that contains a two dimensional list (actually a list of lists) of bools, one for each square, where False is color 1, and True is color 2. The AntGrid class is also responsible for clearing the grid, getting the square color at a coordinate, flipping a square color and drawing itself to a PyGame surface. I chose white for color 1 and dark green for color 2, but feel free to change it if you want something different. class AntGrid(object): def __init__(self, width, height): self.width = width self.height = height self.clear() def clear(self): self.rows = [] for col_no in xrange(self.height): new_row = [] self.rows.append(new_row) for row_no in xrange(self.width): new_row.append(False) def swap(self, x, y): self.rows[y][x] = not self.rows[y][x] def get(self, x, y): return self.rows[y][x] def render(self, surface, colors, square_size): w, h = square_size surface.fill(colors[0]) for y, row in enumerate(self.rows): rect_y = y * h for x, state in enumerate(row): if state: surface.fill(colors[1], (x * w, rect_y, w, h)) Now that we have a grid, we can create a class for the ants. The move function in the Ant class implements the two rules, and the render function draws a sprite at the ants location so we can see where it is. class Ant(object): directions = ( (0,-1), (+1,0), (0,+1), (-1,0) ) def __init__(self, grid, x, y, image, direction=1): self.grid = grid self.x = x self.y = y self.image = image self.direction = direction def move(self): self.grid.swap(self.x, self.y) self.x = ( self.x + Ant.directions[self.direction][0] ) % self.grid.width self.y = ( self.y + Ant.directions[self.direction][1] ) % self.grid.height if self.grid.get(self.x, self.y): self.direction = (self.direction-1) % 4 else: self.direction = (self.direction+1) % 4 def render(self, surface, grid_size): grid_w, grid_h = grid_size ant_w, ant_h = self.image.get_size() render_x = self.x * grid_w - ant_w / 2 render_y = self.y * grid_h - ant_h / 2 surface.blit(self.image, (render_x, render_y)) Finally in the script, the run function handles the guts of the simulation. It sets up the screen, creates the the grid object then enters the main loop. Inside the main loop there are event handlers so that you can drop ants with the left mouse button, clear the grid with the C key and start the simulation with the SPACE key. The remaining portion of the run function moves all the ants and renders the screen. def run(): pygame.init() w = GRID_SIZE[0] * GRID_SQUARE_SIZE[0] h = GRID_SIZE[1] * GRID_SQUARE_SIZE[1] screen = pygame.display.set_mode((w, h), 0, 32) ant_image = pygame.image.load(ant_image_filename).convert_alpha() default_font = pygame.font.get_default_font() font = pygame.font.SysFont(default_font, 22) ants = [] grid = AntGrid(*GRID_SIZE) running = False total_iterations = 0 while True: for event in pygame.event.get(): if event.type == QUIT: return if event.type == MOUSEBUTTONDOWN: x, y = event.pos x /= GRID_SQUARE_SIZE[0] y /= GRID_SQUARE_SIZE[1] ant = Ant(grid, int(x), int(y), ant_image) ants.append(ant) if event.type == KEYDOWN: if event.key == K_SPACE: running = not running if event.key == K_c: grid.clear() total_iterations = 0 del ants[:] grid.render(screen, ((255, 255, 255), (0, 128, 0)), GRID_SQUARE_SIZE) if running: for iteration_no in xrange(ITERATIONS): for ant in ants: ant.move() total_iterations += ITERATIONS txt = "%i iterations"%total_iterations txt_surface = font.render(txt, True, (0, 0, 0)) screen.blit(txt_surface, (0, 0)) for ant in ants: ant.render(screen, GRID_SQUARE_SIZE) pygame.display.update() if __name__ == "__main__": run() And thats our finished Langton Ant simulation. Have a play with it, then come back and explain to me how two simple rules can create such a complex pattern.Download langtonants.zip Update: Here's a screenshot! > ...explain to me how two simple rules can create such a complex pattern. because the rules don't exist in a vacuum. They exist in an enviromnent where the previous results of the rules continue to matter. These two simple rules could only produce a simple result if the whole playing field was wiped clean on every iteration. Or was that question rhetorical? :) I modified the code to put 1000 ants on the screen just to see what happened. Interestingly only some of the ants made real patterns. Most just "wiggled" a bit, but mostly stayed on the spot? for i in range(1,10000,10): ant = Ant(grid, int(x) + (i % 80), int(y) + (i % 56), ant_image) ants.append(ant) I think that would put ants directly on top of each other, i.e on the same cell, which causes a much simpler pattern. If you place two ants on the same cell with the original code, you'll see the same thing happens. Its only when there are an odd number of ants that you get them making patterns. What's the meaning of 90% left/right? From code it seems like 100% left/right. D'oh! That should be 90 degrees left/right. Thanks for pointing it out. Well this seems to be a simplification of Conwa'ys "Game Of Life"'s_Game_of_Life as James Paige said it's patterns are like that because of the chain of events. Anyway a nice example on pygames. PS: a question, which syntax highligting are you using? currently all the ones I have found for wordpress suck. I'm using 'iG:Syntax Hiliter', which does suck because it messes things up when you switch between the wysiwyg and the code editor. :-( Hey, cool script. I was researching this phenomenon on Wikipedia, which linked here for a python script. Thanks, it worked wonderfully! After messing with it, I decided to have some fun with it. Also, would you recommend using pygame for projects like this? How did this go?
https://www.willmcgugan.com/blog/tech/post/langton-ants-in-pygame/
CC-MAIN-2016-36
refinedweb
1,244
69.48
Third party libraries are often a necessity when building iOS applications. Carthage is a ruthlessly simple tool to manage dependencies in Swift. What about CocoaPods? At this point, many iOS developers might be wondering how Carthage differs from CocoaPods which is another dependency manager for iOS described a recent tutorial tutorial. Carthage emphasizes simplicity, described in this Quora answer by a Carthage collaborator. Unlike CocoaPods, which creates an entirely new workspace, Carthage checks out the code for your dependencies and builds them into dynamic frameworks. You need to integrate the frameworks into your project manually. How to install dependencies with Carthage Let’s build an app that will display a recent picture taken on Mars using this NASA API with Alamofire to send HTTP requests and SwiftyJSON to make handling JSON easier. I will be using Xcode 7.3 and Swift 2.2 for this tutorial. Start by creating a Single View Application Xcode project called PicturesFromMars. Select “Universal” for the device and enter whatever you want for the rest of the fields: The three dependencies we are using are Alamofire, SwiftyJSON and AlamofireImage to load an image from a URL. In order to install dependencies, we’ll first need to have Carthage installed. You can do this by installing it manually or via Homebrew by opening up your terminal and entering this command: brew install carthage Carthage looks at a file called Cartfile to determine which libraries to install. Create a file in the same directory as your Xcode project called Cartfile and enter the following to tell Carthage which dependencies we want: github "Alamofire/Alamofire" ~> 3.3 github "Alamofire/AlamofireImage" ~> 2.0 github "SwiftyJSON/SwiftyJSON" Now to actually install everything run the following in your terminal: carthage update --platform iOS This is where things start to really differ from CocoaPods. With Carthage, you need to manually drag the frameworks over to Xcode. Open your project in Xcode, click on the PicturesFromMars project file in the left section of the screen and scroll down to the Linked Frameworks and Libraries section in Xcode. Now open the Carthage folder in Finder: open Carthage Drag the frameworks in the Build/iOS folder over to Xcode as seen in this GIF: Now your Swift code can see these frameworks, but we need to make sure the device that the app is running on has them as well. - In your project settings, navigate to your “Build Phases” section. - Add a “New Copy Files Phase” - Go down to the “Copy Files” section - Under “Destination” select “Frameworks” - Add the frameworks you want to copy over as seen in this GIF: Now that you have the frameworks linked, head over to ViewController.swift and try importing the libraries to see if things are working: import Alamofire import AlamofireImage import SwiftyJSON You can see if everything builds correctly by pressing “Command-B.” Getting ready to use the libraries we just installed Before we can load images from Mars, we’ll need a UIImageView. Go over to Main.storyboard and add a UIImageView to your ViewController as seen in this GIF: Set the constraints so that the UIImageView takes up the whole screen. Click on the “pin” icon and at the top in the four boxes, enter 0 and click on each of the directional margins. Also update the frames as seen in this GIF: We have a UIImageView but no way to control it. Create an outlet for it in ViewController.swift called marsPhotoImageView. You can do this several different ways, but I usually do this by opening the “Assistant Editor” with one screen having Main.storyboard open while the other displays ViewController.swift. While holding the “Control” key, click on the UIImageView in main.storyboard and drag the line over to ViewController.swift. Here is another GIF demonstrating how to do that: The app will grab a picture from Mars taken on the most recent “Earth day” from NASA’s API for the Curiosity Rover and will load that image in our UIImageView. Images are usually not available right away so let’s grab images from 5 days ago to be safe. We’ll need a quick function that generates a string that is compatible with this API. In ViewController.swift add this new function: func getDateString() -> String { let calendar = NSCalendar.currentCalendar() let yesterday = calendar.dateByAddingUnit(.Day, value: -5, toDate: NSDate(), options: []) let components = calendar.components([.Day , .Month , .Year], fromDate: yesterday!) return "\(components.year)-\(components.month)-\(components.day)" } With this taken care of, we can send a request to the Mars Rover API, grab an image URL and load it in the marsPhotoImageView. Handling HTTP requests with Alamofire and SwiftyJSON Alamofire and SwiftyJSON are installed and imported in our code. All we need to do now is send a GET request using Alamofire to receive an image URL that we will use to load our UIImageView’s image property. Replace your viewDidLoad with the following code: override func viewDidLoad() { super.viewDidLoad() let dateString = getDateString() Alamofire.request(.GET, "", parameters: ["api_key": "DEMO_KEY", "earth_date": dateString]) .responseJSON { response in if let result = response.result.value { let json = JSON(result) if let imageURL = json["photos"][0]["img_src"].string { // Replace "http" with "https" in the image URL. let httpsURL = imageURL.stringByReplacingOccurrencesOfString("http", withString: "https") let URL = NSURL(string: httpsURL)! // Set the ImageView with an image from a URL self.marsPhotoImageView.af_setImageWithURL(URL) } } } } Notice that we are replacing the http in the URLs with https because we can only send requests to secure URLs by default. Run the app in the simulator and check out the latest picture from the Mars Rover! Building awesome things is so much easier now There are a ton of APIs out there that you now have access to using Carthage to manage dependencies. Twilio has some awesome APIs if you want to add Video chat or in app chat to your iOS app. I can’t wait to see what you build. Feel free to reach out and share your experiences or ask any questions. - Twitter: @Sagnewshreds - Github: Sagnew - Twitch (streaming live code): Sagnewshreds
https://www.twilio.com/blog/getting-started-with-carthage-to-manage-dependencies-in-swift-and-ios-html
CC-MAIN-2019-51
refinedweb
1,007
64
Results 1 to 3 of 3 Thread: Itunes Import Issues - Itunes Import Issues Hello fellow Mac brothers (and sisters out there), I have recently just bought a 24" iMac and have enjoyed it immensely thus far. However, I recently have run into an issue that I cannot overcome based on my lack of knowledge of the OS. I, how would I say "shared" some music files from the internet and when I went to import them, it only imported 2-3 songs of the album and refused to import the rest. I do not know how to solve this, please help!- "Shortcuts make long delays and inns make longer ones" - Member Since - Sep 30, 2007 - Location - UK - 146 - Specs: - imac 20" 2GHz Intel 2GB RAM, iPod Classic 80Gb, iPhone How are you importing? are you dragging & dropping files/folders directly into your itunes library or are you importing via "File, Add To Library....etc?" P.s if this refers to illegally downloaded stuff I'd look elsewhere as its against forums rules here. I am dragging and dropping them in.- "Shortcuts make long delays and inns make longer ones" Thread Information Users Browsing this Thread There are currently 1 users browsing this thread. (0 members and 1 guests) Similar Threads Entourage folder import issues to Outlook 2001By mrserv0n in forum OS X - Apps and GamesReplies: 0Last Post: 04-19-2012, 12:36 PM outlook 2011 for Mac .PST import issuesBy barnett17 in forum OS X - Apps and GamesReplies: 6Last Post: 01-20-2012, 08:14 PM iMovie import issuesBy iam537 in forum Movies and VideoReplies: 0Last Post: 12-12-2010, 07:14 AM import issue: only showing imovie 08:last import ... unable to locate previous importBy DAIDAI in forum Movies and VideoReplies: 0Last Post: 12-25-2008, 02:03 PM ITunes ImportBy altyson in forum Music, Audio, and PodcastingReplies: 1Last Post: 10-22-2005, 07:44 PM
http://www.mac-forums.com/forums/ipod-hardware-accessories/85595-itunes-import-issues.html
CC-MAIN-2016-30
refinedweb
317
63.32
> In at least Perl, PHP, and Java, you don't have to do anything special > to merge components in a single namespace from multiple parts of the > class/include/autoload path. Not true. In all three languages, you have to declare in the module what package it belongs to. So there is something special to do. > It's for this reason that all packages being namespaces doesn't bother > me for the term. All packages *should* be namespace packages, pretty > much. It's the *non* namespaceyness of Python's default packages that's > broken, not the term. ;-) Python packages have been namespaces since day 1 (as are modules). > Actually... here's an interesting idea. Suppose that we define the > rules so that any directory containing any file with an importable > extension is a namespace package... *but*, if one of those directories > contains an __init__ module, that directory will be placed first on the > package __path__. "... is a package" (not: "namespace package") I'd go further: any directory with the package name could constitute a portion of the package. With your approach, you'd need a file with an importable extension in each portion of the "zope" package, right? Regards, Martin
https://mail.python.org/pipermail/import-sig/2011-July/000254.html
CC-MAIN-2020-29
refinedweb
200
72.36
Code. Collaborate. Organize. No Limits. Try it Today. P0mpey3 wrote:The baby spelling is getting annoying now. Nagy Vilmos wrote:almaspaprika almapaprika public class SanderRossel : Lazy<Person> { public void DoWork() { throw new NotSupportedException(); } } Sampath Lokuge wrote:Become a Social Developer! Argonia wrote:phase Social Developer Duncan Edwards Jones wrote:this is also why Cuban cigars are so expensive Ravi Bhavnani wrote:They're freely available in Canada. Nish Sivakumar wrote:113K, Google's is 126K, Oracle's 113, Amazon has 109K, Apple pays a nice 130K, Facebook 123K, and here's a surprise, Walmart pays 113K average Rage wrote:This is a lot of money !! $110K are about €80K, this is middle management salary level in the area (Germany), or high management in France. What are these people doing ? Are the salaries that high in the US ? Tim Carmichael wrote: they didn't want to work with 'old' technology Tim Carmichael wrote:when they can work in an office building in a major city Tim Carmichael wrote:So, for me, it was a win-win Dan Neely wrote: I could care less* Dan Neely wrote:If you're going to be an annoying pedant you should be obligated to read the footnotes first; Nish Sivakumar wrote:Well, that may or may not be so. General News Suggestion Question Bug Answer Joke 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/Lounge.aspx?fid=1159&df=90&mpp=25&noise=3&prof=True&sort=Position&view=None&spc=Relaxed&select=4526050&fr=14681
CC-MAIN-2014-23
refinedweb
243
58.01
Chad, yes, that's on the list of things to document. The changes throughout the code are extensive and it's going to take a while to get everything documented. On Wed, Dec 14, 2011 at 12:24 PM, Chad Lung <chad.lung@gmail.com> wrote: > I think something useful for the documentation would be the namespace > changes, how the old namespaces have changed to new ones, etc. I know the > other night I spent a fair bit of time trying to find out where classes had > been moved/renamed. > > > > On Wed, Dec 14, 2011 at 11:50 AM, James Snell <jasnell@gmail.com> wrote: > >> We certainly could just create a trunk off the abdera2 path. Biggest >> thing right now tho is I need to finish getting the documentation and >> test cases updated. >>
http://mail-archives.apache.org/mod_mbox/abdera-user/201112.mbox/%3CCABP7Rbeuv5z8LpWZ=PwoCADzD-eVaH4bcOVwPx4=UAAbAbLLOw@mail.gmail.com%3E
CC-MAIN-2018-34
refinedweb
133
72.76
This was a question on a quiz we had in my programming course. The answer is 70 as the output, but I'm having trouble understanding why. Could someone please tell me, step by step, why that comes out to be the output? Code : 1. public class MysteriousClass { 2. public static void main(String[] args) { 3. int i = 20; 4. int b = m2(i); 5. System.out.println(b + i); 6. } 7. public static int m1(int i){ 8. int n = 0; 9. while (n * n <= i){ 10. n++; 11. } 12. return n - 1; 13. } 14. public static int m2(int a){ 15. int b = 0; 16. for (int n = 0; n < a; n++){ 17. int i = m1(n); 18. b = b + i; 19. } 20. return b; 21. } 22. }
http://www.javaprogrammingforums.com/%20java-theory-questions/27592-java-method-question-printingthethread.html
CC-MAIN-2017-47
refinedweb
129
90.05
OK before anyone says that this is homework, let me say that this is homework. I understand the question and have even written the code. The question is. Write A Program to write to a file, read from that file and get the number of lines and the number of words. The number of lines works every time, but the number of words works only for the last line inputted. We have not learnt vectors or using namespace std; yet so they are out of the question. If I skip the whole inputting text part, the program shows me the number of words in the file correctly.If I skip the whole inputting text part, the program shows me the number of words in the file correctly.Code:#include<fstream.h> #include<iostream.h> #include<conio.h> void main() { //Inputting text part char text[50]; ofstream out; out.open("c:/country.txt",ios::app); cout<<"\nEnter text\n"; cin.getline(text,50); out<<text<<"\n"; out.close(); //Outputting and calc text part ifstream inp; const int n=80; int nol=0,now=0; //nol is number of lines and now is number of words char line[n],x[n]; inp.open("c:/country.txt"); cout<<"\nDisplay all records\n\n"; while(inp) { inp.getline(line,80); cout<<line<<endl; nol++; strcpy(x,line); for(int i=0;i<80;i++) { if(x[i]==' '||x[i]=='\n') { now+=1; } } } inp.close(); cout<<"\nTotal number of lines = "<<nol-1<<"\n"; cout<<"\nTotal number of words = "<<now-1<<endl; getch(); } If I dont skip the inputting text part, the program shows me the number of words in the last inputted line only. Please tell me what I am doing wrong. EDIT: Forgot to say thanks in advance
https://cboard.cprogramming.com/cplusplus-programming/121483-need-help-reading-file.html
CC-MAIN-2017-13
refinedweb
294
74.59
On Jan 29, 2010, at 10:27 PM, Tarek Ziadé wrote: . Actually, my version number is a static assignment in __init__.py: __version__ = '2.0.2' and I just manually bump that with every release. I'd be just as happy to bump it in setup.cfg (maybe more!) as long as there was an API that I could add to __init__.py to assign it to my module's namespace, e.g. in mypkg/__init__.py: from distribute.resources import get_version __version__ = get_version('mypkg') I don't much care how that's spelled. The important things are: * One place to bump version numbers * Available from setup.py without importing from the package * Available from the package's namespace -Barry -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 835 bytes Desc: not available URL: <>
https://mail.python.org/pipermail/distutils-sig/2010-January/015436.html
CC-MAIN-2016-36
refinedweb
142
70.5
Contents tagged with Python Functions map, zip and lambda in Python Hello everybody, today I want to describe three elements of Python: map, zip, lambda and *. Zip and * The first step that I want to describe is zip and * usage. Take a look at the following code: a = [5, 6] b = [7, 8] c = zip(a,b) print(*c) How do you think, what will be output, if I'll tell you that zip function zips arrays? If your guess is (5, 6) (7, 8) then unfortunately you are wrong. Output will be the following: (5, 7) (6, 8). I suppose that zip name was chosen because as usually zippers on clothes as usually vertical. Zip functions "zips" elements by columns, like presented on the picture: Now one more question, what is purpose of * ? It tells to Python interpreter to … more How to read little endian file of floats in Java Hello everybody, today I want to document another issue that took from me plenty of time. Recently I've used following code in Python in order to save array of numpy numbers: import numpy as np newImage = ...some way of getting array np.ndarray.tofile(newImage, newFn) But when I tried to get that content in Java code, I faced issue that my inputs where unreadable by Java. After spending some time over net I've found that Python uses little endian encoding, while Java uses another encoding for saving floats. So my research of little endian gave me the following code result in java for reading little endian: InputStream inputStream = null;DataInputStream dataInputStream = null; … more
https://blog.zaletskyy.com/Tags/Python
CC-MAIN-2018-34
refinedweb
267
59.84
Building up an XMonad config and I've hit another road block I can't figure out. I haven't made many changes, just mod key changes and added somethings so XMobar will display properly. OTher than that I have a brand new XMonad config. The issue i'm having is that now I want to change the terminal from xterm to alacritty. My config file import XMonad import Data.Monoid import System.Exit import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Util.Run(spawnPipe) import XMonad.Util.EZConfig(additionalKeys) import XMonad.Util.SpawnOnce import System.IO import qualified XMonad.StackSet as W import qualified Data.Map as M main = do xmproc <- spawnPipe "xmobar" xmonad $ docks defaultConfig { manageHook = myManageHook <+> manageHook defaultConfig -- make sure to include myManageHook definition from above , layoutHook = avoidStruts $ layoutHook defaultConfig , logHook = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor "green" "" . shorten 50 } , modMask = mod4Mask -- Rebind Mod to the Windows key } -- The preferred terminal program, which is used in a binding below and by -- certain contrib modules. -- myTerminal = "alacritty" -- Whether focus follows the mouse pointer. myFocusFollowsMouse :: Bool myFocusFollowsMouse = True -- Whether clicking on a window to focus also passes the click to the window myClickJustFocuses :: Bool myClickJustFocuses = False -- Width of the window border in pixels. -- myBorderWidth = = "#dddddd" myFocusedBorderColor = "#ff0000" ------------------------------------------------------------------------ -- Key bindings. Add, modify or remove key bindings here. -- myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $ -- launch a terminal [ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- launch dmenu , ((modm, xK_p ), spawn "dmenu_run") -- launch gmrun , ((modm .|. shiftMask, xK_p ), spawn "gmrun") -- "xmonad --recompile; xmonad --restart") -- Run xmessage with a summary of the default keybindings (useful for beginners) , ((modm .|. shiftMask, xK_slash ), spawn ("echo \"" ++ help ++ "\" | xmessage -file -")) ] ++ -- -- mod-[1..9], Switch to workspace N -- mod-shift-[1..9], Move client to workspace N -- [((m .|. modm, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ -- -- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3 -- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3 -- [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] ------------------------------------------------------------------------ -- Mouse bindings: default actions bound to mouse events -- myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $ -- mod-button1, Set the window to floating mode and move by dragging [ ((modm, button1), (\w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)) -- mod-button2, Raise the window to the top of the stack , ((modm, button2), (\w -> focus w >> windows W.shiftMaster)) -- mod-button3, Set the window to floating mode and resize by dragging , ((modm, button3), (\w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)) -- you may also bind events to the mouse scroll wheel (button4 and button5) ] ------------------------------------------------------------------------ -- = tiled ||| Mirror tiled ||| Full where -- default tiling algorithm partitions the screen into two panes tiled = Tall =? "desktop_window" --> doIgnore , resource =? "kdesktop" --> doIgnore ] ------------------------------------------------------------------------ -- Event handling -- * EwmhDesktops users should change this to ewmhDesktopsEventHook -- -- Defines a custom handler function for X Events. The function should -- return (All True) if the default handler is to be run afterwards. To -- combine event hooks use mappend or mconcat from Data.Monoid. -- myEventHook = mempty ------------------------------------------------------------------------ -- Status bars and logging -- Perform an arbitrary action on each internal state change or X event. -- See the 'XMonad.Hooks.DynamicLog' extension for examples. -- myLogHook = return () ------------------------------------------------------------------------ -- Startup hook -- Perform an arbitrary action each time xmonad starts or is restarted -- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize -- per-workspace layout choices. -- -- By default, do nothing. myStartupHook = return () ------------------------------------------------------------------------ -- Now run xmonad with all the defaults we set up. -- Run xmonad with the settings you specify. No need to modify this. -- --main = xmonad defaults -- A structure containing your configuration settings, overriding -- fields in the default config. Any you don't override, will -- use the defaults defined in xmonad/XMonad/Config.hs -- -- No need to modify this. -- defaults = def { -- simple stuff terminal = myTerminal, focusFollowsMouse = myFocusFollowsMouse, clickJustFocuses = myClickJustFocuses, borderWidth = myBorderWidth, modMask = myMod } As you can see I changed the lines for myTerminal to alacritty and that didn't work. So then I decided to hard code it into the key bindings, and that didn't work either. So then I was like screw it, I'll make a completely new key binding and delete the other one. That wouldn't work either. At this point I have a key binding that looks like this to launch spotify: , ((modm, xK_e ), spawn "spotify") If i'm doing that correctly then Mod + e should open spotify. But nothing happens. Any help would be greatly appreciated. Offline You have a main function at the top. Everything after that is dead code because this main function doesn't use any of it. Remember you're writing a Haskell program, not setting values for predefined keys in a config file. There's another main function (commented out) near the bottom. That one uses all the myTerminal/myLogHook/... through the "defaults" config defined at the bottom. "defaultConfig" is basically the same as "def"; see … onfig.html. You need one main function and it should run "xmonad" at some point with a config as its only argument. You can build this config however you want. Careful copy/pasting might work, but learning at least a bit about Haskell's ("do"/record/function/operator) syntax should help. xmonad is also said to be a framework to build your own WM; if you won't/can't take full advantage of that, you might consider a more user-friendly/better documented WM. (I actually plan to ditch xmonad myself, even though I know Haskell well enough.) Most allow at least basic customization, I think -- I haven't actually tried many alternatives yet. Offline Appreciate that. I had some work to get done so I went back to qtile. I do need to sit down with it one day and configure it from scratch. I think I was copying and pasting too much code and not actually understanding what it did. I'll come back to this. Thanks. Offline
https://bbs.archlinux.org/viewtopic.php?id=262823
CC-MAIN-2021-10
refinedweb
998
60.72
view raw When I attempt to create a 'BJ_player' object: player = BJ_player(name, number_chips) TypeError: init() takes exactly 2 positional arguments (3 given). class Hand(object): """A hand of playing cards""" def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: rep = "<empty>" return rep class BJ_hand(cardsmodule.Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__() #self.name = name self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() You defined an __init__ method that only takes one argument (plus self): class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): # ^^^^^^^^^^^^ There is no parameter for name, but you are trying to pass that in: player = BJ_player(name, number_chips) # ^^^^ ^^^^^^^^^^^^ Python doesn't look to all base __init__ methods for you; it'll only 'see' BJ_player. If you wanted to pass in a name value for BJ_hand.__init__, then BJ_player.__init__() must accept that as an argument. You can then pass it on via the super().__init__() call: class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, name, number_chips): super(BJ_player, self).__init__(name) Note how the name parameter from the method is now passed on in the chain.
https://codedump.io/share/rzHxL7I0qe6T/1/method-inheritance-issue
CC-MAIN-2017-22
refinedweb
251
53.68
Texture mapping Normal mapping Bump mapping Parallax mapping ( Offset mapping ) Parallax occlusion mapping ( Relief Mapping ) Dynamic Cube Environnement Mapping Shadow mapping Specular... Texture mapping Normal mapping Bump mapping Parallax mapping ( Offset mapping ) Parallax occlusion mapping ( Relief Mapping ) Dynamic Cube Environnement Mapping Shadow mapping Specular... I suggest you making a realtime 2D clock in OpenGL :) Thanks, it runs smooth and fast now and there is no lag. However, I checked my task manager, while running the program, and what I saw is that it used 90%-98% of my CPU O.o Is it normal? Or I... Actually I'm D: Look at the WinMain, if( !GL_drawit() ) { done = true; } else { SwapBuffers( hDC ); } That is not needed, since you cannot resize the window, I have disabled it :D Ah, I got it working: #include "glab.h" #define WINDOW_NAME "Glab - OpenGL - Clock" #define WINDOW_CLASS "glab" #define WINDOW_STYLE (WS_OVERLAPPED | WS_BORDER | WS_CAPTION |... Hello. I'm having a problematic problem D: The problem is that, I draw a triangle and I have the code written so if the mouse moves, then a value is sent to glRotatef(), which rotates... Thank You! :biggrin-new: At first it didn't work, so I re-wrote the code and it works! After I have learned OpenGL, should I study OpenGL 3.3 or OpenGL 4.2 then? :whistle: Who is interested:... I'm trying to make my first polygon, however seems that the dream is broken. Because I wrote a code, complied it and voila ... the triangle is not displayed :( Can somebody say what is wrong...
https://www.opengl.org/discussion_boards/search.php?s=afec217a8fc48dd6e288f72b0eb377c9&searchid=1701878
CC-MAIN-2016-30
refinedweb
257
64.3
In the last little while we started to receive the same error/bug report coming through the Error Reporting functionality within LandlordMax. The error coming back was: Error refreshing logo image javax.imageio.IIOException : Unsupported Image Type Now this seemed weird to us, because we had all kinds of validations on which types of images to accept within LandlordMax. Before I proceed, to give you some context, LandlordMax has the ability to import pictures (jpg’s and gif’s only) into it’s database for 2 things. You can import an image for your logo/letterhead which will appear at the top of all your reports, which is great for the property management companies that purchase LandlordMax (about 50-65% of our customer base). The other area where you can add pictures is for your tenants, buildings, and units. This is a new feature that many people requested and that we added with version 2.12. Getting back to this bug, we added all kinds of validation checks when you import images, such as the file extension (does it end with .gif, .jpg, .jpeg, etc.). We also added validations where it tries to first read the file, in case someone tried to manually change the file extension. And so on. Basically a lot of validation checks! Initially we received some error reports such as the one listed above, and we found that we had missed a few potential validation checks, which we added with one of the patches (version 2.12a). That did significantly reduce the number of error reports, but they didn’t fully go away. Of course not everyone upgrades right away, but with time it seemed to dwindle down very significantly to just a few random ones. However, like I had just said, it didn’t completely go away which we don’t like to see. Yesterday, we were finally fortunate enough to have someone also send us their email address (an optional parameter in the Error Reporting Dialog Window) along with the Error Report. This was great for us in that we finally had a repeatable test case for this very elusive bug that we couldn’t replicate, and that was extremely rare. We immediately contacted this customer and had her send us the image she used for the logo/letterhead as we tracked it down to a specific line in the code. We got the image, saved it, and added it to our test database. No problems, no errors, no issues! What? That didn’t make sense. We then contacted her saying we couldn’t reproduce the error and we would be very appreciative if she could send us her database so that we could investigate it in detail. She obliged us and when we immediately tried it we got the exact error. It didn’t make any sense… So the next step was to manually extract the image from her database into an image file and try that. I know she already sent us the image, but you never know. We extracted the image and opened it up with an image viewing tool without any issues. Very confusing… This image opens up in our image viewing software but not in LandlordMax. So we dug deeper. Nothing. I personally spent several hours looking at this issue with no luck. So onto the internet and Google Search. After another hour or two, I found a weird bug report from Sun (Bug ID# 5100094). This was the key to the issue. It appears that the Java language doesn’t support JPG images that were saved in CMYK mode and threw this exact exception. Like most people, I know what a JPG image is, but I don’t know the details of how it’s encoded, nor do I really want to know. Now I was forced to find out more about this. Without getting into too many technical details, it appears that JPG’s can be encoded from a number of modes, with RGB being the most common by far, or at least that’s my understanding. CMYK mode exist, but it’s not very commonly used. Therefore I quickly checked the images, and low and behold, the image I had extracted from the database was encoded in CMYK! But what about the image she had sent me before? Well I did some further investigation, and to show you just how prevalent RGB mode is, the image she had sent me was in RGB mode. I don’t know if it’s the browser that converted the image or what, but when I did “Save image as…” it saved it in RGB mode. I did some further testing, and when I saved the image in CMYK mode, both browsers weren’t always happy with the image (depending on how exactly I saved it). That was very surprising to me. So it wasn’t only LandlordMax that had difficulties with this image mode sometimes, the major internet browsers also did! As soon as I converted the image to RGB mode, everything went smoothly and with no issue. This was probably the most brutal bug I’ve ever encountered (omitting concurrency issues and such and just limiting it to straight bugs). It wasn’t an issue with the software, so it wasn’t possible to track down in the code. It was an issue with the image file and the programming language’s support of the image type. The error message wasn’t very indicative of the error as it usual is. And I also can’t blame the Java language either if both the major internet browsers had difficulties with this image mode. So now what are the options for LandlordMax? This particular mode is not supported by the programming language. Do we look for a third party component and buy it? This is a very expensive solution, it costs a lot of money, not to mention the integration time (which is probably going to cost more than the component)? Will it have other bugs? Testing costs… For the percentage of users, I don’t think this is a viable solution. Right now I’m personally leaning towards doing an extra validation and trying to invisibly render it from the file directly before accepting it. I’m leaning towards it, I’m not satisfied with it yet as it will have a lot of performance overhead, every new image will have to be rendered before being accepted… Imagine if you add 100 pictures for your building unit and each one has to be rendered. Rather than take a few seconds to a minute to import, it could now take 5-10 or more minutes easily. Is it worth it? Could I do a check after the fact, when trying to render it? That’s a possible solution also but it opens up a whole other can of worms… The reality is that we don’t yet have a solution to this issue. We’re going to further investigate our options and definitely solve it for the next major upgrade, which is now expected to be out next month rather than this month. This is probably the most challenging bug I’ve encountered simply because it was absolutely unobvious what the issue was, there was no way to track it down in the code, and there is no real, or obvious, solution to it. For those of you who don’t program, I hope this gives you an idea of the effort that goes into producing a software like LandlordMax Property Management Software. And although this is probably the most challenging bug I’ve ever encountered, it’s also one of the most interesting because of its difficulty! Discuss (30) The most challenging bugs I’ve had have always been ones where reproducing them was the most difficult step. Why not detect that very image type (or have a list of unsupported image types), and convert it to something supported via ImageMagick? I am glad I could be of help figuring out this most difficult and interesting bug. Again, thanks for you help, and the program has proven to be very useful thusfar. Absolutely, often finding out how to reproduce a bug is much more challenging than fixing it! As for image types, that’s exactly what we’re doing. We accept JPG and GIF image types. However if it was encoded using in one specific mode (out of over 20 different ones) then it won’t work. And the key is that you can’t detect this with the built in libraries without rendering it (the image type says that it’s correct), which means you either have to get another third party library or understand the details of the image types. I don’t want really want to understand the details of how a JPG is encoded, LandlordMax’s core functionality is not as an image viewer, it just ads this ability. This doesn’t mean to say that we don’t care, it just means that we won’t provide support for every single image type. We will therefore limit the software to accepting only the major image types. I’d instead rather focus our energies on enhancing the software’s core features and performance. And yes Katy, you were very instrumental in figuring out this bug! Thank you. Why don’t you import the file to a ‘blob’ field? This way, your response time stays the same. Afterwards, you can move the image to the real field using a batch or a fork. For those of you that don’t program. A batch process is launched at predefined times, mostly when the server workload is lowest. A fork is a parallel process launched when importing the file. .. hmm and it isn’t possible to probe for the CMYK mode inside the file ? I have to do image processing as well (I need to send the correct HTTP content-type headers for an image without relying on its extension), and personally use probing as a method te determine the file type.. for example, if the binary data starts with 0xFF 0xD8 0xFF it is most likely a JPEG file.. I can only assume there must be some kind of header for CMYK mode too, whose information is “out there” somewhere.. 🙂 Of course, the definitive test to know if you’re able to render an image is just to try to rendder it. But you can avoid this, and other corner cases, just by inspecting the image metadata that’s at the beginning of the JPG file. The problem is, the JPG format is very complex and you’ll be probably missing a few other exceptions. But at least you don’t need to render the image. Weird. I’ve come across that exact same problem within in the last few days but within my Delphi app. It had me scratching my head for a few hours too. This is great feedback! I’ve also received several personal emails with additional information. Thank you! Please find below my responses to your latest comments: GUI Junkie: Thank you for the suggesion, however just to let you know LandlordMax is a standalone desktop application (A Swing application). Becuase of this, people expect quick responses. We don’t have the options of batching it, pushing it to the middle of the night, etc. Honestly, if this was a web application, this issue would be a lot simpler and we’d have more options. But that’s life. Leon Mergen and A reader: You guys are right, I could manually go into the JPG’s metadata and figure out what’s going on. But again, the issue with this is that I’m not really interested in learning the details of how a JPG is encoded. Our primary focus is not displaying JPG’s, it’s about property management software. We’re only willing to support the primary image formats, not the exceptions. For example if we added email support into the software, we wouldn’t want to create another Sendmail (would you?). We might just want enough capabilities to support sending emails. And just like “A reader” suggested, the JPG format is very complex and we’d probably end up missing some other exceptions, or possibly make other mistakes. The cost to benefit ratio is just not there. My prefered solution would be to quickly and easily detect these types of JPG images and let the user know that the software won’t import the image because of that reason. Simple, quick, and it will satisfy 99.999% of our customers. Remember they’re not buying LandlordMax to view their pictures, their buying it to manage their real estate properties, and storing pictures and their logo is only a small part of that. John: It’s interesting that Delphi also has this issue. I’ve also heard since putting out the article that other programming languages have this same issue with that JPG mode. As well, some libraries don’t like the Photoshop JPG preview mode either. Just a heads for those of you starting out with this issue. Maybe a solution is to have this as a prominent FAQ item: “If you get this error … then you may be trying to save an RGB file in CMYK mode (which is mainly used for printing). Try saving it in ‘Image -> Mode -> RGB Color’ mode (if using Photoshop) and then loading it into our program.” One quick solution that is likely to satisfy both development time constraints and user interaction concerns might be to add an error capture around where this error happens and add a short summary of why the error is likely happening and perhaps a link to a help file or web page that explains how save in RGB. The help file/web page should have a very short summary and a simple solution using software your clients likely have on hand (I’m assuming MS Paint can fix this pretty easily). Add a link to more detailed information, either here or the resources you found, and you’re golden. Your clients aren’t vested in using CYMK over RGB, and they have control over the file anyway (having been the ones to add it to the database). Your clients can chose the level of detail they want about the error. That way your clients are trained in the issue, it becomes non-business stopping, and the burden of working around this issue is redistributed to the benefit of all. You might look into libjpeg. It’s FreeBSDed. Maybe it handles CYMK. It’s in C but you could probably make something you could call out to to convert the image. Just a suggestion. Sorry, maybe I wasn’t clear about the “image types” thing, or maybe I’m being obtuse. There is a library called “ImageMagick” () that you can use, that will not only tell you anything you want to know about most any image you can feed it, it can also convert between any two formats, including converting between jpeg cmyk and jpeg rgb. I know, because I tried. Alas, the java bindings are not complete. That might be a problem for you, I guess… The flag for the color mode is hidden somewhere in the file, so it is only a matter of time/effort to find it once you get the file uploaded: a) spend another day to learn the jpeg specs; b) grab some open source code that works with the jpegs and cut this time by half; c) find someone who already knows jpegs well to write a simple check code for you (i.e. put in some of your money instead of your time). If you are unsure of the quality of the new check (e.g. scared of false positived), use it as a pre-step for the rendering procedure: this way, only “suspicious” images will have to be rendered, with way less overhead. Andrew, Have you read the JPEG spec? Or, I should say, tried to? Because I have. Here’s a link: . It is, by far, the most difficult to understand non-WS-* spec that I have ever come across. (And I’ve probably read more than my share of specs). All I wanted to do at one point was to write a program to add a comment to the exif metadata of a jpeg file, and it proved to be darn near impossible. He’s looking at more than a day to write that code, and he’s likely to never actually have code that is correct. Normally I’d agree with you, but in this case, the spec is so horribly broken that it’s not worth the pain. I encourage a bit of reading. Try reading that spec, or here’s Mozilla’s jpeg renderer. You might be surprised at how big a problem this is. -Bill Mill bill.mill at gmail.com Sorry, I gave an incorrect reference above: My memory was off, I was trying to read the exif spec at . The JPEG spec is ISO 10918-1, and is not available online. (You can buy it at if you’re so inclined.) It’s still wildly complex, and I still welcome you to tell me, from the Mozilla code, some easy way of figuring out the CMYK-ness of a file, for some large subset of JPEG images. Sorry for the factual errors. Ok, no batch. What about parallel processing? Java does know how to fork. Hi everyone, This is great feedback! The comments you’ve put (and links) really help to put into perspective just how big an issue this is!!! My responses: Barney and Jacob: This is probably close to what I’ll end up doing. The only issue is that if I don’t pre-render it, I won’t know about the error until after it’s trying to display it. Now in a desktop application, I can either put an “X” type image (or something to show it failed) and allow the user to continue with that image (or delete it). That or I attempt to pre-render it… I’m strongly leaning away from checking the image file or converting it. So is the performance hit worth it to pre-check? I’m starting to think no since it’s a small percentage of people who will encounter this issue and it’s easily fixable by the client with the error message and the “X” image replacement (with some good documentation, etc.)… I’ve developed both server and desktop applications, and I’m not sure where you’re experience lies, so please take this with the utmost respect. In GUI applications, you don’t want your application firing off in the background a process to later pop-up an error window that can affect your current work. If you look, even a virus scan locks you out of many tasks while it’s performing the scan (you can’t change the scan parameters in the middle of a scan). The issue is that if I fork off a thread, the user saves the building say, then what happens if there’s an error in the imported images? What if they change the values? It’s better to put a modal progress bar while it’s loading. Of course the faster you can make things happen, the happier your user is. This is generally what desktop users are use to. In a server environment, you have a lot more leeway in what you can do. People’s expectations are also very different on how a web application and a desktop application behave. For example, in a desktop application, anything that takes more than 2 seconds makes the user think your program has frozen or is extremely slow. In a web application, most web pages take more than 2 seconds to load and transmit! Think about Amazon.com, it takes many seconds to render almost any page. This would be unacceptable in a desktop application… User expectations also go the other way too. In a web application, you can’t lock out a user from making changes from one screen to another (one web browser to another). You need to manually do those checks. In a desktop application, all you need to do is make the GUI component modal (or possibly add a progress bar if it’s long enough). Different presentations, different rules. This is also why it’s very difficult for many people to move from a web application to a desktop application. Few people can, the rules are different, not to mention the libraries 😉 Also, until recently, most web application were action driven, whereas desktop applications are event driven. I’m slowly seeing this change with new Java frameworks like JSF, which is great! The others: I’m strongly leaning against manually converting the image, or manually checking for the flags in the meta-data. I think Bill Mill said it best, just look at the specs! We’re not an imagine processing company, nor do we want to be, so why spend an innordinate amount of time on it. And after look at how Mozilla renders it, and knowing that the very same image that I was testing with failed in Mozilla, I know when it’s time to look elsewhere. Yes it failed in the Mozilla code!!! As well, just to let you know, we’re using the main Java librairies to render it. This is not our code, this is a core language library which has this known issue in it. Mozilla (FireFox) also doesn’t have it fully implemented. Internet Explorer also had some issues with it. Looking at the scale of this JPG issue, and that only those software specialized in images have it working (and not all of them, I found some open source imaging solutions that also described this very same issue), I don’t think we should be taking it head-on. The cost to benefit is nowhere near the return on investment!!! Thanks Bill, you showed just how complex this issue is! Let me quote: “Right now I’m personally leaning towards doing an extra validation and trying to invisibly render it from the file directly before accepting it.” Now, your objection to yourself is “I’m not satisfied with it yet as it will have a lot of performance overhead” and that is something you might consider doing with a fork. For example. When accepting an image, you 1) show the reception of the image(s) and it’s status. 2) fork the validation process, this process can update the status of the image. This way, you get what you want. Speed & Validation. I don’t know whether you can reduce the thread priority of the fork so it doesn’t slow down your desktop app. I agree that the JPG format is highly complicated. One thing that is not complicated is the header. It is very easy to read the header and with the header, you can tell if an image is CYMK or not. Here is some code you can use.(Needs a little cleaning up): import java.awt.Graphics; import java.awt.Image; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.JFrame; rest of code: for(int i=0;i Sorry, forgot about entities: import java.awt.Graphics; import java.awt.Image; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream;<imageData.length – 1;i++) { if((imageData[i] & 0x000000ff) == 0xff && (imageData[i + 1] & 0x000000ff) == 0xc0) { startOfHeader = i; break; } } //if image type = 4 CYMK mode is used int imageType = bout.toByteArray()[startOfHeader + 9]; System.out.println(“type = ” + imageType); im = ImageIO.read(new ByteArrayInputStream(bout.toByteArray())); setSize(im.getWidth(null), im.getHeight(null)); } public void paint(Graphics g) { g.drawImage(im, 0, 0, this); } public static void main(String args[]) { Test t = new Test(); try { t.loadImage(new FileInputStream(“any_image.jpg”)); t.setVisible(true); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } catch(Exception e) { e.printStackTrace(); } } } Hi Mark, Thanks for posting all the code! Do you know how thoroughly this code has been tested? The reason I ask is because from what I’ve heard the way the meta data is encoded can be slightly different (the specs are a little ambigiuous at times). From I see in your code, you’re expecting the CMYK flag (aka. image type flag) to appear at a specific location within the header block (9 bytes from the start of the header)… From what I understand, Photoshop for example can also throw in a thumbnail within the image which can skew the whole thing too? Do you know anything about this? Thumbnails or any other anomolies should not cause a problem. From the specs I read, there are certain guaruntees. All information is divided into segments. A segment starts with the the byte 0xFF and 0xFF will only be used to denote the start of a segment. The next byte after 0xFF says what type of segment you have. For the header segment, the bytes 0xFF 0xC0 will appear in that order. The combination of 0xFF followed by 0xC0 will only appear once in any JPEG file. Also the header size is fixed, so the 9th position contains the image type flag always.(Counting 0xFF as position 0.) The code is not thoroughly tested. I just wrote it. Here is the header part of the JPEG spec. SOF0: Start Of Frame 0: ~~~~~~~~~~~~~~~~~~~~~~~ – $ff, $c0 (SOF0) – Remarks: – JFIF uses either 1 component (Y, greyscaled) or 3 components (YCbCr, sometimes called YUV, colour). The spec is on if you want to look at it fully. The segment definitions are near the end. Please take this with the utmost of respect. If it was this simple (I’m not implying that getting to this snippet didn’t take a lot of time and understanding) where one could just write out the code (you mention you just wrote it and didn’t thoroughly test it), then it makes be believe that Mozilla and Internet Explorer should have been able to get it right with all their massive resources? So the question is why didn’t they? By this reasoning, I’m going to assume there’s more than meets the eye… I understand your skeptisism. This code does not allow you to display it. It only allows you to detect if you can. The rest of the spec talks about Huffman encoding and the like, which would take a lot of time to understand.(I have not taken that time.) Don’t let your skeptisism make you automaticaly dismiss a solution that could be correct. The code snippet is so small that it could easily be inserted to try it out and removed later if you still don’t trust it. Also consider your blog related to this where you explain that it is not cost effective for you to go with a developer oriented solution, but need to go more with a business oriented solution. Consider that Microsoft and the Firefox crew have huge budgets and may be only considering the developer oriented solution. As you get bigger sometimes you can get blinded to the simple solution. Good luck. Damn, spelled skepticism wrong. There goes my credibility. 🙂 You’re right, I skipped over the part that the code “only” lets you detect it, nothing more. You’re absolutely right, my apologees. One thing though that I’ve been thinking of since then, no matter what kinds of checks we do, we still have to implement the code in case there is an error. For example, maybe there’s another format that will cause a similar issue. I’ve read something about the Photoshop thumbnail preview mode causing issues with many image renderers too. So the question then becomes, do we just implement one solution or two? Seeing your code, it’s a fairly simple implementation, so it makes me want to implement such a check. But then I start to think about testing it. I’ve only come accross one image that has this issue (of course I can create others). But now how do I test for false positives? Testing for false positives can become very complex, there are many image modes. Since we also have to implement the other solution because of this, is it worth going through this extra effort? That’s a hard question. Right now I’m leaning towards no. Not because the solution is difficult, you provided a great succint solution (thank you!), but testing it is very difficult. We need to test images that have this issue, and all other image formats to make sure we’re not preventing a valid mode. This false positive testing is starting to scare me in terms of costs… And if we look at the gain, since we have to implement the other solution that deals with all cases, what’s the gain of this additional check? It’s an initial performance gain when first importing the images (so we never have to try to render them). This is why I’m going to go with just the simple solution of catching the errors when rendering at this time. Yes it’s more expensive to implement, but we have to implement it anyways, and it’s much cheaper to test. And yes, you’re absolutely right, sometimes the obvious simple solution is the hardest to see! I know I’ve been guilty of that one more than once 🙂 These days, I always try to find some type of justification for what we add into LandlordMax. When you’re smaller every penny counts that much more! It’s also easy to fall into the trap of not fixing bugs, but I’m very opposed to this because I’m strong believer of design debt. However, if the bug fix is very large, the frequency of occurence very low, and the spread non-existant (only affects this, it does not increase design debt), then sometimes you need to look at the alternatives, as was the case with this bug. To give you an idea of some bug fixes that we can’t justify with just the model I described above is performance enhancements. We’ve done some major performance enhancements with the upcoming major release (as well as with version 2.12). We spent a lot of time and effort, almost 1/2 of it was performance based! Will this automatically convert to sales? Maybe, maybe not. However if we hadn’t made these enhancements we would be acquiring a lot of design debt which would have hit us later. Maybe not tomorow, but soon enough. When it comes to performance you’re only as strong (fast) as the weakest (slowest) link in your chain. Since there are anly 3 colour modes for JPEG, I don’t think false positives would be a problem. But I can see a problem with thumbnails. They are not declared in the header, so you would have to find them separately. A tough chore. Good luck with your solution. I didn’t know that… From my initial impressions searching on Google I was pretty sure there were 20 or so different encodings. To be quite honest, I’m very ignorant as to the details of the JPG encodings, and I don’t really have an interest in knowing them, I’m just too busy on other higher priority items. It’s s very interesting to know about the thumbnail! Thank you for sharing that information. Therefore from what I gather they aren’t part of the spec if their not in the header, something that was added after by Photoshop and similar software? Thanks for the information, it’s very appreciated. In regards to the solution we’re going to implement, you’re comments and suggestions are still making me ponder which path to take… Sometimes I find that if I just sit on the options for a while, let it work in the back of my mind, it easier for me. At this point I haven’t decided.
https://www.followsteph.com/2006/10/19/landlordmaxs-most-challenging-bug/
CC-MAIN-2017-17
refinedweb
5,394
71.95
I am currently taking a c programming class, and have just had the worst time trying to figure out how to properly use pointers and functions. I understand how they work in theory, but I just can't seem to get the syntax down right, which has caused no end to my stress. Please, I need some serious help here. My teacher has given me a fully written code, and asked me to build three functions to accommodate it. It seems simple in theory, but I can't figure out how to do it. First, I'm passed a 9 length array that I need to reverse (revArray(a)), then I need to return it to its original state (*revElement(a)), and then I need to sort the evens and the odds (evenOdd(a)). Every time I write a function, it doesn't work at all, so can I tell you what I think I should build as a function, and then you could tell me where I'm mistaken?Every time I write a function, it doesn't work at all, so can I tell you what I think I should build as a function, and then you could tell me where I'm mistaken?Code:#include <stdio.h> #include <stdlib.h> #define N 9 /* MAIN */ int main() { /* Load the array with numbers */ int a[N]; int idx; int *p = a; while(p < a + N) *p++ = a + N - p; printf("Original: "); p = a; while(p < a + N) printf("%2d ",*p++); /* Part A: Reverse the array */ revArray(a); printf("\nReversed: "); p = a; while(p < a + N) printf("%2d ",*p++); printf("\n"); /* Part B: Return elements in reverse order */ /* printf("Original: ");*/ for (idx = 0; idx < N; idx++) { printf("%2d ",*revElement(a)); } printf("\n"); /* Part C: Put even numbers first, odd numbers last in the array. Order of the elements is not important as long as all evens are before first odd*/ printf("Even: "); evenOdd(a); p = a; while(p < a + N) printf("%2d ",*p++); printf("\n"); return 0; } For (revArray(a)), I need to make a pointer equal to (a), and then rewrite (a), assigning a [0] = p [N - 1], a [1] = p [N - 2]...a [N] = p [0]. This is what I wrote Code:int revArray(int arr) { int *p = arr; for (;p < N; p++) { p = arr + N - arr; } for (arr = p; arr <N; arr++) { arr = p + N - arr; } return (arr); } I've tried all kinds of different variations, but none work. What am I missing here?? As for (*revElement(a)), I assume I just have to build the same loop as in (revarray), as a[0] will be put back into a[N]. However, as it's a pointer, I'll need to return (&a), not just (a). Is this correct, or am I wrong on that as well? Finally, for (evenOdd(a)), I assume I can just build an array of N+1, and then use %2, and assign all with an output zero to a++, while those with any other output to a-- + N. I've been so stuck on (revarray) that I haven't even had a chance to write that yet, but does it sound like I'm on the right track? Again, any help would be massively appreciated.
http://cboard.cprogramming.com/c-programming/152883-reversing-array-via-poiinters-function.html
CC-MAIN-2013-48
refinedweb
544
71.68
Hi If I have created a custom component in ActionScript that has non-empty constructor, how do I create this component in MXML? Generally if you create an instance of class defaultly constructor of the class will be executed. As you are creating an custom component mean you may be extending it with some flex component.the custom component will be having the properties of the component extended.In MXML you can directly call that. If I understand properly, you want to re-create an ActionScript component in MXML; is that correcT? MXML doesn't have constructors. You should move the "constructor" code to a preinitialize event handler. Yes, so imagine that I have a panel which looks like the following: public class MyPanel extends VBox { public function DummyComp (title:String) { } } and I want to ensure that the user pass in the title when creating this panel in ActionScript or MXML. Then you can not use MXML tag to create the component. You need to create the component via ActionScript ( new MyComponent( title ) ) in your MXML file Script part, and place it where it is supposed to be with the addChild method of its parent tag. Alternately, if you can provide a default value for all constructor arguments, you *can* declare the component in MXML. E.g., public class MyPanel extends VBox { public function DummyComp (title:String='untitled') { } } You can then use <mycomps:DummyComp/> You'll probably also want to expose a property for title so you can set it after it's constructed. Unfortunately, this makes it pretty much impossible to create immutable properties. If you implement IMXMLComponent (or whatever that interface is called), you'll get a callback for the initialize() method once the component's id and parent container, but this can happen before all properties are initialized (!), which makes it a lot less useful.
https://forums.adobe.com/thread/652084
CC-MAIN-2017-51
refinedweb
308
52.8
This site uses strictly necessary cookies. More Information I'm trying to utilize namespace though can't quite figure out how to set up my C# properly. Lets say I have a namespace named Player, with public classes deriving from MonoBehaviour - Movement & Attack. using UnityEngine; using System.Collections; namespace Player { public class Movement : MonoBehaviour { void Message() { Debug.Log ("Moving"); } } public class Attack : MonoBehaviour { void Message() { Debug.Log("Attacking"); } } } Is this namespace solely for setting up structure? Is there a good place to define the functions and what each class does specifically? How would I go about calling these classes in another script file? This doesn't seem to work: using UnityEngine; using System.Collections; using Player; public class hey : MonoBehaviour { // Update is called once per frame void Update () { Player.Movement.Message(); } } Unless I set void Message() to public static void Message(). In what case would I not have Message() set to public static? I'll be doing some googlin' after submitting this question, any helpful/easy to understand insight would be appreciated as well :) It is generally a good idea to do your googling before posting your question, not after. I've actually been Googling for a while now, whenever I'm scripting or programming I'll never be found without a couple Firefox tabs in Google. I'm hoping that if I ask, maybe I'll better understand rather then trying to decipher somebody else's questions and answers Answer by Kiwasi · Dec 02, 2014 at 06:18 AM There are a bunch of misunderstandings here. First piece of advice - Don't go near namespaces until you already know what they mean and what they are used for. At your level there is no point worrying about them. Your code has to be reasonably complex before namespaces are strictly needed. And they are pretty easy to refractor in. Same advice goes for static. Leave it alone until you already understand it. There is no case when a static is truly needed. Your basic problem comes from a misunderstanding of access modifiers. There are four of them. private - cannot be accessed outside of the class protected - can be accessed by derived classes only. Forget this one for now. internal - can be accessed inside the assembly. Forget this one for now. In general you won't use this unless you are building .dlls for others to use public - can be accessed by everything General rule: Make everything private, unless you really, really need to access it from another class. As for accessing members of another class, there are thousands of question here on it. Start with googling GetComponent. Work your way up from there. Answer by jaja1 · Dec 02, 2014 at 06:18 AM If I understood what you are asking correctly: Read up on accessibility in c#. Accessing the Message() method requires it to be public even within a public class. Declaring it as static is not required unless you want global access to the method without having to create an instance of the Movement class. This also means that any non-static variables that belong to the Movement class can not be accessed by the static Message() method because there can be several instances of the Movement class that these variables belong to. By not declaring Message() as public you are implicitly stating that it is private and can only be accessed within the scope of the class it is declared. Calling functions from other namespaces and scripts. 0 Answers Unity Can't find script class because of namespace 2 Answers What is the default namespace 0 Answers Can't access another script, think it may be due to namespace/public class ? 1 Answer How to use MonoBehaviours inside namespaces. 3 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/845038/working-with-namespace-correct-way-to-set-up.html
CC-MAIN-2021-39
refinedweb
626
65.83
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo You can subscribe to this list here. Showing 2 results of 2 Hi, I'm using cc-mode 5.28 with emacs 21.2.1 and have a problem that, with my configuration, is something I hit a lot. I traced this down to a pretty small environment but I don't know lisp well enough to fix it. Here is how to reproduce: Using all the defaults of cc-mode except for the following: (c-set-offset 'innamespace 0) There is a problem I hit with code looking like the following. Note: we want the code inside a namespace to vertically align with the braces, so innamespace 0 is perfect for our needs. ///////////////////////////// namespace ns { class X { }; } // ns int f() { } int g( ///////////////////////////// Note I'm starting to write a 2nd function, g, and if I type a closing parenthesis for it, I will get: (*BEEP*) Unbalanced close brace at line 8 This problem does not happen if I remove function f(), or if I remove class X. Somehow it seems to forget that it's in a namespace, thinking that all of the braces are "siblings" when in fact clas X is really nested. If I indent class X a space (innamespace 1), or change it to be like this: class X { }; Then it seems to work better. - Chris PS, I did a little experimentation with cc-engine.el in the c-parse-state function, and found where the error message is generated. I see it has a loop looking back for 2 bobs (whatever a bob is), and tried increasing the initial value of cnt to 3, (first line below) and sure enough, it allowed me to write 1 more pair of braces before it started complaining again. Seems to me it's simply walking straight up the file looking for parens, and is not considering the MEANING of the parens, just the position and count. (Is that right?) (let ((cnt 2)) (while (not (or at-bob (zerop cnt))) (goto-char (c-point 'bod)) (if (and (eq (char-after) ?\{) ;; The following catches an obscure special ;; case where the brace is preceded by an ;; open paren. That can only legally occur ;; with blocks inside expressions and in ;; Pike special brace lists. Even so, this ;; test is still bogus then, but hopefully ;; good enough. (We don't want to use ;; up-list here since it might be slow.) (save-excursion (c-backward-syntactic-ws) (not (eq (char-before) ?\()))) (setq cnt (1- cnt))) (if (bobp) (setq at-bob t)))) (point))) It seems to be using the position of the braces without any concern for the actual context. I'd be interested in working on this if only I knew how. (Is thre an "inside cc-mode" documentation geared more at working on the code itself rather than using it?) Thanks again. > I think one of you should be looking at this one. From what I can tell, it's a problem in c-indent-new-comment-line. Stefan
http://sourceforge.net/p/cc-mode/mailman/cc-mode-help/?viewmonth=200306&viewday=14
CC-MAIN-2015-18
refinedweb
517
78.69
j: Next unread message k: Previous unread message j a: Jump to all threads j l: Jump to MailingList overview Hi Renyue, This list shows all of the colormaps available for anything that uses matplotlib (such as projections, profiles, but not anything that uses write_image or write_png or snapshot): You can also use these colormaps anywhere: algae (default) kamae black_green cubehelix There are also a whole bunch of IDL and other colormaps that are accessible, although I have not used them, which you can see a list of by doing: from yt.visualization._colormap_data import color_map_luts print "\n".join(sorted(color_map_luts)) -Matt On Fri, Jan 11, 2013 at 11:17 AM, Renyue Cen cen@astro.princeton.edu wrote: Hi, Where is the list of available colormaps located so I can see their colors? Thanks, Renyue yt-users mailing list yt-users@lists.spacepope.org
https://mail.python.org/archives/list/yt-users@python.org/message/4S2LKJUQQKSFIJ63RCCTIFF76BRLVLST/
CC-MAIN-2019-43
refinedweb
144
53.55
Hi, I’ve recently found a snippet of code online here: Change all detail view display modes And I’ve attempted to copy the final version into my code. I would like to be able to change the following: To a rendered view: Here is my (copied) function for doing so: def SetDetailsToRendered(debug): modes = rs.ViewDisplayModes() setmode = rs.ListBox(modes, “Select mode”) # Find the wireframe display mode display_mode = Rhino.Display.DisplayModeDescription.FindByName(setmode) if display_mode: MessageBox.Show(“display mode”) DebugPrint(display_mode, debug) # Get all of the document’s page views page_views = scriptcontext.doc.Views.GetPageViews() if page_views: MessageBox.Show(“Page views”) # Process each page view for page_view in page_views: MessageBox.Show(“Page view”) DebugPrint(page_view, debug) # Get all of the page view’s details details = page_view.GetDetailViews() if details: MessageBox.Show(“details”) # Process each page view detail for detail in details: MessageBox.Show(“detail”) DebugPrint(detail, debug) # If the detail’s display mode is not wireframe… if detail.Viewport.DisplayMode.Id != display_mode.Id: MessageBox.Show(“if id = id”) # …set it to wireframe. detail.Viewport.DisplayMode = display_mode detail.CommitViewportChanges() # Redraw the page page_view.Redraw() def DebugPrint(object, debug): if object and debug: print object I have attempted a few MessageBoxes to see if it’s going through all the if statements and loops. I’ve noticed it doesn’t get past the “display mode” message box. So it doesn’t go into “if page_views” statement. I’m trying to understand what a page view exactly is and why I’m not getting one. Any help would be greatly appreciated. This is implemented using Rhino 6 WIP. I hope it still works the same as 5. Thanks, Jack.
https://discourse.mcneel.com/t/python-changing-display-mode-of-all-views/43474
CC-MAIN-2018-51
refinedweb
277
52.36
Welcome to the Parallax Discussion Forums, sign-up to participate. jmg wrote: »? It comes down to the Logic cost - to me that's looking a LOT of Bit-Muxes needed, vs a simpler shifter for the RCZR? evanh wrote: » The existing generic barrel shifter in the ALU should be able to handle it if we wanted to throw a full two-operand opcode at the job. TonyB_ wrote: » 2. The D,S form might never by used, as only the very brave or mad would use a register to specify the flag addresses. Any other instructions like that? Heater. wrote: » That is one annoying feature of the Raspberry Pi. You can't just plug it into a USB port and talk to it. #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #define ACCUM_SIZE 16 // Passed in as -D gcc parameter. (Min=9, Max=64) Bit width of generated random numbers. #define CONSTANT_A 14 // Passed in as -D gcc parameter. #define CONSTANT_B 2 // Passed in as -D gcc parameter. #define CONSTANT_C 7 // Passed in as -D gcc parameter. #define ACCUM_MASK (((1ULL<<(ACCUM_SIZE-1))-1)<<1|1) // Bit of a shuffle to work on all 64 bits // Seed the state array. Seed MUST not be all zero. static uint64_t s[2] = {1, 0}; static inline uint64_t rotl(uint64_t value, int shift) { return ((value << shift) | ((value & ACCUM_MASK) >> (ACCUM_SIZE - shift))) & ACCUM_MASK; } static uint64_t next(void) { uint64_t s0 = s[0]; uint64_t s1 = s[1]; uint64_t result = (s0 + s1) & ACCUM_MASK; s1 ^= s0; s[0] = rotl(s0, CONSTANT_A) ^ s1 ^ (s1 << CONSTANT_B) & ACCUM_MASK; s[1] = rotl(s1, CONSTANT_C); return result; } // Store high 8 bits of generated numbers. int main(int argc, char* argv[]) { uint64_t random64; int i = 20; // Print some randomness while(i--) { random64 = next(); printf( "%04lx ", random64 ); } printf("\n"); return 0; } evanh@control:~/hoard/Propeller/Prop2/testing$ ../loadp2 -v -t xoro32-seq20.obj Searching serial ports for a P2 P2 version A found on serial port /dev/ttyUSB0 xoro32-seq20.obj loaded [ Entering terminal mode. Press ESC to exit. ] 00000001 00804085 42a05530 18282c7c 3e06769f 4f83a248 a30edffd f0d0202d c8eff2f1 76f25aca 944b4dc8 9a16d1d1 d6d7adcd 10810598 cc731b30 66418094 093e540c f822d6a4 51139c9d 4c8e2eac evanh wrote: » Here's a hack up of old testing code (ie: Not the actual Prop2's XORO32): evanh wrote: » Lol, you guys aren't really going to use that for anything are you? Are there active source repositories for 6502/Z80? Surely not. The 65xx brand is probably the only processor family that has remained loyal to its ISA over the last 33 years. In addition it has served the widest spectrum of electronic markets through those years. For example, it has served and in some cases created markets for the PC, video game, toy, communication, industrial control, automotive, life support embedded in the human body medical devices, outside the body medical systems, engineering education systems, hobby systems, and you name it electronic market segments. I might add the 65xx has served in a highly reliable and successful way! potatohead wrote: » ....... I wonder about the 6809. That one is beautiful. Best 8 bit ever made, IMHO......... TonyB_ wrote: » Any chance Evan of the first few XORO34 sums for triplet [7,8,12] when seed = 1? I'm now writing a Z80 version of that. Sorry I don't use C and an independent data check would be much appreciated. Xoroshiro40+ PractRand Score Table Combination Word1 Word2 Byte12 Byte06 Byte2 Byte1 Bit ==================================================================== [ 1 7 8] 4M 4M 64M 64M 4M 1M 256G [ 1 16 14] 2M 2M 64K 64K 128K 128K 256G [ 2 1 19] 128K 64K 32K 32K 64K 64K 256G [ 2 7 3] 16M 32M 8M 8M 512K 256K 256G [ 2 16 3] 2M 4M 512K 256K 256K 256K 256G [ 2 18 5] 8M 8M 8M 1M 1M 1M 256G [ 3 2 8] 64M 64M 512M 128M 64M 64M 128G [ 3 7 2] 2M 4M 4M 128K 128K 128K 16M [ 3 10 14] 256M 128M 16G 256K 512K 256M 256G [ 3 16 2] 256K 256K 128K 64K 64K 32K 256G [ 4 2 19] 2M 2M 256K 256K 256K 256K 256G [ 4 3 15] 32M 64M 1M 1M 2M 256M 256G [ 4 4 15] 32M 32M 1M 1M 2M 16M 64G [ 4 9 5] 512M 1G 128M 16M 8M 4M 256G [ 4 19 19] 2M 2M 512K 512K 512K 512K 256K [ 5 2 8] 2G 2G 128M 128M 64M 64M 256G [ 5 2 18] 64M 32M 1M 512K 1M 2M 256G [ 5 9 4] 8M 16M 16M 1M 128K 128K 256M [ 5 16 6] 256M 256M 128G 16M 16M 16M 256G [ 5 18 2] 4M 4M 512K 512K 512K 512K 256G [ 6 3 17] 256M 512M 1M 2M 4M 256M 256G [ 6 10 17] 2G 4G 32G 32M 64M 256M 256G [ 6 14 11] 2G 2G 8G 8G 8G 256M 256G [ 6 16 5] 2M 4M 8M 128K 128K 128K 256G [ 6 16 9] 2G 2G 1G 1G 2G 256M 256G [ 7 1 14] 1G 1G 256M 512M 512M 256M 256G [ 7 2 14] 16G 8G 256M 512M 4G 256M 64G [ 7 9 12] 16G 16G 64G 32G 32G 256M 256G [ 8 2 3] 512M 256M 4M 4M 8M 16M 16M [ 8 2 5] 128M 256M 4M 4M 8M 8M 32M [ 8 5 9] 1G 1G 1G 1G 8G 256M 256G [ 8 7 1] 8M 4M 1M 1M 1M 1M 16M [ 8 8 11] 128M 128M 128M 128M 1G 256M 256G [ 8 13 9] 1G 2G 8G 4G 128G 256M 256G [ 9 5 8] 32M 64M 8M 8M 32M 256M 256M [ 9 13 8] 8M 8M 2G 1G 4G 256M 64G [ 9 16 6] 64M 64M 512M 8M 16M 256M 256G [10 9 17] 32M 64M 1G 1G 512M 256M 256G [11 8 8] 8M 8M 4M 32M 128M 256M 2G [11 13 16] 2G 2G 32G 8G 64G 256M 256G [11 14 6] 2G 2G 16G 32M 8G 256M 256G [12 3 13] 4G 4G 128G 16G 64G 256M 256G [12 6 17] 8G 8G 128G 128G 16G 256M 256G [12 9 7] 2G 1G 64M 64M 64G 256M 4G [12 18 13] 512M 512M 128G 32G 64G 256M 256G [13 3 12] 64M 128M 2G 2G 32G 256M 64G [13 18 12] 4M 4M 16G 4G 2G 256M 256G [14 1 7] 512M 512M 512M 4G 2G 256M 64G [14 2 7] 32G 32G 1G 4G 4G 256M 64G [14 10 3] 2G 4G 8G 128M 64M 256M 64G [14 16 1] 128M 128M 32M 32M 16M 8M 256G [15 3 4] 4G 4G 256M 256M 256M 256M 256G [15 4 4] 64M 64M 8M 32M 16M 16M 256G [15 5 18] 2G 2G 4G 128M 16M 8M 256G [16 13 11] 1G 1G 128G 32G 64G 256M 256G [17 1 18] 32M 32M 16M 16M 16M 16M 256G [17 3 6] 512M 512M 2G 1G 1G 256M 256G [17 6 12] 8G 8G 64G 64G 64G 256M 256G [17 9 10] 4G 4G 4G 16G 2G 256M 256G [17 10 6] 4G 8G 16G 2G 8G 256M 256G [18 1 17] 512K 1M 128K 128K 64K 64K 256G [18 2 5] 2G 2G 1G 512M 512M 256M 256G [18 5 15] 2G 2G 2G 256M 256K 256K 256G [19 1 2] 2M 2M 512K 512K 512K 256K 256G [19 2 4] 64M 64M 64M 64M 64M 64M 256G [19 19 4] 128M 128M 32M 32M 32M 32M 256G evanh wrote: » First twenty 17-bit (Xoroshiro34) sums for triplet [7,8,12] is: For prototyping, obviously board, display, etc... On my bench, the necessary stuff is out there. Plug in, go. Honestly, I will probably leave it there most times, like any other bit of bench gear. I do like, and will use serial / USB regularly. It's like you say, quick. Thanks for the feedback. Although 16 flag sets is the maximum possible with 32-bit D and 9-bit S, eight sets should be enough in practice. D[1:0] = CZ[0], D[3:2] = CZ[1], etc., leaving D[31:16] unused if the limit is eight in the logic. However, the top 16 bits could be switched in as a second bank of eight by simply rotating the words. The proposed XCZ instruction has a couple of interesting and possibly unique properties: 1. The letters in the mnemonic are adjacent on the same keyboard row. Any other instructions like that? 2. The D,S form might never by used, as only the very brave or mad would use a register to specify the flag addresses. Any other instructions like that? I'm rusty on the details, but I think Chip already has bit-index instructions, so this becomes a dual-bit (doublit?) variant on that ? exactly! With the current boot loader you are able to do that, but need to type in some monitor in hex. Since auto baud works on every space, you just need to type steady. Or be able to copy and paste into the terminal. But it would be nicer to have some minimalistic monitor. Hot-P2 one is maybe to much, but I really liked it. Like Chip said, just add access to the smart pins and ready. Some small documented hooks to get in between the serial communication to extend the cmd-interface of the debugger, and we are golden. Mike EDIT: And the source code: Many thanks, Evan. If not done already, xoroshiro32+ is now working on the Z80! 8) Any chance Evan of the first few XORO34 sums for triplet [7,8,12] when seed = 1? I'm now writing a Z80 version of that. Sorry I don't use C and an independent data check would be much appreciated. Evan, you would be surprised at how much source code for the 6502, 6800, and Z80 is still around. In addition to the computer enthusiasts there are also quite a few pieces of equipment that use those chips still in service. They may no longer be state of the art but they are rugged, reliable, and work almost as well as a lot of new equipment. It sees a ton of use in toys, local microcontrollers, small scale embedded... I'm sure the Z80, others are similar. I wonder about the 6809. That one is beautiful. Best 8 bit ever made, IMHO. At higher clocks possible today, those designs can respond very quickly, library code is debugged, known cold, just works, and tools are stable too. Simple, fast, cheap. Just not big. They talk about 200 mhz options! ASIC and FPGA. That gets one into an ISR in about 35ns. A read, respond cycle expectation might be 100ns. I agree. Such a nice architecture and orthogonal instruction set. An algorithm like this could be used standalone or to support interaction of Prop 2 projects with software written for the legacy hardware to provide new grist for the mill of hobbyists. Many of these communities are doing these things not for the next big thing, but because they can.... A few examples: lawlesslegends.com 6502workshop.com/p/nox-archaist.html [7,9,12] was chosen from below scores: EDIT: Although, even though that would easily explain the byte1 sample variant, it is also contradicted by the word2 variant hardly deviating from the word1 variant. (Word1 and byte1 includes bit 1, while word2 and byte2 doesn't.) Many thanks, Evan. You are a star! 08C0 B046 53AE 5FB4 E38E AC74 1479 E254 E127 A736 FC9C F89A 3D47 3466 AA02 EC84 My Z80 code matched the first four first time but 5th sum was EB4E then the rest went very pear-shaped. I hate it when something half works. I prefer total failure! At least I'm on the right track. What would happen is any extra overhang in the input would be immediately right-shifted into the working rang and therefore contaminate the sequence. Funnily, now that the state bits don't have any bleed, that mask probably isn't strictly needed.
https://forums.parallax.com/discussion/166176/random-lfsr-on-p2/p24
CC-MAIN-2021-04
refinedweb
1,991
76.45
Coffeehouse Thread58 posts Does Microsoft plan to build its future products using .NET? Back to Forum: Coffeehouse Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know. Pagination I think this question is what everyone wanna ask, as we have discuss again and again here that Microsoft creates a technology they never really use. Sheva I would think it depends entirely on the class of application they are building. Some suit .NET, some dont. Because most Microsoft applications have a large existing codebase in unmanaged code, it is unlikely we'll see a version of Office completely written in .Net anytime soon. That is not to say MS doesn't use .Net anywhere. Some applications will be completely managed, such as Microsoft Max, some will be largely managed, such as WinFX itself, but most often you will start seeing a lot of integration of .Net with unmanaged products. Examples include the use of managed HttpHandlers in IIS7, managed sprocs in SQL Server 2005, and many more. As far as MS not using its own technologies... I think microsoft.com is probably one of the largest consumers of ASP.NET. And this sometimes even makes it way into server products they redistribute, such as Windows Server Update Services, which uses an entirely ASP.NET based management system. They use it. People who complain they don't are expecting them to rewrite VS, Office, IE or maybe even Windows from the ground up in C#. That's not going to happen anytime soon, if ever. There's way too much existing code that nobody is going to throw away. Not to mention there's a lot of places where using managed code simply doesn't make sense. Watch the Sparkle video. I think that makes the answer pretty clear. Also watch the latest Hotmail video. They're rewriting Hotmail in 100% .NET. And I think SharePoint is also 100% .NET. And I'm pretty sure a big part of Visual Studio is also written in .NET. Great explanation Sven, thanks Sheva Yes. - Steve Sorry, don't think so... I believe it is all unmanaged VC++. Visual Studio is an interesting mish-mash of managed and unmanaged code. For instance, the Windows Forms designer is (mostly) managed code. Not according to Reflector.net. There's quite a few .Net assemblies in my Visual Studio folders, and most of the Windows Forms designer actually uses Windows Forms' own design functionality, which is inherently managed. Ever looked at the System.Windows.Forms.Design namespace? That's the basis of the designer. SharpDevelop uses that too, and that's completely managed code. According to John Gossman Sparkle is completly managed with only one p/invoke call. Even this wasn't necessary but the chose to use it rather than introduce a dependancy on winforms. I also remember an interview with the guy that created the new VS2005 XML-editor (with Intellisense for all XML-files that have an XSD-schema), and he said that the editor was also managed. I've just checked out the VS2005 (beta 2) directories, and there's actually a lot of managed code there: Go to C:\Program Files\Microsoft Visual Studio 8\Common7\IDE IMO. Managed code is mighiter than unmanaged code in many-multi-core era. CLR will do the job for tweaking MSIL to adapt it to multi-core environment without recompiling source code. That's one typical circumstance in which managed code outplays unmanaged code in terms of performance. Sheva No VM can magically make a single code stream multithread. Either the application is coded as multithreaded or it isn't. CLR on a multicore won't change squat. Except for the fact that every .net app uses multiple threads due to the GC. And not to mention the framework libraries that use multiple threads already. Unfortunately last I read Avalon is essentially single threaded.
https://channel9.msdn.com/Forums/Coffeehouse/118061-Does-Microsoft-plan-to-build-its-future-products-using-NET
CC-MAIN-2017-13
refinedweb
676
67.45
The last match before the TCCC may not have been the warm-up that competitors were looking for, as division 1 had one of the hardest sets in recent memory -- only 10 competitors solved more than 1 problem. Of those, tomek, bladerunner and Klinck were the only coders to solve all 3 problems, taking 1st, 2nd and 3rd, respectively. In division 2, coders had it a bit easier, with most coders solving the easy, and over half solving the medium. First timer kaylin took first by less than a point over Artist_, while long time TopCoder, Uranium-235, rounded out the top 3. Value 250 Submission Rate 156 / 172 (90.70%) Success Rate 148 / 156 (94.87%) High Score NeverMore for 243.67 points (4 mins 36 secs) Average Score 190.96 (for 148 correct submissions) A fitting problem to follow March Madness. In order to calculate the points per shot, you need to know 3 things: the total number of points, the number of free throws attempted, and the number of field goals attempted. The simplest way to find all of these is to just have 6 separate cases, one for each possible value of the elements. Clearly, you should just copy and paste these strings from the problem statement, since typing them in yourself is a good way to introduce typos. That was by far the most common solution, and pretty much everyone got it right. There are a few ways in which you could get clever if you really wanted to, but with only 6 cases to deal with, coding each one up is pretty simple.If you want to see how this metric works in the NBA (or how it worked in the '00-'01 season), check this out. Value 500 Submission Rate 122 / 172 (70.93%) Success Rate 83 / 122 (68.03%) High Score SamBob for 462.54 points (8 mins 13 secs) Average Score 324.84 (for 83 correct submissions) Value 250 Submission Rate 153 / 158 (96.84%) Success Rate 129 / 153 (84.31%) High Score antimatter for 246.85 points (3 mins 13 secs) Average Score 213.20 (for 129 correct submissions) This is a bit tougher than it looks at first glance. Its pretty simple to verify that the characters which have been revealed so far match up. But then you have to make sure that there isn't a letter, some of whose instances have been revealed, and some of whose instances have not. Lets consider a method, matches, which takes strings feedback and word, and returns true if word matches the feedback. Once we have this part written, we're 90% done. The first thing we want to do is make sure the strings are the same length. Assuming they are, we look at each character in word. If a character is in word, opposite a '-' in feedback, then we need to make sure the same character doesn't appear anywhere in feedback. If the corresponding character in feedback isn't a '-', we just check that they match: boolean matches(feedback,word) if(lengthof(feedback)!=lengthof(word))return false; for (i = 1 to lengthof(feedback)) if (feedbacki == '-') if(feedback.containsCharacter(wordi)) return false endif else if(feedbacki != wordi) return false endif endif end for return true end String letters = feedback.replaceAll("-",""); String regex = feedback.replaceAll("-","[^"+letters+"9]"); Value 1000 Submission Rate 12 / 172 (6.98%) Success Rate 5 / 12 (41.67%) High Score Uranium-235 for 605.98 points (26 mins 55 secs) Average Score 473.17 (for 5 correct submissions) This problem is a bit easier than it looks. Behind all the big fancy words, the algorithm is relatively simple. Basically, we need to find h(0) and h(1) so that if we simultaneously replace all of the 0's in u with h(0) and all of the 1's in u with h(1), we get v. Now, without any loss of generality, lets say that the first character of u is a '1'. Then, h(1) needs to be the first i characters of v, for some i >= 1. Thus, there are O(n) possibilities of h(1). Now, to find h(0), we can just try every substring of v, of which there are O(n2). This gives us O(n3) combinations of h(0) and h(1) to consider. Finally, to check a given h(0) and h(1), we can just do it in the obvious way: intiialize tmp = "", iterate over characters of u, and append h(0) or h(1) to tmp, depending on the character in u. This adds another factor of n to your runtime, and you end up with an O(n4) algorithm: set validPairs; foreach potential h(0), h(1) pair tmp = "" for (i = 1 to lengthof(u)) if(ui == 0) tmp = tmp + h(0) else tmp = tmp + h(1) endif end for if(tmp == v) validPairs.add(h(0),h(1)) endif endfor return validPairs.size() Value 600 Submission Rate 20 / 158 (12.66%) Success Rate 8 / 20 (40.00%) High Score tomek for 377.76 points (25 mins 8 secs) Average Score 286.54 (for 8 correct submissions) This problem was pretty hard, but when it comes down to it, its just brute force with some pruning. First off, note that the answer is at most 6, since we can just change the 6 digits of c. So, as we are changing digits, if we ever get to 5, and still aren't done, then we shouldn't bother to change any more. Once we figure that out, we should work from right to left. Once we have the rightmost (ones) digits of a, b and c fixed, and (a*b)%10 == c%10, the next digit to the left can no longer mess up what we already have. That is, regardless of what we do to the hundreds digits of a, b and c, we will still have (a*b)%10 == c%10. This suggest a recursive solution, where we first change the tens digits then the hundreds digits, and so on. We stop recursing if we have ever made 5 or more changes, and aren't done yet. Also, to make things a bit quicker, once we have changed the digits of a and b in a particular place, we can tell right away what the corresponding digit of c should be. Here is dgarthur's solution, where pow10 is an array with powers of 10. int bestErrors = 6; void recursiveCorrect(long a, long b, long c, int pos, int errors) { if ((a*b-c)%pow10[6]==0 && errors<bestErrors){ bestErrors = errors; return; } if (errors >= bestErrors-1) return; for (int d1 = 0; d1 < 10; d1++) for (int d2 = 0; d2 < 10; d2++){ int newErrors = errors; long newA = setDigit(a,pos,d1); long newB = setDigit(b,pos,d2); if (a != newA) newErrors++; if (b != newB) newErrors++; int d3 = (int)getDigit(newA*newB,pos); long newC = setDigit(c,pos,d3); if (c != newC) newErrors++; recursiveCorrect(newA, newB, newC, pos+1, newErrors); } } Value 1000 Submission Rate 16 / 158 (10.13%) Success Rate 6 / 16 (37.50%) High Score tomek for 800.51 points (14 mins 58 secs) Average Score 620.46 (for 6 correct submissions) Let's start by counting the number of square free integers less than or equal to k, for some k. Instead of doing this directly, we'll calculate the number of integers less than or equal to k that have a perfect square as a factor, and subtract this from k. If an integer has a perfect square as a factor, then it has the square of a prime as a factor, since any square can be broken up into the product of some primes squared. Therefore, we only need to count the integers with squares of primes as factors. Consider the number of integers less than or equal to k with 4 as a factor (4 is the square of 2). Every 4th number has 4 as a factor, so there are floor(k/4) integers with 4 as a factor. Similarly, there are floor(k/9) integers with 9 as a factor. However, we can't just add these together to get the number of integers with 4 or 9 as factors, since we would end up counting the integers with 36 as a factor twice (the have both 4 and 9 as factors). The simplest way to deal with this is to use the Inclusion-Exclusion Principle. To avoid double counting integers divisible by 36, we subtract floor(k/36). So, if we are considering the first three primes squared, then there are floor(k/4) + floor(k/9) + floor(k/25) - floor(k/36) - floor(k/100) - floor(k/225) + floor(k/900) integers with one of the 3 squared primes as factors. Unfortunately, there are 2m terms to the full equation, if we have m primes to consider. Luckily, most of those are 0, and don't need to be computed. We can find all the non-zero terms using recursion as follows (assume primesSquared is a sorted array holding enough primes squared so that the biggest one is bigger than k). //idx is the index of the prime we are looking at //soFar is the product of some primes squared //k is as described above //this returns the number of integers//less than or equal to k which have //soFar and some prime squared as a factor int recurse(int idx, long soFar,int k){ int ret = 0; //If primesSquared[idx]*soFar > k,//then floor(primesSquared[idx]*soFar/k) == 0, //so all further terms are 0 if(primesSquared[idx]*soFar > k)return 0; //Otherwise, add the number of integers//divisible by primesSquared[idx]*soFar to ret ret += (int)(k/primesSquared[idx]/soFar); //Then, add terms that don't include primesSquared[idx], //but do include soFar and some other prime squared ret += recurse(idx+1,soFar,k); //Finally, subtract terms that include //both primesSquared[idx] and soFar and some other prime squared ret -= recurse(idx+1,soFar*primesSquared[idx],k); return ret; } public int getNumber(int n){ long lb = 1; long ub = 1700000000; long i, j; long maxMoebius = (long)Math.sqrt(ub); int moebius[] = new int[(int)maxMoebius]; int prime[] = new int[(int)maxMoebius]; for (i=0; i<maxMoebius; i++){ moebius[(int)i] = -1; prime[(int)i] = 1; } for (i=2; i<maxMoebius; i++){ for (j=2*i; j<maxMoebius; j+=i) prime[(int)j] = 0; if ( ((long)Math.sqrt(i))*((long)Math.sqrt(i)) == i){ for (j=i; j<maxMoebius; j+=i) moebius[(int)j] = 0; }else if (prime[(int)i] == 1){ for (j=i; j<maxMoebius; j+=i) moebius[(int)j] = -moebius[(int)j]; } } while (lb < ub){ long m = (lb+ub)/2; long thisN = m; for (i = 2; i < maxMoebius; i++) thisN -= moebius[(int)i] * (m / (i*i)); if (thisN < n) lb = m+1; else ub = m; } return (int)lb; }
http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm190
CC-MAIN-2016-40
refinedweb
1,826
70.13
SYNOPSISozmake --help ozmake [--build] [TARGETS...] ozmake --install [TARGETS...] ozmake --install [--package=PKG] ozmake --uninstall [--package=PKG] ozmake --clean ozmake --veryclean ozmake --create [--package=FILE] ozmake --publish ozmake --extract [--package=PKG] ozmake --list [--package=MOGUL] ozmake --config=(put|delete|list) ... ozmake --mogul=(put|delete|list|export) ... ozmake OPTIONS TARGETS ozmake is a tool for building Mozart-based projects and for creating and installing Mozart packages. It was inspired by the Unix tools make and rpm,but is much, much simpler, is specialized for Mozart-based software development and deployment, and transparently supports all platforms on which Mozart has been ported. ozmake must currently be invoked from a shell, but it will eventually acquire additionally an optional, user-friendly graphical interface. OPTIONS In the following, we write meta variables between angle brackets, e.g. <PREFIX> or <URI as cache path> General Options - -v --verbose print out more tracing information that the default. By supplying this option twice, you will sometimes get even more information. - -q --quiet suppress all tracing and feedback information - -n --just-print perform a dry run, i.e. just print what would happen without actually performing the actions - --local do not recurse into subdirectories - --(no)autodepend default: true automatically determine build-time and install-time (run-time) dependencies. Currently, this is only supported for Oz sources by looking at import and require sections. - --(no)requires default: true automatically fetch and install other packages that the current one requires. This option is relevant both for building and for installing. What you should remember here, is that -vn is your friend. Add -vn at the end of any ozmake invocation, and it will tell you in great detail what the command would do, without actually doing it. Directories and URLs - --prefix=<PREFIX> default: ~/.oz root of private installation area - --dir=<DIR> default: current directory default directory for other options below - --builddir=<BUILDDIR> default: <DIR> directory in which to build - --srcdir=<SRCDIR> default: <DIR> directory where source files are located - --bindir=<BINDIR> default: <PREFIX>/bin directory where bin targets are placed - --libroot=<LIBROOT> default: <PREFIX>/cache root directory of cache into which lib targets are installed - --libdir=<LIBDIR> default: <LIBROOT>/<URI as cache path> directory into which lib targets are installed - --docroot=<DOCROOT> default: <PREFIX>/doc root directory into which doc targets are installed - --docdir=<DOCDIR> default: <DOCROOT>/<MOGUL as filename> directory into which doc targets are installed - --extractdir=<EXTRACTDIR> default: <DIR> directory into which to extract a package - --archive=<ARCHIVE> default: URL of mogul archive from which packages can be downloaded - --moguldir=<MOGULDIR> directory in which are placed sub-directories for the user's contributions: a directory for packages, one for documentation, one for mogul database entries. - --mogulurl=<MOGULURL> url corresponding to the MOGULDIR directory Files - -m <FILE> --makefile=<FILE> default: <SRCDIR>/makefile.oz location of makefile - -p <PKG> --package=<PKG> file or URL of package. when creating a package, it should be a local filename. when extracting or installing, it can also be a URL or a mogul id; in the latter case, the package is automatically downloaded from the mogul archive - -V <VERSION> --packageversion=<VERSION> this option is respected by --extract and --install .When --extract is given a MOGUL id and downloads the corresponding package from the MOGUL archive, it will look precisely for the givenVERSION of the package. --install will simply check that the package to be installed really has this VERSION. - --database=<DB> default: <PREFIX>/DATABASE base path of installed packages database. The database is saved in both pickled and textual format respectively in files DB.ozf and DB.txt Helpozmake --help - -h --help print this information message Buildozmake [--build] - build all targets ozmake [--build] FILES... - build these target - -b --build this is the default. builds targets of the package - --optlevel=( none | debug | optimize ) default: optimize select optimization level for compilation - -g --debug --optlevel=debug compile with debugging - -O --optimize --optlevel=optimize compile with full optimization. this is the default - --(no)gnu is the C++ compiler the GNU compiler. this is determined automatically and allows a greater optimization level, namely passing -O3 rather than just -O to the compiler - --(no)fullbuild default: false also build the src targets - --includedir DIR -I DIR tell the C++ compiler to additionally search DIR for include files - --(no)sysincludedirs default: true tell the C++ compiler to additionally search (or not, if using --nosysincludedirs )the Mozart-specific include directories located in the global installation directory and in the user's private ~/.oz area. - --librarydir DIR -L DIR tell the C++ linker to additionally search DIR for libraries - --(no)syslibrarydirs default: true tell the C++ linker to additionally search (or not, if using --nosyslibrarydirs )the Mozart-specific library directories located in the global installation directory and in the user's private ~/.oz area. Installozmake --install - install using the makefile ozmake --install FILES... - install these targets using the makefile ozmake --install --package=PKG - install package PKG - -i --install install targets of the package and updates the package database - --grade=( none | same | up | down | any | freshen ) default: none what to do if this package is already installed? ozmake will compare version and dates, where the version is more significant. --grade=none signals an error --grade=same requires versions and dates to be the same --grade=up requires a package with newer version or same version and newer release date than the one installed --grade=down requires a package with older version or same version and older release date than the one installed --grade=any no conditions --grade=freshen install if the package is newer else do nothing - -U --upgrade equivalent to --install --grade=up - --downgrade equivalent to --install --grade=down - -A --anygrade equivalent to --install --grade=any - -F --freshen equivalent to --install --grade=freshen - --(no)replacefiles default: false allow installation to overwrite files from other packages - -R --replace equivalent to --install --grade=any --replacefiles - --(no)extendpackage default: false whether to replace or extend the current installation of this package if any - -X --extend equivalent to --install --grade=any --extendpackage - --(no)savedb default: true save the updated database after installation - --includedocs --excludedocs default: --includedocs whether to install the doc targets - --includelibs --excludelibs default: --includelibs whether to install the lib targets - --includebins --excludebins default: --includebins whether to install the bin targets - --(no)keepzombies default: false whether to remove files left over from a previous installation of this package - --exe=( default | yes | no | both | multi ) default: default the convention on Windows is that executables have a .exe,while on Unix they have no extension. The --exe option allows you to control the conventions used by ozmake when installing executables. --exe=default use the platform's convention --exe=yes use a .exe extension --exe=no use no extension --exe=both install all executables with .exe extension and without --exe=multi install executable functors for both Unix and Windows. The Unix versions are installed without extension, and the Windows versions are installed with .exe extension Uninstallozmake --uninstall - uninstall package described by makefile ozmake --uninstall --package=PKG - uninstall package named by mogul id PKG - -e --uninstall uninstall a package Cleanozmake --clean ozmake --veryclean - remove files as specified by the makefile's clean and veryclean features. --veryclean implies --clean . Createozmake --create [--package=<FILE>] - create a package and save it in FILE.the files needed for the package are automatically computed from the makefile. If --package=<FILE> is not supplied, a default is computed using the mogul id (and possibly version number) found in the makefile. - --include(bins|libs|docs) --exclude(bins|libs|docs) control which target types are included in the package Publishozmake --publish - automatically takes care of all the steps necessary for creating/updating a package contributed by the user and making all necessary data available to the MOGUL librarian. See documentation for --mogul below. Extractozmake --extract --package=<PKG> - extract the files from file or URL PKG.if PKG is a mogul id, then the package is automatically downloaded from the mogul archive Listozmake --list - list info for all packages in the installed package database ozmake --list --package=<MOGUL> - list info for the installed package identified by mogul id MOGUL - --linewidth=N default: 70 assume a line with of N characters Configozmake --config=put <OPTIONS> - record the given OPTIONS in ozmake's configuration database, and use them as defaults in subsequent invocations of ozmake unless explicitly overridden on the command line. For example: ozmake --config=put --prefix=/usr/local/oz saves /usr/local/oz as the default value for option --prefix ozmake --config=delete <OPT1> ... <OPTn> - deletes some entries from the configuration database. For example: ozmake --config=delete prefix removes the default for --prefix from the configuration database ozmake --config=list - lists the contents of ozmake's configuration database the argument to --config can be abbreviated to any non-ambiguous prefix Mogul If you choose to contribute packages to the MOGUL archive, ozmake --mogul=<ACTION> simplifies your task. It makes it easy for you to maintain a database of your contributions and to export them so that the MOGUL librarian may automatically find them. In fact, the simplest way is to use ozmake --publish which will take take care of all details for you. ozmake --mogul=put - update the user's database of own mogul contributions with the data for this contribution (in local directory) ozmake --mogul=put --package=<PKG> - same as above, but using the package PKG explicitly given ozmake --mogul=delete <MOG1> ... <MOGn> - remove the entries with mogul ids MOG1 through MOGn from the user's database of own contribution ozmake --mogul=delete - remove entry for current contribution ozmake --mogul=list - show the recorded data for all entries in the user's database of own mogul contributions ozmake --mogul=list <MOG1> ... <MOGn> - show the recorded data for entries MOG1 through MOGn in the user's database of own mogul contributions ozmake --mogul=export - write all necessary mogul entries for the user's own mogul contributions. These are the entries which will be read by the MOGUL librarian to automatically assemble the full MOGUL database. The data for your contributions need to be made available to the MOGUL librarian on the WEB. You want to just update a local directory with your contributions, but, in order for the MOGUL librarian to find them, these directories must also be available through URLs on the WEB. Here are some options that allow you to control this correspondence, and for which you should set default using ozmake --config=put - --moguldir=<MOGULDIR> - --mogulurl=<MOGULURL> MOGULDIR is a directory which is also available on the WEB through url MOGULURL. MOGULDIR is intended as a root directory in which sub-directories for packages, documentation, and mogul entries will be found. For those who really enjoy pain, ozmake has of course many options to shoot yourself in the foot. In the options below <ID> stands for the filename version of the package's mogul id (basically replace slashes by dashes). You can control where packages, their documentation and mogul database entries and stored and made available using the options below: - --mogulpkgdir=<MOGULPKGDIR> default: <MOGULDIR>/pkg/<ID>/ - --mogulpkgurl=<MOGULPKGURL> default: <MOGULURL>/pkg/<ID>/ - --moguldocdir=<MOGULDOCDIR> default: <MOGULDIR>/doc/<ID>/ - --moguldocurl=<MOGULDOCURL> default: <MOGULURL>/doc/<ID>/ - --moguldbdir=<MOGULDBDIR> default: <MOGULDIR>/db/<ID>/ - --moguldburl=<MOGULDBURL> default: <MOGULURL>/db/<ID>/ Your contributions should all have mogul ids which are below the mogul id which you where granted for your section of the mogul database. For convenience, ozmake will attempt to guess the root mogul id of your section as soon as there are entries in your database of your own contributions. However, it is much preferable to tell ozmake about it using: - --mogulrootid=<ROOTID> and to set it using ozmake --config=put --mogulrootid=<ROOTID> MAKEFILE The makefile contains a single Oz record which describes the project and should normally be placed in a file called makefile.oz.A makefile typically looks like this: makefile( lib : ['Foo.ozf'] uri : 'x-ozlib://mylib' mogul : 'mogul:/denys/lib-foo') stating explicitly that there is one library target, namely the functor Foo.ozf,and that it should installed at URI: x-ozlib://mylib/Foo.ozf and implicitly that it should be compiled from the Oz source file Foo.oz.When you invoke ozmake --install,the mogul feature serves to uniquely identify this package and the files it contributes in the ozmake database of installed packages. There are many more features which can occur in the makefile and they are all optional. If you omit all the features, you only get the defaults and you don't even need a makefile. All values, such as files,should be given as virtual string; atoms are recommended except for features blurb, info_text and info_html,where strings are recommended. makefile( bin : [ FILES... ] lib : [ FILES... ] doc : [ FILES... ] src : [ FILES... ] depends : o( FILE : [ FILES... ] ... ) rules : o( FILE : TOOL(FILE) ... ) clean : [ GLOB... ] veryclean : [ GLOB... ] uri : URI mogul : MOGUL author : [ AUTHORS... ] released : DATE blurb : TEXT info_text : TEXT info_html : TEXT subdirs : [ DIRS... ] requires : [ MOGUL... ] categories: [ CATEGORY... ] version : VERSION provides : [ FILES... ] ) Features bin, lib and doc list targets to be installed in <BINDIR>, <LIBDIR> and <DOCDIR> respectively. bin targets should be executable functors, i.e. they should end with extension .exe. lib targets are typically compiled functors i.e. ending with extension .ozf,but could also be native functors, i.e. ending with extension .so,or simply data files. doc targets are documentation files. Extensions ozmake knows how to build targets by looking at the target's extension: Foo.exe - is an executable functor and is created from Foo.ozf Foo.ozf - is a compiled functor and is created from Foo.oz Foo.o - is a compiled C++ file and is created from Foo.cc Foo.so - is a native functor and is created from Foo.o Foo.cc - is a C++ source file Foo.hh - is a C++ header file Note that these are abstract targets. In particular, Foo.so really denotes the file Foo.so-<PLATFORM> where <PLATFORM> identifies the architecture and operating system where the package is built; for example: linux-i486.Also, when a bin target Foo.exe is installed, it is installed both as <BINDIR>/Foo.exe and <BINDIR>/Foo so that it can be invoked as Foo on both Windows and Unix platforms. It is imperative that you respect the conventional use of extensions described here: ozmake permits no variation and supports no other extensions. Rules ozmake has built-in rules for building files. Occasionally, you may want to override the default rule for one or more targets. This is done with feature rule which contains a record mapping target to rule: TARGET_FILE : TOOL(SOURCE_FILE) the rule may also have a list of options: TARGET_FILE : TOOL(SOURCE_FILE OPTIONS) The tools supported by ozmake are ozc (Oz compiler), ozl (Oz linker), cc (C++ compiler), ld (C++ linker). The default rules are: 'Foo.exe' : ozl('Foo.ozf' [executable]) 'Foo.ozf' : ozc('Foo.oz') 'Foo.o' : cc('Foo.cc') 'Foo.so' : ld('Foo.o') The tools support the following options: ozc executable - make the result executable 'define'(S) - define macro S.Same as -DS on the command line ozl executable - make the result executable cc include(DIR) - Similar to the usual C++ compiler option -IDIR. DIR is a virtual string 'define'(MAC) - Similar to the usual C++ compiler option -DMAC. MAC is a virtual string ld library(DIR) - Similar to the usual C++ linker option -lDIR. DIR is a virtual string You might want to specify a rule to create a pre-linked library: 'Utils.ozf' : ozl('Foo.ozf') or to create a non-prelinked executable: 'Foo.exe' : ozc('Foo.oz' [executable]) Dependencies ozmake automatically determines whether targets needed to be rebuilt, e.g. because they are missing or if some source file needed to create them has been modified. The rules are used to determine dependencies between files. Sometimes this is insufficient e.g. because you use tool ozl (dependencies on imports), or insert in an Oz file, or #include in a C++ file. In this case you can specify additional dependencies using feature depends which is a record mapping targets to list of dependencies: TARGET : [ FILES... ] For example: 'Foo.o' : [ 'Foo.hh' 'Baz.hh' ] or 'Foo.exe' : [ 'Lib1.ozf' 'Lib2.ozf' ] Cleaning During development, it is often convenient to be able to easily remove all junk and compiled files to obtain again a clean project directory. This is supported by ozmake --clean and ozmake --veryclean;the latter also implies the former. Files to be removed are specified by glob patterns where ? matches any 1 character and * matches a sequence of 0 or more characters. All files in BUILDDIR matching one such pattern is removed. There are built-in patterns, but you can override them with features clean and veryclean which should be lists of glob patterns. For example the default clean glob patterns are: clean : [ "*~" "*.ozf" "*.o" "*.so-*" "*.exe" ] Package Related Featuresuri feature uri indicates the URI where to install lib targets. For example: uri : 'x-ozlib://mylib/XML' states that all lib targets (e.g. Foo.ozf)will be installed under this URI so that they can also be imported from it, i.e.: import MyFoo at 'x-ozlib://mylib/XML/Foo.ozf' mogul feature mogul is the mogul id uniquely identifying this package. It is used to identify the package in the database of installed packages, to create/publish the package, and to install its documentation files. author feature author is a virtual string or list of virtual string resp. identifying the author or authors of the package. It is recommended to identify authors by their mogul id, however is is also possible to simply give their names. For example, the recommended way is: author : 'mogul:/duchier' but the following is also possible: author : 'Denys Duchier' released feature released is a virtual string specifying the date and time of release in the following format: released : "YYYY-MM-DD-HH:MM:SS" time is optional. An appropriate release date using the current date and time is automatically inserted when invoking ozmake --create or ozmake --publish.. blurb feature blurb contains a very short piece of text describing the package. This text should be just one line and is intended to be used as a title when the package is published in the mogul archive. info_text feature info_text contains a plain text description of the package. This is intended to be used as an abstract on the presentation page for the package in the mogul archive. It should be brief and informative, but should not attempt to document the package. info_html feature info_html is similar to info_text but contains HTML rather than plain text. src feature src indicates which targets should be considered source, i.e. in particular non-buildable. All targets mentioned in src should be mentioned in bin, lib,or doc too. The point of src is to support distributing packages with pre-built targets and without giving out the corresponding sources. You should not do this with native functors since they are platform dependent and not portable, but it can be a convenient means of distributing pre-built Oz libraries. For example: makefile( lib : [ 'Foo.ozf' ] src : [ 'Foo.ozf' ] uri : 'x-ozlib://mylib' mogul : 'mogul:/myname/foolib') is a makefile for a package that distribute the pre-compiled Foo.ozf,but does not also distribute its source Foo.oz.Normally, when you build a package it simply checks that the src files are present but will not attempt to build them. If you have the sources, you can force building the src targets if necessary using --fullbuild.. subdirs feature subdirs is a list of bare filenames representing subdirectories of the project. By default, when necessary, ozmake will recurse into these subdirectories. It is expected that each subdirectory should provide its own makefile. The mogul id is automatically inherited to subdirectories and the uri is automatically extended by appending the name of the subdirectory: thus sub-makefiles can be simpler since they don't need to be concerned with package-level features. requires feature requires is a list of module URIs or package MOGUL ids. These represent the external dependencies of the package. They are not yet used, but eventually ozmake will be able to use them to automate the recursive installation of other packages required by the one you are interested in. categories feature categories is a list of MOGUL categories to help categorize this package in the MOGUL archive. version feature version is used to provide a version string. This is a string that consist of integers separated by single dots, e.g. "2" or "3.1.7".. provides feature provides is used to override the default information about what the package provides, normally automatically computed from the bin and lib targets: it should be a list which contains a subset of these targets. The provides feature of a makefile does not override or otherwise affect its sub-makefiles: each makefile should separately override if it so desires. To state that a makefile does not officially provide any functors or executable application, you would add: provides : nil You should use the provides feature when your package contains both official public functors as well as purely implementational functors that are not part of the official public interface and should not be mentioned as provided by the package. CONTACTS Authors should really be referred to by mogul ids denoting mogul entries that describe them. In order to make this easier, a makefile.oz may also contain a contact feature which is either a record describing a person, or a list of such records. You should not have a contact feature in every makefile. Rather, the contact feature is usually intended for makefiles that only have a contact feature, i.e. whose only purpose is to create mogul entries for the corresponding persons. Here is an example of such a makefile: makefile( o( mogul : 'mogul:/duchier/denys' name : 'Denys Duchier' www : '')) You can invoke ozmake --publish on such a makefile to contribute the corresponding mogul database entries
http://manpages.org/ozmake
CC-MAIN-2018-09
refinedweb
3,647
52.7
20 November 2009 09:27 [Source: ICIS news] SINGAPORE (ICIS news)--Oman Polypropylene plans to restart its polypropylene (PP) plant in Sohar on 21 November following an eight-day unscheduled shutdown, a source close to the company said on Friday. The 340,000 tonne/year plant was taken off line "due to technical problems at the fluid catalytic cracker (FCC) unit which provides feedstock propylene to the PP plant", the source said. The FCC unit will also restart tomorrow. The outage has tightened PP supply in the ?xml:namespace> Oman Polypropylene officials were not immediately available for comment. Oman Oil owns a 40% stake in the PP maker, while LG International, Gulf Investment and International Petroleum Investment Co (IPIC) each hold a 20% stake in Oman Polypropylene.
http://www.icis.com/Articles/2009/11/20/9265711/oman-polypropylene-to-restart-plant-on-21-november.html
CC-MAIN-2014-41
refinedweb
127
59.43
Components and supplies Necessary tools and machines Apps and online services About this project Introduction.. Assembling 3D Printed Parts Assemble all the printed parts one by one as shown in the photos. You may also follow the video instruction attached in the first step. After assembling use four screws to tightly fix all the parts.: - i. Accept terms & conditions image 1 - ii. Click 'take survey later' and then 'continue' to dismiss the splash screen image 2, 3 - iii. Start a new project (no spaces!) image 4 - iv. Name the project "BluetoothControlDoorLock" (no spaces!) image 5 Code Arduino SketchArduino #include <Servo.h>); delay(100); } void closeDoor(){ myservo.write(65); delay(100); } Custom parts and enclosures Thingiverse Schematics Author Md. Khairul Alam - 10 projects - 202 followers Published onDecember 19, 2017 Members who respect this project you might like
https://create.arduino.cc/projecthub/taifur/arduino-and-android-based-password-protected-door-lock-36887d
CC-MAIN-2018-30
refinedweb
136
69.68
Charming Python Functional programming in Python, Part 2 Wading into functional programming? Content series: This content is part # of # in the series: Charming Python This content is part of the series:Charming Python Stay tuned for additional content in this series.. Bindings >>> car = lambda lst: lst[0] >>> cdr = lambda lst: lst[1:] >>> sum2 = lambda lst: car(lst)+car(cdr(lst)) >>> sum2(range(10)) 1 >>> car = lambda lst: lst[2] >>> sum2(range(10)) 5. >>> car(range(10)) 0 >>> let = Bindings() # "Real world" function names >>> let.r10 = range(10) >>> let.car = lambda lst: lst[0] >>> let.cdr = lambda lst: lst[1:] >>> eval('car(r10)+car(cdr(r10))', namespace(let)) >>> inv = Bindings() # "Inverted list" function names >>> inv.r10 = let.r10 >>> inv.car = lambda lst: lst[-1] >>> inv.cdr = lambda lst: lst[:-1] >>> eval('car(r10)+car(cdr(r10))', namespace(inv)) 17 Closures >>>: Listing 5. Python session showing global variable >>> N = 10 >>> def addN(i): ... global N ... return i+N ... >>> addN(7) # Add global N to argument 17 >>> N = 20 >>> addN(6) # Add global N to argument 26 >>> N = 10 >>> def addN(i, n=N): ... return i+n ... >>> addN(5) # Add 10 15 >>> N = 20 >>> addN(6) # Add 10 (current N doesn't matter) 16 class TaxCalc: deftaxdue(self):return (self.income-self.deduct)*self.rate taxclass = TaxCalc() taxclass.income = 50000 taxclass.rate = 0.30 taxclass.deduct = 10000 print"Pythonic OOP taxes due =", taxclass.taxdue() class TaxCalc: deftax)))(). Tail recursion. Downloadable resources Related topics - Read all three parts in this series. - Read more installments of Charming Python. - his focus is somewhat the reverse of my column, it provides very good general comparisons between Python and Lisp. - A good starting point for functional programming is the Frequently Asked Questions for comp.lang.functional. - I've.
https://www.ibm.com/developerworks/linux/library/l-prog2/index.html
CC-MAIN-2019-13
refinedweb
290
51.55
Summary: Python output buffering is the process of storing the output of your code in buffer memory. Once the buffer is full, the output gets displayed on the standard output screen. Buffering is enabled by default and you can use one of the following methods to disable it: - Execute the Python code with the -ucommand line switch, for example python -u code.py - Use the flushkeyword - Use sys.stdout.flush() - Wrap sys.stdoutin TextIOWrapperand set the buffered size to 0 - Set PYTHONUNBUFFEREDto a non-empty string Problem: Given a Python program; how to disable output buffering? Overview Of Python Output Buffering Before we learn buffering in the context of Python, we should ponder upon what buffer means in real life? Let me answer this question with another question. When you are in a stressful situation, whom or what do you look up to as an option to lessen your stress? On a personal level, I look up to my friends and family. So they are my “buffer” against stress. According to the dictionary definition, a buffer is a person or thing that reduces a shock or that forms a barrier between incompatible or antagonistic people or things. This is what exactly a buffer does when it comes to a programming language like Python (though it is not a person in this case). In terms of computer science, you may consider buffer as a middle layer which ensures a more efficient way for data to be transferred from one location to another in the system. For example, if you are downloading a 100 MB file and 1 MB gets written at a time to the hard disk would mean that it would require a total of 100 disk writes. However, a buffer could ensure that 10 MB gets written at a time to the disk, and this way only 10 disk writes will be needed. Advantages and Disadvantages: From the above scenario, we learned how buffer can act as an intermediate resource and reduce the number of disk writes thereby enhancing write efficiency and memory management. However, when it comes to a programming language, buffering has a downside too. We cannot see the output in real-time. This does not make much of a difference in case of simple or short programs but in complex and long programs that require a lot of computation, this might become a major drawback since we might need a more granular output rather than the entire output being displayed at once for debugging and testing purposes. Example: Consider the following program for which we shall compare the buffered and unbuffered outputs: for buffer in range(20): print(buffer, end=" ") We know that the Output is a range of numbers from 0 to 19, that is 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 But we are more interested in understanding the nature of the output. If buffering is enabled you will get the output at once on the screen after waiting for 19 seconds. However, when buffering is disabled the numbers will be displayed one by one every 2 seconds. You can try this in our interactive shell: Exercise: Which behavior do you observe? How To Disable Output Buffering In Python? By default output buffering is enabled in Python. Let us have a look at the different ways in which we can disable output buffering in python. Method 1: Running Python With -u Command Line Arguement If you want to skip buffering for the entire program then the simplest solution to do this is to run your program using the command line interface and use the -u switch to bypass buffering. The syntax to disable buffering through the command line is: python -u filename.py Output Method 2: Using The Flush Keyword If you want to skip buffering for specific lines of your code, passing the flush keyword as an argument to the print statement is a good option. By default, the flush argument is set as False. To ensure that output buffering is disabled, the flush argument should be set to True. Let us have a look at the following example to understand the syntax and usage of the flush keyword: import time for buffer in range(20): print(buffer, end=" ", flush=True) time.sleep(2) Output Method 3: Using sys.stdout.flush() Using the sys.stdout.flush() forces the program to flush the buffer. Therefore everything in the buffer will be displayed on the standard output without delay. Let us have a look at how sys.stdout.flush() works in the following program: import time import sys for buffer in range(20): print(buffer, end=" ") sys.stdout.flush() time.sleep(2) Output Method 4: Wrapping sys.stdout Using TextIOWrapper And Setting Buffered Size = 0 Another approach to disable the output buffering in python is to open up the stdout in write mode with buffer size set to 0 (unbuffered) and then wrapping it using TextIOWrapper to ensure that you get a TextIO stream and not a binary file object. Also, you must ensure to enable the write_through to eliminate all buffers. Let us have a look at the following code to get a better grip on the above explanation: # open the stdout file descriptor in write mode and set 0 as the buffer size: unbuffered import io import os import sys import time try: # open stdout in binary mode, then wrap it in a TextIOWrapper and enable write_through sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True) # for flushing on newlines only use : # sys.stdout.reconfigure(line_buffering=True) except TypeError: # In case you are on Python 2 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) print("Enter a Line: ") line = sys.stdin.readline() for i in line: print(i, end=" ") time.sleep(2) Output Method 5: Setting Python Environment Variable PYTHONUNBUFFERED When the PYTHONUNBUFFERED variable is set to a non-empty string, it is equivalent to the -u command line option. Conclusion I hope this article helped you to get an overview of Python output buffering and the methods to disable it. Please stay tuned for more!
https://blog.finxter.com/what-is-python-output-buffering-and-how-to-disable-it/
CC-MAIN-2020-50
refinedweb
1,030
68.5
Member Since 2 Years Ago 3,490? Thanks for your help @jeromefitzpatrick I dumped the data inside the UrlGenerator class and I've seen that the $original variable has some extra data appended because the user team's routes file is inside a 'team' middleware which adds additional information about the team and domain. Not fixed yet but I found the issue and it will be fixed soon. Thanks for your help! I'll post the fix here when its done. Replied to Can Temporary Signed Routes Be Used For Guest Users? Yep, I understand. The signature is failing (because I assume the expiration is still valid after 5 secs of sending the mail). I was using ngrok with my app domain at that moment but I tested with local domain and still failing. The generated URL looks like this:[email protected]?expires=1608277901&signature=a1b6c27993706374dea35fff96b579d533c9f0f0b38c83a5bcbe3b0f9b882044, so i don't think there's SSL or domain problems. The only thing I can think about is that I'm using multitenant and custom domains. This mydomain.test is not the APP_DOMAIN, is my customer team's domain. But as long as i know, only the APP_KEY is used, right? Replied to Can Temporary Signed Routes Be Used For Guest Users? Thanks for the reply. There's no middleware in that route/controller. The route is publicly accessible and I checked that the hasValidSignature() is returning false. For the other questions, I just copied the VerifyEmail signed URL because I wanted to mimic the verify email functionality. And yes I forgot to remove the sha1 and just pass team and email or maybe store the contact with "unverified" status and set up a cron to clean old unverified contacts. But I didn't want to store the newsletter contact for legal reasons until they confirm from their email. My idea is to do something like this after the hasValidSignature: public function storeContact(Team $team, string $email) { $team->contacts()->create([ 'email' => $email, 'sources' => [Contact::SOURCE_NEWSLETTER] ]) } The problem is that the verification is failing. And as long as i know only the APP_KEY is used, so should be correct. Started a new Conversation Can Temporary Signed Routes Be Used For Guest Users? I'm sending a confirmation email to users signing up for a newsletter. I use a temporary signed url so when the user clicks the URL they are added to the newsletter. The problem is that the signature validation is returning false but I'm using the temporary URL generator like always so I'm guessing that maybe the validation check uses the model id to verify if that email is related to the model? This is how I generate the route in this case // Link generation $confirmationLink = URL::temporarySignedRoute( 'newsletter.subscribe.confirm', Carbon::now()->addMinutes(60 * 24), [ 'id' => $team->id, 'hash' => sha1(request()->email), ] ); // Validation Route::get('/newsletter/subscribe/confirm', [NewsletterController::class, 'store']) ->name('newsletter.subscribe.confirm'); public function store() { if (! request()->hasValidSignature()) { abort(401); } // } Can it be failing because I'm passing a team id (owner of the newsletter) and Laravel tries to validate doing a $team->email === sha1(request()->email) or something like this? This article suggests that the singed URL may need a record in the database: Seems like this is the issue then? Started a new Conversation A Model HasMany Different Models I'm having problems trying to decide the correct database structure for the following scenario: I have a Canvas model which can have many different items related: $shapes = $canvas->shapes I need this relationship to retrieve different kinds of shapes on different database tables: The above query should return a collection of ShapeSquare, ShapeCircle, ShapeTriangle... I was thinking to create a Shapes table with canvas_id, shapable_id, shapable_type and then do $canvas->shapes->shapable. Is this approach correct? Started a new Conversation Livewire Temporary File Upload Directly To S3 Is Crashing File uploads are working if using local disk but when switching to s3 driver, I get the following error: Call to undefined method League\Flysystem\Cached\CachedAdapter::getClient() // GenerateSignedUploadUrl.php $command = $adapter->getClient()->getCommand('putObject', array_filter([ 'Bucket' => $adapter->getBucket(), 'Key' => $path, 'ACL' => $visibility, 'ContentType' => $fileType ?: 'application/octet-stream', 'CacheControl' => null, 'Expires' => null, ])); My config is the following: 'temporary_file_upload' => [ 'disk' => 's3', 'rules' => ['required', 'file', 'max:40000'], 'directory' => 'livewire-tmp', 'middleware' => 'throttle:10,1', 'preview_mimes' => [ 'png', 'gif', 'bmp', 'svg', 'wav', 'mp4', 'mov', 'avi', 'wmv', 'mp3', 'm4a', 'jpeg', 'mpga', 'webp', 'wma' ], ], I have this same s3 disk working for other uploads. It's just crashing for the temporary uploads from Livewire. Replied to Don't Match Regex Expression If String IS Certain String Perfect! Started a new Conversation Don't Match Regex Expression If String IS Certain String I want to use a regex match to find if a string is a domain/custom domain or my app domain. I've managed to match the domains with this expression: Route::pattern('domain', '[a-z0-9.\-]+'); But I would like to don't match if the string IS my app domain. user.com -> match sub.mydomain.com ->match mydomain.com -> no match I've tried testing lookahead in but I can not make it work. The best try is this one: (?!domain\.com)[a-z0-9.\-]+ // but "omain.com" still selected Screenshot -> Started a new Conversation Let's Finally Solve The Eternal Question About Routing The App, Subdomains And Custom Domains. I've seen this question on the internet many times but seems like no one is able to give a solution. The scenario is really simple: Having routes for your app which allows your users to use either subdomains or custom domains. That means that we need a standard web.php routes file and then a user.php routes file containing the routes that custom domains and subdomains will use. If someone accesses app.com will see your app (where users log in / register, update settings, manage data, etc...). If someone accesses user.app.com will see the user content. If someone accesses user.com will see the same user content if they configured a custom domain. After many tries, I did this, which seemed to work: // RouteServiceProvider public function boot() { $this->configureRateLimiting(); $this->routes(function () { if (is_team_host()) { Route::middleware('team') ->namespace($this->namespace) ->group(base_path('routes/team.php')); } else { Route::domain(config('app.domain')) ->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } }); } Worked well because when accessed from a user host, the web routes are not registered. The problem is when you run php artisan route:cache, the helper method causes some issue and the routes return 404. Another attempt. Also works but route:cache can not be triggered since it detects duplicated routes (since app and team pages have auth routes and views). // RouteServiceProvider public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::domain(config('app.domain')) ->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); Route::middleware('team') ->namespace($this->namespace) ->group(base_path('routes/team.php')); }); } For now, I can only make it work without the route cache. Any suggestions? Replied to Laravel Jetstream Ignore Routes Not Working Yes! Seems I used the wrong method. Thanks! Started a new Conversation Laravel Jetstream Ignore Routes Not Working I started a new Jetstream app where I need to use team uuid instead of the id. For this reason, I'm trying to override the default routes so i can point to custom controller and retrieve the team model by uuid. The problem is that after doing this... // JetstreamServiceProvider public function boot() { $this->configurePermissions(); Jetstream::ignoreRoutes(); // this } ... I can still access the /tems/{teamId} show route. I can't understand why the routes are still being registered. Started a new Conversation Livewire + Alpine Equivalent Of Axios Call + Do Something With The Return I recently started playing with Livewire. There's one scenario where I can not find the right solution at the documentation and I need some advice from a more experienced Livewire + Alpinejs user. For example, when working with Stripe, what I usually do is post an ajax request that will generate the session id at the backend and then return to the front where the Stripe code redirects the user to the payment page. How would you implement this with Livewire and Alpine? I've tried this but it doesn't work: <div> <button wire: <span>{{ $pricing->name }} ({{ $pricing->type }})</span> <span> {{ $pricing->price }} {{ $pricing->currency }} </span> </button> </div> Finally used this approach but, is there any better approach? // Livewire method $this->dispatchBrowserEvent('checkout-created', $session->id); // Front window.addEventListener('checkout-created', event => { goToCheckout(event.detail) }) Replied to Good Video Service For An Education Saas I really appreciate your feedback @sinnbeck Actually, I already know the technical part, I just wanted to open a discussion about video hosting and streaming providers because I'm new to the e-education world and maybe I missed some important services while researching online. Really interested in services that I can pay per user or per usage. Because I don't want to pay Vimeo 600$ while having 0 users. I need something that i can know the cost per user so I can charge it in their fee. Thank you Replied to Good Video Service For An Education Saas Thanks for the feedback. I think Laracasts use Vimeo. But the scenario is a bit different because Laracasts is the only one uploading videos. I will take a look at this resource but I'm not sure if this will fit my scenario since every user is uploading their content and serving from their custom domain. Thanks Started a new Conversation Good Video Service For An Education Saas I'm building an educational saas app where my users are going to upload videos. I don't want to host and stream them, so I'm trying to find a good service with nice API. Has anyone been in this spot before or has some recommendations? Thanks! Replied to Subdomains And Authenticated Actions On The Main Domain What do you mean? Sorry if my explanation was not good. What I mean, is that the users of my saas, can chose a subdomain or domain where their content will be displayed. I solved it using a route pointing the main Laravel app. Started a new Conversation Subdomains And Authenticated Actions On The Main Domain I'm building an app where my users can create their own page in a subdomain or custom domain. The challenge here is that in those pages, the visitors can click a button that does a certain action in the main website/domain, the app domain. And that action needs to check whether they are logged in or not in order to decide if redirect them to login or proceed with the action. Obviously now it doesn't work because the code is checking if the user is authenticated in the subdomain or custom domain of the user, which is always going to be false. I'm trying to find a clean and standard way to execute authenticated actions in the main app from those custom pages. The first thing it comes to my mind is using the API. Although I am not an expert working with API I think I should put some kind of limitation, so only calls from my user's domains can be executed? But also I think the only way to check if a visitor of those websites is authenticated is to check the cookies in his browser from my main domain, is that correct? Is this approach correct? Am I missing something? Thanks! Edit: I found this answer here, but I'm not sure if that is a good practice... Replied to Mailgun Driver Not Sending Email And Not Giving Any Error And maybe the manual config:cache worked, because i can see the logs after that. I found what's the issue I think. I don't know why it is randomly sending the mails to the spam folder. Some end up there and some end up at the inbox. Replied to Mailgun Driver Not Sending Email And Not Giving Any Error Yes, it's in my deploy script and also tried manually from terminal. My deplay script has: php artisan config:cache Not sure if I have to add php artisan config:clear before that Started a new Conversation Mailgun Driver Not Sending Email And Not Giving Any Error I'm using the Mailgun api driver for sending the transactional emails. I followed the documentation and it's working in my local machine. I pushed to production but no emails are sent and the Mailgun dashboard shows no activity. I checked other questions from people with similar problems but seems like everything is okay. This is what I've done: MAIL_MAILER=mailgun MAILGUN_DOMAIN=mg.domain.com MAILGUN_SECRET=my_secret MAILGUN_ENDPOINT=api.eu.mailgun.net [email protected] MAIL_FROM_NAME="${APP_NAME}" What else can i do to debug this issue? Replied to Cashier With Stripe Webhook Not Updating The Model Thank you so much. I've solved the problem now. Not extending the original class I've realized that the original one was still hit. That's because my endpoint was /stripe/inbox since i changed many times for testing and i forgot to update it in Stripe's dashboard so it was still using the old /stripe/webhook endpoint. Replied to Cashier With Stripe Webhook Not Updating The Model Same result. I thought maybe some other method, file or route overriding or something. But I can not find anything that makes sense for now. Replied to Cashier With Stripe Webhook Not Updating The Model Yes. [2020-08-09 14:33:13] local.INFO: method doent exits: handleCheckoutSessionCompleted Replied to Cashier With Stripe Webhook Not Updating The Model Yes, sorry. I should have given some code. After investigating more about it, I think I've found the problem. Seems like the method I extended can not be found. Basically Stripe is posting to this endpoint: Route::post('/stripe/inbox', [CashierWebhookController::class, 'handleWebhook']); which has the following code: <?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Laravel\Cashier\Events\WebhookHandled; use Laravel\Cashier\Events\WebhookReceived; use Laravel\Cashier\Http\Controllers\WebhookController as CashierController; class CashierWebhookController extends CashierController { public function handleWebhook(Request $request) { $payload = json_decode($request->getContent(), true); $method = 'handle'.Str::studly(str_replace('.', '_', $payload['type'])); WebhookReceived::dispatch($payload); if (method_exists($this, $method)) { $response = $this->{$method}($payload); WebhookHandled::dispatch($payload); return $response; } else { info('method doent exits: ' . $method); } return $this->missingMethod(); } // this method is not found! public function handleCheckoutSessionCompleted(array $payload) { info('stripe is posting'); } } For some reason the method_exists($this, 'handleCheckoutSessionCompleted') returns false. Started a new Conversation Cashier With Stripe Webhook Not Updating The Model I create a checkout session, complete the payment and get redirected to the success URL. Then, I'm expecting Stripe to hit the endpoint i defined at the Stripe dashboard (using ngrok since its in my local machine), but it never hits and the code doesn't get exectued. Also I tried to send a test request inside the Stripe's webhook dashboard and it says: "Success. Webhook Handled" but it never hits my code since I have a log inside the method. I'm kind of new with webhooks. Am I missing something?
https://laracasts.com/@bufferoverflow
CC-MAIN-2021-04
refinedweb
2,556
55.44
Greetings! I've now lost the input lisp file, but the problem is that the C definition needs to precede its usage in the .c output file: #include "cmpinclude.h" #include "sdk-hello.h" void init_sdk_hello(){do_init(VV);} #include <windows.h> /* function definition for SDK-HELLO */ static void L1() { object *old_base=vs_base; object x; x= sdk_hello( vs_base[0]); vs_top=(vs_base=old_base)+1; vs_base[0]=x; } /* C function defined by DEFCFUN */ static object sdk_hello( object ret ) { object *vs=vs_top; object *old_top=vs_top+0; { MessageBox( NULL, "Hello world!", "Hello demo", MB_OK ); return ret; } vs_top=vs; } #ifdef SYSTEM_SPECIAL_INIT SYSTEM_SPECIAL_INIT #endif Does this differ in 2.7 and 2.6? If you could supply the lisp again I can check too. Take care, "Mike Thomas" <address@hidden> writes: > Hi Camm. > > | To use compiler::link, you have to set the :system-p t flag in > | compiler-file, or alternately (setq compiler::*default-system-p* t). > | This will ensure that the init functions for each module will be > | uniquely named based on the lisp filename, as compiler::link expects. > | This should be mentioned in the docs. Otherwise your call above is > | fine. > > Per separate message this all worked thanks. > > | What is the sdk btw? > > Shorthand for the Microsoft Windows Software Development Kit which comprises > most (if not all) of the Windows libraries, headers, examples, documentation > etc and is downloadable for free from the Micsosoft Developers Network > (MSDN) site - a very big download. > > > | >:>>> > | > | Mike, two questions here: > | > | 1) This is 2.6.7pre, not CVS head, no? > > Yes; the problem also occurs for CVS HEAD as I was using gcc 3.4.2 for both > of those builds. > > > | 2) What are lines 5289 and 5281 (with a little context) of > | sdk-hello.c? > > I recompiled using the CVS HEAD and the :system-p t flag which makes a much > smaller file which is now attached to this message: > > ============================================== > >(compile-file "c:/cvs/stable/gcl-2.6.7pre/sdk-hello.lsp" :system-p t) > > Compiling c:/cvs/stable/gcl-2.6.7pre/sdk-hello.lsp. > End of Pass 1. > End of Pass 2. > c:/cvs/stable/gcl-2.6.7pre/sdk-hello.c:20: error: conflicting types for > 'sdk_hel > lo' > c:/cvs/stable/gcl-2.6.7pre/sdk-hello.c:12: error: previous implicit > declaration > of 'sdk_hello' was here > (SYSTEM > "gcc -c -Wall -DVOL=volatile -fsigned-char -pipe -fno-zero-initialized-i > n-bss -mms-bitfields -march=i686 -mfpmath=387 -Ic:/cvs/head/gcl/unixport/../ > h - >:>>>3 > > Error in UNLESS [or a callee]: The tag (NIL) is undefined. > > Fast links are on: do (use-fast-links nil) for debugging > Broken at CERROR. > 1 (Abort) Return to debug level 1. > 2 Continues anyway. > 3 Return to break level 1. > 4 Return to top level. > dbl:>>>> > > ============================================== > > Cheers > > Mike Thomas. > > > > -- Camm Maguire address@hidden ========================================================================== "The earth is but one country, and mankind its citizens." -- Baha'u'llah
http://lists.gnu.org/archive/html/gcl-devel/2005-05/msg00039.html
CC-MAIN-2015-35
refinedweb
476
60.41
Frankenstein Migration: Framework-Agnostic Approach (Part 2) In this article, we’ll be putting all the theory to the test by performing step-by-step migration of an application, following the recommendations from the previous part. To make things straightforward, reduce uncertainties, unknowns, and unnecessary guessing, for the practical example of migration, I decided to demonstrate the practice on a simple to-do application. In general, I assume that you have a good understanding of how a generic to-do application works. This type of application suits our needs very well: it’s predictable, yet has a minimum viable number of required components to demonstrate different aspects of Frankenstein Migration. However, no matter the size and complexity of your real application, the approach is well-scalable and is supposed to be suitable for projects of any size. For this article, as a starting point, I picked a jQuery application from the TodoMVC project — an example that may already be familiar to a lot of you. jQuery is legacy enough, might reflect a real situation with your projects, and most importantly, requires significant maintenance and hacks for powering a modern dynamic application. (This should be enough to consider migration to something more flexible.) What is this “more flexible” that we are going to migrate to then? To show a highly-practical case useful in real life, I had to choose among the two most popular frameworks these days: React and Vue. However, whichever I would pick, we would miss some aspects of the other direction. So in this part, we’ll be running through both of the following: - A migration of a jQuery application to React, and - A migration of a jQuery application to Vue. Code Repositories All the code mentioned here is publicly available, and you can get to it whenever you want. There are two repositories available for you to play with: - Frankenstein TodoMVC This repository contains TodoMVC applications in different frameworks/libraries. For example, you can find branches like vue, angularjs, reactand jqueryin this repository. - Frankenstein Demo It contains several branches, each of which represents a particular migration direction between applications, available in the first repository. There are branches like migration/jquery-to-reactand migration/jquery-to-vue, in particular, that we’ll be covering later on. Both repositories are work-in-progress and new branches with new applications and migration directions should be added to them regularly. (You’re free to contribute as well!) Commits history in migration branches is well structured and might serve as additional documentation with even more details than I could cover in this article. Now, let’s get our hands dirty! We have a long way ahead, so don’t expect it to be a smooth ride. It’s up to you to decide how you want to follow along with this article, but you could do the following: - Clone the jquerybranch from the Frankenstein TodoMVC repository and strictly follow all of the instructions below. - Alternatively, you can open a branch dedicated to either migration to React or migration to Vue from the Frankenstein Demo repository and follow along with commits history. - Alternatively, you can relax and keep reading because I am going to highlight the most critical code right here, and it’s much more important to understand the mechanics of the process rather than the actual code. I’d like to mention one more time that we’ll strictly be following the steps presented in the theoretical first part of the article. Let’s dive right in! - Identify Microservices - Allow Host-to-Alien Access - Write An Alien Microservice/Component - Write Web Component Wrapper Around Alien Service - Replace Host Service With Web Component - Rinse & Repeat For All Of Your Components - Switch To Alien 1. Identify Microservices As Part 1 suggests, in this step, we have to structure our application into small, independent services dedicated to one particular job. The attentive reader might notice that our to-do application is already small and independent and can represent one single microservice on its own. This is how I would treat it myself if this application would live in some broader context. Remember, however, that the process of identifying microservices is entirely subjective and there is no one correct answer. So, in order to see the process of Frankenstein Migration in more detail, we can go a step further and split this to-do application into two independent microservices: - An input field for adding a new item. This service can also contain the application’s header, based purely on positioning proximity of these elements. - A list of already added items. This service is more advanced, and together with the list itself, it also contains actions like filtering, list item’s actions, and so on. Tip: To check whether the picked services are genuinely independent, remove HTML markup, representing each of these services. Make sure that the remaining functions still work. In our case, it should be possible to add new entries into localStorage (that this application is using as storage) from the input field without the list, while the list still renders the entries from localStorage even if the input field is missing. If your application throws errors when you remove markup for potential microservice, take a look at the “Refactor If Needed” section in Part 1 for an example of how to deal with such cases. Of course, we could go on and split the second service and the listing of the items even further into independent microservices for each particular item. However, it might be too granular for this example. So, for now, we conclude that our application is going to have two services; they are independent, and each of them works towards its own particular task. Hence, we have split our application into microservices. 2. Allow Host-to-Alien Access Let me briefly remind you of what these are. - Host This is what our current application is called. It is written with the framework from which we’re about to move away from. In this particular case, our jQuery application. - Alien Simply put, this one’s a gradual re-write of Host on the new framework that we are about to move to. Again, in this particular case, it’s a React or Vue application. The rule of thumb when splitting Host and Alien is that you should be able to develop and deploy any of them without breaking the other one — at any point in time. Keeping Host and Alien independent from each other is crucial for Frankenstein Migration. However, this makes arranging communication between the two a bit challenging. How do we allow Host access Alien without smashing the two together? Adding Alien As A Submodule Of Your Host Even though there are several ways to achieve the setup we need, the simplest form of organizing your project to meet this criterion is probably git submodules. This is what we’re going to use in this article. I’ll leave it up to you to read carefully about how submodules in git work in order to understand limitations and gotchas of this structure. The general principles of our project’s architecture with git submodules should look like this: - Both Host and Alien are independent and are kept in separate gitrepositories; - Host references Alien as a submodule. At this stage, Host picks a particular state (commit) of Alien and adds it as, what looks like, a subfolder in Host’s folder structure. The process of adding a submodule is the same for any application. Teaching git submodules is beyond the scope of this article and is not directly related to Frankenstein Migration itself. So let’s just take a brief look at the possible examples. In the snippets below, we use the React direction as an example. For any other migration direction, replace react with the name of a branch from Frankenstein TodoMVC or adjust to custom values where needed. If you follow along using the original jQuery TodoMVC application: $ git submodule add -b react git@gitlab.com:mishunov/frankenstein-todomvc.git react $ git submodule update --remote $ cd react $ npm i If you follow along with migration/jquery-to-react (or any other migration direction) branch from the Frankenstein Demo repository, the Alien application should already be in there as a git submodule, and you should see a respective folder. However, the folder is empty by default, and you need to update and initialize the registered submodules. From the root of your project (your Host): $ git submodule update --init $ cd react $ npm i Note that in both cases we install dependencies for the Alien application, but those become sandboxed to the subfolder and won’t pollute our Host. After adding the Alien application as a submodule of your Host, you get independent (in terms of microservices) Alien and Host applications. However, Host considers Alien a subfolder in this case, and obviously, that allows Host to access Alien without a problem. 3. Write An Alien Microservice/Component At this step, we have to decide what microservice to migrate first and write/use it on the Alien’s side. Let’s follow the same order of services we identified in Step 1 and start with the first one: input field for adding a new item. However, before we begin, let’s agree that beyond this point, we are going to use a more favorable term component instead of microservice or service as we are moving towards the premises of frontend frameworks and the term component follows the definitions of pretty much any modern framework. Branches of Frankenstein TodoMVC repository contain a resulting component that represents the first service “Input field for adding a new item” as a Header component: Writing components in the framework of your choice is beyond the scope of this article and is not part of Frankenstein Migration. However, there are a couple of things to keep in mind while writing an Alien component. Independence First of all, the components in Alien should follow the same principle of independence, previously set up on the Host’s side: components should not depend on other components in any way. Interoperability Thanks to the independence of the services, most probably, components in your Host communicate in some well-established way be it a state management system, communication through some shared storage or, directly via a system of DOM events. “Interoperability” of Alien components means that they should be able to connect to the same source of communication, established by Host, to dispatch information about its state changes and listen to changes in other components. In practice, this means that if components in your Host communicate via DOM events, building your Alien component exclusively with state management in mind won’t work flawlessly for this type of migration, unfortunately. As an example, take a look at the js/storage.js file that is the primary communication channel for our jQuery components: ... fetch: function() { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"); }, save: function(todos) { localStorage.setItem(STORAGE_KEY, JSON.stringify(todos)); var event = new CustomEvent("store-update", { detail: { todos } }); document.dispatchEvent(event); }, ... Here, we use localStorage (as this example is not security-critical) to store our to-do items, and once the changes to the storage get recorded, we dispatch a custom DOM event on the document element that any component can listen to. At the same time, on the Alien’s side (let’s say React) we can set up as complex state management communication as we want. However, it’s probably smart to keep it for the future: to successfully integrate our Alien React component into Host, we have to connect to the same communication channel used by Host. In this case, it’s localStorage. To make things simple, we just copied over Host’s storage file into Alien and hooked up our components to it: import todoStorage from "../storage"; class Header extends Component { constructor(props) { this.state = { todos: todoStorage.fetch() }; } componentDidMount() { document.addEventListener("store-update", this.updateTodos); } componentWillUnmount() { document.removeEventListener("store-update", this.updateTodos); } componentDidUpdate(prevProps, prevState) { if (prevState.todos !== this.state.todos) { todoStorage.save(this.state.todos); } } ... } Now, our Alien components can talk the same language with Host components and vice versa. 4. Write Web Component Wrapper Around Alien Service Even though we’re now only on the fourth step, we have achieved quite a lot: - We’ve split our Host application into independent services which are ready to be replaced by Alien services; - We’ve set up Host and Alien to be completely independent of each other, yet very well connected via git submodules; - We’ve written our first Alien component using the new framework. Now it’s time to set up a bridge between Host and Alien so that the new Alien component could function in the Host. Reminder from Part 1: Make sure that your Host has a package bundler available. In this article, we rely on Webpack, but it doesn’t mean that the technique won’t work with Rollup or any other bundler of your choice. However, I leave the mapping from Webpack to your experiments. Naming Convention As mentioned in the previous article, we are going to use Web Components to integrate Alien into Host. On the Host’s side, we create a new file: js/frankenstein-wrappers/Header-wrapper.js. (It’s going to be our first Frankenstein wrapper.) Keep in mind that it’s a good idea to name your wrappers the same as your components in Alien application, e.g. just by adding a “ -wrapper” suffix. You”ll see later on why this is a good idea, but for now, let’s agree that this means that if the Alien component is called Header.js (in React) or Header.vue (in Vue), the corresponding wrapper on the Host’s side should be called Header-wrapper.js. In our first wrapper, we begin with the fundamental boilerplate for registering a custom element: class FrankensteinWrapper extends HTMLElement {} customElements.define("frankenstein-header-wrapper", FrankensteinWrapper); Next, we have to initialize Shadow DOM for this element. Please refer to Part 1 to get reasoning on why we use Shadow DOM. class FrankensteinWrapper extends HTMLElement { connectedCallback() { this.attachShadow({ mode: "open" }); } } With this, we have all the essential bits of the Web Component set up, and it’s time to add our Alien component into the mix. First of all, at the beginning of our Frankenstein wrapper, we should import all the bits responsible for the Alien component’s rendering. import React from "../../react/node_modules/react"; import ReactDOM from "../../react/node_modules/react-dom"; import HeaderApp from "../../react/src/components/Header"; ... Here we have to pause for a second. Note that we do not import Alien’s dependencies from Host’s node_modules. Everything comes from the Alien itself that sits in react/ subfolder. That is why Step 2 is so important, and it is crucial to make sure the Host has full access to assets of Alien. Now, we can render our Alien component within Web Component’s Shadow DOM: ... connectedCallback() { ... ReactDOM.render(<HeaderApp />, this.shadowRoot); } ... Note: In this case, React doesn’t need anything else. However, to render the Vue component, you need to add a wrapping node to contain your Vue component like the following: ... connectedCallback() { const mountPoint = document.createElement("div"); this.attachShadow({ mode: "open" }).appendChild(mountPoint); new Vue({ render: h => h(VueHeader) }).$mount(mountPoint); } ... The reason for this is the difference in how React and Vue render components: React appends component to referenced DOM node, while Vue replaces referenced DOM node with the component. Hence, if we do .$mount(this.shadowRoot) for Vue, it essentially replaces the Shadow DOM. That’s all we have to do to our wrapper for now. The current result for Frankenstein wrapper in both jQuery-to-React and jQuery-to-Vue migration directions can be found over here: To sum up the mechanics of the Frankenstein wrapper: - Create a custom element, - Initiate Shadow DOM, - Import everything needed for rendering an Alien component, - Render the Alien component within the custom element’s Shadow DOM. However, this doesn’t render our Alien in Host automatically. We have to replace the existing Host markup with our new Frankenstein wrapper. Fasten your seatbelts, it may not be as straightforward as one would expect! 5. Replace Host Service With Web Component Let’s go on and add our new Header-wrapper.js file to index.html and replace the existing header markup with the newly-created <frankenstein-header-wrapper> custom element. ... <!-- <header class="header">--> <!-- <h1>todos</h1>--> <!-- <input class="new-todo" placeholder="What needs to be done?" autofocus>--> <!-- </header>--> <frankenstein-header-wrapper></frankenstein-header-wrapper> ... <script type="module" src="js/frankenstein-wrappers/Header-wrapper.js"></script> Unfortunately, this won’t work as simple as that. If you open a browser and check the console, there is the Uncaught SyntaxError waiting for you. Depending on the browser and its support for ES6 modules, it will either be related to ES6 imports or to the way the Alien component gets rendered. Either way, we have to do something about it, but the problem and solution should be familiar and clear to most of the readers. 5.1. Update Webpack and Babel where needed We should involve some Webpack and Babel magic before integrating our Frankenstein wrapper. Wrangling these tools is beyond the scope of the article, but you can take a look at the corresponding commits in the Frankenstein Demo repository: Essentially, we set up the processing of the files as well as a new entry point frankenstein in Webpack’s configuration to contain everything related to Frankenstein wrappers in one place. Once Webpack in Host knows how to process the Alien component and Web Components, we’re ready to replace Host’s markup with the new Frankenstein wrapper. 5.2. Actual Component’s Replacement The component’s replacement should be straightforward now. In index.html of your Host, do the following: - Replace <header class="header">DOM element with <frankenstein-header-wrapper>; - Add a new script frankenstein.js. This is the new entry point in Webpack that contains everything related to Frankenstein wrappers. ... <!-- We replace <header class="header"> --> <frankenstein-header-wrapper></frankenstein-header-wrapper> ... <script src="./frankenstein.js"></script> That’s it! Restart your server if needed and witness the magic of the Alien component integrated into Host. However, something still seemd to be is missing. The Alien component in the Host context doesn’t look the same way as it does in the context of the standalone Alien application. It’s simply unstyled. Why is it so? Shouldn’t the component’s styles be integrated with the Alien component into Host automatically? I wish they would, but as in too many situations, it depends. We’re getting to the challenging part of Frankenstein Migration. 5.3. General Information On The Styling Of The Alien Component First of all, the irony is that there is no bug in the way things work. Everything is as it’s designed to work. To explain this, let’s briefly mention different ways of styling components. Global Styles We all are familiar with these: global styles can be (and usually are) distributed without any particular component and get applied to the whole page. Global styles affect all DOM nodes with matching selectors. A few examples of global styles are <style> and <link rel="stylesheet"> tags found into your index.html. Alternatively, a global stylesheet can be imported into some root JS module so that all components could get access to it as well. The problem of styling applications in this way is obvious: maintaining monolithic stylesheets for large applications becomes very hard. Also, as we saw in the previous article, global styles can easily break components that are rendered straight in the main DOM tree like it is in React or Vue. Bundled Styles These styles usually are tightly coupled with a component itself and are rarely distributed without the component. The styles typically reside in the same file with the component. Good examples of this type of styling are styled-components in React or CSS Modules and Scoped CSS in single file components in Vue. However, no matter the variety of tools for writing bundled styles, the underlying principle in most of them is the same: the tools provide a scoping mechanism to lock down styles defined in a component so that the styles don’t break other components or global styles. Why Could Scoped Styles Be Fragile? In Part 1, when justifying the use of Shadow DOM in Frankenstein Migration, we briefly covered the topic of scoping vs. encapsulation) and how encapsulation of Shadow DOM is different from scoping styling tools. However, we did not explain why scoping tools provide such fragile styling for our components, and now, when we faced the unstyled Alien component, it becomes essential for understanding. All scoping tools for modern frameworks work similarly: - You write styles for your component in some way without thinking much about scope or encapsulation; - You run your components with imported/embedded stylesheets through some bundling system, like Webpack or Rollup; - The bundler generates unique CSS classes or other attributes, creating and injecting individual selectors for both your HTML and corresponding stylesheets; - The bundler makes a <style>entry in the <head>of your document and puts your components’ styles with unique mingled selectors in there. That’s pretty much it. It does work and works fine in many cases. Except for when it does not: when styles for all components live in the global styling scope, it becomes easy to break those, for example, using higher specificity. This explains the potential fragility of scoping tools, but why is our Alien component completely unstyled? Let’s take a look at the current Host using DevTools. When inspecting the newly-added Frankenstein wrapper with the Alien React component, for example, we can see something like this: So, Webpack does generate unique CSS classes for our component. Great! Where are the styles then? Well, the styles are precisely where they are designed to be — in the document’s <head>. So everything works as it should, and this is the main problem. Since our Alien component resides in Shadow DOM, and as explained in Part #1, Shadow DOM provides full encapsulation of components from the rest of the page and global styles, including those newly-generated stylesheets for the component that cannot cross the shadow border and get to the Alien component. Hence, the Alien component is left unstyled. However, now, the tactics of solving the problem should be clear: we should somehow place the component’s styles in the same Shadow DOM where our component resides (instead of the document’s <head>). 5.4. Fixing Styles For The Alien Component Up until now, the process of migrating to any framework was the same. However, things start diverging here: every framework has its recommendations on how to style components, and hence, the ways of tackling the problem differ. Here, we discuss most common cases but, if the framework you work with uses some unique way of styling components, you need to keep in mind the basic tactics such as putting the component’s styles into Shadow DOM instead of <head>. In this chapter, we are covering fixes for: - Bundled styles with CSS Modules in Vue (tactics for Scoped CSS are the same); - Bundled styles with styled-components in React; - Generic CSS Modules and global styles. I combine these because CSS Modules, in general, are very similar to the global stylesheets and can be imported by any component making the styles disconnected from any particular component. Constraints first: anything we do to fix styling should not break the Alien component itself. Otherwise, we lose the independence of our Alien and Host systems. So, to address the styling issue, we are going to rely on either bundler’s configuration or the Frankenstein wrapper. Bundled Styles In Vue And Shadow DOM If you’re writing a Vue application, then you’re most probably using single file components. If you’re also using Webpack, you should be familiar with two loaders vue-loader and vue-style-loader. The former allows you to write those single file components while the latter dynamically injects the component’s CSS into a document as a <style> tag. By default, vue-style-loader injects the component’s styles into the document’s <head>. However, both packages accept the shadowMode option in configuration which allows us to easily change the default behavior and inject styles (as the option’s name implies) into Shadow DOM. Let’s see it in action. Webpack Configuration At a bare minimum, the Webpack configuration file should contain the following: const VueLoaderPlugin = require('vue-loader/lib/plugin'); ... module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { shadowMode: true } }, { test: /\.css$/, include: path.resolve(__dirname, '../vue'), use: [ { loader:'vue-style-loader', options: { shadowMode: true } }, 'css-loader' ] } ], plugins: [ new VueLoaderPlugin() ] } In a real application, your test: /\.css$/ block will be more sophisticated (probably involving the oneOf rule) to account for both Host and Alien configurations. However, in this case, our jQuery is styled with simple <link rel="stylesheet"> in index.html, so we don’t build styles for Host via Webpack, and it’s safe to cater for Alien only. Wrapper Configuration In addition to Webpack configuration, we also need to update our Frankenstein wrapper, pointing Vue to the correct Shadow DOM. In our Header-wrapper.js, rendering of the Vue component should include the shadowRoot property leading to shadowRoot of our Frankenstein wrapper: ... new Vue({ shadowRoot: this.shadowRoot, render: h => h(VueHeader) }).$mount(mountPoint); ... After you update the files and restart your server, you should be getting something like this in your DevTools: Finally, styles for the Vue component are within our Shadow DOM. At the same time, your application should look like this: We start getting something resembling our Vue application: styles bundled with the component, are injected into the wrapper’s Shadow DOM, but the component still looks not as it is supposed to. The reason is that in the original Vue application, the component is styled not only with the bundled styles but also partially with global styles. However, before fixing the global styles, we have to get our React integration to the same state as the Vue one. Bundled Styles In React And Shadow DOM Because there are many ways one can style a React component, the particular solution to fix an Alien component in Frankenstein Migration depends on the way we style the component in the first place. Let’s briefly cover the most commonly used alternatives. styled-components styled-components is one of the most popular ways of styling React components. For the Header React component, styled-components is precisely the way we style it. Since this is a classic CSS-in-JS approach, there is no file with a dedicated extension that we could hook our bundler onto as we do for .css or .js files, for example. Luckily, styled-components allow the injection of component’s styles into a custom node (Shadow DOM in our case) instead of the document’s headwith the help of the StyleSheetManager helping component. It is a pre-defined component, installed with the styled-components package that accepts target property, defining “an alternate DOM node to inject styles info”. Exactly what we need! Moreover, we do not even need to change our Webpack configuration: everything is up to our Frankenstein wrapper. We should update our Header-wrapper.js that contains the React Alien component with the following lines: ... import { StyleSheetManager } from "../../react/node_modules/styled-components"; ... const target = this.shadowRoot; ReactDOM.render( <StyleSheetManager target={target}> <HeaderApp /> </StyleSheetManager>, appWrapper ); ... Here, we import the StyleSheetManager component (from Alien, and not from Host) and wrap our React component with it. At the same time, we send the target property pointing to our shadowRoot. That’s it. If you restart the server, you have to see something like this in your DevTools: Now, our component’s styles are in Shadow DOM instead of <head>. This way, the rendering of our app now resembles what we have seen with the Vue app previously. Same story: styled-components are responsible just for the bundled part of the React component’s styles, and the global styles manage the remaining bits. We get back to global styles in a bit after we review one more type of styling components. CSS Modules If you take a closer look at the Vue component that we have fixed earlier, you might notice that CSS Modules is precisely the way we style that component. However, even if we style it with Scoped CSS (another recommended way of styling Vue components) the way we fix our unstyled component doesn’t change: it is still up to vue-loader and vue-style-loader to handle it through shadowMode: true option. When it comes to CSS Modules in React (or any other system using CSS Modules without any dedicated tools), things get a bit more complicated and less flexible, unfortunately. Let’s take a look at the same React component which we’ve just integrated, but this time styled with CSS Modules instead of styled-components. The main thing to note in this component is a separate import for stylesheet: import styles from './Header.module.css' The .module.css extension is a standard way to tell React applications built with the create-react-app utility that the imported stylesheet is a CSS Module. The stylesheet itself is very basic and does precisely the same our styled-components do. Integrating CSS modules into a Frankenstein wrapper consists of two parts: - Enabling CSS Modules in bundler, - Pushing resulting stylesheet into Shadow DOM. I believe the first point is trivial: all you need to do is set { modules: true } for css-loader in your Webpack configuration. Since, in this particular case, we have a dedicated extension for our CSS Modules ( .module.css), we can have a dedicated configuration block for it under the general .css configuration: { test: /\.css$/, oneOf: [ { test: /\.module\.css$/, use: [ ... { loader: 'css-loader', options: { modules: true, } } ] } ] } Note: A modules option for css-loader is all we have to know about CSS Modules no matter whether it’s React or any other system. When it comes to pushing resulting stylesheet into Shadow DOM, however, CSS Modules are no different from any other global stylesheet. By now, we went through the ways of integrating bundled styles into Shadow DOM for the following conventional scenarios: - Vue components, styled with CSS Modules. Dealing with Scoped CSS in Vue components won’t be any different; - React components, styled with styled-components; - Components styled with raw CSS Modules (without dedicated tools like those in Vue). For these, we have enabled support for CSS modules in Webpack configuration. However, our components still don’t look as they are supposed to because their styles partially come from global styles. Those global styles do not come to our Frankenstein wrappers automatically. Moreover, you might get into a situation in which your Alien components are styled exclusively with global styles without any bundled styles whatsoever. So let’s finally fix this side of the story. Global Styles And Shadow DOM Having your components styled with global styles is neither wrong nor bad per se: every project has its requirements and limitations. However, the best you can do for your components if they rely on some global styles is to pull those styles into the component itself. This way, you have proper easy-to-maintain self-contained components with bundled styles. Nevertheless, it’s not always possible or reasonable to do so: several components might share some styling, or your whole styling architecture could be built using global stylesheets that are split into the modular structure, and so on. So having an opportunity to pull in global styles into our Frankenstein wrappers wherever it’s required is essential for the success of this type of migration. Before we get to an example, keep in mind that this part is the same for pretty much any framework of your choice — be it React, Vue or anything else using global stylesheets! Let’s get back to our Header component from the Vue application. Take a look at this import: import "todomvc-app-css/index.css"; This import is where we pull in the global stylesheet. In this case, we do it from the component itself. It’s only one way of using global stylesheet to style your component, but it’s not necessarily like this in your application. Some parent module might add a global stylesheet like in our React application where we import index.css only in index.js, and then our components expect it to be available in the global scope. Your component’s styling might even rely on a stylesheet, added with <style> or <link> to your index.html. It doesn’t matter. What matters, however, is that you should expect to either import global stylesheets in your Alien component (if it doesn’t harm the Alien application) or explicitly in the Frankenstein wrapper. Otherwise, the wrapper would not know that the Alien component needs any stylesheet other than the ones already bundled with it. Caution. If there are many global stylesheets to be shared between Alien components and you have a lot of such components, this might harm the performance of your Host application under the migration period. Here is how import of a global stylesheet, required for the Header component, is done in Frankenstein wrapper for React component: // we import directly from react/, not from Host import '../../react/node_modules/todomvc-app-css/index.css' Nevertheless, by importing a stylesheet this way, we still bring the styles to the global scope of our Host, while what we need is to pull in the styles into our Shadow DOM. How do we do this? Webpack configuration for global stylesheets & Shadow DOM First of all, you might want to add an explicit test to make sure that we process only the stylesheets coming from our Alien. In case of our React migration, it will look similar to this: test: /\.css$/, oneOf: [ // this matches stylesheets coming from /react/ subfolder { test: /\/react\//, use: [] }, ... ] In case of Vue application, obviously, you change test: /\/react\// with something like test: /\/vue\//. Apart from that, the configuration will be the same for any framework. Next, let’s specify the required loaders for this block. ... use: [ { loader: 'style-loader', options: { ... } }, 'css-loader' ] Two things to note. First, you have to specify modules: true in css-loader’s configuration if you’re processing CSS Modules of your Alien application. Second, we should convert styles into <style> tag before injecting those into Shadow DOM. In the case of Webpack, for that, we use style-loader. The default behavior for this loader is to insert styles into the document’s head. Typically. And this is precisely what we don’t want: our goal is to get stylesheets into Shadow DOM. However, in the same way we used target property for styled-components in React or shadowMode option for Vue components that allowed us to specify custom insertion point for our <style> tags, regular style-loader provides us with nearly same functionality for any stylesheet: the insert configuration option is exactly what helps us achieve our primary goal. Great news! Let’s add it to our configuration. ... { loader: 'style-loader', options: { insert: 'frankenstein-header-wrapper' } } However, not everything is so smooth here with a couple of things to keep in mind. Global stylesheets and insert option of style-loader If you check documentation for this option, you notice, that this option takes one selector per configuration. This means that if you have several Alien components requiring global styles pulled into a Frankenstein wrapper, you have to specify style-loader for each of the Frankenstein wrappers. In practice, this means that you, probably, have to rely on oneOf rule in your configuration block to serve to all wrappers. { test: /\/react\//, oneOf: [ { test: /1-TEST-FOR-ALIEN-FILE-PATH$/, use: [ { loader: 'style-loader', options: { insert: '1-frankenstein-wrapper' } }, `css-loader` ] }, { test: /2-TEST-FOR-ALIEN-FILE-PATH$/, use: [ { loader: 'style-loader', options: { insert: '2-frankenstein-wrapper' } }, `css-loader` ] }, // etc. ], } Not very flexible, I agree. Nevertheless, it’s not a big deal as long as you don’t have hundreds of components to migrate. Otherwise, it might make your Webpack configuration hard to maintain. The real problem, however, is that we can not write a CSS selector for Shadow DOM. Trying to solve this, we might note that the insert option can also take a function instead of a plain selector to specify more advanced logic for insertion. With this, we can use this option to insert stylesheets straight into Shadow DOM! In simplified form it might look similar to this: insert: function(element) { var parent = document.querySelector('frankenstein-header-wrapper').shadowRoot; parent.insertBefore(element, parent.firstChild); } Tempting, isn’t it? However, this won’t work for our scenario or will work far from optimal. Our <frankenstein-header-wrapper> is indeed available from index.html (because we added it in Step 5.2). But when Webpack processes all dependencies (incl. the stylesheets) for either an Alien component or a Frankenstein wrapper, Shadow DOM is not yet initialized in the Frankenstein wrapper: imports are processed before that. Hence, pointing insert straight to shadowRoot will result in an error. There is only one case when we can guarantee that Shadow DOM is initialized before Webpack processes our stylesheet dependency. If Alien component does not import a stylesheet itself and it becomes up to Frankenstein wrapper to import it, we might employ dynamic import and import the required stylesheet after we set up Shadow DOM: this.attachShadow({ mode: "open" }); import('../vue/node_modules/todomvc-app-css/index.css'); This will work: such import, combined with the insert configuration above, will indeed find correct Shadow DOM and insert <style> tag into it. Nevertheless, getting and processing stylesheet will take time, which means your users on a slow connection or slow devices might face a moment of the unstyled component before your stylesheet gets on its place within wrapper’s Shadow DOM. So all in all, even though insert accepts function, unfortunately, it’s not enough for us, and we have to fall back to plain CSS selectors like frankenstein-header-wrapper. This doesn’t place stylesheets into Shadow DOM automatically, however, and the stylesheets reside in <frankenstein-header-wrapper> outside of Shadow DOM. We need one more piece of the puzzle. Wrapper configuration for global stylesheets & Shadow DOM Luckily, the fix is quite straightforward on the wrapper’s side: when Shadow DOM gets initialized, we need to check for any pending stylesheets in the current wrapper and pull them into Shadow DOM. The current state of the global stylesheet’s import is as follows: - We import a stylesheet that has to be added into Shadow DOM. The stylesheet can be imported in either the Alien component itself or, explicitly in the Frankenstein wrapper. In the case of migration to React, for example, the import is initialized from the wrapper. However, in migration to Vue, the similar component itself imports the required stylesheet, and we don’t have to import anything in the wrapper. - As pointed out above, when Webpack processes .cssimports for the Alien component, thanks to the insertoption of style-loader, the stylesheets get injected into a Frankenstein wrapper, but outside of Shadow DOM. Simplified initialization of Shadow DOM in Frankenstein wrapper, should currently (before we pull in any stylesheets) look similar to this: this.attachShadow({ mode: "open" }); ReactDOM.render(); // or `new Vue()` Now, to avoid flickering of the unstyled component, what we need to do now is pull in all the required stylesheets after initialization of the Shadow DOM, but before the Alien component’s rendering. this.attachShadow({ mode: "open" }); Array.prototype.slice .call(this.querySelectorAll("style")) .forEach(style => { this.shadowRoot.prepend(style); }); ReactDOM.render(); // or new Vue({}) It was a long explanation with a lot of details, but mainly, all it takes to pull in global stylesheets into Shadow DOM: - In Webpack configuration add style-loaderwith insertoption pointing to required Frankenstein wrapper. - In the wrapper itself, pull in “pending” stylesheets after initialization of Shadow DOM, but before the Alien component’s rendering. After implementing these changes, your component should have everything it needs. The only thing you might want (this is not a requirement) to add is some custom CSS to fine-tune an Alien component in Host’s environment. You might even style your Alien component completely different when used in Host. It goes beyond the main point of the article, but you look at the final code for the wrapper, where you can find examples of how to override simple styles on the wrapper level. You can also take a look at the Webpack configuration at this step of migration: And finally, our components look exactly as we intended them to look like. 5.5. Summary of fixing styles for the Alien component This is a great moment to sum up what we have learned in this chapter so far. It might look like we had to do enormous work to fix styling of the Alien component; however, it all boils down to: - Fixing bundled styles implemented with styled-components in React or CSS modules and Scoped CSS in Vue is as simple as a couple of lines in Frankenstein wrapper or Webpack configuration. - Fixing styles, implemented with CSS Modules, starts with just one line in css-loaderconfiguration. After that, CSS Modules are treated as a global stylesheet. - Fixing global stylesheets requires configuring style-loaderpackage with insertoption in Webpack, and updating Frankenstein wrapper to pull in the stylesheets into Shadow DOM at the right moment of the wrapper’s lifecycle. After all, we have got properly styled Alien component migrated into the Host. There is just one thing that might or might not bother you depending on what framework you migrate to, however. Good news first: If you’re migrating to Vue, the demo should be working just fine, and you should be able to add new to-do items from migrated Vue component. However, if you’re migrating to React, and try to add a new to-do item, you won’t succeed. Adding new items simply doesn’t work, and no entries are added to the list. But why? What’s the problem? No prejudice, but React has its own opinions on some things. 5.6. React And JS Events In Shadow DOM No matter what React documentation tells you, React is not very friendly to Web Components. The simplicity of the example in the documentation doesn’t stand any criticism, and anything more complicated than rendering a link in Web Component requires some research and investigation. As you have seen while fixing the styling for our Alien component, contrary to Vue where things fit Web Components nearly out of the box, React is not that Web Components-ready. For now, we have an understanding of how to make React components at least look good within Web Components, but there is also functionality and JavaScript events to fix. Long story short: Shadow DOM encapsulates events and retargets them, while React does not support this behavior of Shadow DOM natively and hence does not catch events coming from within Shadow DOM. There are deeper reasons for this behavior, and there is even an open issue in React’s bug tracker if you want to dive into more details and discussions. Luckily, smart people prepared a solution for us. @josephnvu provided the basis for the solution, and Lukas Bombach converted it into react-shadow-dom-retarget-events npm module. So you can install the package, follow instructions on the packages’ page, update your wrapper’s code and your Alien component will magically start working: import retargetEvents from 'react-shadow-dom-retarget-events'; ... ReactDOM.render( ... ); retargetEvents(this.shadowRoot); If you want to have it more performant, you can make a local copy of the package (MIT license allows that) and limit the number of events to listen to as it is done in Frankenstein Demo repository. For this example, I know what events I need to retarget and specify only those. With this, we are finally (I know it was a long process) done with proper migration of the first styled and fully-functional Alien component. Get yourself a good drink. You deserve it! 6. Rinse & Repeat For All Of Your Components After we migrated the first component, we should repeat the process for all of our components. In the case of Frankenstein Demo, there is only one left, however: the one, responsible for rendering the listing of to-do items. New Wrappers For New Components Let’s start with adding a new wrapper. Following the naming convention, discussed above (since our React component is called MainSection.js), the corresponding wrapper in migration to React should be called MainSection-wrapper.js. At the same time, a similar component in Vue is called Listing.vue, hence the corresponding wrapper in the migration to Vue should be called Listing-wrapper.js. However, no matter the naming convention, the wrapper itself is going to be nearly identical to the one we already have: There is just one interesting thing we introduce in this second component in React application. Sometimes, for that or another reason, you might want to use some jQuery plugin in your components. In case of our React component, we introduced two things: - Tooltip plugin from Bootstrap that uses jQuery, - A toggle for CSS classes like .addClass()and .removeClass(). Note: This use of jQuery for adding/removing classes is purely illustrative. Please don’t use jQuery for this scenario in real projects — rely on plain JavaScript instead. Of course, it might look weird to introduce jQuery in an Alien component when we migrate away from jQuery, but your Host might be different from the Host in this example — you might migrate away from AngularJS or anything else. Also, jQuery functionality in a component and global jQuery are not necessarily the same thing. However, the problem is that even if you confirm that component works just fine in the context of your Alien application, when you put it into Shadow DOM, your jQuery plugins and other code that rely on jQuery just won’t work. jQuery In Shadow DOM Let’s take a look at a general initialization of a random jQuery plugin: $('.my-selector').fancyPlugin(); This way, all elements with .my-selector are going to be processed by fancyPlugin. This form of initialization assumes that .my-selector is present in global DOM. However, once such an element is put into Shadow DOM, just like with styles, shadow boundaries prevent jQuery from sneaking into it. As a result, jQuery can not find elements within Shadow DOM. The solution is to provide an optional second parameter to the selector that defines the root element for jQuery to search from. And this is, where we can supply our shadowRoot. $('.my-selector', this.shadowRoot).fancyPlugin(); This way, jQuery selectors and, as a result, the plugins will work just fine. Keep in mind though that the Alien components are intended to be used both: in Alien without shadow DOM, and in Host within Shadow DOM. Hence we need a more unified solution that would not assume the presence of Shadow DOM by default. Analyzing MainSection component in our React application, we find that it sets documentRoot property. ... this.documentRoot = this.props.root? this.props.root: document; ... So, we check for passed root property, and if it exists, this is what we use as documentRoot. Otherwise, we fall back to document. Here is the initialize of the tooltip plugin that uses this property: $('[data-toggle="tooltip"]', this.documentRoot).tooltip({ container: this.props.root || 'body' }); As a bonus, we use the same root property to define a container for injecting the tooltip in this case. Now, when the Alien component is ready to accept the root property, we update rendering of the component in corresponding Frankenstein wrapper: // `appWrapper` is the root element within wrapper’s Shadow DOM. ReactDOM.render(<MainApp root={ appWrapper } />, appWrapper); And that’s it! The component works as fine in Shadow DOM as it does in the global DOM. Webpack configuration for multi-wrappers scenario The exciting part is happening in Webpack’s configuration when using several wrappers. Nothing changes for the bundled styles like those CSS Modules in Vue components, or styled-components in React. However, global styles should get a little twist now. Remember, we said that style-loader (responsible for injecting global stylesheets into correct Shadow DOM) is inflexible as it takes just one selector at a time for its insert option. This means that we should split the .css rule in Webpack to have one sub-rule per wrapper using oneOf rule or similar, if you’re on a bundler other than Webpack. It’s always easier to explain by using an example, so let’s talk about the one from migration to Vue this time (the one in migration to React, however, is nearly identical): ... oneOf: [ { issuer: /Header/, use: [ { loader: 'style-loader', options: { insert: 'frankenstein-header-wrapper' } }, ... ] }, { issuer: /Listing/, use: [ { loader: 'style-loader', options: { insert: 'frankenstein-listing-wrapper' } }, ... ] }, ] ... I have excluded css-loader as its configuration is the same in all cases. Let’s talk about style-loader instead. In this configuration, we insert <style> tag into either *-header-* or *-listing-*, depending on the name of the file requesting that stylesheet ( issuer rule in Webpack). But we have to remember that the global stylesheet required for rendering an Alien component might be imported in two places: - The Alien component itself, - A Frankenstein wrapper. And here, we should appreciate the naming convention for wrappers, described above, when the name of an Alien component and a corresponding wrapper match. If, for example, we have a stylesheet, imported in a Vue component called Header.vue, it gets to correct *-header-* wrapper. At the same time, if we, instead, import the stylesheet in the wrapper, such stylesheet follows precisely the same rule if the wrapper is called Header-wrapper.js without any changes in the configuration. Same thing for the Listing.vue component and its corresponding wrapper Listing-wrapper.js. Using this naming convention, we reduce the configuration in our bundler. After all of your components migrated, it’s time for the final step of the migration. 7. Switch To Alien At some point, you find out that the components you identified at the very first step of the migration, are all replaced with Frankenstein wrappers. No jQuery application is left really and what you have is, essentially, the Alien application that is glued together using the means of Host. For example, the content part of index.html in the jQuery application — after migration of both microservices — looks something like this now: <section class="todoapp"> <frankenstein-header-wrapper></frankenstein-header-wrapper> <frankenstein-listing-wrapper></frankenstein-listing-wrapper> </section> At this moment, there is no point in keeping our jQuery application around: instead, we should switch to Vue application and forget about all of our wrappers, Shadow DOM and fancy Webpack configurations. To do this, we have an elegant solution. Let’s talk about HTTP requests. I will mention Apache configuration here, but this is just an implementation detail: doing the switch in Nginx or anything else should be as trivial as in Apache. Imagine that you have your site served from the /var/www/html folder on your server. In this case, your or should have an entry that points to that folder like: DocumentRoot "/var/www/html" To switch your application after the Frankenstein migration from jQuery to React, all you need to do is update the DocumentRoot entry to something like: DocumentRoot "/var/www/html/react/build" Build your Alien application, restart your server, and your application is served directly from the Alien’s folder: the React application served from the react/ folder. However, the same is true for Vue, of course, or any other framework you have migrated too. This is why it is so vital to keep Host and Alien completely independent and functional at any point in time because your Alien becomes your Host at this step. Now you can safely remove everything around your Alien’s folder, including all the Shadow DOM, Frankenstein wrappers and any other migration-related artifact. It was a rough path at moments, but you have migrated your site. Congratulations! Conclusion We definitely went through somewhat rough terrain in this article. However, after we started with a jQuery application, we have managed to migrate it to both Vue and React. We have discovered some unexpected and not-so-trivial issues along the way: we had to fix styling, we had to fix JavaScript functionality, introduce some bundler configurations, and so much more. However, it gave us a better overview of what to expect in real projects. In the end, we have got a contemporary application without any remaining bits from the jQuery application even though we had all the rights to be skeptical about the end result while the migration was in progress. Frankenstein Migration is neither a silver bullet nor should it be a scary process. It’s just the defined algorithm, applicable to a lot of projects, that helps to transform projects into something new and robust in a predictable manner.
https://www.smashingmagazine.com/2019/09/frankenstein-migration-framework-agnostic-approach-part-2/
CC-MAIN-2022-21
refinedweb
8,895
52.7
Error showing values from an image in pixels with mouse callback Hello, I want to check pixel values with this program, however the results are not convincing at all for me. I am loading an image in grayscale and the colors are of course very different as it can be seen in the image However when I pass the mouse (with the implemented mouse callback function) I receive white colors with values of 90 for example, or black colors with values of 130. /*Updated algorithm. Now it doesn't show the values. the window disspaears like with an exception when the mouse is passed through the image" #include <iostream> #include <stdio.h> #include <opencv2/opencv.hpp> #include <highgui.h> using namespace cv; using namespace std; Mat image, imageGreen; char window_name[20]="Get coordinates"; static void onMouse( int event, int x, int y, int f, void* ) { uchar intensity = imageGreen.at<uchar>(x,y); cout << "x: "<< x << " y: " << y << endl << " value: " << (int)intensity << endl; } int main() { namedWindow( window_name, CV_WINDOW_NORMAL ); image = imread("/home/diego/Humanoids/imageGreen0.png"); Mat imageGreen = Mat::zeros(image.size(), CV_8UC1); Vec3b result; for (int i = 0; i < image.rows ; i++) { for (int j = 0; j < image.cols ; j++) { result = image.at<cv::Vec3b>(i,j); int value = result[1]; imageGreen.at<uchar>(i, j) = value; } } cout<< "Image depth: "<<imageGreen.depth()<<" # of channels: "<<imageGreen.channels()<<"\n"; imshow( window_name, imageGreen ); setMouseCallback( window_name, onMouse, 0 ); waitKey(0); return 0; } I want to learn how to use this because I want to get rid of the bottle shadow (by the way, here I put the green value of each pixel from an RGB image into the correspondent pixel in a grayscale image --> It's a green bottle) and I thought that maybe there can be a difference between the values of the bottle and the reflection from the sun which can allow me to make a threshold. Can anyone help me telling me what is the error here? I am trying to stop being a newbie in OpenCV and C++, but I think that there is still a long way for it. Thank you I changed the algorithm and now I'm using another image
http://answers.opencv.org/question/62900/error-showing-values-from-an-image-in-pixels-with-mouse-callback/?sort=latest
CC-MAIN-2019-13
refinedweb
362
62.58
Hey all, ive just started to learn C++ and this is my first post. Im making a simple program just to put together all that ive learned so far, but im getting the error: Error C2447: '{' : Missing function header (old style formal list?) Below is my code, thanks for any help in advance Code: #include <iostream> using namespace std; // This is my very first project, It has no real use, i dont even know what it is // its just a simple program for me to mess around with what ive learned so far. // By Michael Clarke 8/6/2007 int money = 100; int total = 0; int buy = 0; int main(); { // Money is used for how much money i have in pence. // Total is something i will use later to help with the numbers. // buy will be used for input from the user. cout << "You have: " << money << endl; cout << "Would you like to buy a coke for 75p?" << endl; cout << "please press '1' for yes and '0' for no: "; cin >> buy; if buy == 1; { cout << "Thank you, That will be 75 Pence please" << endl; money - 75; } if buy == 0; { cout << "Ok, Come again!" << endl; } else; { cout << "Please input a 0 for no or a 1 for yes" << endl; } cout << "thank you, have a nice day!" << endl; cout << "You have: " << money << "in Change" << endl; }
http://cboard.cprogramming.com/cplusplus-programming/90627-need-help-error-please-printable-thread.html
CC-MAIN-2015-40
refinedweb
222
82.99
python: socketio packaging problems If I hit run: it gives me [assertion Error]. If I install aiohttp first, then it says msgpack has no attribute 'dumps' all I want to do is learn how to use socketio. can anyone help with my packaging problems? Voters In my opinion, the error is this: i think there is something wrong with the module you have/imported. Or it could be an internal error with the module. Hope this helps! Not really sure what that means, does that mean that socketio is broken? if so is there anyway I can fix it? @JBYT27 It could be socketio or it could be the from aiohttp import web. If ti is an internal error, you cant fix it, sry :( If this is not the case though, it could be a code error that connects to the importing. Try looking it through? @SeamusDonahue Actually, I think the error might be the open 'index.html'thing. Because there is no such file, i think that may be the error as well. idk for sure though. @SeamusDonahue seems socketio is the problem @JBYT27 I tried not importing aio same problem but if I don't import socketio the program runs and gives me the obvious socketio not defined error ah, ok. Sad to say that socketio has an error :( @SeamusDonahue although disappointing guess I will have to use a different lib thanks, and have a nice day. @JBYT27 Very disappointing.. You too! @SeamusDonahue @JBYT27 @SeamusDonahue socket.io is not broken... most likely you've messed with the poetry.lockfile or tampered with packaging files. Create a new repl and it should work I have tried deleting the file multiple times to let it regenerate, that is just how repl.it made the file @realTronsi hmm? oh. ok, did you try? did it work? (just curious) @realTronsi for some reason making a new repl import the package correctly, I didn't tamper with poetry.lock in this repl, so It had no right working but somehow it does? @JBYT27 @realTronsi I don't think I can mark that answer as I have already marked an answer lol. wow! @SeamusDonahue @SeamusDonahue wdym, you aren't supposed to touch poetry.lock, especially if you don't know what you're doing. yea I just said that I didn't tamper with it, and deleted it multiple times to get it to regenerate @realTronsi
https://replit.com/talk/ask/python-socketio-packaging-problems/85347
CC-MAIN-2022-21
refinedweb
402
67.25
GeekZilla Restricting the number of rows in a dataview when binding to a repeater The problem I needed to restrict the number of items bound to an asp:repeater. Basically I never wanted more than 10 items to be displayed. Options The right thing to do would be to restrict the number of items at the database level using Set RowCount or top 10. In this instance, it wasn't an option and the lack of a RowCount feature on the DataView object left me needing to find another solution. The Solution After some searching, I came across a bit of code which proved helpful. The following code makes allows me to pass a DataView into an enumerable object which returns only the number of rows I'm interested in. Example Use myRepeater.DataSource = new FilterRows(myDataView, 10); The Enumerable Object using System; using System.Data; using System.Web.Security; using System.Collections; /// <summary> /// Summary description for FilterRows /// </summary> public class FilterRows : IEnumerable { DataView dataView; private int rowsToShow; public FilterRows(DataView dataView, int rowsToShow) { this.rowsToShow = rowsToShow; this.dataView = dataView; } public IEnumerator GetEnumerator() { return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow); } internal class PageOfData : IEnumerator { private IEnumerator e; private int cnt = 0; private int rowsToShow; internal PageOfData(IEnumerator e, int rowsToShow) { this.rowsToShow = rowsToShow; this.e = e; } public object Current { get { return e.Current; } } public bool MoveNext() { // If we've hit out limit return false if (cnt >= rowsToShow) return false; // Track the current row cnt++; return e.MoveNext(); } public void Reset() { e.Reset(); cnt = 0; } } }. Chris Roberts said: I like what you've done here Paul. You're showing the first 10 items, but say you had 100 items. How do you show the next 10 and then the next 10 and so on (basically paging)? Akash Dwivedi said: Good one. you did really good work. I searched for this at many places but got solution at your site. Akash Dwivedi said: Good one. you did really good work. I searched for this at many places but got solution at your site. udeeb said: this really works but I have one question. Once I get the top 10 from dataview, is there any way that I can change the existing dataview to only contain those 10 records, so that I can sort and change those remaining data only? Thanks for your help... phayman said: udeeb, I'd be inclined to use Generics or Linq to do this now. Check the following article: Paul Srinivasan V said: Hi Paul, Thanks for the code. It helps a lot. Good work Paul. by Srini said: You have done realy great job thanks for posting this article Sonny Eugenio said: The code is really great it's exactly what I need. Thanks Paul for sharing it with us. marcusorjames said: If anyone wants this in VB: Imports System Imports System.Data Imports System.Web.Security Imports System.Collections ''' <summary> ''' Summary description for FilterRows ''' </summary> Public Class FilterRows Implements IEnumerable Dim _dataView As New DataView Dim _rowsToShow As Integer Public Sub New(DataView As DataView, rowsToShow As Integer) Me.RowsToShow = rowsToShow Me.DataView = DataView End Sub Public Property RowsToShow As Integer Get Return _rowsToShow End Get Set(value As Integer) _rowsToShow = value End Set End Property Public Property DataView As DataView Get Return _dataView End Get Set(value As DataView) _dataView = value End Set End Property Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Return New PageOfData(Me.DataView.GetEnumerator(), Me.RowsToShow) End Function Private Class PageOfData Implements IEnumerator Dim _e As IEnumerator Dim _cnt As Integer = 0 Dim _rowsToShow As Integer Public Sub New(e As IEnumerator, rowsToShow As Integer) Me.RowsToShow = rowsToShow Me.E = e End Sub Public ReadOnly Property Current As Object Implements System.Collections.IEnumerator.Current Get Return E.Current End Get End Property Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext 'If we've hit out limit return false If _cnt >= RowsToShow Then Return False End If 'Track the current row _cnt = _cnt + 1 Return E.MoveNext() End Function Public Sub Reset() Implements System.Collections.IEnumerator.Reset E.Reset() _cnt = 0 End Sub Public Property RowsToShow As Integer Get Return _rowsToShow End Get Set(value As Integer) _rowsToShow = value End Set End Property Public Property E As IEnumerator Get Return _e End Get Set(value As IEnumerator) _e = value End Set End Property End Class End Class
http://www.geekzilla.co.uk/ViewED362E0D-8205-4947-A751-2D754AB04C64.htm
CC-MAIN-2014-52
refinedweb
733
50.23
Samsung Galaxy Gear2 smartwatches are some nice new wearables from Samsung. As you probably know, creating a widget for Gear2 involves some HTML, CSS and last, but not least, JavaScript skills. In other words - we will be developing on Tizen OS. Gear2 hit the market only 3 months ago so there aren’t many noteworthy tutorials on the web. Unfortunately, only 2 decent official video tutorials are available. Besides that you can find some valuable information on Gear by looking up the denvycom.com blog and… To be honest - that’s all we’ve got. Our WearLabs™ team recently managed to develop an Android application, which successfully takes advantage of Galaxy Gear2 functionalities. I was the one to focus on the smartwatch side of the game and actually really enjoyed it. That’s why I came up with an idea to share what I’ve learned and maybe encourage a few of you to develop some new fancy Gear2 apps. Code shown in this post can be downloaded from my repository. Feel free to play with it or even use it in your own projects. Follow the official install guide carefully and you’re all OK. Remember about dealing with certification matters, because you will NOT be able to run your own applications, nor will you be able to build and launch existing tutorial ones. Don’t forget to push the certificate into Galaxy Gear device. Also be sure to enable USB debugging on smartwatch and check ‘Unknown sources’ option in the Gear Manager app. Now, when your IDE is ready, it’s time to install and import official HelloAccessory tutorial project. As you can see the app is divided into 2 separate pieces: the Android host-side, and the wearable/gear-side. This is the most common scenario called integrated app type. Android-side service-based class runs the logic, which controls the Gear widget. public class HelloAccessoryProviderService extends SAAgent { // ... public HelloAccessoryProviderService() { super(TAG, HelloAccessoryProviderConnection.class); } public class HelloAccessoryProviderConnection extends SASocket { // ... Here’s how the skeleton of host-side Provider Service looks like. SAAgent class extends the standard Android Service class. In other words, this file represents a special Service, which contains all host-side functionalities. There’s also SASocket subclass, which drives the connection itself, between Android smartphone and Gear2 widget. It’s your application’s main logic. In general - SAAgent class can be compared to something like a Peer. On the other hand, SASocket is the ‘bridge’ between SAAgent and Galaxy Gear2 device. Information from the previous paragraph comes very handy when we take a closer look at the Gear-side part of the application. Open up the JavaScript file and compare it with the following method flow diagram: When Gear tries to connect, it searches for available SAAgent. Then, we go one step further by setting appropriate listener and firing ‘SAAgent.findPeerAgents’ method. Next, we check, if SAAgent’s and Gear’s AppNames correspond with each other. If so, we request service connection with SAAgent and finally can communicate with the host-side Android device using SASocket. Here comes the most important part of the first tutorial app - transferring data between Android and Gear. We do that using binary data arrays (in this example, Strings). It’s a very crucial skill, essential basic, which you must know in order to be able to jump into developing bigger and more valuable applications. Let’s take a closer look at the Android-side: public class HelloAccessoryProviderConnection extends SASocket { // ... @Override public void onReceive(int channelId, byte[] data) { // for example Toast.makeText(getBaseContext(), new String(data), Toast.LENGTH_LONG) .show(); } onReceive method is fired every time Android device receives data from Gear. You can even create a simple ‘switch’ here, using String or JSON objects. In the code above we have the easiest example - smartphone receives data from Gear and displays it as Toast notification. As simple as that… Wait, what if you want to send data from host-side to Gear? It’s not explained in the tutorial app, but don’t worry - I’m here to show you. public class HelloAccessoryProviderConnection extends SASocket { // ... public void sendNotification(final String notification) { final HelloAccessoryProviderConnection uHandler = mConnectionsMap.get(mConnectionId); if(uHandler == null){ Log.e(TAG,"Error, can not get handler"); return; } new Thread(new Runnable() { public void run() { try { uHandler.send(HELLOACCESSORY_CHANNEL_ID, notification.getBytes()); } catch (IOException e) { e.printStackTrace(); } } }).start(); } That’s how you send data to Gear from Android device. First of all, you get a uHandler from connectionsMap (this ensures that the connection with smartwatch is active). Then you simply post binary data on the specific channel using Thread. It looks easy, but the trickiest part is to properly launch this method when needed. As I stated at the beginning, SAAgent class extends Android Service. Then, the simplest, yet quite effective way to communicate with the Service (and our sendNotification method) is to use Broadcasts. public class HelloAccessoryProviderService extends SAAgent { // ... public class HelloAccessoryProviderConnection extends SASocket { // ... @Override public void onReceive(int channelId, byte[] data) { // registering the BroadcastReceiver here ensures you, that the Gear connection has been already established GearDataReceiver gearDataReceiver = new GearDataReceiver(); IntentFilter intentFilter = new IntentFilter("myData"); registerReceiver(gearDataReceiver, intentFilter); // for example Toast.makeText(getBaseContext(), new String(data), Toast.LENGTH_LONG) .show(); } } // code below goes to the outer class, which extends SAAgent private class GearDataReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("myData")) { String data = intent.getStringExtra("data"); notifyGear(data); } } } public void notifyGear(String notification) { for(HelloAccessoryProviderConnection provider : mConnectionsMap.values()) { provider.sendNotification(notification); } } } Code shown above lets you send any data to Gear when HelloAccessoryProviderService receives a Broadcast. All you have to do is send that broadcast from an appropriate Activity: // method to place in your Activity public void sendDataToGear(View view) { Intent intent = new Intent("myData"); intent.putExtra("data", "Hello Gear!"); sendBroadcast(intent); } Now, when you know how to handle connection from the Android host part, it’s the time to show you some basic Gear-side scenarios. It’s much easier, so don’t worry. Just remember, that we are coding in JavaScript here. // use this code, when you are sure, that SASocket has been established try { SASocket.setDataReceiveListener(onReceive); } catch(err) { console.log("exception [" + err.name + "] msg[" + err.message + "]"); } function onReceive(channelId, data) { // for example alert(data); } All you have to do is set an appropriate listener (remember, this thingy will work only with SASocket established), which drives the data received from Android. Told you it’d be simple. function myClick(data) { try { SASocket.sendData(CHANNELID, data); } catch(err) { console.log("exception [" + err.name + "] msg[" + err.message + "]"); } } Another easy step. Just be sure to pass a correct argument to this method - it’ll work flawlessly, if the SASocket has been established. That’s it. It’s time to code. You know how to handle the transferring data between Android and Gear. With that essential skill you are now able to develop almost every type of integrated app you want. Feel free to leave a comment here or send me an email at adam@scalac.io - I am eager to help you. Have fun and play with the code above any way you want. by Adam Nadoba July 30, 2014 Tags : Galaxy Gear2 Tizen SDK Samsung Wearables Android
https://blog.scalac.io/2014/07/30/developing-your-first-galaxy-gear-app.html
CC-MAIN-2018-26
refinedweb
1,204
50.12
I would like to display only the two first characters of a word in a Text item. For example, I have a list of words (FRENCH, ENGLISH, ITALIAN) and I would like to display only (FR, EN, IT). If I elide the text, I will always get three dots (...) at the end and I don't want that. Any ideas ? Thanks in advance You could set clip to true but then you would need to play with the width. So I think the best option is to implement a little function in JavaScript to get only the first two letters. Example: main.qml import QtQuick 2.5 import QtQuick.Window 2.2 import "myscript.js" as MyFunctions Window { visible: true // You need to play with the width Text { width: 13 text: "FRENCH" clip: true } // OK. width is not necessary Text { y: 60 text: MyFunctions.substring("FRENCH") } // We don't want this behaviour Text { y: 30 width: 25 text: "FRENCH" elide: Text.ElideRight } } myscript.js function substring(str) { return str.substring(0, 2); } Do remember that the first letters in country names and the corresponding ISO standard 2- or 3-letter country codes are a different thing. For example, the 2-letter code for Andorra is AD. () -- So, if you are trying to achieve country ISO standard country coding, you should simply make a list of objects, which have the properties name, isoCode2, and so on, as required, for example: property var myArrayOfCountries: [ { "name" : "Andorra", "isoCode2" : "AD" }, { "name" : "United Arab Emirates", "isoCode2" : "AE" }, ... ] I would probably try to get these from some web service, if available, as the creation and maintenance of such list could be a pain. ...That said, if you simply need to get the first two letters from a string in QML Javascript, I would simply use text: myString.substring(0, 2) or perhaps in your case, I presume: text: myArrayOfStrings[someIndex].substring(0, 2) Ps., with the object list approach you would use: text: myArrayOfCountries[someIndex]["isoCode2"] of course.
http://www.devsplanet.com/question/35280334
CC-MAIN-2017-04
refinedweb
332
73.47
September 2019 Volume 34 Number 9 [First Word] Visual Basic on .NET Core By Kathleen Dollard | September 2019 I started writing Visual Basic code more than two decades ago, and I understand why so many people still program in Visual Basic .NET. It has almost all of the features of C#, plus unique functionality that makes it easier for you to focus on what your software accomplishes. This comes from features in the language itself, as well as from language extensions and language stability. Visual Basic also includes unique productivity features like XML literals and in-place event hookup. Now Visual Basic .NET 16.0 is bringing your favorite Visual Basic features to .NET Core 3.0. The essential parts of the Visual Basic .NET programming language have been on .NET Core since its early development, but developers can expect an enriched experience when Microsoft ships Visual Studio 16.3 and .NET Core 3.0 with Visual Basic 16.0 and C# 8.0 on board. In my role working on the transition to .NET Core, I was able to dive into the technology behind the language extensions: the special functions, application models and My subsystem. These features are contained in microsoft.visualbasic.dll, also called the Visual Basic Runtime, and many are now included in .NET Core 3.0, except those dependent on Windows Forms (WinForms). Windows Forms Visual Basic .NET has a special relationship with WinForms, which was modeled largely on earlier versions of Visual Basic. Among all the options .NET programmers have to build applications, WinForms remains the best at getting the job done fast. In addition to traditional roles, WinForms offers a rapid way to develop thin front ends for services on-premises or in the cloud, either for production or for functional prototypes. While the WinForms library will be available, the WinForms designers will not be part of Visual Studio 16.3. This limits the experience, so the Visual Basic .NET team decided to focus on the non-WinForms portion of the language extensions for Visual Basic 16.0. This means you can use WinForms on .NET Core with Visual Basic, but you won’t have the project property dialog to enable the Visual Basic Application Model. You’ll need either a Sub Main or a startup form, and you’ll find that the My features aren’t yet available. Parts of the Visual Basic Runtime depend on WinForms, even for unexpected types like My.Computer. We’re splitting the runtime into the parts that are dependent on WinForms and those that aren’t, with the WinForms-dependent part to appear in a future release of Visual Basic. Beyond these limitations, Visual Basic .NET 16.0 brings much of the functions of the Visual Basic runtime to .NET Core. This includes key features, like Fix and Mid, that you expect. Telemetry from API Port helped the team prioritize the work here, and some features with very low usage weren’t ported. Openness and Stability Visual Basic .NET 16.0 includes the financial and file functions that were ported by folks in the community. Of course, Visual Basic .NET has been open source since 2015. There are significant areas where you can contribute, and many of them aren’t nearly as intimidating as the Roslyn compiler! You can also be part of the revival of Visual Basic .NET communities on Facebook and Gitter. Find more about the community and language design at the Visual Basic .NET language design site (github.com/dotnet/vblang). For this latest version of Visual Basic, the runtime was ported directly. There were no changes and no effort to “clean up” features. Things should work the same in .NET Core as they did in .NET Framework. All this is part of the deep commitment to stability within the Visual Basic team. This stability is important for backward compatibility, of course, but the commitment extends to ensuring that code written at different points in the evolution of Visual Basic continues to be easy to read. New features are incorporated slowly in Visual Basic .NET, and only those that feel natural in Visual Basic are added. You can develop applications targeting either .NET Core or .NET Framework (.NET 4.8 and below) with Visual Studio. While .NET Framework will remain supported for a long time, developing applications on .NET Core brings a raft of advantages, including side-by-side and self-contained deployment that eliminates issues that occur when another application’s installation makes changes to production machines. For WinForms, there are new features like better high DPI support. And going forward, new capabilities in .NET, Visual Basic .NET and C# will only be available on .NET Core. In Visual Basic, you’ll get the advantages of Visual Basic 16.0 just by targeting .NET Core 3.0 (netcoreapp2.2). Cross-Platform Support Visual Basic .NET on .NET Core is cross-platform, although WinForms, Windows Presentation Foundation and other Windows-specific features will work only on Windows. You can find the OSes that are supported at aka.ms/net-core-3-0-supported-os. If you run a Visual Basic .NET application on an OS like Linux, features that work cross-platform will just work. If you call Visual Basic Runtime functionality that doesn’t work on that platform, you’ll get a System.PlatformNotSupportedException with a message similar to “<method> not supported on this platform.” This is the same behavior as the rest of .NET, so if you’re working cross-platform, you’ll want to test your application across the OSes where you expect to deploy, regardless of the language you use. Some project types aren’t supported on .NET Core 3.0. For example, WebForms won’t be supported in any language. Visual Basic isn’t supported by ASP.NET Core Razor, so you can’t simply port MVC applications. And while Microsoft doesn’t offer a Web development model that’s 100 percent Visual Basic, you can use Visual Basic in ASP.NET WebAPI with JavaScript front ends, or create combined apps with views in C# Razor projects. API Portability Anaylzer You can test the compatibility of your applications by running the API Portability Analyzer. The tool is available for download as a Visual Studio extension from the Visual Studio gallery or as a command-line tool. Find out more at aka.ms/api-portability. The API Portability Analyzer outputs a spreadsheet listing the percent of your application that will just work in the platforms you select, in this case .NET Core 3.0. Other tabs drill into the specific APIs used in the application, as well as those that aren’t supported. We Want To Hear from You! The team wants to understand the issues that face Visual Basic .NET programmers moving to .NET Core and we invite your help on the next stage of that journey. If you run the Portability Analyzer and find you need things missing in the VisualBasic namespace or other Visual Basic-specific issues, let us know by opening an issue, or by commenting on an existing one, at the Visual Basic .NET language design site (github.com/dotnet/vblang). The work we’re doing with .NET Core sets up Visual Basic for the future. Combined with Microsoft’s long-term commitment to .NET Framework 4.8, you have flexibility for both new and legacy applications in Visual Basic, one of the most productive programming languages ever created. Changes to Visual Studio and .NET Core Installers If you run `dotnet --info` at a command prompt, you’ll see a list of installed .NET Core SDKs and runtimes. There may be a lot more than you anticipated! Earlier Visual Studio and .NET Core installers haven’t been removing older SDKs and runtimes when they update or uninstall. While you may need these to support SDK pinning via global.json or to target older runtimes, they might just be sitting unused on your machine. Now, starting with Visual Studio 2019 16.3, Visual Studio will manage the versions of .NET Core SDKs and runtimes it installs. It will only keep one copy of the .NET Core SDK on each machine per channel (preview or release), and will install the latest runtime. You can target earlier runtimes by selecting them—along with their templates and targeting packs—in the Individual Components tab of the Visual Studio Installer. When you download and install the .NET Core 3.0 SDK from dotnet.microsoft.com/download, earlier patches in the same feature band will now be removed. For example, 3.0.100 will be uninstalled when you install 3.0.102. Previews in that band will also be removed. Each version of the SDK can target all earlier versions of the runtime, so you generally only need one. If you need additional SDKs or runtimes, you can download them from dotnet.microsoft.com/download. You can manually remove .NET Core SDKs and runtimes, or you can clean them up using the recently released .NET Core Uninstall Tool on Windows and macOS (aka.ms/remove-sdk-runtime). Just be careful, SDKs aren’t tracked by Visual Studio, so removing the wrong ones can cause issues. If you delete something that Visual Studio needs, run “Repair” in the Visual Studio installer. Kathleen Dollard is a principal program manager on the .NET Core team at Microsoft. She is the Program Manager for Visual Basic, contributes to the Managed Languages and works on the .NET Core CLI and SDK. Discuss this article in the MSDN Magazine forum
https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/september/first-word-visual-basic-on-net-core
CC-MAIN-2019-47
refinedweb
1,593
60.11
HOUSTON (ICIS)--?xml:namespace> In the Group I tier, industry sources said that ExxonMobil dropped its light grade base stocks by 14 cents/gal effective 21 January, with mid-grades reduced by 10 cents/gal on the same date. Group I producer Paulsboro Refining Company (PRC) confirmed a 14 cents/gal reduction on its light grades and 10 cents/gal on its mid and heavy grades, all effective 24 January. Neither Group I producer changed brightstock prices. In the Group II tier, Chevron and Flint Hills Resources (FHR) announced reductions, with Chevron’s prices moving down 25 cents/gal across all grades effective 22 January. FHR base oil prices were reduced by various amounts per grade, all effective on 21 January. Base oils in Group II+ and Group III tiers are down by 25 cents/gal across the viscosity grades, with effective dates varying by producer. After the reduction, ExxonMobil’s Group I 100 viscosity base stock posted price is at $3.53/gal. In Group II, Chevron’s light vis 100 base oil posted price is at $3.82/gal following the price drop. Price decreases were driven by seasonally slow Q4 demand from the key lubricants sector that pushed base oil producers to offer heavy discounts between November and January.
http://www.icis.com/resources/news/2014/01/23/9746731/us-paraffinic-base-oil-prices-drop-seasonally-slow-demand/
CC-MAIN-2015-11
refinedweb
212
60.04
Push Internet is overflowing with guides on how to implement iOS push notifications -- however, many of these guides are cumbersome, complicated, not up-to-date with Swift 3 and Xcode 8, and/or don't provide backward-compatibility with all iOS versions that support Swift (iOS 7 - iOS 10). Also, they do not make use of the new APNs Auth Keys which greatly simplify the steps involved in sending push notifications. By following this guide, you'll be able to implement push notifications in your iOS app and send notifications from Node.js, using the latest technologies and without much hassle! First off, open your iOS project in Xcode 8. If you don't have Xcode 8 yet, be sure to update via the App Store. If you don't have an iOS project yet, simply create a new one. Make sure that your codebase has been updated to use Swift 3. Second, make sure that you have an active Apple Developer Program Membership, which costs $100/year. It is a requirement in order to send push notifications to your iOS app. Also, make sure Xcode is configured to use the iCloud account which contains your active Apple Developer Program Membership. Third, make sure that your app has a Bundle Identifier configured in the project editor: The first step in setting up push notifications is enabling the feature within Xcode 8 for your app. Simply go to the project editor for your target and then click on theCapabilities tab. Look for Push Notifications and toggle its value to ON: Xcode should display two checkmarks indicating that the capability was successfully enabled. Behind the scenes, Xcode creates an App ID in the Developer Center and enables the Push Notifications service for your app. Devices need to be uniquely identified to receive push notifications. Every device that installs your app is assigned a unique device token by APNs that you can use to push it at any given time. Once the device has been assigned a unique token, it should be persisted in your backend database. A sample device token looks like this: 5311839E985FA01B56E7AD74334C0137F7D6AF71A22745D0FB50DED665E0E882 To request a device token for the current device, open AppDelegate.swift and add the following to the didFinishLaunchingWithOptions callback function, before the return statement: AppDelegate.swift didFinishLaunchingWithOptions return //]) } In iOS 10, a new framework called UserNotifications was introduced and must be imported in order to access the UNUserNotificationCenter class. UserNotifications UNUserNotificationCenter Add the following import statement to the top of AppDelegate.swift: import UserNotifications Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section. Click + and select UserNotifications.framework: + UserNotifications.framework Next, add the following callbacks in AppDelegate.swift which will be invoked when APNs has either successfully registered or failed registering the device to receive notifications: //)") } It's up to you to implement logic that will persist the token in your application backend. Later in this guide, your backend server will connect to APNs and send push notifications by providing this very same device token to indicate which device(s) should receive the notification. Note that the device token may change in the future due to various reasons, so useNSUserDefaults, a local key-value store, to persist the token locally and only update your backend when the token has changed, to avoid unnecessary requests. Run your app on a physical iOS device (the iOS simulator cannot receive notifications) after making the necessary modifications to AppDelegate.swift. Look for the following dialog, and press OK to permit your app to receive push notifications: Within a second or two, the Xcode console should display your device's unique token. Copy it and save it for later. Add the following callback in AppDelegate.swift which will be invoked when your app receives a push notification sent by your backend server: // Push notification received func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { // Print notification payload data print("Push notification received: \(data)") } Note that this callback will only be invoked whenever the user has either clicked or swiped to interact with your push notification from the lock screen / Notification Center, or if your app was open when the push notification was received by the device. It's up to you to develop the actual logic that gets executed when a notification is interacted with. For example, if you have a messenger app, a "new message" push notification should open the relevant chat page and cause the list of messages to be updated from the server. Make use of the data object which will contain any data that you send from your application backend, such as the chat ID, in the messenger app example. data It's important to note that in the event your app is open when a push notification is received, the user will not see the notification at all, and it is up to you to notify the user in some way. This StackOverflow question lists some possible workarounds, such as displaying an in-app banner similar to the stock iOS notification banner. The next step involves generating an authentication key that will allow your backend server to authenticate with APNs when it wants to send one or more of your devices a push notification. Up until a few months ago, the alternative to this was a painful process that involved filling out a Certificate Signing Request in Keychain Access, uploading it to the Developer Center, downloading a signed certificate, and exporting its private key from Keychain Access (not to mention converting both certificates to .pem format). This certificate would then expire and need to be renewed every year and would only be valid for one deployment scheme: Development or Production. .pem Thankfully, Apple has greatly simplified the process of authenticating with APNs with the introduction of APNs Auth Keys, which never expire (unless revoked by you) and work for all deployment schemes. Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key. In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page. Apple will then generate a .p8 key file containing your APNs Auth Key. .p8 Download the .p8 key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs. Now it's time to set up your backend to connect to APNs to send notifications to devices! For the purpose of this guide and for simplicity, I'll choose to do this in Node.js. If you already have a backend implemented in another development language, look for another guide better-tailored for you, or simply follow along to send a test push notification to your device. Make sure you have Node.js v4 or newer installed on your local machine and run the following in a directory of your choice: mkdir apns cd apns npm init --yes npm install apn --save These commands will initiate a new Node.js project and install the amazing apn package from npm, which authenticates with APNs and sends your push notifications. apn Next, copy the .p8 file you just downloaded into the apns folder we created. Name it apns.p8 for simplicity. apns apns.p8 Create a new file in the apns folder named app.js using your favorite editor, and paste the following code inside: app.js); }); There are several things to do before running this code: keyId teamId deviceToken notification.topic Now, lock your device, run node app.js and lo-and-behold, provided you did everything right, your iOS device should be able to receive the notification! node app.js Interacting with the notification will print the following in your Xcode console since didReceiveRemoteNotification is invoked: didReceiveRemoteNotification [AnyHashable("id"): 123, AnyHashable("aps"): { alert = "Hello World \U270c"; badge = 3; sound = "ping.aiff"; }] I hope you were able to get through this tutorial with ease. Let me know if this helped you in the comments below!
https://www.cnblogs.com/ioriwellings/p/6219187.html
CC-MAIN-2018-34
refinedweb
1,352
51.68
Positional parameters Lets say we would like to make some pretty URLs for some lists that we have on our site. We have a "show_list" method that takes a user and an id as parameters. The "normal" way would be to have. But with positional paramteres, this can be written: import cherrypy class Root: def show_list(self, user, id): return "user: %s <br /> id: %s" % (user, id) show_list.exposed = True cherrypy.quickstart(Root()) This also works well when you don't know the number of path components beforehand. Just take advantage of Python's arbitrary arguments: class Root: def view(self, *path): return ", ".join(["(%s)" % p for p in path]) view.exposed = True Older versions You can read more about positional paramters for 2.2 in the CherryPy book () CherryPy 2.1 allowed positional parameters for methods named "default". CherryPy 2.0 had no allowance for positional parameters.
http://cherrypy.org/wiki/PositionalParameters
crawl-001
refinedweb
148
68.47
A Cloud Foundry Buildpack for PHP. A buildpack to deploy PHP applications to Cloud Foundry based systems, such as a cloud provider or your own instance. Official buildpack documentation can be found here: php buildpack docs. git submodule update --init git checkout v4.4.2 # or whatever version you want, see releases page for available versions BUNDLE_GEMFILE=cf.Gemfile bundle BUNDLE_GEMFILE=cf.Gemfile bundle exec buildpack-packager [ --uncached | --cached ] [ --any-stack | --stack=STACK ] Use in Cloud Foundry Upload the buildpack to your Cloud Foundry instance and optionally specify it by name cf create-buildpack custom_php_buildpack php_buildpack-cached-custom.zip 1 cf push my_app -b custom_php_buildpack Find our guidelines here. Buildpacks use the Cutlass framework for running integration tests. To run integration tests, run the following command: ./scripts/integration.sh To run unit tests, run the following command: ./scripts/unit git clone cd php-buildpack python -V # should report 2.6.6, if not fix PyEnv before creating the virtualenv virtualenv `pwd`/env . ./env/bin/activate pip install -r requirements.txt The project is broken down into the following directories: bincontains executable scripts, including compile, releaseand detect defaultscontains the default configuration docscontains project documentation extensionscontains non-core extensions envvirtualenv environment libcontains core extensions, helper code and the buildpack utils scriptscontains the Python scripts that run on compile, release and detect testscontains test scripts and test data run_tests.sha convenience script for running the full suite of tests The easiest way to understand the buildpack is to trace the flow of the scripts. The buildpack system calls the compile, releaseand detectscripts provided by the buildpack. These are located under the bindirectory and are generic. They simply redirect to the corresponding Python script under the scriptsdirectory. Of these, the detectand releasescripts are straightforward, providing the minimal functionality required by a buildpack. The compilescript is more complicated but works like this. WEBDIRdirectory rewriteand startscripts The buildpack relies heavily on extensions. An extension is simply a set of Python methods that will get called at various times during the staging process. Included non-core extensions: - composer- Downloads, installs and runs Composer - dynatrace- Downloads and configures Dynatrace OneAgent - Looks for a bound service with name dynatraceand value credentialswith sub-keys - apiurl- environmentid- apitoken- geoip- Configures geoip & optionally downloads geoip databases - Looks for a bound service with name geoip-serviceand value credentialswith sub-keys - username- license- products- newrelic- Downloads, installs and configures the NewRelic agent for PHP - session- Configures PHP to store session information in a bound Redis or Memcached service instance In general, you shouldn't need to modify the buildpack itself. Instead creating your own extension should be the way to go. To create an extension, simply create a folder. The name of the folder will be the name of the extension. Inside that folder, create a file called extension.py. That file will contain your code. Inside that file, put your extension methods and any additional required code. It's not necessary to fork the buildpack to add extensions for your app. The buildpack will notice and use extensions if you place them in a .extensionsfolder at your application root. See the extensions directory in the cf-ex-wordpressexample for a sample. Here is an explanation of the methods offered to an extension developer. All of them are optional and if a method is not implemented, it is simply skipped. def configure(ctx): pass The configuremethod gives extension authors a chance to adjust the configuration of the buildpack prior to any extensions running. The method is called very early on in the lifecycle of the buildpack, so keep this in mind when using this method. The purpose of this method is to allow an extension author the opportunity to modify the configuration for PHP, the web server or another extension prior to those components being installed. An example of when to use this method would be to adjust the list of PHP extensions that are going to be installed. The method takes one argument, which is the buildpack context. You can edit the context to update the state of the buildpack. Return value is ignore / not necessary. def preprocess_commands(ctx): return () The preprocess_commandsmethod gives extension authors the ability to contribute a list of commands that should be run prior to the services. These commands are run in the execution environment, not the staging environment and should execute and complete quickly. The purpose of these commands is to give extension authors the chance to run any last-minute code to adjust to the environment. As an example, this is used by the core extensions rewrite configuration files with information that is specific to the runtime environment. The method takes the context as an argument and should return a tuple of tuples (i.e. list of commands to run). def service_commands(ctx): return {} The service_commandsmethod gives extension authors the ability to contribute a set of services that need to be run. These commands are run and should continue to run. If any service exits, the process manager will halt all of the other services and the application will be restarted by Cloud Foundry. The method takes the context as an argument and should return a dictionary of services to run. The key should be the service name and the value should be a tuple which is the command and arguments. def service_environment(ctx): return {} The service_environmentmethod gives extension authors the ability to contribute environment variables that will be set and available to the services. The method takes the buildpack context as its argument and should return a dictionary of the environment variables to be added to the environment where services (see service_commands) are executed. The key should be the variable name and the value should be the value. The value can either be a string, in which case the environment variable will be set with the value of the string or it can be a list. If it's a list, the contents will be combined into a string and separated by the path separation character (i.e. ':' on Unix / Linux or ';' on Windows). Keys that are set multiple times by the same or different extensions are automatically combined into one environment variable using the same path separation character. This is helpful when two extensions both want to contribute to the same variable, for example LDLIBRARYPATH. Please note that environment variables are not evaluated as they are set. This would not work because they are set in the staging environment which is different than the execution environment. This means you cannot do things like PATH=$PATH:/new/pathor NEWPATH=$HOME/some/path. To work around this, the buildpack will rewrite the environment variable file before it's processed. This process will replace any @markers with the value of the environment variable from the execution environment. Thus if you do PATHor NEWPATH. def compile(install): return 0 The compilemethod is the main method and where extension authors should perform the bulk of their logic. This method is called by the buildpack while it's installing extensions. The method is given one argument which is an Installer builder object. The object can be used to install packages, configuration files or access the context (for examples of all this, see the core extensions like HTTPD, Nginx, PHP, Dynatrace and NewRelic). The method should return 0 when successful or any other number when it fails. Optionally, the extension can raise an exception. This will also signal a failure and it can provide more details about why something failed. It is sometimes useful to know what order the buildpack will use to call the methods in an extension. They are called in the following order. configure compile service_environment service_commands preprocess_commands Here is an example extension. While technically correct, it doesn't actually do anything. Here's the directory. $ ls -lRh total 0 drwxr-xr-x 3 daniel staff 102B Mar 3 10:57 testextn ./testextn: total 8 -rw-r--r-- 1 daniel staff 321B Mar 3 11:03 extension.py Here's the code. import logging _log = logging.getLogger('textextn') Extension Methods def configure(ctx): pass def preprocess_commands(ctx): return () def service_commands(ctx): return {} def service_environment(ctx): return {} def compile(install): return 0 defaults/options.jsonfile is for the buildpack and its core extensions. See the NewRelic buildpack for an example of this. tests/test_.py. Join the #buildpacks channel in our Slack community This project is managed through GitHub. If you encounter any issues, bug or problems with the buildpack please open an issue. The project backlog is on Pivotal Tracker
https://xscode.com/cloudfoundry/php-buildpack
CC-MAIN-2020-50
refinedweb
1,421
56.25
Singleton objects are not some fancy concept but a very practical solution to representing a specific value as an object as Pythons None object shows. Many programming languages provide syntactical solutions to provide constants. Literals like 123 or "a string" are almost always constants but if you want to give a meaningful name to a constant you need a different approach. Referring to value by name is simple enough, after all a variable assignment does just that, but you need some way to indicate that that variable shouldn't be altered after the assignment. Python does not provide a way to specify a constant but there are ways around this, see for example (this recipe). Paradoxically, it is comparatively simple to define a class that allows only a single instantiated object. There are arguments for and against this Singleton Design Pattern and this article is a good starting point if you want to read about it. And whatever the merits of this design pattern, you can't avoid it because many constants in Python are implemented as singleton classes, for example True, False, NotImplemented and None. And the None implementation illustrates another practical advantage: when comparing a value against a singleton we can check whether they are identical (with the is operator) instead of comparing their values (with the == operator) and although this might not be the primary purpose, it does give us a clear speed advantage as the next snippets shows: import timeit s1 = "123 == None" s2 = "a == None" s3 = "123 is None" s4 = "a is None" count=1000000 t = timeit.Timer(stmt=s1,setup='a=123') print (s1, "%.2f usec/pass" % (count * t.timeit(number=count)/count)) t = timeit.Timer(stmt=s2,setup='a=123') print (s2, "%.2f usec/pass" % (count * t.timeit(number=count)/count)) t = timeit.Timer(stmt=s3,setup='a=123') print (s3, "%.2f usec/pass" % (count * t.timeit(number=count)/count)) t = timeit.Timer(stmt=s4,setup='a=123') print (s4, "%.2f usec/pass" % (count * t.timeit(number=count)/count))The results of running this bit of code on my Samsung NC10 netbook give me the following output: 123 == None 0.29 usec/pass a == None 0.31 usec/pass 123 is None 0.20 usec/pass a is None 0.21 usec/passThis is a significant difference and although it doesn't seem to amount to much, this might shave several seconds of your algorithm when you compare for example the results of a large database query, as databases tend to represent NULL values as None.
http://michelanders.blogspot.com/2011/02/singleton-objects.html
CC-MAIN-2017-22
refinedweb
423
56.66
Testing API Requests From window.fetch - 6/5/2015 - · - #howto - #javascript - #sinon - #testing _Here’s how to combine window.fetch and sinon stubs to test API requests. This is the second of two parts in a miniseries on functional client-server testing. In the first, we used sinon.js’s fakeServer utility to test an XMLHttpRequest-based client. If you’re in a hurry, skip on over to the demo project on Github; everyone else, read on!__ If we designed a generic API for JavaScript client requests today, chances are that it wouldn’t look like XHR. Most of the interactions we need to make with a server can be represented simply as a request (method, path, body); custom headers take care of a few more edges; and the remainder will be made using websockets or novel browser transport layers. It’s no surprise, then, that, the first common cases are covered first by the emerging specification for window.fetch. If we designed an HTTP client API for JavaScript today, chances are it wouldn’t look like XHR. Introduction Simple requests made with fetch look much like those made by any other client library. They take a path and any request-specific options and return the server’s (eventual) Response as a Promise object: window.fetch('/api/v1/users') .then((res) => { console.log(res.status); }); Note that we’ll use ES6 syntax throughout this discussion on the assumption that ES6 will be in widespread use by the time window.fetch is broadly supported (and that babel-compiled projects are sufficient for now); back-porting to ES5-compliant code is left as an exercise for the reader. Supported tomorrow, but usable today At press time window.fetch enjoys native support in exactly zero browsers (update: months pass and adoption is now mixed), but the fine folks over at github have released an XHR-based polyfill for the current specification. It may change before the standard is finalized. For us, though, it’s a start–using it, we can begin using fetch in client applications today: $ npm install whatwg-fetch Next, we’ll need a simple client to test. This implementation proxies window.fetch requests to a JSON API, employing some trivial response parsing to type error responses and capitalize successful ones. import 'whatwg-fetch'; function apiError (status, message) { var err = new Error(message); err.status = status; return err; } function onAPIError (res) { return res.json().then(function (json) { throw apiError(res.status, json.message); }); } function onAPIResponse (res) { return { hello: json.hello.toUpperCase() }; } export default function client (path) { return window.fetch(path) .catch(onAPIError) .then(onAPIResponse); }; End users won’t interact with the client directly, of course. Rather, they’ll be interacting with it through the UI and scheduled events within a bigger web application. While our tests will focus on the client for simplicity, the same approaches used to test the client can also unlock higher-level tests for the interface. If we can mimic a server response to a direct client request, we can mimic the same response (for instance) when a user clicks a button or saves their progress. High-level tests In our previous look at testing XHR-based applications, we considered client-server interactions from both the unit and functional levels: unit - test that our code provides correct arguments to window.fetchor any client libraries that wrap it functional - test that our code results in a correctly-dispatched Requestand reacts appropriately to the Response Functional tests are marginally more difficult to set up, but testing against a standard (even an emerging one) enables separation between application logic and the request layer while encouraging more valuable tests than those written at the unit level. We’ll take a similar approach here. Testing the client Let’s look at a simple functional test that capture’s the client’s “success” behavior. it('formats the response correctly', () => client('/foobar') .then(json => expect(json.hello).toBe('WORLD'))); Running the test as written yields a 404 when the runner is unable to GET /foobar. In order to make it pass, we need to describe the expected behavior of the underlying server. Instead of using an existing utility like sinon.fakeServer as we did with the more complex XHR API, the design of the fetch API is simple enough for us to mock it ourselves. First, let’s stub window.fetch. This serves both to cancel any outbound requests and to let us supply our own default behavior: beforeEach(() => { sinon.stub(window, 'fetch'); }); afterEach(() => { window.fetch.restore(); }); Next, we need to mock a behavior that matches the actual Response we would receive from a fetched request. For a simple success response from a JSON API, we could simply write: beforeEach(() => { var res = new window.Response('{"hello":"world"}', { status: 200, headers: { 'Content-type': 'application/json' } }); window.fetch.returns(Promise.resolve(res)); }); Note that this behavior is synchronous–the Promise-d Response is resolved immediately–but our test is written in an asynchronous style (runners like jasmine and mocha will wait for a returned promise to resolve before moving on to the rest of the suite). While not strictly necessary, assuming that a fetch could resolve during a separate tick through the event loop yields both a more flexible test and a better representation of reality. In any case, the test client will now encounter the resolved Response, apply its formatting, and turn the previously-failing spec bright green. Tidying up Just as with XHRs, the server behaviors mocked across a non-trivial test suite are likely to involve some repetition. Rather than formatting each JSON response independently, or injecting the same headers across multiple tests, it’s well worth considering test helpers to reduce the volume of boilerplate. For an example, we can update the jsonOk and jsonError helpers used in our XHR-based tests to build Response objects instead: function jsonOk (body) { const mockResponse = new window.Response(JSON.stringify(body), { status: 200, headers: { 'Content-type': 'application/json' } }); return Promise.resolve(mockResponse); } function jsonError (status, body) { const mockResponse = new window.Response(JSON.stringify(body), { status: status, headers: { 'Content-type': 'application/json' } }); return Promise.reject(mockResponse); } These barely scratch the surface of useful testing facilities–we might want to match specific requests, for instance, or write helpers to describe sequences of requests (as in an authentication flow)–but even a simple helper like jsonOk can reduce test setup to a nearly-trivial line: beforeEach(() => { window.fetch.returns(jsonOk({ hello: 'world' })); }); Conclusion window.fetch provides a more straightforward API than XMLHttpRequest, and it’s reflected in our tests. Instead of needing to contrive a mock with a wide range of event states, accessors, and boutique behaviors, fetch can be tested with simple stubs and instances of the actual objects used in its normal operation. There’s still a fair amount of boilerplate, which helpers can mitigate somewhat, but the volume of “magic”–fake global objects and the like–needed to mimic low-level behavior is significantly reduced.
https://rjzaworski.com/2015/06/testing-api-requests-from-window-fetch
CC-MAIN-2022-05
refinedweb
1,161
53.61
import hook, overwrite import? Discussion in 'Python' started by Torsten Mohr, Jan 26, 2005. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads Hook JScript Client Events to Server ControlsDavid Pifer via .NET 247, May 2, 2004, in forum: ASP .Net - Replies: - 1 - Views: - 2,934 - David Jessee - May 2, 2004 Reference implementation of an import hookNoam Raphael, Jun 21, 2004, in forum: Python - Replies: - 0 - Views: - 331 - Noam Raphael - Jun 21, 2004 import hookJeremy Sanders, Jun 11, 2006, in forum: Python - Replies: - 4 - Views: - 450 - Jeremy Sanders - Jun 18, 2006 simple import hookAndrea Crotti, Nov 10, 2011, in forum: Python - Replies: - 0 - Views: - 197 - Andrea Crotti - Nov 10, 2011 multiversion flag and auto requiring import hookAndrea Crotti, Jan 19, 2012, in forum: Python - Replies: - 0 - Views: - 225 - Andrea Crotti - Jan 19, 2012
http://www.thecodingforums.com/threads/import-hook-overwrite-import.340759/
CC-MAIN-2016-07
refinedweb
170
75.64
These are the DM L2 Issues. This document is an editor's draft and has no normative status This document identifies the status of Last Call issues on XQuery 1.0 and XPath 2.0 Data Model as of February 11, 2005. The Working Groups have continued to develop the document since the close of the previous Last Call period.\u2019ll add the mapping. Here are the comments from the DOM Working Group regarding the XQuery/XPath Data Model document [1]. [\u2026]\u2019ll you for your comment. You asked that the Data model should support cdata sections. The XML Query and XSL Working Groups considered this request. Since CDATA sections are an artifact of input encoding, they are not reflected in the Data Model, and the comment was therefore rejected. SECTION. [My.] apologies that these comments are coming in after the end of the Last Call comment period.] Section 3 The second paragraph states that "The data model supports well-formed XML documents conforming to [Namespaces in XML]." The Infoset recommendation errata supports documents conforming to XML 1.1 and Namespaces in XML 1.1. If Data Model refers to Infoset, this section needs to either include Namespaces 1.1 or be worded more generally. This comment applies throughout this section. Thanks, Henry [Speaking on behalf of reviewers from IBM, not just personally.] Decided at BEA face-to-face: fixed [My.] Decided at joint telcon 183: added wording to clarify. SECTION. Decided at BEA face-to-face: agreed to clarify. SECTION) Decided at BEA face-to-face: it\u2019s an error to map a PI whose name is not an NCName. SECTION 6.5.1: Overview (of processing instructions) It says that the target property must be an NCName. XML 1.0 only requires the target to be a Name, ie, permits any number of colons. Oddly, Namespaces 1.0 has nothing to say about the target of processing instructions. It seems like the target of a processing instruction should be allowed to be a Name, since that is the only restriction in XML 1.0 + Namespaces 1.0; or at least a QName, which would be a restriction in the spirit if not the letter of Namespaces 1.0. (see also comment re: 6.5.3) Decided at BEA face-to-face: it\u2019s Model: specification too fuzzy The Data Model misses certain consistency constraints that seem to be required to preserve a data model instance internally consistent. Examples are: (a) is it true that if a node has a base uri propery, then all the descendants have the same base-uri property? (b) is it true that if a node has the nillability property being true, then it has no text and elements nodes as children, and it has an attribute xsi:nil="true"? (c) if the type annotation of an element is a certain Qname different from xdt:untyped and the element has an attribute xsi:type, then are the value of the attribute and the type annotation required to be the same ? (d) etc If the data model is generated via Infoset or PSVI it is relatively clear that those extra constraints are not violated. The problem is that Data Model instances can be generated directly by applications from other input structures (e.g SQL records, COBOL structures) etc. The concern is that the application generated data model instances (other then Infoset and PSVI) do not have a set of rules and constraints clearly spelled out that they will have to satisfy to create correct data model instances.]. The spec has been significantly redrafted in this area and we believe your concern has now been addressed.\u2019t have a conformance section; the host language has to describe conformance.] This issue is just the preamble for the issues that follow. Closed. this is fixed. Norm to ask schema to review.. Decided at BEA face-to-face: added note about lightweight] The spec has been significantly redrafted in this area and we believe your concern has now been addressed.? The spec has been significantly redrafted in this area and we believe your concern has now been addressed., ..." The spec has been significantly redrafted in this area and we believe your concern has now been addressed.? The spec has been significantly redrafted in this area and we believe your concern has now been addressed.." Decided at BEA face-to-face: DM/FS/F&O editors should review revised Section 7.. The particular problem identified here does not occur because we use the SchemaNormalizedValue if it exists. But this section has been rewritten to clarify the points raised by Schema.. Decided at BEA face-to-face: DM/FS/F&O editors should review revised Section 7.. Decided at BEA face-to-face: DM/FS/F&O editors should review revised Section 7..) Decided at BEA face-to-face: status quo solves existing use cases. Announced.. Decided at the Aug 2004 f2f: the triples proposal will address this issue. Model Section 6.3.2 (Attribute Nodes--Accessors): The dm:typed-value accessor claims to return the "atomic value that is determined from its tuple representation." But (as in the case of element nodes), the properties of an attribute node do not include any such "tuple representation". The typed-value accessor should be defined in terms of the properties of the node, and these properties should be extended if necessary to support the accessor. Model Section 6.3.4 (Attribute Nodes--Construction from a PSVI): Earlier sections have stated that for date/time values, an explicit timezone must be captured. This mapping section does not describe any way in which the explicit timezone of a date/time value is extracted from the PSVI.. Decided at joint telcon 183: resolved to make the type of nodes always the union type and the type of the atomic values the member type. This was approved at meeting 185. Section).\u2019ve adopted a new definition of document order and made the other editorial changes. The) White space is now significant in all cases except element-only content where it is not significant. The draft has been clarified to reflect this.". Decided at joint telcon 183: occurrences of the word \u2018type\u2019 have been qualified.. The WG feels comfortable with the current model. Closed with no action...] + ... The spec has been significantly redrafted in this area and we believe your concern has now been addressed. ...". We believe these comments are all addressed in the 23 July draft.. / Asir Vedamuthu <asirv@webmethods.com> was heard to say: | I have a quick question. I am wondering if these issues are recorded in a | last call issues list. If so, may I request you to send me a link? They are now recorded[1]. Apologies in advance for any formatting glitches; like the rest of the XSL/XML Query editorial team, I'm still getting used to the ExIT system. Asir/Michael/Schema WG: please acknowledge that you accept resolution of qt-2003Aug0002-14, the issues I believe have been overtaken by events. Paul: please add qt-2003Aug0002-03 (1.3. Items and singleton sequences) and qt-2003Aug0002-04 (1.4. The implications of [validity] != valid) to the discussion list for the f2f. (And accept my apologies for tardiness, please.) Be seeing you, norm [1] > | [3.. Decided at joint telcon 185: define the term \u201cinstance of the data model\u201d 1: Introduction In paragraph 5, the spec stated, "Every value in the data model is a sequence of zero or more items." It went on to discuss "node" and "atomic value" in paragraph 6 and 7. Paragraph 6: "Every node is one of the seven kinds defined in 6 Nodes..." Paragraph 7: "An atomic value encapsulates an XML Schema atomic type and a corresponding value of that type..." A sentence should be appended in paragraph 5 to clarify what is an item, say ", and an item may be a node or an atomic value". This would bridge the current conceptual gap between sequence and node/atomic value. SECTION...". SECTION 2.4: document order First sentence: "A document order is defined among all the nodes used during a given query or transformation." Good sentence; you have not equated the data model with a particular realization of it. Third sentence: "Informally, document order is the order returned by an in-order, depth-first traversal of the data model." wrong! What you mean is "traversal of the trees in an instance of the data\u2019s discretion. Closed. SECTION 3: Data Model Construction The paragraph before 3.1 refers to 'well-formed document fragments', what is this ? The words 'well-formed', 'fragments', 'document' are overloaded in XML. Please define them exactly here. SECTION. 6.2.1 : Overview (of element nodes) Point 10 in the list of constraints on elements nodes says: "If an attribute node A has a parent element E, then A must be among the attributes of E. The data model permits attribute nodes without parents. Such attribute nodes must not appear among the attributes of any element node." And in 6.3.1 Overview (for attribute nodes) constraint 2 is a duplicate of this constraint. Consider the following pathological data set: two elements E1 and E2 and one attribute A. The attributes property for both E1 and E2 lists A as the only attribute of these elements. Attribute A lists E1 as its parent. This data set meets all of the constraints quoted. What is missing is a constraint that says that if A is an attribute of element E, then E is the parent of A. That is, you have a constraint on one direction of the pointers, but not on the other direction. I believe namespace nodes have the same problem. Accepted editorial suggestions. (Fragment is now referenced.) SECTION..." SECTION 5.10: namespaces accessor You don't specify the order of the namespace nodes. Is it intended that the sequence of namespace nodes is in document order, as defined in section 2.4 "Document order", or is it perhaps left as an implementation-dependent order? Suggest: add "... in Document order" to the definition.: +? The spec has been significantly redrafted in this area and we believe your concern has now been addressed.. / D..4: Typo - "Retreiving" should be "Retrieving". [ Fixed in DM 17 Feb 2004 ].]" The spec has been significantly redrafted in this area and we believe your concern has now been addressed.." The spec has been significantly redrafted in this area and we believe your concern has now been addressed.. The spec has been significantly redrafted in this area and we believe your concern has now been addressed.? These problems have been fixed.? The spec has been significantly redrafted in this area and we believe your concern has now been addressed. Model Section 6.2.3 (Element Nodes--Construction from an Infoset): Under "namespaces" we see that an implementation may ignore namespace info items for namespaces that do not appear "in the expanded QName of any element or attribute info item". This should be clarified to state "in the expanded QName of the current element or any of its attributes." Presumably the infoset-to-data-model mapping for a given element should not depend on whether a namespace has been used in the name of some other element. Data Model Sections 6.5.3 and 6.6.3: Section heading should be "Construction from an Infoset" in each case. Data Model Section 6.2.2 (Element Nodes--Accessors): The dm:string-value and dm:typed value accessors have some problems with terminology. Both accessor descriptions refer to "complex type with complex content" but this terminology is not found in XML Schema. In XML Schema, a complex type may have empty content, simple content, mixed content, or element-only content. The accessor descriptions should use these terms rather than the undefined term "complex content". For an example of how to do this, see Section 2.4.2 (Typed Value and String Value) in the language document, which the Data Model description should be consistent with in any?) Section (also applies to other specifications) Editorial The specifications currently use the term value in a somewhat ambiguous way. Sometimes it implies "atomic value" (what most people associate with this term), sometimes it implies "item", sometimes it implies "sequence of items". Since we believe that most spec readers understand "atomic value" when they read "value", we propose that the specs should not use the term value. Use item, node, atomic value and sequence thereof as appropriate instead. \u201ckind\u201d.] The section on types and atomic values has been extensively redrafted to address this and a number of other related comments."?
http://www.w3.org/2005/02/data-model-issues.html
CC-MAIN-2018-26
refinedweb
2,107
57.47
send a message to a process associated with a file descriptor #include <sys/kernel.h> #include <sys/sendmx.h> int Sendfdmx( int fd, unsigned sparts, unsigned rparts, struct _mxfer_entry *smsg, struct _mxfer_entry *rmsg ); The kernel function Sendfdmx() sends a message taken from the array of buffers pointed to by smsg to the process associated with fd. Any reply is placed in the array of buffers pointed to by rmsg. The size of the send array is given by sparts, while the size of the receive array is given by rparts. The size of these arrays must not exceed _QNX_MXTAB_LEN (defined in <limits.h>).mx() becomes equivalent to a Sendmx(). This call is used heavily by the I/O library to direct messages to the appropriate resource manager based upon a file descriptor (for example, read()). You should only need to use it if you write your own resource manager that implements a new file descriptor that doesn't exist, or the process mapped by that file descriptor dies while you're BLOCKED on it, Sendfdmx() returns -1 and errno is set to ESRCH. Sendfdmx() may be interrupted by a signal, in which case it returns -1 and errno is set to EINTR. It's quite common to send two-part messages consisting of a fixed header and a buffer of data. Sendfd <limits.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/kernel.h> #include <sys/io_msg.h> char buffer[100]; int main() { int fd, n; if( ( fd = open( "/config/sysinit", O_RDONLY ) ) == -1 ) return( -1 ); while( ( n = reed( fd, buffer, sizeof( buffer ) ) ) > 0 ) write( 2, buffer, n ); return ( EXIT_SUCCESS ); } int reed( fd, buf, nbytes ) int fd; void *buf; unsigned int nbytes; { union _read { struct _io_read s; struct _io_read_reply r; } msg; struct _mxfer_entry mx_entry[2]; if( nbytes > INT_MAX ) { errno = EINVAL; return( -1 ); } /* Set up the message header. */ msg.s.type = _IO_READ; msg.s.fd = fd; msg.s.nbytes = nbytes; msg.s.zero = 0; _setmx( &mx_entry[0], &msg, sizeof( struct _io_read ) ); /* Setup the reply buffer description. */ _setmx( &mx_entry[1], buf, nbytes ); /* Sendfd would need to copy the message header and */ /* data into one contiguous message. */ if( Sendfdmx( fd, 1, 2, &mx_entry, &mx_entry ) == -1 ) return( -1 ); if( msg.r.status != EOK ) { errno = msg.r.status; return( -1 ); } return( msg.r.nbytes ); } QNX Sendfd() is a macro. Creceive(), Creceivemx(), errno, Receive(), Receivemx(), Reply(), Replymx(), Readmsg(), Readmsgmx(), Send(), Sendfd(), Sendmx(), Writemsg(), Writemsgmx(), Trigger()
https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/sendfdmx.html
CC-MAIN-2022-33
refinedweb
405
66.74
Groovy Development Native List and Map Syntax Like Jython (my previous favorite JVM-based scripting language), Groovy has some very powerful support for lists and maps built in. For example, instead of having to say: HashMap myMap = new HashMap(); myMap..put("1","Fred"); myMap.put("2","George"); You can use the much shorter and clearer: groovyMap = ["1":"Fred", "2":"George"] Likewise, list support is built in: myList = [1,"2","Three",4] Note: Boxing for the int values in the list is handled for you, so the above is perfectly valid Groovy syntax. Not much exciting there, but the simplicity continues: copyList = myList[1..2] will create a list called copyList with the contents ["2","Three"] based on the second and third elements of myList. This barely scratches the surface of collections in Groovy, but you should move on to the more interesting stuff. Suffice to say that much more information on the collections and the other language features can be found at. Closures The reason I did bring collections up is because they are really useful for demonstrating closures. In a nutshell, a closure is a code block that does not have a name. One typical use for a closure is to run some block of code on every element in a collection. A closure has enclosing braces, and then a part where parameters are declared, followed by a -> operator, and then the code block. So, for example: groovyMap = ["Fred":1, "George":3, "Harry":2, "Tom":2] groovyMap.each() { name, times -> for (i in 1..times) { System.out.print(name + " "); } System.out.println(); } When executed, this will print each of the names the number of times matching the numerical argument associated with each in the map. Closures can also just be stored in a variable; for example: def clos = { name, times -> for (i in 1..times) { System.out.print(name + " "); } System.out.println(); } clos.call("James",4) Will print James four times to the standard output. Note that while this might just look like a strange function definition, the closure could be passed in to a Groovy method to be applied to data from inside the method. This is very powerful and yet simple polymorphism. Smalltalk and Lisp programmers will immediately recognize the potential and power here. Closures can be applied to all sorts of things. I have demonstrated simple collections here, but farther down I will demonstrate them on much more useful things, like XML nodes and SQL results sets. Other Syntax Enhancements There are many other syntactical enhancements that make programming Groovy a pleasure. For example: built-in support for regular expressions using the =~ operator, and an improved switch operator that can natively match strings and also perform range checks (is switch value in range 0..12). Another important one is the Groovy expression language. This lets you insert variables and expressions into strings or other formatted output. For example: println "hello ${name}" will print "hello " followed by the value of the name variable. This comes in useful in the examples below. It can do more than just variable expansion, allowing you to navigate object hierarchies. You even can call methods and the return argument will be inserted into the string. There are many more than could be covered in this article, so again I would like to point you at the language guide () because I really want to move on to the SQL and XML stuff. Markup There is one more important Groovy construct before you start laying your hands on XML and SQL. That is the idea of Markup. Markup is very cool. It is the ability to construct something (say, an XML file or Swing GUI) by using structured code that looks kind of like a Java class or method definition. It's hard to explain, but far easier to demonstrate. import groovy.xml.MarkupBuilder; def myXMLDoc = new MarkupBuilder() myXMLDoc.library { section(id:"Programming") { book(title:"Java? Groovy!", author:"Duke McCoffee") book(title:"The art of hacking code", author:"Uber Hacker") } } println myXMLDoc results in the XML snippet: <library> <section id='Programming'> <book title='Java? Groovy!' author='Duke McCoffee' /> <book title='The art of hacking code' author='Uber Hacker' /> </section> </library> Not bad. When was the last time you were able to form an XML document in Java where the code to create it was about as compact as the resulting XML document (ignoring the import and the line to create the markup builder)? XML Handling You have just seen the compact way that XML can be output, but face it, although the notation is compact, there is nothing particularly hard about outputting XML, right? The hard part with XML is parsing it in; even the "easy" option of DOM in Java is pretty wordy. Fortunately, Groovy is as strong at parsing XML as it is at writing it. Once again, an example tells you more than any amount of description: xmlData = """<library> <section id='Programming'> <book title='Java? Groovy!' author='Duke McCoffee' /> <book title='The art of hacking code' author='Uber Hacker' /> </section> <section id='Whimsy'> <book title='Ooh, la la' author='The Fops' /> </section> </library>""" library = new groovy.util.XmlParser().parseText(xmlData) library.section.each() { section -> println "Section = ${section['@id']}" section.book.each() { book -> println "Book: ${book['@title']} by ${book['@author']}" } } The first section is just putting an XML snippet into a string; the triple quotes let the string span several lines and include the newlines, so this is representative of what you might read out of an XML file. The line that reads: library = new groovy.util.XmlParser().parseText(xmlData) creates a groovy XML parser node that you can use within the rest of the example. The really interesting stuff happens below that, though. Firstly, you assign the handle "library" to the node; you know in this case that your document's outer node is the "library" node, so that is just for readability. However, you also can start referring to the XML tags inside of that node by name. library.section matches the section child tags inside the library node; the details are not too important, but you can think of it as returning a collection of those section nodes, which you can use a closure on. So, the line: library.section.each() { section -> iterates over the section nodes in library and calls the closure for each one, putting the node into the section variable before doing so; you then can refer to it from there. Apply this trick deep enough and you can parse the whole XML document, and equally easily just ignore the sections you are not interested in. Also, farther down you start to use the XML attributes in the tags. For example, you access the ID attribute in the section tag, and the title and author attributes from the book tag. To do this, you use the xpath notation @attr-name in the context of a list or map lookup. For example: println "Book: ${book['@title']} by ${book['@author']}" obtains the title and author attributes out of the book node as though they were named map entries (which, in a sense, they are). Note also that the Groovy expression language is used to good effect here to dump the resulting values directly into a formatted string. Now, I don't know about you, but this is among the simplest and best XML handling I have seen in any language, for both input and output. This example is small, but this same few lines of code could intelligently handle a library with hundreds of sections and books. A few more nested closures and it could handle some pretty large and complex XML schemas in a very few lines of code. Likewise, the output, with careful use of loops and closures there mixed in with the XML markup, could produce equally large and complex XML schemas in a similarly compact way. You have won the first battle for your translators—easy XML handling—now what can you do about the SQL side (remember, these translators are for XML->SQL and SQL->XML)? Page 2 of 3
http://www.developer.com/lang/article.php/10924_3548721_2/Groovy-Development.htm
CC-MAIN-2014-52
refinedweb
1,347
60.85
Table of Contents In Berkeley DB Java Edition, a database is a collection of records. Records, in turn, consist of key/data pairings. Conceptually, you can think of a Database as containing a two-column table where column 1 contains a key and column 2 contains data. Both the key and the data are managed using DatabaseEntry class instances (see Database Records for details on this class ). So, fundamentally, using a JE Database involves putting, getting, and deleting database records, which in turns involves efficiently managing information encapsulated by DatabaseEntry objects. The next several chapters of this book are dedicated to those activities. Note that on disk, databases are stored in sequentially numerically named log files in the directory where the opening environment is located. JE log files are described Databases and Log Files. You open a database by using the Environment.openDatabase() method (environments are described in Database Environments). This method creates and returns a Database object handle. You must provide Environment.openDatabase() with a database name. You can optionally provide Environment.openDatabase() with a DatabaseConfig() object. DatabaseConfig() allows you to set properties for the database, such as whether it can be created if it does not currently exist, whether you are opening it read-only, and whether the database is to support transactions. Note that by default, JE does not create databases if they do not already exist. To override this behavior, set the creation property to true. Finally, if you configured your environment and database to support transactions, you can optionally provide a transaction object to the Environment.openDatabase(). Transactions are described in the Berkeley DB Java Edition Getting Started with Transaction Processing guide. The following code fragment illustrates a database open:); myDatabase = myDbEnvironment.openDatabase(null, "sampleDatabase", dbConfig); } catch (DatabaseException dbe) { // Exception handling goes here } By default, JE's databases are all persistent. That is, the data they contain is stored on disk so that it can be accessed across program runs. However, it is possible to configure JE's databases so that they are by default not persistent. JE calls databases configured in this way to be deferred write databases. Deferred write databases are essentially in-memory only databases. Therefore, they are particularly useful for applications that want databases which are truly temporary. Note that deferred write databases do not always avoid disk I/O. It is particularly important to realize that deferred write databases can page to disk if the cache is not large enough to hold the database's entire contents. Therefore, deferred write database performance is best if your in-memory cache is large enough to hold the database's entire data-set. Beyond that, you can deliberately cause data modifications made to a deferred write database to be made persistent. If Database.sync() is called before the application is shutdown, the contents of the deferred write database is saved to disk. In short, upon reopening an environment and a deferred write database, the database is guaranteed to be in at least the same state it was in at the time of the last database sync. (It is possible that due to a full in-memory cache, the database will page to disk and so the database might actually be in a state sometime after the last sync.) This means that if the deferred write database is never sync'd, it is entirely possible for it to open as an empty database. Because modifications made to a deferred write databases can be made persistent at a time that is easily controlled by the programmer, these types of databases are also useful for applications that perform a great deal of database modifications, record additions, deletions, and so forth. By delaying the data write, you delay the disk I/O. Depending on your workload, this can improve your data throughput by quite a lot. Be aware that you lose modifications to a deferred write database only if you (1) do not call sync, (2) close the deferred write database and (3) also close the environment. If you only close the database but leave the environment opened, then all operations performed on that database since the time of the last environment open may be retained. All other rules of behavior pertain to deferred write databases as they do to normal databases. Deferred write databases must be named and created just as you would a normal database. If you want to delete the deferred write database, you must remove it just as you would a normal database. This is true even if the deferred write database is empty because its name persists in the environment's namespace until such a time as the database is removed. Note that determining whether a database is deferred write is a configuration option. It is therefore possible to switch a database between "normal" mode and deferred write database. You might want to do this if, for example, you want to load a lot of data to the database. In this case, loading data to the database while it is in deferred write state is faster than in "normal" state, because you can avoid a lot of the normal disk I/O overhead during the load process. Once the load is complete, sync the database, close it, and and then reopen it as a normal database. You can then continue operations as if the database had been created as a "normal" database. To configure a database as deferred write, set DatabaseConfig.setDeferredWrite() to true and then open the database with that DatabaseConfig option. For example, the following code fragment opens and closes a deferred write database:); // Make it deferred write dbConfig.setDeferredWrite(true); myDatabase = myDbEnvironment.openDatabase(null, "sampleDatabase", dbConfig); ... // do work ... // Do this if you want the work to persist across // program runs // myDatabase.sync(); // then close the database and environment here // (see the next section) } catch (DatabaseException dbe) { // Exception handling goes here } Once you are done using the database, you must close it. You use the Database.close() method to do this. Closing a database causes it to become unusable until it is opened again. If any cursors are opened for the database, JE warns you about the open cursors, and then closes them for you. Active cursors during a database close can cause unexpected results, especially if any of those cursors are writing to the database in another thread. You should always make sure that all your database accesses have completed before closing your database. Remember that for the same reason, you should always close all your databases before closing the environment to which they belong. Cursors are described in Using Cursors later in this manual. The following illustrates database and environment close: import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Database; import com.sleepycat.je.Environment; ... try { if (myDatabase != null) { myDatabase.close(); } if (myDbEnvironment != null) { myDbEnvironment.close(); } } catch (DatabaseException dbe) { // Exception handling goes here }
http://www.oracle.com/technology/documentation/berkeley-db/je/GettingStartedGuide/DB.html
crawl-001
refinedweb
1,146
55.64
Analysis programs in Flink are regular programs that implement transformations on data sets (e.g., filtering, mapping, joining, grouping). The data sets are initially created from certain sources (e.g., by reading files, or from. In order to create your own Flink program, we encourage you to start with the program skeleton and gradually add your own transformations. The remaining sections act as references for additional operations and advanced features. The following program is a complete, working example of WordCount. You can copy & paste the code to run it locally. from flink.plan.Environment import get_environment from flink.functions.GroupReduceFunction import GroupReduceFunction class Adder(GroupReduceFunction): def reduce(self, iterator, collector): count, word = iterator.next() count += sum([x[0] for x in iterator]) collector.collect((count, word)) env = get_environment() data = env.from_elements("Who's there?", "I think I hear them. Stand, ho! Who's there?") data \ .flat_map(lambda x, c: [(1, word) for word in x.lower().split()]) \ .group_by(1) \ .reduce_group(Adder(), combinable=True) \ .output() env.execute(local=True) As we already saw in the example, Flink programs look like regular python programs. Each program consists of the same basic parts: Environment, We will now give an overview of each of those steps but please refer to the respective sections for more details. The Environment is the basis for all Flink programs. You can obtain one using these static methods on class Environment: get_environment() For specifying data sources the execution environment has several methods to read from files. To just read a text file as a sequence of lines, you can use: env = get_environment() text = env.read_text("") This will give you a DataSet on which you can then apply transformations. For more information on data sources and input formats, please refer to Data Sources. Once you have a DataSet you can apply transformations to create a new DataSet which you can then write to a file, transform again, or combine with other DataSets. You apply transformations by calling methods on DataSet with your own custom transformation function. For example, a map transformation looks like this: data.map(lambda x: x*2) This will create a new DataSet by doubling every value in the original DataSet. For more information and a list of all the transformations, please refer to Transformations. Once you have a DataSet that needs to be written to disk you can call one of these methods on DataSet: data.write_text("<file-path>", WriteMode=Constants.NO_OVERWRITE) write_csv("<file-path>", line_delimiter='\n', field_delimiter=',', write_mode=Constants.NO_OVERWRITE). You can force a local execution by using execute(local=True). Apart from setting up Flink, no additional work is required. The python package can be found in the /resource folder of your Flink distribution. The flink package, along with the plan and optional packages are automatically distributed among the cluster via HDFS when running a job. The Python API was tested on Linux/Windows systems that have Python 2.7 or 3.4 installed. By default Flink will start python processes by calling “python” or “python3”, depending on which start-script was used. By setting the “python.binary.python[2/3]” key in the flink-conf.yaml you can modify this behaviour to use a binary of your DataSets into a new DataSet. Programs can combine multiple transformations into sophisticated assemblies. This section gives a brief overview of the available transformations. The transformations documentation has a full description of all transformations with examples. Some transformations (like Join or CoGroup) require that a key is defined on its argument DataSets, and other transformations (Reduce, GroupReduce) allow that the DataSet is grouped on a key before they are applied. A DataSet is grouped as reduced = data \ .group_by(<define key here>) \ .reduce_group(<do something>) The data model of Flink is not based on key-value pairs. Therefore, you do not need to physically pack the data set types into keys and values. Keys are “virtual”: they are defined as functions over the actual data to guide the grouping operator. The simplest case is grouping a data set of Tuples on one or more fields of the Tuple: reduced = data \ .group_by(0) \ .reduce_group(<do something>) The data set is grouped on the first field of the tuples. The group-reduce function will thus receive groups of tuples with the same value in the first field. grouped = data \ .group_by(0,1) \ .reduce(/*do something*/) The data set is grouped on the composite key consisting of the first and the second fields, therefore the reduce function will receive groups with the same value for both fields. A note on nested Tuples: If you have a DataSet with a nested tuple specifying group_by(<index of tuple>) will cause the system to use the full tuple as a key. Certain operations require user-defined functions, whereas all of them accept lambda functions and rich functions as arguments. data.filter(lambda x: x > 5) class Filter(FilterFunction): def filter(self, value): return value > 5 data.filter(Filter()) Rich functions allow the use of imported functions, provide access to broadcast-variables, can be parameterized using init(), and are the go-to-option for complex functions. They are also the only way to define an optional combine function for a reduce operation. Lambda functions allow the easy insertion of one-liners. Note that a lambda function has to return an iterable, if the operation can return multiple values. (All functions receiving a collector argument) Flink’s Python API currently only offers native support for primitive python types (int, float, bool, string) and byte arrays. The type support can be extended by passing a serializer, deserializer and type class to the environment. class MyObj(object): def __init__(self, i): self.value = i class MySerializer(object): def serialize(self, value): return struct.pack(">i", value.value) class MyDeserializer(object): def _deserialize(self, read): i = struct.unpack(">i", read(4))[0] return MyObj(i) env.register_custom_type(MyObj, MySerializer(), MyDeserializer()) You can use the tuples (or lists) for composite types. Python tuples are mapped to the Flink Tuple type, that contain a fix number of fields of various types (up to 25). Every field of a tuple can be a primitive type - including further tuples, resulting in nested tuples. word_counts = env.from_elements(("hello", 1), ("world",2)) counts = word_counts.map(lambda x: x[1]) When working with operators that require a Key for grouping or matching records, Tuples let you simply specify the positions of the fields to be used as key. You can specify more than one position to use composite keys (see Section Data Transformations). wordCounts \ .group_by(0) \ .reduce(MyReduceFunction()) Data sources create the initial data sets, such as from files or from collections. File-based: read_text(path)- Reads files line wise and returns them as Strings. read_csv(path, type)- Parses files of comma (or another char) delimited fields. Returns a DataSet of tuples. Supports the basic java types and their Value counterparts as field types. Collection-based: from_elements(*args)- Creates a data set from a Seq. All elements generate_sequence(from, to)- Generates the sequence of numbers in the given interval, in parallel. Examples env = get_environment \# read text file from local files system localLiens = env.read_text("file:#/path/to/my/textfile") \# read text file from a HDFS running at nnHost:nnPort hdfsLines = env.read_text("hdfs://nnHost:nnPort/path/to/my/textfile") \# read a CSV file with three fields, schema defined using constants defined in flink.plan.Constants csvInput = env.read_csv("hdfs:///the/CSV/file", (INT, STRING, DOUBLE)) \# create a set from some given elements values = env.from_elements("Foo", "bar", "foobar", "fubar") \# generate a number sequence numbers = env.generate_sequence(1, 10000000) Data sinks consume DataSets and are used to store or return them: write_text()- Writes elements line-wise as Strings. The Strings are obtained by calling the str() method of each element. write_csv(...)- Writes tuples as comma-separated value files. Row and field delimiters are configurable. The value for each field comes from the str() method of the objects. output()- Prints the str() value of each element on the standard out. A DataSet can be input to multiple operations. Programs can write or print a data set and at the same time run additional transformations on them. Examples Standard data sink methods: write DataSet to a file on the local file system textData.write_text("") write DataSet to a file on a HDFS with a namenode running at nnHost:nnPort textData.write_text("hdfs://nnHost:nnPort/my/result/on/localFS") write DataSet to a file and overwrite the file if it exists textData.write_text("", WriteMode.OVERWRITE) tuples as lines with pipe as the separator "a|b|c" values.write_csv("", line_delimiter="\n", field_delimiter="|") this writes tuples in the text formatting "(a, b, c)", rather than as CSV lines values.write_text(""). with_broadcast_set(DataSet, String) self.context.get_broadcast_variable(String)at the target operator class MapperBcv(MapFunction): def map(self, value): factor = self.context.get_broadcast_variable("bcv")[0][0] return value * factor # 1. The DataSet to be broadcasted toBroadcast = env.from_elements(1, 2, 3) data = env.from_elements("a", "b") # 2. Broadcast the DataSet data.map(MapperBcv()).with_broadcast_set("bcv", toBroadcast) Make sure that the names ( bcv in the previous example) match when registering and accessing broadcasted data sets. Note: As the content of broadcast variables is kept in-memory on each node, it should not become too large. For simpler things like scalar values you can simply parameterize the rich function. = get_environment() env.set_parallelism(3) text.flat_map(lambda x,c: x.lower().split()) \ .group_by(1) \ .reduce_group(Adder(), combinable=True) \ .output().sh script from the /bin folder. use pyflink2.sh for python 2.7, and pyflink3.sh for python 3.4. The script containing the plan has to be passed as the first argument, followed by a number of additional python packages, and finally, separated by - additional arguments that will be fed to the script. ./bin/pyflink<2/3>.sh <Script>[ <pathToPackage1>[ <pathToPackageX]][ - <param1>[ <paramX>]]
https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/batch/python.html
CC-MAIN-2018-13
refinedweb
1,637
50.02
Deeply Understand Currying in 7 Minutes Yazeed Bzadough ・6 min read Originally posted on yazeedb.com. So if you have greet = (greeting, first, last) => `${greeting}, ${first} ${last}`; greet('Hello', 'Bruce', 'Wayne'); // Hello, Bruce Wayne Properly currying greet gives you curriedGreet = curry(greet); curriedGreet('Hello')('Bruce')('Wayne'); // Hello, Bruce Wayne This 3-argument function has been turned into three unary functions. As you supply one parameter, a new function pops out expecting the next one. Properly? I say "properly currying" because some curry functions are more flexible in their usage. Currying's great in theory, but invoking a function for each argument gets tiring in JavaScript. Ramda's curry function lets you invoke curriedGreet like this: // greet requires 3 params: (greeting, first, last) // these all return a function looking for (first, last) curriedGreet('Hello'); curriedGreet('Hello')(); curriedGreet()('Hello')()(); // these all return a function looking for (last) curriedGreet('Hello')('Bruce'); curriedGreet('Hello', 'Bruce'); curriedGreet('Hello')()('Bruce')(); // these return a greeting, since all 3 params were honored curriedGreet('Hello')('Bruce')('Wayne'); curriedGreet('Hello', 'Bruce', 'Wayne'); curriedGreet('Hello', 'Bruce')()()('Wayne'); Notice you can choose to give multiple arguments in a single shot. This implementation's more useful while writing code. And as demonstrated above, you can invoke this function forever without parameters and it’ll always return a function that expects the remaining parameters. How's This Possible? Mr. Elliot shared a curry implementation much like Ramda's. Here’s the code, or as he aptly called it, a magic spell: const curry = (f, arr = []) => (...args) => ((a) => (a.length === f.length ? f(...a) : curry(f, a)))([...arr, ...args]); Umm… 😐 Yeah, I know... It's incredibly concise, so let's refactor and appreciate it together. This Version Works the Same I've also sprinkled debugger statements to examine it in Chrome Developer Tools. curry = (originalFunction, initialParams = []) => { debugger; return (...nextParams) => { debugger; const curriedFunction = (params) => { debugger; if (params.length === originalFunction.length) { return originalFunction(...params); } return curry(originalFunction, params); }; return curriedFunction([...initialParams, ...nextParams]); }; }; Open your Developer Tools and follow along! Let's Do This! Paste greet and curry into your console. Then enter curriedGreet = curry(greet) and begin the madness.'). Pause on line 4 Before moving on, type originalFunction and initialParams in your console. Notice we can still access those 2 parameters even though we’re in a completely new function? That’s because functions returned from parent functions enjoy their parent’s scope. Real-life inheritance After a parent function passes on, they leave their parameters for their kids to use. Kind of like inheritance in the real life sense. curry was initially given originalFunction and initialParams and then returned a “child” function. Those 2 variables weren’t disposed of yet because maybe that child needs. Line 6 now, iTakeOneParam = (a) => {}; iTakeTwoParams = (a, b) => {}; iTakeOneParam.length; // 1 iTakeTwoParams.length; //. Back at line! For more content like this, check out yazeedb.com!
https://dev.to/yazeedb/deeply-understand-currying-in-7-minutes-1ago
CC-MAIN-2019-43
refinedweb
474
50.73
Python has many powerful features that provide great flexibility when dealing with classes. Here, I'll show you five advanced techniques that can help you write better code. 1. Create a constant value Suppose we are creating a class Circle. We may need a method to calculate the area and a method to calculate the perimeter: class Circle(): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius def perimeter(self): return 2 * 3.14 * self.radius This implementation seems feasible, but what if we want to change the value of pi to be more precise? We need to change it in two places. A better idea is to save the value of PI in a variable: class Circle(): def __init__(self, radius): self.radius = radius self.pi = 3.14 def area(self): return self.pi * self.radius * self.radius def perimeter(self): return 2 * self.pi * self.radius However, now anyone can change the value of pi. This is not a good idea. What if the user writes the following: c = Circle(4) c.pi = 5 This will destroy all our functions! Obviously, we must do something about it. Unfortunately, Python does not allow the creation of constant variables. What we can do is use a function that returns a pi with the tag @ property. In this way, functions can be called like variables without parentheses. class Circle(): def __init__(self, radius): self.radius = radius @property def pi(self): return 3.14 def area(self): return self.pi * self.radius * self.radius def perimeter(self): return 2 * self.pi * self.radius Now the value of pi cannot be changed by the user, it can only be stored in the attribute pi. 2. Multiple class constructors In Python, the constructor of a class is__ init__ Method defined. Unfortunately, function overloading is not allowed, so we can only define a function with the same function. However, there is a way to use a method similar to a class constructor. This can be done using the tag @ classmethod. For example, suppose we are creating a class Date. The first constructor is: class Date(): def __init__(self, day, month, year): self.day = day self.month = month self.year = year Now we may want to add another constructor to get the Date from the string in the format dd/mm/yyyy. We can create a class method in the Date class: @classmethod def fromString(cls, s): day = int(s[:2]) month = int(s[3:5]) year = int(s[6:]) return cls(day, month, year) # Returns a new object Now we can create a new Date object by calling the fromString method: d = Date.fromString("21/07/2020") print(d.day, d.month, d.year) Output: 21 7 2020 3. Create enumeration Suppose you have a variable in your program that represents the day of the week. You might express it as an integer, for example, Monday is 1, Tuesday is 2, and so on. However, this is not the best, because you must remember whether to start from zero or 1. In addition, when you print the value, it will only be an integer, so you need a function to convert it to the correct name. Fortunately, we can use the enum class in the enum library. When you create a subclass of enum, it contains a set of variables, each with its own value, which you can use in your program. For example: from enum import Enum class WeekDay(Enum): Monday = 1 Tuesday = 2 Wednesday = 3 Thursday = 4 Friday = 5 Saturday = 6 Sunday = 7 Now set the variable to the value "Friday", you can write: day = WeekDay.Friday You can also get the integer value represented by "Friday": intDay = day.value # This value is 5 4. Iterator Iterators are classes that allow you to iterate over all elements in a data structure. An example of an iterator is the range function: you can iterate over all integer values in a range (for example, using a for loop). If you want to create your own iterator, you just need to implement it__ next__ And__ iter__ method. - __ iter__ The iterator object should be returned (so it returns self in most cases) - __ next__ The next element of the data structure should be returned Suppose we are creating an iterator to loop through a list from back to front. The correct approach is: class Backward(): def __init__(self, data): self.data = data # We're going to iterate over a list type of data self.index = len(self.data) def __iter__(self): return self def __next__(self): if(self.index == 0): raise StopIteration else: self.index -= 1 return self.data[self.index] As you can see, if there are no more elements to iterate__ next__ The function will raise a StopIteration error. Otherwise, it returns the next element to view. Now we can use the Backward object in the for loop: bw = Backward([1,2,3,4,5]) for elem in bw: print(elem) The output is as follows: 5 4 3 2 1 5. Access a class as a list When we use lists, we can use square brackets to access specific values. We can also use__ getitem__ And__ setitem__ To implement similar functions for our own classes. These are the methods when we use square brackets for list calls: - x = l[idx] and x = L__ getitem__ (IDX) has the same function. - l[idx] = x and L__ setitem__ (IDX, x) has the same function. So if we implement these two methods in a custom class, we can use square brackets like a list. This is a very simple example (it is a list whose size cannot be changed and whose index starts from 1): class MyList(): def __init__(self, dimension): self.l = [0 for i in range(dimension)] def __getitem__(self, idx): return self.l[idx-1] def __setitem__(self, idx, data): self.l[idx-1] = data ml = MyList(5) ml[1] = 50 # Set the first element to 50 ml[2] = 100 # Set the first element to 100 x = ml[1] # The value of x is now 50 Translated from:
https://programmer.group/5-tips-you-don-t-know-about-python-classes.html
CC-MAIN-2022-40
refinedweb
1,022
65.73
copysign, copysignf, copysignl - copy sign of a number #include <math.h> double copysign(double x, double y); float copysignf(float x, float y); long double copysignl(long double x, long double y); Link with -lm. Feature Test Macro Requirements for glibc (see feature_test_macros(7)): These functions return a value whose absolute value matches that of x, but whose sign bit matches that of y. For example, copysign(42.0, -1.0) and copysign(-42.0, -1.0) both return -42.0. On success, these functions return a value whose magnitude is taken from x and whose sign is taken from y. If x is a NaN, a NaN with the sign bit of y is returned. No errors occur.. This page is part of release 4.15 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manual.cs50.io/3/copysignl
CC-MAIN-2021-04
refinedweb
153
76.62
jkn wrote: > Hi Peter > > On Feb 9, 7:33 pm, Peter Otten <__pete... at web.de> wrote: >> jkn wrote: >> > is it possible to have multiple namespaces within a single python >> > module? >> >> Unless you are abusing classes I don't think so. >> >> > I have a small app which is in three or four .py files. For various >> > reasons I would like to (perhaps optionally) combine these into one >> > file. >> >> Rename your main script into __main__.py, put it into a zip file together >> with the other modules and run that. > > Hmm ... thanks for mentioning this feature, I didn't know of it > before. Sounds great, except that I gather it needs Python >2.5? I'm > stuck with v2.4 at the moment unfortunately... You can import and run explicitly, $ PYTHONPATH mylib.zip python -c'import mainmod; mainmod.main()' assuming you have a module mainmod.py containing a function main() in mylib.zip.
https://mail.python.org/pipermail/python-list/2012-February/619656.html
CC-MAIN-2020-24
refinedweb
152
78.96
Interfaces, similar to abstract classes, contain a collection of abstract methods. With abstract classes, you are able to create incomplete classes and rely on subclasses to implement the rest. Essentially, abstract classes are just normal classes with at least one abstract method. Interfaces are similar to abstract classes, but the difference is that interfaces have only unimplemented methods and nothing else, whereas abstract classes have a mix of implemented and abstract methods. Interfaces help guarantee that all subclasses have at the bare minimum the methods specified in the interface. Declaring variables as an interface type also helps your code stay flexible by allowing you to easily change the subclasses the variables are instantiated with. Interfaces are very useful for very abstract ideas, and although you might not have seen them yet, they are very commonly used in programming. For example, let’s say you want to create an Animal class. However, just having an Animal object probably wouldn’t be sufficient. What kind of animal is it? Does it live on land or sea? Does it walk or fly? Because you can’t answer any of these questions with an Animal class alone, you should make Animal an interface with a few methods that all animals should be able to perform, but without the method implementations (as these depend on the type of animal). With interfaces, creating unimplemented methods is similar to how you would do it in an abstract method, except you simply leave out the access level modifiers and don’t include abstract: public interface Animal { void makeNoise(); void eat(); ... } Like with abstract classes, the following call will not compile because you cannot directly instantiate an Animal object: Animal a = new Animal(); Now you can have more specific classes, like Dog and Fish, extend this interface and each provide its own implementation details for the methods listed in the interface. However, with interfaces, you don’t extend them, you implement them: public class Dog implements Animal { /* field variables */ public Dog() { /* implementation details */ } public void makeNoise() { System.out.println("Bark"); } public void eat() { System.out.println("Dog eats bone"); } /* optional other methods */ } Since interfaces are such abstract ideas, they often include a very large hierarchy of classes, abstract classes, and even other interfaces extending and implementing each other, getting more and more concrete as you go further down the hierarchy. For example, you could easily change the Dog and Fish classes to be abstract, and then have other classes like Husky, Poodle and Goldfish extend from them. And, taking it even further, you could introduce two new interfaces, LandAnimal and SeaAnimal, that lie in between the Animal interface and the Dog and Fish abstract classes. As you can see, there are endless possibilities when it comes to interfaces. The added benefit of having this kind of hierarchy is that you can choose the amount of flexibility you have. For example, take a look at the following two variables: Animal a = new Poodle(); Dog d = new Poodle(); Both variables now hold a Poodle object. However, the first variable a is classified as an animal whereas the second d is classified as a dog. Both are valid code examples, although each offers its own benefits. One benefit of the first one is that variable a is more generally classified and therefore gives you a greater variety of animals to choose from, like a husky and even a goldfish, whereas since d is defined more specifically as a Dog, you can only change it to be a husky or another type of Dog. However, since a can be any type of animal, this also means there are more restrictions to what methods are available to it. Variable d can call all the methods listed in the Animal interface as well as any new methods provided in the Dog class (such as performTrick or chaseMailman) because it’s guaranteed to hold a dog. However, only methods included in the Animal interface (as well as the default methods included in the Object class, like toString) can be used by the variable a because it can be any type of animal, and animals like goldfish would not be able to perform a method in the Dog class, such as chasing a mailman. To get even more methods, such as the methods defined specifically in the Poodle class, you could create a variable like this: Poodle p = new Poodle(). However, in some cases, it is better practice to define p as a Dog rather than a Poodle to give yourself a bit more flexibility in the future. If you needed to use a method defined in the Poodle class that isn’t defined in the Dog class, you could cast your Dog p into a Poodle each time you want to use one of those methods (if you don’t remember casting, it will be revisited in the next lesson about polymorphism). Of course, if you find yourself requiring a lot of the methods in the Poodle class, it is most likely better to define your variable as Poodle p = new Poodle(). In an upcoming lesson, you will be taking your first look at the Collection interface hierarchy, which defines several classes and interfaces that act as data structures. More specifically, you will be working with Lists and ArrayLists: Source: Neemeekaa Consulting Notice how in this hierarchy some classes can implement multiple interfaces (e.g. public class LinkedList implements List, Queue, Deque). Also important to pay attention to are the different types of arrows. The filled arrows represent the extends keyword whereas the empty arrows represent the implements keyword. For example, you can see that ArrayList implements List, an interface, and LinkedHashSet extends HashSet, a class. If you pay close attention, you’ll also notice that the interfaces here extend the other interfaces rather than implementing them. This is a small detail but important to know if you ever go on to write your own hierarchy of classes and interfaces. Lesson Quiz 1. Assume that A is an interface, B is an abstract class, and C is a class. Which of the following headers would result in an error? I. public class C extends B II. public class B implements A III. public class C extends A 2. Order classes, abstract classes, and interfaces in order from most concrete to most abstract. Written by Alan Bi Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.
https://teamscode.com/learn/ap-computer-science/interfaces/
CC-MAIN-2019-04
refinedweb
1,076
58.42
I have access to numpy and scipy and want to create a simple FFT of a dataset. I have two lists one that is y values and the other is timestamps for those y values. What is the simplest way to feed these lists into a scipy or numpy method and plot the resulting FFT? I have looked up examples, but they all rely on creating a set of fake data with some certain number of data points, and frequency, etc. and doesn't really show how to do it with just a set of data and the corresponding timestamps. I have tried the following example: from scipy.fftpack import fft # Number of samplepoints N = 600 # sample spacing T = 1.0 / 800.0 x = np.linspace(0.0, N*T, N) y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80])) plt.grid() plt.show() ## Perform FFT WITH SCIPY signalFFT = fft(yInterp) ## Get Power Spectral Density signalPSD = np.abs(signalFFT) ** 2 ## Get frequencies corresponding to signal PSD fftFreq = fftfreq(len(signalPSD), spacing) ## Get positive half of frequencies i = fftfreq>0 ## plt.figurefigsize=(8,4)); plt.plot(fftFreq[i], 10*np.log10(signalPSD[i])); #plt.xlim(0, 100); plt.xlabel('Frequency Hz'); plt.ylabel('PSD (dB)') xInterp[1]-xInterp[0] So I run a functionally equivalent form of your code in an IPython notebook: () I get what I believe to be very reasonable output. It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue? The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate. import pandas import matplotlib.pyplot as plt #import seaborn %matplotlib inline # the OP's data x = pandas.read_csv('', skiprows=2, header=None).values y = pandas.read_csv('', skiprows=2, header=None).values fig, ax = plt.subplots() ax.plot(x, y)
https://codedump.io/share/TFKSfBFhpawM/1/plotting-a-fast-fourier-transform-in-python
CC-MAIN-2017-17
refinedweb
343
68.06
On 3 May 2010 16:40, Dave Wright <wrightd@gmail.com> wrote: > > Should this be a znode in the privileged namespace? > > > > I think having a znode for the current cluster members is part of the > ZOOKEEPER-107 proposal, with the idea being that you could get/set the > membership just by writing to that node. On the client side, you could > watch that znode and update your server list when it changes. > This is tricky: what happens if the server your client is connected to is decommissioned by a view change, and you are unable to locate another server to connect to because other view changes committed while you are reconnecting have removed all the servers you knew about. We'd need to make sure that watches on this znode were fired before a view change, but it's hard to know how to avoid having to wait for a session timeout before a client that might just be migrating servers reappears in order to make sure it sees the veiw change. Even then, the problem of 'locating' the cluster still exists in the case that there are no clients connected to tell anyone about it. Henry -- Henry Robinson Software Engineer Cloudera 415-994-6679
http://mail-archives.apache.org/mod_mbox/hadoop-zookeeper-user/201005.mbox/%3Cz2yb54edc3a1005031649na1659d8avde450fda4afd8c25@mail.gmail.com%3E
CC-MAIN-2017-47
refinedweb
205
63.53
A simple guide to understanding object-oriented ruby relationships (finally!) As a beginner, I have had the hardest time wrapping my head around the concept of object-oriented relationships in code. After weeks (or try months) of reading explainers and watching tutorial videos, I’m beginning to see the light. Here, I’ll distill examples of belongs to, has many, and has many through relationships down to bare bones, which has helped me build comprehension. And hopefully, it’s useful to you too. Let me know? Belongs to relationship The belongs to relationship means that ONE object (a song, a book, a dog, etc.) has an owner (an artist, an author, a shelter, etc). We’re able to show that in code by creating an attr_accessor for the owner. class Dog attr_accessor :shelter end class Shelter end The above code allows us to create a new dog and assign ownership of the dog to a shelter. Step 1: Create new dog and assign it equal to Bandit variable. Step 2: Create new shelter Step 3: Assign bandit’s shelter attribute to your instance of Shelter that you just created Voila, Bandit is now a instance of the Dog class with a shelter attribute. bandit = Dog.new nycshelter = Shelter.new bandit.shelter = nycshelter #assigning the dogbandit.shelter bandit => #<Dog:0x000055b18e671ca0 @shelter=#<Shelter:0x000055b18e671c78>> But there’s trouble in paradise. At this point, the instance of Shelter does not recognize or see the dog it owns. Here’s how we know that: nycshelter.dogs => undefined method `dogs’ for #<Shelter:0x00005557b6fca1f8> (repl):15:in `<main>’ When we ask nycshelter, an instance of Shelter, what dogs it has many of, it has no clue. Looking at the error, we have a clue, which points to what we need to do next. We need to define a method for dogs for the shelter. But every instance of shelter in general should probably know what dogs it has many of. Has Many Relationships Here’s the flip side of the belongs to relationship. A shelter has many dogs or you could say the shelter has a collection of dogs. To establish a has many relationship, our owner instance needs an empty array to store its collection of items (in this case, dogs), where every instance of the dog that’s instantiated can be added. class Shelter attr_accessor :dogs, :name def initialize(name) @name = name @dogs = [] end end Here, we’re just setting up a new shelter named brooklynshelter: brooklynshelter = Shelter.new(brooklynshelter) => #<Shelter:0x000055a164d8b1d8 @name=nil, @dogs=[]> We’re going to reset our dog (belongs to) and shelter (has many) relationship. brooklynshelter = Shelter.new(brooklynshelter) snacks = Dog.new snacks.shelter = brooklynshelter snacks => #<Dog:0x00005614828bf708 @shelter=#<Shelter:0x00005614828bf758 @name=nil, @dogs=[]>> So, we can that snacks now belongs to brooklynshelter, an instance of Shelter, which has a collection (empty array) of dogs. brooklynshelter.dogs => [] When we ask brooklynshelters for its dogs attribute, it’s still showing up as being empty. Because there’s another essential step we’re forgetting: ADDING THE INSTANTIATED DOG INTO THE EMPTY ARRAY. We’re going to do that with an #add_dog method brooklynshelter = Shelter.new(brooklynshelter) snacks = Dog.new snacks.shelter = brooklynshelterbrooklynshelter.add_to_shelter(snacks) brooklynshelter => #<Shelter:0x0000563fc0797240 @name=nil, @dogs=[#<Dog:0x0000563fc07971f0 @shelter=#<Shelter:0x0000563fc0797240 …>>]> Now, the flip side of the relationship — the has many relationship — is complete. The instance of Shelter — brooklynshelter — knows it has a dog instance whose shelter attribute is equal to the shelter. Has Many Through Relationship One way I get my brain to comprehend complicated Ruby concepts is by breaking them down into simple rules or its smallest components. I’m going to try that, here, with the has many relationship. The has many through relationship describes the connection between 3 classes, wherein 1 of 3 classes provides an indirect link (or relationship) between the other 2. - One item will be the middle man and provides an indirect relationship between or through two objects - The shared item will belong to the other two items - The other two items will have many of the shared item For example: →shelter → dogs→ owner In this relationship: * shelter has many dogs * dog belongs to shelter and owner * owners has many dogs * through dogs, shelter has many owners and owners has many shelters class Shelter #has many dogs attr_accessor :name, :city @@all = []def initialize (name, city) @name = name @city = city @dogs = [] @@all << self enddef add_dog(dog) #always should have an argument so we can pass in an instance of dog dog.shelter = self @dogs << dog enddef dogs @dogs enddef self.all @all end end class Dog #belong to a shelter & an owner attr_accessor :name, :age, :breed, :shelter, :owner @@all = []def initialize (name, age, breed) @name = name @age = age @breed = breed @@all << self enddef self.all @all end end class Owner #has many dogs attr_accessor :name, :age, :dogs @@all = []def initialize (name, age) @name = name @age = age @dogs = [] @shelters = [] @@all << self enddef add_dog(dog) @dogs << dog dog.owner = self enddef shelters self.dogs.each do |dog| @shelters << dog.shelter if dog.shelter end @shelters end def self.all @@all end end With all this, we can invoke: ruffles = Dog.new(“ruffles”, 1, “corgi”) queensshelter = Shelter.new(“Queens Humane Society”, “NYC”) ruffles.shelter = queensshelter ruffles.shelter queensshelter.add_dog(ruffles)joe = Owner.new(“joe”, 30) joe.add_dog(ruffles)joe.shelters joe.shelters.each {|shelter| puts shelter.name} => Queens Humane Society => [#=[…]>>]>]
https://joannpan.medium.com/a-simple-guide-to-understanding-object-oriented-ruby-relationships-finally-92cb2fb3b4d
CC-MAIN-2022-40
refinedweb
895
55.64
MASM32 Downloads yes - they do have their placei tried other languages in days of oldbut always came back to assembler because of some limitation from the compiler if i were writing apps on a professional basis, i would probably use C with some asm-created OBJ's No high level language owns assembler I only made a point of the fact that the hll section in MASM is based on C. Since the feedback here seems to revolve around other unrelated issues, and the purpose of the fix only serves selfish interest, I will not pursue this any further. So obviously MASM is based on GfaBasic. Quote from: jj2007 on November 15, 2012, 05:24:32 PMSo obviously MASM is based on GfaBasic.I think Microsoft started on MASM around 1980, so they must have had an early pre-alpha version that they pirated Also, be a bit careful with statements about C. I well remember Agner Fog a few years ago who started a discussion about JWasm and assembly language "standards". He happened to make a innocent remark, kinda "C is probably sometimes better than assembly", and was then scared away by one of the super-intelligent super-moderators. This event made me realize that this forum is the WRONG place for ... "certain things". There is a vast number of our members who can read and write competent C code with many years of experience but they write assembler code where they need it without needing to try and shift the status of one language over another. .WHILE TRUE invoke GetMessage, ADDR msg, 0,0,0 .BREAK .IF (!eax) invoke TranslateAccelerator, hwnd, hAccel, ADDR msg .IF !eax invoke TranslateMessage, ADDR msg invoke DispatchMessage, ADDR msg .ENDIF .ENDW… .while GetMessage(ADDR msg, 0,0,0) .if !TranslateAccelerator(hwnd, hAccel, ADDR msg) invoke TranslateMessage, ADDR msg invoke DispatchMessage, ADDR msg .endif .endw if i had to write code on a day-to-day basis, i would probably want to use C with some routines in assemblerit's a matter of productivity and maintainabilitythis hypothetical company i work for can hire C programmers a lot easier than it can hire assembly programmers #include <io.h>#include <dir.h>#include <stdio.h>#include <stdlib.h>#include <string. h>..int IOGetFileType(char *fname){ char *p; p = strrchr(fname, '.'); if (p == NULL) return NO_SOURCE; if (!stricmp(p, ".c")) return SOURCE_C; if (!stricmp(rsi, ".asm")) return SOURCE_ASM; if (!stricmp(rsi, ".idd")) return SOURCE_IDD; if (!stricmp(rsi, ".obj")) return SOURCE_OBJ; return –1;}…include io.incinclude dir.incinclude stdio.incinclude stdlib.incinclude string.inc..IOGetFileType proc uses rsi fname:ptr byte invoke strrchr,fname, '.' mov rsi,eax .if !rax mov rax,NO_SOURCE .elseif !stricmp(rsi, ".c") mov rax,SOURCE_C .elseif !stricmp(rsi, ".asm") mov rax,SOURCE_ASM .elseif !stricmp(rsi, ".idd") mov rax,SOURCE_IDD .elseif !stricmp(rsi, ".obj") mov rax,SOURCE_OBJ .else mov rax,-1 .endif retIOGetFileType endp
http://masm32.com/board/index.php?topic=902.30
CC-MAIN-2019-13
refinedweb
479
56.55
namespace (namespaces can require multiple namespaces to complete their creation). That got me thinking about how you discover the mof file associated with a class. Which leads to $ns = "root\cimv2" $class = "Win32_Logicaldisk" $p = Get-WmiObject -Namespace $ns -Class $class | select -f 1 | select -ExpandProperty qualifiers | where {$_.Name -eq 'provider'} $class $p Get-ChildItem -Path C:\Windows\System32\wbem -Filter "*$($p.Value)*" Get the first instance of a class, expand the qualifiers and select the qualifier with a name of provider. Then perform a dir on the wbem folder to find the appropriate files. This isn’t infallible due to files names not necessarily being consistent but its a good starting point for the standard classes  Comment on this Post
https://itknowledgeexchange.techtarget.com/powershell/wmi-provider-and-mof-file/
CC-MAIN-2019-35
refinedweb
121
63.7
Creating and Consuming .NET Web Services in 5 Easy StepsBy Dimitrios Markatos Aside from your typical data namespace import, you also add the Web Services namespace: using System.Web.Services In VB this would be: Imports System.Web.Services Here I've added the [WebService(Description="My Suppliers List Web Service")], which gives a custom description. Next we create our class, which, in order that it be exposed, and able to inherit the Webservicebase class, must be a public class. public class GetInfo : WebService { Now we mark the method that’s to be exposed via the WebMethod attribute. Every class that’s enclosed within a WebMethod will be exposed as a service. Also, I boost performance by setting the BufferResponse to true. [WebMethod (BufferResponse=true)] If you prefer to have the description right below the exposed WebMethod link, you can achieve it like this in C#: [WebMethod (Description="My Suppliers List Web Service",BufferResponse=true)] The VB version would incorporate the description and BufferResponse in one statement, namely WebMethod, that used angle brackets. This is placed after the class creation and Web service inheriting line, and on the same line with, but before the function, like so: <WebMethod(Description:="My Suppliers List Web Service",BufferResponse:=True)> Public Function ShowSuppliers (ByVal str As String) As DataSet Next, we set up our method or VB function, which the basics: public DataSet ShowSuppliers (string str) Here, we set up our dataset method to return us exactly that. Lastly, we perform typical data connection and access and return our results, and we’re done! So far so good? After viewing this in your browser, the above code should to start to make sense. Let’s go to Step 2. Step 2 – Consume the Web Service Source File Next, append ?WSDL to the Web services URI (Uniform Resource Identifier) like so: “What’s this?” you ask. This is the WSDL document that the client will use to access this service. Even so, you don’t have to know much about this unreadable code to produce results, which is where the WSDL.exe command-line tool comes into play. Due to the open protocol nature of Web services, this tool enables you to consume non-.NET Web Services as well. You can bypass WSDL and test the XML results instantly through HTTP GET protocol, by typing the following into your browser: This passes USA as a parameter to the ShowSuppliers class method. Note that gobbledyg that /l is the language you’re using. /n:creates the Wservicenamespace so you can reference it from your .aspx page, and finally send the C#/VB source file to the bin folder from which we'll create the dll assembly that we'll use in Step 3. Also add pause, so after this is all said and done, you'll be prompted to press any key to continue, and more importantly, you'll know for sure that it all went according to plan. Now locate your new batch file, and double-click on it to run it. Once you've done this, you will have created, rather consumed, the proxy class or source file GetSuppliers.cs right from the .asmx file. Have a look in your bin folder. Note that you could run these commands via the command-line prompt, but for the sake of convenience, I prefer the good old' batch file. You may be wondering where the phrase "consuming" came from? In this regard, it simply refers to the presentation of the Web Service to the "consumer". No Reader comments
https://www.sitepoint.com/net-web-services-5-steps-2/
CC-MAIN-2016-44
refinedweb
592
63.29
is available, but is not registered by default. I shall not cover this aspect as its already explained in detail in the spring documentation. In this post I shall cover one more aspect of spring bean scope i.e Custom Scopes. 1. Custom Scope in Spring As per the Spring doc As of Spring 2.0, the bean scoping mechanism is extensible. You can define your own scopes, or even redefine existing scopes, although the latter is considered bad practice and you cannot override the built-in singleton and prototype scopes. A custom scope typically corresponds to a backing store that can manage object instances. In this case, Spring provides its familiar programming model, enabling injection and look-up, and the backing store provides instance management of the scoped objects. Typical backing stores are:HTTP session, Clustered cache, Other persistent store The need to create a Custom Scope actually depends on the problem at hand. For instance, you might want to create a pre-defined number of instances of a particular bean, but not more than that. So until this number is met, you keep creating new instances, but once the number is met, you return existing instances in a balanced manner. This is just one context or instance when we can use Custom Scopes. As said, the usage depends on the problem at hand. Now let’s see how to integrate the custom scopes in spring framework with an example. In the following example I’ve created a MyScope as Custom Scope. The idea behind the Scope MyScope is to keep the short lived objects. Here, the beans will be alive until an explicit call is made to clear of all the bean instances. Follow the steps below: 2. Create Project in Eclipse Let us have working Eclipse IDE in place.Create a simple Java Project using Eclipse IDE. Follow the option File -> New -> Project and finally select Java Project wizard from the wizard list. Now name your project as SpringCustomBeanScope using the wizard window. 3. Add external libraries and dependencies Next let’s add the Spring Framework and common logging API libraries in our project. Right click on your project name SpringCustomBeanScope and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window. Now use Add External JARs button available under Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories: - 4. Implement Custom Scope bean To integrate your custom scope(s) into the Spring container, you need to implement the org.springframework.beans.factory.config.Scope interface. Create the custom scope com.javabeat.MyScope under directory src/com/javabeat which implements Scope interface. The contents of the file are as below: package com.javabeat; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; public class MyScope implements Scope { private Map<String, Object> objectMap = Collections .synchronizedMap(new HashMap<String, Object>()); /** * (non-Javadoc) * * @see org.springframework.beans.factory.config.Scope#get(java.lang.String, * org.springframework.beans.factory.ObjectFactory) */ public Object get(String name, ObjectFactory<?> objectFactory) { if (!objectMap.containsKey(name)) { objectMap.put(name, objectFactory.getObject()); } return objectMap.get(name); } /** * (non-Javadoc) * * @see org.springframework.beans.factory.config.Scope#remove(java.lang.String) */ public Object remove(String name) { return objectMap.remove(name); } /** * (non-Javadoc) * * @see org.springframework.beans.factory.config.Scope#registerDestructionCallback * (java.lang.String, java.lang.Runnable) */ public void registerDestructionCallback(String name, Runnable callback) { // do nothing } /** * (non-Javadoc) * * @see org.springframework.beans.factory.config.Scope#resolveContextualObject(java.lang.String) */ public Object resolveContextualObject(String key) { return null; } /** * (non-Javadoc) * * @see org.springframework.beans.factory.config.Scope#getConversationId() */ public String getConversationId() { return "MyScope"; } /** * clear the beans */ public void clearBean() { objectMap.clear(); } } Details of the above file: The methods defined in Scope interface which needs to be implemented by the custom scope are as follows: - Object get(String name, ObjectFactory objectFactory) - Return the bean instance from underlying scope if the bean exists, otherwise return a new bean instance and bind the instance to the underlying scope for future references. - String getConversationId() - Return the Conversation id (if any) for the underlying scope.This identifier is different for each scope. For a session scoped implementation, this identifier can be the session identifier. Note: This method is optional. - void registerDestructionCallback(String name, Runnable callback) - Register a callback to be executed on destruction of the specified object in the scope (or at destruction of the entire scope, if the scope does not destroy individual objects but rather only terminates in its entirety).Note: This method is optional. - Object remove(String name) - Removes the bean instance from the underlying scope. Note: This method is optional. - Object resolveContextualObject(String key) - Resolves the contextual object (if any) for the given key. E.g. the HttpServletRequest object for key “request”. There’s also another method called clearBean. This method should be invoked by the application (may be at regular intervals) to remove the short lived objects. 5. Create a example bean Add com.javabeat.Person bean under directory src/com/javabeat. The contents of the file are as below: package com.javabeat; public class Person { /** * Default Constructor */ public Person() { System.out.println("*** Person() constructor ***"); } } 6. Create spring configuration file and register the Custom scope bean Create bean’s configuration file Custombean.xml under the src folder. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <bean id="myScope" class="com.javabeat.MyScope"/> <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="customscope"> <ref bean="myScope" /> </entry> </map> </property> </bean> <bean name="p1" class="com.javabeat.Person" scope="customscope" /> </beans> Few things to notice here: MyScope is defined as a bean here with name customscope. Application can lookup this bean to remove the short lived beans. MyScope is registered with the Spring IoC container using CustomScopeConfigurer with scope name myScope. The key will be the name of the Custom Scope to be used in the bean definition and the value will be bean which implement the scope. Finally, the Person bean is defined with scope customscope. 7. Sample application for spring custom scope and testing Create MainApp.java Write a MainApp class under the directory src/com/javabeat. The contents of the file are as below: package com.javabeat; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String args[]) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "Custombean.xml"); // 1. Retrieve the bean 'p1' from Context System.out.println("Looking up 'p1'"); Person p1 = ctx.getBean("p1", Person.class); // 2. Retrieve the bean 'p1' from Context again System.out.println("Looking up 'p1' again"); Person p2 = ctx.getBean("p1", Person.class); // 3. The beans retrieved in step 1 and 2 should be same. System.out.println("p1 = " + p1.toString()); System.out.println("p2 = " + p2.toString()); // 4. Trigger the Clearing of bean. System.out.println("======================================================"); System.out.println("Clearing the beans..."); MyScope myScope = ctx.getBean("myScope", MyScope.class); myScope.clearBean(); System.out.println("Clear Bean Completed."); System.out.println("======================================================"); // 4. Retrieve the bean 'p1' from Context after clearing System.out.println("Looking up 'p1'"); Person p3 = ctx.getBean("p1", Person.class); // 5. Retrieve the bean 'p1' from Context again after clearing System.out.println("Looking up 'p1' again"); Person p4 = ctx.getBean("p1", Person.class); // 6. The beans retrieved in step 4 and 5 should be same. System.out.println("p3 = " + p3.toString()); System.out.println("p4 = " + p4.toString()); } } Final directory structure is as shown in the image below: Run the sample application: As a final step, let us run the application. If everything is fine with your application, the following output is printed: Looking up 'p1' *** Person() constructor *** Looking up 'p1' again p1 = [email protected] p2 = [email protected] ====================================================== Clearing the beans... Clear Bean Completed. ====================================================== Looking up 'p1' *** Person() constructor *** Looking up 'p1' again p3 = [email protected] p4 = [email protected] We can see in the output that Person constructor is called first time when we requested the bean from the context, for the next request (at step 2), the Person constructor is not invoked, instead, Spring has returned the same instance which is created earlier (at step 1). After removing/clearing bean, when we requested the bean p1 (at step 4), the Person constructor is invoked, and for the next request (at step 5), the instance which is created earlier (at step 4) is returned. 8. Summary In this post we saw how to custom create a bean scope in Spring with an example. On similar lines custom scopes can be create for beans which can be shared between servlet contexts or for beans which can be shared within a same thread and many more examples. In the next post I shall cover “customizing Spring beans callback methods”. If you are interested in receiving the future articles, please subscribe here.
http://javabeat.net/custom-scope-spring-beans/
CC-MAIN-2017-04
refinedweb
1,483
50.33
It’s ShowTime 🎥 ShowTime displays all your taps and gestures on screen, perfect for that demo, presentation or video. One file is all you need to turbo-boost your demos. ShowTime even displays the level of force you’re applying, and can be configured to show the actual number of taps performed. Apple Pencil events are configurable and disabled by default. ShowTime works with single- and multi-window setups, check out How it works. ShowTime works best when mirroring your screen or recording through QuickTime. By default the size of the visual touches are 44pt; this mirrors Apple’s guidelines for minimim hit size for buttons on iOS. You’re free to change this, of course! Showing your gestures during demos helps give your audience a much clearer context on what’s happening on your device. Consider trying ShowTime for your next demo! Installation There are two very easy ways to integrate ShowTime. Using Cocoapods? Simply add the following to your podfile: pod 'ShowTime' Update your pods with pod update, and that’s it. You don’t even have to import ShowTime into a file in your project, unless you want to change the defaults. If you’re not using Cocoapods: - Step 1: Drop ShowTime.swiftinto your project or copy the contents of it where ever you like. - Step 2: There is no step 2; you’re ready to go. NOTE If you’re using Xcode 8.3.2 or newer you may get a warning about initialize() being unavailable in future versions of Swift. When this is removed by Apple, I have a decent workaround ready to implement, but may mean an extra step in the setup process. Usage ShowTime works out of the box, but you can customise it to turn it on or off (you could use this to have a demo environment), change the colour and outline of the taps, and even choose whether to display the number of taps for multiple taps. Here’s a list of options: // Defines when and if ShowTime is enabled // // Possible values are: // - .always // - .never // - .debugOnly // // .always by default ShowTime.itsShowTime: ShowTime.Enabled // The fill (background) color of a visual touch. // Twitter blue with 50% opacity) // // `.standard` by default. ShowTime.disappearAnimation: ShowTime.Animation // The delay, in seconds, before the visual touch disappears after a touch ends. // `0 // Whether visual touches should visually show how much force is applied. // `true` by default (show off that amazing tech!). ShowTime.shouldShowForce: Bool // Whether touch events from Apple Pencil are ignored. // `true` by default. ShowTime.shouldIgnoreApplePencilEvents How it works hook into the initialize() method and do some swizzlin’.(_:). Useful info Can I use this in production? In theory, yes. You could easily set up a configuration that disables ShowTime by setting ShowTime.itsShowTime to false (check out configen for easily having different configrations based on Xcode schemes), however ShowTime is new and hasn’t been stress tested, so do so at your own risk. What I would suggest doing instead, is having a demo branch that you have ShowTime installed in, and merge your changes into that branch whenever you want to demo something. Because there is so little setup to ShowTime, you should rarely get any conflicts. Is there really only one step to installing ShowTime? Yes! Thanks to method Swizzling and Swift extensions all you have to do is include the code somewhere in your project. ShowTime works out of the box, but is quite customizable. Why would I want to show the number of multiple taps? The thing to remember here is that people watching a demo of your app don’t know exactly what your fingers are doing, which is why ShowTime exists.. Can I have a different colour tap per-screen rather than per-app? This is possible, you’d just need to set the colour in viewDidLoad or viewDidAppear(_:) in the screens you want to change the colour of the taps on. It adds a small layer of complexity, but certainly possible. Latest podspec { "name": "ShowTime", "version": "1.0.1", "summary": "The easiest way to show off your iOS taps and gestures for demos.", "description": "ShowTime displays all your taps and gestures on screen, perfect for that demo, presentation or video.nOne file is all you need to turbo-boost your demos. ShowTime even displays the level of force you're applying, and can be configured to show the actual number of taps performed. Apple Pencil events are configurable and disabled by default.nShowTime works with single- and multi-window setups.nShowTime works best when mirroring your screen or recording through QuickTime. By default the size of the visual touches are 44pt; this mirrors Apple's guidelines for minimim hit size for buttons on iOS. You're free to change this, of course!nShowing your gestures during demos helps give your audience a much clearer context on what's happening on your device. Consider trying ShowTime for your next demo!", "homepage": "", "license": { "type": "MIT", "file": "LICENSE.md" }, "authors": { "kanecheshire": "[email protected]" }, "source": { "git": "", "tag": "1.0.1" }, "social_media_url": "", "platforms": { "ios": "8.0" }, "source_files": [ "ShowTime/Classes/**/*", "ShowTime.swift" ], "pushed_with_swift_version": "3.0" } Fri, 28 Apr 2017 15:00:07 +0000
https://tryexcept.com/articles/cocoapod/showtime
CC-MAIN-2017-22
refinedweb
862
66.84
GYP is Chromium's own build system generator: We use source code from a few Google projects that use GYP as their build-system: at least ANGLE and (afaik) Breakpad. We are currently manually porting these to our own Makefiles, which is tedious and potentially has to be partly redone whenever we sync with upstream. Also, for part of ANGLE, we are currently using GYP-generated VS project files on Windows, which is causing some trouble: bug 641630, bug 633348. Having a GYP generator generating Mozilla Makefiles should be very useful for these reasons. Now WebRTC as well (with hundreds of .gyp files...) Breakpad's gyp files only cover the Windows client, so it wouldn't be totally useful there. For WebRTC, I'm first trying to see if we can just make the gyp-generated Makefiles work on Windows. If that turns out to not be feasible then this is probably the tack I'll take. Relevant to gps's work on making our build system suck less. I don't think it's particularly relevant, TBH. The likelihood of us using GYP for Mozilla at large is virtually nil. Created attachment 583770 [details] [diff] [review] implement Makefile.in backend for GYP This still isn't finished, but it's getting closer. It's an awful awful mess, so I apologize if anyone actually reads this patch. The basic concept here is to: a) Generate one Makefile per gyp target (because our build system only supports one target per-Makefile.in), putting them fairly close to the gyp file they were generated from. I generate a subdir per-target, named "gypfile_targetname". b) Generate a common.mk that gets included by every Makefile.in, because GYP files set things like DEFINES and INCLUDES per-target-type (Release vs. Debug), so that has to be chosen at build-time, so this just encapsulates that logic. c) Generate a top-level Makefile.in that simply uses DIRS to build all the other targets. This doesn't produce a working WebRTC build yet, but it does compile some things. I have a few more things to fix, the known ones include: * Adding extra libs to the link line * Checking that build order of targets is correct wrt dependencies * Proper paths to source files (I think object files are winding up in the srcdir right now) * Handling some other GYP bits, like actions/rules/copies * Mac support (ObjC, might need to pull settings from the XCodeSettings) * Test building on Windows Sample output (for webrtc.gyp) can be seen in attachment 583771 [details] [diff] [review] on bug 688187. Looking good! Would it make sense to put this code under build/ instead of /media/webrtc/? IMO the files constituting the build system are fragmented enough as it is. I'd like to see consolidation of all the code logic (especially the Python bits) in a common directory so we can treat them as a Python package and not have so much PYTHONPATH hackiness. ensure_directory_exists(path) is not thread safe. You probably want the same construct used in bug 629668: try: os.makedirs(dir) except OSError, ex: if ex.errno != errno.EEXIST: raise ex # else directory already exists. silently ignore and continue Unless of course there is no way this can be called from multiple threads. Also, you use underscore for that method but CamelCase elsewhere. Underscore is the standard Python naming convention. But it looks like GYP uses CamelCase. Hmmm. Same goes for getdepth(). Be consistent. Can you convert the Makefile-producing methods into generators? This loosely couples the act of generating the Makefiles from the GYP-specific side-effect of writing out a file. Personally, I would like this because my alternate build system could consume the Makefile as a "stream" and pipe it directly into my parsing logic without involving any filesystem overhead. It also makes it easier to test the API since, again, you don't involve the filesystem. If the GYP->Makefile generation happens at check-in time, not after checkout, then I don't care as much. On a higher-level, GYP has access to the global state of everything, no? If so, it would be awesome if you could produce a single Makefile from all the GYP files in one go. Of course, this would require adding adding support to rules.mk or circumventing the rules.mk logic. Those are probably beyond scope, but I'm throwing it out there just in case. Either way, my magical build system could consume your generated Makefiles since they conform to the existing convention, so the end result would be the same (if I can deliver). Created attachment 583919 [details] [diff] [review] implement Makefile.in backend for GYP I fixed a couple of the things off that list: * Extra libs now make it to the link line (although it's still failing to link the first test program it gets to, need to figure that out) * Paths to source files have been sorted out * I punted on actions/rules/copies, they don't seem to be used in webrtc except for building the protobuf compiler, which I hear is optional If you'd like to try this out, the patch in bug 688187 was generated with the following command after applying this patch: luser@cuatro:~/build/alder/media/webrtc/trunk$ ./build/gyp_chromium --debug=all --format=mozmake --depth=. -D build_with_mozilla=1 -G relative_srcdir=media/webrtc/trunk webrtc.gyp Very excited to see this! If you want a big and useful GYP testcase, see (In reply to Gregory Szorc [:gps] from comment #7) > Would it make sense to put this code under build/ instead of /media/webrtc/? It very much would, since we already have at least ANGLE that also uses GYP and would benefit from this. Unfortunately, this code has to live inside of the gyp folder, since gyp loads its generators by module name. Also, apparently the trunk version of gyp can't build the WebRTC project, so I had to use the copy of gyp that was bundled with the WebRTC source. Created attachment 584795 [details] [diff] [review] implement Makefile.in backend for GYP This fixes most of the previous issues, I'm able to generate a set of Makefiles and build WebRTC on Linux. I need to test this on Mac and Windows next. Created attachment 586192 [details] [diff] [review] implement Makefile.in backend for GYP Some slight revisions here. I changed things to generate Makefiles directly, instead of Makefile.ins in the srcdir. I'll attach a patch in bug 688187 showing how I'm doing this for WebRTC. I landed an updated version of this on alder: I'll get post-facto review from someone once I get things working properly on Windows. (It's close there, but not quite yet.) Ted landed a version that works on windows as well. Yeah ted! However, it has a few issues with the Win32 build servers 1) the use of the 'with' statement, which is not in Python 2.5 by default (see attachment , which has been landed on alder to fix this) 2) with 1) fixed, you find that the json module for python isn't on the WIn32 build servers: Updating projects from gyp files... *** Fix above errors and then restart with "make -f client.mk build" make[2]: Leaving directory `/e/builds/moz2_slave/a-w32/build' make[1]: Leaving directory `/e/builds/moz2_slave/a-w32/build' Traceback (most recent call last): File "e:/builds/moz2_slave/a-w32/build/media/webrtc/trunk/build/gyp_chromium", line 171, in <module> sys.exit(gyp.main(args)) File "e:\builds\moz2_slave\a-w32\build\media\webrtc\trunk\tools\gyp\pylib\gyp\__init__.py", line 471, in main options.circular_check) File "e:\builds\moz2_slave\a-w32\build\media\webrtc\trunk\tools\gyp\pylib\gyp\__init__.py", line 72, in Load generator = __import__(generator_name, globals(), locals(), generator_name) File "e:\builds\moz2_slave\a-w32\build\media\webrtc\trunk\tools\gyp\pylib\gyp\generator\mozmake.py", line 7, in <module> import json ImportError: No module named json configure: error: failed to generate WebRTC Makefiles For json, we can either update python to 2.6 or later on Linux and Windows build servers, or we can remove the dependency on the json module from mozmake.py, or we could install simplejson on the build servers and alternatively import that: try: import json except ImportError: import simplejson as json . (In reply to Ben Hearsum [:bhearsum] from comment #18) > . That's exactly what the patch I've applied to alder does. :-) > > The Linux build servers are also Python 2.5 (without json). As indicated in comment 17, I'm good with either updating python (yeah!) or installing simplejson (if it isn't there; I haven't checked yet) and using the snippet above. Mac seems ok. just to note, turns out json was included but not needed; so i removed the json include from alder I was looking at alder, and it appears when I touch certain headers, the correct stuff isn't rebuild (in this case sink_filter_windows.h). When I touch the source file (sink_filter_windows.cc) stuff rebuilds correctly. Note known bug - it doesn't rebuild Makefiles if a gyp file changes I landed a couple of follow-ups here: - Fix GNU make incompatible paths on Windows - Add rules to regenerate Makefiles when GYP files change I'm going to call this project FIXED now. These changes should get review before we land alder into mozilla-central, but this isn't blocking any WebRTC work anymore.
https://bugzilla.mozilla.org/show_bug.cgi?id=643692
CC-MAIN-2016-30
refinedweb
1,587
64.3