text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Created on 2004-01-01 16:28 by gvanrossum, last changed 2011-10-19 19:46 by eric.araujo. This issue is now closed.). So it would behoove us to standardize these. An easy way would be unit tests. Any takers? Logged In: YES user_id=1038590 Sure. I've been looking for something to do after giving up on finding any more Python-level speed increases for Decimal :) Patch forthcoming in the next few days. Logged In: YES user_id=1038590 Although, now that I look at the relevant py-dev threads, I'm not entirely sure what needs to be standardised. Consider the following: <type 'array.array'> <type 'dict'> __main__.foo <__main__.foo instance at 0xf6f8baac> <unbound method foo.x> <bound method foo.x of <__main__.foo instance at 0xf6f8bacc>> <class '__main__.bar'> <__main__.bar object at 0xf6f8baec> <unbound method bar.x> <bound method bar.x of <__main__.bar object at 0xf6f8bb0c>> <function func at 0xf6f87294> Which is the result of: from array import array class foo: def x(): pass class bar(object): def x(): pass def func(): pass for obj in array, dict, foo, foo(), foo.x, foo().x, bar, bar(), bar.x, bar().x, func: print obj If any work needs to be done on this issue, it should probably be labeled "easy." (At least the writing the unit tests part. Making <...> reprs consistent is another story.) The unit tests for old-style and new-style class reprs are present in test_repr and seem to predate the original request. There are some more similar tests elsewhere (test_file, test_descr, etc.) I'd rather not label this as easy yet, since there's a decision to be made. I would welcome a doc patch though! I think the attached patch captures the most of what can currently be said about <...> reprs. I think the biggest offender in terms of inconsistency in the 2.x series is the file object with the repr which does not even start with the name of the type. For 3.0, I think it is feasible to standardize on the <{type} object ['{name}'] ... at 0x{addr}> pattern. Applied doc patch in r61871, r61872 (3.0). Georg, did your two patches finish this issue, so it can be closed, or is there more to do? Ping? I wonder whether closing an issue from 2004 would result in "Achievement unlocked: archaeological issue management" Original report: >). <...>-style reprs have been documented by Georg; for the consistency part, I just run the snippet from Nick on 3.2: <class 'array.array'> <class 'dict'> <class '__main__.foo'> <__main__.foo object at 0x13fa810> <function x at 0x1399050> <bound method foo.x of <__main__.foo object at 0x13fa850>> <function func at 0x132cf30> I would call that consistent. (FWIW I like that the dict repr contains “dict” and not “builtins.dict”, as the common form for using it does not need the module part.) For the standardization part, Alexander proposed this: > For 3.0, I think it is feasible to standardize on the > <{type} object ['{name}'] ... at 0x{addr}> pattern. If there are tools out there that parse reprs, I think a change that would break them should have been in 3.0, now we’re bound by b/w compat. To sum up: <...>-style reprs are documented and consistent enough, so let’s close this. I think there's nothing to be done for a bug this general. If you find a specific object whose repr() is awkward, go ahead and file a specific bug. In most cases I think people who parse repr() output know they are on thin ice, and would prefer that the object whose repr() they are parsing had a method or attribute that returned what they were after. Example: in 3.2, parsing repr(range(...)) is the only way to access the start/stop/step attributes; but we're fixing this for 3.3. Exception: unittests that specifically verify the form of a repr(). Off-topic:__.) One could even claim that the repr() of a class could be the same, since one of the guiding principles for repr() is that it should, if possible, return an expression that (perhaps given a suitable environment) could reconstruct the value exactly (and otherwise it should have the <...> form discussed in this issue). But both of these wishes are debatable, and if anyone cares, they should open a new bug to discuss it. >__.) Me too. I have a small metaclass to do that :) Given your tentative support, I’ll open a feature request for 3.3. > One could even claim that the repr() of a class could be the same I think of repr first as “string form for debugging”, so I like the angle brackets. I opened #13224 with a patch to change str(class).
http://bugs.python.org/issue868845
crawl-003
refinedweb
797
84.68
Comment on Tutorial - How to Send SMS using Java Program (full code sample included) By Emiley J. Comment Added by : shikha Comment Added at : 2008-10-13 11:43:40 Comment on Tutorial : How to Send SMS using Java Program (full code sample included) By Emiley J. can anybody tell me the full code for sending sms from pc to mobile...plz reply at my mail download the all 5 codes.but how can i run View Tutorial By: Chathu at 2011-01-30 02:28:53 2. import java.util.Scanner; public class Swit View Tutorial By: srinath at 2013-04-28 10:17:24 3. i want to learn j2me basic to .... View Tutorial By: gopiraj at 2012-12-21 11:52:01 4. I did all steps, but it only shows the first pictu View Tutorial By: behzad at 2012-07-15 16:32:41 5. i am run code this rectify this error please some View Tutorial By: indiran at 2010-01-28 01:45:56 6. This tutorial is very nice for beginners. View Tutorial By: Wakil Ahamad at 2009-02-07 05:58:31 7. I have maked all you said and when I open jsp I am View Tutorial By: ismail at 2011-03-16 04:08:53 8. How to write data from keyboard to a file in java? View Tutorial By: Ashish Ranjan at 2011-07-13 01:04:38 9. Hi Rima, View Tutorial By: Ramlak at 2008-12-28 03:00:01 10. i want a java code to make a GUI in netbeans and s View Tutorial By: siddharth at 2012-03-17 09:59:59
https://java-samples.com/showcomment.php?commentid=33612
CC-MAIN-2019-43
refinedweb
278
74.69
Feb. 27-Mar. 02, 2011, Denver, CO Preprint 11-097 OPEN PIT GEOMETRY MODELING AND ECONOMIC ANALYSIS OF NOVEL AT-FACE-SLURRY OPTIONS R. S. Suglo, Univ. of Mines & Technology, Tarkwa, Ghana S. Frimpong, Missouri Univ. of Science & Technology, Rolla, MO O. F. Brown, Missouri Univ. of Science & Technology, Rolla, MO the frequent changes in the pit configuration. As open pit layouts expand, equipment cycle times and haulage costs increases resulting in lower production rates and system efficiencies. Thus, there is a need for cheaper mining and haulage systems for ensuring optimum profitability. Bulk materials transport systems such as belt conveyors and hydraulic transport systems have been noted to offer lower operating costs. They are also versatile and have practically unlimited range of capacities and are increasingly being employed in the bulk transportation of materials in large surface mines. They offer competitive advantages over other materials handling systems in reducing the unit production costs. ABSTRACT novel at face slurry (AFS) system is intended to take advantage of the lower unit operating costs, higher payloaddeadweight ratio, and higher efficiencies of hydraulic and belt conveyor transport systems by extending the transport systems to the production faces. In the AFS system, the shovel at the pit face will be linked to the treatment plant by mobile trains of either a hopper-crusher-belt conveyor wagons-slurry facility or a hopper-crusher-slurry facilityflexible/fixed pipeline system. Thus the excavation, crushing and slurry process will be done at the face before being pumped to the main treatment plant. The AFS system will introduce a unique set of mine design layout, configuration and ergonomic challenges by allowing the mobile train of flexible pipelines or conveyor belt systems to adapt to the production face dynamics. ×. The shovel-truck system, referred to as the current mining system (CMS), is widely used in most surface mines in the world. Due to the operating flexibility, mobility and resale value, truck haulage is the favored method for moving both ore and waste in open pit mines (Frizzell and Martin 1992). The shovel-truck system is currently being used in mining and waste stripping operations in most hard rock and oil sands mining companies. The CMS comprises shovels as the primary loaders with diesel-powered dump trucks that are dispatched or allocated to each excavator. The loaded trucks transport the materials to dump sites at the crusher-slurry facility or to the waste dump site. The system comprises discrete loading and haulage units whose outputs per hour are characterized by their cycle times. INTRODUCTION Surface mine production scheduling can be challenging due to the fact that most open pit mines work with multiple benches and often involve the simultaneous excavation of both ore and waste from a number of working faces (Dohm 1979; Bohnet 1989; Armstrong 1990; Erarslan 2002). These production schedules and plans are used to maintain and maximize the expected profit (Hustrulid and Kuchta 1995); determine the future investment in mining; optimize return on investment; evaluate alternative investment options; and conserve and develop the mine's resources (O’Neil 1998). To determine the pit volumes, the expansion rates, and periodic volume of materials within the pits and optimize resources allocation, Matlab was used to solve geometric equations for materials excavation on a multi-bench, multiface open pit mine subject to constraints imposed by the initial and boundary conditions. The CycEx CBCS comprises a shovel, a crawler-mounted mobile crusher, belt conveyor wagons, a mixing tower and a slurry facility. The shovel loads its materials into a crawler-mounted hopper located at the face. Apron feeders transfer the materials to sizers then into double roll crushers for size reduction. The crushed materials will be sized and conveyed on a train of crawler-mounted belt conveyor wagons to a surge facility from which apron feeders will transport it to a slurry facility. The oil sands slurry is transported through the main hydrotransport system (HTS) to the main processing plant (Changirwa et al. 2000; Coward 2000). The slurry unit will also receive materials from other faces in a multi-bench, multi-face mining and materials flow system. This will ensure a continuous flow of materials from the cyclical shovels to the slurry unit. The aim is to meet the required production targets, and avoid downtimes of the slurry unit because of a problem at any of the mining faces. The cross-sections of most open pit mines are either circular or elliptical in shape. To accurately determine the volumes of materials excavated in these pits, geometric calculations and PDEs were employed. The dimensions of the pits are expanded and deepened by lateral and longitudinal incremental pushbacks. Surface mining materials handling is mainly by discrete or continuous flow units and processes. Discrete materials loading and haulage systems are predominantly used in open pit mines because they allow high flexibility in planning and scheduling of operations and easily cope with Different combinations of equipment can be used in a mine to achieve the desired production targets. However, some equipment combinations and their operating times result in lower unit operating 1 Table 2 summarizes the results of the times required to mine all the ore on benches 1 to 3 using geometric calculations and PDEs for an elliptical pit. 02.68 2600. CO costs and higher system efficiencies than others.97 yr and 11.987.50 Bench #2 CBCS 2615. Figure 1 is a 3D layout of an open pit with three benches while Figure 2 is a solid 3D layout of the faces of a circular pit after taking ten incremental pushbacks of 10 m each.15 yr.00 0.000 m.33 Bench #1 CBCS 2. In a typical open pit mine. 2011.45 yr. Table 1. the ore reserves on bench #1 would be mined out in 2.11 to 3.53 Average Figure 1.50 2780.67 CMS 2827. are almost the same as those obtained from PDEs for the different pit configurations. The performance of CSM and an AFS conceptual option. From the geometric calculations. 3D View of Circular Pit Faces after taking Incremental Pushbacks on Bench #1.50 CMS 2677. The ore on benches 2 and 3 will be completely mined out in 11. In this paper Matlab algorithms are used in geometric calculations and parabolic partial differential equations (PDEs) to determine the pit volumes and expansion rates of pits in a hypothetical oil sands mine with elliptical and spherical geometries.19 years to completely mine all the ore on benches 1 to 3 respectively using the CycEx CBCS method.38 yr.96 0.56 2497. show that the values from geometric calculations using Matlab. both the waste and ore must be mined at the required rates simultaneously. geometric estimates show that the ore in benches 1 to 3 will be completely excavated after 12. Ratio 1. The remaining reserves along the major axis on the various benches can then be mined later and the volumes calculated using PDEs.51 to 8. Thus PDEs may be successfully used in volume calculations to arrive at the same values as obtained from geometric process. Thus for every tonne of ore mined about 1.03 1.58 2710. 11. the periodic volume changes in circular and elliptical pits are modeled using parabolic differential equations.99 0.1 tonnes of waste have to be removed to maintain the stripping ratio. The hypothetical mine has a daily production target of 262. the PDE calculations tend to overestimate the volumes excavated as the pit deepens (i. the ore in benches 1 to 3 will be completely excavated in 12.01 Geometric Volume of Materials from an Elliptical Pit Matlab was used for calculating the geometric volume of materials excavated from an elliptical pit. the CycEx CBCS in the different pit configurations are evaluated.95 years (using PDEs). Table 2.06 yr and 10.33 to 8.01 1.e. 3D View of a Circular Pit with 3 Benches. the ore on benches 1 to 3 will be completely mined out from 7.984. Geometric Volume of Materials from a Circular Pit Matlab algorithms are used in calculating the geometric volume of materials excavated from a circular pit.000 m.26 2812. The thickness of the deposit averages 60 m.97 1.03 0.82 yr and 11. However. Figure 2. The spaces in between the colored circular frustums show the voids created after taking each pushback with a thickness of 10 m.82 yr respectively.82 m after taking 10 pushbacks on bench #1. Time to Excavate Ore Reserves from a Circular Pit. The initial pit radius in Figure 2 is 80 m while the final pit diameter at the top is 381.52 yr respectively. In addition.13 yr and 11.18 years on the three benches (using geometric calculations) and from 6. The initial pit 2 Copyright © 2011 by SME .33 Bench #3 CBCS 2635.00 CMS 2630. Detailed geometric calculations show that it will Figure 3 is a solid 3D diagram of the faces of an elliptical pit after ten incremental pushbacks each of 10 m in thickness.376. calculations using PDEs for pit expansion in all directions are usually terminated when the boundary conditions along the minor axis or shorter dimensions of the property boundaries are attained.00 Bench #1 CBCS 2.99 0.17 CMS 2778.84 to 7. in Tables 1 and 2.95 0. Using the CycEx CBCS option in a circular pit configuration.87 2991.99 1.934.33 2900.76 days to mine the ore materials within each incremental pushback in all directions on bench #1.25 2908.1:1.90 2854. The results from both tables show that generally.01 0.19 yr respectively.04 1.926. In this case the calculations are terminated when the initial length of the minor axes of the elliptical cross-section is 3.04 yr) at the projected production rate of 262. the results show that the ore benches 1 to 3 will be completely extracted in 12.000 t/day. Table 1 summarizes the results of the times required to mine all the ore on benches 1 to 3 using geometric calculations and PDEs for a circular pit configuration. 11.00 Bench #3 CBCS 2. Geometric PDE (days) (days) CMS 2934.99 The results.21 yr respectively.24 2541. it will take from 6. Ratio 1. 27-Mar. The results show that when the CMS option is used. The waste stripping operation has to precede the ore mining and must continue at a good rate to ensure that sufficient ore material is exposed to meet the required ore production targets. This means that the amount of ore to be mined is almost the same as that of the waste stripping requirements.SME Annual Meeting Feb. The pit limits are reached when the radius of the pit reaches the shortest length of the property boundaries. at the lower benches) relative to geometric calculations. Time to Excavate Reserves from an Elliptical Pit Geometric PDE (days) (days) CMS 2. Denver.000 tonnes at a stripping ratio of 1.67 Average DYNAMICS OF EXCAVATED MATERIALS The dynamic modeling of the pit design and the material volumes from the pits with circular and elliptical shapes is done using Matlab. 11. The pit limits are reached when the pit dimensions along the minor axis reach the boundary conditions. When PDEs are used in the calculations.03 2841. When the CMS option is employed in an elliptical pit. When PDEs are employed with the CycEx CBCS option.10 2708.67 Bench #2 CBCS 2. take between 0.673.25 days (8. In this case the calculations are terminated when the radius of the pit is 3. This may leave some reserves in the pit along the major axis whose volume can be similarly determined using PDEs if excavation is assumed to be taking place in only that direction. the volume of ore that can be mined on benches 1 to 3 are 3. It shows that the rate of change in the volume of the elliptical pit is virtually the same irrespective of the type of mining option used.00E+08 4.72 3 3 3 × 108 m . Time using CMS and CycEx 10000 20000 30000 40000 50000 60000 70000 80000 Time (hr) CMS The calculations show that the rate of increase in the pit dimensions was about 0.00E+08 80000 Time (hr) CMS 3.84 × 108 m respectively.44 × 3 3 108 m and 3.23 × 108 m and 2. Figure 3.00E+08 2. CBCS.23 × 108 m respectively.73 × 108 m . ECONOMIC ANALYSIS OF MINING OPTIONS Mining projects normally involve huge levels of capital outlays with their corresponding high investment risks. 3.50E+08 1. This section presents the economic analysis of the CMS and CycEx CBCS options. 3. 27-Mar. involve continuous processes.50E+08 5.00E+08 1.91 × 108 m respectively. Using the CMS option. 3. Thus. 3D View of Elliptical Pit Faces after Incremental Pushbacks. if the differential volume expansion of the pit is known.50E+08 4.82 m × 431. to determine the attractiveness of projects and to aid in the selection of the best investment ventures from many options. Volume of Elliptical Pit vs. 2011.82 m after taking the 10 pushbacks on bench #1. From Figure 4.28 × 108 m respectively. then the time it will take to excavate it can be obtained from the x-axis or vice versa. The geometric volumes of ore that can be extracted from the elliptical frustum on benches 1 to 3 using the CMS option are 3. Figure 5 shows the initial AFS equipment layout in a circular pit for the application of the CycEx CBCS option. Economic analysis is one the best tools for evaluating and comparing different projects or investments options. Accordingly. Initial AFS Equipment Layout in a Circular Pit.00E+00 0 Volume of Circular Pit vs. 5. Figure 6 shows the respective rates of change of the volume of an elliptical pit at any given time when the CMS and CycEx CBCS options are used respectively. Dynamics of Excavated Volumes The expansion and materials handling operations.50E+08 Figure 5. The geometric volumes of ore from benches 1 to 3 of 3 the elliptical pit using the CycEx CBCS option are 3. design and scheduling cannot be used to accurately capture the continuous changes.00E+08 Volum e Excavated (m 3 ) V o lu m e E x c a v a te d (m 3 ) 4.00E+08 2. With the CycEx CBCS option. within the pit.50E+08 2. dimensions are 328 m × 208 m while the final pit diameter at the top is 549. 3. CBCS Figure 6.00E+08 3.SME Annual Meeting Feb.00E+08 4. the volume 3 of ore that can be mined from benches 1 to 3 are 3.65 × 108 3 3 3 m . Parabolic partial differential equations (PDEs) with their associated boundary conditions can be used to model changes in the pit volume and configuration when the pit expansion is in only one direction. it is much better to assess both options using the appropriate evaluation economic criteria. most of the available software for mine planning.00E+07 CBCS 0.046 m/hr.50E+08 1. alone or in combination. 3.00E+08 1. Figure 7 shows the initial AFS equipment layout in an elliptical pit for the application of the CycEx CBCS option. all new mining projects or modifications to existing projects have to be economically evaluated to assess their viabilities and whether they add value to the company.31 3 3 × 108 m and 2. Figure 4 shows the volume of a circular pit at any given time on bench #1 when using CMS and CycEx CBCS.50E+08 5. CO of 0. Even though the cost of production per tonne from the two options may be used to determine the better option. 02. Denver. Various economic evaluation criteria are commonly used.00E+00 0 10000 20000 30000 40000 50000 60000 70000 Figure 4.00E+08 5.66 × 108 m .048 m/hr. Time using PDEs on Bench #1 for CMS and CycEx CBCS Option (Source: Suglo 2004). 3.00E+07 0. The dimensions of the elliptical frustum on bench #1 will expand at the rate 3 Copyright © 2011 by SME .50 × 108 m and 3.50E+08 2. A detailed economic analysis on the CMS and CycEx CBCS options is carried out (Anon. AIME.. Vol. In addition. 6..b. (1990). Table 3. 7. and Szymanski. R.37 2. Figure 7. Kennedy.02%) and extremely short discounted payback periods (≤ 3. No.37 1.15 0.canadianeconomy.558/barrel). Initial AFS Equipment Layout in an Elliptical Pit (Source: Suglo 2004). Kennedy. calculations using PDEs for pit expansion in all directions are usually terminated when the boundary conditions along the minor axis or shorter dimensions of the property boundaries are attained. PI (> 19%) and IRR (> 29. As well. Frimpong. Syncrude Canada Ltd. Baltimore: 476-479. 2011.24 months). 27-Mar. 5. The results of the economic analysis show that both the current mining system which involves shovels and trucks and the conceptual AFS option. are viable with higher NPV values (≥ $3. the CycEx CBCS option has almost half the DPBP of the CMS option. In this study.13 times that of the CMS option. (2003b). as well as the frequent changes in political regimes in some states and provinces. ed. in Ch. 94.). The PI and IRR of the CycEx CBCS option are respectively 2. REFERENCES Table 3 summarizes the results of the economic analysis conducted on the two mining options in this paper.bankofcanada. 4. “Project Millennium – Suncor Ramping Up to Double Production”. some governments tend to impose higher than expected taxes on mining companies to balance their accounts and to meet increasing public demand for public facilities and services. Anon.774/barrel) while that of the CycEx CBCS option is $0. Thus PDEs may be successfully used in volume calculations to yield the same values as geometric estimates. 02. The results show that both mining options are viable with high net present values (≥ $3. Anon. “The Current Economy – Analysis of the Current State of the Economy”. 1054: 13-27. it is often necessary to assess the effect of changes in the discount rate at various percentages because with most new operations.78 times that of the CycEx CBCS option.37 43. Against a discount rate of 15% set by the company. the CycEx CBCS option is clearly more economically viable than the CMS option.02%) and extremely short discounted payback periods (≤ 3. Changirwa. © Palisade Corporation.27 times that of the CMS option.24 29. S. Collaborative Research on an At Face Slurrying (AFS) Technology – NSERC-Syncrude-University of Alberta. Optimum Production Scheduling.59 4 Copyright © 2011 by SME . As well. CIM Bulletin. Baltimore: 459-464. E. Bank of Canada webpage. profitability indices (> 19%) and internal rates of return (> 29. This means that it is cheaper for oil sands mining companies to adapt the CycEx CBCS option as against the CMS to increase their profitabilities and enhance the environmental conditions in their mines.ca 5. Anon.27 times that of the CMS option. 2001a. NY. The results show that the data closely fit various statistical distributions (Suglo and Szymanski 1995. 3. “Why We’re Here”. Anon. Over the years as more information is gathered and various parameters are known to high levels of certainty. The times to excavate the ore reserves contained in benches 1 to 3 using the CMS and CycEx CBCS options were also computed. “AFS Recommended Option”. (1997). 2003a.78 times that of the CycEx CBCS option.486. (2001b). the PDE calculations tend to overestimate the volumes excavated as the pit deepens relative to geometric calculations.27 19.779/tonne ($1.386/tonne ($2. Due to the unpredictable nature of mineral prices and other economic indices. The PI and IRR of the CycEx CBCS option are respectively 2.386/tonne ($2. The depletion allowance is taken as the minimum of 5% of gross revenue or 10% of Pre-Capital Cost Allowance (PreCCA) while the average exchange rate of the US $ to the Canadian $ for the past 7 years was 1. (2001a).24 and 1. www. 1997).13 times that of the CMS option.syncrude. The collected data are processed using the stabilized probability plot method and BestFit.gc. Armstrong. Economic Analysis of Mining Options. www. 2nd ed.. (1989). However. CONCLUSION In this paper geometric calculations and PDEs have been used to determine the pit volumes and expansion rates of pits with elliptical and spherical geometries. (2000). CO Table 4 (see last page) summarizes the total operating costs of the CMS and CycEx CBCS options obtained from calculations. The costs were assumed to vary by ±25% of their mean values.). the cyclic excavator conveyor belt control system (CycEx CBCS).A. Anon. the CycEx CBCS option has almost half the DPBP of the CMS option.16 0. Government of Canada webpage.20 × 1010). (2003a). the discount rates are reduced to reflect the level of confidence in the project parameters.558/barrel). The results show that the CMS option has an operating cost of $1. From Table 3. 2nd ed. Bohnet. “Bank of Canada – Monetary Policy”.SME Annual Meeting Feb. the CycEx CBCS option is clearly the better option to invest in.20 × 1010).A. As well. The CMS option has an operating cost of $1.b. Its NPV is 1. These results show that the CycEx CBCS option is clearly the better option for mining companies working on oil sands deposits to invest in.24 months).774/barrel) while that of the CycEx CBCS option is $0.02 33. Newfield. Anon. Thus the unit operating cost of the CMS option is about 1. 2. Thus the unit operating cost of the CMS option is about 1. ed. AIME. Anon. Coward 2003).06 1. It is also noted that generally.L.4 of Surface Mining (B. one barrel of oil is obtained for every two tonnes of ore.779/tonne ($1. Planning and Design of Surface Mines. www. it is also necessary to assess the impact of federal and state taxes on the viability of projects at various tax levels. D.27 0.com. 1.htm. The results show that the calculated values from geometric calculations using Matlab are almost the same as those obtained from PDEs for different pit configurations. Thus. “@RISK: Risk Simulation and Analysis for Spreadsheets”. Profitability Measure NPV ($1010) PI IRR ( %) DPBP (yr) Mining Option Ratio (CBCS/CMS) CMS CycEx CBCS 3. Thus. Its NPV is 1. webpage. Denver. 8. the CycEx CBCS option is more economically viable than the CMS option. in Ch.ca/en/monetary. 5 of Surface Mining (B.24 and 1. The Double Declining Balance (DDB) method of depreciation is used at the mine. An allowance of 25% of the cost is given for contingencies. comprehensive economic and risk analyses are required for all the possible scenarios to ensure proper comparison of the various mining options and to make informed investment decisions. Progress Report # NSERC/SCL/CRD00001 (January): 161. most investors often apply high discount rates at the start of operations. J.20 4. Summary of Operating Costs of CMS and CycEx CBCS Options. 10. No. eds. and Petroleum Engineers.T. Metallurgical. (1992). (J.60 Shovel (O&K RH200) 6 22. sen. (March 2003). Denver.L.26 1. 21 of Open Pit Mine Planning and Design.C. Edmonton. Proceedings of Underground Operators’ Conference. 13. Mining Engineering. “Computer Simulation of Underground Room and Pillar Mining”. Table 4. (January 2000).80 2. Ch.84 54. (2004). R. of Units ($/min.A.S.2 Mobile Crusher & Slurrification 1 1. J. in.66 1. Dohm.. Suglo. J.05 13. Fundamentals. Circular Analysis – Open Pit Optimization.81 10.61 18. Open Pit Mine Design and Planning. J. 3: 313-321. (2002). (1979). Balkema. Communication with Syncrude Canada Ltd. Inc. Vol. 2011. University of Alberta.80 2.20 Crusher 1 7. (1995). Operators 9 6 6 12 Total Operator Cost ($ × 106) 7.779 ± 0. PhD Dissertation.80 1. 11. “A Practical Approach for Open Pit Design and Visualisation”. “Syncrude: Biggest Oil-Sand Miner gets Biggest Hydraulic Shovel”. (2003). (2000).5 of SME Mining Engineering Handbook 2nd ed.60 Total Operating Cost ($ × 106) Operating Cost per tonne ($/tonne) CycEx CBCS Option Maintenance Cost Operator Cost Type of Equipment No. W. (1995). (1998). American Institute of Mining. ed. and Martin. CO 9. Rotterdam: 1-625. Maintenance Cost Operator Cost Type of Equipment No. Communication with Syncrude Canada Ltd. R. 1. in Ch. Erarslan.023 Copyright © 2011 by SME .25 ± 2. Hustrulid.75 1. A.98 6.) ($ × 106) Belt conveyor wagons (20 m) 18 6. (H. AIME.M.A. Coward.09 15 12.386 ± 0. K. AIME-SME.90 9. NY: 31-40.07 Total Cost ($ × 106) 55. Kalgoolie.SME Annual Meeting Feb. 27-Mar. 12. 15.6 Mobile transfer conveyor 2 2. 9.66 0. Littleton.6 unit Total Operating Costs ($ × 106) Operating Cost per tonne ($/tonne) 5 Total No.). Journal of Mineral Resources Eng.49 ± 4. G. Canada: 1-181. New York.15 1. Operators 36 18 12 Total Operator Cost ($ × 106) 30. and Kuchta. Hustrulid. November 13-14. Vol.S. 1995): 1-4. M. 2. and Szymanski. Suglo.. Frizzell. 13.27 20.40 1. In-Pit Crushing and Conveying. O’Neil. Geometrical Mine Design and Multi-Bench Material Flow Simulation for AFS Characterization.57 5.05 5. Coward. of Units ($/min. 16. 02.49 22. Vol.6 Shovel (O&K RH200) 6 3. E. T. CO: 33-39. 17.18 Total No.6 Hydrotransport Pipelines 1 0.09 13.) ($ × 106) CMS Option Trucks (360 t unit) 24 14.02 74. W.94 1.52 22. Hartman.. 14.). Crawford and W. T. Baltimore: 13431350.87 Total Cost ($ × 106) 17.
https://www.scribd.com/document/250103930/open-pit1
CC-MAIN-2018-51
refinedweb
4,318
58.18
On Friday 22 February 2008, Peter LaDow wrote: > >From: "Julius Luukko" <address@hidden> > >>> Are you using my port version? If you are, you might want to start with > >>> a > >>> newer version available in my page > >>> > >>> > >> > >> > > Thanks for the links. Though your site mentions the patch applies to 2.52 > and 2.70, I am using 2.86. Know of any issues there? A cursory inspection > shows the os_cpu_c.c still assumes a 2-byte PC. I'll compare the rest to > see what else has changed. Yes you are right, I have not updated the port to take into account a 3-byte PC. I meant that there are other serious bugs in the version which is available from Micrium (e.g. usage of r0 and r1 when mixing C and assembly). Version 2.70 is the last version I have obtained from Micrium. I got it when I first submitted the port to Micrium, at that point only for 2.52 (the version with the book). Updates are not freely available and I don't have a commercial license for uC/OS-II (I work in a university). So I don't know if there are changes that affect ports. > > One note though. I modified os_cpu_a.asm to remove the dependence on TCNT0 > in OSTickISR. I'm using a different timer, which auto-reloads, so there is > no need for the output to TCNT0. I commented this out in my version and > relied upon a vector to jump to this handler. In fact, I do: > > .global OSTickISR > > .global TIMER1_COMPA_vect > TIMER1_COMPA_vect: > jmp OSTickISR This is of course wise. I have only included the tick ISR with timer0 since it is available in every AVR. > > Of course with copious commenting. This eliminates the coupling of the OS > port to a specific platform. Though it does make it more difficult to use > with hardware that does not auto-reload a timer. But that would likely > require modification anyways. I think my change makes the port more > platform independent. > The choice between timers could be made with preprocessor macros. You could define these in os_cfg.h so that you can choose the timer in every project without making changes to the actual OS source. > >> (even though the header on the page only mentions gcc 3.x, it also works > >> with > >> 4.x) > > Perfect. :) I am using 4.2.1. > > >> I haven't been very active with uC/OS-II or AVR lately. However, if you > >> are > >> able to get it run with newer parts (with more than 128kB memory), I > >> would be > >> happy to integrate your changes into my port. The current port should > >> work > >> with all AVRs (with 128kB or less) and with your changes, it should be a > >> simple matter of preprocessor conditionals to support both older and > >> newer > >> chips. If you are willing to take over the "support" of the port, you > >> could > >> contact me offlist. > > "Support"? :) I mean that if you publish something, someone is bound to ask you something about it. I have received about 90 uC/OS-II related emails since March 2003. > > I have to admit, I'm using the AT90USB1287 for a project, not the > ATmega2561. Though I am experimenting with the 2561 (having used it on my > last project) for the uC/OS-II stuff I am doing. But given the USB1287's > apparent use of a 3-byte PC, a port to the USB1287 could perhaps provide a > fix to a part with more than 128K. > > The question is how to determine, compile time, if a part as a 3-byte PC or > a 2-byte PC. It seems that the size of the flash doesn't matter, if my > observations of the USB1287 prove true. > I don't know if there is a universal method to determine it at compile time. You'll just have to test chip by chip: #if defined(__AVR_ATmega256__) || defined(some_other_with_3_byte_PC) #define THREEBYTEPC 1 #else #define THREEBYTEPC 0 #endif I am not sure if __AVR_ATmega256__ is the right constant name. If you have more uC/OS-II related questions, maybe the discussion should be moved offlist or to avr-chat. -- Julius
http://lists.gnu.org/archive/html/avr-gcc-list/2008-02/msg00048.html
CC-MAIN-2016-36
refinedweb
693
83.66
NAME msgctl - message control operations SYNOPSIS #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msgctl(int msqid, int cmd, struct msqid_ds *buf); DESCRIPTION msgctl() performs the control operation specified by cmd on the message queue with identifier msqid. The msqid_ds data structure is defined in <sys/msg.h> as follows: struct msqid_ds { struct ipc_perm msg_perm; /* Ownership and permissions */ time_t msg_stime; /* Time of last msgsnd(2) */ time_t msg_rtime; /* Time of last msgrcv(2) */(2) */ pid_t msg_lrpid; /* PID of last msgrcv(2) */ }; The ipc_perm structure is defined in <sys/ipc.h> as follows (the highlighted fields are settable using IPC_SET): struct ipc_perm { key_t __key; /* Key supplied to msgget msqid into the msqid_ds structure pointed to by buf. The caller must have read permission on the message queue. IPC_SET Write the values of some members of the msqid_ds structure pointed to by buf to the kernel data structure associated with this message queue, updating also its msg_ctime member. The following members of the structure are updated: msg_qbytes, msg_perm.uid, msg_perm.gid, and (the least significant 9 bits of) msg_perm.mode. The effective UID of the calling process must match the owner (msg_perm.uid) or creator (msg_perm.cuid) of the message queue, or the caller must be privileged. Appropriate privilege (Linux: the CAP_IPC_RESOURCE capability) is required to raise the msg_qbytes value beyond the system parameter MSGMNB. IPC_RMID Immediately remove the message queue, awakening all waiting reader and writer processes (with an error return and errno set to EIDRM). The calling process must have appropriate privileges or its effective user ID must be either that of the creator or owner of the message queue. IPC_INFO (Linux-specific) Returns information about system-wide message queue limits and parameters in the structure pointed to by buf. This structure is of type msginfo (thus, a cast is required), defined in <sys/msg.h> if the _GNU_SOURCE feature test macro is defined: struct msginfo { int msgpool; /* Size in kibibytes of buffer pool used to hold message data; unused within kernel */ int msgmap; /* Maximum number of entries in message map; unused within kernel */ int msgmax; /* Maximum number of bytes that can be written in a single message */ int msgmnb; /* Maximum number of bytes that can be written to queue; used to initialize msg_qbytes during queue creation (msgget(2)) */ int msgmni; /* Maximum number of message queues */ int msgssz; /* Message segment size; unused within kernel */ int msgtql; /* Maximum number of messages on all queues in system; unused within kernel */ unsigned short int msgseg; /* Maximum number of segments; unused within kernel */ }; The msgmni, msgmax, and msgmnb settings can be changed via /proc files of the same name; see proc(5) for details. MSG_INFO (Linux-specific) Returns a msginfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by message queues: the msgpool field returns the number of message queues that currently exist on the system; the msgmap field returns the total number of messages in all queues on the system; and the msgtql field returns the total number of bytes in all messages in all queues on the system. MSG_STAT (Linux-specific) Returns a msqid_ds structure as for IPC_STAT. However, the msqid argument is not a queue identifier, but instead an index into the kernel’s internal array that maintains information about all message queues on the system. RETURN VALUE On success, IPC_STAT, IPC_SET, and IPC_RMID return 0. A successful IPC_INFO or MSG_INFO operation returns the index of the highest used entry in the kernel’s internal array recording information about all message queues. (This information can be used with repeated MSG_STAT operations to obtain information about all queues on the system.) A successful MSG_STAT operation returns the identifier of the queue whose index was given in msqid. On error, -1 is returned with errno indicating the error. ERRORS On failure, errno is set to one of the following: EACCES The argument cmd is equal to IPC_STAT or MSG_STAT, but the calling process does not have read permission on the message queue msqid, and does not have the CAP_IPC_OWNER capability. EFAULT The argument cmd has the value IPC_SET or IPC_STAT, but the address pointed to by buf isn’t accessible. EIDRM The message queue was removed. EINVAL Invalid value for cmd or msqid. Or: for a MSG_STAT operation, the index value specified in msqid referred to an array slot that is currently unused. EPERM The argument cmd has the value IPC_SET or IPC_RMID, but the effective user ID of the calling process is not the creator (as found in msg_perm.cuid) or the owner (as found in msg_perm.uid) of the message queue, and the process is not privileged (Linux: it does not have the CAP_SYS_ADMIN capability). CONFORMING TO SVr4, POSIX.1-2001. NOTES The IPC_INFO, MSG_STAT and MSG_INFO operations are used by the ipcs(8) program to provide information on allocated resources. In the future these may modified or moved to a /proc file system interface. Various fields in the struct msq msgget(2), msgrcv(2), msgsnd(2), capabilities(7), mq_overview(7), svipc(7) COLOPHON This page is part of release 3.15 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/jaunty/en/man2/msgctl.2.html
CC-MAIN-2013-48
refinedweb
878
51.28
Get the highlights in your inbox every week. Use logzero for simple logging in Python | Opensource.com Use logzero for simple logging in Python A quick primer on the handy log library that can help you master this important programming concept. Subscribe now colored in an easy-to-read way: So now, instead of using print to figure out what's going on, use logger instead, with the relevant log level. Writing logs to a file in PythonIf you only read this far and make that one change in the way you write code, that's good enough for me. If you want to go further, read on! Writing to stdout is fun for testing a new program, but it is only useful if you are logged into the computer where the script is running. Many times when using an application you'll want to execute the code remotely and review errors after the fact. That's when it's helpful to log to a file instead. Let's try it: from logzero import logger, logfile logfile('/home/pi/test.log') Now your log entries will be logged into the file test.log. Remember to make sure that the script has permission to write to that file and its directory structure. You can specify some more options too: logfile(’/home/pi/test.log’, maxBytes=1e6, backupCount=3) Now when the file provided to logfile reaches 1MB (1×106 bytes), it will rotate entries through test.log.1, test.log.2, and so on. This behavior is nice to avoid generating a massive log file that is I/O intensive for the system to open and close. You might also want to log to /var/log like a pro. Assuming you're on Linux, you a directory and make your user the owner so they can write to it: $ sudo mkdir /var/log/test $ sudo chown pi /var/log/test Then in your Python code, change(f"{e.__class__.__name__}: {e}") Now this will produce the more succinct: [E 190423 00:04:16 test:9] ZeroDivisionError: division by zero There are plenty more options which you can read in the docs at logzero.readthedocs.io. logzero shines for education Logging can be a challenging concept for a new programmer. Most frameworks depend on flow control and lots of variable manipulation to make a meaningful log, but logzero is different. With its syntax being similar to a print statement, it is a big win for education as it saves from explaining another concept. Give it a try on your next project. -- This article was originally written on my blog and is republished with permission. 3 Comments Excellent overview and very simple to implement! "Writing to stdout is fun for testing a new program, but it is only useful if you are logged into the computer where the script is running." Thanks to the systemd journal, this isn't (on most distros) entirely true! If your program (or a program using your module) is run as a systemd service, anything it prints to stdout gets logged to the journal. So for simple 'real' logging in this situation, probably logzero's basic mode would be enough. I just tried this. The ANSI-colored errors are cool to look at. I'm not sure how to define custom colors though.
https://opensource.com/article/20/2/logzero-python
CC-MAIN-2020-24
refinedweb
555
63.8
MLOCKALL(2) BSD Programmer's Manual MLOCKALL(2) mlockall, munlockall - lock (unlock) the address space of a process #include <sys/types.h> #include <sys/mman.h> int mlockall(int flags); int munlockall(void); The mlockall system call locks into memory the physical pages associated ad- dress space. Any regions mapped after an munlockall call will not be locked. privileges to perform the requested operation. mincore(2), mlock(2), mmap(2), munmap(2), setrlimit(2) The mlockall() and munlockall() functions conform to IEEE Std 1003.1b- 1993 ("POSIX"). The mlockall() and munlockall() functions first appeared in OpenBSD 2.9. only as a single page in the system limit. MirOS BSD #10-current June 12,.
http://www.mirbsd.org/htman/i386/man2/mlockall.htm
CC-MAIN-2014-35
refinedweb
113
61.73
From: Philipp Frauenfelder (pfrauenf_at_[hidden]) Date: 2004-08-16 00:43:44 Hi I would like to define different libraries to link with when in different address modes. Currently, I have to following in my site-config.jam: [ ... ] if [ os.name ] = LINUX { import site-config.linux ; } if [ os.name ] = SOLARIS { import site-config.solaris ; } How can I put it that I can have a site-config.solaris32 and site-config.solaris64 (and the same for Linux as well)? I would imagine something like if [ feature.value address-mode = 32 ] { // blah } Btw, I have feature address-mode : 32 64 : propagated ; in tools/builtin.jam. Thanks a lot in advance.
https://lists.boost.org/boost-build/2004/08/6985.php
CC-MAIN-2019-26
refinedweb
108
55.1
08 February 2012 18:36 [Source: ICIS news] HOUSTON (ICIS)--LyondellBasell will start work on its planned 40% butadiene expansion at Wesseling near ?xml:namespace> Following completion of the work in mid-2013, the plant’s butadiene capacity will be 238,000 tonnes/year, LyondellBasell spokesman David Harpole told ICIS. He would not comment on the project’s expected costs. Also at Wesseling, LyondellBasell will permanently close down two older polypropylene (PP) units. The closure has been scheduled for mid-2012, Harpole said. Harpole added that the two projects – butadiene expansion and PP closure - are not linked. “Each is a separate business decision,” he said. According to information on LyondellBasell’s website, the PP closure affects a total capacity of 90
http://www.icis.com/Articles/2012/02/08/9530638/lyondellbasell-to-start-work-on-germany-butadiene-expansion.html
CC-MAIN-2014-10
refinedweb
121
57.37
Computer Science Archive: Questions from September 01, 2009 - Anonymous askedProblem 1. Write the following sequence of code into NIOS-IIassembly code:x = x + y + z - q;Assume... Show more Problem 1. Write the following sequence of code into NIOS-IIassembly code:x = x + y + z - q;Assume that x, y, z, q are stored in registers $1-$4.• Show less Problem 2. In NIOS-II assembly, write an assembly language version of the following C code segment: int A[100], B[100]; for (i=1; i < 100; i++) { A[i] = A[i-1] + B[i]; } 1G At the beginning of this code segment, the only values in registers are the base address of arrays A and B in registers $1 and $2. Avoidthe use of multiplication instructions.they are unnecessary Problem 3. The NIOS-II instruction set includes several shift instructions. They include logical-shiftleft, logical-shift-right, and arithmetic-shift-right. Other architectures only provide an arithmeticshift- right instruction. a) Why doesn't NIOS-II offer an .arithmetic-shift-left. opcode? b) How would you implement in the assembler a logical-shift-left (LSL) pseudo-operation for a machine that didn.t have this particular instruction? Be sure your LSL instruction can shift up to W-bits where W is the machine word size in bits.0 answers - Anonymous asked1. Ask the user how many questions are in... Show moreWrite a program that grades arithmetic quizzes as follows: 1. Ask the user how many questions are in the quiz. 2. Ask the user to enter the key (that is, the correct answers).There should be one answer for each question in the quiz, and eachanswer should be an integer. They can be entered on a single line,e.g., 34 7 13 100 81 3 9 10 321 12 might be the key for a10-question quiz. You will need to store the key in an array. 3. Ask the user to enter the answers for the quiz to be graded. Asfor the key, these can be entered on a single line. Again thereneeds to be one for each question. Note that these answers do notneed to be stored; each answer can simply be compared to the key asit is entered. 4. When the user has entered all of the answers to be graded, printthe number correct and the percent correct. ****When this works, add a loop so that the user can grade anynumber of quizzes with a single key. After the results have beenprinted for each quiz, ask "Grade another quiz? (y/n)." -------------------- I am not sure what do due for the last part, adding a loop so theuser can grade any number of quizzes with a single key and afterthe results have been printed for each quiz, ask ..... this is what i have so far, i think i got 1-4 done, last parti am stuck public class Quiz { public static void main(String[] args) { int num_quiz; //number on thequiz int to_grade; int count = 0; double total; int total_quizzes; //total #of quizzes to be graded Scanner scan = new Scanner(System.in); System.out.print ("How many questions are in the quiz? "); num_quiz =scan.nextInt(); int [] answers = new int[num_quiz]; System.out.println("Enter theanswer keys for the questions."); for (int i=0; i<answers.length; i++) { answers[i] =scan.nextInt(); } System.out.print("How many quizzes do you wantto grade? "); total_quizzes =scan.nextInt(); for (int i =0; i <answers.length; i++) { System.out.println("Enter the answer to be graded : "); to_grade = scan.nextInt(); if(to_grade == answers[i]){ ++count; } } total = (double)count /num_quiz *100; System.out.println("Thenumber of questions correct are: " + count); System.out.println("Thepercentage correct is: " +total); System.out.println("Gradeanother Quiz? y/n"); } } • Show less1 answer - Anonymous askedWrite a MAL program that reads in 2 decimal numbers, multipliesthem together, stores them in a scrat... Show moreWrite a MAL program that reads in 2 decimal numbers, multipliesthem together, stores them in a scratchpad register. take intoaccount a number that is zero, two positive numbers, two negativenumbers, or a positive and a negative number. It should take nomore than 14 lines. n means the number is negative z means the number is all zeros • Show less0 answers - Anonymous askedIn a file called doesit.m write afunction verifying whether or not xis equal to either -2, -1.5, 1,... Show more In a file called doesit.m write afunction verifying whether or not xis equal to either -2, -1.5, 1, or 3.• Show less Return the value 0 if it does not satisfy the equation and 1 if itdoes.0 answers - Anonymous askedIn a file called count.m, write afunction counting how many integers (call themk)between 1 and N are... Show more In a file called count.m, write afunction counting how many integers (call themk)between 1 and N are such that sink 0.5. Show your results forN = 100, 200, 300.• Show less0 answers - Anonymous asked. What... Show more Write a function to generate anN-node random binary search tree with distinct keys 1 throughN. What is the runningtime of your routine?• Show less0 answers - meeow4 askedThis is the first assignment from the... Show more There are in all 132bytes in the message below, or 1056 bits, This is the first assignment from the Chem402 class. It is about packets and their transmission over links with differentbandwidths. Each letter of themessage above represents 1 byte (8 bits). That includes blanks andperiods. (a) (6 points) Find thetime it will take to transmit this message on end to end linkswith bandwidths of 56kbps(phone modem), 1.5Mbps and 4Mbps(DSL), assuming circuitswitching. (b)(9 points) If youwere to break up the message into packets of size 20 bytes each,with 4 bytes for header, how longwill it take to reach the destination if it must go through allthree linksmentioned above, and the routersare operating in store and forward mode.Will rateasap. Is this really just very simple math? Am Imissing something? Thanks!• Show less1 answer - Anonymous askedSuppose two hosts, Aand B, are separated by 2... Show moreplease help me solvethis problem, will rate lifesaver!Suppose two hosts, Aand B, are separated by 20 kilometers and are connected by a directlink of R=10Mbps. Suppose the propagation speed over the link is 2.5*10^8meters/sec. Considering sending a file of 100,000 bits from A toB as one big message.Ignore the processing and the queuing delays, i.e. weonly examine transmissionand propagation delays. a. How long doesit take to send the file? Note, we count the time fromthe moment the first bitof the file leaves A until the moment the last bit arrivesB. b. What is themaximum number of bits that will be in the link at any given time? c. For how long time,the number of bits in the link is equal to the maximum number of bits (thequantity you derived in b.)?• Show less1 answer - Anonymous askedI started out b... Show moreI am confused on how to convert a -26 signed decimal integerto a 16-bit hexadecimal.I started out by making the -26 positive to 26. i then did thefollowing:(2*16^1) + (6*16^0) = 32 + 6 = 38the binary form is 01000110.Now how do I convert to 16-bit hexadecimal?• Show less1 answer - Anonymous askedWhich of the following sorting algorithms arestable: insertion sort, merge sort, heapsort, and quick... Show more Which of the following sorting algorithms arestable: insertion sort, merge sort, heapsort, and quicksort? Give asimple scheme that makes any sorting algorithm stable. How muchadditional time and space does your scheme entail?• Show less1 answer - Anonymous asked1 answer - Anonymous askedUs... Show morewrite a program(in Java) that constructs a Rectangle object andthen computes and prints its area.• Show lessUse the getWidth and getHeightmethods.1 answer - Anonymous askedWrite a program(in Java) that constructs aRectangle object, prints its location, and then translates... Show moreWrite a program(in Java) that constructs aRectangle object, prints its location, and then translatesand prints it three more times, so that, if the rectangles weredrawn, they would form one large rectangle. • Show less0 answers - Anonymous asked) that encodes astring by replacing all letters "i" with "!" and all letters... Show moreWrite a program( in Java) that encodes astring by replacing all letters "i" with "!" and all letters "s"with "$". Use the replace method. Demonstrate that you cancorrectly encode the string "Mississippi". • Show less2 answers
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2009-september-01
CC-MAIN-2014-35
refinedweb
1,399
67.55
Inter-Page Communication This documentation is for an older version of ZK. For the latest documentation please click here. Communications among pages in the same desktop is straightforward. First, you can use attributes to share data. Second, you can use event to notify each other. Attributes Each component, page, desktop, session and Web application has an independent map of attributes. It is a good place to share data among components, pages, desktops and even sessions. In zscript and EL expressions, you could use the implicit objects: componentScope, pageScope, desktopScope, sessionScope, requestScope and applicationScope. In Java , you could use "setAttribute()","removeAttribute()" and "getAttribute()" Relevant api includes setAttribute, getAttribute, removeAttribute. In zscript, you can use call such api through implicit objects. For example, <window> <zscript><![CDATA[ desktop.setAttribute("some","anyObject"); ]]> </zscript> 1:${desktopScope["some"]} </window> Note that desktop setAttribute will be saved at desktopScope. In EL, you can use "[ ]" operator as the key to retrieve element of map. You could communicate among pages in the same desktop. The way to communicate is to use the postEvent or sendEvent to notify a component in the target page. Events.postEvent(new Event("SomethingHappens", comp.getDesktop().getPage("another").getFellow("main")); You can also pass object by event. The third parameter in postEvent will be put into Event.data. You can encapsulate data you want to pass in the object. In the following example, window's title will be set to "this will be send". <window use="MyWindow"> <zscript> Events.postEvent("onTest", self, "this will be send"); </zscript> </window> And MyWindow.java is as follow, import org.zkoss.zk.ui.event.Event; import org.zkoss.zul.Window; public class MyWindow extends Window { public void onTest(Event evt){ this.setTitle(evt.getData().toString()); } } Note: These api has to take care about component life cycle, if you use these api outside ZK event handler, please refer to server push.
https://www.zkoss.org/wiki/ZK_Developer%27s_Guide/ZK_in_Depth/Inter_Page,_App_Communication/Inter-Page_Communication
CC-MAIN-2021-43
refinedweb
311
52.26
Yes, the jargon here is terrible. Likely for legacy reasons. (Although I can’t think of which ones exactly? I remember this being fuzzy way back in Maya 4.0) But, it isn’t true that the s hotkey puts a key on non-keyable attributes, can you confirm? s You should find all attributes in the channel box have a key, except for those three. But, as far as I know, only the s key respects this attribute. And the s key is mostly a wasted keyboard shortcut. (How often do you intend on keying every single keyable attribute?) More usable means disregards the non-keyable state (perhaps for the better). Shift + wstill keys translateY and translateZ, regardless of their non-keyable state Key Selectedstill produces a key, again regardless of their non-keyable state. Some tools do respect the non-keyable state, like Edit -> Bake Simulation and creating a new animation layer. So, unlike the locked state the non-keyable state is more of a hint. Some metadata that tools may choose whether or not to respect, with a slight hint in the channel box for the animator that the attribute isn’t intended to be keyed. With that in mind, one way of making a channel 100% unkeyable is by making it locked, although that typically isn’t a practical use for the locked state. Another is by making it un-connectable, since a keyed channel is merely one that is connected to a keyframe node, like animCurveTL. I wasn’t able to find a way of doing this via cmds, maybe someone else knows? from maya.api import OpenMaya as om cmds.file(new=True, force=True) cube, _ = cmds.polyCube() sl = om.MSelectionList() sl.add(cube) mobj = sl.getDependNode(0) fn = om.MFnDependencyNode(mobj) plug = fn.findPlug("translateX", False) plug.name() fna = om.MFnAttribute(plug.attribute()) fna.connectable = False cmds.setKeyframe(v=10, at="translateX") # Fail! The API does sometime allow metadata like this to be edited without actually being able to save it with the scene (e.g. MFnAttribute.setNiceNameOverride), especially not for native plugs like this one. But this does appear to save and load fine. This would make an attribute truly non-keyable, whilst still allowing it to be edited (unlike a locked attribute). -- You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group. To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com. To view this discussion on the web visit. The solution whould be set connectable to False, but the problem is that if you close maya and open a new session it reverts it to keyable, so it doesn’t really save if you close your session. Ah that’s a bummer. Now that I think of it, that’s what happens to setNiceNameOverride too, even when editing your own custom attributes. Quite misleading. I expect those properties are solely meant for creating new attributes rather than editing existing ones. The translate attributes are probably special since they are native and not plug-in based, but the closest similarity might be to extension attributes. Which I understand as a kind of “instanced” attribute. To view this discussion on the web visit. To view this discussion on the web visit. It would be fickle, because what does “keyable” mean? In Maya, an attribute of one node can connect to an attribute of another node. Sometimes, that other node is a animCurveTL which we then perceive as being “keyed”. But there’s nothing differentiating the animCurveTL.output attribute from a someTransform.translateX attribute. So, it would have to be completely unconnectable. But that means it also cannot be simply driven by another attribute, like an animation control. It would be very limiting. What maybe could happen though, is for that right-click menu and Shift + w to respect the non-keyable state. And that may be doable. Ideally by Autodesk, but even by us as both of those are (probably?) MEL commands that can be overridden post-launch. Anyone care to take a crack at it? To view this discussion on the web visit.
https://groups.google.com/g/python_inside_maya/c/zkif__yPqf0
CC-MAIN-2022-33
refinedweb
699
68.16
Jakub, On Tue, Jul 26, 2011 at 06:28:23PM +0200, Jakub Wilk wrote: > * Adam Borowski <kilobyte@angband.pl>, 2011-07-26, 15:24: > >>. > >> > >>Did you verify that your new d/rules does everything that the > >>old one did? > > > >Yes, actually it does a bit more: the old one failed to install > >the upstream changelog. > > FWIW, that's because of bumping debheleper compat to 7. > > >I just checked that it cross-builds correctly too, dh is smart > >enough to disable the testsuite on cross builds like the old > >d/rules did. > > What raised my suspicion was that that the old d/rules had: > > | ifneq "$(wildcard /usr/share/misc/config.sub)" "" > | cp -f /usr/share/misc/config.sub config.sub > | endif > | ifneq "$(wildcard /usr/share/misc/config.guess)" "" > | cp -f /usr/share/misc/config.guess config.guess > | endif > > dh certainly doesn't do anything like that. Granted, this code was > silly[0] and, in this particular case, completely unnecessary[1], > but I'd prefer to learn about such changes from the changelog. On the contrary! dh can very well do such things! But it's required to pass --with autotools_dev as argument (see man dh for more detail). Regarding the rest I'm perfectly with you that all intended changes are to be documented in debian/changelog even if they're abbreviated in a form like "bump all of debian/compat and Build-Depends and debian/copyright to latest standards" or something like this. But it needs to be clear that any change a DD can find in the debdiff is valid and intentionally put there. -- Best regards, Kilian Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-mentors/2011/07/msg00552.html
CC-MAIN-2018-22
refinedweb
274
67.55
Interface Segregation Principle If I don't care about it, don't make me implement it! The interface segregation principle simply dictates that you design your interfaces with the other principles in mind. Instead of creating a bloated interface, interfaces should be segregated into cohesive units of functionality. This way the implementation of the interface can focus on what is important for that class. To better illustrate this, consider a data access class. One common approach might be to interface that class, and declare methods for loading, saving, updating, deleting, searching, performing a list, a security check, and who-knows-what-else. You could then create a concrete class that implemented this interface. The result is a fat interface that does everything the class needs, but doesn't necessarily allow for appropriate scaling. Another example is the use of an ORM like NHibernate. Perhaps your company decides this is useful for the basic CRUD operations (create, read, update, delete) but that LINQ to SQL or some other framework will be used for the complex searches and sorts. With one large, "IWidgetDataAccess" interface, you would have to implement all of the method signatures, even if you really only did something concrete to the CRUD pieces. A common practice is to do this: void MethodNotUsed() { throw new NotImplementedException(); } If you find yourself throwing this exception, it's a pretty good sign you are not following the interface segregation principle. A better approach would be to break out two different interfaces. One interface is your standard CRUD interface, call it "ICrud" and the other is the specific set of methods for the class ("IWidget"). Then you could implement your ICrud pieces with the concrete NHibernate instance, and save the IWidget for a different concrete class. This really comes back to the Liskov substitution principle. I don't want to pollute my IUser interface with methods for an administrator, otherwise everyone has to implement the method signature (even if simply to throw a NotImplementedException). With interface segregation, I can have IUser and IAdminUser and then my AdminUser would implement both: public class AdminUser : BaseUser, IUser, IAdminUser In summary, the interface should be fine-grained and focused on the client class that will implement the interface, rather than fat and bloated covering every possibility. Dependency Injection or Inversion of Control Depend on abstraction, not concreteness. This final principle is very popular but not well understood. I see lots of discussion about dependency injection and inversion of control, but it all seems centered on the frameworks that implement it (such as StructureMap, Unity, Spring.NET, and so forth) rather than the principle itself. Like many of the other SOLID and DRY principles, this one does not stand alone but ties into the other principles as well. The idea is rooted back in our "Single Responsibility." Once again, let's take an example. I am writing my data access class and for troubleshooting, I want to log issues. I decide that I'm going to use log4net and so I configure everything that I need and then start writing out logging information in my class. At this point I've violated "single responsibility" because my class isn't doing one thing (data access), it's responsible for two things (data access and logging). If I continue down this path I'll end up with dozens or even hundreds of classes with log4net logging embedded in them. Then I get the notice from the powers that be that we cannot use any type of open source in our project. We decide to shift to Enterprise Library. Now I've got my work cut out for me because I depended so much on my concrete logging implementation that I have to touch every class. By focusing on abstractions, I could instead have allowed for an ILogger interface and coded to that. I no longer make my class responsible for logging, instead it simply takes in the abstraction of a logger interface (ILogger) and depends on something else to make it concrete. This is where "dependency injection" comes from: the dependency on the concrete implementation is injected by something else. This also explains what "inversion of control" is - instead of my class being in control of logging, I invert that control and let something higher up the chain decide. For a more detailed explanation of dependency injection, read Simplified Mocking with Dependency Injection. As I mention in that article, DI does not require a framework. Taking the logging example, I could easily do this at the beginning, when I think, "We're going to use log4net, but let me go ahead and follow some solid object-oriented design principles and abstract it just in case." public class Widget { private ILogger _logger; public Widget() { _logger = LoggerFactory.GetLogger(); } public Widget(ILogger logger) { _logger = logger; } ... } public static class LoggerFactory { public static ILogger GetLogger() { return new Log4NetLogger(); } } As you can see, no framework is required. My classes work fine without anything knowing what to inject, but they make a constructor available anyway so if I do decide to move to configuration or a framework, I can do so. I use the factory pattern to get the logger. Again, we're hardcoded right now. But now I have possibilities. If I switch to Enterprise Library, for example, I only have to go to one place to change the concrete instance of my logger. Furthermore, I might want to have my logs Debug.Print during testing, in which case I create my custom DebugLogger that uses Debug.Print and inject that for testing. Summary These concepts are by no means "programming law" and there are many variations. I also didn't intend this to be a comprehensive discussion of the principles, but hopefully have touched on the surface and generated enough interest and curiosity for those not familiar to begin more research and apply these methods to their own software. In my opinion, you can give complex names to certain concepts or come up with new "architectures" or "design patterns" but in the end, it's about getting back to the basics and continuing to write simple, modular, easy to read and understand, maintainable code that works as building blocks for more powerful applications. codeprojectcodeproject
http://csharperimage.jeremylikness.com/2009/05/solid-and-dry-part-2.html
CC-MAIN-2016-40
refinedweb
1,039
52.09
This Pydon't will teach you how to use Python's conditional expressions. (If you are new here and have no idea what a Pydon't is, you may want to read the Pydon't Manifesto.) Conditional expressions are what Python has closest to what is called a “ternary operator” in other languages. In this Pydon't, you will: if: ... elif: ... else:statements and conditional expressions; You can now get your free copy of the ebook “Pydon'ts – Write beautiful Python code” on Gumroad to help support the series of “Pydon't” articles 💪. A conditional expression in Python is an expression (in other words, a piece of code that evaluates to a result) whose value depends on a condition. To make it clearer, here is an example of a Python expression: >>> 3 + 4 * 5 23 The code 3 + 4 * 5 is an expression, and that expression evaluates to 23. Some pieces of code are not expressions. For example, pass is not an expression because it does not evaluate to a result. pass is just a statement, it does not “have” or “evaluate to” any result. This might be odd (or not!) but to help you figure out if something is an expression or not, try sticking it inside a >>> print(3 + 4 * 5) 23 >>> print(pass) File "<stdin>", line 1 print(pass) ^ SyntaxError: invalid syntax The syntactic error here is that the statement pass cannot go inside the pass gives nothing. We are very used to using if statements to run pieces of code when certain conditions are met. Rewording that, a condition can dictate what piece(s) of code run. In conditional expressions, we will use a condition to change the value to which the expression evaluates. Wait, isn't this the same as an if statement? No! Statements and expressions are not the same thing. Instead of beating around the bush, let me just show you the anatomy of a conditional expression: expr_if_true if condition else expr_if_false A conditional expression is composed of three sub-expressions and the keywords if and else. None of these components are optional. All of them have to be present. How does this work? First, condition is evaluated. Then, depending on whether condition evaluates to Truthy or Falsy, the expression evaluates expr_if_true or expr_if_false, respectively. As you may be guessing from the names, expr_if_true and expr_if_false can themselves be expressions. This means they can be simple literal values like 42 or "spam", or other “complicated” expressions. (Heck, the expressions in conditional expressions can even be other conditional expressions! Keep reading for that 😉) Here are a couple of simple examples, broken down according to the expr_if_true, condition, and expr_if_false anatomy presented above. 1. >>> 42 if True else 0 42 2. >>> 42 if False else 0 0 3. >>> "Mathspp".lower() if pow(3, 27, 10) > 5 else "Oh boy." 'mathspp' For reference: >>> pow(3, 27, 10) 7 While the conditional expression presents the operands in an order that may throw some of you off, it is easy to read it as an English sentence. Take this reference conditional expression: value if condition else other_value Here are two possible English “translations” of the conditional expression: “Evaluate to valueif conditionis true, otherwise evaluate to other_value.” or “Give valueif conditionis true and other_valueotherwise.” With this out of the way, ... Many languages have a ternary operator that looks like condition ? expr_if_true : expr_if_false. Python does not have such a ternary operator, but conditional expressions are similar. Conditional expressions are similar in that they evaluate one of two values, but they are syntactically different because they use keywords (instead of ? and :) and because the order of the operands is different. The rationale behind conditional expressions is simple to understand: programmers are often faced with a situation where they have to pick one of two values. That's just it. Whenever you find yourself having to choose between one value or another, typically inside an if: ... else: ... block, that might be a good use-case for a conditional expression. ifstatements Here are some simple functions that show that: def parity(n): if n % 2: return "odd" else: return "even" >>> parity(15) "odd" >>> parity(42) "even" def abs(x): if x > 0: return x else: return -x >>> abs(10) 10 >>> abs(-42) 42 These two functions have a structure that is very similar: they check a condition and return a given value if the condition evaluates to True. If it doesn't, they return a different value. Can you refactor the functions above to use conditional expressions? Here is one possible refactoring for each: def parity(n): return "odd" if n % 2 else "even" This function now reads as “return "odd"if nleaves remainder when divided by 2and "even"otherwise.” As for the absolute value function, def abs(n): return x if x > 0 else -x it now reads as “return xif xis positive, otherwise return -x.” You may be familiar with Boolean short-circuiting, in which case you might be pleased to know that conditional expressions also short-circuit. For those of you who don't know Boolean short-circuiting yet, I can recommend my thorough Pydon't article on the subject. Either way, it's something to understand for our conditional expressions: a conditional expression will only evaluate what it really has to. In other words, if your conditional expression looks like expr_if_true if condition else expr_if_false then only one of expr_if_true and expr_if_false is ever evaluated. This might look silly to point out, but is actually quite important. Some times, we might want to do something ( expr_if_true) that only works if a certain condition is met. For example, say we want to implement the quad-UCS function from APL. That function is simple to explain: it converts integers into characters and characters into integers. In Python-speak, it just uses chr and ord, whatever makes sense on the input. Here is an example implementation: def ucs(x): if isinstance(x, int): return chr(x) else: return ord(x) >>> ucs("A") 65 >>> ucs(65) 'A >>> ucs(102) 'f' >>> ucs("f") 102 What isn't clear from this piece of code is that ord throws an error when called on integers, and chr fails when called on characters: >>> ord(65) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ord() expected string of length 1, but int found >>> chr("f") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: an integer is required (got type str) Thankfully, this is not a problem for conditional expressions, and therefore ucs can be implemented with one: def ucs(x): return chr(x) if isinstance(x, int) else ord(x) >>> ucs("A") 65 >>> ucs(65) 'A >>> ucs(102) 'f' >>> ucs("f") 102 Therefore, we see that when x is an integer, ord(x) never runs. On the flip side, when x is not an integer, chr(x) never runs. This is a very useful subtlety! ifstatements if This has been implicit throughout the article, but I'll write it down explicitly now for the sake of clarity. (And also because “Explicit is better than implicit.” 😁!) There is a close relationship between the conditional expression name = expr_if_true if condition else expr_if_false and the if statement if condition: name = expr_if_true else: name = expr_if_false And that close relationship is that of equivalence. The two pieces of code are exactly equivalent. if- elif- elseblocks Given the equivalence between conditional expressions and if: ... else: ... blocks, it is natural to wonder whether there is some equivalent to the elif statement in conditional expressions as well. For example, can we rewrite the following function to use a conditional expression? def sign(x): if x == 0: return 0 elif x > 0: return 1 else: return -1 >>> sign(-73) -1 >>> sign(0) 0 >>> sign(42) 1 How can we write this as a conditional expression? Conditional expressions do not allow the usage of the elif keyword so, instead, we start by reworking the if block itself: def sign(x): if x == 0: return 0 else: if x > 0: return 1 else: return -1 This isn't a great implementation, but this intermediate representation makes it clearer that the bottom of the if block can be replaced with a conditional expression: def sign(x): if x == 0: return 0 else: return 1 if x > 0 else -1 Now, if we abstract away from the fact that the second return value is a conditional expression itself, we can rewrite the existing if block as a conditional expression: def sign(x): return 0 if x == 0 else (1 if x > 0 else -1) >>> sign(-73) -1 >>> sign(0) 0 >>> sign(42) 1 This shows that conditional expressions can be nested, naturally. Now it is just a matter of checking whether the parenthesis are needed or not. In other words, if we write A if B else C if D else E does Python interpret it as (A if B else C) if D else E or does it interpret it as A if B else (C if D else E) As it turns out, it's the latter. So, the sign function above can be rewritten as def sign(x): return 0 if x == 0 else 1 if x > 0 else -1 It's this chain of if ... else ... if ... else ... – that can be arbitrarily long – that emulates elifs. To convert from a long if block (with or without elifs) to a conditional expression, go from top to bottom and interleave values and conditions, alternating between the keyword if and the keyword else. When reading this aloud in English, the word “otherwise” helps clarify what the longer conditional expressions mean: return 0 if x == 0 else 1 if x > 0 else -1 reads as “return 0 if x is 0, otherwise, return 1 if x is positive otherwise return -1.” The repetition of the word “otherwise” becomes cumbersome, a good indicator that it is generally not a good idea to get carried away and chaining several conditional expressions. For reference, here's a “side-by-side” comparison of the first conditional block and the final conditional expression: # Compare if x == 0: return 0 elif x > 0: return 1 else: return -1 # to: return 0 if x == 0 else 1 if x > 0 else -1 Because of the equivalence I just showed, many people may then believe that conditional expressions could be implemented as a function enclosing the previous if: ... else: ... block: def cond(condition, value_if_true, value_if_false): if condition: return value_if_true else: return value_if_false With this definition, we might think we have implemented conditional expressions: >>> cond(pow(3, 27, 10) > 5, "Mathspp".lower(), "Oh boy.") 'mathspp' >>> "Mathspp".lower() if pow(3, 27, 10) > 5 else "Oh boy." 'mathspp' In fact, we haven't! That's because the function call to cond only happens after we have evaluated all the arguments. This is different from what conditional expressions really do: as I showed above, conditional expressions only evaluate the expression they need. Hence, we can't use this cond to implement ucs: def ucs(x): return cond(isinstance(x, int), chr(x), ord(x)) This code looks sane, but it won't behave like we would like: >>> ucs(65) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in ucs TypeError: ord() expected string of length 1, but int found When given 65, the first argument evaluates to True, and the second argument evaluates to "A", but the third argument raises an error! Conditional expressions are the expressions with lowest precedence, according to the documentation. This means that sometimes you may need to parenthesise a conditional expression if you are using it inside another expression. For example, take a look at this function: def foo(n, b): if b: to_add = 10 else: to_add = -10 return n + to_add >>> foo(42, True) 52 >>> foo(42, False) 32 You might spot the pattern of assigning one of two values, and decide to use a conditional expression: def foo(n, b): to_add = 10 if b else -10 return n + to_add >>> foo(42, True) 52 >>> foo(42, False) 32 But then, you decide there is no need to waste a line here, and you decide to inline the conditional expression (that is, you put the conditional expression inside the arithmetic expression with n +): def foo(n, b): return n + 10 if b else -10 By doing this, you suddenly break the function when b is False: >>> foo(42, False) -10 That's because the expression n + 10 if b else -10 is seen by Python as (n + 10) if b else -10 while you meant for it to mean n + (10 if b else -10) In other words, and in not-so-rigourous terms, the + “pulled” the neighbouring 10 and it's the whole n + 10 that is seen as the expression to evaluate if the condition evaluates to Truthy. Before showing good usage examples of conditional expressions, let me just go ahead and show you something you should avoid when using conditional expressions Conditional expressions are suboptimal when they evaluate to Boolean values. Here is a silly example: def is_huge(n): return True if n > pow(10, 10) else False Can you see what is wrong with this implementation of is_huge? This function might look really good, because it is short and readable, and its behaviour is clear: >>> is_huge(3.1415) False >>> is_huge(999) False >>> is_huge(73_324_634_325_242) True However... The conditional expression isn't doing anything relevant! The conditional expression just evaluates to the same value as the condition itself! Take a close look at the function. If n > pow(10, 10) evaluates to True, then we return True. If n > pow(10, 10) evaluates to False, then we return False. Here is a short table summarising this information: So, if the value of n > pow(10, 10) is the same as the thing we return, why don't we just return n > pow(10, 10)? In fact, that's what we should do: def is_huge(n): return n > pow(10, 10) Take this with you: never use if: ... else: ... or conditional expressions to evaluate to/return Boolean values. Often, it suffices to work with the condition alone. A related use case where conditional expressions shouldn't be used is when assigning default values to variables. Some of these default values can be assigned with Boolean short-circuiting, using the or operator. Here are a couple of examples where conditional expressions shine. You will notice that these examples aren't particularly complicated or require much context to understand the mechanics of what is happening. That's because the rationale behind conditional expressions is simple: pick between two values. .getmethod The collections has a ChainMap class. This can be used to chain several dictionaries together, as I've shown in a tweet in the past: In #Python, you can use `collections.ChainMap` to create a larger mapping out of several other maps. Useful, for example, when you want to juxtapose user configurations with default configurations.— Rodrigo 🐍📝 (@mathsppblog) June 4, 2021 Follow for more #tips about Python 🐍#learnpython #learncode #100daysofcode pic.twitter.com/ip9IInItYG What's interesting is that ChainMap also defines a .get method, much like a dictionary. The .get method tries to retrieve a key and returns a default value if it finds it: >>> from collections import ChainMap >>> user_config = {"name": "mathspp"} >>> default_config = {"name": "<noname>", "fullscreen": True} # Access a key directly: >>> config["fullscreen"] True # config["darkmode"] would've failed with a KeyError. >>> config.get("darkmode", False) False Here is the full implementation of the .get method: # From Lib/collections/__init__.py in Python 3.9.2 class ChainMap(_collections_abc.MutableMapping): # ... def get(self, key, default=None): return self[key] if key in self else default Simple! Return the value associated with the key if key is in the dictionary, otherwise return the default value! Just that. The module pathlib is great when you need to deal with paths. One of the functionalities provided is the .resolve method, that takes a path and makes it absolute, getting rid of symlinks along the way: # Running this from C:/Users/rodri: >>> Path("..").resolve() WindowsPath('C:/Users') # The current working directory is irrelevant here: >>> Path("C:/Users").resolve() WindowsPath('C:/Users') Here is part of the code that resolves paths: # In Lib/pathlib.py from Python 3.9.2 class _PosixFlavour(_Flavour): # ... def resolve(self, path, strict=False): # ... base = '' if path.is_absolute() else os.getcwd() return _resolve(base, str(path)) or sep As you can see, before calling the auxiliary function _resolve and returning, the function figures out if there is a need to add a base to the path. If the path I enter is relative, like the ".." path above, then the base is set to be the current working directory ( os.getcwd()). If the path is absolute, then there is no need for a base, because it is already there. Here's the main takeaway of this Pydon't, for you, on a silver platter: “Conditional expressions excel at evaluating to one of two distinct values, depending on the value of a condition.” This Pydon't showed you that: ifand elsekeywords; if: ... elif: ... else: ...blocks;. collections.ChainMap, [last accessed 28-09-2021]; pathlib.Path.resolve, [last accessed 28-09-2021];
https://mathspp.com/blog/pydonts/conditional-expressions
CC-MAIN-2022-05
refinedweb
2,875
59.84
NVS Partition Parser Utility Introduction The utility nvs_flash/nvs_partition_parser/nvs_read.py loads and parses an NVS storage partition for easier debugging and data extraction. The utility also features integrity check which scans the partition for potential errors. Encrypted Partitions This utility does not support decryption. To decrypt the NVS partition, please use the NVS Partition Generator Utility which does support NVS partition encryption and decryption. Usage - The utility provides six different output styles with -d or –dump option: all (default) - Prints all entries with metadata. written - Prints only written entries with metadata. minimal - Prints written namespace:key = value pairs. namespaces - Prints all written namespaces blobs - Prints all blobs and strings (reconstructs them if they are chunked). storage_info - Prints entry states count for every page. Note There is also a none option which will not print anything. This can be used with the integrity check option if the NVS partition contents are irrelevant. The utility also provides an integrity check feature via the -i or –integrity-check option. This feature scans through the entire partition and prints potential errors. It can be used with the -d none option which will print only the potential errors.
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/nvs_partition_parse.html
CC-MAIN-2022-40
refinedweb
194
50.23
I wrote a module that traps $SIG{__DIE__} and $SIG{__WARN__} and send an email using Mail::Mailer. I called it Carp::Mailer, but I'm not sure how name it. Is Carp::Mailer ok, or does anybody has a best name? Igor 'izut' Sutton your code, your rules. How is this related to Carp? Other than trapping signals, does it otherwise improve upon the existing Carp::Notify? Could it be done as a patch to Carp::Notify or should it be an extension, e.g. Carp::Notify::Signals? -xdg Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk. Well, I checked Carp::Notify but it modifies or add other features to Carp. Actually I don't know what 'Carp' stands for. The module traps $SIG{__DIE__} and $SIG{__WARN__} and sends an email to someone. It works with Carp and raw die and warn messages. If its usage dos not apply in Carp namespace, could you suggest another? Is it a mailer that carps? (Mailer::Carp) Or is it a carper that mails? (Carp::Mailer) If it's primary objective is to be a mailer, and that mailer is different from other mailers in that it carps (complains) if there's trouble, I would think Mailer::Carp is more appropriate. If it's a carper (complainer) that mails its complaint, it would be more appropriately named Carp::Mailer. Dave It is a module will send an email to someone when it complains about a die and warn. It will send an email containing complete stack when using Carp. I think it really should be named Carp::Mailer, then. Thank you all. Hell yes! Definitely not I guess so I guess not Results (58 votes), past polls
http://www.perlmonks.org/?node_id=533549
CC-MAIN-2014-52
refinedweb
319
76.42
So, lets imagine that you are using Xamarin do develop some Apps that will targeting Android, iOS and Windows 8.1 devices, now lets imagine also that due to security concerns you will need to use TLS 1.2 for all these three platforms. If you do a quick research on the Web you will find that iOS does this out-of-box, in Android you could rely on the ModernHTTPClient to achieve this, but for Windows 8.1 seems that there is no way to implement this type of security requirement. But if you think about it, the solution is there for grabs, we just need to think a little about what we already have in .NET. In fact the solution here would be much obvious than you will think, if you take a look at the "Windows.Web.Http" namespace you can see that in fact "Windows.Web.Http" wraps WinInet which uses TLS 1.2 unless the system is specifically configured otherwise. And that is it, your solution right there for you, all you need to do is just make a HTTPClient call to a TLS1.2 site using the Windows.Web.Http. You can learn more about this class in the below article: Hope that helps
https://blogs.msdn.microsoft.com/whereismysolution/2017/11/01/605/
CC-MAIN-2017-47
refinedweb
210
81.43
Created on 2017-09-30 23:04 by Dandan Lee, last changed 2020-03-05 16:50 by Alexander Stohr. This issue is now closed. The make install step fails with this error: Traceback (most recent call last): File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/ensurepip/__main__.py", line 4, in <module> ensurepip._main() File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/ensurepip/__init__.py", line 189, in _main default_pip=args.default_pip, File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/ensurepip/__init__.py", line 102, in bootstrap _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/ensurepip/__init__.py", line 27, in _run_pip import pip File "/tmp/tmpcg658x_c/pip-9.0.1-py2.py3-none-any.whl/pip/__init__.py", line 28, in <module> File "/tmp/tmpcg658x_c/pip-9.0.1-py2.py3-none-any.whl/pip/vcs/mercurial.py", line 9, in <module> File "/tmp/tmpcg658x_c/pip-9.0.1-py2.py3-none-any.whl/pip/download.py", line 36, in <module> File "/tmp/tmpcg658x_c/pip-9.0.1-py2.py3-none-any.whl/pip/utils/glibc.py", line 4, in <module> File "/home/dandan/Downloads/cpython-3.7.0a1/Lib/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' Makefile:1080: recipe for target 'install' failed make: *** [install] Error 1 Am I missing something? I expect that the root cause is missing libffi(-dev[el]) on your system, preventing _ctypes from building, so your quick fix would be to install that and try again. However, not having _ctypes shouldn't cause installation to fail. Donald, is ctypes a hard requirement for pip to install itself? If so, ensurepip as called by `make install` should either gracefully handle a lack of ctypes or be disabled when ctypes is not available. Confirming that this is still failing with 3.7.0 released. In <> Chi-Hsuan suggests “configure --without-ensurepip” as a workaround. > I expect that the root cause is missing libffi(-dev[el]) on your system Yes, on my Ubuntu 18.04, `make` failed to compile _ctypes module. After install libffi-dev, it was compiled successfully: One more word, full necessary dependencies on my Ubuntu 18.04: sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev Similar error on CentOS 7 ModuleNotFoundError: No module named '_ctypes' Install -- yum install libffi-devel Repeat: ./configure --enable-optimizations make altinstall Results: Collecting setuptools Collecting pip Installing collected packages: setuptools, pip Successfully installed pip-10.0.1 setuptools-39.0.1 NOTE: The error did not stop python3.7 from operating as noted on this page. # python3.7 Python 3.7.0 (default, Jul 16 2018, 11:25:12) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print ("Hello Python") Hello Python >>> I'm getting the same error File "/usr/src/Python-3.7.0/Lib/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' Makefile:1122: recipe for target 'install' failed make: *** [install] Error 1 Linux Mint 19 Hi All, Iam using centos 7. And as mentioned in this thread, though this error came, Iam able to go to python3.7 interpreter fine. However, when i wanted to install pip, I get the same _ctype error as below. So, I think, this needs to be resolved in order to use python3.7 in centos. File "get-pip.py", line 20651, in <module> main() File "get-pip.py", line 197, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip._internal File "/tmp/tmpu88jadkc/pip.zip/pip/_internal/__init__.py", line 42, in <module> File "/tmp/tmpu88jadkc/pip.zip/pip/_internal/cmdoptions.py", line 16, in <module> File "/tmp/tmpu88jadkc/pip.zip/pip/_internal/index.py", line 24, in <module> File "/tmp/tmpu88jadkc/pip.zip/pip/_internal/download.py", line 38, in <module> File "/tmp/tmpu88jadkc/pip.zip/pip/_internal/utils/glibc.py", line 3, in <module> File "/usr/local/lib/python3.7/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' Looking for advice. As mentioned before, this is due to missing libffi-devel on a Centos 7 system. Verified it as well on one of my systems. Could you try again, but before just do a 'yum install libffi-devel'? Maybe a warning could be added to the install output when it can't find libffi. Linux Mint 19.1 sudo make altinstall Traceback (most recent call last): File "/usr/src/Python-3.7.2/Lib/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/src/Python-3.7.2/Lib/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/src/Python-3.7.2/Lib/ensurepip/__main__.py", line 5, in <module> sys.exit(ensurepip._main()) File "/usr/src/Python-3.7.2/Lib/ensurepip/__init__.py", line 204, in _main default_pip=args.default_pip, File "/usr/src/Python-3.7.2/Lib/ensurepip/__init__.py", line 117, in _bootstrap return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) File "/usr/src/Python-3.7.2/Lib/ensurepip/__init__.py", line 27, in _run_pip import pip._internal File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/__init__.py", line 40, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/cli/autocompletion.py", line 8, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/cli/main_parser.py", line 12, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/commands/__init__.py", line 6, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/commands/completion.py", line 6, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/cli/base_command.py", line 18, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/download.py", line 38, in <module> File "/tmp/tmpc5nmmwk0/pip-18.1-py2.py3-none-any.whl/pip/_internal/utils/glibc.py", line 3, in <module> File "/usr/src/Python-3.7.2/Lib/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' Makefile:1140: recipe for target 'altinstall' failed make: *** [altinstall] Error 1 In case this helps: I noticed this during the build: *** WARNING: renaming "_ssl" since importing it failed: ld.so.1: python: fatal: libssl.so.1.1: open failed: No such file or directory *** WARNING: renaming "_hashlib" since importing it failed: ld.so.1: python: fatal: libssl.so.1.1: open failed: No such file or directory *** WARNING: renaming "_ctypes" since importing it failed: ld.so.1: python: fatal: libffi.so.6: open failed: No such file or directory ... Following modules built successfully but were removed because they could not be imported: _ctypes _hashlib _ssl In my case the reason was that libffi was installed under /opt/local, so the fix was: ./configure LDFLAGS='-L/opt/local/lib -R/opt/local/lib' and rebuild For other users I would recommend to inspect the build output for _ctypes related errors, I am not saying that the cause is the same Installing libffi-dev worked for me. Ubuntu 16.04 in a very bare naked setup. Similar/same problem profile by message and other lines in the log. Installed libffi6 and libffi-dev => worked. Not sure if both were needed (or interdependent, 2nd to 1st).
https://bugs.python.org/issue31652
CC-MAIN-2021-39
refinedweb
1,333
52.66
Accessing image metadata: storing tags inside the image file A recent Slashdot discussion on image tagging and organization a while back got me thinking about putting image tags inside each image, in its metadata. Currently, I use my MetaPho image tagger to update a file named Tags in the same directory as the images I'm tagging. Then I have a script called fotogr that searches for combinations of tags in these Tags files. That works fine. But I have occasionally wondered if I should also be saving tags inside the images themselves, in case I ever want compatibility with other programs. I decided I should at least figure out how that would work, in case I want to add it to MetaPho. I thought it would be simple -- add some sort of key in the images's EXIF tags. But no -- EXIF has no provision for tags or keywords. But JPEG (and some other formats) supports lots of tags besides EXIF. Was it one of the XMP tags? Web searching only increased my confusion; it seems that there is no standard for this, but there have been lots of pseudo-standards over the years. It's not clear what tag most programs read, but my impression is that the most common is the "Keywords" IPTC tag. Okay. So how would I read or change that from a Python program? Lots of Python libraries can read EXIF tags, including Python's own PIL library -- I even wrote a few years ago about reading EXIF from PIL. But writing it is another story. Nearly everybody points to pyexiv2, a fairly mature library that even has a well-written pyexiv2 tutorial. Great! The only problem with it is that the pyexiv2 front page has a big red Deprecation warning saying that it's being replaced by GExiv2. With a link that goes to a nonexistent page; and Debian doesn't seem to have a package for GExiv2, nor could I find a tutorial on it anywhere. Sigh. I have to say that pyexiv2 sounds like a much better bet for now even if it is supposedly deprecated. Following the tutorial, I was able to whip up a little proof of concept that can look for an IPTC Keywords tag in an existing image, print out its value, add new tags to it and write it back to the file. import sys import pyexiv2 if len(sys.argv) < 2: print "Usage:", sys.argv[0], "imagename.jpg [tag ...]" sys.exit(1) metadata = pyexiv2.ImageMetadata(sys.argv[1]) metadata.read() newkeywords = sys.argv[2:] keyword_tag = 'Iptc.Application2.Keywords' if keyword_tag in metadata.iptc_keys: tag = metadata[keyword_tag] oldkeywords = tag.value print "Existing keywords:", oldkeywords if not newkeywords: sys.exit(0) for newkey in newkeywords: oldkeywords.append(newkey) tag.value = oldkeywords else: print "No IPTC keywords set yet" if not newkeywords: sys.exit(0) metadata[keyword_tag] = pyexiv2.IptcTag(keyword_tag, newkeywords) tag = metadata[keyword_tag] print "New keywords:", tag.value metadata.write() Does that mean I'm immediately adding it to MetaPho? No. To be honest, I'm not sure I care very much, since I don't have any other software that uses that IPTC field and no other MetaPho user has ever asked for it. But it's nice to know that if I ever have a reason to add it, I can. [ 10:28 Jan 08, 2015 More photo | permalink to this entry | comments ]
http://shallowsky.com/blog/photo/image-tagging-with-metadata.html
CC-MAIN-2019-13
refinedweb
568
65.22
Polymorphic Data Structures in C/Pointers Pointers are one of the most essential constructs in C. A pointer is a variable that stores the address (in memory) of another variable for reference by a function. Through the use of pointers, we are able to achieve a higher level of data manipulation, since modifying static variables in functions outside the ones that created them is not supported by any algorithm developed in C. Contents Simple Pointer Operations[edit] Developers can explicitly declare pointers using the pointer operator (*): int *p_int ; The standard convention used in this book is to append the variable being pointed to with "p_" to designate its status as a pointer. This is helpful when there are multiple variables of the same apparent type in a function, where some are pointers and some are not. In order to access the information pointed to by a pointer, a programmer must use the dereference operator (also the asterisk) to denote the reference. printf( "%d" , *p_int ) ; If a variable is not a pointer, but needs to be modified inside a called function, then the address-of operator (&) can be used to create an "on-the-fly" pointer that is passed to the function. Many programmers understand that the scanf() function needs the address-of operator in front of the variables read into, but not all of them know why. It is because scanf() needs to affect the variable where the information is being stored. Pointers are usually used for keeping track of dynamically allocated memory. In this demonstration, the pointer is redundant, but it will illustrate the principles of pointers. #include <stdio.h> int main( int argc , char *argv[] ) { int i ; int *p_i = &i ; i = 5 ; printf( "%d " , i ) ; *p_i = 7 ; printf( "%d\n" , *p_i ) ; return 0 ; } First, an integer i is created as a static variable of main(). Then, the pointer p_i is created and its value is set to the address of i. Next, i is assigned the value of 5 and printed. Finally, the integer that p_i points to is assigned the value of 7 and printed. Notice the use of dereference and address-of operators. The proper use of pointer, dereference and address-of operators is key in an understanding of polymorphism. Dynamic Memory Allocation[edit] Perhaps the most important use of pointers is to keep track of memory that has been allocated dynamically (at run-time). Memory is allocated dynamically using the malloc() function. malloc() has one argument (the amount of space to be allocated, in bytes) and returns a pointer to a void, which is usually recast into a pointer to some other type. The challenge with dynamic memory allocation is that type sizes can be machine-dependent, meaning an integer on one computer may not be the same size in memory as an integer on another. To overcome this, C describes a sizeof operator which takes a type name as a parameter and returns the size, in bytes, of that type as an integer. For example, in order to dynamically allocate space in memory for one character, a developer would write: char *p_char ; p_char = (char *)malloc( sizeof ( char ) ) ; More complexly, dynamic memory allocation is usually used when the amount of space to be reserved is not known at the time of compilation. In the following program, the user is asked how many integers they would like to store, and stores them. #include <stdio.h> #include <stdlib.h> int main( int argc , char *argv[] ) { int i , amount , *p_int ; printf( "How many integers would you like to store? " ) ; scanf( "%d" , &amount ) ; p_int = (int *)malloc( sizeof ( int ) * amount ) ; printf( "Please enter %d integers, separated with a space, to store. " , amount ) ; for ( i = 0 ; i < amount ; i++ ) scanf( "%d" , p_int[i] ) ; for ( i = 0 ; i < amount ; i++ ) printf( "%d " , p_int[i] ) ; printf( "\n" ) ; return 0 ; } Notice how stdlib was included in the header. malloc() is declared in stdlib.h, so it has to be included along with stdio.h in programs that use it. Notice also how the space reserved by malloc() is referred to using the standard syntax for arrays. This is because malloc() reserves space sequentially (all in a row), so pointer arithmetic (discussed below) can be applied to it. In other words, when malloc() reserves space for more than one of a given type, it allocates space for an array of that type. Pointer Operations on Structures[edit] In addition to the standard member operator (.), ANSI C includes a different member operator symbol, ->. It performs two operations at the same time: it dereferences the structure name before the operator and evaluates its member (after the operator). This is helpful when using pointers to refer to the structure. Using the employee data structure from the previous chapter: struct employee_data *p_search ; p_search = (struct employee_data *)malloc( sizeof ( struct employee_data ) ) ; p_search -> address.name = "Ryan" ; (*p_search).address.name = "Ryan" ; The bottom two statements perform exactly the same operations. Because we will be working with pointers to structures for the majority of this book, the dereference-member operator will be used more often. Note that sub-members must still be referred to using the normal member operator. Using Pointers to Return Values[edit] Functions in C can only return one value. This is an unfortunate consequence of the procedural programming paradigm. However, sometimes multiple variables need to be changed. In order to do that, one must pass a pointer to that variable to the function called. For more on this topic, please refer to Appendix 1, Function Invocation. The information there is extremely valuable, make sure to go through it before moving on. The remainder of this book assumes that the reader has read and understands the contents of Appendix 1. Pointer Arithmetic[edit] Performing pointer arithmetic is a very simple concept, but a somewhat difficult practice. Performing pointer addition on arrays is done implicitly, with the subscript operators []. The following statement would return TRUE: int A[4] ; ( A[2] == *(A + 2) ) ; The addition to a pointer causes the reference address to be "moved forward" by the specified number of units, multiplied by the size of the type. So, &A[2] is the location of A[0], plus the size of two integers in memory (thus giving you the third item in the array, since arrays start indexing at 0). Pointer arithmetic can be applied to unions and structures as well, but this method is not used as often in favor of member referencing. Pointers to Functions[edit] A very powerful feature of the C language is the ability to take the address of a function and store it as a pointer. In this manner, one could theoretically write a function, then have that function call a different function that is known only at runtime (decreasing the amount of conditional programming needed). Every C programmer is familiar with the standard function declaration syntax: return_type function( parameter_1 , parameter_2 ... ) ; Similar to variables, functions are also typed. Assuming they are not of type void, all functions return data, and that data must have type. As a side effect of this structure, a programmer can declare pointers to functions. return_type (*p_function)( parameter_1 , parameter_2 ... ) ; This code can be used to execute any number of functions in the same line of code, demonstrated below in this text manipulation program. #include <stdio.h> void print_reverse( char *string ) ; void print_normal( char *string ) ; int main( int argc , char *argv[] ) { char input_string[32] ; int state , i ; void (*p_function)( char *string ) ; for ( i = 0 ; i < 32 ; i++ ) input_string[i] = '\0' ; printf( "Please enter a short line of text: " ) ; scanf( "%s" , input_string ) ; printf( "Would you like to print this string in reverse? 1 for yes, 0 for no. " ) ; scanf( "%d" , &state ) ; if ( state == 1 ) p_function = print_reverse ; else if ( state == 0 ) p_function = print_normal ; else { printf( "Error: Must enter 0 or 1. Exiting." ) ; exit 1; } p_function( input_string ) ; return 0 ; } void print_reverse( char *string ) { int i ; for ( i = 31 ; i >= 0 ; i-- ) { if ( string[i] != '\0' ) putchar( string[i] ) ; } printf( "\n" ) ; } void print_normal( char *string ) { int i = 0 ; while ( ( i < 32 ) && ( string[i] != '\0' ) ) { putchar( string[i] ) ; i++ ; } printf( "\n" ) ; } In this program, there are two functions, print_reverse() and print_normal(). One simply prints the string, and the other prints the string's contents out in reverse order. But the actual function call inside main() is the same in both cases: p_function( input_string ) ; This is made possible through C's ability to reference functions by pointers to that function, and to properly pass parameters to that function.
http://en.wikibooks.org/wiki/Polymorphic_Data_Structures_in_C/Pointers
CC-MAIN-2014-35
refinedweb
1,409
51.89
To reply to IBUS guy which is hiding behind some noreply adress… this is my third try to use katalon in my project in last six months. And YES I DID read the docs. And tried everything, and NO, it is NOT easy like in postman. If you do not want to help, stop mocking me. And YES, documentation SUCKS! To reply to IBUS guy which is hiding behind some noreply adress… have you searched the forum too? you may find some answers … amazing, katalon way is ${variable}.or … is the groovy way? you have exactly one post above you started the new one an example where i show what the previous OP done wrong. did you read it? Obviously I am not alone, and there is no example on how to do this… My profile has two variables: host (set as string to host01) and port (set as string to 9876)… that’s all… i tried REST API URL this ways: -{host}:${port}/rest/v1.0/administration/clusters -{GlobalVariable.host}:${GlobalVariable.port}/rest/v1.0/administration/clusters - … and everything else that came to my mind in last three installations of katalon. And it throws errors when called. I am pretty frustrated, as this should be easy, and I have no idea what I am doing wrong. As I canot put more that three replies (what a retarded rule), I have to edit previous reply and hope that someone see this: In profile, I set global variables g_bc and g_port. Then click send request. Error is: Cannot send the test request. Reason: For input string: “${g_port}”. java.net.MalformedURLException: For input string: “${g_port}” at com.kms.katalon.core.webservice.common.RestfulClient.sendRequest(RestfulClient.java:74) at com.kms.katalon.core.webservice.common.RestfulClient.send(RestfulClient.java:59) at com.kms.katalon.controller.WebServiceController.sendRequest(WebServiceController.java:121) at com.kms.katalon.composer.webservice.parts.RestServicePart$6.run(RestServicePart.java:187) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119) Caused by: java.lang.NumberFormatException: For input string: “${g_port}” … 5 more If I put port by number and hostname in URL, everything works. But using ${var} is not working. Well it finally worked, and I have no idea why it was not working before. I used again URL format I used in method 2: ${GlobalVariable.var} format, and now it works. This is really strange behavior. what errors did you get? did you set the appropiate headers in the request objects? or do you expect katalon to do all the ‘underhood magic’ for you? I’m having a related issue, attempting to authenticate to my API via parameters/variables A GET request: ${url}/authenticate?username=${username}&password=${password} ${url} and ${username} and ${password} are all variables of type String, the default values of which are all seemingly correct. My API returns: { “data”:null, “message”:“Required String parameter ‘password’ is not present”, “ok”:false } Which I find confusing. Any hints? The event log says this: 15:22:52.219 [ModalContext] INFO com.kms.katalon.core.webservice.common.HarLogger - HAR: C:\Users\awedd\AppData\Local\Temp\3\har8268017398050496001\requests\ModalContext\60.har Thu Sep 12 15:22:52 AEST 2019)) are the variables global (defined in profile) or local (declared in the request object)? @adrian.wedd ok, let’s take it step by step. we are going to use a free test api: So, kindly reproduce exactly my setup, see the pics: make an request object, set the headers, set the local variables and press the green ‘play’ button. you should get the same response: Once you confirm is working for you too, we move forward. Otherwise, you did something wrong … or you have connectivity issues. ** note also my katalon version, i am using 6.1.2. although not very important,check yours too to be sure we are almost on the same page. some versions were known to be buggy I’m running 6.3.3 and I suspect I have a connectivity issue: I’ll look into that. Interestingly 6.3.3 seems to think I had an illegal character in my url. Presumably “$”? switch to the ‘Variables Editor’ tab an post a complete screenshot. you may have a mistyping somewhere. 'api/users\r\n' Presumably my issue (aside from \r\n above) indeed looks to be connectivity. I’ll look at the firewall issue and get back to you tomorrow. Thanks for your hand-holding it’s ok, happened to me also … the implementation of the variables tab is not the best, if you press enter after you paste a string such issue may occur. once you figure out what is wrong with your networking we move forward to use globals Can i define the local variable like systemDate in Verifications tab and call it in HTTP json body? def date = new Date() sdf = new SimpleDateFormat(“YYYY-MM-dd”) def systemDate= sdf.format(date) In Json body: { … “due_date”:“${systemDate}” … } Do I define this variable under “Variables” tab to pull in my json body? if so, how do i define this as local variable? Wondering how to use the List variables within the Web Service Request. Do you call it like a string or do you have to write it different within the body? Is there a way to send a parameter as a boolean and not a string ? My case : where I type ${urlPassCollecte}/api/user-profil/${adh}?msgInfo=false as the request URL, Katalon generates “queryString” : [ { “name” : “msgInfo”, “value” : “false” } ] (with double-quotes around false value), casting i fact the boolean to a string value. The API under tests expects a boolean (the same QueryString without the double-quotes around false) and therefore answers an error to my request. Any clue ? Tanks in advance, an url in the end is just a string, no matter if some tools are able to split what is after ? as key=val parameters. looks for me like a bad designed API, it should be able to cast internally false | False | no | No into boolean What about including a dynamic variable within the URL of the GET? I have tried but it does not work. Included the variable in the test case: category_id, number, default value 0. GET URL/product/${category_id}.json WS.sendRequest(findTestObject(‘API/products’), [(‘category_id’) : categoryID]) It fails on the send request: Reason: groovy.lang.MissingMethodException: No signature of method: static com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords.sendRequest() is applicable for argument types: (com.kms.katalon.core.testobject.RequestObject, java.util.LinkedHashMap) values: [TestObject - ‘Object Repository/API/products’, [category_id:15]] Possible solutions: sendRequest(com.kms.katalon.core.testobject.RequestObject), sendRequest(com.kms.katalon.core.testobject.RequestObject, com.kms.katalon.core.model.FailureHandling) Any help? Thank you! hello, anybody knows a way to use a variable of type Map ? I don’t find a correct syntax to get my withPAPG value from my Map variable I tried ${params[‘withWCSParam’]}, ${params.withWCSParam}, $params.withWCSParam without achieving it compose this kind of url : GetGeekData?depositCode=CPE&activityCode=EPF&withPAPG=%5BwithPAPG%3Atrue%2C+w
https://forum.katalon.com/t/parameterize-a-web-service-object/16654?page=2
CC-MAIN-2022-33
refinedweb
1,172
58.48
This article will demonstrate how we can use mplayer to easily control in VB.NET WinForm application without using any COM/ActiveX control. Downloaded source code is sample part of Veron Media Player 1.9. At first, we need mplayer.exe in our main application's start path. It can be downloaded from here. Mplayer is a command line audio & video player. It can play audio or video file using several different output drivers. There were no previous examples of how to use mplayer to play audio or video in VB.NET winform application. C++ examples that were found to control mplayer but it is more easy and reliable if we use VB.NET program. Screenshot: Process object, Window handle control, Input and Output redirection. We will use Process class of System.Diagnostics namespace to launch an instance of mplayer to play files. We'll redirect input & output so that we can send commands to mplayer and get information about the file. System.Diagnostics Here is the code that we use to declare variables and initialize process: Delegate Sub ChangeTextsSafe(ByVal percent As String) ' To declare Variables :- Dim args, time_length, time_pos, buffer, CDP As String Dim posh, tdr As Long Dim ps As Process = Nothing ' To initialize process :- ps = New Process() ps.StartInfo.ErrorDialog = False ps.StartInfo.UseShellExecute = False ps.StartInfo.RedirectStandardInput = True ps.StartInfo.RedirectStandardOutput = True ps.StartInfo.FileName = "mplayer.exe" ps.StartInfo.CreateNoWindow = True BackgroundWorker1.RunWorkerAsync() Here, args will hold the arguments that will be passed to process except file name. ps is the process object which will use it to keep a reference to the mplayer process. args We will use "-slave" option because we want to run mplayer in 'slave' mode where it will read commands from another process and do actions accordingly. -nofs option for not to run in full screen mode. -wid option will tell the id of window where we want to display video output. Here we want to display in Panel1, so we get its handle and pass it after -wid. -af-add equalizer=0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 used for giving audio effects command. -slave mplayer -nofs -wid Panel1 -wid -af-add We used BackgroundWorker1 because we want to run mplayer on a separate way. So that we do not need timer to read mplayer's each line after 1 ms continuously. A timer can sometimes freeze the form. BackgroundWorker1 When user clicks on open file, a dialog will open and after a file is selected, mplayer will run that file. Code for playing file is as follows: If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then mplay() End If ' mplay() procedure :- Public Sub mplay() stp() args = "-nofs -noquiet -identify -slave -af-add equalizer=0:0:0:0:0:0:0:0:0:0 -volume " _ & TrackBar1.Value & " -nomouseinput -sub-fuzziness 1 -vo direct3d, -ao dsound -osdlevel _ 0 -wid " & CInt(Panel1.Handle.ToInt32) & CDP ps.StartInfo.Arguments = args & " """ & OpenFileDialog1.FileName & """" ps.Start() CDP = "" posh = 1 tdr = 1 Timer1.Start() Timer2.Start() End Sub ' stp() procedure :- Public Sub stp() posh = 0 Try ps.Kill() Catch End Try time_length = "" time_pos = "" Button1.Text = "Pause" Timer1.Stop() ProgressBar1.Value = 0 Label1.Text = "00:00:00" Label2.Text = "00:00:00" End Sub First, we want to make sure that any previous instance of mplayer started by us is closed. So, ps.Kill in try catch used that if the process has already exited or not started, the error does not show. For special purposes, timer1 is used and I will discuss later. timer2 for activating effect if pre-selected. timer2 interval will be 1s to 3s, otherwise if less, sometimes it will not work. CDP is declared as string for adding argument to play CD. ps.Kill try catch timer1 timer2 string We can send commands to mplayer to control the file that is being played. Each command must end with vbLf. SendCommand function will perform the task of sending commands to mplayer process. vbLf SendCommand Public Sub SendCommand(ByVal cmd As String) Try If ps IsNot Nothing AndAlso ps.HasExited = False Then ps.StandardInput.Write(cmd & vbLf) End If Catch End Try End Sub We can give any slave mode command to mplayer by this SendCommand function. All slave mode commands can be found in here. DoWork event in BackgroundWorker1: DoWork BackgroundWorker1 Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts) Do System.Threading.Thread.Sleep(1) Try If posh = 1 Then Dim sLine As String = ps.StandardOutput.ReadLine If sLine.Contains("ANS_LENGTH") Or sLine.Contains("ANS_TIME_POSITION") Then Me.Invoke(safedelegate, sLine) End If End If Catch End Try Loop ' ChangeTexts() procedure :- Public Sub ChangeTexts(ByVal per As String) Try If posh = 1 Then If per.Contains("ANS_LENGTH") Then ConvertTimeHHMMSS(per.Replace("ANS_LENGTH=", ""), 1) Else ConvertTimeHHMMSS(per.Replace("ANS_TIME_POSITION=", ""), 0) End If End If Catch End Try End Sub Now, description about timer1. It is used to get file's duration & time position. timer1 If tdr = 1 Then SendCommand("get_time_length") Else SendCommand("get_time_pos") End If Interval of timer1 must be 250 to 500ms. The value of tdr will be zero, when we will get file's time length. After zero, timer1 will send time-position command. Mplayer shows file's time position in seconds and we want to see it HH:MM:SS format. Therefore, ConvertTimeHHMMSS function was used. The following code is used for that function: tdr ConvertTimeHHMMSS Public Sub ConvertTimeHHMMSS(ByVal timeInSeconds As Double, ByVal strx As Long) Try If timeInSeconds >= 0 Then Dim iSecond As Double = timeInSeconds Dim iSpan As TimeSpan = TimeSpan.FromSeconds(iSecond) If strx = 1 Then time_length = iSpan.Hours.ToString.PadLeft(2, "0"c) & _ ":" & iSpan.Minutes.ToString.PadLeft(2, "0"c) & _ ":" & iSpan.Seconds.ToString.PadLeft(2, "0"c) ProgressBar1.Maximum = timeInSeconds tdr = 0 Else time_pos = iSpan.Hours.ToString.PadLeft(2, "0"c) & ":" _ & iSpan.Minutes.ToString.PadLeft(2, "0"c) & ":" _ & iSpan.Seconds.ToString.PadLeft(2, "0"c) ProgressBar1.Value = timeInSeconds End If Label1.Text = time_pos Label2.Text = time_length End If Catch End Try End Sub Here, TimeSpan.FromSeconds method is used which returns a timespan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. TimeSpan.FromSeconds timespan Code for MouseDown event in progressbar1: MouseDown progressbar1 Try If e.Button = Windows.Forms.MouseButtons.Left And Button1.Text = "Pause" Then Dim dValue As Double dValue = (Convert.ToDouble(e.X) / Convert.ToDouble(ProgressBar1.Width)) * _ (ProgressBar1.Maximum - ProgressBar1.Minimum) ProgressBar1.Value = Convert.ToInt32(dValue) SendCommand("seek " & ProgressBar1.Value & " 2") End If Catch End Try We can Rip/Read CD by mplayer. So, the argument will be then: ' To read CD, just add string in CDP :- Public Sub cdplay(ByVal r1 As String, ByVal r2 As String) CDP = " cdda://" & r1 & " -cdrom-device " & r2 End Sub ' r1= Track Number, r2= cd drive name ' To Rip CD :- ps.StartInfo.Arguments = "-nofs -noquiet -identify -slave _ -nomouseinput cdda://" & ListBox1.SelectedIndex + 1 & " _ -cdrom-device " & ComboBox1.SelectedItem.ToString.Replace("\", "") & " -ao pcm" ' Show CD/DVD drives name :- Try For Each drive As DriveInfo In DriveInfo.GetDrives().Where_ (Function(d) d.DriveType = DriveType.CDRom) ComboBox1.Items.Add(drive.Name) ComboBox1.SelectedIndex = 0 Catch End Try We can also listen to internet radio by mplayer with record option. ' To Stream :- ps.StartInfo.Arguments = "-nofs -noquiet -identify -slave -volume " & _ TrackBar1.Value & " -nomouseinput -sub-fuzziness 1 " _ & TextBox2.Text & " -capture" ' Here Textbox2 must contains Stream url and -capture command for recording. ' It will record in mp3 format & file name is stream.dump ' To Record :- Try If Button3.Text = "Record" Then Try System.IO.File.Delete(Application.StartupPath & "\stream.dump") Catch End Try SendCommand("capturing") Button3.Text = "Stop" Else SendCommand("capturing 0") Button3.Text = "Record" End If Catch End Try For audio effects: Form1.SendCommand("af_eq_set_bands " & a1 & ":" & a2 & ":" & a3 & ":" & _ a4 & ":" & a5 & ":" & a6 & ":" & a7 & ":" & a8 & ":" & a9 & ":" & a10) ' Other effects can be found in downloaded project file We can write config file of mplayer to set stream cache size and activate screenshot, video effects. We can add commands in argument if we do not like to write in config file. Config file written process will be: # cache setting cache=1024 vf-add=hue=0,eq=0:0 vf-add=screenshot vf-add=scale Mplayer is a really great command line application program and obviously VB.NET Program is one of the best to control mplayer. However, Mplayer has no audio visualization, but it can be possible by using FFT algorithm. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) sub_load <subtitle_file> Loads subtitles from <subtitle_file> Dim args, file, time_length As String Dim str As Long Dim ps As Process = Nothing General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://codeproject.freetls.fastly.net/Articles/647837/Mplayer-Control-by-VB-NET-used-in-Veron-Media-Pl?fid=1841542&df=90&mpp=25&sort=Position&view=Normal&spc=Relaxed&prof=True&select=4962803&fr=1
CC-MAIN-2022-40
refinedweb
1,470
60.11
SCardTransmitSCardTransmit() do not work reliably any more on Yosemite. In some cases using 2 PC/SC applications the functions returns SCARD_W_UNPOWERED_CARD (or 0x0x80100067). InterpretationMy interpretation is that Apple tried to implement a card auto power off mechanism. I added this feature in pcsc-lite version 1.6.5 from 2010. See "Card auto power on and off". The card auto power off feature is visible with some smart card readers, like the Gemalto PC Twin (renamed PC USB TR and then renamed IDBridge CT30). The reader has a LED in it. If the LED blinks then the reader is powered. If the LED is ON then the smart card is powered. On Mavericks (and the previous versions of Mac OS X) when you insert a card the LED is ON (unless the reader driver is not found) and stays ON until you remove the card. On Yosemite when you insert a smart card the LED is ON and after 5 seconds the LED blinks. This indicates that the card is powered for 5 seconds and then the card is powered off. Great. BugThe problem is that the Apple code is bogus. When 2 PC/SC applications are using the smart smart card at the same time the 5 seconds delay before powering off the card is started when the first application releases the card, even if the second application still has an access to the smart card. After the 5 seconds delay the second application will get a SCARD_W_UNPOWERED_CARD error on the next SCardTransmit() call. It looks like Apple forgot to power off the card only if NO other PC/SC application is using the card, not just after the first SCardDisconnect(). The sleep(5)in the sample code is important. This is the delay needed for the PC/SC layer to decide to power off the card. You can also remove this delay and wait before you press enter to continue the first execution. See alsoApple bug report #19764910 "PC/SC: SCardTransmit returns SCARD_W_UNPOWERED_CARD" The bug has been closed by Apple on 8th April 2015 as fixed in 10.10.3. Sample code #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef __APPLE__ #include <PCSC/winscard.h> #include <PCSC/wintypes.h> #else #include <winscard.h> #endif int main(int argc, const char * argv[]) { SCARDCONTEXT hContext; LPSTR mszReaders; DWORD err = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); if (err != SCARD_S_SUCCESS) { printf("ScardEstablishedContext : %08x\n",err); return -1; } DWORD cchReaders = 0; err = SCardListReaders(hContext, "SCard$AllReaders", NULL, &cchReaders); if (err != 0) { printf("ScardListReaders : %08x\n",err); return -1; } mszReaders = calloc(cchReaders, sizeof(char)); if (!mszReaders) { printf("calloc\n"); return -1; } err = SCardListReaders(hContext,"SCard$AllReaders", mszReaders, &cchReaders); if (err != SCARD_S_SUCCESS) { printf("ScardListReaders : %08x\n",err); return -1; } printf("Reader : %s\n", mszReaders); SCARDHANDLE hCard; DWORD dwActiveProtocol; err = SCardConnect(hContext, mszReaders, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &hCard, &dwActiveProtocol); if (err != SCARD_S_SUCCESS) { printf("SCardConnect : %08x\n",err); return -1; } unsigned char cmd[] = {0, 0, 0, 0, 0}; unsigned char resp[255]; DWORD resp_len; SCARD_IO_REQUEST *pci; if (SCARD_PROTOCOL_T0 == dwActiveProtocol) pci = SCARD_PCI_T0; else pci = SCARD_PCI_T1; resp_len = sizeof resp; err = SCardTransmit(hCard, pci, cmd, sizeof cmd, NULL, resp, &resp_len); if (err != SCARD_S_SUCCESS) { printf("ScardTransmit: %08x\n",err); return -1; } printf("SCardTransmit: %0X\n", err); if (1 == argc) { printf("Run the second instance\n"); getchar(); } resp_len = sizeof resp; err = SCardTransmit(hCard, pci, cmd, sizeof cmd, NULL, resp, &resp_len); if (err != SCARD_S_SUCCESS) { printf("ScardTransmit: %08x\n",err); return -1; } printf("SCardTransmit: %0X\n", err); SCardDisconnect(hCard, SCARD_LEAVE_CARD); SCardReleaseContext(hContext); if (argc > 1) { /* The sleeping time is important here */ sleep(5); printf("Continue the first instance\n"); } return 0; } Result (on Yosemite) $ CFLAGS="-framework PCSC" make main cc -framework PCSC main.c -o main Since this sample code needs two programs you need to have two Terminal windows opened. In the first terminal you run ./mainand in the second terminal you run ./main a(with an argument). Once the second execution has finished you press enter in the first terminal to continue the execution of the first program. Expected result (on Debian) $ CFLAGS=`pkg-config --cflags libpcsclite` LDFLAGS=`pkg-config --libs libpcsclite` make main cc -pthread -I/usr/include/PCSC -lpcsclite main.c -o main Known workaroundNone known. One very bad (and untested) solution would be to create an application that sends an APDU (with no side effect) every 3 or 4 seconds so that the 5 seconds delay never occurs. But that is a very very bad solution. And it may be difficult or impossible to find an APDU that would be safe to send at any time.
https://ludovicrousseau.blogspot.com/2015/02/os-x-yosemite-bug-scardtransmit-returns.html
CC-MAIN-2021-21
refinedweb
757
56.15
Chapter 2: Your First Program!. Hello World: Let’s Program. All programs must have the extension .java Our first program will be named: HelloWorld.java Let’s get started…. The name of the class must be EXACTLY the same as the name of the file!. The class starts: Your First Program! The name of the class must be EXACTLY the same as the name of the file! The class starts here A Comment:the “//” tells the computer to ignore this line. The only line that DOES anything!Prints “Hello World” and goes to the next line.This is a statement and must end with a semicolon. The main function:the code in here is what happens when you “run” the program. And ends here.ALL code will be inside the class. All Java programs are inside a “class”. public class HelloWorld{ public static void main(String [ ] args){//Prints Hello WorldSystem.out.println("Hello World"); }} HelloWorld.java HelloWorld.class Byte Code Source Code Compiler You JVM JVM Mr. PC Mr. Mac Capitalization errors and other typos (missing semicolons) will result in compile-time errors (aka syntax errors) Unfinished quote SEMICOLON!!! Why, that’s a large “P” you have there. public class HelloWorld{ public static void main(String [ ] args){//Prints Hello WorldSystem.out.Println(“Hello World) }}");}}
http://www.slideserve.com/denise/chapter-2-your-first-program
CC-MAIN-2017-22
refinedweb
214
79.56
WinRM – Invoke windows applications remotely WinRM is the solution if you are facing problem to invoke windows application commands from linux machine remotely !!! We need few things to perform this exercise : - 1 windows Remote desktop machine - 1 linux machine which could access windows machine(in same network) - WINRM enabled on Windows machine - python(2.7) installed on linux machine How it works ! Basically , the idea is to control few windows applications without login to the exact windows machine . Suppose , you are on linux machine and you have a requirement to get few results from windows machine or controlling some remote windows machine without login to it , then it is best way to use WINRM . What is WINRM ?, you should note that BOTH computers must have WinRM installed and enabled on them for WinRS to work and retrieve information from the remote system. While WinRM listens on port 80 by default, it doesn’t mean traffic is un-encrypted. Traffic by default is only accepted by WinRM when it is encrypted using the Negotiate or Kerberos SSP. WinRM uses HTTP (TCP 80) or HTTPS (TCP 443). It also includes helper code that lets its listener to share port 80 with IIS or any other application that may need to use that port.. How to enable it on Windows ? Step 1: Start Windows PowerShell as an administrator by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator and run below commands sc start WinRM winrm create winrm/config/Listener?Address= *+Transport=HTTP Enable-PSRemoting -Force Set-Item wsman:\localhost\client\*+Transport=HTTP Enable-PSRemoting -Force Set-Item wsman:\localhost\client\"} Step 2 : Come to linux machine - install python on it - install python module pywinrm (Python library to initiate and execute commands on remote machine windows or any other ) Write a short script to just get the ip of the Windows Remote machine which we want to access. import winrm import time s = winrm.Session('', auth=('username', 'password')) r = s.run_cmd('ipconfig',['/all']) #r = s.run_cmd('shutdown',['/r']) //for shutdown the windows print(r.std_err) print(r.std_out) print (r.status_code) it will display the IP information of the windows machine . Similarly, you can perform opening a notepad writing something into it and save it , or download some files on remote windows and execute them.
https://www.talentcookie.com/2015/12/winrm-invoke-windows-applications-remotely/
CC-MAIN-2020-10
refinedweb
384
54.52
> > ------------------------------------------------------------------------ > > The situation is that an API to an external resource must enforce > consistency with the resource's expectations of data (ie: ID's must be > immutable). > > The Python docs clearly show the use of the property() decorator in both > the example classes shown here. Both ensure that an assignment to the > class objects' 'id' attribute will raise an AttributeError > exception. Both will satisfy the requirements. > > I assume we all know what the implementation differences are between the > two examples here. What I am curious about is what use case would the > MyInterface example have? My guess is that it's added protection for > attribute names on objects generated from factories or generators. I'd > like a more concrete explanation from someone who has encountered a > scenario where it was required. The MyInterface2 version is preferred because it avoids creating an extra symbol in the class's namespace. That's pretty much it. The MyInterface example was how you had to do it before there were decorators. It still works, and the world won't end if you do it that way. There is not really much practical difference between the two versions to someone using the class. Also, the MyInterface version stores its data in a name-mangled attribute (two underscores), but you can also use a name-mangled attribute for the MyInterface2 version if you want. Neither version is foolproof. >. It's probably just for the reason I mentioned. Python likes to have an quasi-official way to do basic things such as define properties. ("There should be one--and preferrably only one--obvious way to do it.") That current quasi-official way is to use property is as a decorator, for the reason I gave: it avoids namespace pollution.. Finally, some people think read-only attributes are unpythonic. I think that's ridiculous, although in general I'd advise against making attributes read-only willy-nilly. But there's a time and place for it. Last thing I'll advise is don't get too hung up on terms like "Pythonic". Treat such labels are more of a red flag and get people who throw out the term to explain why. Carl Banks
https://mail.python.org/pipermail/python-list/2009-April/533580.html
CC-MAIN-2019-18
refinedweb
365
65.42
I'm trying to create a simple drawing application with undo and redo features. I assume you can add what you are drawing into a list and calling upon the list to draw everything. Then undoing should just remove the last added item and redraw everything again. The problem is, how do I add what I've drawn into a list and use that list to undo? I'm using the bitmap redraw method. This is how I draw: Point start, end; bool painting; private List<PointF> myPoints = new List<PointF>(); private void pnlMain_MouseDown(object sender, MouseEventArgs e) { start = e.Location; painting = true; } private void pnlMain_MouseUp(object sender, MouseEventArgs e) { painting = false; } private void pnlMain_MouseMove(object sender, MouseEventArgs e) { if (painting == true) { end = e.Location; g.DrawLine(p, start, end); myPoints.Add(e.Location); pnlMain.Refresh(); start = end; } } private void btnUndo_Click(object sender, EventArgs e) { g.Clear(cldFill.Color); if (myPoints.Count > 2) { myPoints.RemoveAt(myPoints.Count - 1); g.DrawCurve(p, myPoints.ToArray()); } pnlMain.Refresh(); //This works but you have to spam it to get rid of //a line and does some weird connections. } You need to store lines in a List<List<Point>>. Each element of the list contains points of a drawing which you draw using a down, move and up. The next line which you draw, will store in the next element of list. Each undo, will remove the last drawing. Put an instance of this control on your form and it will handle the drawing for you. Also to perform undo, call its Undo method. using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; public class DrawingSurface : Control { public DrawingSurface() { this.DoubleBuffered = true; } List<List<Point>> Lines = new List<List<Point>>(); bool drawing = false; protected override void OnMouseDown(MouseEventArgs e) { Lines.Add(new List<Point>()); Lines.Last().Add(e.Location); drawing = true; base.OnMouseDown(e); } protected override void OnMouseMove(MouseEventArgs e) { if (drawing) { Lines.Last().Add(e.Location); this.Invalidate(); } base.OnMouseMove(e); } protected override void OnMouseUp(MouseEventArgs e) { if (drawing) { this.drawing = false; Lines.Last().Add(e.Location); this.Invalidate(); } base.OnMouseUp(e); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; foreach (var item in Lines) e.Graphics.DrawLines(Pens.Black, item.ToArray()); /*or DrawCurve*/ } public void Undo() { if (Lines.Count > 0) { this.Lines.RemoveAt(Lines.Count - 1); this.Invalidate(); } } } Note List<List<Point>>. It's enough to copy the last item before undo to redo list using RedoBuffer.Add(Lines.Last());. Then for each redo command, it's enough to add the last item of redo buffer to Linesand remove it from redo buffer. You should also clear the redo buffer after each mouse down. You can use either of DrawLines or DrawCurve based on your requirement. DrawLines draws a poly-line, while DrawCurve draws a more smooth curve. I prefer to encapsulate Lines.Count > 0 in a property like bool CanUndo and make it accessible from outside of control. It's just an example and you can simply extend the solution. For example, instead of List<List<Point>> you can create a Shape class containing List<Point>, LineWidth, LineColor, etc and perform task using List<Shape>.
https://codedump.io/share/wDJBB6Ct6UbK/1/draw-multiple-freehand-polyline-or-curve-drawing---adding-undo-feature
CC-MAIN-2017-34
refinedweb
534
52.97
Like I said in the first post of the series, Express is all about middlewares. So, here's the problem statement Problem Statement Can we create a middleware out of any function, so that developers don't have to worry about the tricky syntax and testing of middlewares Well, the hardest part is over, defining the problem. Let's get our hands dirty now. The generic syntax of a middleware is //generic express middleware syntax const middleware = (req, res, next) => { // EXECUTION LOGIC next(); // This is where the control leaves this middleware and moves to next item in the queue, which could be another middleware, or the final controller etc } Our intention is make it work in a way, that we should be able to inject the EXECUTION LOGIC dynamically. For this, we slightly move away from OOPS of JS and take help of a functional programming concept called Higher Order Function. How does it help, you ask? Well, we're going to create a function, that returns a middleware. and through that function, we're going to inject the execution logic. We're going to create a file, withMiddleware.js //withMiddleware.js //Higher Order Function const withMiddleware = (func) => { return (req, res, next) => { func(); //func has the EXECUTION LOGIC next(); } } module.export = withMiddleware; Let's see how we can make this work for us. const withMiddleware = require('./withMiddleware'); const funcOne = () => { //YOUR BUSINESS LOGIC } const funcTwo = () => { //YOUR ANOTHER BUSINESS LOGIC } const middlewareOne = withMiddleware(funcOne); const middlewareTwo = withMiddleware(funcTwo); //use this middlewares in a standard way. app.get("/path", middlewareOne, middlewareTwo, (req, res)=>{ //further execution, if any res.send({}); }) The Magic ends here for now, but there are a few problems yet to be solved for this. In the next post we're going to take this a little higher and address the following - How will we handle the async middlewares? - What if I'm writing auth or validation middlewares, that needs access to the request object? - Passing data between middlewares? Although we solved it in the first post, see the PS: section, but how can we make it work effortlessly - Logging. The generic activities of the middlewares needs to be logged. Like, in case of async middleware, that fetches data over another API, or fetches data from a DB, the time taken for the async operation needs to be logged. Discussion (0)
https://dev.to/tirthaguha/playing-with-express-middlewares-and-higher-order-functions-5e4n
CC-MAIN-2021-39
refinedweb
390
53.51
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. I fixed the PR libstdc++/3988, a gcc 3.0.1 regression with respect to gcc 3.0. The name of the guard was wrong. After replacing the name _GBLICPP_HAVE_LOGL with HAVE_LOGL the test case passes. The logl function from glibc is now used rather than the function defined in the stubs.c file. After applying the appended patch, all tests from the boost regression test suite pass on the i686-pc-linux-gnu target! Please apply this patch to the branch and the main line, if OK. Hope this helps, Peter Schmid Output of the testcase t include in PR 3988 ./t 0 1 0 1 2001-08-14 Peter Schmid <schmid@snake.iap.physik.tu-darmstadt.de> * libstdc++-v3/libmath/stubs.c: Fix PR/3988, replace _GBLICPP_HAVE_LOGL with HAVE_LOGL *** libstdc++-v3/libmath/stubs.c.orig Tue Aug 14 01:13:03 2001 --- libstdc++-v3/libmath/stubs.c Tue Aug 14 01:13:31 2001 *************** logf(float x) *** 143,149 **** } #endif ! #ifndef _GBLICPP_HAVE_LOGL long double logl(long double x) { --- 143,149 ---- } #endif ! #ifndef HAVE_LOGL long double logl(long double x) {
http://gcc.gnu.org/ml/gcc/2001-08/msg00733.html
CC-MAIN-2018-17
refinedweb
198
69.99
Dear all I see that on SSCUI 102364 there is a message existing in list ME n° 063 called Acct. assgt. category & not defined (please check your input) When adding this new entry, a message error appears: ( any idea how to add the blocking message ? We want to make it mandatory to enter a value in acct assg cat and not let it in blank at the creation of the purchase order) Message no. SV019 You tried to add a new entry, and when doing so, used a key value that lies outside of the namespace you manage. This can cause problems in later upgrades because the entry could be overwritten by an import, or overwrite an existing entry. Check your entry and try to enter a key value from your namespace.
https://answers.sap.com/questions/13242380/view.html
CC-MAIN-2021-31
refinedweb
132
66.07
. Advertisements […] today’s Programming Praxis exercise, our goal is to simulate the well-known birthday paradox. Let’s […] My Haskell solution (see for a version with comments): Should one not allow for leap years? Here is a video explaining birthday paradox: A Python version import random as RA import itertools as IT def analytic(N): prob = 1 for i in range(0, N): prob *= (1.0 – i / 365.0) return 1 – prob def gen_cases(N): while 1: yield [RA.randint(1, 365) for i in range(N)] def monte_carlo(N, mcsamples = 1000): “””calculate chance that 2 or more people have same birthday””” cnt = sum(len(c) != len(set(c)) for c in IT.islice(gen_cases(N), mcsamples)) return cnt / float(mcsamples) #[/sourcecode] Repost. A python version. A Python version which takes into account leap years, 0-364 are the non-leap days of the year and 365 is Feb 29th: Hah, beat you to one for once. :) Here’s a post that I wrote a week and a half ago on my own birthday that basically works out the math behind the problem and then lets you run a simulation build into the web page (Javascript w/ JQuery). You can choose any number of birthdays to simulate and it will generate that many for you over the next year, keeping statistics for each number, along with the expected value. I think it’s pretty neat at least. :) Check it out here: The Birthday Paradox Clojure solution. Solution written in Go (source code): package main import ( "fmt" "math/rand" ) func main() { fmt.Printf("Chance of same birthday in group with 23 people: %.0f%%\n", getChanceOfSameBirthdayInGroup(23)*100) fmt.Printf("Chance of same birthday in group with 57 people: %.0f%%\n", getChanceOfSameBirthdayInGroup(57)*100) } func getChanceOfSameBirthdayInGroup(groupSize uint) float32 { n := 10000 numberOfSameBirthdays := 0 for i := 0; i < n; i++ { if isSameBirthdayInGroup(groupSize) { numberOfSameBirthdays++ } } return float32(numberOfSameBirthdays) / float32(n) } func isSameBirthdayInGroup(groupSize uint) bool { birthdays := make(map[int]uint8) for i := uint(0); i < groupSize; i++ { birthday := rand.Intn(365) birthdays[birthday]++ if birthdays[birthday] == 2 { return true } } return false } A year whose number is divisible by 100 is not a leap year, unless it is also divisible by 400. So the year 2000 was a leap year, but the year 2100 won’t be. A program trying to calculate birthday statistics for people currently alive can ignore this issue, but if it’s supposed to work across history it needs to take it into account. Of course, if one goes back before the Gregorian calendar was adopted, matters get extremely complicated, and figuring out how to deal with the eventual breakdown (at some not-yet-predictable time) of the Gregorian calendar is even trickier. A Java Solution: Leap years? Not sure what leap years have to do with the original problem stated in the main blog homepage. Here is my PHP solution for the first part. for($i = 1; $i < 1000; $i++) { $arr = array(); for($q = 0; $q 1) { $total++; } } echo $total / 1000; Not sure what’s wrong with your blog but it just can’t off half my code. Forget this. Moving on. […] Pages: 1 2 […]
https://programmingpraxis.com/2012/10/12/birthday-paradox/?like=1&source=post_flair&_wpnonce=0df65f7478
CC-MAIN-2018-17
refinedweb
525
62.88
I have this regular expression code for finding the anomaly pattern. if not re.match(r'(-?[01].[0-9]{1,8})s(-?[01].[0-9]{1,8})', text): print("anomaly!!") I want to find something that anomaly pattern through if not. My code usually works well, but I found a case where doesn’t work: 0.00000000e+00 // It should be error (included non-numeric strings) 0.000000 // It should be error (complete zero cannot exist) 0.00 0000 // It should be error (included non-numeric strings) I complied with the following rules: 1. The value after the decimal point can be from at least one letter to at maximum eight. 2. Never include non-numeric strings. 3. A complete zero (0.0 ~0.00000000) cannot exist. 4. A value must exist after the decimal point. I think, my regular expression can’t detect complete zero (0.0 to 0.00000000) and non-numeric values. How can I apply two exceptions to my regular expression? Please give me some advice. This is my test cases: [-0.19666128 -0.0000] # It should be error (complete zero cannot exist) [-1.09666128 -0.16812956] # It should be correct. [-0.180045 -0.22017317] # It should be correct. [1.00000786 -0.24855652] # It should be correct. [0.1766060 -1.] # It should be error (A value must exist after the decimal point) [1.16797414 0.00000000e+00] # It should be error (included non-numeric strings) [-0. 0.] # It should be error (A value must exist after the decimal point) [1.1223297 -0.2840327] # It should be correct. [1. -0. ] # It should be error (A value must exist after the decimal point and included non-numeric strings) [-0.11070672 -0.20553467] # It should be correct. [1.04924586 -0.16772696] # It should be correct. [0.06169098 -0.15855075] # It should be correct. [-0.11988816 1.20512903] # It should be correct. [-0.180045 -1.22017317] # It should be correct. [-0.18486786 -0.24855652] # It should be correct. Answer You need to use re.search (since ) and use the following regex: [(-?(?!0(?:.0+)?s)[01](?:.[0-9]{1,8})?)s+(-?(?!0(?:.0+)?])[01](?:.[0-9]{1,8})?)] See the regex demo. The (?!0(?:.0+)?s) and (?!0(?:.0+)?]) lookaheads will cancel the match if either of the numbers are all zeros. See the Python demo: import re n = r'[01](?:.[0-9]{1,8})?' # Number matching part declared as a variable rx = re.compile(fr"[(-?(?!0(?:.0+)?{n}s))s+(-?(?!0(?:.0+)?]){n})]") test_strs = ["[-0.19666128 -0.0000]","[-1.09666128 -0.16812956]","[-0.180045 -0.22017317]", "[1.00000786 -0.24855652]", "[0.1766060 -1.]", "[1.16797414 0.00000000e+00]", "[-0. 0.]", "[1.1223297 -0.2840327]","[1. -0. ]", "[-0.11070672 -0.20553467]","[1.04924586 -0.16772696]" "[0.06169098 -0.15855075]","[-0.11988816 1.20512903]","[-0.180045 -1.22017317]","[-0.18486786 -0.24855652]"] for text in test_strs: if rx.search(text): print(f'{text}: Valid') else: print(f'{text}: Invalid') Output: [-0.19666128 -0.0000]: Invalid [-1.09666128 -0.16812956]: Valid [-0.180045 -0.22017317]: Valid [1.00000786 -0.24855652]: Valid [0.1766060 -1.]: Invalid [1.16797414 0.00000000e+00]: Invalid [-0. 0.]: Invalid [1.1223297 -0.2840327]: Valid [1. -0. ]: Invalid [-0.11070672 -0.20553467]: Valid [1.04924586 -0.16772696][0.06169098 -0.15855075]: Valid [-0.11988816 1.20512903]: Valid [-0.180045 -1.22017317]: Valid [-0.18486786 -0.24855652]: Valid
https://www.tutorialguruji.com/python/python-how-can-i-apply-two-exceptions-to-my-regular-expression/
CC-MAIN-2021-21
refinedweb
558
80.68
Products.Maps 3.3 A simple, easy to use Plone integration with Google Maps Topics Installation Maps shows up in the “Add-ons” configuration panel. Implementing custom content with map field If you want to add location foeld to your custom content type, you should implement the following steps: Add GeoLocation field: from Products.Maps.field import LocationWidget, LocationField from Products.Maps.interfaces import IMapEnabled, ILocation MyContentSchema = ... LocationField('geolocation', required=False, searchable=False, validators=('isGeoLocation',), widget = LocationWidget(label = u'Event location'), ), ... Update your class definition: class MyContent(ATCTContent): """ my content description """ implements(IMyContent, IMapEnabled, ILocation) ... def getMarkerIcon(self): """ Can be implemented as select field. See Maps.Location content """ return "Red Marker" Add following snippet to custom content view/template: <div class="googleMapView googleMapLocation" tal: <dl metal: </dl> </div> Dependencies - Plone 3.3 / 4.x Credits Created by Florian Schulze for Jarn AS in 2007. Parts are based on: - “ATGoogleMaps”: - “qPloneGoogleMaps”: - “geolocation”: Development originally sponsored by The “Student Services of Bergen, Norway”: “University of Oxford”: (Medical Sciences Division) Contributors for version 3.0 Maurizio Lupo @sithmel - maurizio.lupo@redomino.com Luca Fabbri @keul - luca@keul.it Changelog 3.3 (2013-04-05) - Store map objects in window.activeMaps to allow end-develops access [StevenLooman] - added title in popup window [giacomos] 3.2 (2013-03-14) - fix on location widget when used as archetype field [sithmel] - fix on save maps layout buttons (Plone3 only) [sithmel] 3.0 (2013-01-25) - Completely refactored js code using Jquery [sithmel] - Updated to Google API v.3 (reverse geocoding, streetview ecc.) [sithmel] - Added autocompletion for places [sithmel] - Fixed Layer feature (based on keywords) [sithmel] - added search to map view [sithmel] - Added Italian Translation [sithmel] - added new plone collection compatibility [sithmel] - new control panel [sithmel] - various bugfixes and compatibility tests [keul] 2.1.2 - Unreleased - Update for Plone 4.1: include Products.CMFCore to define missing permissions. Fix undefined name showContents in default view. [thefunny42] - Add “Add permission” for Site Administrator too. [thefunny42] - Add controlpanel option to turn off displaying full item contents in pop-up. () [khink] 2.1.1 - 2011-05-13 - Force validator registration before use. Avoids spurious warning. [ggozad] - Kicked out qPloneGoogleMaps and Products.geolocation [ggozad] - Fixed broken TestCase. [ggozad] - Updated control panel actions for Plone 4. [ggozad] - Update ILocation interface. Custom content type must implement getMarkerIcon method to successfully support LocationMarker adapter. [naro] - Added notes about implementation geolocation field to custom content type. [naro] - Allow maps_map to be used as view template without being the default view () [khink] - Replace __init__ profile initialization with xml file GS profile setup, so we can add Products.Maps as a dependency in another product’s Generic Setup profile. [khink] - Added Dutch translation [kcleong] 2.1.0 - 2010-09-19 Update documentation to require Plone 4.x. [hannosch] Update license to GPL version 2 only. [hannosch] Removed IndexIterator since it was removed in Plone 4.0. [pbauer] Added support missing plone domain on i18n directory. Added Spanish translation. Updated full support for i18n and generate new template. [macagua] Improve map initialization when the location field is displayed in an other schemata. Merged from branches/map-in-another-schemata. Notes: Width and height must be define in the theme’s styles, if you put the field in an other schemata: div.googleMapEdit { width:756px; /* must be in pixels */ height:455px; /* must be in pixels */ padding-bottom:30px; } [sylvainb, toutpt] 2.0.3 - 2010-05-07 - Added missing i18n_domain to the configure.zcml. [hannosch] - Cook javascript resources after control panel submissions. [silviot] 2.0.2 - 2010-02-10 - Added an add permission for GeoLocations to support fine grained control of where the content type can be added. [rossp] 2.0.1 - 2010-01-19 - Updated LocationFieldValidator to be compatible with both Plone 3 and 4. [hannosch] 2.0 - 2008-09-17 - Add a metadata.xml to the GenericSetup profile. [wichert] - Refactored to make it easier to use Maps in custom content types. If you write a content type and use a field named ‘geolocation’, then you can use default implementations of adapters now instead of writing three on your own. [fschulze] - Moved to common egg file layout. This means there will be no more tarball releases, because the docs are outside of the Products folder. [fschulze] - Converted HISTORY.txt and README.txt to reStructureText. [fschulze] - Added a simple buildout configuration to the package, to be able to develop and test it on its own. [hannosch] 1.2 - July 3, 2008 - Added greek translation. [ggozad] - Updated templates for Plone 3.0. [fschulze] - Dropped compatibility with Plone 2.5. [fschulze] 1.1 - September 05, 2007 - Fixed the logic when to show layers. [fschulze] - Fixed viewing of maps if the workflow state was ‘private’. There is a new interface and view which only has the ‘enabled’ attribute and which is accessible without restriction. This is now used as the condition in portal_javascripts. [fschulze] - The coordinates field now uses a tuple with two floats everywhere. The widget for it now uses two input fields. [fschulze] - Made LinguaPlone aware. [fschulze] - Added custom view for locations. The map is smaller at the upper right and the rich text is shown besides it. [fschulze] 1.1rc1 - May 17, 2007 - Added configlet for Plone 3.0. [fschulze] - Fixed scrolling of map when clicking on pin. This only happend when there were no layers. [fschulze] - Fixed functionality of layer checkboxes for IE6/7. [fschulze] - Fixed key lookup when the URL has a trailing slash. [fschulze] - Added fallback to Google AJAX Search if the Google Maps geocoding did not return any results. This allows you to search for cities i.e. the UK and China. [fschulze] 1.0 - May 03, 2007 - Changed the markup. All markers are in one definition list instead of one marker in one list. A dt with class=”title” marks the beginning of a new marker. [fschulze] - Added support for layers. The default is to take keywords as the name of the layer in which a marker is visible. Then you get a map control with checkboxes for each keyword and you can view/hide the markers with that. [fschulze] - Using GenericSetup for installation. [fschulze] - Added support for existing qPloneGoogleMaps markers. Added support of content with location from the geolocation product. [fschulze] - Added RichText field to Location objects. [fschulze] - Added support for tabbed info windows. [fschulze] 0.5 - April 02, 2007 - Initial public release. [fschulze] - Author: Florian Schulze - Keywords: Google Maps Zope Plone - License: GPL - Categories - Package Index Owner: hannosch, fschulze, rpatterson, maurizio.lupo, ggozad, pbauer, collective, keul - Package Index Maintainer: rpatterson, pbauer - DOAP record: Products.Maps-3.3.xml
https://pypi.python.org/pypi/Products.Maps
CC-MAIN-2017-39
refinedweb
1,094
60.82
With the xtremepush ANE, you can add xtremepush to both iOS and Android apps built with Adobe Air. Platform Specific Information Xtremepush supports push notifications for iOS devices via Apples's Push Notification Service (APNs for short) and push notifications for Android devices via Google’s GCM/FCM (Google/Firebase Cloud Messaging for Android) service. This page contains Adobe Air A full Adobe Air integration guide is given below. Adding the ANE Download the archive of the Xtremepush ANE from here and extract the XPush.ane file from it, to use in your app. Open up your project properties by right-clicking on your project and selecting properties. In the menu on the left-hand side find 'ActionScript Build Path' and click it. There will now be a tab on the top of the page called 'Native Extensions', click it. Now click the button on the right-hand side that reads 'Add ANE', browse to the XPush.Ane and select it. Now the ANE is added to the project, but we must still ensure that it is packaged with the project. To do this, we navigate to 'ActionScript Build Packaging' on the left-hand menu. This is a drop-down menu that has all the platforms associated with the project. For each one, click on the 'Native Extensions' tab and ensure that the 'package' checkbox is checked for XPush.Ane Android App.XML Requirements The following is a sample manifest with all the XPush manifest requirements iOS App.XML Requirements The following is a sample of the XPush iOS requirements Note: aps-environment is a must to make pushes work. "development" - for testing in sandbox APNS. "production" - for production apps Setup the XPush Native Extension in your App 1. Import the XPushNativeASExtension import ie.imobile.xtremepush.XPushASExtension 2. Create the Object private var _ane:XPushASExtension; _ane = new XPushASExtension(); 3. Register your settings with XtremePush Events and Tags If you want to send tags or events to our platform elsewhere in your app, this can be achieved with the following function calls: _ane.hitEvent("event"); _ane.hitTag("tag"); _ane.hitTagWithValue("tag", "value"); Inbox To open up the xtremepush inbox, use the following function call _ane.openInbox(); Unsubscribe from Notifications _ane.setSubscription(false); Set External ID _ane.setExternalId(""); Article is closed for comments.
https://support.xtremepush.com/hc/en-us/articles/115005105969-Adobe-Air
CC-MAIN-2019-18
refinedweb
381
57.77
IRC log of rdfcore on 2003-06-06 Timestamps are in UTC. 14:00:43 [RRSAgent] RRSAgent has joined #rdfcore 14:00:48 [em-lap] zakim, this is rdfcoew 14:00:48 [Zakim] sorry, em-lap, I do not see a conference named 'rdfcoew' 14:00:50 [em-lap] zakim, this is rdfcore 14:00:50 [Zakim] ok, em-lap 14:00:54 [Zakim] +??P18 14:00:56 [em-lap] zakim, dial emiller-bos 14:00:56 [Zakim] ok, em-lap; the call is being made 14:00:57 [Zakim] +Emiller 14:01:58 [Zakim] +??P19 14:02:06 [bwm] Zalim, ??p19 is bwm 14:02:11 [bwm] Zakim, ??p19 is bwm 14:02:11 [Zakim] +bwm; got it 14:02:16 [Zakim] +PatH 14:02:28 [bwm] Zakim, bwm is HP 14:02:28 [Zakim] +HP; got it 14:02:34 [em-lap] em-lap has changed the topic to: rdfcore 2003-06-06 telecon 14:02:34 [bwm] Zakim, HP has bwm 14:02:34 [Zakim] +bwm; got it 14:03:29 [bwm] zakim, who is on the phone? 14:03:29 [Zakim] On the phone I see ??P17, ??P18, Emiller, HP, PatH 14:03:30 [Zakim] HP has bwm 14:04:18 [bwm] Zakim, mute ??p17 14:04:18 [Zakim] ??P17 should now be muted 14:04:48 [bwm] Zakim ??p18 is ILRT 14:04:58 [bwm] Zakim, unmute ??p17 14:04:58 [Zakim] ??P17 should no longer be muted 14:05:11 [gk-scribe] gk-scribe has joined #rdfcore 14:05:18 [cmjg] cmjg has joined #rdfcore 14:05:44 [bwm] Zakim, ??p17 is FrankM 14:05:44 [Zakim] +FrankM; got it 14:05:51 [bwm] Zakim, HP has bwm, jjc 14:05:51 [Zakim] bwm was already listed in HP, bwm 14:05:52 [Zakim] +jjc; got it 14:06:05 [DaveB] DaveB has joined #rdfcore 14:06:19 [bwm] Zakim, ilrt has jang and daveB 14:06:19 [Zakim] sorry, bwm, I do not recognize a party named 'ilrt' 14:06:24 [jcarroll] jcarroll has joined #rdfcore 14:06:27 [jang] zakim, who is here? 14:06:27 [Zakim] On the phone I see FrankM, ??P18, Emiller, HP, PatH 14:06:29 [Zakim] HP has jjc 14:06:30 [Zakim] On IRC I see jcarroll, DaveB, jang, gk-scribe, RRSAgent, Zakim, em-lap, bwm, logger 14:06:38 [bwm] Zakim, ??p18 is ILRT 14:06:38 [Zakim] +ILRT; got it 14:06:48 [bwm] Zakim, ILRT has daveb, jang 14:06:48 [Zakim] +daveb, jang; got it 14:06:50 [Zakim] +GrahamKlyne 14:06:55 [bwm] Zakim, who is on the phone 14:06:55 [Zakim] I don't understand 'who is on the phone', bwm 14:06:57 [bwm] ? 14:07:01 [bwm] Zakim, who is on the phone? 14:07:01 [Zakim] On the phone I see FrankM, ILRT, Emiller, HP, PatH, GrahamKlyne 14:07:02 [Zakim] ILRT has daveb, jang 14:07:03 [Zakim] HP has jjc 14:07:51 [jjc] jjc has joined #rdfcore 14:09:24 [jjcscribe] Agenda changes 14:09:31 [jjcscribe] - OWL Test Cases 14:09:36 [jjcscribe] - Duerst comments 14:09:37 [bwm] Zakim, ILRT has danbri 14:09:37 [Zakim] +danbri; got it 14:10:05 [jjcscribe] - responses from WebOnt on OWL comments 14:10:29 [gk] q+ to ask if approval of last minutes should be on agenda 14:10:46 [jjcscribe] Agenda item 3 goofy literals 14:10:51 [gk] q- 14:11:19 [bwm] 14:12:24 [Zakim] +Mike_Dean 14:13:20 [JosD] JosD has joined #rdfcore 14:14:11 [Zakim] +??P21 14:14:25 [gk] My Haskell datatype for RDF nodes looks like this: 14:14:27 [gk] data RDFLabel = 14:14:27 [gk] Res QName -- resource 14:14:27 [gk] | Lit String (Maybe QName) Lang -- literal [type] [language] 14:14:27 [gk] | Blank String -- blank node 14:14:33 [bwm] Zakim, ??p21 is jos 14:14:33 [Zakim] +jos; got it 14:14:43 [mdean] mdean has joined #rdfcore 14:15:34 [DaveB] jjc's proposal of this morning 14:16:19 [jjcscribe] graham seconds, no objections 14:16:45 [jjcscribe] (There was some discussion of which values are the same as which values) 14:18:32 [jjcscribe] XML namespace elements 14:19:55 [danbri_] danbri_ has joined #rdfcore 14:20:37 [gk] XML spec says names beginning XML are reserved 14:22:22 [jjcscribe] Dave has editorial descretion to deal with this question. (Chair) 14:22:36 [jjcscribe] Item 5. 14:22:40 [jjcscribe] Arc 14:23:41 [jjcscribe] In the explanation of striping, use "Arc" 14:24:09 [jjcscribe] Arc is fine for the pictures (PatH) 14:24:19 [DaveB] 'predicate arc in the pic' 14:24:22 [jjcscribe] When moving to the RDF/XML talk about predicates 14:25:01 [jjcscribe] Item 7 pfps-24 what is RDF Schema 14:25:09 [danbri_] proposed resoution: 14:25:11 [DaveB] agenda 14:26:02 [jjcscribe] Very little discussion. 14:26:12 [jjcscribe] Path seconds. 14:26:21 [jjcscribe] No objections. 14:26:35 [danbri_] resolved: issue closed, moved to editorial on rdfs 14:26:47 [jjcscribe] ACTION: danbri move to editorial on rdfs 14:26:57 [danbri_] action: danbri to change rdfs spec per 14:27:44 [bwm] 14:27:47 [jjcscribe] Agenda item 8 pfps-25 14:28:56 [jjcscribe] Brian has worked through the discrepancies, and the changes have been made in the semantics doc 14:29:05 [jjcscribe] that bring the two documents into line 14:30:18 [jjcscribe] DanBri proposes #225, PatH seconds 14:30:28 [jjcscribe] NO objections, so resovled. 14:30:43 [danbri_] so action on path to edit semantics? 14:30:56 [jjcscribe] pat has already done it 14:31:05 [danbri_] ah ok. great. 14:31:17 [jjcscribe] Item 9 qu-04 14:31:37 [jjcscribe] 14:31:47 [danbri_] dave proposes this; danbri 2nds 14:32:31 [jjcscribe] We are not bringing all the specs into a uniform ordering 14:32:48 [jjcscribe] No objections, resolved. 14:33:01 [jjcscribe] ACTION: danbri to edit as in #224 14:33:13 [jjcscribe] ACTION: danbri to respond to qu-04 14:33:35 [jjcscribe] ACTION: danbri to respond to pfps-025 14:33:45 [jjcscribe] ACTION: danbri to respond to pfps-024 14:34:33 [jjcscribe] Agendum webont-01 14:36:13 [jjcscribe] Brian argues agaisnt change for changes sake because of the quantity of work 14:36:29 [jjcscribe] Is there a substantive positive benefit? 14:36:33 [danbri_] in [[ 14:36:35 [danbri_] * never using 'rdf schema' in noun form, ie avoiding talk of their being 14:36:35 [danbri_] things that are 'rdf schemas' (while leaving it in as a _name_ for the 14:36:35 [danbri_] basic rdf vocabulary description language defined by w3c, just as OWL is 14:36:36 [danbri_] the name for W3C's 2nd RDF-based VDL). 14:36:40 [danbri_] ]] 14:36:47 [danbri_] q+ to comment re noun form 14:37:37 [bwm] ack danbri 14:37:37 [Zakim] danbri_, you wanted to comment re noun form 14:38:58 [jjcscribe] q+ 14:39:08 [em-lap] q+ 14:39:16 [jjcscribe] PatH SRI was = Stanford research institute 14:40:16 [jjcscribe] Propose we do not accept this comment and stay with current terminology and usage. 14:40:24 [jang] rdfs stands for "resource description vocabulary everything needs a snappier name, stupid" 14:40:31 [jjcscribe] Proposed danbri, seconder gk 14:40:43 [jjcscribe] Abstain ericM 14:41:17 [jjcscribe] ACTION: danbri to respond to webont 14:41:31 [jjcscribe] ACTION: danbri 7= to respond to webont on webont-01 14:41:47 [jjcscribe] Flat layering vass-01 item 11 14:41:57 [bwm] 14:42:40 [gk] q+ to say that I think we're agrees to not accept this, and only talking about how to respond 14:42:50 [em-lap] ack em-lap 14:43:33 [jjcscribe] are we going to hand behind charter? 14:43:53 [jjcscribe] Discussion of Horrocks paper in Budapest 14:44:22 [gk] q+ to ask if we can bounce this to SWCG 14:44:43 [bwm] 14:45:04 [jjcscribe] ack 14:46:34 [jjcscribe] gk suggests that drafting a response is not a WG priority 14:47:08 [jjcscribe] Brian: is 227 good enough as a response or not? 14:48:00 [jjcscribe] q+ 14:48:09 [jjcscribe] Pat agrees with the message 14:48:10 [gk] q+ to say that Broan's message 0227 is fine, but that I don't think it should/need be sent from the wg 14:48:24 [jjcscribe] Brian do we have to expand it? 14:48:35 [bwm] ack gk 14:48:35 [Zakim] gk, you wanted to say that I think we're agrees to not accept this, and only talking about how to respond and to ask if we can bounce this to SWCG and to say that Broan's message 14:48:38 [Zakim] ... 0227 is fine, but that I don't think it should/need be sent from the wg 14:48:56 [bwm] ack jjc 14:51:16 [jjcscribe] DanBri wants to show that we have listened and thought about it 14:52:18 [gk] q+ to suggest if WG weighjt is required to delegate Pat/Danbri to draft response, and then let the WG approve it before sending 14:52:52 [jjcscribe] jjc propose to not accept comment 14:52:55 [jjcscribe] danbri seconds 14:53:02 [jjcscribe] resolved unaminous 14:53:09 [gk] q- 14:53:12 [jjcscribe] action pat to draft a response for the wg to send 14:53:29 [jjcscribe] item 12 rdfs:comment 14:54:07 [bwm] 14:54:30 [bwm] 14:56:55 [jjcscribe] Pat: can we just use differnt forms of words 14:57:24 [danbri_] q+ to mention constraint resource 14:57:36 [jjcscribe] perhaps weaken the nonformal descriptions 14:58:50 [bwm] ack danbri 14:58:50 [Zakim] danbri_, you wanted to mention constraint resource 15:00:19 [jjcscribe] brian wonders whether we should ask peter for text 15:00:28 [DaveB] [we hear bwm break up] 15:00:46 [danbri_] (bwm faded out with crackling noises; then got louder again) 15:04:13 [jjcscribe] jjc I disagree with this issue 15:05:27 [gk] q+ to suggest reducing expectations in RDF vocab doc 15:05:58 [bwm] ack gk 15:05:58 [Zakim] gk, you wanted to suggest reducing expectations in RDF vocab doc 15:07:29 [jjcscribe] ACTION: danbri to ask peter for text he would prefer 15:07:39 [jjcscribe] ITEM 6 pfps-12 lsits 15:07:40 [gk] "This document provides an informal description of elements of RDF and RDFS vocabulary. For formal semantics, see the ..." 15:08:29 [bwm] 15:10:12 [danbri_] (pat: '3 triple should be 2 tuple'(?) in semantics -- editorial?) 15:10:48 [DaveB] I find in semantics editor's draft 15:10:58 [DaveB] 3.2.3 rdf collections - 'well-formed' 15:11:15 [bwm] 15:12:40 [DaveB] q+ 15:13:26 [bwm] ack daveB 15:16:59 [gk] q+ to suggest rather than accepting the comment as on the table, to use it to develo0p new text and THEN ask if it addresses the problem 15:18:35 [gk] q- 15:18:48 [jjcscribe] discussion of domain cosntraitns and peter's text 15:19:19 [bwm] [[For the case of rdf:first above, I would much prefer 15:19:19 [bwm] rdf:first is an instance of rdf:Property that can be used to build 15:19:19 [bwm] descriptions of lists and other list-like structures. A triple of 15:19:19 [bwm] the form: 15:19:19 [bwm] L rdf:first O 15:19:20 [bwm] states that there is a first-element relationship between L and O. 15:19:22 [bwm] Note: RDFS does not require that there be only one first element 15:19:24 [bwm] of a list-like structure, or even that a list-like structure have a 15:19:26 [bwm] first element. 15:19:28 [bwm] I note that similar changes would have to be make for at least rdf:rest and 15:19:29 [jjcscribe] ACTION: danbri discuss #179 with peter concerning domains as well 15:19:30 [bwm] rdf:List.]] 15:20:04 [jjcscribe] refine text to include domain constaint, and make new proposal 15:20:21 [jjcscribe] Onto AOB 15:20:51 [jjcscribe] Jeremy asks RDF Core to review OWL Test Case 15:21:40 [jjcscribe] DaveB: reviewing document or tests? 15:22:26 [jjcscribe] ACTION: jjc TO get clear request from WebOnt chairs. 15:24:14 [jjcscribe] Jan may do it, depending on the request 15:24:47 [jjcscribe] I18N 15:26:10 [DaveB] msg 1 15:26:23 [DaveB] msg 2 - from I18N 15:26:25 [gk] My summary and comments on Martin's comments at: 15:29:44 [DaveB] jjc discuses "<rdf:RDF>" vs xml"<rdf:RDF>" ->xhtml escape, vs don't escape <> 15:31:45 [jjcscribe] gk argues against jjc particularly that this is a domain of discourse issue 15:32:39 [DaveB] q+ 15:32:50 [jjcscribe] gk notes that ralph supported xmlliteral = string 15:33:18 [jjcscribe] brian asks gk to establish case to reopen 15:33:26 [jjcscribe] gk 1) I18N comment 15:34:08 [DaveB] q- 15:34:28 [jjcscribe] gk 2) concerning cannes we needed the bit to trigger c14n, now we are doing c14n in the parser so we do not need to do this 15:35:51 [jjcscribe] gk is arguing on basis of complexity 15:36:36 [jjcscribe] daveb: we are simplified the xmlliterals 15:36:53 [em-lap] q+ to ask about feedback from query 15:37:46 [jjcscribe] daveb: we are primarily using this to ship around xhtml, according to the xml exc-c14n 15:38:42 [em-lap] q- 15:40:11 [jjcscribe] daveb discusses RSS feed use case 15:43:26 [DaveB] jjc? 15:44:37 [bwm] bwm: Question: Is the comment from I18N consistent with the advice given by I18N to RDFCore at the Cannes tech plenary? 15:44:45 [bwm] jjcscribe: Answer: No 15:44:57 [em-lap] RRSAgent, pointer 15:44:57 [RRSAgent] See 15:47:31 [gk] Other peoploe who've made rfelated comments (from memory)... TimBL doesn't seee why XML is special case in RDF; PFPS recently made some comments that XMLLiteral data type handling was "inconsistent" 15:48:23 [jjcscribe] 15:49:59 [gk] I think the core question is: "do we really want/need XML literals to something other than character sequences"? If the RDF user community answer is "yes" then Jeremy is right. I've heard that requirement articulated. 15:50:12 [gk] s/heard/not heard/ 15:51:07 [gk] BTW, to be fair, Patrick S hard argued that XML lits should be different things 15:55:20 [bwm] ACtion: jjc to provide an integrated definition of the value space of xml literal to include terminology for lexical space and value space. 15:55:44 [jang] 15:57:21 [DaveB] q+ quick syntax report 15:59:02 [em-lap] ack DaveB 15:59:17 [Zakim] -jos 15:59:20 [jjcscribe] adjourned 15:59:20 [Zakim] -FrankM 15:59:22 [Zakim] -Mike_Dean 15:59:34 [Zakim] -GrahamKlyne 16:07:22 [Zakim] -ILRT 16:12:27 [Zakim] -PatH 16:12:29 [Zakim] -HP 16:12:30 [Zakim] SW_RDFCore()10:00AM has ended 16:23:32 [jjc] jjc has joined #rdfcore 17:01:42 [danbri_] danbri_ has joined #rdfcore 17:02:00 [danbri_] danbri_ has left #rdfcore 18:13:20 [em-lap] em-lap has joined #rdfcore
http://www.w3.org/2003/06/06-rdfcore-irc
CC-MAIN-2015-06
refinedweb
2,624
50.84
Hi All, Like the previous posts, we start coding a simple class with the default constructor. Let's name it Finally, to test this program we must a That's it! Now we have a lot of information from our DICOM file header! Enjoy :) Some readers have asked me questions regarding how to access DICOM header information by DICOM Tag parameters. On this post I present you a quick tutorial on how to list all header information, including the Tag value, VR (value representation), Tag description, and the values of each field using the great dcm4che 2 toolkit. (0008,0005) [CS] Specific Character Set [ISO_IR 100] (0008,0008) [CS] Image Type [ORIGINAL] (0008,0016) [UI] SOP Class UID [1.2.840.10008.5.1.4.1.1.2] (0008,0020) [DA] Study Date [20040827] (0008,0021) [DA] Series Date [20040827] (0008,0022) [DA] Acquisition Date [20040827] (0008,0023) [DA] Content Date [20040827] (0008,0030) [TM] Study Time [100357.953000] (0008,0031) [TM] Series Time [100607.062000] (0008,0032) [TM] Acquisition Time [100622.688476] (0008,0033) [TM] Content Time [100622.688476] (0008,0050) [SH] Accession Number [null] (0008,0060) [CS] Modality [CT] (0008,0070) [LO] Manufacturer [SIEMENS] Like the previous posts, we start coding a simple class with the default constructor. Let's name it ListDicomHeader. public class ListDicomHeader { public ListDicomHeader() { // TODO Auto-generated method stub } public static void main(String[] args) { // TODO Auto-generated method stub } } The next step is to code the method responsible for extracting the header info. Note that this method is recursive. This is done because some DICOM files bring encoded Items that may hold other DICOM objects denoted by de value representation SQ. So, we are handling also sequence information with this code. The method is written as follows: public void listHeader(DicomObject object) { Iterator iter = object.datasetIterator(); while(iter.hasNext()) { DicomElement element = iter.next(); int tag = element.tag(); try { String tagName = object.nameOf(tag); String tagAddr = TagUtils.toString(tag); String tagVR = object.vrOf(tag).toString(); if (tagVR.equals("SQ")) { if (element.hasItems()) { System.out.println(tagAddr +" ["+ tagVR +"] "+ tagName); listHeader(element.getDicomObject()); continue; } } String tagValue = object.getString(tag); System.out.println(tagAddr +" ["+ tagVR +"] "+ tagName +" ["+ tagValue+"]"); } catch (Exception e) { e.printStackTrace(); } } } Looking at the code, first we get an iterator to go through our DICOM dataset. Then we code a while loop to get each DICOM element present in the header. At each iteration a new DicomElementis kept so we can access its values. The tagvariable holds the current Tag value. From then on there are some useful functions that may help us a lot. We can use the nameOfmethod from DicomObjectclass to get the Tag description as a String. I also suggest you to have a look at the TagUtilsclass for other great functions. The vrOffunction will return the value representation to the current element. Then comes the recursive part. We test the VR to see if it's a sequence (SQ), if so then we check if this element has any Items. Then if the answer is true we get the new object and call the listHeaderfunction again, starting the recursive loop. Each iteration then prints out the desired information. Finally, to test this program we must a mainmethod for this class. The method may be written as follows: public static void main(String[] args) { DicomObject object = null; try { DicomInputStream dis = new DicomInputStream(new File("c:/image.dcm")); object = dis.readDicomObject(); dis.close(); } catch (Exception e) { System.out.println(e.getMessage()); System.exit(0); } ListDicomHeader list = new ListDicomHeader(); list.listHeader(object); } That's it! Now we have a lot of information from our DICOM file header! Enjoy :)
http://jaypthakkar.blogspot.com/2013/08/listing-dicom-header-information-with.html
CC-MAIN-2017-22
refinedweb
603
51.44
I am in an Intro to Computing class and I have been doing fairly well but this program really has me stumped. This is our assignment: The program will take as input a worker’s first name, last name, ID number (four digit number), and unit production numbers for the last 5 weeks. Each unit production number is an integer value indicating how many pieces the employee produced that week. Next the program will call a function that calculates the mean of the number of units. Next, the program will call a function that calculates the median of the number of units. Finally, the program will call a third function that prints the employee’s last name, the mean and the median that were calculated in the other two functions. The program will continue reading in information and printing the results until the user indicates that there are no more employees. My problem is with the median. We haven't learned anything about arrays or sorting in the class. I do not want to do 120 "else-if" statements, but it is the only solution I have come up with. Any input from you guys about how to fix the function would be great and most appreciated. #include <iostream> #include <string> using namespace std; float Mean (int num1, int num2, int num3, int num4, int num5) {//PURPOSE: Calculate the mean of the five numbers //INPUT: five integers, weekOne, weekTwo, weekThree, weekFour, weekFive //OUTPUT: the mean of the five numbers, avg float avg=0; avg=((num1+num2+num3+num4+num5)/ 5.0); return avg; } float Median (int a, int b, int c, int d, int e) // variables named for easier coding {//PURPOSE: Calculate the median of the five numbers //INPUT: five integers, weekOne, weekTwo, weekThree, weekFour, weekFive //OUTPUT: the median of five numbers, median float median=0; if (a<b && b<c && c<d && d<e) cout<<a<<b<<c<<d<<e; else if (a<b && b<c && d<c && e<d) cout<<a<<b<<c<<e<<d; else if ( < && < && < && < ) cout<< << << << << ; return median; } void Print (string last, float m, float med) //parameters {//PURPOSE:To print out three variables //INPUT: the three reference parameters lastName, mn, md //OUTPUT: the three variables, last, m, med cout<<last<<", "<<m<<" and "<<med<<endl; } int main () { string firstName, lastName; char response; int ID, weekOne, weekTwo=0, weekThree=0, weekFour=0, weekFive=0; float mn=0, md=0; cout<<"Do you have an employee to input? Y or N"<<endl; cin>>response; while(response=='Y') { cout<<"Enter first name, last name, ID number (four digits), and unit production numbers (for past five weeks)"<<endl; cin>>firstName; cin>>lastName; cin>>ID; cin>>weekOne; cin>>weekTwo; cin>>weekThree; cin>>weekFour; cin>>weekFive; mn = Mean(weekOne, weekTwo, weekThree, weekFour, weekFive); //function call md = Median(weekOne, weekTwo, weekThree, weekFour, weekFive); Print (lastName, mn, md); cout<<"Do you have an employee to input? Y or N"<<endl; cin>>response; } return 0; } Edited by deceptikon: Fixed code tags
https://www.daniweb.com/programming/software-development/threads/420862/finding-median-of-five-input-integers
CC-MAIN-2017-09
refinedweb
495
50.4
SqlableSqlable Sqlable is a Swift library for storing data in a SQLite database easy as pie. Create a struct, make it Sqlable, and then read, write, update and delete to your heart’s content! Why would I want that?Why would I want that? Persistence is often a pain when making iOS apps. If you want to only use 1st party frameworks from Apple, your choice is either Core Data, or serializing to JSON or plist files. there’s a few nice 3rd party options, like Realm, but that’s mostly active objects doing a lot of dynamic things behind your back. If you want to just operate on plain structs, and just want to read and write to a database, Sqlable is the simplest option. Show me how to use it!Show me how to use it! Suppose you have this struct: struct Bicycle { let id : Int? var name : String var color : String } And you want to persist this in a database. To do this, you just make your struct Sqlable by implementing the Sqlable protocol like this: extension Bicycle : Sqlable { static let id = Column("id", .integer, PrimaryKey(autoincrement: true)) static let name = Column("name", .text) static let color = Column("color", .text) static let tableLayout = [id, name, color] func valueForColumn(column : Column) -> SqlValue? { switch column { case Bicycle.id: return id case Bicycle.name: return name case Bicycle.color: return color case _: return nil } } init(row : ReadRow) throws { id = try row.get(Bicycle.id) name = try row.get(Bicycle.name) color = try row.get(Bicycle.color) } } These are the only three things you need to specify: • The table layout (which columns do you want stored) • How to save a column • How to read a row And when you’ve done that, you can start using your struct with SQLite! The first step to using it is to setup a new SQLite database and create the table for the bicycle: db = try SqliteDatabase(filepath: documentsPath() + "/db.sqlite") try db.createTable(Bicycle.self) And then you’re ready to write, read, update and delete bicycles from the database! // Insert bicycle var bike = Bicycle(id: 1, name: "My bike", color: "Black") try bike.insert().run(db) // Read all bicycles let bicycles = try Bicycle.read().run(db) // Read some bicycles let redBikes = try Bicycle.read().filter(Bicycle.color == "red").limit(3).run(db) // Count all bicycles let bicycleCount = try Bicycle.count().run(db) // Update a bicycle bike.name = "Sportsbike" try bike.update().run(db) // Delete bike try bike.delete().run(db) New in version 1.2New in version 1.2 Update callbacksUpdate callbacks You can now very easily observe changes via update callbacks on inserts, deletes and updates. db.observe(.insert, on: Bicycle.self) { id in print("Inserted bicycle \(id)") } db.observe(.update, on: Bicycle.self, id: 2) { id in print("bicycle 2 has been updated") } ConcurrencyConcurrency Sqlable now uses SQLites write-ahead log, which makes concurrent operations fast and easy. And since Sqlable is operating with plain structs, you can freely pass information between different threads. let child = try db.createChild() dispatch_async(background_queue) { let bicycles = try! Bicycle.read().run(child) dispatch_async(main_queue) { self.displayData(bicycles) } } You can use transactions to lock the database, and other threads will wait until the transaction is done. Full documentationFull documentation All public functions now have documentation New in 1.1 (+1.1.1)New in 1.1 (+1.1.1) • Nested transactions • SQL function calling for filters (e.g. "like", "upper" and "lower") What other cool features does it have?What other cool features does it have? TransactionsTransactions Transactions are very simple to do: try db.transaction { db in if try Bicycle.count().run(db) == 0 { try bike.insert().run(db) } } You can also do rollbacks: try db.beginTransaction() try bike.insert().run(db) try db.rollbackTransaction() And nested transactions! (new in 1.1.1!) try db.transaction { db in try db.transaction { db in if try Bicycle.count().run(db) == 0 { try bike.insert().run(db) } } } Foreign key constraintsForeign key constraints extension Bicycle : Sqlable { static let ownerId = Column("owner_id", .Integer, ForeignKey<Person>()) ... And you can also specify other columns and delete/update rules: extension Bicycle : Sqlable { static let ownerId = Column("owner_id", .Integer, ForeignKey<Person>(column: Person.regId, onDelete: .cascade)) ... Uniqueness constraintsUniqueness constraints (New in 1.1!) If you want each bicycle in the database to have a unique name: extension Bicycle : Sqlable { static let name = Column("name", .text) static let tableConstraints : [TableConstraint] = [Unique(Bicycle.name)] ... Or, if you want the combination of name and color to be unique: extension Bicycle : Sqlable { static let name = Column("name", .text) static let color = Column("color", .text) static let tableConstraints : [TableConstraint] = [Unique(Bicycle.name, Bicycle.color)] ... DSL for query filtersDSL for query filters Bicycle.read().filter(Bicycle.color == "red" && !(Bicycle.id == 0 || Bicycle.id > 1000)) Update callbackUpdate callback (New in 1.2!) Register the didUpdate callback on your database handler to get notified when anything changes: db.didUpdate = { table, id, change in switch change { case .insert: print("Inserted \(id) into \(table)") case .update: print("Updated \(id) in \(table)") case .delete: print("Deleted \(id) from \(table)") } } But even better, you can register event callbacks on specific actions, tables and ids: db.observe(.insert, on: Bicycle.self) { id in print("Inserted bicycle \(id)") } db.observe(.update, on: Bicycle.self, id: 2) { id in print("bicycle 2 has been updated") } db.observe(.delete, on: Bicycle.self) { id in print("bicycle \(id) has been deleted") } db.observe(on: Bicycle.self) { id in print("Something was updated on bicycle \(id)") } Swift style error handlingSwift style error handling Every function call that can fail is marked with throws, so you can handle every error that can possibly happen. The APIs are also constructed so that you can set up your statements without touching the database, so you can set everything up without any error handling: let idFilter = Bicycle.id > 2 && Bicyckle.id < 10 let read = Bicycle.read().filter(idFilter).limit(2) do { let result = read.run(db) } catch let error { // handle error } It also supports an optional handy callback for when any error occurs, which you can use if it fits into your app. Just call the fail method on your database handler when you encounter an error like this: do { try Bicycle.read().limit(-1).run(db) } catch let error { db.fail(error) } And it will be passed to your registered error handler: db.didFail = { error in print("Oh no! \(error)") } ConcurrencyConcurrency (new in 1.2!) Ever had to deal with concurrency in Core Data? Don't worry, Sqlable is nothing like that. Each SqliteDatabase instance is unique to one thread/queue. If you want to run some code in the background, you can create a child instance: let child = try db.createChild() dispatch_async(background_queue) { for bicycle in try! Bicycle.read().run(child) { ... } } That's the only rule: keep each instance unique on its thread/queue. Sqlable and Sqlite will take care of locking the database correctly. The parent will even get update notifications from changes made in the child. If you want some database operations to happen serially, you can put them in a transaction, which will automatically lock the database on all threads. Also, since model instances are just value types, you can freely move them around on threads. If you need to load 10.000.000 bicycles from your database, just run the read query in the background, and dispatch the result to the main queue. How do I install it?How do I install it? If you’re using Carthage (you should!), just add this to your Cartfile: github "ulrikdamm/Sqlable" And then just in your source files: import Sqlable And you’re good to go! Which features are coming soon?Which features are coming soon? • Migrations • Joins More technical detailsMore technical details StatementsStatements When you make a struct Sqlable, it gains instance- and static methods for returning statements. These methods are read, count, insert, update and delete. All these returns a Statement struct, which you can then modify (with .filter, .limit, .onConflict, .orderBy). The statement is just an immutable struct, no magic going on. You can save it, serialize it, etc. When you want to run the statement, you just call the run method, which takes a database handler to run it in, and might throw an error, or give you a result. The type of the result depends on which initial method created the statement. Query DSLQuery DSL The query DSL supports following operators: Is equal: column == value (e.g. Bicycle.id == 1) Is not equal: column != value Is less than: column < value Is less than or equal: column <= value Is greater than: column > value Is greater than or equal: column => value And: expression && expression Or: expression || expression Inverse: !expression Is null: !column Contains: column ∈ [value] or contains(column, value) String lowercase: column.lowercase() String uppercase: column.uppercase() In-string search: column.like(value) (e.g. Bicycle.name.like("%bike%")) column means an instance of a Column struct, e.g. Bicycle.id. value means any value that works with SQL, like Int, String, Double, etc. expression is anything returned by one of these operators Who made this?Who made this? I did. My name is Ulrik Flænø Damm, I’m an iOS and Unity developer at Northplay in Copenhagen. You can follow me on Twitter, or visit my website. If you want to contribute with code or ideas, open some issues or submit some pull requests!
https://swiftpackageregistry.com/ulrikdamm/Sqlable
CC-MAIN-2022-33
refinedweb
1,568
61.12
Using WebSockets on Heroku with Java and the Play Framework Last updated 09 September 2015 Table of Contents This tutorial demonstrates how to build a Java and Play Framework application that uses a WebSocket, deployed to Heroku. Sample code for the demo application is available on GitHub. Edits and enhancements are welcome. Just fork the repository, make your changes and send us a pull request. Prerequisites - Java, Play Framework 2.x, and the Heroku Toolbelt (as described in the Heroku CLI setup article) - A Heroku user account. Signup is free and instant. Create WebSocket app The sample application provides a simple example of using a WebSocket with Java and Play. You can clone the sample and follow along with the code as you read. If you’d rather write the app yourself you can add the sample code to a new Play app as you go. Option 1. Clone the sample app If you want to get going more quickly you can just clone the sample app: $ git clone git@github.com:heroku-examples/play-websockets-sample.git Cloning into 'play-websockets-sample'... remote: Counting objects: 31, done. remote: Compressing objects: 100% (24/24), done. remote: Total 31 (delta 0), reused 31 (delta 0) Receiving objects: 100% (31/31), 38.33 KiB | 0 bytes/s, done. Checking connectivity... done Option 2. Create a new Play app $ play new _ _ __ | | __ _ _ _ | '_ \| |/ _' | || | | __/|_|\____|\__ / |_| |__/ play 2.2.0 built with Scala 2.10.2 (running Java 1.6.0_51), The new application will be created in /Users/jsimone/dev/supportApps/play22test ... Choose an application name and Java as the language. Functionality The sample application renders a simple web page that will open a WebSocket to the backend. The server will send a payload containing the time over the WebSocket once a second. That time will be displayed on the page. There are 3 important pieces to the interaction that takes place here: a controller method that returns a WebSocket object, a JavaScript method that opens that WebSocket, and an Akka actor that sends the payload across that WebSocket every second. Let’s explore each. Controller You can return a WebSocket from a Play controller method. There is an example in /app/controllers/Application.java in the sample application: public static WebSocket<String> pingWs() { return new WebSocket<String>() { public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) { final ActorRef pingActor = Akka.system().actorOf(Props.create(Pinger.class, in, out)); final Cancellable cancellable = Akka.system().scheduler().schedule(Duration.create(1, SECONDS), Duration.create(1, SECONDS), pingActor, "Tick", Akka.system().dispatcher(), null ); in.onClose(new Callback0() { @Override public void invoke() throws Throwable { cancellable.cancel(); } }); } }; } public static Result pingJs() { return ok(views.js.ping.render()); } public static Result index() { return ok(index.render()); } This method returns a new WebSocket object that has a String as its payload. In the WebSocket object we define the onReady() method to talk to an actor via the Akka scheduler. The work of sending data over the socket will occur in that actor. When the WebSocket is closed the callback registered on the input stream will be called. The other methods will render our js and html templates. We’ll also need a route to be set up for these methods in our routes file: # Home page GET / controllers.Application.index() GET /pingWs controllers.Application.pingWs() GET /assets/javascripts/ping.js controllers.Application.pingJs() Model In the controller example you’ll notice that we pass around the in and out streams of the WebSocket. In our actor we’re able to read from and write to these streams just like any other IO stream. Here’s the code for the Pinger actor ( /app/models/Pinger.java): package models; public class Pinger extends UntypedActor { WebSocket.In<String> in; WebSocket.Out<String> out; public Pinger(WebSocket.In<String> in, WebSocket.Out<String> out) { this.in = in; this.out = out; } @Override public void onReceive(Object message) { if (message.equals("Tick")) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); out.write(sdf.format(cal.getTime())); } else { unhandled(message); } } } You’ll notice that this actor counts on the schedule defined in the controller method to send it a “Tick” message every second. When that happens it sends the current date and time over the WebSocket. Views The final piece is the client code that will call the WebSocket. For this our sample application uses Scala templates to render JavaScript and HTML called /app/views/ping.scala.js and /app/views/index.scala.html respectively. index.scala.html provides a div to display the data in and references the JavaScript: @main("Welcome to Play") { <strong>Stats</strong><br> <div id="ping"></div> <script type="text/javascript" charset="utf-8" src="@routes.Application.pingJs()"></script> } ping.scala.js connects to the WebSocket and defines the receiveEvent method to populate the dates into the displayed div as they come across: $(function() { var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket var dateSocket = new WS("@routes.Application.pingWs().webSocketURL(request)") var receiveEvent = function(event) { $("#ping").html("Last ping: "+event.data); } dateSocket.onmessage = receiveEvent }) Deploy It’s time to deploy your app to Heroku. If you haven’t done so already put your application into a git repository: $ git init $ git add . $ git commit -m "Ready to deploy" Create the Heroku app to deploy to: $ heroku create Creating high-lightning-129... done, stack is cedar-14 | git@heroku.com:high-lightning-129.git Git remote heroku added Deploy your code with git push. $ Scaling This app demonstrates simple usage of a WebSocket. For production use, and any app that requires more than a single web dyno, please read about building a scalable app with WebSockets.
https://devcenter.heroku.com/articles/play-java-websockets
CC-MAIN-2016-18
refinedweb
960
52.15
// python script to solve the 8 queens problem def allowedMoves(usedCol, usedDiagL, usedDiagR): allowed = ~(usedCol | usedDiagL | usedDiagR) for col in (1,2,4,8,16,32,64,128): if col & allowed: yield usedCol | col, (usedDiagL | col) << 1, (usedDiagR | col) >> 1 def eightQueensSolutions(): for q0 in allowedMoves(0, 0, 0): for q1 in allowedMoves(*q0): for q2 in allowedMoves(*q1): for q3 in allowedMoves(*q2): for q4 in allowedMoves(*q3): for q5 in allowedMoves(*q4): for q6 in allowedMoves(*q5): for q7 in allowedMoves(*q6): yield (0,0,0),q0,q1,q2,q3,q4,q5,q6,q7 def solve8queens(): ''' Solves the problem of placing 8 queens on a chess board with no queen under attack. Queens are placed row by row, with the respective columns encoded by setting bit after bit in the qN variables for fast generation of allowed moves. The printboard() function decodes these to show the final board. My goal was a fast program that is easy to read. The code is a concise combination of a generator for allowed moves and a deeply nested loop to traverse the search tree. Most assignments are accomplished by function calls and loops. Speed is achieved by not using recursion, by limiting data carried through the search to three integers, and through testing for allowed moves by a single bitwise operation. For diagonal attacks, two integers (usedDiagL and usedDiagR) keep track of queens placed, and are shifted left or right bitwise as the search proceeds from row to row. On my machine, it takes 7 ms to find all 92 solutions. Because the number of queens to be placed is hardcoded (by the giant nested loop), there is no need to have branching code deciding whether the final queen was just placed (in which case you have a solution). It is not possible to parameterize the dimensions of the chess board using this approach in a way that would keep the program lean and mean. ''' solutions = [i for i in eightQueensSolutions()] for s in solutions: print '' printboard(s) print len(solutions), "solutions found" def printboard(s): b = '_Q' for i,j in zip(s[:-1],s[1:]): n = i[0] ^ j[0] print " ".join([b[(n >> y) & 1] for y in range(8-1, -1, -1)]) if __name__ == "__main__": solve8queens()
http://www.dzone.com/snippets/eight-queens-problem
CC-MAIN-2014-49
refinedweb
379
61.9
Hi , I'm using MKL with fftw3 to calculate the price of an option. I've converted code from Matlab to C++. The code used to work in VS2008 but I had to upgrade my environment and now I use VS2010 with a new compiler and it no longer works. Environment information is System Type x64-based PC Processor Intel Core2 Duo CPU P8600 @ 2.40GHz, 2401 Mhz, 2 Core(s), 2 Logical Processor(s) Intel Parallel Studio XE for Windows* (all tools) Version 2011 (SP1 Update 2 VS) Intel Math Kernel Library for Windows* Version 10.3 (9) Microsoft Visual Studio 2010 Version 10.0.30319.1 RTMRel Microsoft .NET Framework Version 4.0.30319 RTMRel Intel C++ Composer XE 2011 Update 9 Package ID: w_ccompxe_2011.9.300 Intel C++ Composer XE 2011 Update 9 Integration for Microsoft Visual Studio* 2010, Version 12.1.1109.2010, Copyright 2002-2012 Intel Corporation Intel Inspector XE 2011 Update 9 Intel Inspector XE 2011 Update 9, (build 218166), Copyright 2009-2012 Intel Corporation. All rights reserved. Intel VTune Amplifier XE 2011 Update 8 Intel VTune Amplifier XE 2011 Update 8, (build 221625), Copyright 2009-2012 Intel Corporation. All rights reserved. NB. when I look at VS2010 "about" information it does not show the MKL installed. Should it? The errors coming out from the compilation are all for the use of the MKL_INT declaration of the k variable in the for loop. Example, error is 1>AOptionPricer.cpp(310): warning C4244: 'argument' : conversion from '__int64' to 'const int', possible loss of data and the related code for this error is for ( MKL_INT k=0 ; k complex gxc = i*u[0]*y[k] ; cA[k].real = gxc.real() ; cA[k].imag = gxc.imag() ; } where the line highlighted for this error in VS2010 is complex gxc = i*u[0]*y[k] ; I am doing complex number arithmetic so need y[k] to be a vector calculation, hence the use of MKL_INT. This used to work, but now still compiles but crashes when run. I had this problem some time ago in vs20008, but corrected it with an updated compiler and I think some compiler options. Now I've updated the compiler and environment again and it does not work any more. my includes are #include "stdafx.h" #include "nr3.h" //#include #include #include #include #include #include #include "interp_1d.h" #include "interp_linear.h" #include #include "fftw3.h" #include "fftw3_mkl.h" #include "windows.h" #include "mkl_service.h" #include "mkl.h" #include "mkl_vml.h" and all are shown as found in vs2010 and as i said i have no link errors, only this conversion error. I had fixed some of the conversion errors using a static_cast for my call to pow below for (MKL_INT k=0 ; k v=pow(static_cast(k),static_cast(2.0f)) ; complex yyc = -pi*i*a*v ; cA[k].real = yyc.real() ; cA[k].imag = yyc.imag() ; } but am stuck for a fix for the aforementioned for loop. Can you please help? Thanks Ian
https://software.intel.com/en-us/forums/intel-math-kernel-library/topic/278873
CC-MAIN-2017-39
refinedweb
499
68.06
Noda Time has a guilty secret, and I’m not just talking about the fact that there’s been very little progress on it recently. (It’s not dead as a project – I have high hopes, when I can put some quality time into it.) This secret is called LocalInstant, and it’s a pain in the neck. One of the nice things about giving talks about an API you’re currently writing is that you can see which concepts make sense to people, and which don’t – as well as seeing which concepts you’re able to explain and which you can’t. LocalInstant has been an awkward type to explain right from day 1, and I don’t think it’s improved much since then. For the purpose of this blog post, you don’t actually need to know what it means, but if you’re really interested, imagine that it’s like a time-zone-less date and time (such as "10:58 on July 2nd 2015" but also missing a calendar system, so you can’t really tell what the month is etc. The important point is that it’s not just time-zone-less, but it’s actually local – so it doesn’t represent a single instant in time. Unlike every other concept in Noda Time, I haven’t thought of any good analogy between LocalInstant and the real world. Now, I don’t like having types I can’t describe easily, and I’d love to just get rid of it completely… but it’s actually an incredibly powerful concept to have in the library. Not for users of course, but for the implementation. It’s spattered all over the place. Okay, the next best step to removing it is to hide it away from consumers: let’s make it internal. Unfortunately, that doesn’t work either, because it’s referred to in interfaces all the time too. For example, almost every member of ICalendarSystem has LocalInstant as one of its parameters. The rules around interfaces Just to recap, every member of an interface – even an internal interface – is implicitly public. That causes some interesting restrictions. Firstly, every type referred to in a public interface must be public. So this would be invalid: // Doesn’t compile: Inconsistent accessibility public interface ICalendarSystem { LocalInstant GetLocalInstant(int year, int month, int day); } So far, so good. It’s entirely reasonable that a public member’s declaration shouldn’t refer to an internal type. Calling code wouldn’t understand what LocalInstant was, so how could it possibly use ICalendarSystem sensibly? But suppose we only wanted to declare the interface internally. That should be okay, right? Indeed, the compiler allows the following code: // Compiles with no problems internal interface ICalendarSystem { LocalInstant GetLocalInstant(int year, int month, int day); } But hang on… isn’t GetLocalInstant public? That’s what I said earlier, right? So we’re declaring a public member using an internal type… which we thought wasn’t allowed. Is this a compiler bug? Well, no. My earlier claim that "a public member’s declaration shouldn’t refer to an internal type" isn’t nearly precise enough. The important aspect isn’t just whether the member is declared public – but its accessibility domain. In this case, the accessibility domain of ICalendarSystem.GetLocalInstant is only the assembly, which is why it’s a valid declaration. However, life becomes fun when we try to implement ICalendarSystem in a public class. It’s perfectly valid for a public class to implement an internal interface, but we have some problems declaring the method implementing GetLocalInstant. We can’t make it a public method, because at that point its accessibility domain would be anything referring to the assembly, but the accessibility domain of LocalInstant itself would still only be the assembly. We can’t make it internal, because it’s implementing an interface member, which is public. There is an alternative though: explicit interface implementation. That comes with all kinds of other interesting points, but it does at least compile: internal interface ICalendarSystem { LocalInstant GetLocalInstant(int year, int month, int day); } public class GregorianCalendarSystem : ICalendarSystem { // Has to be implemented explicitly LocalInstant ICalendarSystem.GetLocalInstant(int year, int month, int day); { // Implementation } } So, we’ve got somewhere at this point. We’ve managed to make a type used within an interface internal, but at the cost of making the interface itself internal, and requiring explicit interface implementation within any public classes implementing the interface. That could potentially be useful in Noda Time, but it doesn’t solve our real LocalInstant / ICalendarSystem problem. We need ICalendarSystem to be public, because consumers need to be able to specify a calendar when they create an instance of ZonedDateTime or something similar. Interfaces are just too demanding in terms of publicity. Fortunately, we have another option up our sleeves… Abstract classes to the rescue! I should come clean at this point and say that generally speaking, I’m an interface weenie. Whenever I need a reusable and testable abstraction, I reach for interfaces by default. I have a general bias against concrete inheritance, including abstract classes. I’m probably a little too harsh on them though… particularly as in this case they do everything I need them to. In Noda Time, I definitely don’t need the ability to implement ICalendarSystem and derive from another concrete class… so making it a purely abstract class will be okay in those terms. Let’s see what happens when we try: public abstract class CalendarSystem { internal abstract LocalInstant GetLocalInstant(int year, int month, int day); } internal class GregorianCalendarSystem : CalendarSystem { internal override LocalInstant GetLocalInstant(int year, int month, int day) { // Implementation } } Hoorah! Now we’ve hidden away LocalInstant but left CalendarSystem public, just as we wanted to. We could make GregorianCalendarSystem public or not, as we felt like it. If we want to make any of CalendarSystem‘s abstract methods public, then we can do so provided they don’t require any internal types. There’s on interesting point though: types outside the assembly can’t derive from CalendarSystem. It’s a little bit as if the class only provided an internal constructor, but with a little bit more of an air of mystery… you can override every method you can actually see, and still get a compile-time error message like this: ‘CalendarSystem.GetLocalInstant(int, int, int)’ I can just imagine the author of the other assembly thinking, "But I can’t even see that method! What is it? Where is it coming from?" Certainly a case where the documentation needs to be clear. Whereas it’s impossible to create an interface which is visible to the outside world but can’t be implemented externally, that’s precisely the situation we’ve reached here. The abstract class is a little bit like an authentication token given by a single-sign-on system. From the outside, it’s an opaque item: you don’t know what’s in it or how it does its job… all you know is that you need to obtain it, and then you can use it to do other things. On the inside, it’s much richer – full of useful data and members. Conclusion Until recently, I hadn’t thought of using abstract classes like this. It would possibly be nice if we could use interfaces in the same way, effectively limiting the implementation to be in the declaring assembly, but letting the interface itself (and some members) be visible externally. A bigger question is whether this is a good idea in terms of design anyway. If I do make LocalInstant internal, there will be a lot of interfaces which go the same way… or become completely internal. For example, the whole "fields" API of Noda Time could become an implementation detail, with suitable helper methods to fetch things like "how many days are there in the given month." The fields API is an elegant overall design, but it’s quite complicated considering the very limited situations in which most callers will use it. I suspect I will try to go for this "reduced API" for v1, knowing that we can always make things more public later on… that way we give ourselves a bit more flexibility in terms of not having to get everything right first time within those APIs, too. Part of me still feels uncomfortable with the level of hiding involved – I know other developers I respect deeply who hide as little as possible, for maximum flexibility – but I do like the idea of an API which is really simple to browse. Aside from the concrete use case of Noda Time, this has proved an interesting exercise in terms of revisiting accessibility and the rules on what C# allows. 30 thoughts on “The curious case of the publicity-seeking interface and the shy abstract class” Too cool. Even I would be thinking to build a few internal interfaces and expose only those methods which will be used. Cheers. :) Why would you say a member on an internal interface is public? It’s clearly internal. You can’t access that member from outside the assembly. That’s like having internal class C { public void Member() { } } is C.Member here public? No, it’s internal. About interfaces, you *can* have interfaces with both public and internal members, using ugly interface inheritance. public interface ICalendarSystem { public methods; } internal interface ICalendarSystemInternal { LocalInstant GetLocalInstant(int year, int month, int day); } Of course, that does come with a pretty steep price – you’d have to check that the calendar system is an internal one every time and you’ve basically lost any type safety. @configurator: No, it’s clearly public. Look in the IL, look at the spec. They’re both very explicit about it. Your C.Member member is public, but its accessibility domain is the assembly. There’s a difference, and it’s relevant. Actually I think it’s OK to expose this type publicly, even if you don’t have an easy way to explain what it does. Even though most users won’t use it, it will still be available to advanced users who do understand how the library works internally. The .NET framework has a lot of public types that come with this description: “This API supports the .NET Framework infrastructure and is not intended to be used directly from your code” I think you could do something similar with LocalInstant… “I know other developers I respect deeply who hide as little as possible, for maximum flexibility” Hmmm. Now, I would have said that hiding as much as possible gives you the most flexibility. It depends what you want to be flexible about. If you hide as much as possible, especially in a framework whose use you don’t control, you will have much more flexibility to change it later. The more you expose, the more brittle to change it becomes. Also, I have for many years railed against this obsession with interfaces many developers have. You are almost always better off starting with a class (abstract or not). The reason is reversibility. When you discover a problem with your design, it’s easy to extract an interface from a class (and it’s generally obvious when it’s a good idea), but it’s not so easy to go the other way. I believe interfaces are another one of these “last responsible moment” things. Waiting for the right interfaces to fall out of the design is often better than just throwing one in whenever you think one might be required. And I don’t like Thomas’ suggestion. Just because MS do it doesn’t make it a good idea. @Jim: Hiding everything gives the *implementor* flexibility later on. Exposing everything gives the *caller* flexibility. Sorry for not being clear. I’m still generally in favour of interfaces as a “purer” expression of an abstraction, but I think they’ll win me over in this case. I *do* definitely disagree with Thomas, in that I really don’t like having bits of the API which I effectively have to say “Look but don’t touch” about. It also makes the API harder to explore, when there’s more of it. All this disagreement is very healthy though, I think :) I’ve used the ‘internal abstract’ technique a lot over the years. I tend towards trying to hide as much as possible, as shipping an API to third-party users means committing to a contract: you want that contract to be as narrow and precise as you can make it, yet still get the job done. As I said in an earlier tweet, it comes in useful for class hierarchies that are not open to be derived from in third-party code; and this actually happens quite often when writing APIs. I often use polymorphism for interface-level assignment compatibility purposes, but not for third-party reuse. An example might be in a reflection mechanism: Member might have a name and visibility, while Method deriving from Member may introduce Parameters and ReturnType, etc. But a reflection mechanism (e.g. built into a langauge’s RTL) isn’t generally meant to be derived from by third parties, as the language isn’t usually extensible by third parties. Thus internal abstract methods (or equivalents) help with creating a nice API, but being able to communicate effectively behind the scenes to get the functionality working. Other thing: as to interfaces as “purer” expressions of an abstraction, I agree, but only if the abstraction definitely is pure. Since there’s no way to change the interface after it’s been shipped, you have to be absolutely certain of the abstraction being modeled. If in doubt, then use a class. All right, I must be missing something big here. What does it matter if the member is public or internal in an internal class? What’s the difference, and why is it relevant? The last code snippet carried over the “Has to be implemented explicitly” comment when it no longer applies. (Clearly there’s a rant about the merits of comments hiding here.) @configurator: The problem is that when you override a method (or implement an interface method) it has to be as public as the original declaration. So you can’t implicitly implement an internal interface method with an internal method, which is what you probably want to do. @Blake: Oops, thanks :) Fixed. As I understand it, the problem at hand is not the exposure of the LocalInstant type per se, but rather that it is hard to explain? In that case perhaps it would be sufficient to find a better name for the type, and leave it exposed (which is not necessarily easier). The name RelativeInstant pops up in my head; it describes an instant that is defined only in relation to some other non-relative instant. Not sure that would make things more clear though. Either way, interesting use of abstract classes (that I often feel is a feature that doesn’t get the love it deserves). Slight digression: does the recent DateTimeOffset structure in .NET 3.5 have any consequences for Noda? @Fredrik: Well, I don’t want to expose any types that the caller doesn’t need to use, ideally… and I don’t *think* they really ought to be thinking in terms of LocalInstant. Whatever the name is, I’d have to describe it in words – and that’s proved extremely difficult :( @Rob: We’ll probably have a conversion to DateTimeOffset where appropriate, but that’s all. Right, you can’t implicitly implement an internal interface member with an internal member. But you can explicitly, and that’s just semantics (although I don’t like explicit implementation syntax I don’t think it really matters). Anything else that’s different between the members being public or internal? @configurator: “That’s just semantics” always seems a strange phrase to me. What’s the difference between a cat and a data-center? Just semantics. The two words just mean different things, that’s all – semantics. Explicit interface implementation comes with some odd bits and pieces, including making it awkward to call a method from the same class, and making it impossible to override the member in a derived class. Another option could be to nest the LocalInstant class in the abstract base class and make it protected internal. That would enable anyone inheriting from the base class to use it while keeping it hidden during normal use. Hi! Fun post, it’s a long time since I’ve pondered about the different impacts of visibility between abstractions. I think it is good that Noda now will scale down and focus on getting something out there that will satisfy most users. Most users use standard .Net 2 or above, they use the System.DateTime type and they are familiar with the methods exposed by this class. I also think that most users have never used Joda, and is not familiar with the Joda API. Thus at least I think it is natural to avoid transelaring the API directly, but rather rethink how the API should be exposed to give developers a feeling of using their standard DateTime implementation but with calendars and time zone support. I think that this is critical to make Noda a popular choice in the .Net community. Good luck, Steianr. If your public abstract class CalendarSystem has an internal abstract method, then you should probably make all its constructors abstract as well. That makes it very obvious that CalendarSystem can’t be derived from by classes outside the assembly. I don’t think making the constructors internal would have any nasty side effects. Sorry, I meant to say ‘make its constructors internal’. Obviously constructors can’t be abstract. @Joren: Yes, that’s a good point. I’ll make sure that’s the case in Noda Time :) I’m a bit surprised you need to resort to base classes, I was thinking a public interface could derive from an internal base interface (which you could have used to hold the internal interface methods), but I’ve just tried this and found that the compiler rejects it. Why? Classes are allowed to do the same thing after all. @Freed: No, classes aren’t allowed to do the same thing – you can’t derive a public class from an internal one. And how about going with two interfaces? like so: ICalendarSystemImplementation : ICalendarSystem Where the first one is internal and explicitly implemented and the second one is public. Oh, now that I see the comments, is what Freed says but inverted, I think it works. Although, thinking it through a little more.. that won’t allow you to just take an ICalendarSystem and (internally) reference some method that uses LocalInstant.. some downcasting to ICalendarSystemImplementation will probably have to be involved, uglier.. but it may still be an option to consider though. If i understand this correct, clients of NodaTime get references to LocalInstant, maybe they also use it as parameter in own methods. If they want to test their own code, they probably want to mock LocalInstant. But they can’t as they can’t derive from it. This is currently the only thing holding me off from using this pattern. No, LocalInstantis entirely hidden – it’s internal. That’s one of the things I wanted to achieve, which interfaces wouldn’t let me do. Clients of Noda Time do get to see CalendarSystembut can’t mock it though, so you’re right on that front. However, I don’t think there’s significant benefit from them mocking it anyway. It will always be one of the existing calendar systems, so why not test with the one you want to use? I personally feel mocking is somewhat overused these days, leading to brittle tests. Thank you for your quick answer! My component provides entity objects to clients. The clients may only change an entity by calling special change methods. The entity objects also have internal methods, that only my component is allowed to call. Currently i use an external and an internal interface to separate the internal methods from the methods the clients see. When the client passes one of the entities under the external interface back to me, i cast to the internal interface to call the internal methods. This allows the client to mock/stub my entities for his own tests, which is absolutely necessary. But he can’t create instances, that satisfy my component. That’s ok. The only thing bugging me is the cast. That smells. So i was thrilled to read your solution. But it does not allow my clients to substitute my entities. Apparently i have to live with the cast.
https://codeblog.jonskeet.uk/2010/10/03/the-curious-case-of-the-publicity-seeking-interface-and-the-shy-abstract-class/?like_comment=28629&_wpnonce=2527807300
CC-MAIN-2021-10
refinedweb
3,467
62.48
This RFC proposes Cargo Templates to generate new projects from existing prototypes. A simple version was already merged (but not released in Stable) without an RFC,but some useful feedback has underlined the need to have more feedback in thedesign phase. Writing boiler plate is no fun. Starting a new project often involves writing alot of repeated code, copying a LICENSE file into place, setting cratedependencies, filling out a hello world example for the crate. In the case of adaemon, setting up the main event loop and signal handling is also somethingthat requires filling out. We propose Cargo Templates to generate new projects from existing prototypes.This lets people start projects more quickly by not having to type out boilerplate each time. Also, because the templates can be managed as a repository, they can work asway to spread up to date 'best practices' through curated templates. The design of templates consists of two sides. The interface for users, and theinterface for template writers. Users creating a new project will use templates as follows: $ cargo new foo --template Template repositories may also have multiple templates within them. Thereforeyou can specify a subdirectory: may also have sever $ cargo new foo --template --template-subdir cmdline Templates can also be taken from file:// or from the local filesystem (using apath). When using file:// or a path, it does not make sense to use--template-subdir but it file:// --template-subdir Templates will consist of two parts: a Template.toml file and the filesthemselves. The Template.toml will consist of two parts: actions andrenames. Template.toml actions renames Templates actions consist of templating a file or copying a file into place.Copying a file into place is used for binary blobs or files that do not need tobe templated (e.g. they may be templates themselves). Renames are for files that conflict with files in the template. For example,README.md and Template.toml (if you were to make a template of a template). README.md A rename entry is a list of <input-name> = output-name> <input-name> output-name> [actions] template = ["src/main.rs", "src/cmd/new.rs"] copy = [".travis.yml", "some-template.handlebars"] [renames] "README.md.in" = "README.md" "Template.toml.in" = "Template.toml" Some strings need to be escaped in different ways. For example a string in atoml file needs \" when escaping quotes and nothing for <. But html uses< for <. This is done by the template system with toml-escape andhtml-escape: \" < < toml-escape html-escape [package] name = "{{name}}" version = "0.1.0" authors = [{{toml-escape author}}] There are initially three template strings: name author date This should be documented in the crates.io documentation for the Cargo.tomlmanifest format. This adds some complication into Cargo which could possibly be better suited toan external tool, or one that is installed (e.g. clippy, etc). Templating systems exist. They tend to be focused on their own languagecommunities. e.g. Cookiecutterappears to focus on Python, while Boilrappears to focus on Go. Creating a template tool that works as a cargo subcommand which could beinstalled. This is not in line one of the goals of discoverability as new userswho want to generate a hello world project would have no simple way to see thatthe template subcommand exists. However, clippy surely has a dedicatedfollowing. clippy We can use other template libraries. For example,moustache orAskama. Using templates to reduce work is a superb idea! Now, maybe I don't understand the rationale for all the details in this pre-rfc but it seems to me like an overly complex solution. A template could just be a repo that you clone, i.e.: git clone --depth=1 --branch=master foo rm -rf !$/.git I don't really agree with the reason not to go with this alternative. There are many very useful third-party cargo subcommands already existing. If the discoverability of these is currently not good enough I think we need to improve that, rather than start shoving random subcommands into the cargo codebase. cargo Especially in this case, if this is useful enough a lot of large projects (e.g. iron, piston) along with a lot of the "intro to rust" series should be adopting it for their tutorials, giving it publicity on it's own merits instead of just because it's a part of the default cargo install (if it's widely used enough I could even see some argument towards including it as part of the default rust install as well, that still doesn't mean it needs to live in the cargo codebase). iron piston rust I do agree that it would make sense to have this as a community designed project to ensure it is useful for all use cases, but that could be done by pulling cargo-template into the nursery. I just don't see any need for it to be tightly integrated into cargo itself. cargo-template Instead of passing a git url to --template, a crates.io fork/clone/flavor for template could be created. This would shorten --template cargo new foo --template to cargo new foo --template user/rust-project-template or even cargo new foo --template rust-project-template Additionally, this would allow versioning on templates (user/web-with-angular@^1.0.0 vs user/web-with-angular@^2.0.0) and would make searching for a template for a certain purpose much easier. user/web-with-angular@^1.0.0 user/web-with-angular@^2.0.0 Then you need to go through and fill out the name, date, and author information. I mean, if using git like you suggest works for you then that's fine but I don't think it's a very nice solution. I'm very sympathetic to turning this into an external tool. while waiting on the original cargo PR to merge, I actually extricated it into a project I still have on my laptop (called mould) so I could release that instead if it ended up taking forever. mould Template Writer Interface: I agree that there needs to be some support for template strings, but I don't understand the motivation for most of the other complication in this feature. In particular, I'm not sure why any of the keys in the Template.toml file exist. Why would you want to store files in the template at anything other than their ultimate name (that is, why have the renames section)? Why have a distinction between files to be copied and templated, instead of just supporting an escape syntax in the template? If templating grows significant enough that complex knobs like this are needed, I'd rather see some sort of programmatic hook provided so that the template could contain Rust code which will be executed, instead of a declarative config file. I suspect that if we open the door like this, what we'll end up with is a junkdraw of configuration features for templates which are not fully orthogonal to one another. But in any event, anything more complex than copying all of the files over and inserting the template strings into them seems unnecessary as a first pass at this feature. User Interace: What I do think is needed is a more complex system for distributing and using templates than this RFC suggests. The point of templates is to make starting new projects following a certain template ergonomic and easy. Figuring a git repo to clone from is decidedly not that. Its important to support local paths and git repos (just as we need to for dependencies), but I think the normal path should be to just install templates from crates.io and be able to access them at the name you used to install them. I'm not exactly sure what the mechanism for implementing that is, but I do think it should be analogous to the experience of creating or installing a cargo subcommand - I upload my-template to crates.io, users can install my-template, and then cargo new --template my-template. Possibly they need to exist in their own namespace & use their own subcommands, I'm not certain. my-template cargo new --template my-template This is why I think an external system won't work - it wouldn't be able to host templates on crates.io. (I also think the --template-subdir flag is overkill for a first pass; I don't see why we should support multiple templates in a single git repo, it does not seem like a good UX to me.) I would vote for this being outside of Cargo. From the proposal it seems that it only copies files but I don't really see the point since you would normally use a git url to get it. Why not use git clone instead? To be useful like cookiecutter, it needs to ask lots of random potential variables (see example for django here:) to actually set up a useful project. I'm not a big fan of the proposed "copies and renames" design because requiring the user to manually maintain a list of every file in a template that gets copied into place seems like an anti-feature. It makes extra work for the template maintainer and it's just a mistake waiting to happen as people add, remove, and rename files and I think an "excludes and renames" design which makes "copy verbatim" the default action would make more sense. The problem with your proposed idea for a shorter syntax is that it ties the tool a little too heavily to GitHub. For example, I'd be using templates off my hard drive which may just happen to be pushed to GitHub if I think they're ready and useful to others. (cargo new --template rust-cli-boilerplate being ~/src/rust-cli-boilerplate while $PWD is ~/src) cargo new --template rust-cli-boilerplate ~/src/rust-cli-boilerplate $PWD ~/src ...and, while I currently use GitHub, I put a lot of effort into maintaining an Exit Strategy document. Your proposed solution would massively inconvenience me if I moved to BitBucket or GitLab. That's the approach the earlier one was taking. While I was giving the initial feedback which prompted the earlier implementation to be pulled, it brought up the case of "this template needs to contain a binary blob" (could be something that must be incorporated into an embedded build, could be a Windows resource like an icon or cursor, etc.) The ludicrously hyperbolic but illustrative example I gave was the idea of a Django project requiring you to hex-edit {% verbatim %} and {% endverbatim %} onto the beginning and end of the EXE files you're serving to avoid the risk of 0x7b 0x7b ({{) sequences prompting pathological behaviour. {% verbatim %} {% endverbatim %} 0x7b 0x7b {{ So that the template repository and the projects it generates don't have to share the same LICENSE, README, .travis.yml, etc. files. LICENSE README .travis.yml (eg. I have a template which is MIT/Apache licensed but generates GPLv3 projects by default. GitHub's license detector isn't smart enough to read the "This is actually MIT/Apache... it just needs LICENSE to contain the GPL for functional reasons" message in the readme.) I did in no way propose using "github-user/repo-name" or even using github at all. What I said is that a central index would be a big for the template proposal as it allow shorter names, a global index and proper versioning. No doubt most template creators will choose github as a platform, be it for technical reasons or just for convenience. But you're free to host your code anywhere else, whether it is bitbucket or even a self written git server running on free hardware. Which requirements and restrictions exactly will apply on the code hosting will be determined by creators and maintainers of the (still hypothetical) platform. I agree that you need to able to install template from other source too, but this should be a separate subcommand/flag as this is an edge case mainly required for testing. You're over-generalizing. At least one person (me) always makes templates locally and then, maybe, if they've matured enough and have enough general appeal, they'll be pushed to GitHub... but I still insist on initializing new projects from the local copy. (Among other reasons, because it's one less pointless point of failure. I've already got the authoritative copy on my hard drive. Why should I bounce it over a fallible network connection to a service which has had downtime in the past, and hope that the git->github->cargo-new chain will enforce as much tamper detection as simply never letting the data leave my system in the first place?) git->github->cargo-new In fact, getting a "too simple to have even considered non-GitHub sources" impression from their READMEs is an actual reason I've dismissed several project templating tools without reading further. ...and given what I already do with shell script and sed (and could do properly with a bit of simple Python glue), I'd be more likely to stick with my home-hacked project-templating solution than to bother building new muscle memory for something where I'd still need to wrap it up in a wrapper like I wrote for ripgrep, which fakes a different set of default command-line flags. sed As I have said, installing from a directory is a mandatory feature. Having to use a flag for that shouldn't hurt to much, though: cargo template --local ~/some-template-of-mine But please consider that the main point of having templating support isn't that experienced developers can have their custom workflows simplified, but that guides can offer a one line quickstart with batteries included. Custom workflows are of course a valid demand, but I highly doubt that it is possible to reach any consensus on that. As you've already seen for yourself, most experience developers will be best of with some shell, regex and python tailored to their individual preferences. If examples allowed an extra Cargo.toml, it would be nice to have something like cargo new --from crate_on_crates_io/basic_example. Cargo.toml cargo new --from crate_on_crates_io/basic_example Update: Another advantage of this approach is that it is in-tree, automatically tested and therefore always works with the relevant library version. Please add this (dealing with different versions) to Unresolved questions. Thanks for explaining the motivation for these features. If we want to support these, I think the easier solutions are: template If I understand the feedback so far: My prototype for a tool (currently called mold because that's like a 3d template/stencil and also old and decaying like rust, ha, puns!) which isn't in cargo has the following: mold Mold.toml ~/.local/conf/mold.d/Mold.toml nursery = {type = "git", url = ""} we can run: mold new nursery/tokio-tcp mycoolproject mold new nursery/tokio-tcp mycoolproject Further extensions could be to add a 'cargo` type which pulls from some cargo-alike for templates. I think there's not that many files you usually need to template. Cargo.toml, LICENSE, and .<continuous-integration-system>.yml. The rest will usually be verbatim. .<continuous-integration-system>.yml I'm fine with an external tool for this, as long as we can agree on one. I assume tokio-tcp is the name of the template in a repository registered as nursey. tokio-tcp nursey It seems this repositories is just for templates, how to make sure that these templates actually compile? And how to deal with multiple versions, say somebody wrote a tutorial for a library foo 2.0 and a reader wants to try it out but 3.0 was already released? foo 2.0 3.0 For the latter one tags would probably be sufficient, but how to test templates if they aren't in tree? Good question. By default we can use HEAD but I don't see why we couldn't also add a tag, branch or revision ID either at the command line or in the Mold.toml declaration. HEAD Indeed. I see it passes the 'so obvious you can tell what it's doing without having to dig through docs' test. I was thinking that I would expect packages -- e.g., tokio -- to have associated templates, so that one could do cargo new --template tokio/hello-world or something like that. This feels awfully close to the existing "examples", in fact. cargo new --template tokio/hello-world
https://internals.rust-lang.org/t/pre-rfc-cargo-templates/5056
CC-MAIN-2017-34
refinedweb
2,765
60.75
On 12:29 pm Mar 4 David Ford <david+challenge-response@blue-labs.org> wrote:> powerix root # cat /proc/acpi/battery/BAT0/state> present: yes> ERROR: Unable to read battery status>> powerix root # dmesg -c> ACPI-0279: *** Error: Looking up [BST0] in namespace,> AE_ALREADY_EXISTS ACPI-1120: *** Error: Method execution failed> [\_SB_.BAT0._BST] (Node e7bd7680), AE_ALREADY_EXISTS>> powerix root # uname -r> 2.6.4-rc1>> This has been going on since about 2.6.3-rc something. Some while> after reading the /proc files, the ability to read the battery> information gets munged.Same here on a Toshiba 1410-s173 noteboook:[logger] ACPI group battery / action battery is not defined[kernel] ACPI-0279: *** Error: Looking up [BUFF] in namespace, AE_ALREADY_EXISTSI don't think it's happened in less than 24 hours of uptime, during whicheverything is good. I have been using suspend to ram daily if that matters(echo 3 > /proc/acpi/sleep).Linux version 2.6.3-wolk1.0 (root@jackass) (gcc version 3.3.3 20040217(Gentoo Linux 3.3.3, propolice-3.3-7)) #1 Thu Feb 26 16:18:24 CST 2004\__ Jason Munro \__ jason@stdbev.com \__ unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2004/3/4/251
CC-MAIN-2017-09
refinedweb
220
50.02
Free rotating free flash banner xmlpekerja an inertial measurement unit (IMU) that outputs its orientation in q... Need a PSD of home page converted to HTML (and JS): Navigation will fun...when it gets to the top: [login to view URL] Needs to work on mobile. There are 3 images above the "view all projects". This will be on a rotating canvas. The "featured in" section needs to be scrollable, as the number of items may increase. 1. Create SWF flash file 2. Convert into HTML 5 3. Design is the attachment We are need Free International Calling App Example App: Voxofone FakeId We call .. Hi there, I wish to have a banner designed for a media photo backdrop. I would like our logo and a text "Merry Christmas" on a image i will give. Size of banner: 10x10feet Software de tv digital free tv libre online .., im looking some one talented, who can setup 123flash chat and make android and iphone application for mobil chat. only experiment guy's please! ...) - banner design ,editing,photo editing. ...add a unique movement of your parent-child based objects. [login to view URL] add both (g) mouse interaction and (h) keyboard interactions to transform hierarchy chained objects (e.g., rotating hierarchical objects) expressing different motion. [login to view URL] your (h) unique design approach/process and (i) research endeavor.... Amadeus XML API Development in PHP ..” import search filter large json file . search edit export data in many ways xls pdf etc.. will provide sample of small file and example data inside it once we discuss. winner of this project who place best bid . thanks] Designer Office tables, Chairs, Coffee tables made out of laser cutting I need 50 pages including android App Design(Graphic +XML) and Web(Graphic +Html5/css3) ...simulating up and down moment) -Steering wheel (Animation - Rotating) -Turning Front wheels(Animation - Right left) -Axle (Rotating and changing color) -The 3D model should be capable of being visualized from various angles(By click and drag of a cursor) -The car itself should be rotating on a plane graphical platform (Animation - Based on compass ([login to view URL]) - Looking for minimal and feminine design - See the attached pics for inspiration
https://www.my.freelancer.com/work/free-rotating-free-flash-banner-xml/
CC-MAIN-2018-43
refinedweb
367
57.57
Developer Materials Introduction & Getting Started - Purpose and Target Audience - Installation - Creating a new Java EE 6 project with Maven - Exploring the newly generated project - Adding a new entity using Forge - Reviewing persistence.xml & updating import.sql - Adding a new entity using JBoss Developer Studio - Deployment - Adding a JAX-RS RESTful web service - Adding a jQuery Mobile client application - Conclusion Purpose and Target Audience The target audience for this tutorial are those individuals who do not yet have a great deal of experience with: Eclipse + JBoss Tools (JBoss Developer Studio) JBoss Enterprise Application Platform 6.3 Java EE 6 features like JAX-RS HTML5 & jQuery for building an mobile web front-end. This tutorial sets the stage for the creation of TicketMonster - our sample application that illustrates how to bring together the best features of Java EE 6 + HTML5 + JBoss to create a rich, mobile-optimized and dynamic application. If you prefer to watch instead of read, a large portion of this content is also covered in video form. In this tutorial, we will cover the following topics: Working with JBoss Developer Studio (Eclipse + JBoss Tools) Creating of a Java EE 6 project via a Maven archetype Leveraging m2e and m2e-wtp Using Forge to create a JPA entity Using Hibernate Tools Database Schema Generation Deployment to a local JBoss Server Adding a JAX-RS endpoint Adding a jQuery Mobile client Using the Mobile BrowserSim Installation The first order of business is to get your development environment setup and JBoss Developer Studio v8 installed. JBoss Developer Studio is Eclipse Luna (e4.4) for Java EE Developers plus select JBoss Tools and is available for free. Visit to download it. You may also choose to install JBoss Tools 4.2 into your existing Eclipse for Java EE Developers installation. This document uses screenshots depicting JBoss Developer Studio. You must have a Java Development Kit (JDK) installed. Java 7 JDK is recommended - whilst a JVM runtime will work for most use cases, for a developer environment it is normally best to have the full JDK. The JBoss Developer Studio installer has a (very long!) name such as jboss-devstudio-8.0.0.GA-v20141020-1042-B317-installer-standalone.jar where the latter portion of the file name relates to build date and version information and the text near the front related to the target operating system. The "universal" installer is for any operating system. To launch the installer you may simply be able to double-click on the .jar file name or you may need to issue the following from the operating system command line: java -jar jboss-devstudio-8.0.0.GA-v20141020-1042-B317-installer-standalone.jar We recommend using the "universal" installer as it handles Windows, Mac OS X and Linux - 32-bit and 64-bit versions. The rest of the steps are fairly self explanatory. If you run into trouble, please consult the videos above as they explore a few troubleshooting tips related to JRE/JDK setup. You can skip the step in the installation wizard that allows you to install JBoss Enterprise Application Platform 6.3 as we will do this in the next step. Once installed, launch JBoss Developer Studio. Please make sure to say Yes to the prompt that says "Will you allow JBoss Tools team to receive anonymous usage statistics for this Eclipse instance with JBoss Tools?". This information is very helpful to us when it comes to prioritizing our QA efforts in terms of operating system platforms. More information concerning our usage tracking can be found at Creating a new Java EE 6 project with Maven Now that everything is properly installed, configured, running and verified to work, let’s build something "from scratch". We recommend that you switch to the JBoss Perspective if you have not already. First, select Start from scratch → Java EE Web Project in JBoss Central. Under the covers, this uses a Maven archetype which creates a Java EE 6 web application (.war), based around Maven. The project can be built outside of the IDE, and in continuous integration solutions like Hudson/Jenkins. You will be prompted with a dialog box that verifies that JBoss Developer Studio is configured correctly. If you are in a brand new workspace, the application server will not be configured yet and you will notice the lack of a check mark on the server/runtime row. To add JBoss Enterprise Application Platform, click on the Install… button, or if you have not yet downloaded and unzipped the server, click on the Download and Install… button. Selecting Install… will pop up the JBoss Runtime Detection section of Preferences. You can always get back to this dialog by selecting Preferences → JBoss Tools → JBoss Tools Runtime Detection. Select the Add button which will take you to a file browser dialog where you should locate your unzipped JBoss server. Select Open and JBoss Developer Studio will pop up the Searching for runtimes… window. Simply select OK. You should see the added runtime in the Paths list. Select OK to close the Preferences dialog, and you will be returned to the New Project Example dialog, with the the server/runtime found. The Target Runtime allows you to choose between JBoss Enterprise Application Platform and JBoss AS 7. If it is left empty, JBoss AS 7 will be elected. Proceed to select the EAP 6.3 runtime, you just created. You may see a warning (like the one in the screenshot), if you do not have the JBoss Enterprise Maven repository configured in your environment. Should this be the case, select the repository link in the warning, to open the JBoss Maven Integration wizard. The wizard dialog will prompt you to add the JBoss Enterprise Maven repository. Click Ok. You’ll now be shown the proposed changes to your Maven settings.xml file. Click Finish after reviewing the proposed updates. You’ll be prompted to confirm the update. Click Yes. The updates will now be persisted, and you’ll be returned to the original wizard. Now, select Next in the New Project wizard to proceed to the next step. The default Project name is jboss-javaee6-webapp. If this field appears blank, it is because your workspace already contains a "jboss-javaee6-webapp" in which case just provide another name for your project. Change the project name to ticket-monster, and the package name to org.jboss.examples.ticketmonster. Select Finish. JBoss Tools/JBoss Developer Studio will now generate the template project and import it into the workspace. You will see it pop up into the Project Explorer and a message that asks if you would like to open the cheatsheet file associated with the project. Select Finish Exploring the newly generated project Using the Project Explorer, open up the generated project, and double-click on the pom.xml. The generated project is a Maven-based project with a pom.xml in its root directory. JBoss Developer Studio and JBoss Tools include m2e and m2e-wtp. m2e is the Maven Eclipse plug-in and provides a graphical editor for editing pom.xml files, along with the ability to run maven goals directly from within Eclipse. m2e-wtp allows you to deploy your Maven-based project directly to any Web Tools Project (WTP) compliant application server. This means you can drag & drop, use Run As → Run on Server and other mechanisms to have the IDE deploy your application. The pom.xml editor has several tabs along its bottom edge. For this tutorial, we do not need to edit the pom.xml as it already provides the Java EE 6 APIs that we will need (e.g. JPA, JAX-RS, CDI). You should spend some time exploring the Dependencies and the pom.xml (source view) tabs. One key element to make note of is <version.jboss.bom.eap>6.3.2.GA</version.jboss.bom.eap> which establishes the version of the JBoss Enterprise Application Platform dependencies. The BOM (Bill of Materials) specifies the versions of the Java EE (and other) APIs defined in the dependency section. If you are using community version of the JBoss Application Server and you selected that as your Target Runtime, you will find a different property as the version string. Using the Project Explorer, drill-down into src/main/java under Java Resources. The initial project includes the following Java packages: .controller contains the backing beans for {newMember}and {memberRegistration}in the JSF page index.xhtml .data contains a class which uses @Producesand @Namedto return the list of members for index.xhtml .model contains the JPA entity class, a POJO annotated with @Entity, annotated with Bean Validation (JSR 303) constraints .rest contains the JAX-RS endpoints, POJOs annotated with @Path .service handles the registration transaction for new members .util contains Resources.java which sets up an alias for @PersistenceContextto be injectable via @Inject Now, let’s explore the resources in the project. Under src you will find: main/resources/import.sql contains insert statements that provides initial database data. This is particularly useful when hibernate.hbm2dll.auto=create-dropis set in persistence.xml. hibernate.hbm2dll.auto=create-dropcauses the schema to be recreated each time the application is deployed. main/resources/META-INF/persistence.xml establishes that this project contains JPA entities and it identifies the datasource, which is deployed alongside the project. It also includes the hibernate.hbm2dll.autoproperty set to create-dropby default. test/java/test provides the .testpackage that contains MemberRegistrationTest.java, an Arquillian based test that runs both from within JBoss Developer Studio via Run As → JUnit Test and at the command line: mvn test –Parq-jbossas-remote Note that you will need to start the JBoss Enterprise Application Platform 6.3 server before running the test. src/main/webapp contains index.xhtml, the JSF-based user interface for the sample application. If you double-click on that file you will see Visual Page Editor allows you to visually navigate through the file and see the source simultaneously. Changes to the source are immediately reflected in the visual pane. In src/main/webapp/WEB-INF, you will find three key files: beans.xml is an empty file that indicates this is a CDI capable EE6 application faces-config.xml is an empty file that indicates this is a JSF capable EE6 application ticket-monster-ds.xml when deployed, creates a new datasource within the JBoss container Adding a new entity using Forge There are several ways to add a new JPA entity to your project: - Starting from scratch Right-click on the .modelpackage and select New → Class. JPA entities are annotated POJOs so starting from a simple class is a common approach. - Reverse Engineering Right-click on the "model" package and select New → JPA Entities from Tables. For more information on this technique see this video - Using Forge to create a new entity for your project using a CLI (we will explore this in more detail below) - Reverse Engineering with Forge Forge has a Hibernate Tools plug-in that allows you to script the conversion of RDBMS schema into JPA entities. For more information on this technique see this video. For the purposes of this tutorial, we will take advantage of Forge to add a new JPA entity. This requires the least keystrokes, and we do not yet have a RDBMS schema to reverse engineer. There is also an optional section for adding an entity using New → Class. Select the project in the Project Navigator view of JBoss Developer Studio and enter the Ctrl + 4 (in Windows/Linux) or Cmd + 4 (Mac) key combination. This will launch Forge if it is not started already. The list of commands that you can execute in Forge will be visible in the Forge quick action menu. Forge is a multi-faceted rapid application development tool that allows you to enter commands that generate classes and code. You could use either a GUI within your IDE that offers a familar wizard and dialog based UI, or a shell-like interface to perform operations. It will automatically update the IDE for you. A key feature is "contentual command activation", launched by running the Forge shortcut (Ctrl + 4 or Cmd + 4). For instance, launching Forge on a selected project activates different commands, than launching it in isolation, or for that matter launching Forge with a selected Java source file. We’ll generate an entity using the Forge GUI. Let’s work through this, step by step. We start by selecting the TicketMonster project. Launch Forge through the shortcut (Ctrl + 4 or Cmd + 4). Type jpa in the command filter textbox located in the menu. The menu will filter out irrelevant entries, leaving you with JPA-specific commands. Select the "JPA: New Entity" entry in the menu. Click it or hit the Enter key to execute the command. You will be presented with a dialog where you can provide certain inputs that control how the new entity would be generated, like the package where the entity would be created, the name of the JPA entity/class, the primary-key strategy used for the entity etc. Specify the value of the entity as Event and click Finish. The defaults for other values are sufficient - note how Forge intelligently constructs the value for the package field from the Maven group Id and artifact Id values of the project. You should see a notification bubble in Eclipse when Forge completes the action. Forge would have created a JPA entity as instructed, and it would also open the Java source file in Eclipse. Note that it would have created not only a new class with the @Entity annotation, but also created a primary-key field named id, a version field, along with getters and setters for both, in addition to equals, hashCode and toString methods. Let’s add a new field to this entity. Select the Event class in the project navigator and launch the Forge menu once again. Filter on jpa as usual, and launch the "JPA: New Field" command. Specify the field name as name, to store the name of the event. The defaults are sufficient for other input fields. Click Finish or hit the Enter button as usual. You will now notice that the Event class is enhanced with a name field of type String, as well as a getter and setter, along with modifications to the toString method. Let’s now add Bean Validation (JSR-303) capabilities to the project. Launch the Forge menu, and filter for the "Constraint: Setup" command. Execute the command. You’ll be presented with a choice on what Bean Validation providers you’d like to setup in the project. The defaults are sufficient - we’ll use the Bean Validation provider supplied by the Java EE application. Click Finish or hit Enter to setup Bean valdiation. We’ll now add a constraint on the newly added name field in the Event class. Select the Event class in the project navigator and proceed to launch the "Constraint: Add" command from the Forge menu. Note that selecting the Event class allows Forge to provide commands relevant to this class in the action menu, as well as populating this class in input fields where it is fit to populate them. This launches a wizard where one can add Bean Validation constraints. The class to operate on will default to the currently selected class, i.e. Event. If you want to switch to a different class, you can do so in the wizard. There is no need to re-launch the wizard. Proceed to select the name field, on which we add a NotNull constraint. Click Finish or hit Enter. Similarly, add a Size constraint with min and max values of 5 and 50 respectively on the name field. From this point forward, we will assume you have the basics of using Forge’s menu and the commands executed thus far. Add a new field description to the Event class. Add a Size constraint on the description field to the event class, with min and max values of 20 and 1000 respectively. Add a new boolean field major. Note - you will need to change the type to boolean from the default value of String. Add another field picture to the Event class. The easiest way to see the results of Forge operating on the Event.java JPA Entity is to use the Outline View of JBoss Developer Studio. It is normally on the right-side of the IDE when using the JBoss Perspective. Alternatively, you could perform the same sequence of operations in the Forge Console, using these commands: jpa-new-entity --named Event --targetPackage org.jboss.examples.ticketmonster.model ; jpa-new-field --named name ; constraint-setup ; constraint-add --onProperty name --constraint NotNull ; constraint-add --onProperty name --constraint Size --min 5 --max 50 --message "An event's name must contain between 5 and 50 characters" ; jpa-new-field --named description ; constraint-add --onProperty description --constraint Size --min 20 --max 1000 --message "An event's description must contain between 20 and 1000 characters" ; jpa-new-field --named major --type boolean ; jpa-new-field --named picture ; Reviewing persistence.xml & updating import.sql By default, the entity classes generate the database schema, and is controlled by src/main/resources/persistence.xml. The two key settings are the <jta-data-source> and the hibernate.hbm2ddl.auto property. The datasource maps to the datasource defined in src\main\webapp\ticket-monster–ds.xml. The hibernate.hbm2ddl.auto=create-drop property indicates that all database tables will be dropped when an application is undeployed, or redeployed, and created when the application is deployed. The import.sql file contains SQL statements that will inject sample data into your initial database structure. Add the following insert statements: insert into Event (id, name, description, major, picture, version) values (1, 'Shane''s Sock Puppets', 'This critically acclaimed masterpiece...', true, '', 1); insert into Event (id, name, description, major, picture, version) values (2, 'Rock concert of the decade', 'Get ready to rock...', true, '', 1); Adding a new entity using JBoss Developer Studio Alternatively, we can add an entity with JBoss Developer Studio or JBoss Tools. First, right-click on the .model package and select New → Class. Enter the class name as Venue - our concerts & shows happen at particular stadiums, concert halls and theaters. First, add some private fields representing the entities properties, which translate to the columns in the database table. package org.jboss.examples.ticketmonster.model; public class Venue { private Long id; private String name; private String description; private int capacity; } Now, right-click on the editor itself, and from the pop-up, context menu select Source → Generate Getters and Setters. This will create accessor and mutator methods for all your fields, making them accessible properties for the entity class. Click Select All and then OK. Now, right-click on the editor, from the pop-up context menu select Source → Generate Hibernate/JPA Annotations. If you are prompted to save Venue.java, simply select OK. The Hibernate: add JPA annotations wizard will start up. First, verify that Venue is the class you are working on. Select Next. The next step in the wizard will provide a sampling of the refactored sources – describing the basic changes that are being made to Venue. Select Finish. Now you may wish to add the Bean Validation constraint annotations, such as @NotNull to the fields. Deployment At this point, if you have not already deployed the application, right click on the project name in the Project Explorer and select Run As → Run on Server. If needed, this will startup the application server instance, compile & build the application and push the application into the JBOSS_HOME/standalone/deployments directory. This directory is scanned for new deployments, so simply placing your war in the directory will cause it to be deployed. Now, deploy the h2console webapp. It can be found in the JBoss EAP quickstarts. You can read more on how to do this in the h2console quickstart. You need to deploy the h2console.war application, located in the quickstarts, to the JBoss Application Server. You can deploy this application by copying the WAR file to the $JBOSS_HOME/standalone/deployments directory. The Run As → Run on Server option will also launch the internal Eclipse browser with the appropriate URL so that you can immediately begin interacting with the application. Now, go to to start up the h2 console. Use jdbc:h2:mem:ticket-monster as the JDBC URL (this is defined in src/main/webapp/WEB-INF/ticket-monster-ds.xml), sa as the username and sa as the password. Click Connect You will see both the EVENT table, the VENUE table and the MEMBER tables have been added to the H2 schema. And if you enter the SQL statement: select * from event and select the Run (Ctrl-Enter) button, it will display the data you entered in the import.sql file in a previous step. With these relatively simple steps, you have verified that your new EE 6 JPA entities have been added to the system and deployed successfully, creating the supporting RDBMS schema as needed. Adding a JAX-RS RESTful web service The goal of this section of the tutorial is to walk you through the creation of a POJO with the JAX-RS annotations. Right-click on the .rest package, select New → Class from the context menu, and enter EventService as the class name. Select Finish. Replace the contents of the class with this sample code: package org.jboss.examples.ticketmonster.rest; @Path("/events") @RequestScoped public class EventService { @Inject private EntityManager em; @GET @Produces(MediaType.APPLICATION_JSON) public List<Event> getAllEvents() { final List<Event> results = em.createQuery( "select e from Event e order by e.name").getResultList(); return results; } } This class is a JAX-RS endpoint that returns all Events. You’ll notice a lot of errors, relating to missing imports. The easiest way to solve this is to right-click inside the editor and select Source → Organize Imports from the context menu. Some of the class names are not unique. Eclipse will prompt you with any decisions around what class is intended. Select the following: javax.ws.rs.core.MediaType org.jboss.examples.ticketmonster.model.Event javax.ws.rs.Produces java.util.List java.inject.Inject java.enterprise.context.RequestScoped The following screenshots illustrate how you handle these decisions. The Figure description indicates the name of the class you should select. You should end up with these imports: import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.examples.ticketmonster.model.Event; Once these import statements are in place you should have no more compilation errors. When you save EventService.java, you will see it listed in JAX-RS REST Web Services in the Project Explorer. This feature of JBoss Developer Studio and JBoss Tools provides a nice visual indicator that you have successfully configured your JAX-RS endpoint. You should now redeploy your project via Run As → Run on Server, or by right clicking on the project in the Servers tab and select Full Publish. Using a browser, visit to see the results of the query, formatted as JSON (JavaScript Object Notation). Adding a jQuery Mobile client application Now, it is time to add a HTML5, jQuery based client application that is optimized for the mobile web experience. There are numerous JavaScript libraries that help you optimize the end-user experience on a mobile web browser. We have found that jQuery Mobile is one of the easier ones to get started with but as your skills mature, you might investigate solutions like Sencha Touch, Zepto or Jo. This tutorial focuses on jQuery Mobile as the basis for creating the UI layer of the application. The UI components interact with the JAX-RS RESTful services (e.g. EventService.java). These next steps will guide you through the creation of a file called mobile.html that provides a mobile friendly version of the application, using jQuery Mobile. First, using the Project Explorer, navigate to src/main/webapp, and right-click on webapp, and choose New HTML file. Change directory to ticket-monster/src/main/webapp and enter name the file mobile.html. Select Next. On the Select HTML Template page of the New HTML File wizard, select New HTML File (5). This template will get you started with a boilerplate HTML5 document. Select Finish. The document must start with <!DOCTYPE html> as this identifies the page as HTML 5 based. For this particular phase of the tutorial, we are not introducing a bunch of HTML 5 specific concepts like the new form fields (type=email), websockets or the new CSS capabilities. For now, we simply wish to get our mobile application completed as soon as possible. The good news is that jQuery and jQuery Mobile make the consumption of a RESTful endpoint very simple. You will now notice the Palette View visible in the JBoss perspective. This view contains a collection of popular jQuery Mobile widgets that can be dragged and dropped into the HTML pages to speed up construction of jQuery Mobile pages. Let us first set the title of the HTML5 document as: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TicketMonster</title> </head> <body> </body> </html> We shall now add the jQuery and jQuery Mobile JavaScript and CSS files to the HTML document. Luckily for us we can do this by clicking the JS/CSS widget in the palette. This results in the following document with the jQuery JavaScript file and the jQuery Mobile JavaScript and CSS files being added to the head element. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="" /> <script src=""></script> <script src=""></script> <meta charset="UTF-8"> <title>TicketMonster</title> </head> <body> </body> </html> We shall now proceed to setup the page layout. Click the page widget in the palette to do so. Ensure that the cursor is in the <body> element of the document when you do so. This opens a dialog to configure the jQuery Mobile page. Set the page title as "TicketMonster", footer as blank, and the ID as "page1". Click Finish to add a new jQuery Mobile page to the document. The layout is now established. <"> <p>Page content goes here.</p> </div> <div data- <h4></h4> </div> </div> </body> </html> To populate the page content, remove the paragraph element: <p>Page content goes here.</p> to start with a blank content section. Click the Listview widget in the palette to start populating the content section. This opens a new dialog to configure the jQuery Mobile listview widget. Select the inset checkbox to display the list as an inset list. Inset lists do not span the entire widget of the display. Set the ID as "listOfItems". Retain the number of items in the list as three, modify the label values to One, Two and Three respectively, and finally, set the URL values to '#'. Retain the default values for the other fields, and click Finish. This will create a listview widget with 3 item entries in the list. The jQuery Mobile page is now structurally complete. <"> <ul data- <li><a href="#">One</a></li> <li><a href="#">Two</a></li> <li><a href="#">Three</a></li> </ul> </div> <div data- <h4></h4> </div> </div> </body> </html> You might notice that in the Visual Page Editor, the visual portion is not that attractive, this is because the majority of jQuery Mobile magic happens at runtime and our visual page editor simply displays the HTML without embellishment. As soon as the page loads, you can view the jQuery Mobile enhanced page. One side benefit of using a HTML5 + jQuery-based front-end to your application is that it allows for fast turnaround in development. Simply edit the HTML file, save the file and refresh your browser. Now the secret sauce to connecting your front-end to your back-end is simply observing the jQuery Mobile pageinit JavaScript event and including an invocation of the previously created Events JAX-RS service. Insert the following block of code as the last item in the <head> element <head> ... <title>TicketMonster</title> <script type="text/javascript"> $(document).on("pageinit", "#page1", function(event){ $.getJSON("rest/events", function(events) { // console.log("returned are " + events); var listOfEvents = $("#listOfItems"); listOfEvents.empty(); $.each(events, function(index, event) { // console.log(event.name); listOfEvents.append("<li><a href='#'>" + event.name + "</a>"); }); listOfEvents.listview("refresh"); }); }); </script> </head> Note: On triggering pageinit on the page having id "page1" using $.getJSON("rest/events")to hit the EventService.java a commented out // console.log, causes problems in IE Getting a reference to listOfItemswhich is declared in the HTML using an idattribute Calling .emptyon that list - removing the exiting One, Two, Threeitems For each event - based on what is returned in step 1 another commented out // console.log appendthe found event to the UL in the HTML refreshthe listOfItems The result is ready for the average mobile phone. Simply refresh your browser to see the results. JBoss Developer Studio and JBoss Tools includes BrowerSim to help you better understand what your mobile application will look like. Look for a "phone" icon in the toolbar, visible in the JBoss Perspective. The Mobile BrowserSim has a Devices menu, on Mac it is in the top menu bar and on Windows it is available via right-click as a pop-up menu. This menu allows you to change user-agent and dimensions of the browser, plus change the orientation of the device. You can also add your own custom device/browser types. Under the File menu, you will find a View Page Source option that will open up the mobile-version of the website’s source code inside of JBoss Developer Studio. This is a very useful feature for learning how other developers are creating their mobile web presence. Conclusion This concludes our introduction to building HTML5 Mobile Web applications using Java EE 6 with Forge and JBoss Developer Studio. At this point, you should feel confident enough to tackle any of the additional exercises to learn how the TicketMonster sample application is constructed. Cleaning up the generated code Before we proceed with the tutorial and implement TicketMonster, we need to clean up some of the archetype-generated code. The Member management code, while useful for illustrating the general setup of a Java EE 6 web application, will not be part of TicketMonster, so we can safely remove some packages, classes, and resources: All the Member-related persistence and business code: src/main/java/org/jboss/examples/ticketmonster/controller/ src/main/java/org/jboss/examples/ticketmonster/data/ src/main/java/org/jboss/examples/ticketmonster/model/Member.java src/main/java/org/jboss/examples/ticketmonster/rest/MemberResourceRESTService.java src/main/java/org/jboss/examples/ticketmonster/service/MemberRegistration.java src/test/java/org/jboss/examples/ticketmonster/test/MemberRegistrationTest.java Generated web content src/main/webapp/ src/main/webapp/index.xhtml src/main/webapp/WEB-INF/templates/ JSF configuration src/main/webapp/WEB-INF/faces-config.xml Prototype mobile application (we will generate a proper mobile interface) src/main/webapp/mobile.html Also, we will update the src/main/resources/import.sql file and remove the Member entity insertion: insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212' The data file should contain only the Event data import: insert into Event (id, name, description, major, picture, version) values (1, 'Shane''s Sock Puppets', 'This critically acclaimed masterpiece...', true, '', 1); insert into Event (id, name, description, major, picture, version) values (2, 'Rock concert of the decade', 'Get ready to rock...', true, '', 1); Recent Changelog - - Jan 8, 2015(Vineet Reynolds):Fixed path to MemberRegistrationTest - - Oct 28, 2014(Vineet Reynolds):Prepare for 2.7.0.ER1 release
https://developers.redhat.com/ticket-monster/introduction/
CC-MAIN-2018-09
refinedweb
5,323
56.25
On Fri, 2007-09-14 at 09:19 -0700, Randy Dunlap wrote:> On Fri, 14 Sep 2007 15:18:44 +1000 Rusty Russell wrote:> > > We turn "Virtualization" into a menu, not a config option, since it's> > actually only used as a menu. Then we move lguest under that menu.> > so you want to revert the 2007-july-16 merge that changes> menu -> menuconfig and makes most of the menus consistent in> presentation. I'd rather not, but I don't own it.Ok, I missed that one. To me it seems gratuitous to create a configoption simply to control a menu. However if that is considered theRight Way, here is the "Just move lguest" variant.> And Yes, lguest does need to be moved into a better location.Indeed,Rusty.===Move lguest under the virtualization menu.Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>diff -r c2893801de2a drivers/Kconfig--- a/drivers/Kconfig Fri Sep 14 13:24:46 2007 +1000+++ b/drivers/Kconfig Fri Sep 14 13:24:49 2007 +1000@@ -87,6 +87,4 @@ source "drivers/kvm/Kconfig" source "drivers/kvm/Kconfig" source "drivers/uio/Kconfig"--source "drivers/lguest/Kconfig" endmenudiff -r c2893801de2a drivers/kvm/Kconfig--- a/drivers/kvm/Kconfig Fri Sep 14 13:24:46 2007 +1000+++ b/drivers/kvm/Kconfig Fri Sep 14 13:32:22 2007 +1000@@ -45,4 +36,8 @@ config KVM_AMD Provides support for KVM on AMD processors equipped with the AMD-V (SVM) extensions. -endif # VIRTUALIZATION+# OK, it's a little counter-intuitive to do this, but it puts it neatly under+# the virtualization menu.+source drivers/lguest/Kconfig++endif # VIRTUALIZATION-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2007/9/14/366
CC-MAIN-2018-13
refinedweb
297
54.83
Below is the example class of the object and .txt file, I use filehelpers to create this class,then I read a .txt file using FileHelpers and it converts this file into these objects and I put them in a List. .txt file: 1122233 4455566 Example class: [FixedLengthRecord(FixedMode.AllowLessChars)] public class Example { [FieldFixedLength(2)] public string first; [FieldFixedLength(3)] public string second; [FieldFixedLength(2)] public string third; } Reading this with filehelpers gives me 2 objects of Example.The first Example.first value being '11' etc. I push this data in a database with by converting the List to a DataTable and using SqlBulkCopy. This all goes well. The table in the database just contains 3 columns(varchar) with column names; first,second and third. The problem comes when I try to fetch the data back from the database and map it back into a List, I use the following code (using Dapper) for this: IDbConnection connection = new SqlConnection(connectionString); var rows = connection.Query<Example>("select * from examplesTable"); foreach (Example e in rows) { examples.Add(e); //List<Example> examples } This returns the correct amount of rows, however if I try to fetch data from the objects, it contains null data. I can't figure out what I'm doing wrong. I would check that you have the data loaded correctly before the SQL bulk insert and then that you are not getting any errors from the bulk insert. Does the table in SQL Management studio have the correct data? If you have the correct data trying just reading as a data table to see what is brought back as that will be object values rather than a specific type. It is not possible to just write foreach (Example e in rows), you should create constructor for Example, that will create an object of Example based on the data from each row. It would look kinda like foreach (DaraRow r in rows) { Example e = new Examaple(r["First"],r["Second"]); examples.Add(e); //List<Example> examples }
https://dapper-tutorial.net/knowledge-base/32964346/how-to-map-rows-from-a-database-into-a-list-of-objects-
CC-MAIN-2021-10
refinedweb
335
64.2
08 January 2009 18:00 [Source: ICIS news] HOUSTON (ICIS news)--Here is Thursday’s mid-day ?xml:namespace> CRUDE: February WTI: $41.39/bbl, down $1.24; February Brent: $44.63/bbl, down $1.23 Crude prices worked lower, extending the previous session’s losses in response to bearish natural gas inventories and a gloomy retails sales report. WTI (West Texas Intermediate) bottomed out at $40.74/bbl before rebounding. NATURAL GAS: $5.629/MMBtu, down 24.3 cents Natural gas prices plunged following a much lower-than-expected draw in domestic inventories. Initial expectations were a 79bn cubic foot decline, but the US Energy Information Administration (EIA) showed a 47bn cubic foot decline. RBOB: $1.0721/gal, down 0.43 cents Reformulated gasoline blendstock for oxygenate blending (RBOB) prices inched down in early trading. BENZENE: US Gulf coast benzene was quiet with bids in the low-to-mid 80s cents/gal and offers notionally pegged around 91 cents/gal. ETHYLENE: US ethylene spot prices were notionally steady at 24.25-24.50 cents/lb based on the last deals heard in the market. Ethylene spot prices have jumped by about 4 cents/lb this week, lifted by higher upstream energy values. PROPYLENE: No refinery-grade propylene (RGP) spot activity was heard on Th
http://www.icis.com/Articles/2009/01/08/9182965/noon-snapshot-americas-markets-summary.html
CC-MAIN-2014-52
refinedweb
215
61.73
I really like this so far- I can see it going places as a general-purpose panel. I've always wanted something similar to Xfce built on Qt, since I love Qt and KDE applications, but it's not exactly fun to use them anywhere but KDE itself. There's no 'lighter' way to get full integration with KDE applications. Which is, of course, not at all part of this discussion, but one can dream. T3T So far it's usable, easy to look at, and generally good enough as a basic panel. The effects are a great addition and something I fully welcome, and I can see the configuration going somewhere as well. All in all, I'm quite impressed. It gives me the urge to start working on a notifier to catch KDE notifications so they don't display in an ugly box, and maybe even a light window manager that could use Kwin themes. Now that would be sick. But seriously, good job. Keep up the good work- I'll totally use this panel in place of the others in the future. Let's get this thing packaged for a wider audience, neh? Offline Just a quick note to say thanks for a very promising panel. I will keep a close eye on this as features are added. It looks great and works perfectly with Pekwm on my system at least. At this point in time though it does not fit my needs. Once I can configure it to be smaller, and auto hide on the left side of my screen I will be back. Thanks again for all your hard work. Desktop: Compiz Stand Alone w/ Cairo Dock. Laptop: Pekwm w/ Tint2 Jukebox: MPD w/ cli Gateway: Vuurmuur w/dialog Offline Status update: improved mouse interaction with dock (it will handle a click correctly, if you slightly moved the mouse between button down and button up events), and _NET_WM_ICON_GEOMETRY hints are now set up correctly. P.S. This really needs more developers. I will not have much motivation alone, since it's already doing what I wanted. Maybe it would be a good idea to tell about project to a wider audience, I'm just not sure where. Offline Hi. Thanks for panel. I'm using it on Debian and its work pretty nice. If you want more developers and tell about project to a wider audience, then probably will be the best choice. Last edited by merez (2011-07-04 08:50:13) Offline Havent had much time to look at your xdg class but depending on how your doing it this might be easyer. QSettings settings("/home/steven/Desktop/dolphin.desktop", QSettings::IniFormat); settings.beginGroup("Desktop Entry"); qDebug() << settings.value("Name").toString(); qDebug() << settings.value("Exec").toString(); qDebug() << settings.value("Icon").toString(); qDebug() << settings.value("Type").toString(); qDebug() << settings.value("Terminal").toString(); qDebug() << settings.value("MimeType").toString(); settings.endGroup(); This is the output "Dolphin" "dolphin %i -caption %c%u" "system-file-manager" "Application" "false" "inode/directory" Not sure if you know about QFreeDesktopMime … tent=86454 You can use this class for your Pager The QxtScreen class provides access to screen settings. This one is for a taskbar The QxtWindowSystem class provides means for accessing native windows. … ystem.html There part of Nokias library And not sure if you seen my last post in my thread but. You can add this for external stylesheets instead of having everything hard coded. QFile file("/root/.qtpanel/style.qss"); <----- Just replace the hard coded path with a path variable file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); setStyleSheet(styleSheet); Just letting you know because it might make things easyer for yah. Keep up the good work... Zester Last edited by zester (2011-09-01 06:07:02) Offline Fixed a problem with tray icons of wrong size. Tried to implement support for non-composited tray icons (legacy, but still used e.g. in wine), but that didn't go well. Is there someone with experience to help with that? Offline Few more improvements and polish just landed. See git log for details. Also, added configuration option for top/bottom panel position. Offline Firstly, thanks for a great little panel! bodged it manually for my setup, but it would be good to take this into account automatically when you have time to code it. Also, I made this modification which some people might find useful (middle click on windows in taskbar to close them): diff --git a/dockapplet.cpp b/dockapplet.cpp index 5d57281..4ea9ca0 100644 --- a/dockapplet.cpp +++ b/dockapplet.cpp @@ -26,7 +26,7 @@ DockItem::DockItem(DockApplet* dockApplet) setParentItem(m_dockApplet); setAcceptsHoverEvents(true); - setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton); + setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton | Qt::MiddleButton); m_textItem = new TextGraphicsItem(this); m_textItem->setColor(Qt::white); @@ -242,6 +242,11 @@ void DockItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) menu.addAction(QIcon::fromTheme("window-close"), "Close", this, SLOT(close())); menu.exec(event->screenPos()); } + + if(event->button() == Qt::MiddleButton && !m_dragging) + { + this->close(); + } } } Offline have a straightforward dual-display configuration with equal sizes, so I need your help to try this diff: diff --git a/panelwindow.cpp b/panelwindow.cpp index f400b0a..b76e288 100644 --- a/panelwindow.cpp +++ b/panelwindow.cpp @@ -224,12 +224,12 @@ void PanelWindow::updatePosition() switch(m_horizontalAnchor) { case Min: - values[0] = width(); + values[0] = x + width(); values[4] = y; values[5] = y + height(); break; case Max: - values[1] = width(); + values[1] = QApplication::desktop()->width() - x; values[6] = y; values[7] = y + height(); break; @@ -239,12 +239,12 @@ void PanelWindow::updatePosition() switch(m_verticalAnchor) { case Min: - values[2] = height(); + values[2] = y + height(); values[8] = x; values[9] = x + width(); break; case Max: - values[3] = height(); + values[3] = QApplication::desktop()->height() - y; values[10] = x; values[11] = x + width(); break; If it works well for your case, I'm going to submit it. Offline I have a straightforward dual-display configuration with equal sizes, so I need your help to try this diff: ... If it works well for your case, I'm going to submit it. Seems to work pretty well. At least, I can't find any fault with its behaviour. Awesomesauce! Thanks! Offline Seems to work pretty well. Good. The change is now pushed to public repo. Offline Great work @Mad Fish. Thank you for beautiful and useful panel. I think, it's better than lxpanel, pypanel, fbpanel etc. Last edited by hsngrms (2012-06-10 13:11:24) Offline Has anyone managed to get this working together with XMonad? I've got both XMonad.Hooks.EwmhDesktops and XMonad.Hooks.ManageDocks enabled in ~/.xmonad/xmonad.hs: import XMonad import XMonad.Actions.CycleWS import XMonad.Actions.UpdatePointer import XMonad.Hooks.EwmhDesktops import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Layout.FixedColumn import XMonad.Layout.LimitWindows import XMonad.Layout.Magnifier import XMonad.Layout.NoBorders import XMonad.Layout.Renamed import XMonad.Layout.SimplestFloat import XMonad.Prompt import XMonad.Prompt.Shell import XMonad.Prompt.Window import System.Exit import qualified XMonad.StackSet as W import qualified Data.Map as M myFont = "xft:Droid Sans:style=Bold:size=16" mySmallerFont = "xft:Droid Sans:style=Bold:size=10" myWhiteColor = "#ffffff" myLightGreyColor = "#aaaaaa" myGreyColor = "#646464" myDarkGreyColor = "#323232" myBlackColor = "#000000" myBlueColor = "#2c72c7" myRedColor = "#e20800" myBorderWidth = 2 myTerminal = "konsole" myBar = "xmobar" myWorkspaces = ["ZSH","DEV","NET","SYS"] myModMask = mod4Mask myAltMask = mod1Mask myLogHook = updatePointer (Relative 0.5 0.5) myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $ [ ((modm, xK_Escape), spawn "slock"), ((modm .|. shiftMask, xK_Escape), io (exitWith ExitSuccess)), ((modm, xK_F1), spawn "konqueror"), ((modm, xK_F2), spawn "qtfm"), ((modm, xK_F3), spawn "gwenview"), ((modm, xK_F4), spawn "qtcreator"), ((modm, xK_F5), spawn "kdbg"), ((modm, xK_F6), spawn "kontact"), ((modm, xK_F7), spawn "konversation"), ((modm, xK_F8), spawn "opera"), ((modm, xK_F9), spawn "transmission-qt"), ((modm, xK_F10), spawn "qmpdclient"), ((modm, xK_F11), spawn "ksysguard"), ((modm, xK_F12), spawn "systemsettings"), ((modm, xK_r), spawn "xmonad --restart"), ((modm, xK_Return), spawn $ XMonad.terminal conf), ((modm .|. shiftMask, xK_Return), spawn "kate"), ((modm, xK_n), prevWS), ((modm .|. shiftMask, xK_n), shiftToPrev >> prevWS), ((modm, xK_e), windows W.focusDown), ((modm, xK_i), windows W.focusUp), ((modm, xK_o), nextWS), ((modm .|. shiftMask, xK_o), shiftToNext >> nextWS), ((modm, xK_k), kill), ((modm, xK_m), windows W.swapMaster), ((modm, xK_comma), sendMessage Shrink), ((modm, xK_period), sendMessage Expand), ((0, 0x1008FF11), spawn "amixer set Master 2-"), ((0, 0x1008FF12), spawn "amixer set Master toggle"), ((0, 0x1008FF13), spawn "amixer set Master 2+"), ((modm, xK_s), spawn "scrot '%Y-%m-%d_$wx$h.png' -t 10 -e 'mv --backup=numbered {$f,$m} ~/pictures/screenshots/'"), ((modm, xK_space), shellPrompt myXPConfig), ((modm .|. myAltMask, xK_space), windowPromptGoto myXPConfig) ] -- Mouse keybindings myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $ [ ((modm, button1), (\w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)), ((modm, button2), (\w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)), ((modm, button3), windows . W.sink) ] myFull = noBorders Full myVertical = limitWindows 3 $ magnifiercz' 1.4 $ FixedColumn 1 20 80 10 myHorizontal = limitWindows 3 $ magnifiercz' 1.4 $ Mirror $ Tall nmaster delta ratio where nmaster = 1 delta = 4/100 ratio = 80/100 myFloat = simplestFloat myLayout = avoidStruts $ smartBorders $ renamed [Replace "Full"] myFull ||| renamed [Replace "Vertical"] myVertical ||| renamed [Replace "Horizontal"] myHorizontal ||| renamed [Replace "Float"] myFloat myManageHook = manageDocks <+> composeAll [ className =? "kontact" --> doShift "NET", className =? "konversation" --> doShift "NET", className =? "konqueror" --> doShift "NET", className =? "qmpdclient" --> doShift "ETC", className =? "qtcreator" --> doShift "VIM", className =? "transmission-qt" --> doShift "NET", className =? "xmessage" --> doCenterFloat ] myPP = xmobarPP { ppCurrent = xmobarColor myWhiteColor "", ppVisible = xmobarColor myBlueColor "", ppHidden = xmobarColor myGreyColor "", ppHiddenNoWindows = xmobarColor myDarkGreyColor "", ppUrgent = xmobarColor myRedColor "", ppTitle = xmobarColor myWhiteColor "" . shorten 86, ppLayout = xmobarColor myLightGreyColor "", ppSep = " » ", ppWsSep = " " } myXPConfig = defaultXPConfig { font = myFont, bgColor = myBlackColor, fgColor = myWhiteColor, bgHLight = myBlackColor, fgHLight = myBlueColor, borderColor = myBlackColor, promptBorderWidth = 0, position = Top, height = 32 } myConfig = defaultConfig { terminal = myTerminal, borderWidth = myBorderWidth, modMask = myModMask, workspaces = myWorkspaces, normalBorderColor = myBlackColor, focusedBorderColor = myGreyColor, keys = myKeys, mouseBindings = myMouseBindings, layoutHook = myLayout, manageHook = myManageHook, logHook = myLogHook } main = xmonad =<< statusBar myBar myPP (\c -> (modMask c, xK_b)) myConfig I use hsetroot to set my "desktop" background - not sure if it's relevant - and the xprop output on clicking it (as in the root window, not xmobar, qtpanel, konsole or whatever) looks like this - minus the ASCII art icons: _QT_CLIPBOARD_SENTINEL(WINDOW): window id # 0x1200002, 0x1200002 _NET_SUPPORTING_WM_CHECK(WINDOW): window id # 0xc00001 _NET_SUPPORTED(ATOM) = _NET_SUPPORTING_WM_CHECK, _NET_WM_NAME, _NET_WM_STATE_HIDDEN, _NET_NUMBER_OF_DESKTOPS, _NET_CLIENT_LIST, _NET_CLIENT_LIST_STACKING, _NET_CURRENT_DESKTOP, _NET_DESKTOP_NAMES, _NET_ACTIVE_WINDOW, _NET_WM_DESKTOP, _NET_WM_STRUT _NET_ACTIVE_WINDOW(WINDOW): window id # 0xe00017 _NET_CURRENT_DESKTOP(CARDINAL) = 0 _NET_CLIENT_LIST_STACKING(WINDOW): window id # 0xe00017, 0x240000e, 0x1e0000b, 0x1200018, 0x100000e _NET_CLIENT_LIST(WINDOW): window id # 0xe00017, 0x240000e, 0x1e0000b, 0x1200018, 0x100000e _NET_DESKTOP_NAMES(UTF8_STRING) = "ZSH", "VIM", "NET", "SYS" _NET_NUMBER_OF_DESKTOPS(CARDINAL) = 4 WM_HINTS(WM_HINTS): bitmap id # to use for icon: 0x100000b _NET_WM_ICON(CARDINAL) = Icon (16 x 16): (snip) Icon (32 x 32): (snip) Icon (64 x 64): (snip) Icon (128 x 128): (snip) ESETROOT_PMAP_ID(PIXMAP): pixmap id # 0x800001 _XROOTPMAP_ID(PIXMAP): pixmap id # 0x800001 _XKB_RULES_NAMES(STRING) = "evdev", "evdev", "us(colemak)", "", "" XFree86_VT(INTEGER) = 1 XFree86_DDC_EDID1_RAWDATA(INTEGER) = 0, -1, -1, -1, -1, -1, -1, 0, 76, -93, 66, 84, 0, 0, 0, 0, 0, 18, 1, 3, -112, 33, 21, 120, 10, -121, -11, -108, 87, 79, -116, 39, 39, 80, 84, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 48, 42, -96, 24, 82, -124, 12, 48, 64, 32, 51, 0, 75, -49, 16, 0, 0, 26, 40, 28, -96, 24, 82, -124, 12, 48, 64, 32, 51, 0, 75, -49, 16, 0, 0, 26, 0, 0, 0, -2, 0, 88, 80, 57, 55, 49, -127, 49, 53, 52, 66, 84, 10, 32, 0, 0, 0, 0, 0, 12, 16, 23, 27, 54, 105, -87, -1, 2, 1, 10, 32, 32, 0, -5 It seems to me that there is a _NET_CLIENT_LIST property on it... Moving on - xprop on xmobar: _NET_WM_PID(CARDINAL) = 2977 _NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK _NET_WM_STRUT_PARTIAL(CARDINAL) = 0, 0, 32, 0, 0, 0, 0, 0, 0, 1439, 0, 0 WM_NAME(STRING) = "xmobar" WM_CLASS(STRING) = "xmobar" xprop on qtpanel: _NET_WM_USER_TIME(CARDINAL) = 19648683 WM_STATE(WM_STATE): window state: Normal icon window: 0x0 _NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 44040201 _KDE_OXYGEN_BACKGROUND_PIXMAP(CARDINAL) = 0 _KDE_OXYGEN_BACKGROUND_GRADIENT(CARDINAL) = 1 _NET_SYSTEM_TRAY_VISUAL(VISUALID): visual id # 0x72 _KDE_NET_WM_BLUR_BEHIND_REGION(CARDINAL) = 0, 0, 1440, 32 _NET_WM_STRUT(CARDINAL) = 0, 0, 32, 0 _NET_WM_STRUT_PARTIAL(CARDINAL) = 0, 0, 32, 0, 0, 0, 0, 0, 0, 1440, 0, 0 _NET_WM_DESKTOP(CARDINAL) = 42949672955 _NET_WM_PID(CARDINAL) = 5577 _NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK, _NET_WM_WINDOW_TYPE_NORMAL ) = "qtpanel" WM_LOCALE_NAME(STRING) = "en_GB.UTF-8" WM_CLASS(STRING) = "qtpanel", "Qtpanel" WM_HINTS(WM_HINTS): Client accepts input or input focus: True Initial state is Normal State. window id # of group leader: 0x2a00005 WM_NORMAL_HINTS(WM_SIZE_HINTS): user specified location: 0, 0 program specified location: 0, 0 user specified size: 1440 by 32 program specified size: 1440 by 32 window gravity: NorthWest WM_CLIENT_MACHINE(STRING) = "wraith" WM_COMMAND(STRING) = { "qtpanel" } xprop on plasma-desktop (the KDE panel-thingy - not sure if one can run only the panel itself - and, again, without ASCII icons) _KDE_NET_WM_BLUR_BEHIND_REGION(CARDINAL) = 0, 0, 1440, 27 WM_STATE(WM_STATE): window state: Normal icon window: 0x0 _NET_WM_STRUT(CARDINAL) = 0, 0, 27, 0 _NET_WM_STRUT_PARTIAL(CARDINAL) = 0, 0, 27, 0, 0, 0, 0, 0, 0, 1439, 0, 0 _NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 44040437 _KDE_OXYGEN_BACKGROUND_PIXMAP(CARDINAL) = 0 _KDE_OXYGEN_BACKGROUND_GRADIENT(CARDINAL) = 1 _NET_STARTUP_ID(UTF8_STRING) = "0" _KDE_SLIDE(_KDE_SLIDE) = 0xffffffff, 0x1 WM_WINDOW_ROLE(STRING) = "panel_1" _NET_WM_DESKTOP(CARDINAL) = 4294967295 _KDE_NET_WM_SHADOW(CARDINAL) = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 _NET_WM_ICON(CARDINAL) = Icon (16 x 16): (snip) Icon (32 x 32): (snip) Icon (64 x 64): (snip) Icon (128 x 128): (snip)4 _NET_WM_PID(CARDINAL) = 5603 _NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK ) = "plasma-desktop" WM_LOCALE_NAME(STRING) = "en_GB.UTF-8" WM_CLASS(STRING) = "Plasma", "Plasma" WM_HINTS(WM_HINTS): Client accepts input or input focus: True Initial state is Normal State. bitmap id # to use for icon: 0x2a000f2 window id # of group leader: 0x2a00004 WM_NORMAL_HINTS(WM_SIZE_HINTS): window gravity: NorthWest WM_CLIENT_MACHINE(STRING) = "wraith" WM_COMMAND(STRING) = { "plasma-desktop" } I've been skimming through the qtpanel source, especially x11support.cpp, but haven't found anything yet. Offline totte, what exactly does not work (how it looks and behaves)? Offline totte, what exactly does not work (how it looks and behaves)? Oops, forgot that part. Same as for cf8, link, if qtpanel is set to the vertical position "top" it fills up the entire screen except for the space at the top of the screen where it should be. If I switch to another workspace and then back to the one with qtpanel, it is displayed somewhat correctly but at the bottom of the display instead of the top. If I switch between open windows (qtpanel, konsole etc) the other windows will behave the same way that qtpanel does in the second case, i.e. shrink into a small bar along the bottom of the screen. Offline qtpanel sets its size and position directly, so xmonad may not be handling _NET_WM_WINDOW_TYPE correctly. It is set to _NET_WM_WINDOW_TYPE_DOCK, which means that window manager should not mess with it. It does. Oh well. Maybe it's because _NET_WM_WINDOW_TYPE is set to two values, in order of preference? (note that this is allowed by standard and is what's done by Qt in this case) You may want to experiment there. Do other panels work? Anyway, it looks like a problem on xmonad side. I never used it myself, so... Offline Yeah I've tested a whole bunch of other panels - but most of them are GTK-based, so I thought it was of no interest to this discussion (they all seemed to work). Aside from this and the KDE plasma-whatchamacallits I haven't found any other Qt-based panels. There's the Razor-Qt project, but it didn't seem like there was an easy way to only use the panel or run the whole thing with XMonad. Anyway, I found this issue over at the XMonad issue tracker on Google Code. It seems somewhat related to what I experienced. Yesterday, I asked the nice people in #xmonad how XMonad handles multiple _NET_WM_WINDOW_TYPEs and was told the same thing, more or less, that BurntSushi stated earlier in this thread: The EWMH spec says that the first type should be considered primary. I don't know much about XMonad and Haskell, but adding this line to my ManageHook (in ~/.xmonad/xmonad.hs) at least has qtpanel stick to the top of the screen and be displayed on all workspaces: resource =? "qtpanel" --> doIgnore The applications menu works, as does the system tray! Not sure if this is a proper solution though.. Last edited by totte (2012-11-27 16:11:29) Offline. There is no documentation. Everything should be obvious as it is. Hopefully. Yes, simple config file seems totally fine for configuration - not that there is much of configuration anyway. For a pager - since I don't use multiple desktops, don't expect me to do it, but if someone implements it, I will accept it. Offline Very cool, I'd love to do it myself since I know exactly how I want it to work and be displayed. I'm a beginner though when it comes to C++ and Qt so I'm not sure if it's possible to have XMonad communicate with qtpanel the way it does with XMobar to get the current desktop, layout and focused window. I'm also thinking that the menu bar for the current window could be displayed in the qtpanel task bar area (since I don't use that in XMonad - I only need the current window) like in OS X. Thomas Luebking who made the Bespin theme put together some sort of plasmoid called Xbar that imitates this functionality. I haven't tested it though so I dunnu how stable it is. The latest Ubuntu seems to be into this OS X-like deal as well, aside from it's "dock" being glued to the left side of the screen. Just brainstorming a bit, going to clone the repository tonight and see what I can make out of it.. Configuration is applied in PanelApplication::init. Adjust size in resize() call, set horizontal anchor to Min or Max, depending on where you want your panel to be, set layout policy to Normal instead of FillSpace (so that manual size is respected). All of these should have been exposed in configuration, but I never got to it. Offline Thank you sir. It's very fine as it is. That is, after I've changed the date-time format! Offline Sorry, if this has been mentioned before: The panel border looks ugly when the background image is dark on one side of the screen and light on the other. That is, the panel seems to have a light coloured border only through half of its length. Have built again with "borderThickness = 0" (panelwindow.cpp) and find it nicer as well. Offline Some updates: Main repo is now located on GitHub (GitHub provides more convenient web interface). High-DPI (aka retina) support landed (see screenshot - 2880x1800, DPI set to 192). Last edited by Mad Fish (2013-02-23 21:54:27) Offline Is it possible to edit date string via qtpanel.conf? cmst does not seem to tray but that may not be a qtpanel problem Mr Green Offline
https://bbs.archlinux.org/viewtopic.php?pid=984736
CC-MAIN-2018-26
refinedweb
3,110
55.64
Created on 2008-02-21 15:47 by hoffman, last changed 2010-08-01 14:58 by georg.brandl. This issue is now closed. Adding these four lines to optparse.OptionGroup makes using option groups vastly easier: def __enter__(self): return self def __exit__(self, *exc_info): self.parser.add_option_group(self) You can then do things like: with OptionGroup(parser, "Group name") as group: group.add_option(...) Patch is inline. Is there anything I can do to get this feature request considered earlier? I can generate a real patch, but I figured that wouldn't necessary for something so simple. This has the advantage that it can probably be cut/pasted into any version of the code. This API is too "magical" to my liking and doesn't really reflect what context manager's are supposed to do, i.e. handling resources. Also, I don't see much advantage over: group = OptionGroup(parser, "Group name") group.add_option(...) parser.add_option_group(group) Finally, the __exit__ handler adds the option group to the parser in any case, whether there was an exception raised inside the block or not. I agree with Sebastian that this is not a good use for a context manager.
https://bugs.python.org/issue2155
CC-MAIN-2021-25
refinedweb
198
57.98
28 May 2010 17:25 [Source: ICIS news] By John Richardson and Malini Hariharan ?xml:namespace> SINGAPORE And even in the poor, benighted eurozone, where demand is the big problem, petrochemicals markets are tight because of production and currency issues. The good news, not only in “Markets are reaching a new critical mass and we are seeing much-higher multiples of growth over GDP (gross domestic product) for many of the basic plastics and chemicals than we had expected,” said a senior source with a global polyethylene (PE) producer. But none of this will matter a jot for the medium-term prospects of the industry if the numbers that really count take hold of the real economy: The price of crude and the values of the dollar and global equity markets. The fear gripping petrochemicals this week is that if financial market weakness persists, the world could be dragged into a new recession as the speculators once again wreak their havoc. Tumbling crude seems to have been a big factor behind the price falls reported across a range of products as traders have off-loaded inventory. “We are certainly seeing a lot of panicky unwinding of PE by traders in “Inventory levels in. "Buying ideas are very bad; we are waiting for concrete enquiries, said a South Korean producer on Thursday of this week. “Chinese converters are not buying as they are worried that the European crisis will result in a fall in orders for finished goods." A further factor behind the reluctance of petrochemicals buyers to place orders is likely to be volatility in crude. This could have raised the fear of being caught on the wrong side of a price correction. Depressed buying is not just confined to But, as we said, a lot of the news from For the first four months of this year, low-density polyethylene (LDPE) and polypropylene (PP) demand was up 10% at 1.2m and 4.4m tonnes respectively, compared with the same period last year, according to the Shanghai-based commodity information service, CBI. Linear-low density PE grew even faster at 36% to 1.9m tonnes, while high density PE (HDPE) demand expanded by 28% to 2.6m tonnes, added CBI. Imports of LDPE were up 35% at 638,000 tonnes, LLDPE rose by 19% to 950,000 tonnes while HDPE imports increased 9% to 1.27m tonnes. But the bad news is that much of the demand growth seems to have been captured by increased local production, which grew by 50% for both of these polymers. Details of imports by country are not yet available but it seems likely that low-cost Middle East suppliers have been able to gain market share from higher-cost Asian exporters to And in the case of PP, imports dropped 7% to 1.35m tonnes as commissioning of new plants pushed up local production by 20% to around 3m tonnes for January-April. Everyone had long-realised, though, that rising Chinese and The great news is that this is happening at a time of resilient Chinese demand-growth. There are those who, of course, fear that the Chinese economy is a giant bubble that will eventually go pop. The sceptics have been predicting a steep fall in Chinese growth for the best part of a year and it hasn’t happened. Perhaps the reason is that local consumption has a reached a level higher and more sustainable than anyone had expected. Even recent monetary tightening and the possible further withdrawal of government stimulus aren’t worrying some of the optimists. "We are at that point in time when a lot infrastructure projects funded by the stimulus package (which was announced in December 2008) will enter the construction phase, thereby boosting chemicals and plastics demand,” said the source with the second global PE producer. Media reports also recently indicated that despite reductions in loan growth, the government is no hurry to implement further major cuts in support for the economy. Officials were quoted as saying that a proactive fiscal policy and moderately easy monetary policy would continue to be pursued because of global economic uncertainties. And despite the recent rise in Other causes for cheer are consistent operating-rate discipline in the West and Saudi Arabian production constraints caused by reduced associated gas supply. This is the result of cuts in OPEC oil output aimed at keeping the crude price within the $70-80/bbl range. Privately, many senior executives believe that the long-predicted new-supply flood will not happen. However, publicly, perhaps out of the need not to over-promise to investors, they are sticking to the “severe supply-driven down-cycle” theory. In these private conversations, the executives persist with the view that the biggest danger to petrochemicals is demand. The eurozone crisis getting out of control is one of the obvious demand-side side threats they have identified. In the end, it all seems to depend, when it comes to economic prospects, on whether you view your glass as half-empty or half-full. But if the eurozone crisis accelerates out of control, what’s left in the glass might end up being drained away..
http://www.icis.com/Articles/2010/05/28/9363452/insight+better+than+expected+demand+drives+petchems.html
CC-MAIN-2013-20
refinedweb
865
57.2
Jenkins Job DSL - Properties Learn how to work with global properties in DSL Groovy script, and how to handle missing properties. If you are not familiar with Jenkins Job DSL, this post may be a good starting point; Properties When you are working with main Groovy script, all Jenkins environment variables are available as so called properties. Properties, because you main script is more than just a similar shell script, in fact you are working with an instance of a Groovy class, that’s why there are properties. For example, you can read the value of Jenkins’ BUILD_NUMBER environment variable in DSL script like this String buildNumber = ${BUILD_NUMBER} Very convenient way to read any environment variable. Additionally you can use EnvInject plugin and inject more environment variables to the build job. Missing Properties But what happens if environment variable is not defined? In that case corresponding property will not be defined as well, so if you try to read that property, you will get a runtime error. println "${NO_SUCH_PROPERTY}" So what do you do if you really want to read the variable first and if it’s not there just use sensible default? For example String rubyVersion = ${RUBY_VERSION} ?: "2.0" First thing you may try is to use hasProperty method which is a member of any Groovy class. // 'this.' can be dropped println this.hasProperty("RUBY_VERSION") ? "Yes, has property!" : "No such property" println this.metaClass.hasProperty("RUBY_VERSION") ? "Yes, has property!" : "No such property" This code will not throw a runtime error. The problem is that hasProperty will always return false. Bindings All is not lost though. Each Jenkins DSL script has a reference to so called “bindings”. Apparently, bindings are used to bind all the environment variables and make them available for the script. Additionally bindings include references to things like standard output, which will come handy later on. def configuration = new HashMap() def binding = getBinding() configuration.putAll(binding.getVariables()) That’s all you have to do to get the script bindings. Now you can access environment variables in a safe way. String buildNumber = configuration["BUILD_NUMBER"] String rubyVersion = configuration["RUBY_VERSION"] ?: "2.0" If the property is not defined, the return value is null and your code will fallback to a default value. Standard Output As I mentioned before, bindings also bind such things as standard output. By default println statements will work only when called from the body of the main script. If you use packages and other classes in your DSL, logging from other modules via println statement will not work, will not yield any output to console to be more specific. /** * Logger utility class */ class Logger { // Default standard output private static out = System.out /** * Set standard output * @param out Standard output */ public static setOutput(out) { this.out = out } /** * Log a message * @param message Message */ public static log(String message) { Logger.out.println(message) } } // Get proper standard output from bindings def configuration = new HashMap() def binding = getBinding() configuration.putAll(binding.getVariables()) // Set working stdout for Logger Logger.setOutput(configuration["out"]) // Log all you want Logger.log("This message will work in any module!") Of course it makes no sense to declare Logger class in the body of the main script. Proper way is to factor it out into a separate file and import the package instead. I plan to have a write up on advanced DSL with classes and packages. blog comments powered by Disqus
http://mgrebenets.github.io/mobile%20ci/2015/05/17/jenkins-job-dsl-properties
CC-MAIN-2017-13
refinedweb
566
57.57
: >>> import redis >>> >>> conn = redis.StrictRedis() >>> conn.set('foo', 'bar') >>> print conn.get('foo') bar >>> for c in 'this is a test': ... conn.sadd('myset', c) >>> print conn.smembers('myset') set(['a', ' ', 'e', 'i', 'h', 's', 't']) Every command for every data structure is attached to an instance of StrictRedis. If you look at the redis command set you will see there are some commands that apply to all data structures, while others apply to one data structure or another. For example, commands like exists, expire, and ttl can be used against any key in the datastore, while commands get, set, and incr, can only be applied to strings, and hget, hkeys, and hset can only be applied to hashes. A picture begins to form for the potential for an abstract base class, Key, with concrete subclasses String, List, Set, SortedSet, and Hash. Red: # _redis_methods = ['delete', 'exists', 'expire', 'expireat', 'persist', 'pexpire', 'pexpireat', 'pttl', 'ttl',] Each subclass adds to the list the methods it implements. For example, for RedisString: # _redis_methods = RedisBase._redis_methods + ['append', 'bitcount', 'decr', 'decrby', 'get', 'getbit', 'getrange', 'getset', 'incr', 'incrby', 'incrbyfloat', 'psetex', 'set', 'setbit', 'setex', 'setnx', 'setrange', 'strlen'] The magic, getattribute() def getattribute(self, name): ‘The magic that delegates redis commands to the underlying redis-py methods’ def helper(*args, **kwargs): method = getattr(get_redis_connection(), name) return method(self.key, *args, **kwargs) methods = object.__getattribute__(self, '_redis_methods') if name in methods: return helper return object.__getattribute__(self, name) The method getattribute() is called unconditionally for attribute look-up on python class instances (in python 2.X, this method exists only for new style classes, i.e., those that are subclasses of object). In lines 167-169 we get the list of delegated methods and if the attribute we’re looking up is one of these methods, we return the function helper (highlighted). If the attribute is not one of the delegated methods, we proceed with normal attribute look-up in line 171. The function helper() first finds the method named name on the global StrictRedis instance (returned by get_redis_connection(), not discussed here, but a doc string in lines 79-91 describes the function) then calls the method passing self.key as the first argument, followed by other parameters and keyword arguments, returning its value. Scanning through the file you will notice the heart of the implementation (i.e., not counting documentation and the included test suite) is Red: class MySet(RedisSet): pass mset = MySet(some_key) # use mset, lots of calls to mset.sadd() then get its size cardinality = mset.scard() or check for an item if mset.sismember(some_item): ... It would be much nicer to be able to use python idioms: create mset as above then get its size cardinality = len(mset) or check for an item if some_item in mset.sismember: ... It is very easy to add this functionality to our classes by implementing contains() and len() on RedisSet: def <strong>contains</strong>(self, item): return self.sismember(item) def __len__(self): return self.scard() We can continue to add special methods to make our classes emulate python containers. For example, if we add implementations of getitem(), setitem(), delitem(), len(), and iter() to RedisHash, plus have it subclass collections.MutableMapping, we can use inst.
https://artandlogic.com/2014/05/making-an-inherited-api-pythonic/
CC-MAIN-2021-49
refinedweb
534
54.93
So I'm really new to java programming and of course I've gotten down to the wire on an assignment and I'm stuck. I keep getting the error "plotBar cannot be resolved to a type" and I'm really clueless as to what to do I've tried many things and I'm stumped, my only other programming experience is in C programming. Here's what I'm supposed to do: A public method plotBar which returns nothing and takes in order these arguments: an int for the x-coordinate of the bar's lower-left corner, an int for the y-coordinate of the bar's lower-left corner, a double for the bar's width, and a String for the bar's text label. Suppose this method is called with: plotBar(10, 20, 57.5, "Vegan Republicans"); Then this method prints the text: newpath 10 20 moveto 57.5 0 rlineto 0 BAR_HEIGHT rlineto -57.5 0 rlineto closepath fill 67.5 20 moveto (Vegan Republicans) show This code traces the perimeter of the bar and fills it. The last two lines print the label text starting at the lower-right corner of the bar. Here's my code: package hw1; public class BarPlot { public static final int BAR_HEIGHT = 20; public void plotBar(int givenX, int givenY, double givenWidth, String name){ private int x, y; double width; x = givenX; y = givenY; width = givenWidth; } } Other than the error I was trying to figure if I'm entering the string in the method parameters correctly. Thanks for any help you can give(and yeah its due tomorrow ))
http://www.javaprogrammingforums.com/whats-wrong-my-code/3390-cannot-resolved-type.html
CC-MAIN-2016-36
refinedweb
269
65.96
Answered by: System.ArgumentNullException: Value cannot be null.Parameter name: second Question - i get this error when reading results from this query. i am using overwritechanges option because its the only way expand actually works. DataServiceQuery<Scripts> qScripts = (DataServiceQuery<Scripts>) from o in _db.Scripts.Expand("ScriptsToCampaigns") select o;Thursday, January 15, 2009 8:25 PM Answers - All replies - - hi, what is the situation for this problem ? Any patch available ? thanks, dogu doguWednesday, February 18, 2009 7:53 AM - I've had this issue today. I got it when I tried to expand an empty many-to-many relationship from a specific entity. It works fine if I don't use expand and then use LoadProperty. It also works fine if there are items in the many-to-many table for the specific entity. Is it definitely a bug? Fixed in the imminent release of 1.5? Tuesday, March 17, 2009 2:48 PM - Hello Dave, Yes, definitely a bug. Currently there is no known walkaround, but it has been fixed already. Regards, PQ Peter Q.Tuesday, March 17, 2009 8:21 PMAnswerer - Hi PQ, I've installed v1.5, changed my service app to use the new namespaces and recompiled. In my client app I've deleted the service reference and recreated it from the new 1.5-enabled service (Hence the client-side code has been regenerated) I still get this error in my client code if I try to use "expand" when retrieving related entities that don't exist. It works correctly if I just retrieve the entity, then execute "LoadProperty" on each association. The error ALWAYS occurs if the association collection is empty (eg, I am retrieving a "region" and I want to expand "contacts" for that region.....For regions that contain 1+ contacts it works fine. If a region contains 0 contacts it returns this error. Retrieving the region, then doing LoadProperty on the Contacts collection always works) I'm using standard vb.net with VS2008 3.5SP1. Dave Friday, March 20, 2009 2:29 PM - I have this issue too when I try to Expand a navigation property in a many to many relationship, but it works fine with MergeOptions.AppendOnly but I don't know why! Regards ;)Tuesday, April 7, 2009 11:10 AM - Dave, It sounds like you are describing a slightly different issue, namely expanding a navigation property that is 'empty'. Can you post the following details: - The URI / client code you are using to make the request (or whether or not it is the same as your earlier post) - The actual contents of the request and response made (you can use Fiddler ) with debugging information turned on for the service (see Phani's blog post: Debugging ADO.NET Data Services ) - The client side error message / exception you are seeing, with stack trace if possible - The model for your service, at least for the types/sets involved in this issue - Some description of the data (ie, which set is empty, which is not) Matt Meehan ADO.NET Data Services (Astoria)Tuesday, April 7, 2009 6:52 PMModerator - Vicente, Have you installed the recent 1.5 CTP release? Are you hitting the same issue with an empty collection that Dave is, or the general issue originally raised in this thread? As Peter said, there is a known issue that has been fixed in the recent CTP, so you may want to give that a try. You can find more information about it here . Matt Meehan ADO.NET Data Services (Astoria)Tuesday, April 7, 2009 6:52 PMModerator - Hi Matt, thanks for your time. I can't install the 1.5 ctp because I'm developing a production software, I must wait for the RTM version. I have the same problem that Dave and I know that it is a known issue, but I thought that Dave didn't know that he can change the MergeOption to AppendOnly and it works, almost to me :) Thanks for you time :)Tuesday, April 7, 2009 7:31 PM
https://social.msdn.microsoft.com/Forums/en-US/dd2735a3-3dfb-4a40-9a1a-f2c625fb4818/systemargumentnullexception-value-cannot-be-nullparameter-name-second?forum=adodotnetdataservices
CC-MAIN-2021-31
refinedweb
672
64.51
SOLVED Can I set os/2 font info (or other OpenType info) in script? - StephenNixon last edited by gferreira TL;DR: the answer to my question is the spec at It's very simple to set basic font info through script: # Update the family name of the current font CurrentFont().info.familyName = "New Family Name" This is great, as it allows me to efficiently update font info across many fonts, like this: from vanilla.dialogs import * inputFonts = getFile("select UFOs", allowsMultipleSelection=True, fileTypes=["ufo"]) for fontPath in inputFonts: f = OpenFont(fontPath, showInterface=False) f.info.familyName = "New Family Name" f.save() f.close() However, I'm struggling to set OS/2 info in fonts. My expectation is that something like f.info.achVendID = "ARRW"or f.info.OS_2.achVendID = "ARRW"or f.info.openTypeOS2AchVendIDwould work, but they're not. This will be even more important for me to set the vertical metrics (usWinAscent, typoDescent, etc) how I want to across many fonts. Ultimately, I hope to create one script that sets any font info across many masters (24+). Beyond help(f.info), which only gives partial insight, how can I learn the methods to set arbitrary font info? UPDATE: Just before I submitted this, I found the UFO3 spec, which is just the master list I was hoping for. So, my question is solved, but I'll post this anyway, so it's easier for the next person (possibly myself in the future) to find. I can set the vendor ID like this: f.info.openTypeOS2VendorID = "ARRW" And I can set the Hhea Descender like this: f.info.openTypeHheaDescender = -350 the spec is the place to learn about font.infoattributes, also it describes where the values go to while generating a binary. programmatically you can get all ufo3 font info attributes with: f = CurrentFont() print(f.info.fontInfoAttributesVersion3) cool!!!!! - StephenNixon last edited by Amazing; two great replies! Thanks so much :) - StephenNixon last edited by Connor, I love you. @ThunderNixon aw:) 💅
https://forum.robofont.com/topic/622/can-i-set-os-2-font-info-or-other-opentype-info-in-script
CC-MAIN-2022-40
refinedweb
330
58.08
Reversing Digits September 4, 2015 The answers are different in Scheme and Python, which surprised me. First the Scheme version, which uses digits and undigits from the Standard Prelude: (define (timing rev) (time (let ((count 0)) (do ((n 1 (+ n 1))) ((< 2000000 n) count) (when (= n (rev n)) (set! count (+ count 1))))))) (define (rev1 n) ; iterative (let loop ((n n) (z 0)) (if (zero? n) z (loop (quotient n 10) (+ (* z 10) (modulo n 10)))))) (define (rev2 n) ; recursive (define (rev n r) (if (zero? n) r (rev (quotient n 10) (+ (* r 10) (modulo n 10))))) (rev n 0)) (define (rev3 n) ; numeric split (undigits (reverse (digits n)))) (define (rev4 n) ; string split (string->number (list->string (reverse (string->list (number->string n)))))) > (timing rev1) (time (let ((...)) ...)) 22 collections 1731 ms elapsed cpu time, including 0 ms collecting 1729 ms elapsed real time, including 1 ms collecting 192005856 bytes allocated, including 185119744 bytes reclaimed 2998 > (timing rev2) (time (let ((...)) ...)) 27 collections 1747 ms elapsed cpu time, including 0 ms collecting 1751 ms elapsed real time, including 0 ms collecting 224007136 bytes allocated, including 227317600 bytes reclaimed 2998 > (timing rev3) (time (let ((...)) ...)) 132 collections 2918 ms elapsed cpu time, including 0 ms collecting 2911 ms elapsed real time, including 1 ms collecting 1116478688 bytes allocated, including 1112394288 bytes reclaimed 2998 > (timing rev4) (time (let ((...)) ...)) 317 collections 2527 ms elapsed cpu time, including 47 ms collecting 2560 ms elapsed real time, including 18 ms collecting 2668524480 bytes allocated, including 2669892448 bytes reclaimed 2998 The iterative and recursive versions are about the same, the version that uses the convenience functions from the Standard Prelude is the worst, and the version that converts back and forth to a string is in the middle. Which is what I expected. Now the Python version: from time import clock def rev(n): # iterative r = 0 while n > 0: r = r * 10 + n % 10 n = n // 10 return r print "iterative:" start = clock() count = 0 for n in xrange(100000): if n == rev(n): count += 1 print count print (clock() - start) * 1000 def rev(n, r=0): # recursive if n == 0: return r return rev(n // 10, r*10 + n%10) print "" print "recursive:" start = clock() count = 0 for n in xrange(100000): if n == rev(n): count += 1 print count print (clock() - start) * 1000 def rev(n): # convert to string return int("".join(reversed(str(n)))) print "" print "convert to string:" start = clock() count = 0 for n in xrange(100000): if n == rev(n): count += 1 print count print (clock() - start) * 1000 Running that script produces this output at ideone: iterative: 1099 184.628 recursive: 1099 265.007 convert to string: 1099 354.793 That surprised me. The recursive version is substantially slower than the iterative version. Apparently Python has slow function-calling performance. You can run the program at. You will see there that the version the converts to a string is very fast, which surprises me. Obviously the underlying cost models of Chicken Scheme, which is used by ideone, and Chez Scheme, which I run at home, are very different.); }
https://programmingpraxis.com/2015/09/04/reversing-digits/2/
CC-MAIN-2019-04
refinedweb
515
63.53
hi , when i use python to get some data from eikon, i got this error Error code 429 | Client Error: Too Many Requests - Too many requests, please try again later and this is my code: import eikon as ek ek.set_app_key('*********') df = ek.get_timeseries("USCPI=ECI",start_date="2018-01-27",end_date="2019-01-27",interval='monthly') how can i fix this problem,thx Hi @willywang Please read more information on this link regarding error code 429. hi , I can't fix the problem and it is important issue . 1.On developer community, there are so many people have same problem, but they didn't have an answer too. 2.I got some data through python api at 7 April .From then on, i can't get ant data by eikon api. how to fix this problem , thx @willywang Have you reviewed the document @chavalit.jintamalit pointed you to? This document describes the reasons why users may receive EikonError 429. It should also help you determine which specific throttle your code is triggering. If after reviewing the above doc you still cannot figure out which throttle your code is triggering and why, you can enable logging per instructions in this comment. The log will tell you which throttle limit your requests are breaching. It would also be very helpful if you provided specifics of your experience: what exactly you're doing and what results you get. Hi @willywang, Let me add a real world experience to Chavalit's answer: I have some Python code with a loop on 100 items. Inside the loop there is a request (tr.get_news_story). Running my code gave me a 429. After adding a 50 millisecond pause in the loop the error disappeared. To add the pause I added this to my imports: import time And here is the loop: for i in enumerate(index): ... time.sleep(0.05) ... You might need to tweak the pause duration to ensure you do not hit the limit. For my code, 30 ms sometimes worked, but sometimes it failed, so I finally settled for 50 ms. Hope this helps. See also this thread and this thread. How can I access the Eikon Data API using Python on macOS? Is it possible to search for all Equities listed on a particular exchange using the Eikon.get_data() function? EikonError: Error code 408 | UDF timeout occured. The operation was canceled. EikonError: Error code 429 | Client Error: Too many requests, please try again later. Wait for 51602 seconds. Eikon Data Api Not Displaying Any Streaming Prices
https://community.developers.refinitiv.com/questions/41005/error-code-429-client-error-too-many-requests-too.html
CC-MAIN-2021-21
refinedweb
423
75.1
Details Description External code: using System.Collections.Generic; public class D { } public class C<T> { public IEnumerable<U> Do<U> () where U : T { return null; } } Caller code: class B: pass C[of B]().Do[of B]() #B is internal, it works! C[of D]().Do[of D]() #D is external -> BCE0149 :( Gives: BCE0149: The type 'B' must derive from 'T' in order to substitute the generic parameter 'U' in 'C[of T].Do()'. Marking it Blocker for 0.9.1 as it blocks MonoDevelop guys wrt BooBinding. Thanks to Michael Hutchinson for reporting. FWIW, internal code works (testcase-worthy anyway): class B: pass class D (B): pass class C[of T]: def Do[of U(T)]() as U*: pass C[of B]().Do[of B]()
http://jira.codehaus.org/browse/BOO-1167?page=com.atlassian.jira.plugin.system.issuetabpanels:changehistory-tabpanel
CC-MAIN-2014-10
refinedweb
125
66.84
Talk:Tag:landuse=industrial From OpenStreetMap Wiki=* on nodes? This page suggests putting landuse=industrial on nodes, but the landuse=* page shows quite clearly that it shouldn't be used on nodes. It would kind of make sense for some of the values of industrial=* (such as industrial=machine_shop) to be put on nodes, and that tag supposedly requires landuse=industrial, but we should probably find some other way of denoting them. --Harry Cutts (talk) 03:46, 14 September 2016 (UTC) - landuse=industrial is not the only page allowing to be used on nodes. See the other tags in landuse=*. I agree that this is not nice. The taginfo count of usage on nodes suggests that there is a some need to use landuse=* on nodes. So we should probably change the landuse=* to allow it, but maybe discourage it in the text of page. Chrabros (talk) 06:25, 14 September 2016 (UTC) - The namespace landuse=* suggests it is an area (use of land), so tagging as node should ONLY occur when sufficient information to create a polygon is absent. Creating a full polygon should always be the preferred option, and a node tagged as landuse=* should assume fixme=Need survey of area --Skippern (talk) 18:37, 2 October 2016 (UTC)
https://wiki.openstreetmap.org/wiki/Talk:Tag:landuse%3Dindustrial
CC-MAIN-2018-17
refinedweb
211
59.74
Here is my solution. The idea others had, to use ax + by + c = 0 to store the lines has one big benefit: you can store these three values as integers and therefore can use your Line as key for a Hashmap. But it will also have one downside - you have to take care of cases like 1x + 1y + 0 and 2x+2y + 0 and therefore calculate the gcd which will bump your solution to O(n^2log(n)) Using the other format y = m*x + b you will end up with fractions which will be float or double which should NEVER be used in Objects that are supposed to be Hashmap keys. So how to circumvent this problem? This is the idea: mulitply the slope m and y-distance b (don't know the technical english term) by 1000 and then store this value as int. Basically you're saying you will only need 3 digits after the decimal point with a multiplier by 1000. There are two caveats: - We do have limited precision (but 3 digits after the decimal point should be enough here) - If we have "big" points we could get overflow problems (because multiplying by 1000). What do you guys think? public class Solution { public int maxPoints(Point[] points) { if(points == null || points.length == 0) { return 0; } if(points.length == 1) { return 1; } Map<Line, Set<Integer>> lineMap = new HashMap<>(); int max = 2; for(int i = 0; i < points.length-1; i++) { for(int j = i+1; j < points.length; j++) { Line cur = new Line(points[i], points[j]); if(!lineMap.containsKey(cur)) { Set<Integer> pointSet = new HashSet<>(); pointSet.add(i); pointSet.add(j); lineMap.put(cur, pointSet); } else { Set<Integer> pointSet = lineMap.get(cur); if(!pointSet.contains(i)) { pointSet.add(i); } if(!pointSet.contains(j)) { pointSet.add(j); } max = Math.max(pointSet.size(), max); } } } return max; } private static class Line { final static int ACC_MULT = 1000; // Note: slope and yDist are multiplied by ACC_MULT; int slope; int yDist; int xDist; boolean infSlope; Line(Point p1, Point p2) { if(p2.x - p1.x == 0) { infSlope = true; xDist = p1.x; } else { slope = ((p2.y - p1.y) * ACC_MULT) / (p2.x - p1.x); yDist = ((p1.x*p2.y-p2.x*p1.y) * ACC_MULT) / (p1.x-p2.x); } } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Line)) { return false; } Line line = (Line) o; return line.slope == this.slope && line.yDist == this.yDist && line.infSlope == this.infSlope && line.xDist == this.xDist; } @Override public int hashCode() { int result = 17; result = 31 * result + slope; result = 31 * result + yDist; result = 31 * result + xDist; result = 31 * result + ((infSlope) ? 1 : 0); return result; } } } What do you guys think? Two things... float or double which should NEVER be used in Objects that are supposed to be Hashmap keys You have a float/double phobia :-P The typical y = m*x + b implementation of course does suffer from inaccuracies since it calculates further with already rounded values, but I challenge you to find a case where using doubles goes wrong in the approach where each point and its slopes dy/dx to all other points are used (like this or this). 3 digits after the decimal point should be enough here You're wrong. Your program tells me that (0, 0), (10000, 10000), (100000001, 100000000), and (99999999, 100000000) are all on the same line. And that was the first thing I tried. Double and float are just not guaranteed to give you the "correct" results (eg. System.out.println(1586.6 - 708.75);) This can introduce really bad bugs in your code, so I would avoid it. Yes of course you will find examples where 3 digits after the decimal points are not enough. You will not get 100% accuracy with double either (ignoring that results even maybe wrong with double). The questions is, is it exact enough. I agree that for this use case 3 digits after the decimal point is probably stretching it. (you could increase 1000 to become more exact but even more risk an int overflow). Yes, I'm obviously aware that doubles aren't exact, but that just means you can't blindly trust them, not that you can never trust them. The challenge remains open to break the dy/dx solutions. Can you? Or just find ints a, b, c and d so that ((double) a) / b == ((double) c) / d misjudges those two slopes, i.e., that it returns something different than ((long) a) * d == ((long) c) * b Here's a fun program: class Main { public static void main(String[] args) { long double_wrong = 0, int_wrong = 0; int ACC_MULT = 1000; for (int a=1; a<=1000000; a+=12345) { for (int b=1; b<=1000000; b+=9876) { for (int c=1; c<=1000000; c+=13579) { for (int d=1; d<=1000000; d+=9764) { boolean real_eq = ((long) a) * d == ((long) c) * b; boolean double_eq = ((double) a) / b == ((double) c) / d; boolean int_eq = a * ACC_MULT / b == c * ACC_MULT / d; if (double_eq != real_eq) double_wrong++; if (int_eq != real_eq) int_wrong++; } } } } System.out.println("double was wrong " + double_wrong + " times"); System.out.println("int was wrong " + int_wrong + " times"); } } That compares your int method and the straight-forward double division against the correct judgement. The output: double was wrong 0 times int was wrong 29894 times Can you adapt your int method so that you get zero wrong times as well? And can you find test cases where the double method fails? Like previously stated it's obvious and does not need any proof that 3 digits after the decimal point is not very accurate. It is interesting that double did not fail for your loops. Maybe it is a non issue here. Generally it's a mistake to trust floating points numbers as hash keys though still. At some point you may have a horrible bug that only shows up like 0.001% of the time. Because it worked for everything before people will start trusting your method and maybe even don't know your implementation. If you are in a Coding Interview I would at least address this to the interviewer. Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/17586/true-o-n-2-solution-no-gcd-and-why-y-m-x-b-is-not-bad-after-all
CC-MAIN-2017-47
refinedweb
1,031
71.85
On 2008-04-11 11:56, Christian Heimes wrote: > M.-A. Lemburg schrieb: >> In my experience, Guido has shown that he doesn't get convinced by >> someone pointing him at a problem - he has to run into the problem >> himself. >> >> Now, Python is a community project and its user set is very diverse, >> so I'd like to see what the community thinks. If there's a tie, Guido >> can break it, but I don't really see why he should be the only one >> who's being asked. > > We had the discussion on the Python general list a while ago. Guido and > several other developers were against Java-like namespace packages for > the stdlib. We've had such discussions on and off several times during the past 8-10 years. So far, the only arguments against moving the whole Python std lib under a single package (without deeper nesting) were the following: * too much to write * hard to change all the code out there Now that we're going for a transition from 2.x to 3.x, the second argument no longer applies. 2to3.py can easily change the imports as necessary (just like it will for the stdlib reorg in general). The first argument is not really a strong one, but more a personal preference. Using a Python package will make it easier for IDEs to provide auto-complete, so over time On the plus side, we would finally have the freedom to choose any generic name we like for Python modules - without causing problems with existing code outside the std lib, e.g. all the *lib modules could have the "lib" removed. And you can finally see whether a module came from the Python std lib or some other source right in the source file. Accidental sys.path overrides will no longer happen. If I've missed any arguments against the py-package idea, please let me know. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr
https://mail.python.org/pipermail/stdlib-sig/2008-April/000249.html
CC-MAIN-2016-50
refinedweb
337
71.65
Abstract: LinkedHashMap gives us a map that retains the order in which elements were inserted. This can help us maintain a dictionary of key-value pairs in the same order as they were read in. Welcome to the 73rd edition of The Java(tm) Specialists' Newsletter. Five years ago today, I was holding my newly-released son Maximilian Francis in my arms. After last week's newsletter, some readers remarked that Dilbert could also be received via email. I knew that, but my way is more interesting than subscribing to a mailing list and has far greater applications than just "Dilbert". Another reader suggested that we should always read the "terms of use" of websites to ensure we do not inadvertantly violate a law. javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge. Did you know that the JDK 1.4.x contained a LinkedHashMap and a LinkedHashSet? I love catching people off-guard. I love it more than being caught off-guard. I was speaking to my pastor the other day and told him: "Bruce, you should put a wireless network in your house so that you can communicate with your office downstairs." Bruce had this look on his face of "Yeah, pull the other leg, I won't fall for you again!" That is a problem that wisecracks experience: even useful comments sound like jokes :-( This is similar to my experience with programmers when I mention the LinkedHashMap. It usually results in a look of puzzlement: "Should I believe that such a thing exists? Or is Heinz having me on again?" Granted, the term LinkedHashMap sounds like something I would invent, like the IdentityWeakSoftHardPhantomHashLinkMap that I spoke about in an earlier newsletter. A LinkedHashMap is a combination of hash table and linked list. It has a predictable iteration order (a la linked list), yet the retrieval speed is that of a HashMap. The order of the iteration is determined by the insertion order, so you will get the key/values back in the order that they were added to this Map. You have to be a bit careful here, since re-inserting a key does not change the original order. Let us imagine that we want to retrieve rows from a database table and convert these rows to Java Objects. Let us also imagine we are not using JDO. We need the elements in some order, and we need to search on keys quickly. Pre JDK 1.4, I would probably have made the objects Comparable and inserted them into a TreeMap. TreeMap works with a type of balanced binary tree, so the lookup would be O(log2n). If we have 1024 elements, it will take at most ten lookups. This is worse than a HashMap with a good hash function, which should only take one lookup. Keeping the tree balanced is expensive since it involves shuffling the nodes around whenever one side of the tree becomes too deep. Inserting the elements into a TreeMap is probably more expensive than sorting in your database, since the database is optimised for such things. [Balanced binary trees make excellent second-year computer science assignments. Mine did not work, but then neither did my tutor, so he gave me full marks.] With the LinkedHashMap we get the best of both worlds. We can let the database do the sorting, retrieve the rows and insert them into the LinkedHashMap. This way we can retrieve them quickly via the HashMap mechanism, but we can still iterate through them in the sorted order. To illustrate, let us use a domain that nerds know little about: Sport. We start with a Player, which we term as someone professionally engaged in a particular sporting activity. He makes his money from running around, instead of pushing a mouse around a mousepad. My father-in-law was a professional sportsman and even at sixty he is fitter than me. My brothers-in-law are world-ranked gravity racers. I was excused from physical education. import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Super athlete who earns money running around and styling * his hair nicely. */ public class Player { private final Key key; private final String name; private final Date dateOfBirth; public Player(String id, String name, Date dob) { this.key = new Key(id); this.name = name; this.dateOfBirth = dob; } public Key getKey() { return key; } public String getName() { return name; } public Date getDateOfBirth() { return dateOfBirth; } private final static DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); public String toString() { return name + " born on " + df.format(dateOfBirth); } public static final class Key { private final String id; public Key(String id) { if (id == null) { throw new IllegalArgumentException(); } this.id = id; } public int hashCode() { return id.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof Key)) return false; return id.equals(((Key) obj).id); } } } We now define a SportDatabase interface: /** * This represents some database that retrieves the Players from * a backend database. */ public interface SportDatabase { Player[] getPlayers(); } In South Africa, we put on white clothes and stand on a big field hoping for a ball to come our way. The complaining outfielders kept on "chirping", which led to the sport being called "Cricket". import java.util.Date; /** * Cricket is a boring sport that is popular in countries * previously occupied by the British Empire. Like warm * beer, the taste for cricket has to be acquired. It is * probably more of a spectator sport than unterwater hockey, * but not by much. * * South Africa does officially have a cricket team. */ public class CricketDatabase implements SportDatabase { private final static Player[] p = { new Player("12341", "Boeta Dippenaar", new Date(77, 5, 14)), new Player("23432", "Gary Kirsten", new Date(67, 10, 23)), new Player("23411", "Graeme Smith", new Date(81, 1, 1)), new Player("55221", "Jonty Rhodes", new Date(69, 6, 27)), new Player("61234", "Monde Zondeki", new Date(82, 6, 25)), new Player("23415", "Paul Adams", new Date(77, 0, 20)), }; public Player[] getPlayers() { return p; } } Note that the players are sorted by name. We assume that the players would be retrieved in that sort order from the database. We can see the difference between the HashMaps from this example: import java.util.*; public class LinkedHashMapTest { private static void fill(Map players, SportDatabase sd) { Player[] p = sd.getPlayers(); for (int i = 0; i < p.length; i++) { players.put(p[i].getKey(), p[i]); } } private static void test(Map players, SportDatabase sd) { System.out.println("Testing " + players.getClass().getName()); fill(players, sd); for (Iterator it = players.values().iterator(); it.hasNext();) { System.out.println(it.next()); } System.out.println(); } public static void main(String[] args) { SportDatabase sd = new CricketDatabase(); test(new HashMap(), sd); test(new LinkedHashMap(), sd); test(new IdentityHashMap(), sd); } } When we run this code, we get the following output: Testing java.util.HashMap Jonty Rhodes born on 1969/07/27 Graeme Smith born on 1981/02/01 Paul Adams born on 1977/01/20 Monde Zondeki born on 1982/07/25 Gary Kirsten born on 1967/11/23 Boeta Dippenaar born on 1977/06/14 Testing java.util.LinkedHashMap Boeta Dippenaar born on 1977/06/14 Gary Kirsten born on 1967/11/23 Graeme Smith born on 1981/02/01 Jonty Rhodes born on 1969/07/27 Monde Zondeki born on 1982/07/25 Paul Adams born on 1977/01/20 Testing java.util.IdentityHashMap Paul Adams born on 1977/01/20 Jonty Rhodes born on 1969/07/27 Gary Kirsten born on 1967/11/23 Graeme Smith born on 1981/02/01 Monde Zondeki born on 1982/07/25 Boeta Dippenaar born on 1977/06/14 Another application for the LinkedHashMap is in building LRU caches. One of the constructors allows us to specify that we use access order instead of insert order. The order is from least-recently accessed to most-recently. You can override the removeEldestEntry(Map.Entry) method to impose a policy for automatically removing stale when new mappings are added to the map. The implementation of this LRUCache is left as an exercise to the reader, or just look at the IdentityWeakSoftHardPhantomHashLinkMap from our earlier newsletter ;-) Kind regards Heinz P.S. In case you thought I was kidding about my brothers-in-law being world-ranked street lugers and skateboarders, search for Kytides on the gravity-sports world rankings....
https://www.javaspecialists.eu/archive/Issue073.html
CC-MAIN-2020-05
refinedweb
1,391
63.9
It would appear, based on the error message, that you have accfile defined at the outer scope as being an ifstream, and you still can't write to an ifstream. Printable View It would appear, based on the error message, that you have accfile defined at the outer scope as being an ifstream, and you still can't write to an ifstream. Anything that is declared after an opening brace has a lifetime that lasts until the corresponding closing brace and then goes "out of scope". So you cannot use accfile outside the scope where it was declared. All the errors have been sorted. I am now having a problem with only the latest pieces of data that I output being saved in the file. Whatever else was in there vanishes. From examples that I've looked at, it should be working. Am I ouputting to the file wrong? How do I correctly append the file? You should open the file with std::ios::app as the mode flag.You should open the file with std::ios::app as the mode flag.Quote: Originally Posted by Furious5k If I'm using those, I don't need to write the "std::ios::" part?If I'm using those, I don't need to write the "std::ios::" part?Code: #include <iostream> using namespace std; Do I write this? Code: accfile.setf(app); You would still need to qualify with ios.You would still need to qualify with ios.Quote: Originally Posted by Furious5k More like:More like:Quote: Originally Posted by Furious5k or:or:Code: ofstream accfile(filename, ios::app); Code: accfile.open(filename, ios::app); Could anyone point me in the right direction, I'm struggling to figure out/find example of how I can erase a line of text from a txt file? You can't. You can copy the file or the parts you want to keep. Alright, how would I go about doing that? Would I just read everything into an array and then write it back skipping the unwanted bits? The only thing I found in tutorials is "ios::trunc", would I write the following before writing everything (minus unwanted bits) to the file to get an updated version? Code: accfile.open(filename, ios::trunc, ios::app); You do not want ios::trunc, ios::app - you either want to append, or you want to truncate (which makes the file zero length) - and if you want to combine such attributes, they should be combined with | not a comma. Yes, to remove a something in a file, you have two choices: - Read all the file into memory (an array or some such), create a new file with the same name [do not crash at this point, or all data is lost!], write back out the bits you actually want to keep [of course, you can "not store them in memory" if that is easy to determine when you are reading the file into memory]. - Create a temporary file, read from the input file, write the data (except the bits you want to remove) to the temporary file. Remove the old file, then rename the temporary file to the original name. You can obviously do the first variant by writing the new data to a temporary file, then removing the original and renaming the temporary file, which avoids the "all is lost if you crash here". -- Mats Is the code for creating/removing/renaming files difficult? (working on a 10" netbook during holidays frustrated me into giving up until I got home, so I'm a bit tight on the deadlines now) I'm getting a "Segmentation fault", which is odd since I'm outputting much the same as I did before. (I made a copy of the file for crashes, thanks for the pointer).I'm getting a "Segmentation fault", which is odd since I'm outputting much the same as I did before. (I made a copy of the file for crashes, thanks for the pointer).Code: ofstream accfile; accfile.open ("loans.txt", ios::trunc | ios::app); string book; cin >> book; for (int i = 0; i < (BOOK_MAX+1); i++) { if (book == Loans[i].Book) { accfile << Loans[i].User << ";" << Loans[i].Book; } } accfile.close(); I agree with matsp: ios::trunc | ios::app does not make sense. In The C++ Standard Library: A Tutorial and Reference Josuttis states on page 632 that "other combinations not listed in the table, such as trunc|app, not allowed".
http://cboard.cprogramming.com/cplusplus-programming/110820-problem-appending-2-print.html
CC-MAIN-2014-52
refinedweb
746
70.63
Using the Windows 7 Sensor and Location Platform from C# Introduction PCs are very versatile in their connectivity with different devices. For instance with USB alone, you can connect thousands of different devices, many of which could be considered to be sensors of some kind. But what is a sensor, really? A sensor, in the Windows 7 sense, is a device that is capable of metering the physical outside world. For instance, a sensor could detect the current temperature, ambient light level, location (as in GPS), acceleration in 3D, and so forth. All in all, many different devices fit into this broad definition. This article assumes you are using the Microsoft Visual Studio 2010 Release Candidate (RC) version or later. The new location classes in .NET 4.0 have changed since the previous Beta 2 release, so if you are using the older beta, you will need to adjust the code. As for the sensor examples with Windows API Code Pack, version v1.0.1 was used. Remember that the code pack can be used with both Microsoft Visual Studio 2008 and 2010 (including Beta 2 and RC versions). Sensor and Location Platform Architecture Before Windows 7, all different sensor devices, hundreds of them, have more or less had a unique way of controlling them from code. Devices have different physical interfaces, different control commands, and their output is in different format. This makes the life of developers difficult, as each device has to be programmed differently. The Sensor and Location Platform (SLP) in Windows 7 aims to change this by providing a common program model and driver interface for all sensor (including location) devices (Figure 1). If the device has a Windows 7 SLP compatible driver available (these drivers are user-mode based, and thus can be written more easily than kernel-based drivers), Windows 7 will properly detect the device as a sensor, and then allow the SLP API to access the device. Figure 1 - Windows 7 has a new Control Panel applet to show sensor and location devices If compatible devices are present, you can, on the lowest level, use a COM API supported by SLP to communicate with the device. SLP supports a wide range of different device types, and these devices are identified with GUID values. Support for Sensors and Location in .NET In Windows 7, the new Sensor and Location Platform API is COM based, meaning that the API is available to both native and managed code applications. As a .NET developer, you could either create your own wrappers around these COM classes and interfaces, or you could use ready-made code. Currently, you have two basic options, you can use the free Windows API Code Pack to get access to the SLP features, or if you are already using .NET 4.0 with Visual Studio 2010, then you can use the new features in .NET 4.0 to access parts of the functionality provided by SLP. For those preferring to use .NET 4.0, there is a new namespace called the System.Device.Location. This namespace contains support for Windows 7's Location APIs, but does not directly support the Sensor platform, at least yet. So, with .NET 4.0 alone, you can use location services (think GPS), but for the rest of the functionality, you need to continue using the Windows API Code Pack. Since the System.Device.Location is indeed part of .NET 4.0, then technically, you could access the classes and methods even on a Windows XP machine. However, although the .NET classes are available, they will report that the state of the location system is always Disabled, unless you are using Windows 7. Thus, even if the .NET classes are available to you, it doesn't mean the operating system support is there. When programming for devices, the common developer question is: can I start developing without real hardware in my hands, and then only later start testing with a real device? The answer is yes, as far as sensors are concerned. The Windows 7 SDK contains a virtual device that emulates a physical light sensor, and has drivers that make Windows 7 think it is a real device. This makes starting development easy. As for location based services, you currently need to have a physical device in place. Of course, if you had for instance a laptop with a built-in (internal) GPS device and Windows 7 compatible SLP drivers for it, then that would work just as well. But generally speaking, most GPS devices are external. Getting Started With Sensor Development To get started with developing sensor applications for the new Sensor and Location Platform with Microsoft Visual Studio, you will need either version 2008 or 2010 (at this writing, the release candidate is the latest 2010 version), the Windows API Code Pack, and, obviously, Windows 7. If you have a physical sensor device that you can connect to your PC, you are in good hands. If you don't, then Microsoft refers you to Freescale Semiconductor. They sell a piece of hardware called the Flexis JM Badge Board, which is priced at $49. You can order one directly from Freescale, and this could then be used as basis for your own testing. For those developers that don't have a physical device in place but wish to get started with development, they should download and install the Windows 7 SDK kit (Figure 2). It takes a while to install this kit (remember to check whether you need the x86 or x64 version!), but once it is done, you can run the VirtualLightSensor.exe application from the folder Bin under the SDK installation path (by default, C:\Program Files\Microsoft SDKs\Windows\v7.0). This gives you a virtual sensor to program against. Figure 2 - The Windows 7 SDK kit gives access to a virtual light sensor that is useful when testing code Note that before you can successfully run the virtual light sensor application, you must install the proper drivers into Windows 7. This can be done from an elevated command prompt with the " pnputil -a VirtualLightSensorDriver.inf" command. You can find the .INF file in the Bin directory of the SDK kit (Figure 3). Figure 3 - Installing the driver for the virtual light sensor with PnpUtil Whether you are using a physical sensor or the virtual one provided by the Windows 7 SDK, you should see the device in Control Panel under Location and Other Sensors. Once you can see your device here, you are ready to start programming. The first step is to create or open a project in Microsoft Visual Studio, for instance a Windows Forms or Windows Presentation Foundation (WPF) application. Then, add a reference to the Windows API Code Pack (see the Resources section for the download URL), and you are set. The DLLs you need to reference are named Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Sensors.dll. With the references in place, you can start using the namespace Microsoft.WindowsAPICodePack.Sensors. This namespace contains a class named SensorManager, with which you can get overall information about the supported sensors in the system. For example: SensorList<Sensor> sensors = SensorManager.GetAllSensors(); MessageBox.Show("There are " + sensors.Count + " sensor(s) installed on the system."); Once you know that sensors are available on the system (for instance, check the Count property of the above list), you can start using each individual sensor. Sensors have properties with which you can detect their type (what kind of sensor it is) from a pre-defined set of GUIDs. With the Windows API Code Pack, the enumeration SensorTypes lists the available types. For the virtual light sensor, the type is specified as SensorTypes.AmbientLight. Since the SLP APIs are generic and support many different sensor types, you can either read sensor values in a generic manner, or by typecasting the generic sensor object to a given type. Typecasting allows you to read the values more easily. One of such specific sensor classes is AmbientLightSensor, which is derived from the generic Sensor class. To get an instance of the ambient light sensor, you could use code like this: SensorList<AmbientLightSensor> sensors = SensorManager.GetSensorsByTypeId<AmbientLightSensor>(); foreach (AmbientLightSensor sensor in sensors) { ... } Here, the GetSensorsByTypeId method of the SensorManager class accepts a generic type specification, which allows you to have a list of correctly typed sensor objects to work with. There is also a non-generic version of this method available. To read the current value from a sensor object, you can use the following code: sensor.UpdateData(); MessageBox.Show("The sensor \"" + sensor.FriendlyName + "\" reports the luminosity " + "value to be " + sensor. CurrentLuminousIntensity.Intensity + " lux."); The light level reported by the virtual light sensor can be controlled through the VirtualLightSensor.exe application (Figure 4). If you change the setting to a certain lux value, the value reported by the above code will change. The actual numeric value is reported by the CurrentLuminousIntensity.Intensity property. Figure 4. The virtual light sensor control application The code shown above is good for reading the metered value in a one-off fashion. If you instead prefer to be notified whenever the value changes, you can write an event handler for the sensor object's DataReportChanged event. You could also check the value of the State property to determine if a value can be read. Location programming with .NET 4.0 If you are already using Visual Studio 2010 and .NET 4.0, you can test your skills with the new System.Device.Location namespace. Using this namespace requires you to have a compatible device capable of calculating its location. Most often, this would be a GPS device with a USB or Bluetooth connection, but it could also be a mobile device able to detect its location using cell tower triangulation, for instance. The next section assumes that you have a compatible location device in place. To begin writing code, with Visual Studio 2010, start a new project, and make sure you select .NET 4.0 as your target framework version (Figure 5). Figure 5. To take best advantage of Windows 7, you need to use .NET 4.0. In Visual Studio's Solution Explorer, add a reference to System.Device.dll, and add the appropriate using statement to your code file: using System.Device.Location; Now you are ready to start using the classes inside the new namespace. A class named GeoCoordinateWatcher can be considered as a starting point for developers. With this class, you can initiate a location process, and in return get an object of type GeoCoordinate. This object is able to return the location as a conventional latitude and longitude pair. When using these watcher and coordinate classes, there are two particular details that you need to be aware of. First, there might be multiple location-sensing devices (providers) connected. The GeoCoordinateWatcher class will automatically select the most appropriate location provider based on the required accuracy (which can be set when creating an instance of the watcher), the last time a particular provider could detect its location, and so on. For instance, when moving indoors, a GPS device might no longer be the most accurate provider for location. Secondly, finding the current location using the device might take a relatively long time, multiple seconds perhaps, or even more if the device has just been powered on. Because of this, the GeoCoordinateWatcher class is usually operated in an asynchronous manner, as not to block the user interface thread of the application. To achieve asynchronous operation, you can call the Start method of the GeoCoordinateWatcher class to initiate location data acquisition, and then write an event handler for the PositionChanged event. This way, the watcher class will automatically call the event handler once location data becomes available. The synchronous way of getting the current location can be achieved by calling the TryStart method. This method takes a timeout value as a parameter that indicates how long the method will wait for location data to become available. Here is how you might use the location based classes to determine the current latitude and longitude asynchronously: private void button1_Click( object sender, EventArgs e) { GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(); watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs< GeoCoordinate>>(GeoPositionChanged); watcher.Start(); } private void GeoPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { MessageBox.Show("The current location is: " + e.Position.Location.Latitude + "/" + e.Position.Location.Longitude + "."); } In this code snippet, the determined location is read in the PositionChanged event handler named GeoPositionChanged. The passed event arguments (parameter e) are of type GeoPositionChangedEventArgs<GEOCOORDINATE>, which is a generic type declaration. In this case, the GeoCoordinate class is the type of the Position.Location property. The GeoCoordinate class in turn has two properties of interest: Latitude and Longitude. In many cases, a latitude/longitude coordinate pair is enough to plot the current location on a map. However, SLP also supports conversion of these coordinates into a so-called civic address, which is a traditional street, city and country type of address. Not all devices or services are able to do such conversions, but if such a service is available, then you can use the CivicAddressResolver class to convert a GeoCoordinate to a civic address. At this point, you are aware of how you can use the basic classes in the new System.Device.Location namespace to find the user's current location if suitable devices (providers) are present. However, before concluding, there's one security related detail you need to be aware of. Location based information is considered sensitive in Windows 7, and thus the user must give his or her consent that the location can be determined. This is done with a permission dialog box, in a similar fashion to the User Account Control (UAC) prompt, though not as intrusively as the UAC prompt. Once the user gives permission to find the location, the GeoCoordinateWatcher class can operate normally. Otherwise, location data will not be available, just as if there were no location providers connected. Conclusion The new Sensor and Location Platform, part of Windows 7, is a nice new addition to the operating system. In the future, especially location will be a major player in successful applications, and thus it is imperative to have an easily programmable interface for location-sensing devices. This way, the developer doesn't need to learn the specific APIs to access each different device; as such details are enclosed in the user-mode drivers. The Sensor and Location Platform differentiates devices into two broad classes: those that can sense the physical environment (such as temperature, light level or orientation), and those that can sense location. For sensors, the platform provides a generic API that can be used to query the properties of each device. For location-sensing devices, the platform provides an API through which the latitude and longitude coordinates can be retrieved, and optionally, a civic address (street, city, state, etc.). In the future, more and more devices will start to include drivers that are compatible with the Sensor and Location Platform. Once this happens, applications that need to sense the environment will be much easier to write. Resources Visual Studio 2010 RC download page Windows API Code Pack download for Visual Studio 2008 and 2010 MSDN documentation for the System.Device.Location namespace Freescale Semiconductor Flexis JM Badge Board There are no comments yet. Be the first to comment!
http://www.codeguru.com/csharp/.net/article.php/c16973/Using-the-Windows-7-Sensor-and-Location-Platform-from-C.htm
CC-MAIN-2017-13
refinedweb
2,561
54.02
Question:- Tom was standing outside a cow barn. A group of men was appointed to take care of the cattle. All Tom could see was’ heads and ‘n’ feet. Write a program to display the number of cows and the number of men found. Input consists of the heads as the first input and feet as the second input. If sum of number of cows and number of men is not equal to heads, then display “Invalid Input”. Sample Input 1 3 10 Sample Output 1 Number of Cows: 2 Number of Men: 1 Sample Input 2 10 44 Sample Output 2 Invalid Input Code:- import java.util.*; public class Main{ public static void main (String[] args) { Scanner sc = new Scanner(System.in); int hd = sc.nextInt(); int lg = sc.nextInt(); int cow=hd, men=0; if(lg>(hd*4)) { System.out.println("Invalid Input"); } else if(lg==(hd*4)){ System.out.println("Number of Cows: "+hd); System.out.println("Number of Men: 0"); } else{ while(cow>0) { if(lg<cow*4){ cow--; lg-=2; men++; } else if(lg==cow*4){ break; } } System.out.println("Number of Cows: "+cow); System.out.println("Number of Men: "+men); } } }
https://quizforexam.com/java-count-at-the-cow-barn/
CC-MAIN-2021-21
refinedweb
196
69.89
Now, guzz 1.3.0 joined the Spring Declaration Transaction. You can write programs running on MANY databases and maintain the distributed transaction with Springframwork, just like writing a Hibernate program. <!--?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /--> Guzz is a java object-relational mapping framework that will let you use many databases in one system. It provides a full stack data-layer solution for large systems. guzz’s database layer features: 1. You have too many tables in a database, or they took too much resource for one database. Distribute them in different database machines with dbgroup in chapeter 3: 2. Some table is too big. Spit them into small ones with ShadowTable in chapter 15: 3. Your business is special, for example a shopping site; each table may/should own its special columns. Ok, split them with CustomTable in chapter 16: 4. Big tables are split, but the split small tables are too many or too big in total to store together. Distribute the small tables in different database machines with VirtualDB in chapter 17: 5. Some column is too big to store in the database, or should be treated very special. Store it in File System, in memcached, or in anything you like with CustomColumnLoader in chapter 11: 6. The system is really very very busy, a single database is absolutely impossible to achieve your mission. Ok, deploy more READ machines with the native read-write separation support in guzz. Guzz can work with hibernate and ibatis, and can also work alone. If a system meets something of lacking database-scale ability, deploy more database machines and introduce guzz to upgrade database-scale related modules. It’s simple to write, easy to understand, and future-oriented. Read more about us:
http://www.theserverside.com/discussions/thread.tss?thread_id=63291
CC-MAIN-2014-15
refinedweb
297
67.04
I was asked "This program asks for a series of five test scores and calculates the average score in a function. The function should receive the total of the five scores as an argument and return the average of the five scores. The program should not accept scores less than zero or greater than one hundred. The output should look like the example below." Here's my code. It works, but I think I could do WAY better. Could anobody nudge me in the right direction? I really need to check each input as is comes in, but can't figure out a way to do that. BTW I'm really green with C++ so be gentle. ;) #include<iostream> #include<string> using namespace std; int average(int a, int b, int c, int d, int e); // prototype average int main() { // declare variables int testscore = 0; int iaverage = 0; int f = 0; int g = 0; int h = 0; int i = 0; int j = 0; // get input cout << "Please enter 5 test scores "; cin >> f >> g >> h >> i >> j; if(f <= 0 || f > 100) { cout << "Please enter a value between 0 - 100"; cout << endl; } else { iaverage = average(f, g, h, i, j); testscore = (f+g+h+i+j); cout << "Total of all scores: " << testscore << endl; cout << "Average score: " << iaverage << endl; }//end if-else return 0; }//end main int average(int a, int b, int c, int d, int e) { int daverage; daverage = (a+b+c+d+e) / 5; return daverage; } //end average
https://www.daniweb.com/programming/software-development/threads/233477/noob-inputing-5-grades-and-averaging-them
CC-MAIN-2017-26
refinedweb
250
73.31
ivprasad (46) Anand Narayanaswamy(7) Mahesh Chand(2) Kamran (2) Sibeesh Venu(1) Hussain Khawaja(1) Sachin Kalia(1) Shivprasad Koir Koirala(1) Resources No resource found C# FAQ 7: What Are Data Types, Variables And Operators Apr 25, 2016. In this article, you will learn the concepts related to data types, variables and operators. C# FAQ 6 - How Do I Display Numbers In Different Formats Jan 01, 2016. This article examines the various ways by which you can display numbers in C#. C# FAQ 5 - How Do I Write My First C# Program Nov 30, 2015. In this FAQ, we will examine the steps required to develop a simple C# console based program. C# Faq 4 - How Do I Configure C# Compiler Nov 29, 2015. This article helps you to learn the initial steps required to compile a C# program from DOS command prompt. C# FAQ 3 - Getting Started With C# Oct 19, 2015. This article examines the basics concepts associated with C# programming such as CLR, Class libraries and namespaces. C# FAQ 2 - About .NET Framework And Visual Studio Oct 09, 2015. This FAQ examines the concepts associated with .NET Framework, CLR, Visual Studio, Visual Studio Community and Visual Studio Online. C# FAQ 1 - What Is Object Oriented Programming? Oct 03, 2015. In this article you will learn about Object Oriented Programming with C#. C# Corner FAQ Integration in Web Application Using IntroJS Nov 12, 2014. In this article you will learn how to use IntroJS in a web application.. 12 Important FAQ on VSTS Testing Dec 06, 2009. This article has 12 important FAQ which covers unit testing, automated testing, data driven test, LOAD / performance test, code coverage, database testing and ordered testing... WCF FAQ Part 3 - 10 Security Related FAQ Jun 23, 2009.. Project Management Schedule Management FAQ series Apr 13, 2009. In this article we will run through a quick FAQ for schedule management of software projects. Crystal and Reporting Services FAQ - Part 2 Apr 03, 2009. This article is the continuation of Crystal and Reporting Services FAQ - Part 1. This FAQ will give you a quick start for two giant reports on Crystal and Reporting Services.. SharePoint Quick Start FAQ - Part 4 Feb 07, 2009. This is my fourth series of SharePoint Quick Start FAQ. In this series the theme is WebPart , WebPart and WebPart J. So let’s enjoy the WebPart bonanza. Ajax Quick Start FAQ Feb 04, 2009. This FAQ is like a starter kit. It will help you understand the main aspects of Ajax in a rapid fashion.... Architecture FAQ for Localization and Globalization: Part II Feb 03, 2009. This article is Part 2 of "Localization and Globalization" in this we will go through a series of FAQ which will give you a quick start on making application multi-language based. Architecture FAQ for Localization and Globalization: Part I Feb 02, 2009. In this article we will go through a series of FAQ which will give you a quick start on making application multi-language based. Microsoft Azure FAQs Nov 23, 2015. This article addresses some basic FAQs regarding azure platform, subscription and services. Execution Order of Filters in MVC 4 With Practices: Important FAQ Jun 13, 2014. This article describes the execution order of filters in MVC with practices.. JQuery FAQ Feb 24, 2010. Here are some frequently asked questions about JQuery. .NET 4.0 FAQ: Part I - The DLR Oct 13, 2009. In this section we will look in to new features provided by .NET 4.0 framework. We have a glance on some important features, DLR, subsystems of DLR, dynamic object and expand objects.. Azure FAQ: Part I Aug 03, 2009.. SilverLight FAQ's - Part 3 Jun 25, 2009. This article discusses 12 FAQ’s which revolve around bindings, layouts, consuming WCF services and how to connect to database through SilverLight. Project Management Costing - FAQ's May 19, 2009. This is a short and sweet FAQ which iterates through the most common metrics which will help you judge your project health.. Windows Communication Foundation FAQ: Part II Apr 16, 2009. In this article, we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.. SQL Server - FAQ's Feb 16, 2009. In this article we will go through the most basic and frequently asked interview questions on SQL Server. Service Oriented Architecture (SOA) - FAQ's Feb 14, 2009. In this article we will discuss abour Service Oriented Architecture (SOA) which is must and essential for every architect... ASP.NET FAQ's: Part I Jan 27, 2009. In this article, we will touch base on one of important concepts in ASP.Net. Caching FAQ's: Part I Jan 22, 2009. In this section we will touch base on one of important concepts in .NET Caching.. I Jan 13, 2009. Below is quick start FAQ for people who are new to share point. We will warm up some theory in the first two articles and then do some practical on the same lines. Windows Workflow Foundation(WWF) - FAQ Jan 05, 2009. In this FAQ we will quickly run through and get a feel of how WWF (Windows Workflow Foundation) will help you in making custom work flows in your project. Windows Communication Foundation(WCF) FAQ: Part I Jan 02, 2009. WCF is a part of .NET 3.0.“. WCF is a unification technology, which unites the following technologies like NET remoting, MSMQ, Web services, COM+. (WPF) Windows Presentation Foundation - FAQ Jan 02, 2009. In this section we will make a quick walkthrough of WPF which will help you understand WPF instantly. Database and SQL Server FAQ: Part I Dec 31, 2007. This article is a primer on databases and Sql Server. Similar to a FAQ, it is written with questions that could potentially be asked in a job interview. HoloLens Frequently Asked Questions Apr 02, 2016. Here is a list of Microsoft HoloLens frequently asked questions and their answers. Find an Operating System version Nov 09, 2012. This tutorial gives description about OS Version using Env classes. SharePoint workflow basics Apr 08, 2009. In this article we will understand the basics of sharepoint workflow , the life cycle of sharepoint work flow and finally we implement a simple work flow using the three-state work flow which is available in share point.. Agile Development: Part II Jan 09, 2009. This article is a quick FAQ of Agile. By reading this you will understand fundamentals of Agile and different ways of implementing Agile. Agile Development: Part I Jan 07, 2009. This article is a quick FAQ of Agile. By reading this you will understand fundamentals of Agile and different ways of implementing Agile. C# and .NET Jan 07, 2002. It is sometimes important to know the details of what the compiler does. You may want to know whether constants are evaluated at compile time, or whether constant strings are folded at compile time. About FA.
http://www.c-sharpcorner.com/tags/FAQ
CC-MAIN-2016-50
refinedweb
1,168
67.15
Losing your Loops Fast Numerical Computing with NumPy 436 3 21982 You can do this with numpy built-ins using broadcasting. Broadcasting allows you to add together two arrays of different shapes without making excessive copies or looping excessively. We can solve your problem by creating two vectors representing the row and column sums respectively, and 'multiplying' them together, which will broadcast them into a correctly sized and shaped array. The best introduction to this topic I know of is the talk Losing Your Loops: Fast Numerical Computation with Numpy by Jake Vanderplass. It contains visual examples that I find essential for wrapping your head around broadcasting. Here's a simple example: IN import numpy as np a = np.arange(3) b = np.reshape(np.arange(3), [3, 1]) print('a = ', a) print('b = ') print(b) print('a+b = ') print(a+b) OUT: a = [0 1 2] b = [[0] [1] [2]] a+b = [[0 1 2] [1 2 3] [2 3 4]] We can solve your problem by creating two vectors representing the row and column sums respectively 'multiplying' them together, broadcasting them into a correctly sized and shaped array. import numpy as np def gen_expected(array: np.ndarray): col_sums = (np.sum(array, axis=0)) row_sums = np.sum(array, axis=1) np.reshape(row_sums, [len(row_sums), 1]) return (col_sums * row_sums) / np.sum(array) # NOTE: this result might be transposed! Check it yourself! I have some data that I want to "one-hot encode" and it is represented as a 1-dimensional vector of positions. Is there any function in NumPy that can expand my x into my x_ohe? I'm trying to avoid using for-loops in Python at all costs for operations like this after watching Jake Vanderplas's talk x = np.asarray([0,0,1,0,2]) x_ohe = np.zeros((len(x), 3), dtype=int) for i, pos in enumerate(x): x_ohe[i,pos] = 1 x_ohe # array([[1, 0, 0], # [1, 0, 0], # [0, 1, 0], # [1, 0, 0], # [0, 0, 1]]) I already did! Its more of an abstract question really, I saw this vid and it blew my mind. I was just trying to apply it to my work. No worries tough, I will have a look at the pivot table post you linked to. Thanks for your help. Popular Videos 128 Submit Your Video By anonymous 2017-09-20 Instead of substituting your for-loops with lambdas, try substituting them with ufuncs. Losing Your Loops: Fast Numerical Computation with Numpy is an excellent talk by Jake Vanderplass on the subject. Using universal functions and broadcasting instead of for-loops can dramatically improve the speed of your code. Here is a basic example: INPUT: OUTPUT: Note by eliminating our loops we have a 60x speedup! Original Thread
https://dev-videos.com/videos/EEUXKG97YRw/Losing-your-Loops-Fast-Numerical-Computing-with-NumPy
CC-MAIN-2018-26
refinedweb
461
65.12
This page aims to give a general introduction to the GPIO header on the Raspberry Pi. The GPIO pins allow you to interface the Pi to the real world. I was mainly interested in the standard GPIO pins for reading switches and controlling LEDs and Motors. I found a great deal of confusion surrounding the numbering and naming of these pins so decided to create my own diagram. The idea was to create a page that I could print out and stick in my box of wires and cables. Reading information from a webpage is useful but when you are up to your neck in soldering irons, wires and tools it is sometimes easier to have a piece of paper to hand. The other advantage is that you can scribble notes on it. Pi 3 Model B+, Pi 3 Model A+ and Pi 3 Model B The Pi 3 has the same layout at the : - Pi Zero & Pi Zero W - Pi 2 Model B - Pi Model B+ - Pi Model A+ Pi 2 Model B The Pi 2 has the same layout at the : - Pi Zero & Pi Zero W - Pi 3 - Pi Model B+ - Pi Model A+ Pi 1 Model B+ The pin-out of the header on the Model B+ is described in more detail on my Model B+ GPIO page. The Model B+ has the same layout at the : - Pi Zero & Pi Zero W - Pi 3 - Pi 2 - Pi Model A+ Pi 1 Model A+ The Model A+ has the same layout at the : - Pi Zero & Pi Zero W - Pi 3 - Pi 2 - Pi Model B+ Pi 1 Model B (Revision 1.0) This is where it all began. The original 26-pin GPIO header : It consists of two rows of thirteen pins. Pin 1 is clearly marked on the board as “P1”. It is vital you are looking at the header the correct way round. Locate “P1” and compare the header to the diagram below : Pi 1 Model A/B (Revision 2.0) To find out what board revisions you have take a look at my Guide to finding out your PCB revision number. The white pins were previously “DNC” (Do Not Connect) as they were reserved for future use. It has now been confirmed their function will not be changed so the diagrams above show their permanent assignment. The Pin marked “P1” is Pin 1 and provides 3.3V (50mA max). You can work out all the other pins from there. Note how the numbering works. Even numbers on the top row and odd numbers on the bottom row. Labels – Clear as Mud The labels above are the names of the pins on the Broadcom system chip to which the pin is physically connected. Much of the confusion around the GPIO is due to these labels, their relationship to the Broadcom labels and how they are referred to in your programs. To confuse things even more the GPIO pins are sometimes renamed with another set of numbers. In order to avoid damaging your Pi you need to be sure what pins you are connecting to other hardware and that your program is referring to the correct pins. GPIO Header Power Pins The header provides 5V on Pin 2 and 3.3V on Pin 1. The 3.3V supply is limited to 50mA. The 5V supply draws current directly from your microUSB supply so can use whatever is left over after the board has taken its share. A 1A power supply could supply up to 300mA once the board has drawn 700mA. Basic GPIO The header provides 17 Pins that can be configured as inputs and outputs. By default they are all configured as inputs except GPIO 14 & 15. In order to use these pins you must tell the system whether they are inputs or outputs. This can be achieved a number of ways and it depends on how you intend to control them. GPIO in Python The easiest way to control the GPIO pins is using the RPi.GPIO Python library. Installing the library is easy if you follow my RPi.GPIO Installation Guide. Once installed using the pins is as easy as : import RPi.GPIO as GPIO # Use GPIO numbers not pin numbers GPIO.setmode(GPIO.BCM) # set up the GPIO channels - one input and one output GPIO.setup(7, GPIO.IN) GPIO.setup(8, GPIO.OUT) # input from GPIO7 input_value = GPIO.input(7) # output to GPIO8 GPIO.output(8, True) In this example we use GPIO7 (pin 26) and GPIO8 (pin 24). Python scripts that use the GPIO library must be run using sudo. i.e. sudo python yourscript.py Pin Protection Most of the pins in the header go directly to the Broadcom chip. It is important to carefully design the components you attach to them as there is a risk you will permanently damage your Pi. Short circuits and wiring mistakes could also ruin your day so double check everything. A multimeter is probably going to help a lot here as you can double check wiring before you connect to the Pi. Circuits Luckily there are some basic circuits that you can use to protect the pins and the cost of implementing them is minimal. Here are some links to circuits I have built : Controlling an LED using a GPIO pin I will post links to other circuits as I test them. Alternative GPIO Header Diagram Here is an alternative header diagram for the Revision 1.0 board created by scottchiefbaker on the Raspberry Pi Forums : This is not true:- However only 8 of these are considered GPIO pins out of the box. The other 9 can perform more complex roles but I’m only interested in the basics. All the pins except GPIO 14 & 15 come up initialised as inputs. If you want to use them as inputs there is nothing further you have to do to them. GPIO 14 & 15 come up initialised as serial data lines TX & RX so you can connect a serial terminal to allow you to log on. Ah thanks for the clarification. It all seems much clearer now. I’ve made some improvements to my diagram so it should be easier to follow now! Out of all the info on the net – I found yours was the closest that I found I needed to getting this working. If you try this on the current default RaspberryPi Debian download then the code doesn’t work as there is a permission restriction that prevents the standard user from using GPIO (It works up to the point when you issue GPIO.setup(11, GPIO.IN) and then bombs 🙁 ) I don’t know if this is just peculiar to that distro but since its likely to be the first one that people use it would be great if you could add that in order to use the code that sometimes you have to run Python using sudo python first. I think your article would be nigh on perfect then 🙂 As you’ve noticed Python scripts that use the GPIO library need to be run as sudo. I’ve updated the article to mention it. Nice diagrams. I started from the docs of RPi.GPIO library but those where abit sparse about how to map these numbers to the actual board pins. I also have a book ‘Raspberry Pi Projects for the Evil Genius’ which has some diagrams and tables. But yours are the best / clearest by far. Especially pins 3 and 5 which are different between revision 1 and 2. Those had me stumped before your diagrams made it clear to me why my program wasn’t driving those pins… the diagrams I had been looking at are for Rev 1 and my Pi is Rev 2. The ‘Evil Genius’ book completely missed pointing that out and only has Rev 1 diagrams. Thanks for sharing your diagrams with us 🙂 Pingback: Raspberry PI with Erlang | Matthew (Phil)yaw Slight error/inconsistency in your diagrams above: For Rev 1.0, GPIO1 ought to be labelled as I2C0_SCL For Rev 2.0, GPIO2 ought to be labelled I2C1_SDA and GPIO3 ought to be labelled as I2C1_SCL Thanks for noticing. They were a bit messy. I’ve made them all consistent but gone for a slightly different label to align them slightly more with the style used on the B+ schematics. …nearly there! You’ve now got both GPIO2 and GPIO3 labelled as SDA1 I2C 😉 Arrrggghhh. I’m sure that changed behind my back! Thanks for the feedback. Should be correct now. Is there a difference between the black and white grounds or the red and white 5 volt rails? No. The white pins were originally specified as “do not connect” but the Pi Foundation later stated they weren’t going to change so their use became fixed. Hello, Great article and diagrams. I am looking to set the TX GPIO14 as a regular GPIO input pin. For some background, I am using the Wolfson audio card which takes up most of the gpio pins. It has a header that passes the serial pins (GPIO14&15). The only other device I have to connect to the Pi is an Adafruit Ultimate GPS. I do not need to talk to the GPS so I only need the Rx (GPIO15) on the Pi. I do, however need to hook up a PPS timing input signal from the GPS.. My question is, do you see a problem with my approach here and can I just follow your example Python script to reconfigure the pin? Thanks for your help and your time Adam All the GPIO pins can be configured as inputs or outputs so you should be fine. Thanks Matt, I went ahead with this plan and it is working fine! Adam Pingback: What is the difference between BOARD and BCM for GPIO pin numbering? | DL-UAT Hi! I was wondering if anyone else is having an issue getting their GPIOs to communicate? I wrote a small snippet of code, really simple that controls the GPIO on and off. I have been simply using a multimeter to measure the change in voltage. This code normally works, but after I enabled and have been playing with my I2C and SPI pins (which all work excellently) I am no longer able to communicate with the GPIO. I even tried re-blacklisting I2C and SPI to see if that could help fix the problem, but to no avail. It really depends on what code you are using and what library you are using to access the GPIO pins. It’s probably best to post on the Official Raspberry Pi Forums as it will easier to work through the options. this tutorial is simple amazing!!! this saved my day 🙂 “P1” does not mean Pin 1 — its the connector designation: as you can see connectors “P2” and “P3” also exist on the board. Pin 1 is indicated by a squared pad (instead of a circle) or a white button-like marking, sometimes a white dot (as on S5). You are right but on the original Pi the P1 label was next to Pin 1 so was a good way to explain to people which end to look at. It isn’t the case on the newer models so I will revise the text at some point.
https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins
CC-MAIN-2019-09
refinedweb
1,894
71.04
User talk:Gubby From Uncyclopedia, the content-free encyclopedia edit Welcome! Hello, Gubby,:33, 2 July 2006 (UTC) edit HowTo:Maintain a vanity site on Wikipedia I nominated your article from the front page. It's getting strong support, as it should. Great work!--Procopius 12:30, 7 August 2006 (UTC) - Seconded. A great article well 'researched'. Bravo! -- Hindleyite | PL | GUN | WOTM | Image Review - Use it | Converse 16:31, 7 August 2006 (UTC) - Thanks guys! :) Gubby 16:36, 7 August 2006 (UTC) - Don't believe them.....they are after your gusset. Run, run as fast as you) - Damn, he's onto us. Everyone scatter. -- Imrealized ...hmm? 16:59, 7 August 2006 (UTC) About the article you seem to have "vandalized" on Wikipedia, I must ask... was that a real article, or did you just make one that looked real with your name in it? Wehpudicabok 00:48, 15 August 2006 (UTC) - Hm? You mean,.. did I really make those articles on wikipedia, only to have them deleted instantly? Yes. (I'm not sure I get your question. If this didn't do the job, try rephrasing it).--Gubby 01:19, 15 August 2006 (UTC) - I mean, was there an article called "Sister ___" before you came along, or did you make all of that page up? Wehpudicabok 02:23, 15 August 2006 (UTC) - You haven't been reading my article properly! I hope you're not in school anymore because the Awesomeness teacher would surely mark you WAY low for that. I took a random article from wikipedia and replaced every instance of the subject's name with mine (with the help of the Find&Replace tool in notepad--Gubby 02:27, 15 August 2006 (UTC)), then pasted it in "Gubby". - Okay, I finally found it. I kept trying to find the original article that you had vandalized, but couldn't. That's why I tried asking you, because it wouldn't come up in searches, even if I left out the word "Gubby." I had to go to through the category "Former students of St Anne's College, Oxford" before I did, but I finally found that the article was in fact on Sister Wendy Beckett. - What a waste of time that was. Oh well. Wehpudicabok 00:56, 21 August 2006 (UTC) Is this undelete request on Meta-Wiki about your vanity page attempt? It seems someone was fooled into thinking that it was legitimate... Pentium5dot1 05:19, 9 September 2006 (UTC) edit Fisher Price Just nominated it separately on the VFH page. Go Vote! --:47, 12 August 2006 (UTC) edit Arguement edit VFH-HowTo:Maintain a vanity site on Wikipedia What is this "admin XD", and why am I it? Modusoperandi 15:14, 15 August 2006 (UTC) - XD is an emoticon.--Gubby 15:16, 15 August 2006 (UTC) - Didn't they fight the Autobots? I'm pretty sure I had the one that turned from a robot into a "winky" face. Modusoperandi 15:32, 15 August 2006 (UTC) edit Why Did You Remove My Gibson Quote From Snakes on a Plane?!?! Why???? --TaintedCell 01:32, 22 August 2006 (UTC) - Uh... can't remember. It probably sucked. But maybe I just didn't get it. You can put it back if you like. :P--Gubby 10:48, 22 August 2006 (UTC) edit DeviantART Hi! as the seemingly Main watcher and "person who has generally given up on things" of the DevArt article, I wanted to thank you for helping to make the article actually almost worth reading, and comment that you're more than welcome to continue working on and loving the little adopted retard tyke. --epynephrin 02:57, 21 September:01, 23 September 2006 (UTC) edit HMS Potatore I'd heard of it, but only read it when Shandon dragged me along on our mad adventure. Our version is better, as it's shorter (we cover the whole plot in one paragraph) and the cast breaks out into song less often. Having read it, do you feel more cultured, at least?--Sir Modusoperandi Boinc! 22:56, 24 September 2006 (UTC) edit Link at the bottom Should we change the pseudo-external link at the bottom of your user page to something obviously invalid like ? (It confused me the first time around... Don't worry, that was a long time ago. I'm not that much of a n00b now.) Pentium5dot1 02:06, 11 November 2006 (UTC) You could I suppose, if you think it'll confuse more n00bs... my own reaction would be to leave well alone. Whatever really. --Gubby 13:54, 11 November 2006 (UTC) - It's not to confuse more n00bs; it's to stop them from being confused. Since my logic has been pwned, however, I think I'll leave it alone. Pentium5dot1 20:20, 11 November 2006 (UTC) edit Hello Might I suggest that, rather than just blanking other people's contributions, you add your quote on 'homosexuality'? You're much less likely to get banned - which wouldn't be good, because your contribution on My Chemical Romance was funny. RabbiTechno 19:12, 6 April 2007 (UTC) - Also, vandalising other people's userpages is a seriously bad idea. RabbiTechno 19:21, 6 April 2007 (UTC) - Gubby, my bad. Got vandalised by an IP...sorry, wasn't you. Ignore that last bit. RabbiTechno 19:25, 6 April 2007 (UTC) edit David DeAngelo's Newsletter Hi. I'm not entirely sure if you were sarcastic or not when you said you liked the article, but either way, it's clear you are not indifferent to it. Which is good. I recently nominated the page for feature status (after receiving some positive feedback), but it's entry is pretty much stagnating. I would appreciate you voting either way. --Medvedev (scream) 21:06, 7 April 2007 (UTC) edit HowTo:Maintain a vanity site on Uncyclopedia Please take a look and make any changes you think of....--Dantoller 17:50, 2 May 2007 (UTC) edit RE: blah Because a current article exists for Bureaucracy, your version would be a rewrite. Good luck by the way. --Hotadmin4u69 [TALK] 15:44, 25 June 2007 (UTC) edit Picture Who's that in the picture you used to replace Angelina Jolie's pic? Say what? Be more specific here.----Gubby 14:35, 3 July 2007 (UTC) ----sign please I think it says "Andrea Puccini" or Paccini or something written there on the photo. But I don't know really, I was just looking for someone hot to put up. Why did I call it Angelina Jolie? Wierd. --Gubby 08:40, 4 July 2007 (UTC) Andrea Puccini is a photographer. And on there you said you got it off Wikipedia... Oh well, it'd remain a mystery then. 74.97.32.140 21:17, 7 July 2007 (UTC) Alright, after some internet sleuthing: That model is Daniella Sarahyba Fernandes - I knew she looked familiar because she was on SI a couple of times. 74.97.32.140 21:41, 7 July 2007 (UTC) --Gubby 07:36, 1 August 2007 (UTC) edit Hate repetition articles? Than could you do me a favor and vote delete on Uncyclopedia:Votes for deletion#The word parakeet written exactly two hundred and forty-two HowTo:Maintain a vanity site on Wikipedia I fucking lol'd at step 4, I love that idea. You're hilarious. Mightywayne 15:55, 2 September 2007 (UTC) edit Oops! My bad on the infiniblock. I forgot you were the guy who wrote the vanity on Wikipedia stuff. I've severed my itchy trigger finger. Accept it as a token of apology. PS: As per rewriting Cake. Make it in your namespace first, submit to pee review, then we cna replace the article wholesale.-- 21:11, 23 September 2007 (UTC) ...Okay. *catches breath* --Gubby 21:14, 23 September 2007 (UTC) edit Maddox The point of the Maddox article is to parody Maddox's style of writing. Now what you have wrote here, I don't know, I personally have never seen him write anything like this. If you could point out a part of one of his articles that looks like this, then yes it should be kept, otherwise, I don't think it really fits. Hmmm, interesting are the artices of his style you have pointed out. When I had envisioned a parody of Maddox's writing, I had imagined along the lines of this article: I guess we can do a combination of both styles for the Maddox article.--Little Jimmy 03:14, 1 December 2007 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:Gubby
CC-MAIN-2014-42
refinedweb
1,424
73.58
New in Symfony 2.2: Security Utilities Contributed by Fabien Potencier in #4763. As of Symfony 2.2, we have refactored some security utilities so that you can use them in your own code. These utilities are available in the Symfony\Component\Security\Core\Util namespace. Generating a secure Random Number¶ If you need to generate a secure random number, you'd better rely on a strong implementation. Symfony provides one: The nextBytes() methods returns a random string composed of the number of characters passed as an argument ( 10 in the above example). Comparing Strings¶ Timing attacks are not that well-known, but still, Symfony has protection for them. In Symfony 2.0 and 2.1, this protection was applied to password comparisons done in the Security bundle, but as of Symfony 2.2, it is also available to the developer: Want to learn more? Have a look at the dedicated documentation. To ensure that comments stay relevant, they are closed for old posts. Clément Guillemain said on Dec 19, 2012 at 23:25 #1
http://symfony.com/blog/new-in-symfony-2-2-security-utilities?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+symfony%2Fblog+%28Symfony+Blog%29
CC-MAIN-2017-47
refinedweb
175
60.41
So i am not getting the formula for the last one I'm not sure why it is not coming out. And also for the Fahrenheit my value keeps equaling to 0 I am not sure why. Code: //study iomanip to depth for this project //to define a constant use #define PI 3.14159 #include "stdafx.h" #include <iostream> #include <iomanip> #define PI 3.14159 #define g 9.81 using namespace std; int main() { double Volume,SurfaceArea,Circumference,Area,Sum, SideA; double Length,Width,Height,SlantHeight,Radius,Value; int F,K,C; // temperatures double Number, a, l; double P,V,R,T SideA = 15; // This is the base of the triangle Height = 3; Area = 1 * SideA * Height / 2; cout << "\n\t\tThe area of this beautiful triangle = " << Area; //Volume of Sphere Radius = 6; Height = 3; Volume = 4/3 * PI * Radius * Radius; cout << "\n\t\t The volume of this cone = " << Volume; //The Sum Number = 4; a = 1; l = 7; Sum = Number/2 * (a+l); cout<<"\n\n\n The Sum of this sum = " << Sum; // I don't know Radius = 3; SlantHeight = 4; Area = PI * Radius * SlantHeight * 1/2; cout<<"\n\n\n The Area of this = " << Area; //Celcius C = 100; cout << "\n\t\tThe value of 5 / 9 * (F - 32) = " << 5/9* (F - 32) << " Farenheit"; //Farenheit F = 150; cout <<"\n\t\tThe value of 9 / 5 * C + 32 = " << 9/5 * C + 32 <<" Celcius "; // Last Formula P = 3; V = 6; R = 2; T = 7; Number = P*V/T*R; cout<<"\n\n\t The value of P * V/ T* R = " << Value; cout << "\n\n\n"; return 0; }
https://cboard.cprogramming.com/cplusplus-programming/154197-formula-error-printable-thread.html
CC-MAIN-2017-30
refinedweb
266
56.83
Association List An association list or alist is a simple lookup table or map: a linked list containing a key value and some information associated with the key. (assoc 'two '((one 1) (two 2) (three 3))) -> (two 2) public static Cons assoc(Object key, Cons lst) { if ( lst == null ) return null; else if ( key.equals(first((Cons) first(lst))) ) return ((Cons) first(lst)); else return assoc(key, rest(lst)); } (defun assoc (key lst) (if (null lst) nil (if (equal key (first (first lst))) (first lst) (assoc key (rest lst)) ) ) ) New items can be added to the association list using cons. Adv: Simple code. Table is easily expanded. Dis: O(n) lookup: Suitable only for small tables.
http://www.cs.utexas.edu/users/novak/cs31482.html
CC-MAIN-2015-35
refinedweb
116
61.87
You will learn You are now going to build a simple and quick SAP HANA XS application, if you already have experience doing this feel free to jump ahead as you feel fit. By Craig Cmehil Part 2 of 10, Setup and configure your initial SAP HANA XS application for use with your IoT Data You are now going to build a simple and quick SAP HANA XS application, if you already have experience doing this feel free to jump ahead as you feel fit. SAP HANA XS are extended services applications based on JavaScript, HTML and CSS, as you well as several built in features such as OData within the SAP HANA environment. Login to the server provided during this event or to your own SAP HANA server and go to the SAP HANA Web Based Development Workbench Your login is: user name CODEJAMMER and CodeJam2015 (or whichever username and password you have been given to login with) Once you have your editor loaded you will need to create a package name under the CODEJAMMER package with your name. This is done by right clicking on the CODEJAMMER package and choosing New > Package and then entering your name. If the CODEJAMMER package does not exist then simply create a new package under the root package which is simply the “Content” folder. Then under your new package you will want to create another new package called myiot. This will be the package that you place all of our XS code under for our application. Now you will need to right-click on your myiot package and choose Create Application. Accept the default values, and an empty application with the basic .xsapp and .xsaccess files you need will be created. Now that you have the basic application you will add in some data objects so you can store data from your devices. The first object you need will be a schema file. Select your myiot package, right-click and choose New > File. Use something simple like your name (in all caps) for the first part of the file name. In this example, JOHNDOE was used. Name the file: YOURNAME.hdbschema Be sure to use all capital letters for the schema filename Enter the following content into your .hdbschema file, replacing JOHNDOE with your name. Ensure you use all capital letters for the schema name schema_name="JOHNDOE"; The the next file you need to create is a table definition file. Right-click on your myiot package, select New > File and name the file mydata.hdbdd. This file will define the table and data types that you will use to store the data as well as access it later. Enter the following content in your mydata.hdbdd file, and replace instances of johndoe and JOHNDOE with the name you used. namespace CODEJAMMER.johndoe.myiot; @Schema: 'JOHNDOE' context mydata { type SDate : UTCTimestamp; type tt_error { HTTP_STATUS_CODE: Integer; ERROR_MESSAGE: String(100); DETAIL: String(200); }; type tt_details { ID: Integer; TIMESTAMP: SDate; TEMPERATURE: Decimal(9,5); HUMIDITY: Double; BRIGHTNESS: Double; }; @Catalog.tableType : #COLUMN Entity Data { key ID: Integer; TIMESTAMP: SDate; TEMPERATURE: Decimal(9,5); HUMIDITY: Double; BRIGHTNESS: Double; }; }; Once table definition file is saved it will activate and create your table. You will now need to create a stored procedure and an OData service file. The OData service file will allow you to access any data and set the connection to the stored procedure for enabling the insertion of new data into the table. To create a sequence (an incrementing number for the ID field in your table), right-click on your myiot package, select New > File and name the file johndoe_id_seq.hdbsequence. You will notice the use of the “name” in these examples it is “JOHNDOE” so be sure to make the appropriate changes. Enter the following content in your .hdbsequence file, and replace instances of johndoe and JOHNDOE with the name you used. schema="JOHNDOE"; start_with=100; minvalue=1; cycles=false; depends_on_table="CODEJAMMER.johndoe.myiot::mydata.Data"; Now that you have your table and incrementing ID field you need to create the stored procedure that will insert new data into the table. Follow the same procedure as above to add new file to your myiot package and name it: newdata.hdbprocedure Enter the following content in your .hdbprocedure file, and replace instances of johndoe and JOHNDOE with the name you used. PROCEDURE "JOHNDOE"."CODEJAMMER.johndoe.myiot::newdata" ( IN row JOHNDOE."CODEJAMMER.johndoe.myiot::mydata.tt_details", OUT error JOHNDOE."CODEJAMMER.johndoe.myiot::mydata.tt_error" ) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER DEFAULT SCHEMA JOHNDOE AS BEGIN /***************************** Write your procedure logic *****************************/ declare lv_temperature string; declare lv_humidity string; declare lv_bright string; select TEMPERATURE, HUMIDITY, BRIGHTNESS into lv_temperature, lv_humidity, lv_bright from :row; if :lv_temperature = ' ' then error = select 400 as http_status_code, 'invalid date' as error_message, 'Invalid response from sensor' as detail from dummy; else insert into "CODEJAMMER.johndoe.myiot::mydata.Data" values ("CODEJAMMER.johndoe.myiot::johndoe_id_seq".NEXTVAL, now(), CAST(lv_temperature AS decimal(9,5)), CAST(lv_humidity AS double), CAST(lv_bright AS double) ); end if; END; This code will use the “types” you defined in the table definition and then do an insert to the table with the “value” passed to it. In order to activate or utilize this new procedure you will need to create an OData service. To do so, create another new file in your myiot package called mydata.xsodata. Enter the following content in your .xsodata file, and make the appropriate name changes. This file will provide us the ability to read data but also insert data into our table. service namespace "CODEJAMMER.johndoe.myiot" { "JOHNDOE"."CODEJAMMER.johndoe.myiot::mydata.Data" as "HISTORY"; "JOHNDOE"."CODEJAMMER.johndoe.myiot::mydata.Data" as "DATA" create using "CODEJAMMER.johndoe.myiot::newdata"; } Your service enabled table is almost ready for use. You also need to give some authorizations and to do this you will create a “ROLE”. Right-click on your myiot package and select New > Role. Enter johndoe_myiot for the role name (modify the name accordingly) and click Create. Once created, click on Object Privileges, then the + sign. Enter your name (**JOHNDOE** used here) and a schema and sequence Object Type should appear in the Matching Items list. Select the schema item then click OK to add it to the role. Once the schema is added, select all the checkboxes under Privileges (on the right hand side). Click the + sign again, enter your name again, select the sequence item and click OK. Once added, mark the SELECT checkbox under Privileges. You will need to add your schema, table, sequence and procedure to this and then save. Now that you have a role defined you need to apply that role to your user. Be sure to SAVE the role before continuing! To apply the role to your user, click the small link icon in the editor and choose Security. When the page updates, unroll the Users hierarchy, and select CODEJAMMER (or which ever user you were given for this server). Click the + symbol under the Granted Roles tab and search for the role you created (e.g. johndoe). Select your role, click OK and Save.  Now it’s time to test… Updated 09/13/2017 Contributors Provide Feedback akula86 nancymic2 ccmehil < 5 Min.
https://www.sap.com/norway/developer/tutorials/iot-part2-hanaxs-setup.html
CC-MAIN-2017-47
refinedweb
1,198
54.73
17 August 2012 08:18 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The PVC facility will be shut for a week and will be operating at a reduced rate of 70-75% following the shutdown until the upstream VCM unit is restarted, the source said. FPC shut its 800,000 tonne/year VCM and 1.18m tonne/year ethylene dichloride (EDC) units in Mailiao on 16 August, the source added. The VCM and EDC units will be offline for a month and two weeks, respectively. FPC also shut its 1.33m dry metric tonne/year caustic soda unit at Mailiao for a planned two-week maintenance on 16 August, according to another company
http://www.icis.com/Articles/2012/08/17/9587852/taiwans-fpc-to-shut-mailiao-pvc-plant-on-27-august.html
CC-MAIN-2014-35
refinedweb
113
73.58
I work with large data structures which are kept in memory for speed, and over the years I have encountered out of memory exceptions numerous times, especially on 32bit systems. With 64bit OS rapidly becoming the standard we can now get a fast performing disk version of the structures using Memory Mapped Files for storage. Large structures would on 32bit be 800mb+ and on 64bit as much physical memory as you have available. When you move close to those boundaries .Net is bound to give you an out of memory exception which in most cases will break your application at unknown places. I have long thought about creating a disk based version of an array to store my data, but this would require a lot of caching logic to make it perform fast enough compared to physical memory. A couple of years ago I stumbled across Memory Mapped Files which has long existed in the operating systems and is typically used in Windows for the swap space. With even more data in my current project and running on a 64bit platform, the time seemed right to wrap this into a small library. Last time neccessary on 64bit systems. (If you want to use arrays which hold over 2gb of data on 32bit systems I recommend reverting to Steve's original version and set a view size of 200-500mb.). The project is made in Visual Studio 2008 compiled against .Net 3.5, but you should be able to take the files and create projects in VS2005 as well. It should mostly be .Net 2.0 compatible. If I get enough requests I'll create a VS2005 version. The class accepts only value types. The reason is that the data is stored as bytes and to keep track of the offset TValue needs to be serialized to a defined size. The initial signature of my class looked like this: public class GenericMemoryMappedArray<TValue> : IDisposable, IEnumerable<TValue> { } The problem I then encounted was that a user could create an array with whatever class which won't serialize to a defined size. To allow this you would need a key file to store all the offsets in the value files as well. That will be left for my next project implementing a memory mapped Dictionary. So I ended up with: public class GenericMemoryMappedArray<TValue> : IDisposable, IEnumerable<TValue> where TValue : struct { } which restricts the usage to structs and value types. IDisposable is implemented in order to free up the mmf and delete the file used, and also release the unsafe memory areas allocated for working buffers. The buffers will be the size of the TValue, and calculated in the constructor. The constructor takes the size of the array and where to store the mmf as parameters. /// <summary> /// Create a new memory mapped array on disk /// </summary> /// <param name="size">The length of the array to allocate</param> /// <param name="path">The directory where the memory mapped file is to be stored</param> public GenericMemoryMappedArray(long size, string path) { ... // Get the size of TValue _dataSize = Marshal.SizeOf(typeof(TValue)); // Allocate a global buffer for this instance _buffer = new byte[_dataSize]; // Allocate a global unmanaged buffer for this instance _memPtr = Marshal.AllocHGlobal(_dataSize); ... } The generic class has also implemented thread safety, so more than one thread can access the array at the same time. Since each thread has to set the position first, and then read or write, I keep a pool of all threads. .Net reuses internal threads so the pool will not grow very large. Even if it did, it's not a problem on 64bit due to the large address space available. A timer runs every hour to clean up unused threads. Here's an example of the Write method which gets the current thread id, then gets a view of the mmf for that thread, and finally writes the data to the mmf. public void Write(byte[] buffer) { int threadId = Thread.CurrentThread.ManagedThreadId; _lastUsedThread[threadId] = DateTime.UtcNow; Stream s = GetView(threadId); s.Write(buffer, 0, buffer.Length); } The class supports auto growing the array and has a property for this which default is true. Useful for being able to add more data as you go along. string path = AppDomain.CurrentDomain.BaseDirectory; var myList = new GenericMemoryMappedArray<int>(1024*1024, path); using (myList) // automatically dispose the mmf when done { myList.AutoGrow = false; try { myList[1024 * 1024] = 1; } catch (Exception e) { Console.WriteLine(e.Message); //will give exception } myList.AutoGrow = true; myList[0] = 1; myList[1024 * 1024] = 1; // will now increase the file } For my needs memory mapped files has proven to be a good trade off between speed and usage of physical memory. Of course physical memory is used for caching in the back end, but having the OS work it's magic is much better than getting out of memory exceptions from .Net. I've tried with both sequential and random reads/writes and it works pretty good imo. Be sure not to resize the array too often, as unmapping will flush the underlying pages. This will have an impact on performance if the structure is constantly used. The code can also be modified to keep the temp files it uses for permanent storage and not deleting them when the class is disposed. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/recipes/MemoryMappedGenericArray.aspx
crawl-002
refinedweb
887
62.58
Since commit 4cb3cee03d558fd457cb58f56c80a2a09a66110c the code generatedfor the in_beXX() and out_beXX() mmio functions has been sub-optimal.The out_leXX() family of functions are created with the macroDEF_MMIO_OUT_LE() while the out_beXX() family are created withDEF_MMIO_OUT_BE(). In what was perhaps a bit too much macro use, both ofthese macros are in turn created via the macro DEF_MMIO_OUT().For the LE versions, eventually they boil down to an asm that will looksomething like this:asm("sync; stwbrx %1,0,%2" : "=m" (*addr) : "r" (val), "r" (addr));While not perfect, this appears to be the best one can do. The issue isthat the "stwbrx" instruction only comes in an indexed, or 'x', version, inwhich the address is represented by the sum of two registers (the "0,%2").Unfortunately, gcc doesn't have a constraint for an indexed memoryreference. The "m" constraint allows both indexed and offset, i.e.register plus constant, memory references and there is no "stwbr" versionfor offset references.The unused first operand to the asm is just to tell gcc that *addr is anoutput of the asm. The address used is passed in a single register via thethird asm operand, and the index register is just hard coded as 0. Thismeans gcc is forced to put the address in a single register and can't useindex addressing, e.g. if one has the data in register 9, a base address inregister 3 and an index in register 4, gcc must emit code like "add 11,4,3;stwbrx 9,0,11" instead of just "stwbrx 9,4,3". This costs an extra addinstruction and another register.This brings us the to problem with the BE version. In this case, the "stw"instruction does have both indexed and non-indexed versions. The final asmends up looking like this:asm("sync; stw%U0%X0 %1,%0" : "=m" (*addr) : "r" (val), "r" (addr));The undocumented codes "%U0" and "%0X" will generate a 'u' if the memoryreference should be a auto-updating one, and an 'x' if the memory referenceis indexed, respectively. The third operand is unused, it's just therebecause asm the code is reused from the LE version. However, gcc does notknow this, and generates unnecessary code to stick addr in a register! Touse the example from the LE version, gcc will generate "add 11,4,3; stwx9,4,3". It is able to use the indexed address "4,3" for the "stwx", butstill thinks it needs to put 4+3 into register 11, which will never beused.This also ends up happening a lot for the offset addressing mode, wherecommon code like this: out_be32(&device_registers->some_register, data);uses an instruction like "stw 9, 42(3)", where register 3 has the pointerdevice_registers and 42 is the offset of some_register in that structure.gcc will be forced to generate the unnecessary instruction "addi 11, 3, 42"to put the address into a single (unused) register.The in_* versions end up having these exact same problems as well.Signed-off-by: Trent Piepho <tpiepho@freescale.com>CC: Benjamin Herrenschmidt <benh@kernel.crashing.org>CC: Scott Wood <scottwood@freescale.com>---There was some discussion on a Freescale list if the powerpc I/O accessorsshould be strictly ordered w.r.t. normal memory. Currently they are not. Itdoes not appear as if any other architecture's I/O accessors are strictlyordered in this manner. memory-barriers.txt explicitly states that the I/Ospace (inb, outw, etc.) are NOT strictly ordered w.r.t. normal memoryaccesses and it's implied the other I/O accessors (e.g., writel) are the same.However, it is somewhat harder to program for this model, and there are almostcertainly a number of drivers using coherent DMA which have subtle bugs becausethe do not include the necessary barriers.But clearly and change to this would be a subject for a different patch. include/asm-powerpc/io.h | 44 +++++++++++++++++++++++++------------------- 1 files changed, 25 insertions(+), 19 deletions(-)diff --git a/include/asm-powerpc/io.h b/include/asm-powerpc/io.hindex e0062d7..795b5d4 100644--- a/include/asm-powerpc/io.h+++ b/include/asm-powerpc/io.h@@ -95,33 +95,39 @@ extern resource_size_t isa_mem_base; #define IO_SET_SYNC_FLAG() #endif -#define DEF_MMIO_IN(name, type, insn) \-static inline type name(const volatile type __iomem *addr) \+#define DEF_MMIO_IN_LE(name, size, insn) \+static inline u##size name(const volatile u##size __iomem *addr) \ { \- type ret; \- __asm__ __volatile__("sync;" insn ";twi 0,%0,0;isync" \- : "=r" (ret) : "r" (addr), "m" (*addr)); \+ u##size ret; \+ __asm__ __volatile__("sync;"#insn" %0,0,%1;twi 0,%0,0;isync" \+ : "=r" (ret) : "r" (addr), "m" (*addr)); \ return ret; \ } -#define DEF_MMIO_OUT(name, type, insn) \-static inline void name(volatile type __iomem *addr, type val) \+#define DEF_MMIO_IN_BE(name, size, insn) \+static inline u##size name(const volatile u##size __iomem *addr) \ { \- __asm__ __volatile__("sync;" insn \- : "=m" (*addr) : "r" (val), "r" (addr)); \- IO_SET_SYNC_FLAG(); \+ u##size ret; \+ __asm__ __volatile__("sync;"#insn"%U1%X1 %0,%1;twi 0,%0,0;isync"\+ : "=r" (ret) : "m" (*addr)); \+ return ret; \ } +#define DEF_MMIO_OUT_BE(name, size, insn) \+static inline void name(volatile u##size __iomem *addr, u##size val) \+{ \+ __asm__ __volatile__("sync;"#insn"%U0%X0 %1,%0" \+ : "=m" (*addr) : "r" (val)); \+ IO_SET_SYNC_FLAG(); \+} -#define DEF_MMIO_IN_BE(name, size, insn) \- DEF_MMIO_IN(name, u##size, __stringify(insn)"%U2%X2 %0,%2")-#define DEF_MMIO_IN_LE(name, size, insn) \- DEF_MMIO_IN(name, u##size, __stringify(insn)" %0,0,%1")--#define DEF_MMIO_OUT_BE(name, size, insn) \- DEF_MMIO_OUT(name, u##size, __stringify(insn)"%U0%X0 %1,%0")-#define DEF_MMIO_OUT_LE(name, size, insn) \- DEF_MMIO_OUT(name, u##size, __stringify(insn)" %1,0,%2")+#define DEF_MMIO_OUT_LE(name, size, insn) \+static inline void name(volatile u##size __iomem *addr, u##size val) \+{ \+ __asm__ __volatile__("sync;"#insn" %1,0,%2" \+ : "=m" (*addr) : "r" (val), "r" (addr)); \+ IO_SET_SYNC_FLAG(); \+} DEF_MMIO_IN_BE(in_8, 8, lbz); DEF_MMIO_IN_BE(in_be16, 16, lhz);-- 1.5.4.1
http://lkml.org/lkml/2008/5/20/504
CC-MAIN-2014-42
refinedweb
955
51.07
Continuing my endeavour to convert my callbacks spaghetti code into something more readable, I’m stumbling against Panda3D implementation of gather() In asyncio, gather() takes a list of coroutines or futures and returns a future that typically is awaited on. AsyncFuture has a static method gather() that seems to do this job, but I can not make the whole thing work. from direct.task.Task import gather async def one(): print("ONE") async def two(): print("TWO") async def test(): await gather(one(), two()) print("THREE") def add_task(): print("CREATE") taskMgr.add(test(), 'test') print("DONE") import direct.directbase.DirectStart add_task() base.run() The output does not show any code from the coro one or two : Using deprecated DirectStart interface. Known pipe types: CocoaGraphicsPipe (all display modules loaded.) CREATE DONE
https://discourse.panda3d.org/t/task-gather-does-not-seem-to-work/27313
CC-MAIN-2022-33
refinedweb
130
54.63
. For example the PayrollTests.AddAndPayTest page shows a typical ColumnFixture that uses a valid() function to enter employee data into a database. RowEntryFixture is a better option in many cases. - RowEntryFixture is an abstract class. You have to derive from it. - It derives from ColumnFixture and works just the same way it does. - You override the enterRow function to add your data to the database. - If you have trouble adding your data, you throw an exception loaded with a message explaining the problem. Here is an example of a very simple RowEntryFixture: public class RowEntryExample extends RowEntryFixture { public int v; public void enterRow() throws Exception { if (v == 0) throw new Exception("Oh, no! Zero!"); } } And here you can see it running. [ User Guide] [.FrontPage] [.RecentChanges]
http://fitnesse.org/FitNesse.RowEntryFixture
crawl-001
refinedweb
125
58.99
by David Piepgrass A quick yet in-depth tour of TypeScript and its types Union types, generics, JSX, type system loopholes and more! This quick tour of TypeScript is mainly for people who have some experience with JavaScript. I’ll explain a few surprising facts about JavaScript, too, in case you only studied something vaguely similar, like Java or C#. If you’d like to know how to set up a TypeScript project, see my previous article. TypeScript is based on JavaScript. The TypeScript compiler (or other tools based on it, like ts-node or ts-jest) translates TypeScript into normal JavaScript simply by stripping out all the type information. Alongside that process, type checking is performed in order to discover type errors — mistakes you’ve made that have something to do with types. Of course, occasionally, it also complains about things you did intentionally that nevertheless broke the rules of TypeScript. Types Types can be attached to variables with a colon (:) in their definition, like so: let z: number = 26; However you often don’t have to write down the type. For example, if you write: let z = 26; TypeScript infers that z is a number. So if you write: let z = 26;z = "Not a number"; You’ll get an error on the second line. TypeScript originally did adopt a loophole though: any variable can be null or undefined: z = null; // Allowed!z = undefined; // Allowed! If you’re new to JavaScript, you’re probably wondering what null and undefined are, or why they are two different things. Well, I promised to tell you about TypeScript and null/ undefined are JavaScript things. Ha! Personally, I don’t use null very much. I find it convenient to use undefined consistently to avoid worrying about the distinction. undefined is the default value of new variables and function parameters that were not provided by the caller. It’s the value you get if you read a property that doesn’t exist on an object. By contrast, JavaScript itself only rarely uses null, so if you don’t use it yourself, you won’t encounter it very often. I’m sure some people do the opposite, and prefer null. Anyway, some people — including me — are of the opinion that allowing every variable to be null/ undefined was a bad idea. So TypeScript 2.0 allows you to take away that permission with the "strictNullChecks": true compiler option in “tsconfig.json”. You can use "strict": true for Maximum type checking. Instead, you would write: let z: number | null = 26; if you want z to be potentially null (| means “or”). Union types TypeScript has the ability to understand variables that can have multiple types. For example, here is some normal JavaScript code: This is allowed in TypeScript by default, because var y (by itself) gives y a type of any, meaning anything. So we can assign anything, for example value or object, to y. We can certainly set it to a string, or a number, or an array of two things. any is a special type — it means “this value or variable should act like a JavaScript value or variable and, therefore, not give me any type errors.” I recommend the "strict": true compiler option. But, in that mode, TypeScript doesn’t allow var y— it requires var y: any instead. However, TypeScript allows us to be more specific by saying: var y: string | number; This means “variable y is a string or a number”. If y is created this way, using the example above, the if-else part is allowed. But the other part that says y = [y, y] is not allowed, because [y, y] is not a string and not a number either. y is an array of type number[] | string[]. This feature, in which a variable can have one of two (or more) types, is called union types and it’s often useful. Tip: To help you learn TypeScript, it may help to do experiments in the playground. To help you learn more about JavaScript, press F12 in Chrome, Firefox or Edge and look for the Console. In the console you can write JavaScript code, to find out what a small piece of JavaScript does and whether you are writing it correctly: This console is fantastic because you can use it to run experiments in any browser tab — even this one! Since TypeScript is just JavaScript with static type checking, you can use the console to help you learn about the part of TypeScript that doesn’t have static types. In your TypeScript file you can call console.log(something) to print things in the browser’s console. In some browsers, log can display complex objects. For example, try writing console.log({name:"Steve", age:37, favoriteNumbers:[7, 666, -1]}): Classes As you know, classes are bundles of functions and variables that can be instantiated into multiple objects. Functions inside classes can refer to other functions and variables inside the class, but in JavaScript and TypeScript you must use the prefix this.A typical JavaScript class might look like this: The console output is: The big box is 10000 times larger than the small oneThe zero-size box has an area of 0. JavaScript is a little picky. When you create a function outside a class, it has the word function in front of it. But, when you create a function inside a class, it is not allowed to have the word function in front of it. Functions and methods are the same thing, except that methods in classes have access to this - a reference to the current object, except for static methods. static methods are called on the class , Box.ZeroSize in this example, so they do not have a “current object”. (Well, actually the current object of ZeroSize is the Box constructor function, which is not an instance of Box.) Unlike JavaScript, TypeScript classes allow variable declarations, such as width and height in this example: For convenience, TypeScript lets you define a constructor and the variables it initializes at the same time. So instead of width: number; height: number; constructor(width: number, height: number) { this.width = width; this.height = height; } you can simply write constructor(public width: number, public height: number) {} By the way, for any C# developers reading this, it works exactly like my LeMP system for C#. Unlike JavaScript, TypeScript has private (and protected) variables and functions which are inaccessible outside the class: private variables allow you to clearly mark parts of a class as “internal”. Users of the class cannot modify or read these. Interfaces Interfaces are a way of describing “shapes” of objects. Here’s an example: IBox refers to any class that has a width and height property that are readable numbers. IArea refers to anything with a readable area property. The Box class satisfies both of these requirements. The get area() function counts as a property, because it is called without () parentheses. So I could write: let a: IBox = new Box(10,100); // OKlet b: IArea = new Box(10,100); // OK Interfaces in TypeScript work like interfaces in the Go programming language, not like interfaces in Java and C#. That’s a good thing. It means that classes don’t have to explicitly say that they implement an interface. Box implements IBox and IArea without saying so. This means we can define interfaces for types that originally were not designed for any particular interface. For example, my BTree package defines an IMap<Key,Val> interface that represents a dictionary of key-value pairs. Th e new Map class built into ES6 also conforms to this interface, so you can put a Map in to an IMap variable. So, for example, you can write a function wi th an IMap parameter, and you can p ass a Map or a BTree to the function, and the function doesn’t need to know or care which type it received. readonly means we can read, but not change: console.log(`The box is ${a.width} by ${a.height}.`); // OKa.width = 2; /* ERR: Cannot assign to 'width' because it is a constant or a read-only property. */ TypeScript does not require readonly for interface compatibility. For example, TypeScript accepts this code even though it doesn’t work: interface IArea { area: number; // area is not readonly, so it can be changed} let ia: IArea = new Box(10,100);ia.area = 5; // Accepted by TypeScript, but causes a runtime error I think of it as a bug in TypeScript. TypeScript also has a concept of optional parts of an interface: interface Person { readonly name: string; readonly age: number; readonly spouse?: Person;} For example we can write let p: Person = {name:'John Doe', age:37}. Since p is a Person, we can later refer to p.spouse. This is equal to undefined in this case, but could be a Person if a different object were assigned to it that has a spouse. However, if you use p = {name:'Chad', age:19, spouse:'Jennifer'} with the wrong data type for spouse , TypeScript responds that Type string is not assignable to type Person | undefined. Intersection types Intersection types are the lesser-known cousin of union types. A union type like A | B means that a value can be either an A or a B, but not both. An intersection type like A & B means that a value is both A and B at the same time. For instance, this box is both IBox and IArea, so it has all the properties from both interfaces: let box: IBox & IArea = new Box(5, 7); If you mix union and intersection types, you can use parentheses to change the meaning: // either a Date&IArea or IBox&IArealet box1: (Date | IBox) & IArea = new Box(5, 7);// either a Date or an IBox&IArealet box2: Date | (IBox & IArea) = new Box(5, 7); & has higher precedence than |, so A & B | C means (A & B) | C. Structural types In some other programming languages, every type has a name, such as string or double or Component. In TypeScript, many types do have names but, more fundamentally, most types are defined by their structure. In other words, the type’s name, if it has one, is not important to the type system. Here’s an example where variables have a structural type: var book1 = { title: "Adventures of Tom Sawyer", year:1876 };var book2 = { title: "Adventures of Huckleberry Finn", year:1884 }; If you hover your mouse over book1 in VS Code, its type is described as { title: string; year: number; }. This is a structural type: a type defined entirely by the fact that it has a property called title which is a string, and another property called year which is a number. Thus book1 and book2 have the same type, and you can assign one to the other, or to a different book. book1 = book2; // allowedbook2 = { year: 1995, title: "Vertical Run" }; // allowed Generally speaking, you can assign a value with “more stuff” to a variable whose type includes “less stuff”, but not the other way around: var book3 = { title: "The Duplicate", author: "William Sleator", year:1988 };var book4 = { title: "The Boy Who Reversed Himself" };book1 = book3; // allowedbool1 = bool4; /* NOT allowed. Here is the error message: Type '{ title: string; }' is not assignable to type '{ title: string; year: number; }'. Property 'year' is missing in type '{ title: string; }'. */ In addition, if we have an interface like this: interface Book { title: string; author?: string; year: number;} Then we can assign any Book value to either book1 or book2. But author is required in book3 and Book might not contain an author. We can assign any of the book variables to a new variable of type Book , except book4, of course. Clearly, structural types are fantastic. This is obvious after you spend a few years using languages without them. For example, imagine if two people, Alfred and Barbara, write different modules A and B. They both deal with points using X-Y coordinates. So each module contains a Point interface: interface Point { x: number; y: number;} Many languages use nominal types instead of structural types. In these languages, A.Point is considered to be a completely different type than B.Point even though they are identical. So any points produced by A cannot be used by B and vice versa. This can be frustrating, so please take a moment to celebrate with me the wonder of TypeScript’s structural typing. Structural types can be written either with semicolons or commas, e.g. { x: number, y: number } and { x: number; y: number; } are the same. Flow-based typing and the exclamation mark If s is a string, you could write s.match(/[0-9]+/) to find the first group of digits in that string. /[0-9]+/ is a RegExp - an object that can be used to search strings using Regular Expressions. Regular expressions are a string-matching system supported by many programming languages, including JavaScript. match returns an array of strings, or null if the RegExp did not match the string. For example, if s = "I have 10 cats and 2 dogs" then s.match(/[0-9]+/) returns ["10"], but if s = "I have ten velociraptors and a weevil" then match returns null. If you were looking for digits in a string, you’d want your code to behave differently depending on whether the string has digits or not, right? So you’d use an if statement: var found: string[]|null = s.match(/[0-9]+/);if (found) { console.log("The string has a number in it: " + found[0]);} else { console.log("The string lacks digits.");} As you probably know, if (found) means “if found is truthy”. It basically means if (found != null && found != 0 && found != false). If you don’t check whether found !== null, TypeScript will give you an error: var found = s.match(/[0-9]+/);console.log("The string has a number in it: " + found[0]); // Error: Object is possibly 'null' ^^^^^ So why don’t you get an error when you use the if statement? That’s the magic of TypeScript’s flow-based typing. In the first branch of the if statement, TypeScript knows that found cannot be null, and so the type of found changes within that block to exclude null. Thus, its type becomes string[]. Similarly, inside the else {...} block, TypeScript knows that found cannot be string[], so string[] is excluded and the type of found becomes null in that region. But TypeScript has a ! operator which is used to avoid certain error messages. It means “look, compiler, I know you think this variable could be null or undefined, but I promise you it isn’t. So if found has type string[]|null, then found! has type string[].” If you’re sure that s has digits in it, you can use ! to avoid the error message: var found = s.match(/[0-9]+/);console.log("The string has a number in it: " + found![0]); TypeScript’s flow-based typing system supports the typeof and instanceof operators, as well as ordinary comparison operators. If you start with a variable that could have several types, you can use any of these operators to narrow down the type: Note: JavaScript distinguishes between primitive and boxed primitive types, which are objects. For example, "yarn" is a primitive, and its type is string. However, there is also a boxed string type called String with a capital S, which is rarely used. You can create a String by writing new String("yarn"). The thing to keep in mind is that these are totally different types. "yarn" instanceof String is false: "yarn" is a string, not a String! "yarn" instanceof string is not false. Instead it’s a totally illegal expression — the right-hand side of instanceof must be a constructor function and string does not have a constructor. JavaScript provides two different operators for testing the types of primitives and objects (non-primitives): instanceofchecks the prototype chain to find out if a value is a certain kind of object. typeofchecks whether something is a primitive and if so, what kind. As you can see in the code above, instanceof is a binary operator that returns a boolean, while typeof is a unary operator that returns a string. For example, typeof "yarn" returns "string" and typeof 12345 returns "number". The primitive types are number, boolean, string, symbol, undefined, and null. Everything that is not a primitive is an Object, including functions. But typeof treats functions specially. For example, typeof Math.sqrt === "function", and Math.sqrt instanceof Object === true. Symbols are new in ES6 and, although null is a primitive, typeof null === "object" is a mistake. As you can see in the example above, TypeScript also understands Array.isArray as a way to detect an array. However, some other methods of detecting types in JavaScript are not supported: if (thing.unshift)is sometimes used to distinguish strings from other things, because almost nothing except strings have an unshiftmethod. This is not supported in TypeScript because it does not let you read a property that may not exist. if (thing.hasOwnProperty("unshift"))isn’t recognized as a type test. if (thing.constructor === String)isn’t recognized as a type test. In JavaScript, reading a property such as constructorpromotes thingto Boxed status, so even if thingis a primitive string, its .constructorwill be non-primitive. if ("unshift" in thing)doesn’t work. “The right-hand side of an ‘in’ expression must be of type ‘any’, an object type or a type parameter.” ( inshould be avoided anyway because it is slow.) Type aliases The type statement creates a new name for a type. For example after writing: type num = number; You can use num as a synonym for number. type is similar to interface since you can write something like this… type Point = { x: number; y: number;} …instead of interface Point {...}. However, only interfaces support inheritance. For example I can create a new interface that is like Point but also has a new member z, like this: interface Point3D extends Point { z: number;} You can’t do inheritance with type. However if Point was defined with type, you are still allowed to extend it with an interface. Function types In JavaScript you can pass functions to other functions, like this: function doubler(x) { return x*2; }function squarer(x) { return x*x; }function experimenter(func){ console.log(`When I send 5 to my function, I get ${func(5)}.`);}experimenter(doubler);experimenter(squarer); Output: When I send 5 to my function, I get 10.When I send 5 to my function, I get 25. In TypeScript you normally need to write down the types of function arguments — you need to know how to express the type of func. As you can see here, its type should be something like (param: number) => number: function doubler(x: number) { return x*2; }function squarer(x: number) { return x*x; }function experimenter(func: (param: number) => number){ console.log(`When I send 5 to my function, I get ${func(5)}.`);}experimenter(doubler);experimenter(squarer); TypeScript requires you to give a name to the parameter of func, but it doesn’t matter what that name is. I could have called it x, or Wednesday, or myFavoriteSwearWord and it would have made no difference whatsoever. But don’t even think of calling it asshat. The compiler won’t care, but what about your boss? Better safe than sorry, that’s all I can say. In JavaScript, everything inside an object is a property — a kind of variable — and that includes functions. As a consequence, these two interfaces mean the same thing: interface Thing1 { func: (param: number) => number;}interface Thing2 { func(param: number): number;} And so this code is allowed: class Thing { func(x: number) { return x * x * x; }}let t1: Thing1 = new Thing();let t2: Thing2 = t1; Does it seem weird to you that TypeScript requires : before the return type of a “normal” function but it requires => before the return type of a function variable? Anyway, that’s the way it is. Generics, and dates, and stuff Dates Let’s say I write a function that ensures a value is an array, like this: function asArray(v: any): any[] { // return v if it is an array, otherwise return [v] return (Array.isArray(v) ? v : [v]);} The asArray function works, but it loses type information. For example, what if this function calls it? /** Prints one or more dates to the console */function printDates(dates: Date|Date[]) { for (let date of asArray(dates)) { // SUPER BUGGY! var year = date.getYear(); var month = date.getMonth() + 1; var day = date.getDay(); console.log(`${year}/${month}/${day}`); }} The TypeScript compiler accepts this code, but it has two bugs. The code correctly added 1 to the month, because getMonth() returns 0 for January and 11 for December. But the code for getting the year and day are both wrong. Since asArray returns any[], however, type checking and IntelliSense — which could have caught these bugs — is disabled on date. These bugs could have been avoided if asArray was generic: function asArray<T>(v: T | T[]): T[] { return Array.isArray(v) ? v : [v];} This version of asArray does the same thing, but it has a type parameter, which I have decided to call T, to enable enhanced type checking. The type parameter can be any type, so it is similar to any. But it enables the function to describe the relationship between the parameter v and the return value. Specifically, it says that v and the return value have, well, similar types. When you call asArray, the TypeScript compiler finds a value of T that allows the call to make sense. For example, if you call asArray(42) then the compiler chooses T=number because it is possible to use 42 as an argument to asArray(v: number|number[]): number[]. After choosing T=number, TypeScript realizes that asArray returns an array of numbers. In printDates we called asArray(dates) and the compiler figures out that T=Date works best in that situation. After choosing T=Date, TypeScript realizes that asArray returns an array of Date. Therefore, the variable date has type Date, and then it finds the first bug: date.getYear does not exist! Well, actually it does exist, but it has been deprecated due to its behavior — it returns the number of years since 1900 — 118 in 2018. Instead, you should call getFullYear. TypeScript itself doesn’t notice the second bug. But, when you type date.getDay, VS Code will inform you in a little popup box that this function “Gets the day of the week, using local time”. The day of the week? You have got to be kidding me! Thanks to generics and VS Code, we fix our code to call date.getDate instead. This does not return the date without a time attached to it but, rather, the day of the current month. Unlike the month, the day does not start counting from zero. /** Prints one or more dates to the console */function printDates(dates: Date|Date[]) { for (let date of asArray(dates)) { var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); console.log(`${year}/${month}/${day}`); }} One good thing about Dateis that they are normally stored in UTC — universal time zone, or GMT. This means that if the user changes the time zone on their computer, the Date objects in your program continue to represent the same point in time, but the string returned by .toString() changes. Usually this is what you want, especially in JavaScript where you might have client and server code running in different time zones. Generics An advanced example of generics appears in my simplertime module. In this case I had a timeToString function that accepted a list of formatting options like this: export interface TimeFormatOptions { /** If true, a 24-hour clock is used and AM/PM is hidden */ use24hourTime?: boolean; /** Whether to include seconds in the output (null causes seconds * to be shown only if seconds or milliseconds are nonzero) */ showSeconds?: boolean|null; ...} export function timeToString(time: Date|number, opt?: TimeFormatOptions): string { ...} The export keyword is used for sharing code to other source files. For example you can import timeToString in your own code using import {timeToString} from 'simplertime' (after installing with npm i simplertime of course). If you want to import things from a different file in the same folder, add a ./ prefix on the filename, e.g. import * as stuff from './mystuff'. Generics can also be used on classes and interfaces. For example, JavaScript has a Set type for holding an unordered collection of values. We might use it like this: var primes = new Set([2, 3, 5, 7]);for (var i = 0; i < 10; i++) console.log(`Is the number ${i} prime? ${primes.has(i)}`); In TypeScript, though, Set has a type parameter, Set<;T>, meaning that all items in the set have that T=number, so if you write primes.add("hello!") you’ll get a Type Error. If you actually want to create a set that can hold both strings and numbers, you can do it like this: type T. In this code TypeScript inferstype T. In this code TypeScript infers var primes = new Set<string|number>([2, 3, 5, 7]); You can also create your own generic types. For example, I created a B+ Tree data structure called BTree<K, V>, which is a collection of key-value pairs, sorted by key, that supports fast cloning. It has two type parame ters, K (a key ) and V (a value) and its definition looks roughly like this. Note: function bodies have been omitted because I just want to show you how a generic class looks: Literals as types Remember how there is an error when you write this? let z = 26;z = "Zed"; The error message sounds a bit strange: Type '"Zed"' is not assignable to type 'number' Why does it say that "Zed" is a “type”, instead of a “value” or a “string”? In order to understand this, it is necessary to understand that TypeScript has an ability to treat values as types. "Zed" is a string, of course, but it’s more than that — it has another type at the same time, a more specific type called "Zed" which represents the value "Zed" . We can even create a variable with this type: let zed: "Zed" = "Zed"; Now we have created a completely useless variable called zed. We can set this variable to "Zed", but nothing else: zed = "Zed"; // OKzed = "ZED"; // Error: Type '"ZED"' is not assignable to type '"Zed"'. By default we can set zed to null and undefined. Luckily with the "strictNullChecks": true option, we can close that loophole so that this variable will never be anything except “Zed”. Thank God for that, is all I can say. So what are these literal-types good for? Well, sometimes a function allows only certain particular strings. For example, imagine if you have a function that lets you turn("left") or turn("right") but nothing else. This function could be declared with a literal-type: function turn(direction: "left"|"right") { … } Fixed-length arrays Here’s another puzzle for you: what’s the difference between the types number[] and [number]? The first is an array of numbers, the second is an array that contains only one element, which is a number. Similarly [string,number] denotes an array of length 2 with the first element being a string and the second being a number. In addition, the array has a property length: 2, i.e. its type is 2, not just number. These fixed-length arrays are called tuple types. Advanced generics So, remember the simplertime module I was talking about? It also exports a defaultTimeFormat object which holds default values for the timeToString formatting options. I wanted to define a special function which would allow me to write things like get(options, 'use24hourTime') to retrieve the value of options.use24hourTime if it exists and defaultTimeFormat.use24hourTime if it does not exist. In many languages it is impossible to write a function like that, but it is possible in “dynamic” languages such JavaScript. Here’s how the get function would look like in JavaScript: function get(opt, name) { if (opt === undefined || opt[name] === undefined) return defaultTimeFormat[name] return opt[name];} In JavaScript and TypeScript, thing.property can be written as thing["property"] instead and, if the property does not exist, the result is undefined. But in the square-bracket version we can use a variable, so that the question “which property are we using?” can be answered by code located elsewhere. Translating this to TypeScript is possible with a feature called keyof, but it’s very tricky. Here is the translation: function get<;K extends keyof TimeFormatOptions>( opt: TimeFormatOptions|undefined, name: K): TimeFormatOptions[K]{ if (opt === undefined || opt[name] === undefined) return defaultTimeFormat[name] return opt[name];} Here, the type variable K has a constraint attached to it, K extends keyof TimeFormatOptions. Here’s how it works: keyof Xturns the properties of Xinto a union type of the names of the properties. For example, given the Bookinterface from earlier, keyof Bookmeans "title" | "author" | "age". Likewise keyof TimeFormatOptionsis any of the property names in TimeFormatOptions. - The “extends” constraint, X extends Y, means that “X must be Y, or a subtype of Y”. For example X extends Objectmeans that Xmust be some kind of Object, which means it can be an array or a Dateor even a function, all of which are considered to be Objects, but it can’t be a stringor a numberor a boolean. Similarly X extends Pointmeans that Xis Pointor a more specific type than Point, such as Point3D. - What would B extends keyof Bookmean? It would mean that Bis a subtype of "title" | "author" | "age". And, remember, that we are talking about types here, not values. The string literal "title"has the value "title"but it also has the type "title", which is a different concept. The type is handled by the TypeScript type system, and the value is handled by the JavaScript. The "title"type no longer exists when the program is running, but the "title"value still does. Now, Bcan be assigned to types like "title"or "title" | "age", because every value of type "title" | "age"(or "title") can be assigned to a variable of type keyof Book. However Bcannot be string, because some strings are not “title”, “author”, or “age”. - Similarly, Kis constrained to have a subtype of keyof TimeFormatOptions, such as "use24hourTime". - The type X[Y]means “the type of the Y property of X, where Y is a number or string literal”. For example, the type Book["author"]is string | undefined. Putting this all together, when I write get(options, 'use24hourTime'), the compiler decides that K='use24hourTime'. Therefore, the name parameter has type "use24hourTime" and the return type is TimeFormatOptions["use24hourTime"], which means boolean | undefined. Holes in the type system Since TypeScript is built on top of JavaScript, it accepts some flaws in its type system for various reasons. Earlier we saw one of these flaws, the fact that this code is legal: class Box { constructor(public width: number, public height: number) {} get area() { return this.width*this.height; }} interface IArea { area: number; // area is not readonly} let ia: IArea = new Box(10,100);ia.area = 5; // Accepted by TypeScript, but causes a runtime error Here are some other interesting loopholes: You can assign a derived class to a base class A Date is a kind of Object so naturally you can write: var d: Object = new Date(); So it makes sense that we can also assign this D interface to this O interface, right? interface D { date: Date }interface O { date: Object }var de: D = { date: new Date() }; // okay...var oh: O = de; // makes sense...oh.date = { date: {wait:"what?"} } // wait, what? Well, no, not really, because TypeScript now believes de.date is a Date when it is actually an Object. You can assign [A,B] to (A|B)[] It makes sense that an array of two items, an A followed by a B, is also a an array of A|B, right? Actually, no, not really: var array1: [number,string] = [5,"five"];var array2: (number|string)[] = array1; // makes sense...array2[0] = "string!"; // wait, what? TypeScript now believes array1[0] is a number when it is actually a string. This is an example of a more general problem, that arrays are treated as covariant but they aren’t really covariant because they are editable. Arrays? There be dragons. In the recommended strict mode, you can’t put null or undefined in arrays of numbers… var a = [1,2,3];a[3] = undefined; // 'undefined' is not assignable to type 'number' So that means when we get a value from an array of numbers, it’s a number, right? Actually, no, not really: var array = [1,2,3];var n = array[4]; TypeScript now believes n is a number when it is actually undefined. A more obvious hole is that you can allocate a sized array of numbers… with no numbers in it: var array = new Array<number>(2); // array of two "numbers"var n:number = array[0]; Function parameters are bivariant when overriding Unlike other languages with static typing, TypeScript allows overriding with covariant parameters. Covariant parameter means that, as the class gets more specific (A to B), the parameter also gets more specific (Object to Date): class A { method(value: Object) { }} class B extends A { method(value: Date) { console.log(value.getFullYear()); }} var a:A = new B();a.method({}); // Calls B.method, which has a runtime error This is unsafe, but oddly it is allowed. In contrast, it is (relatively) safe to override with contravariant parameters, like this: class A { method(value: Date) { }}class B extends A { method(value: Object) { console.log(value instanceof Date); }} Covariant return types are also safe: class A { method(): Object { return {} }}class B extends A { method(): Date { return new Date(); }} TypeScript rightly rejects contravariant return types: class A { method(): Date { return new Date(); }}class B extends A { // Property 'method' in type 'B' is not assignable to // the same property in base type 'A'. // Type '() => Object' is not assignable to type '() => Date' // Type 'Object' is not assignable to type 'Date' method(): Object { return {} }} Classes think they are interfaces (but they’re not) TypeScript allows you to treat a class as though it were an interface. For example, this is legal: class Class { content: string = "";} var stuff: Class = {content:"stuff"}; Stuff isn’t a real Class, but TypeScript thinks it is, which can cause a runtime TypeError if you use instanceof Class somewhere else in the program: function typeTest(x: Class|Date) { if (x instanceof Class) console.log("The class's content is " + x.content); else console.log("It's a Date in the year " + x.getFullYear());} typeTest(stuff); this isn’t necessarily what you think this is a loophole of JavaScript, not TypeScript. Any time a function uses this, it might be accessing some completely unexpected object, with a different type than you think: class Time { constructor(public hours: number, public minutes: number) { } toDate(day: Date) { var clone = new Date(day); clone.setHours(this.hours, this.minutes); return clone; }} // Call toDate() with this=12345Time.prototype.toDate.call(12345, new Date()); TypeScript’s only sin is that it won’t try to stop you from doing this. Speaking of this, one thing JavaScript developers should know is that arrow functions like x => x+1 work slightly differently than anonymous functions li ke function(x) {return x+1}. Arrow functions inherit the value of this from the outer function in which they are located. Normal functions receive a new value of this from the caller. So, if f is an arrow function, f.call(12345, x) doesn’t change this, so it’s like calling f(x). That’s usually a good thing, but if you write: var obj = { x: 5, f: () => this.x } You should realize that obj.f() does not return obj.x. Lessons To avoid these holes, you need to: - Not treat an object as a “baser” type (e.g. don’t treat Das an O) unless you are sure that the baser type won’t be modified in a way that could violate the type system. - Not treat an array as a “baser” type (e.g. don’t treat D[]as O[], or [A,B]as (A|B)[]) unless you are sure that the baser type won’t be modified in a way that could violate the type system. - Be careful not to leave any “holes” with undefined values in your arrays. - Be careful not to use out-of-bounds array indexes. - Not override a base-class method with covariant parameters. - Avoid treating a class Kas though it were an interface, unless you are sure that no code will ever check the type with instanceof. - Avoid using .call(...), and be careful how you deal with references to functions. TypeScript actually had more holes in the past, which are now plugged. JSX React introduced the concept of JSX code. Or, maybe, Hyperscript introduced it and React copied the idea soon afterward. In any case, JSX looks like HTML/XML code. But you are not making DOM elements, you’re making plain-old JavaScript objects, which we call a “virtual DOM”. For example, <img src={imageUrl}/> actually means React.createElement("img", { src: imageUrl }) in a .jsx or .tsx file. If JSX is a React thing, why am I talking about it in the TypeScript section? Because support for JSX is built into the TypeScript compiler. To get JSX support in any TypeScript file, you just have to change the file’s extension from .ts to .tsx. JSX can be used in the same places as normal expressions: you can pass JSX code to a function… ReactDOM.render(<h1>I'm JSX code!</h1>, document.body); you can store it in a variable… let variable = <h1>I'm JSX code!</h1>; and you can return it from a function… return <h1>I'm JSX code!</h1>; Because <h1>I'm JSX code!</h1> really just means React.createElement("h1", null, "I'm JSX code!"). It is important whether a JSX tag starts with a capital letters — it is translated to TypeScript (or JavaScript) differently if it does. For example: <div class="foo"/> means React.createElement('div', {"class":"foo"}), but <Div class="foo"/> means React.createElement(Div, {"class":"foo"}) (without quotes a round Div). Tips for using JSX: - JSX is XML-like, so all tags must be closed: write <br/> , not <br>. - JSX only supports string attributes and JavaScript expressions. When writing numeric attributes in TypeScript, use <input type="number" min={0} max={100}/>, be cause max=100 is a syntax erro r and max="100" is a type error. - In React/Preact, you can use an array of elements in any location where a list of children are expected. For example, instead of return <p>Ann<br/>Bob<br/>Cam&l t;/p>, you can write let x = [<br/>, 'Bob', <br/>]; return <p>Ann{x}Cam</p>. This has the same effect because React/Preact “flattens” arrays in the child list. - In React, the classattribute is not supported for some reason. Use classNameinstead. - JSX itself does not support optional property or children. For example, suppose you write <Foo prop={x}> but you want to omi t the prop x is undefined. Well, JSX itself doesn’t support anything like that. However, most components tre at an undefined property the same as a missing property, so it usually works anyway. JSX doesn’t support optional children either, but you can get the same effect with an empty array: because arrays are “collapsed” by React/Pr eact, <Foo>{ [] }</Foo> has t he same effec t as <Foo></Foo>. <Foo>{undefined}</Foo> does not have this effect (you endup with a single child equal to undefined.) - If you have an object like obj = {a:1, b:2}and you would like to use all the properties of the object as properties of a Component, you can write <Component {...obj}/>. The dots are always requ ired; <Component {obj}/> is not allowed. At the top of the file, the @jsx pragma can control the “factory” function that is called to translate JSX elements. For example if you use /** @jsx h */ then <b>this</b> tr anslates to h('b', null, "this") instead of React.createElement('b', null, "this"). Some Preact apps use t his pragma (h is the preact function to create elements), but you won’t need to use it in thi s tutorial (createElement is a synonym for h). Also, in “tsconfig.json” you can get the same effect with "jsxFactory": "h" in the compilerOptions. See also TypeScript evolution explains the newest TypeScript features in more detail. You might also like to see Advanced Types in TypeScript’s manual. Before you go… If you liked this article, don’t forget to clap or tweet! And if you’d like to learn React, continue on to my next article.
https://www.freecodecamp.org/news/typescript-and-its-types-f509d799947d/
CC-MAIN-2019-35
refinedweb
6,839
72.36
use: import java.awt.image.*; import java.awt.*; //... // original image: Image image = ... // we create a filter to crop the image in a box starting at (25, 30), that is 50 pixels // wide and 50 pixels high CropImageFilter filter = new CropImageFilter(25,30,50,5 // we create the new image, cropped version of the original: Toolkit toolkit = Toolkit.getDefaultToolkit( Image croppedImage = toolkit.createImage(new FilteredImageSource(image. as a rectangle drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) the sx1,sy1 is the x and y coordinate of the image, the upper left corner the sx2,sy2 is the x and y coordinate of the image, the lower right corner there are other ways to crop... this is just a quick suggestion
https://www.experts-exchange.com/questions/10099647/Easy-Image-one.html
CC-MAIN-2018-17
refinedweb
133
51.38
Hace 4 años Hace 4 años decidí mudarme a vivir a Santiago. Necesitaba ver a mi hermana, que ya hacia tiempo estaba viviendo allá, pero además necesitaba salir de una duda, arriesgarme como un quinceañero y lanzarme a la vida antes que las neuronas retomaran su trono. Pasar tiempo con alguien que por esas tincadas irracionales, me parecía que llegaría a ser alguien importante en mi vida. Así fue, ese alguien era Andrea y hoy cumplimos 4 años. Qué felices 4 años! Esta es la primera de muchas fotografías que nos tomaríamos. Syndicated 2008-05-11 21:03:15 from Dewback, bits & pieces May 11War was a bit more cerebral than I was expecting, and I certainly didn't see the twist coming. Pretty good movie, though. Syndicated 2008-05-11 23:59:59 from Waider's Geek Diary Sans.se A week of Xbox fun). Syndicated 2008-05-11 20:48:00 (Updated 2008-05-11 21:00:00) from zeenix Metrics Provide An Inner Product Another post for the Poincaré Project. We've already seen that a one-form is a linear function from a vector to a (for our purposes) real number. On a manifold, one-forms correspond to stack-type vectors being applied to arrow-type vectors by counting how many "stacks" the arrow passes through. In the previous post Metrics As Mappings Between Arrows and Stacks, we saw that a metric is an extra bit of structure that describes how to map between arrow-type vectors and stack-type vectors. So, in summary: These two facts can be combined to let you take two arrow-type vectors and get a real number out of them. This has parallels with currying in functional programming. Recall that if a function "add" takes two integers and returns an integer, it can be viewed as a function that takes one integer and returns a function that takes one integer and returns an integer. add :: Int -> Int -> Int Now, a one-form is a function that takes a vector and returns a real. In other words: Vector -> Real So it is easy to see that if you curry a real-valued function that takes two vectors you get: Vector -> Vector -> Real In other words, a function taking two vectors to a real is equivalent to a function from a vector to a one-form. So if you have a metric that can convert between vectors and one-forms (or, in the context of a manifold, between arrows and stacks) then you also have a function from two vectors to a real. Such a function is called an inner product or dot product. Often the notion of an inner product is defined first, before one-forms are introduced (if at all). In fact, some texts will define a metric to be an inner product. It is best for our purposes, though, to think of the metric's fundamental purpose as being converting between arrows and stacks (and back again) and the inner product as being an extra concept we get for free. Syndicated 2008-05-11 14:55:12 (Updated 2008-05-11 14:55:14) from James Tauber As Always, Always Follow the Incentives.... Syndicated 2008-05-12 00:03:30 from Mark Atwood Kubuntu issues - follow-upI'm just following up on my last post - thanks to everyone commenting! Syndicated 2008-05-11 11:15:00 from Life of a Developer M. Syndicated 2008-05-10 08:36:26 from etbe Israeli Independence Day Special: Enough with the Obsession With National Security! (English Transla Note:! Syndicated 2008-05-11 16:03:08 from shlomif where is sarah?<content type="xhtml"> today i checked my deserted blog, feeling a bit guilty after a friend had told me that i have effectively vanished behind the google cone of silence. and what do i see in the logs? 5 days, 9 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 5 days, 6 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 5 days, 3 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 5 days ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 21 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 18 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 15 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 12 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 9 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 6 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days, 3 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 4 days ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 21 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 18 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 15 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 12 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 9 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days, 6 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 3 days ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 21 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 18 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 15 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 12 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 9 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 6 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days, 3 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 2 days ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 21 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 18 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 15 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 12 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 9 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 6 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day, 3 hours ago 209.85.238.3 Search: query for 'sarah m. byers' 1 day ago 209.85.238.3 Search: query for 'sarah m. byers' 21 hours, 46 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 18 hours, 46 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 15 hours, 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 12 hours, 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 9 hours, 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 6 hours, 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 3 hours, 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' 45 minutes ago 209.85.238.3 Search: query for 'sarah m. byers' someone* must be really interested in sarah's whereabouts! if you haven't heard, sarah is currently traveling in the stans for work. when internet connectivity allows, she is posting awesome pictures. here is a sampler:<style>div#setThumbs div.setThumbs-indv {float:left;} div#setThumbs span.pc_s {display:block;} div#setThumbs span.pc_s a.pc_link img {bottom:3px; float:left;} </style> * "someone" indeed. here's why. Syndicated 2008-05-11 23:54:20 (Updated 2008-05-12 00:23:39) from gregor 2008-05-11 GPL is not always the GNU General Public License G Syndicated 2008-05-11 14:04:56 from AdulauWikiDiary: RecentChanges oops Really, really windy day. There was a tornado watch until 3, which I didn't think much about until I was up on a ridge overlooping Slagle Hollow at 3:30, in one of the strongest winds I've experienced, blowing small branches past me. And lost. That could have not turned out well, but I made the right guesses at the turns, and it gave me the incentive to power-hike for an hour to get down off the hill and back to Roosterfront. Before that I found a beautiful long hollow full of mossy deadfalls and trilliums, atonishingly close to the well-traveled trails. Syndicated 2008-05-11 23:53:44 from see shy jo I, 2008-05-11: Engineers without Borders<!-- start of entry 200805/11 --> Engineers without Borders I went to an Engineers Without Borders conference in Montreal a while ago, and I was very impressed; these people seem to have their goals straight. And little did I know that it was founded in 2000 by University of Waterloo students who were in school at the same time I was. Considering it now has 25000+ members, that's incredibly fast growth. Anyway, as a sample of the sort of things they do, here's a report of a field study of how a proposed drought-resistant crop worked out in a heavy rainfall season. Summary: not so well. But that's not the point; the point is that they actually went to check, and then reported the results honestly, just like you'd expect engineers to do. I really respect that. <!-- end of entry 200805/11 --> Syndicated 2008-05-08 18:57:02 from apenwarr - Business is Programming Edwards attributes that to a lucky twist: The computer was running an ancient operating system, DOS, which does not scatter data all over drives as other approaches do. Μετά τη συνάντηση της 23 Απριλίου στη Θεσσαλονίκη αποφάσισα να δημιουργήσω (και να συντηρώ) τη. Προφανώς το εγχείρημα αυτό απαιτεί μεγάλο όγκο αρχικών δεδομένων και αυτοματοποίηση της διαδικασίας δημιουργίας του γράφου. Τη δεύτερη απαίτηση την ικανοποίησα με ένα απλό Perl πρόγραμμα μεγέθους μερικών δεκάδων γραμμών το οποίο κάνει χρήση του προγράμματος sig2dot.pl ως βιβλιοθήκη. Για την ικανοποίηση της πρώτης απαίτησης μπορείτε να συνεισφέρετε στέλνοντάς μου στη διεύθυνση argp at domain cs.tcd.ie το αποτέλεσμα της εντολής gpg --list-sigs > $USER.txt. Κάποια πρώτα αποτελέσματα υπάρχουν παρακάτω. Η πρόσφατη συνάντηση στη Θεσσαλονίκη είναι εμφανής στο πάνω δεξιά μέρος του γράφου.. Syndicated 2008-05-10 15:31:49 from I Am Not Charles OpenQabal 0.0.3 available OpenQabal 0.0.3 has been released and is now available from the SVN repo. As with previous releases, there are not yet pre-built binary releases available... you will have to check the code out from SVN and build it. Thankfully this process is now *much* easier as a result of massive work on the build system and the addition of scripts to automate most of the tedious stuff. You can now essentially build and install OpenQabal with 4 commands. Changes in this release include: This release is a huge step in the direction of having a really usable system, but there is still a LOT of work to be done. Some things that had originally been planned for this release had to be deferred to 0.0.4, with OpenID support being the most notable such item. And of course there are still plenty of ideas on the roadmap that we haven't even gotten started on yet. But we're now in a lot better position to be able to start on some of the more interesting stuff, such as the "distributed conversation" support, tools for building a managing the "social graph," etc. Look for a new post soon with more discussion of what the roadmap will look in the near future, as well as some discussion of some of the important changes that did make it into 0.0.3. And with any luck, the long-awaited "demo server" will be coming soon, as well as some screencasts and other ways of exploring OpenQabal. Syndicated 2008-05-10 22:24:31 (Updated 2008-05-10 22:25:45) from openqabal Smirking cat murderedThis is a weird story already, but that illustrative photo, and especially its caption, are just plain bizarre. Syndicated 2008-05-10 16:56:00 (Updated 2008-05-10 16:57:44) from John Levon May 10Oof, woke up with a head full of BEES. Or something. That'll teach me... or not. Syndicated 2008-05-10 23:59:59 from Waider's Geek Diary Yea, just look at all the passion on that wall. Syndicated 2008-05-10 20:00:06 from Steve Kemp's Blog Walk of ShameThis is great.... Syndicated 2008-05-10 23:43:15 (Updated 2008-05-11 19:17:38) from Brad Fitzpatrick Introducing Pinax: Syndicated 2008-05-10 15:22:38 (Updated 2008-05-10 15:22:40) from James Tauber OMG IT IS A NEW MEMEWhen Obama wins... Syndicated 2008-05-11 01:36:13 from Monument . Syndicated 2008-05-10 18:47:52 from shlomif song archetypes: the list song I often think about different kinds of song archetypes -- songs that either in form or content, get written and rewritten constantly. One of these days, I want to do an album of all song archetypes... I suppose one approach would be to make you try to figure out what archetype it is, and the other approach would be to make it incredibly obvious... I'm not sure which strategy I'll take on this nebulous idea (file it under "probably won't ever happen"). Anyway, one archetype that, as a kid, I thought was absolutely hilarious and clever, was what I called the "list song", which basically just begged you to memorize it. Notable list songs: We Didn't Start the Fire, and It's the End of the World As We Know It. I think that American Pie is also one part list song -- it's also one part "mysterious lyrics" song, which is a different archetype I'll talk about some other time. All three of those also have the distinction of being list songs about historical events... but I'm sure there are lots of these songs out there. Stay tuned for more song archetypes. Syndicated 2008-05-10 17:53:49 from (l)andscape: (a)lien Toll Avoidance, and Gain Conversions Syndicated 2008-05-10 21:57:00 (Updated 2008-05-10 21:57:27) from Kelly Martin interesting research on ‘conditional cooperation’…) Syndicated 2008-05-10 16:39:21 from Luis Villa's Blog The Stainless Steel Rat SeriesI am increasingly becoming obsessed with science fiction from 1950s and 1960s. Again stolen from Wikipedia, here is a list of all the Stainless Steel Rat books: Syndicated 2008-05-12 03:19:00 from stillhq.com : Mikal, a geek from Canberra living in Silicon Valley As can be seen on our roadmap sample support is scheduled for 0.4. As this is the major feature, we started working on it. I have to say that building buzztard on top of GStreamer was definitely the right thing to do. We can now load whatever GStreamer can handle. FSM did a nice cairo-based waveform widget. Right now I am working on the code that allows plugins to access the wavetable. It will hopefully be ready real soon. Besides that I've started to restructure the gst-buzztard package a bit further. I also plan to merge the buzz wrapper plugin into it. The aim is to reduce the number of packages that one needs to build. Well, it’s taken a month and a half — and over 2000 lines of code — but I finally got a method out of Shark. I made a chart showing which bytecodes are implemented, which I’ll keep updated as I progress. The estimated total coverage of 18% is slightly fanciful as it treats all bytecodes as equally complex, with nop having the same weight as new for example. Some codes are marked as complete but untested too. The way the compiler is structured means that in simple cases I can copy and paste whole blocks of bytecodes from the server compiler, so where I was doing one bytecode in a block I’ve copied the lot across. Most of them ought to be fine, but a couple are dubious. I’m still shuffling things around to try and make things less so. Onwards… Syndicated 2008-05-09 12:25:55 from gbenson.net Doing Nothing Better in Perl 5 Perl<nobr> <wbr></nobr> ..."))) + } ; <nobr> <wbr></nobr>/* "my" declarations, with optional attributes */ Apply this to recentish bleadperl sources, run perl regen_perly.pl, rebuild, and now you can run programs such as: sub foo {<nobr> <wbr></nobr>... } foo(); And get an "Unimplemented at file line line." error message. (Now everyone who complains that I don't code enough to match my talk, please punch yourself in the face.) Syndicated 2008-05-10 02:24:04 from pudge Wordpress from daniel.haxx.se Elite Oolite When I lived in Brunei in the mid-80s, a neighbour had a BBC Micro and I would go over there to play the space trading game Elite. :-) I was aware of various Elite clones over the years, but the other day I stumbled across Oolite, an open-source Mac OS X version with modern OpenGL graphics. Simply amazing and just as addictive as I remember the original being. It also seems to be highly pluggable, with numerous extensions available to add both to the UI and gameplay. Syndicated 2008-05-09 23:27:59 (Updated 2008-05-09 23:34:36) from James Tauber Engessamento Conceitual Toda pessoa tem suas preferências em relação a uma série de assuntos, tecnologias e opções. Nós, que trabalhamos com tecnologia, não somos exceção a isso. Muitas vezes discutimos apaixonadamente sobre nossas tecnologias preferidas. E muitas vezes, não deixamos de incorrer em alguns erros no processo. Recentemente, no PlanetPython foi veiculado um texto de wjbyral, mostrando algumas razões porque ele não gostava de javascript. Entre as razões citadas estão o fato de javascript não ter namespace e o sistema de objetos de javascript. Javascript não é uma linguagem orientada a objetos clássica, como Java, Python, ou qualquer outra que você possa lembrar. Ela segue o conceito de protótipos. Existe um tipo de 'desejo coletivo' de que javascript se torne uma linguagem orientada a objetos mais convencional, com construtores e herança de forma mais tradicional. Aliás, isso já está sendo feito, com o ecmascript4. Há um tempo atrás, eu dei uma olhada em como está ficando a especificação. Meu primeiro pensamento foi: 'estragaram a linguagem!'. O padrão adiciona toda o arcabouço comum da orientação a objetos tradicional: construtores, herança, etc. A linguagem passa a ser multi-paradigma: além dos protótipos, teremos agora a herança comum. Fora o fato de, em muitos sentidos, javascript ter um certo sabor de linguagem funcional. Uma maravilha não? Porém, o fato é que eu gosto da linguagem como é agora. Trabalho com linguagens orientadas a objetos, mas isso não quer dizer que eu despreze outros paradigmas. Todos eles tem a sua beleza e a sua vez. Pra que esse sentimento uniformizador das coisas? Qualquer cristalização em torno de algum conceito fatalmente me aborrecerá. A orientação a objetos é boa? Com certeza é. Mas é necessariamente melhor que o paradigma funcional, por exemplo? Talvez seja para os casos x e y, mas não para o z. Isso me lembra outro conceito, que trazemos do mundo da informática para outros lugares de forma equivocada. Esperamos que o último computador seja sempre melhor que o anterior. Mais memória, mais velocidade de processamento, um HD maior e, claro, sempre a um preço menor do que aquele que você comprou seis meses atrás. Mas nem todos os lugares isso é assim: um piano Fender Rhodes e uma Fender Stratocaster terão sempre o seu valor e não serão necessariamente piores que seus equivalente mais modernos. Nem sempre a próxima linguagem ou a próxima moda será inerentemente melhor que as anteriores. Para cada caso e situação certamente haverá uma ferramenta melhor. E para o bem de todos, é bom que diferenças de pensamento sempre existam. Syndicated 2008-05-09 14:53:56 from devlog The WombatsWho are The Wombats and why does Facebook think that I should get targetted ads about them since I list the Cure on my favourites list? Syndicated 2008-05-09 16:15:45 (Updated 2008-05-09 16:17:55) from Monument LangPop.com - programming language popularity - update These few days when Ilenia and Helen are still in the hospital are the eye of the storm for me. It's quiet at home and I actually have a few free hours when I'm not allowed to be in the hospital, or when they need to get some rest. One of the things I managed to do recently was some Javascript hacking in order to create a timeline for LangPop.com:. It was fun, because most of the "heavy lifting" is done by Timeplot, and I just had to push the data into place. Of course, there isn't much interesting there because the site is relatively new, but it should be interesting to see how languages fare over time. I did some hacking on Timeplot to make it easier to host it on my own server, and to load a bit faster by stuffing it into one big ugly blob of Javascript. When I get a bit of time, I'll make my changes public, as I think they're fairly useful for anyone who wants to fiddle around with Timeplot some, and thus host it themselves. The other thing I did with the site was switch the X and Y axis of the charts, because that works out better in terms of screen space for the labels, with so many languages to keep track of. Syndicated 2008-05-09 16:15:00 (Updated 2008-05-09 16:25:16) from David's Computer Stuff Journal greenindex Syndicated 2008-05-09 18:03:12 from journal/notes On reading books). Syndicated 2008-05-09 19:21:19 from Dave Jones recollection of stuff that happened. Syndicated 2008-05-09 15:25:11 from Matthew Garrett The GPL is like a green envelope German.” Syndicated 2008-05-09 10:24:46 from Mark J. Wielaard OpenSolaris update Well, it seems OpenSolaris.com fixed most of the issues I was bitching about. So, it now takes 2 clicks to get an OpenSolaris iso. I haven’t used it for too long but I figure I’d post this before someone inevitably points out how behind the times I am. These here tubes move fast! Other than that it seems an old version of X is being used as I experience nasty refresh shake at work. There was/is also an issue with the installation which would kick one back to a Grub prompt. This turns out to be faulty media from Lead Data Inc at least in this case. A freebsd iso worked fine, but I dumped the rest of the cd’s as Google juice reported other people having problems with said manufacturer. When I get sometime i’ll play around with OpenSolaris a bit more, seems like a solid effort was made to put together something usable. Syndicated 2008-05-10 08:27:17 from Christopher Warner Isaac Asimov's Foundation SeriesI'm getting really into reading second hand science fiction from the 1950s onwards. I read a few (but nowhere near all) of the Foundation series as a child, and I remember liking them a lot. Stolen from Wikipedia, here is a list of the books in The Foundation series in Asimov's suggested reading order: Syndicated 2008-05-11 11:39:00 (Updated 2008-05-12 02:04:48) from stillhq.com : Mikal, a geek from Canberra living in Silicon Valley I.) py --Chang Yu 2008-05-09: Great moments in probability<!-- start of entry 200805.) <!-- end of entry 200805/09 --> Syndicated 2008-05-07 18:22:52 from apenwarr - Business is Programming gnome-terminal titlesThis finally annoyed me enough to find a solution. Syndicated 2008-05-09 00:58:00 (Updated 2008-05-09 01:01:21) from John Levon Perl 6 Design Minutes for 07 May 2008<summary type="xhtml"> The Perl 6 design team met by phone on 07 May 2008. Larry, Allison, Patrick, Will, Jerry, Nicholas, Jesse, and chromatic attended. Allison: c: Allison: c: Patrick: c: Jesse: Larry: nofatrule Patrick: Jerry: Patrick: Jerry: c: Nicholas: stateimplementation of any language Jesse: Patrick: Jesse: Nicholas: Jesse: Will: Jerry: Patrick: Nicholas: Jerry: Jesse: Nicholas: Allison: Jesse: Allison: Will: Patrick: Allison: Will: Allison: Jerry: Patrick: Will: Patrick: Jerry: Patrick: Larry: Patrick: Larry: c: Will: Jesse: Syndicated 2008-05-08 22:42:28 from pudge May 9Office drinkies. Syndicated 2008-05-09 23:59:59 from Waider's Geek Diary More fresh Rockbox targets I!
http://www.advogato.org/recentlog.html
crawl-001
refinedweb
4,235
74.49
OK, lets see I am trying to use a ONE structure with multiple .cpp's (which I got to work just not the right way). I initialized my structure in my header file. I trying to find a way to save a value in a int or string from the structure and then be able to output the value of the struct variable in another .cpp... I search for about 2 hours on google and the boards themselves ( Im not to good at searching for stuff )... I did end up figuring out how to have 2 different values with the same name but not a way to have one with same name over the span of multiple .cpp's. any help is greatly appreciated (BELOW is a small sample program I made to try this ( it doesnt work the way I want tho )) This is my header This is one .cppThis is one .cppCode:#include <iostream> #include <windows.h> #include <fstream> using namespace std; void menu(); void load(); void newg(); int main(); struct test { int tst; }; test tet; This is my other .cppThis is my other .cppCode:#include "all.h" int main() { cout << "choose a value for tst" << endl; cin >> tet.tst; cin.get(); menu(); } and this is the error that I getand this is the error that I getCode:#include "all.h" void menu() { cout << "tst Value you chose" << tet.tst << endl; cin.get(); } Thanks again for any help you provideThanks again for any help you provideCode:.objs\main.o:main.cpp:(.bss+0x0): multiple definition of `tet'
https://cboard.cprogramming.com/cplusplus-programming/80408-structure-trouble.html
CC-MAIN-2017-17
refinedweb
259
82.54
Introduction. Due to these and several other reasons you will see below, Jupyter Notebooks are one of the! Are you ready to learn? Let’s begin! Table of Contents - What is a Jupyter Notebook? - How to Install Jupyter Notebook? - Getting Started! - Using the Magic Functions - Not just limited to Python – Use R, Julia and JavaScript within Notebooks - Interactive Dashboards in Jupyter Notebooks – why not? - Keyboard Shortcuts – Save time and become even more productive! - Useful Jupyter Notebook Extensions - Saving and Sharing your Notebook - JupyterLab – The evolution of Jupyter Notebooks - Best Practices and Tips. This allows the user to test a specific block of code in a project without having to execute the code from the start of the script. Many other IDE enviornments (like RStudio) also do this in several ways, but I have personally found Jupyter’s individual cells structure to be the best of the lot. As you will see in this article, these Notebooks are incredibly flexible, interactive and powerful tools in the hands of a data scientist. They even allow you to run other languages besides Python, like R, SQL, etc. Since they are more interactive than an IDE platform, they are widely used to display codes in a more pedagogical manner. How to install Jupyter Notebook As you might have guessed by now, you need to have Python installed on your machine first. Either Python 2.7 or Python 3.3 (or greater) will do. Anaconda For new users, the general consensus is that you should use the Anaconda distribution to install both Python and the Jupyter notebook. Anaconda installs both these tools and includes quite a lot of packages commonly used in the data science and machine learning community. You can download the latest version of Anaconda from here. The pip method If, for some reason, you decide not to use Anaconda, then you need to ensure that your machine is running the latest pip version. How do you do that? If you have Python already installed, pip will already be there. To upgrade to the latest pip version, follow the below code: #Linux and OSX pip install -U pip setuptools #Windows python -m pip install -U pip setuptools Once pip is ready, you can go ahead and install Jupyter: #For Python2 pip install jupyter #For Python3 pip3 install jupyter You can view the official Jupyter installation documentation here. Getting Started! We’ve now learned all about what these notebooks are and how to go about setting them up on our own machines. Time to get the party started! To run your Jupyter notebook, simply type the below command and you’re good to go! jupyter notebook Once you do this, the Jupyter notebook will open up in your default web browser with the below URL: In some cases, it might not open up automatically. A URL will be generated in the terminal/command prompt with the token key. You will need to copy paste this entire URL, including the token key, into your browser when you are opening a Notebook. Once the Notebook is opened, you’ll see three tabs at the top: Files, Running and Clusters. Files basically lists all the files, Running shows you the terminals and notebooks you currently have open, and Clusters is provided by IPython parallel. To open a new Jupyter notebook, click on the ‘New’ option on the right-hand side of the page. Here, you get four options to choose from: - Python 3 - Text File - Folder - Terminal In a Text File, you are given a blank slate. Add whatever alphabets, words and numbers you wish. It basically works as a text editor (similar to the application on Ubuntu). You also get the option to choose a language (there are a plethora of them given to you) so you can write a script in that. You also have the ability to find and replace words in the file. In the Folder option, it does what the name suggests. You can create a new folder to put your documents in, rename it and delete it, whatever your requirement. The Terminal works exactly like the terminal on your Mac or Linux machine (cmd on Windows). It does a job of supporting terminal sessions within your web browser. Type python in this terminal and voila! Your python script is ready to be written. But in this article, we are going to focus on the notebook so we will select the Python 3 option from the ‘New’ option. You will get the below screen: You can then start things off by importing the most common Python libraries: pandas and numpy. In the menu just above the code, you have options to play around with the cells: add, edit, cut, move cells up and down, run the code in the cell, stop the code, save your work and restart the kernel. In the drop-down menu (shown above), you even have four options: - Code – This is self-explanatory; it is where you type your code - Markdown – This is where you type your text. You can add your conclusions after running a code, add comments, etc. - Raw NBConvert – It’s a command line tool to convert your notebook into another format (like HTML) - Heading – This is where you add Headings to separate sections and make your notebook look tidy and neat. This has now been converted into the Markdown option itself. Add a ‘##’ to ensure that whatever you type after that will be taken as a heading Using Jupyter Notebook’s Magic Functions The developers have inserted pre-defined magic functions that make your life easier and your work far more interactive. You can run the below command to see a list of these functions (note: the “%” is not needed usually because Automagic is usually turned on): %lsmagic You’ll see a lot of options listed and you might even recognise a few! Functions like %clear, %autosave, %debug and %mkdir are some you must have seen previously. Now, magic commands run in two ways: - Line-wise - Cell-wise As the name suggests, line-wise is when you want to execute a single command line while cell-wise is when you want to execute not just a line, but the entire block of code in the entire cell. In line-wise, all given commands must started with the % character while in cell-wise, all commands must begin with %%. Let’s look at the below example to get a better understanding: Line-wise: %time a = range(10) Cell-wise: %%timeit a = range (10) min(a) I suggest you run these commands and see the difference for yourself! Not just limited to Python – Use R, Julia and JavaScript within Notebooks And the magic doesn’t stop there. You can even use other languages in your Notebook, like R, Julia, JavaScript, etc. I personally love the ‘ggplot2’ package in R so using this for exploratory data analysis is a huge, huge bonus. To enable R in Jupyter, you will need the ‘IRKernel’ (dedicated kernel for R) which is available on GitHub. It’s a 8 step process and has been explained in detail, along with screenshots to guide you, here. If you are a Julia user, you can use that within Jupyter Notebooks too! Check out this comprehensive article which is focused on learning data science for a Julia user and includes a section on how to leverage it within the Jupyter environment. If you prefer working on JavaScript, I recommend using the ‘IJavascript’ kernel. Check out this GitHub repository which walks you through the steps required for installing this kernel on different OS. Note that you will need to have Node.js and npm installed before being able to use this. Interactive Dashboards in Jupyter Notebooks – Why not? Before you go about adding widgets, you need to import the widgets package: from ipywidgets import widgets The basic type of widgets are your typical text input, input-based, and buttons. See the below example, taken from Dominodatalab, on how an interactive widget looks like: You can check out a comprehensive guide to widgets here. Keyboard Shortcuts – Save time and become even more productive! Shortcuts are one of the best things about Jupyter Notebooks. When you want to run any code block, all you need to do is press Ctrl+Enter. There are a lot more keyboard shortcuts that Jupyter notebooks offer that save us a bunch of time. Below are a few shortcuts we hand picked that will be of immense use to you, when starting out. I highly recommend trying these out as you read them one by one. You won’t know how you lived without them! A Jupyter Notebook offers two different keyboard input modes – Command and Edit. Command mode binds the keyboard to notebook level commands and is indicated by a grey cell border with a blue left margin. Edit mode allows you to type text (or code) into the active cell and is indicated by a green cell border. Jump between command and edit mode using Esc and Enter, respectively. Try it out right now! Once you are in command mode (that is, you don’t have an active cell), you can try out the below shortcuts: - A will insert a new cell above the active cell, and B will insert one below the active cell - To delete a cell, press D twice in succession - To undo a deleted cell, press Z - Y turns the currently active cell into a code cell - Hold down Shift + the up or down arrow key to select multiple cells. While in multiple selection mode, pressing Shift + M will merge your selection - F will pop up the ‘Find and Replace’ menu When in edit mode (press Enter when in command mode to get into Edit mode), you will find the below shortcuts handy: - Ctrl + Home to go the start of the cell - Ctrl + S will save your progress - As mentioned, Ctrl + Enter will run your entire cell block - Alt + Enter will not only run your cell block, it also adds a new cell below - Ctrl + Shift + F opens the command palette To see the entire list of keyboard shortcuts, press ‘H’ in command mode or go to Help > Keyboard shortcuts. Keep checking this regularly as new shortcuts are added frequently.: pip install jupyter_contrib_nbextensions Step 2: Install the associated JavaScript and CSS files: jupyter contrib nbextension install --user Once you’re done with this, you’ll see a ‘Nbextensions’ tab on the top of your Jupyter Notebook home. And voila! There are a collection of awesome extensions you can use for your projects. To enable an extension, just click on it to activate it. I have mentioned 4 extensions below that I have found most useful: - Code prettify: It reformats and beautifies the contents of code blocks. - Printview: This extension adds a toolbar button to call jupyter nbconvert for the current the notebook and optionally display the converted file in a new browser tab. - Scratchpad: This adds a scratchpad cell, which enables you to run your code without having to modify your Notebook. It’s a really handy extension to have when you want to experiment with your code but don’t want to do it on your live Notebook. - Table of Contents (2): This awesome extension collects all the headers in your Notebook and displays them in a floating window. These are just some of the extensions you have at your disposal. I highly recommend checking out their entire list and experimenting with them. Saving and Sharing your Notebook This is one of the most important and awesome features of a Jupyter Notebook. When I have to do a blog post and my code and comments are in a Jupyter file, I need to first convert them into another format. Remember these notebooks are in json format and that isn’t really helpful when it comes to sharing it. I can’t go about posting the different cells blocks in an email or on the blog, right? Go to the ‘Files’ menu and you’ll see a ‘Download As’ option there: You can save your Notebook in any of the 7 options provided. The most commonly used is either a .ipynb file so the other person can replicate your code on their machine or the .html one which opens as a web page (this comes in handy when you want to save the images embedded in the Notebook). You can also use the nbconvert option to manually convert your notebook into a different format like HTML or PDF. You can also use jupyterhub, which lets you host notebooks on it’s server and share it with multiple users. A lot of top notch research projects use this for collaboration. JupyterLab – The evolution of Jupyter Notebooks JupyterLab was launched in February this year and is considered the evolution of Jupyter Notebooks. It allows a more flexible and powerful way of working on projects, but with the same components that Jupyter notebooks have. The JupyterLab environment is exactly the same as a Jupyter Notebook, but with a more productive experience. JupyterLab enables you to arrange your work area with notebooks, terminals, text files and outputs – all in one window! You just have to drag and drop the cells where you want them. You can also edit popular file formats like Markdown, CSV and JSON with a live preview to see the changes happening in real time in the actual file. You can see the installation instructions here if you want to try it out on your machine. The long term aim of the developers is for JupyterLab to eventually replace Jupyter notebooks. But that point is still a bit further away right now. Best Practices While working alone on projects can be fun, most of the time you’ll find yourself working within a team. And in that situation, it’s very important to follow guidelines and best practices to ensure your code and Jupyter Notebooks are annotated properly so as to be consistent with your team members. Here I have listed down a few best practices pointers you should definitely follow while working on a Jupyter Notebook: - One of the most important things for any programmer – always ensure you properly add comments for your code! - Make sure you have the required documentation for your code - Consider a naming scheme and stick to it throughout your code to ensure consistency. This makes it easier for others to follow along - Whatever libraries you require for your code, import them at the start of your notebook (and add a comment next to them for what purpose you’re loading them) - Ensure proper line spacing in your code. You don’t want your loops and functions in the same line – that makes for a maddening experience when it has to be referenced later! - You’ll find sometimes that your file has become quite code heavy. Check out options on how to hide some of the code you deem not important for later reference. This can be invaluable to make your Notebook look tidier and cleaner - Check out this notebook on matplotlib to see how beautifully and neatly it can be represented Another bonus tip! When you think of creating a presentation, the first tools to come to mind are PowerPoint and Google Slides. Nut your Jupyter Notebooks can create slides too! Remember when I said it’s super flexible? I wasn’t exaggerating. To convert your Notebook into slides, go to ‘View’ -> ‘Cell Toolbar’ and click on ‘Slideshow’. Boom! Each block of code now displays a ‘Slide Type’ drop-down option on the right. You will get the below 5 options: Play around with each option to understand it better. It will change the way you present your code! End Notes Do note that this is not an exhaustive list of things you can do with your Jupyter notebook. There is so much more to it and you pick these things up the more you use it. The key, as with so many things, is experimenting with practice. Check out this GitHub repository which contains a collection of fascinating Jupyter Notebooks. This guide is just the starting point in your data science journey and I’m glad you are taking it with me! Let me know your take on Jupyter Notebooks and how they have helped you in the comments section below. Also, if you have any questions – let me know! Learn, train, compete, hack and get hired! You can also read this article on our Mobile APPYou can also read this article on our Mobile APP 17 Comments Wow such a wonderful article for a fresher Glad you found it useful, Kamal. 🙂 A great article. Many thanks. Thanks, Rahan! I am learning Python now…This article will help me a lot think so…Can you please share some articles regarding MI and AI as well Hi Thrilochan, All articles on Analytics Vidhya are machine learning focused. 🙂 Are you looking for any specific domain or technique? I can help you out with that. Hi Thrilochan, All the articles on Analytics Vidhya are machine learning focused. Are you looking for any specific domain or technique based articles? I can help you out with that. You can also check out the training platform to get started with your data science journey: Nice article. Data science is indeed an important subject to talk about. A great article. Many thanks. Great article. Thanks a lot This article is very useful for beginners those who want to do python in jupyter. Very useful commands , tips and more. thanks for this article pranav ..it really helps Innovative detailed information get.. thanks!!! I don’t get the Notebook Extensions! Any help ? Hi Amna, Were you able to install using the steps provided? I was not able to execute Step 7: install.packages(c(‘rzmq’,’repr’,’IRkernel’,’IRdisplay’), repos = ‘’, type = ‘source’). can you please suggest next steps. Error message: Warning: unable to access index for repository trib: cannot open URL ‘’ Warning message: packages ‘rzmq’, ‘repr’, ‘IRkernel’, ‘IRdisplay’ are not available (for R versio n 3.5.1) Hi Anupama, It seems the irkernel page has been updated hence that step as mentioned on the Discussion portal might not work. You can check out the irkernel page directly to see the installation instructions:
https://www.analyticsvidhya.com/blog/2018/05/starters-guide-jupyter-notebook/?utm_source=blog&utm_medium=pycaret-machine-learning-model-seconds
CC-MAIN-2020-40
refinedweb
3,051
69.82
Confession: every time I do a counter based problem, I end up with off by one errors, so much so that I have to go through at least three iterations to get it right. Generator functions used in part as counters are what got me through this. The script was a mess and the use of the yield statement inside a couple functions cleaned it up for me to the point where it only took one more iteration to get it right (I had spent a weekend and about six iterations prior to this). The main utility of the yield statement for me has three parts: 1) it "remembers" where it is and where it stopped within the generator between next() calls. 2) it "remembers" the values within itself (in this case a counter) between next() calls. 3) because of 1) and 2) it's harder (for me, at least) to corrupt values and state than it is by passing around a counter variable and applying += operator calls. The (somewhat convoluted) scenario: I'm working at a mine in Africa. The boss comes to me with a spreadsheet of about 500 items from various data sources and requests a database and a report that looks just like it and updates any time it's called. Difficult, but not impossible. I start on a schema for a database. Considering I'm a geologist, it's not all bad: Coworker comes by not long after and informs us that he is not keen on the idea of a custom database and that the problem should be done using SharePoint lists as lookup tables. MS SQL 2008 r2 SSRS (SQL Server Reporting Services) is what we and our mine software vendor use for reporting. I start to work on the SharePoint lists and hit a snag. SSRS in its current state can only operate on a single dataset when you're presenting information in a table. My main dataset in this case is the list of performance indicators or assays my boss asked for in the first place. That list is in a SharePoint list. Further, SSRS can only take one SharePoint list as a data source. In other words, to the best of my knowledge, you can not write a relational query across SharePoint lists in SSRS 2008 r2. My solution was to lookup values within my table in SSRS based on names or keys. It got ugly and string concatenation was involved, but, amazingly, it worked. The only real problem, apart from lousy performance, was the matching of shipment data from the mine based on mine levels as required in the spreadsheet. What I needed to do was create a separate record in the main KPI list for each KPI-pit-material(roughly economic character of the rock)-bench-subbench combination. There was a last column dealing with mining method, but for the time being I could get that from the subbench number. Anyway, 4 or 5 data sources requiring elevations, 4 (currently, there will be more) open pits, 5 KPI's, 9 or 10 materials, about 40 benches, 9 subbenches - it ends up being a lot of records (5 * 4 * 5 * 10 * 40 * 9 ~= 360,000). In the end I had about 350,000 records total. I actually started doing this by hand in an Excel spreadsheet. I got as far as replicating everything for the four pits and knew I would have to do the rest programmatically. Knowing what I know now, I would have done the whole thing programmatically. Live and learn. Shown below is the code (sorry about the plain look - I'm not with it with Syntax Highlighter and other tools yet). There are some naive constructs and hacks, but it works. Thanks for having a look. """ Deal with main list of KPI's in Jeff's reconciliation report. Deal with elevation, flitch, and mining method here. Assign key values (integers) to relevant columns. """ import csv import collections as colx import os import sys import pprint # ranges that require bench/flitch addition import benchranges as br # bench range file format: # # """ # Row ranges in <boss's> Excel spreadsheet # that require repetition for bench and flitch. # """ # # RANGES = ((36, 42), # (42, 48), # (48, 54), # (54, 60), # (60, 66), # (66, 72), # (72, 78), # (78, 84), # . # . # . # etc. DIRX = r'C:\MSPROJECTS\SiteTripJAN13\JeffDatabase\FirstAttemptWDatabase\LookupDataSetup' DIRCSV = r'C:\MSPROJECTS\SiteTripJAN13\JeffDatabase\FirstAttemptWDatabase\LookupDataSetup\loadtosharepoint\spreadsheetsforload\cvsdumps' CSV = '.csv' KPIFIELDS = ['KPIID', 'KPIOrder', 'AttributeDescription', 'Units', 'DataType', 'Source', 'ValueCalc', 'Period', 'Location', 'Pit', 'Level', 'MiningMethod'] NTKPIFIELDS = ','.join(KPIFIELDS) # account for extra level, flitch, and BHVermeer files CSVFILES = KPIFIELDS[2:] + ['Benches', 'BHVermeer', 'Flitches'] MAINFILE = 'kpiids' BIGNUMBER = 1000000 # OK, the only file that needs a named tuple is the KPI one. # The others all have two columns where we're trying to match # basic format of KPI lookup csv files (faux unit example): # # 1,Frobnostication unit # 2,Foo unit # 3,ounces # 4,gallons per minute # . # . # . # etc. # format of main input file: # # 1,1,Plant Harvest Salable Copper,Tonne Metal,Plant Actual,Mill Report,Value,Shift Day,Plant,Not Applicable,Not Applicable,Not Applicable # 2,2,Plant Contained Salable Cobalt,Tonne Metal,Plant Actual,Mill Report,Value,Shift Day,Plant,Not Applicable,Not Applicable,Not Applicable # 3,3,Mill Tonnage,Tonne Ore,Plant Actual,Mill Report,Value,Hour,Plant,Not Applicable,Not Applicable,Not Applicable # . # . # . # etc. # intended format of output file: # # 1,1,120,10,4,2,2,3,3,3,2,42,10,2,4 # 2,2,119,10,4,2,2,3,3,3,2,42,10,2,4 # 3,3,108,11,4,2,2,1,3,3,2,42,10,2,4 # . # . # . # etc. # have to add slots for pit, bench, flitch, mining method # 14 slots all integers # XXX - very much hard coded # 'KPIID', 'KPIOrder', 'AttributeDescription', 'Units' # 'DataType', 'Source', 'ValueCalc', 'Period' # 'Location', 'Pit', 'Level', Bench, Flitch' # 'MiningMethod', BHVermeer MAINFILELINEFMT = (11 * '{{{}}},').format(*[x for x in KPIFIELDS[:11]]) MAINFILELINEFMT += '{Bench},{Flitch},{MiningMethod},{BHVermeer}' KPIID = 'KPIID' KPIORDER = 'KPIOrder' PIT = 'Pit' BENCH = 'Bench' FLITCH = 'Flitch' BHVERMEER = 'BHVermeer' NA = 'Not Applicable' # specific for each item (1FEB2013) NABENCH = 42 NAFLITCH = 10 NABHVERMEER = 4 NAPIT = 3 EXCEL = 'excel' def makelookupdict(): """ Read the available csv files for the SharePoint lookup tables and make a corresponding dictionary of integer values corresponding to each value (string) key. Returns dictionary. """ os.chdir(DIRCSV) # make lookup table of values lookupdict = {} for filex in CSVFILES: f = open(filex + CSV, 'r') lookupdict[filex] = {} readerx = csv.reader(f, dialect = EXCEL) for linex in readerx: keyx = linex[1] lookupdict[filex][keyx] = linex[0] f.close() return lookupdict def newnum(): """ Generator function that will continuously increment an integer and yield the new value. """ x = 1 while 1: yield x x += 1 def initializerecord(recorddict, recordnt, lookupdict): """ Put corresponding integer lookup values for fields in dictionary. recorddict is an empty dictionary. recordnt is a named tuple of record values. lookupdict is a dictionary of lookup indices for the values in question. """ for namex in KPIFIELDS[2:]: # XXX - dictionary lookup is a bit hackish recorddict[namex] = lookupdict[namex][recordnt.__dict__[namex]] def dummyfieldsforkpi(recorddict, n): """ Fills in Not Applicable for fields in KPI that doesn't require them (bench, flitch, etc.) recorddict is the dictionary for the KPI in question. n is the KPI identifier and order number of original KPI file. """ recorddict[BENCH] = NABENCH recorddict[FLITCH] = NAFLITCH recorddict[BHVERMEER] = NABHVERMEER recorddict[KPIID] = n recorddict[KPIORDER] = n def dealwithbenchloop(n, counter, recorddicts, f2): """ Generator function. Fill in rows for benches and flitches for a given set of grouped KPI's. n is the current line number of the file being written to. counter is the generator for incrementing line numbers is the file being written to. recorddicts is the base list of grouped record dictionaries. f2 is the file being written to. Returns the position the line number counter for the new file. """ # loop through benches for benchx in range(1, 42): # loop through flitches, increment counter # 1-9 corresponds to flitch indices in original flitch list (1-9) for flitchx in range(1, 10): for recn in recorddicts: # newlineno will represent KPIID, KPIOrder, add to dict recn[KPIID] = n recn[KPIORDER] = n # match bench, flitch, bhvermeer with id's and add to dict recn[BENCH] = benchx recn[FLITCH] = flitchx if flitchx == 9: recn[BHVERMEER] = 1 else: recn[BHVERMEER] = 2 # write dictionary to file print(MAINFILELINEFMT.format(**recn), file = f2) n = next(counter) yield n def cyclethroughkpis(): """ Generator function that will cycle through a list of KPI (key performance indicator) records and write each one to a new file adding records for benches and flitches where appropriate. """ # get main file and assign lookup values os.chdir(DIRX) f = open(MAINFILE + CSV, 'r') f2 = open('kpilookups.csv', 'w') # named tuple for cycling through file recordx = colx.namedtuple('recordx', KPIFIELDS) # counter for new file x = newnum() # map object of records # want line number and named tuple records in an iterable ziplines = zip(range(1, BIGNUMBER), map(recordx._make, csv.reader(f, dialect = EXCEL))) # lookup dictionary lookupdict = makelookupdict() # multiple bench original file line index ranges benchidxs = (range(*z) for z in br.RANGES) # increment new file counter n = next(x) while 1: recorddict = {} try: zipnt = next(ziplines) except StopIteration: f.close() f2.close() initializerecord(recorddict, zipnt[1], lookupdict) # if this requires multiple repeated records for bench and flitch if int(recorddict[PIT]) != NAPIT: # list of grouped record dictionaries recorddicts = [recorddict] # get range of rows for grouped KPI's rowrange = next(benchidxs) # first item in rowrange already current for i in rowrange[1:]: zipnt = next(ziplines) recorddict = {} initializerecord(recorddict, zipnt[1], lookupdict) recorddicts.append(recorddict) r = dealwithbenchloop(n, x, recorddicts, f2) # track new file counter for w in r: yield w # track counter n = w yield n, zipnt[0], rowrange else: # make record complete dummyfieldsforkpi(recorddict, n) # write to file print(MAINFILELINEFMT.format(**recorddict), file = f2) # yield current file counter, original file counter, and row range yield n, zipnt[0], None n = next(x) if __name__ == '__main__': dorecords = cyclethroughkpis() while 1: try: print(next(dorecords)) except StopIteration: print('Finished run.') # XXX - a bit hackish sys.exit() f.close() f2.close() Equivalent to itertools.count (1)? @Bjørnar Yes and no. The incrementing is the same, but the idea of the object maintaining its state between calls, if I understand things correctly, is a generator or yield characteristic. There are two main yield calls in cyclethroughkpis(), one for the count in the file being written to, and one for the line number of the original file. This is the utility of the yield statement to me; it allows me to track a couple things at once without having to worry about it once it's set up. This is probably not the simplest approach to the problem, but it works for me. Thanks for having a look. CBT @Bjørnar I thought about this over breakfast and I now know what you were saying. The newnum() function is entirely unnecessary, and, if I'm not mistaken, so is range(1, BIGNUMBER) used elsewhere in the script. Next time I'll cut down on code and use itertools.count(1) like you suggested. I mentioned in the narrative that I probably had used some naive constructs. This is an example of one. This is a learning experience for me and I really appreciate you taking the time. CBT Thanks for the post, I will look forward to see more posts from your blog and Adpower Generators. Hi, very informative thanks for sharing. Generator Toowoomba
http://pyright.blogspot.com/2013/02/generators-used-as-counters.html
CC-MAIN-2015-22
refinedweb
1,903
61.36
Assistance Needed for a refresh of dynamic list item... As the title says, I have a dynamic list item on my sub menu, I actually have 2 of them. I have a car model type setup I am working on so you select the type of vehicle you want aka muscle, and the second list populates with all the hashes of that type. The issue I have is if I select muscle, the list loads, but then if I change it to sport, the list remains the same with all the muscle cars listed. So my second dynamic list is not updating when I have changed the first one of model. @xhiyikfkox It might help if you explained whether this is your own menu system, or an existing library. Not sure what you mean by that... I can say this though. I have been using NativeUI to make a modmenu, same one you helped me with before, but after getting the muscle car setup working I wanted to make a dynamic list setup. So the way it will work is dynaic list vehicleTypes gets all known vehicleclass's from the vehicleclass list, then fills it into the dynamic list ot vehicleTypes. When you select a type from that list I have dynamic list vehicleTypeHashes go and get all the vehicles of that type, ex vehicleTypes select muscle cehicleTyeHashes gets all the muscle car hashes. However if you then change the vehicleTypes to sports car, the vehicleTypeHashes dose not update with the new list. In otherwords its not refreshing. @xhiyikfkox It didn't say you were using NativeUI, so it wasn't clear if that's what you were using. I know we've discussed your code before, but for anyone who hasn't they would have no idea if that's what you were using. There are a lot of mods out there with menus that don't use it... that's why I mentioned it. As for the problem, now I know it's NativeUI, unless he has changed the code and released the updated version, you can't do what you want. I had to get the source code and make my own changes to make it do that, because the List<dynamic> isn't a property you can set, unless it's in the UIMenuListItem constructor. is there a way to remove it from the menu? if so I could just remove it and repost it to the menu after the change has been made. @xhiyikfkox I can't remember to be honest... It's possible. I use my own menu system now so I don't know for sure. I know a while back I was speaking to someone who needed the same thing and they did submit a pull request on GitHub to add the List<> access feature. I don't know if the available version has that code in it though. I suppose the problem with that is the item that is getting refreshed would always have to be the bottom item in the menu, as that's where it would get added back. List<dynamic> listOfVehicleTypes = new List<dynamic>(); VehicleClass[] allVehicleTypes = (VehicleClass[])Enum.GetValues(typeof(VehicleClass)); for(int i = 0; i < allVehicleTypes.Length; i++) { listOfVehicleTypes.Add(allVehicleTypes[i]); } UIMenuListItem types = new UIMenuListItem("Vehicle Types: ", listOfVehicleTypes, 0); submenu.AddItem(types); List<dynamic> listOfVehicleHashesType = new List<dynamic>(); VehicleHash[] allVehicleHashes = (VehicleHash[])Enum.GetValues(typeof(VehicleHash)); int x = 0; submenu.OnListChange += (sender, listItem, newIndex) => { if (listItem == types) { listOfVehicleHashesType = new List<dynamic>(); VehicleClass getter = allVehicleTypes[newIndex]; for (int i = 0; i < allVehicleHashes.Length; i++) { if (Function.Call<int>(Hash.GET_VEHICLE_CLASS_FROM_NAME, (int)allVehicleHashes[i]) == (int)getter) { listOfVehicleHashesType.Add(allVehicleHashes[i]); } if (listOfVehicleHashesType.Count == 0) UI.Notify("Nothing in the list"); else UI.Notify("List Count: " + listOfVehicleHashesType.Count); } vehicleTypes = new UIMenuListItem("Vehicle: ", listOfVehicleHashesType, 0); if(x == 0) { submenu.AddItem(vehicleTypes); x++; } } }; was trying to think how to describe the code but figured posting would be better. As you can see I only call the hashes and post to menu once you change the list on the first dynamic list. I have my second list, the hashes declared in the main class so its not having to be created over and over in this area. but I only add the second list after the first change, then each time after it just says the second list is new to over write it but it does not refresh in game is the issue. @xhiyikfkox You can't create a List<dynamic> pass it into the contructor of a UIMenuListItem and then change that original List<dynamic> and have it change on the menu. You would have to set the List<> property of that UIMenuListItem with a new List<dynamic> or update it by accessing it through the UIMenuListItem. And that's the thing you can't do, unless he has released the updated code. Think of it like this. In this code, if Y is changed after being assigned to Foo, myX inside Foo doesn't get updated. int Y = 10; Foo myFoo = new Foo(Y); Y = Y + 1; public class Foo { int myX; Public Foo(int x) { myX = x; } } Asked my Dad if he could check the code a moment and told him what I was trying to do... Like a min later this is his change: vehicleTypes = new UIMenuListItem("Vehicle: ", listOfVehicleHashesType, 0); if(x == 1) { submenu.RemoveItemAt(submenu.MenuItems.Count() - 1 ); } submenu.AddItem(vehicleTypes); x = 1; and all works now just as I was wanting it to. @xhiyikfkox Which as I said earlier, is fine if you know where the item is on the list, and it's at the end because List.AddItem adds it back onto the end. And if the menu currently has the last item selected, you could very well generate an index out of range error because you have reduced the number of items by one and possibly removed the item that was currently indexed. Brute force isn't always the solution, no matter how quickly that solution can be found. Not sure if its brute forcing it but I can say it works thus far. Even setup my code to gen the second button as the first vehicleclass type in the type array by default and only change when you change the type. Also just got the vehicle spawn mechanic wired into it too thus far all is working.
https://forums.gta5-mods.com/topic/7798/assistance-needed-for-a-refresh-of-dynamic-list-item
CC-MAIN-2018-13
refinedweb
1,065
63.29
Forward declarations. Our calculator can deal with symbolic variables. The user creates a variable by inventing a name for it and then using it in arithmetic operations. Every variable has to be initialized—assigned a value in an assignment expression—before it can be used in evaluating other expressions. To store the values of user defined variables our calculator will need some kind of "memory." We will create a class Store that contains a fixed number, size, of memory cells. Each cell can store a value of the type double. The cells are numbered from zero to size-1. Each cell can be in either of two states—uninitialized or initialized. enum { stNotInit, stInit }; The association between a symbolic name—a string—and the cell number is handled by the symbol table. For instance, when the user first introduces a given variable, say x, the string "x" is added to the symbol table and assigned an integer, say 3. From that point on, the value of the variable x will be stored in cell number 3 in the Store object. We would also like to pre-initialize the symbol table and the store with some useful constants like e (the base of natural logarithms) and pi (the ratio of the circumference of a circle to its diameter). We would like to do it in the constructor of Store, therefore we need to pass it a reference to the symbol table. Now here’s a little snag: We want to put the definition of the class Store in a separate header file, store.h. The definition of the class SymbolTable is in a different file, symtab.h. When the compiler is looking at the declaration of the constructor of Store Store (int size, SymbolTable & symTab); it has no idea what SymbolTable is. The simple-minded solution is to include the file symtab.h in store.h. There is nothing wrong with doing that, except for burdening the compiler with the processing of one more file whenever it is processing symtab.h or any file that includes it. In a really big project, with a lot of header files including one another, it might become a real headache. If you are using any type of dependency checker, it will assume that a change in symtab.h requires the recompilation of all the files that include it directly or indirectly. In particular, any file that includes store.h will have to be recompiled too. And all this unnecessary processing just because we wanted to let the compiler know that SymbolTable is a name of a class? Why don’t we just say that? Indeed, the syntax of such a forward declaration is: class SymbolTable; As long as we are only using pointers or references to SymbolTable, this will do. We don’t need to include symtab.h. On the other hand, a forward declaration would not be sufficient if we wanted to call any of the methods of SymbolTable (including the constructor or the destructor) or if we tried to embed or inherit from SymbolTable. class SymbolTable; // forward declaration class Store { public: Store (int size, SymbolTable & symTab); ~Store () { delete []_cell; delete []_status; } bool IsInit (int id) const { return (id < _size && _status [id] != stNotInit); } double Value (int id) const { assert (IsInit (id)); return _cell [id]; } void SetValue (int id, double val) { if (id < _size) { _cell [id] = val; _status [id] = stInit; } } private: int _size; double * _cell; unsigned char * _status; }; Store contains two arrays. The array of cells and the array of statuses (initialized/uninitialized). They are initialized in the constructor and deleted in the destructor. We also store the size of these arrays (it's used for error checking). The client of Store can check whether a given cell has been initialized, get the value stored there, as well as set (and initialize) this value. The constructor of Store is defined in the source file store.cpp. Since the constructor calls actual methods of the SymbolTable, the forward declaration of this class is no longer sufficient and we need to explicitly include the header symtab.h in store.cpp. Store::Store (int size, SymbolTable & symTab): _size (size) { _cell = new double [size]; _status = new unsigned char [size]; for (int i = 0; i < size; ++i) _status [i] = stNotInit; // add predefined constants // Note: if more needed, do a more general job cout << "e = " << exp(1) << endl; int id = symTab.ForceAdd ("e", 1); SetValue (id, exp (1)); cout << "pi = " << 2 * acos (0.0) << endl; id = symTab.ForceAdd ("pi", 2); SetValue (id, 2.0 * acos (0.0)); } We add the mapping of the string "e" of size 1 to the symbol table and then use the returned integer as a cell number in the call to SetValue. The same procedure is used to initialize the value of "pi."
http://www.relisoft.com/book/lang/project/7store.html
crawl-002
refinedweb
798
62.98
Using qdoc to document classes within a namespace Hello, I try to use qdoc to document a class which is within a namespace, and have the following problems: (just a preliminary remark: in my setup, everything works fine if I remove all the namespaces; I use qdoc in qt beta5 under osX). for example, I have a class Feature in a namespace xxx: @ namespace xxx { class Feature { ... } } @ I try to write a documentation for it: scenario 1: the class is a pure header class, thus I write a Feature.qdoc file, and add the following comment: @ /*! \class Feature ... */ @ I get the error Cannot find 'Feature' specified with '\class' in any header file if I add 'using namespace xxx;' in the first line of the .qdoc file, nothing changes. Now, instead of using a .qdoc file, I use a .cpp file. The error disappears if I add 'using namespace xxx;'; still, if I refer to the class using \l{Feature} somewhere else, I get the error: Can't create link to 'Feature' scenario 2: same as above, but I link to the class using \l{xxx::Feature}. When running qdoc, it does not complain, but using the documentation, and clicking on the link, it tries to open a file named xxx-feature.html, which qdoc did not create (it does not exist). scenario 3: I use \class xxx::Feature instead of \class Feature in the source file, but the xxx-feature.html does not get generated. I googled quite some time, and did not find any answer. Is there a solution ? the only one I found was to remove the namespace, or to replace it with a macro which I add to the Cpp.ignoretokens (but for some reasons, this is not a good solution in my case) what are the best practices to document code with namespaces ?? thanks, Dd - David Stiel Hi, It looks like the html output files (xxx-feature.html) are only generated if you describe the namespace (eg. in a separate .qdoc file): /*! \namespace publish bla bla bla */ On a side note documentation of properties (\property ) only works if the Q_PROPERTY(...) declarations comes before any Q_ENUMS(...) - sierdzio Moderators If you are not working on Qt itself, it's recommended to use Doxygen instead of qdoc. Just sayin' ;) - David Stiel Out of curiosity. Why do you recommended doxygen instead of qdoc. I was kind of intrigued by using the qdoc because it comes with Qt and can document Qt stuff like properties, signal, slots etc. But I’m sure you have your reasons… ;) - JKSH Moderators QDoc is an internal Qt tool. It's possible to use it for external projects, but I'm not sure if it was intended for this purpose. Doxygen, on the other hand, was specifically designed to be used by external projects. It "understands Qt features": like signals and slots. - sierdzio Moderators As JKSH said, plus: - qdoc does not guarantee it's API, it is being modified between Qt releases and can simply break without notice - doxygen supports just soo much more: aparat from C++ and Qt with all it's features (including QML), it also understands Java, JavaScript and many others. It also supports different comment styles, and can produce much more output formats than qdoc (HTML, PDF, man pages, LaTeX, etc.)
https://forum.qt.io/topic/20383/using-qdoc-to-document-classes-within-a-namespace
CC-MAIN-2018-39
refinedweb
549
71.55
I want my player to aim his gun at the cursor. To do this, I made an animation of him aiming from straight down to straight up on the animation scale of 0:00 to 1:00 (I am assuming that those are suppose to be seconds, but I am not really sure). I now want to set the time of the animation (how far along it is) so that he can go anywhere in the animation, depending on the cursor's location. I have the angle all figured out, and I know the time I want to set it to, but I can't figure out what time variable I can change that I can get to when using mechanum, and not having a list of animation components attacked to an object. This means I cannot use animation["animation name"].time=time, in case that was not clear. animation["animation name"].time=time I also cannot use animator.GetCurrentAnimatorStateInfo(1).normalizedTime=time; , because normalizedTime is read-only. animator.GetCurrentAnimatorStateInfo(1).normalizedTime=time; I am pretty sure what I am looking for is AnimationState.time, but for the life of me, I can't figure out how to get a reference to it when I only have a reference to the animator. AnimationState.time If I am doing this all wrong, what should I do to make my character be able to aim at the cursor? (other than set his transform by hand, of course) Thanks in advance! Finally, I would like to add that this is not a duplicate of either of the following because I cannot use animation["name"].time: animation["name"].time or Answer by chrisholdem · Oct 24, 2015 at 02:12 AM Chances are you've figured something out already, but this is for future viewers. There's no clear way to access AnimationState without having an Animation component on your object.The only alternative I've found is to use, if you cannot use legacy/deprecated options: Animator.Play("StateName", layer, normalizedTime); The trick is finding a way to turn whatever value you are using into a number between 0 and 1. In my case of using a timer that is finding what amount though the time bar you want to be, then dividing it by the total time. Hope this helps someone on their search. Thank you so much, I've been looking forever for a way to directly access an animation's "time" in code without needing to revert to legacy components. You've made my day :) Perfect, just what I was looking for! Answer by stuffkikker · Mar 26, 2018 at 09:35 AM For anyone looking for this as well; they've made this functionality a bit easier to access in the animator! There is a checkbox on your animation clip for 'normalized time' that uses any float variable you make in your animator as a time input. It's a more direct way to do what Chris Holdem provided a way for also. This was very useful info! Now I can use a very simple class which can be called with a unity event: public class SetAnimationClipProgress : MonoBehaviour { [SerializeField] private Animator _animator; public void SetAnimationProgress(float ratio) { _animator.SetFloat("progress", ratio); } } Answer by phaem · Jul 08, 2015 at 10:16 AM Try to use this for changing animation playback speed. It affects the current animation playing and all consequent animations so do not forget to return the value back to 1 when finished. I'm late to the party, but this is a completely terrible answer that completely circumvents and downplays the question he is actually posing. He is looking to access the AnimationState.time component because he is not simply changing the rate of animation play. AnimationState allows direct manipulation of animation states, eg where the animation is within the timeline. Absolutely everyone responds in the same exact way and there is 0 progress being made in finding the solution here since using Animation has become legacy/deprecated. Please do not respond generically to a specific question like this, it makes it look like there in an answer available when there isn. Animator idle minimal delay 0 Answers Mecanim CrossFade transition interruption issue 2 Answers Generic rigs out of sync 0 Answers How to get length of animation in Mecanim? 0 Answers Proper handling of animation events when setting normalised time 0 Answers
https://answers.unity.com/questions/1002400/how-do-i-set-the-time-of-an-animation-playing-in-t.html
CC-MAIN-2019-43
refinedweb
733
52.09
Everyone knows that loops in R are to be avoided, but vectorization is not always possible Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. It goes without saying that there are always many ways to solve a problem in R, but clearly some ways are better (for example, faster) than others. Recently, I found myself in a situation where I could not find a way to avoid using a loop, and I was immediately concerned, knowing that I would want this code to be flexible enough to run with a very large number of observations, possibly over many observations. Two tools immediately came to mind: data.table and Rcpp . This brief description explains the background of the simulation problem I was working on and walks through the evolution of ideas to address the problems I ran into when I tried to simulate a large number of inviduals. In particular, when I tried to simulate a very large number of individuals, say over 1 million, running the simulation over night wasn’t enough. Setting up the problem The task in question here is not the focus, but needs a little explanation to understand what is motivating the programming issue. I am conducting a series of simulations that involve generating an individual-level stochastic (Markov) process for any number of individuals. For the data generation, I am using the simstudy package developed to help facilitate simulated data. The functions defDataAdd and genData are both from simstudy. The first part of the simulation involves specifying the transition matrix P that determine a state I am calling status, and then defining the probability of an event that are based on a particular status level at a particular time point. For each individual, I generate 36 months of data and a status and event for each month. library(data.table) library(simstudy) set.seed(123) P <- matrix(c(0.985, 0.015, 0.000, 0.000, 0.000, 0.950, 0.050, 0.000, 0.000, 0.000, 0.850, 0.150, 0.000, 0.000, 0.000, 1.000), nrow = 4, byrow = TRUE) form <- "(status == 1) * 0.02 + (status == 2) * 0.10 + (status == 3) * 0.20" dtDef <- defDataAdd(varname = "event", formula = form, dist = "binary", link = "identity") N = 5000 did <- genData(N) In order to simulate the Markov process, I decided immediately that Rcpp would be most appropriate because I knew I could not avoid looping. Since each state of a Markov process depends on the state immediately preceding, states need to be generated sequentially, which means no obvious way to vectorize (if someone has figured that out, let me know.) #include <RcppArmadilloExtensions/sample.h> // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; // [[Rcpp::export]] IntegerVector MCsim( unsigned int nMonths, NumericMatrix P, int startStatus, unsigned int startMonth ) { IntegerVector sim( nMonths ); IntegerVector m( P.ncol()); NumericVector currentP; IntegerVector newstate; unsigned int q = P.ncol(); m = Rcpp::seq(1, q); sim[startMonth - 1] = startStatus; for (unsigned int i = startMonth; i < nMonths; i++) { newstate = RcppArmadillo::sample(m, 1, TRUE, P.row(sim(i-1) - 1)); sim(i) = newstate(0); } return sim; } The process is simulated for each individual using the Rcpp function MCsim, but is done in the context of a data.table statement. The key here is that each individual is processed separately through the keyby = id statement. This obviates the requirement to loop through individuals even though I still need to loop within individuals for the stochastic process. This algorithm is quite fast, even with very large numbers of individuals and large numbers of observations (in this case months) per individual. dt <- did[, .(status = MCsim(36, P, 1, 1)), keyby = id] dt[, month := 1 : .N, keyby = id] dt <- addColumns(dtDefs = dtDef, dtOld = dt) dt ## id status month event ## 1: 1 1 1 0 ## 2: 1 1 2 0 ## 3: 1 1 3 0 ## 4: 1 1 4 0 ## 5: 1 1 5 0 ## --- ## 179996: 5000 4 32 0 ## 179997: 5000 4 33 0 ## 179998: 5000 4 34 0 ## 179999: 5000 4 35 0 ## 180000: 5000 4 36 0 This is where things begin to slow down It is the next phase of the simulation that started to cause me problems. For the simulation, I need to assign individuals to a group or cohort which is defined by a month and is based on several factors: (1) whether an event occurred in that month, (2) whether the status of that individual in that month exceeded a value of 1, and (3) whether or not the individual experienced 2 or more events in the prior 12 months. An indivdual might be eligible for more than one cohort, but will be assigned to the first possible cohort (i.e. the earliest month where all three criteria are met.) Again, the specifics of the simulation are not important here. What is important, is the notion that the problem requires looking through individual data sequentially, something R is generally not so good at when the sequences get particularly long, and they must be repeated a large number of times. My first, naïve, approach was to create an R function that loops through all the individuals and loops within each individual until a cohort is found: rAssignCohortID <- function(id, month, status, event, nInds, startMonth, thresholdNum) { cohort <- rep(0, length(id)); for (j in (1 : nInds)) { idMonth = month[id == j]; idEvent = event[id == j]; idStatus = status[id == j]; endMonth = length(idMonth); done = FALSE; i = max(startMonth - idMonth[1], 13); while (i <= endMonth && !done) { if (idEvent[i] == 1 && idStatus[i] > 1) { begin = i-12; end = i-1; sumED = sum(idEvent[begin:end]); if (sumED >= thresholdNum) { cohort[id == j] <- i - 1 + month[1]; done = TRUE; } } i = i + 1; } } return(cohort); } Working through possible solutions system.time(dt[, cohort1 := rAssignCohortID(id, month, status, event, nInds = N, startMonth = 13, thresholdNum = 2)]) ## user system elapsed ## 12.555 0.180 13.256 The naïve approach works, but can we do better? I thought Rcpp might be a solution, because we know that loops in C++ are much more efficient. However, things did not turn out so well after I translated the function into C++; in fact, they got a little worse. #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] IntegerVector cAssignCohortID( IntegerVector id, IntegerVector month, IntegerVector status, IntegerVector event, int nInds, int startMonth, int thresholdNum) { IntegerVector cohort(id.length(), 0); IntegerVector idMonth; IntegerVector idEvent; IntegerVector idStatus; for (int j = 0; j < nInds; j++) { idMonth = month[id == j+1]; idEvent = event[id == j+1]; idStatus = status[id == j+1]; int endMonth = idMonth.length(); int sumED; bool done = FALSE; int i = std::max(startMonth - idMonth(0), 12); int begin; int end; while (i < endMonth && !done) { if (idEvent(i) == 1 && idStatus(i) > 1) { begin = i-12; end = i-1; sumED = sum(idEvent[Rcpp::seq(begin, end)]); if (sumED >= thresholdNum) { cohort[id == j + 1] = i + month(0); done = TRUE; } } i += 1; } } return(cohort); } system.time(dt[, cohort2 := cAssignCohortID(id, month, status, event, nInds = N, startMonth = 13, thresholdNum = 2)]) ## user system elapsed ## 12.405 0.140 12.886 I know that the function cAssignCohortID bogs down not in the loop, but in each phase where I need to subset the data set to work on a single id. For example, I need to execute the statement idMonth = month[id == j+1] for each id, and this apparently uses a lot of resources. I tried variations on this theme, alternatives to subset the data set within the Rcpp function, but could get no improvements. But a light bulb went off in my head (dim as it might be), telling me that this is one of the many things data.table is particularly good at. In fact, I used this trick earlier in generating the stochastic process data. So, rather than subsetting the data within the function, I created a regular R function that handles only a single individual id at a time, and let data.table do the hard work of splitting up the data set to process by individual. As you can see, things got markedly faster. rAssignCohort <- function(id, month, status, event, nInds, startMonth, thresholdNum) { cohort <- 0 endMonth = length(month); done = FALSE; i = max(startMonth - month[1], 13); while (i <= endMonth && !done) { if (event[i] == 1 && status[i] > 1) { begin = i-12; end = i-1; sumED = sum(event[begin:end]); if (sumED >= thresholdNum) { cohort <- i - 1 + month[1]; done = TRUE; } } i = i + 1; } return(cohort) } system.time(dt[, cohort3 := rAssignCohort(id, month, status, event, nInds = N, startMonth = 13, thresholdNum = 2), keyby=id]) ## user system elapsed ## 0.150 0.009 0.171 Finally, it occurred to me that an Rcpp function that is not required to subset the data might offer more yet improvements in speed. So, for the last iteration, I combined the strengths of looping in Rcpp with the strengths of subsetting in data.table to create a formidable combination. (Even when sample sizes exceed 1 million, the data are generated in a flash.) #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] int cAssignCohort( IntegerVector month, IntegerVector status, IntegerVector event, int startMonth, int thresholdNum) { int endMonth = month.length(); int sumED; int cohort = 0; bool done = FALSE; int i = std::max(startMonth - month(0), 12); int begin; int end; while (i < endMonth && !done) { if (event(i) == 1 && status(i) > 1) { begin = i-12; end = i-1; sumED = sum(event[Rcpp::seq(begin, end)]); if (sumED >= thresholdNum) { cohort = i + month(0); done = TRUE; } } i += 1; } return(cohort); } system.time(dt[, cohort4 := cAssignCohort(month, status, event, startMonth=13, thresholdNum = 2), keyby=id]) ## user system elapsed ## 0.029 0.004 0.035 For a more robust comparison, let’s use the benchmark function in package rbenchmark, and you can see how well data.table performs and how much Rcpp can add when used efficiently. library(rbenchmark) benchmark( dt[, cohort1 := rAssignCohortID(id, month, status, event, # Naïve approach nInds = N, startMonth = 13, thresholdNum = 2)], dt[, cohort2 := cAssignCohortID(id, month, status, event, # Rcpp approach nInds = N, startMonth = 13, thresholdNum = 2)], dt[, cohort3 := rAssignCohort(id, month, status, event, # data.table approach nInds = N, startMonth = 13, thresholdNum = 2), keyby=id], dt[, cohort4 := cAssignCohort(month, status, event, # combined data.table/Rcpp startMonth=13, thresholdNum = 2), keyby=id], replications = 5, columns = c("replications", "elapsed", "relative")) ## replications elapsed relative ## 1 5 52.578 395.323 ## 2 5 66.528 500.211 ## 3 5 0.752 5.654 ## 4 5 0.133 1.000 Postscript I shared all of this with the incredibly helpful folks who have created data.table, and they offered a data.table only solution that avoids all looping, which I will share here for completeness. While it is an improvement over the third approach presented above (R function with data.table statment keyby), it is still no match for the fastest solution. (But, this all just goes to show you there will always be new approaches to consider, and I don’t claim to have come any where near to trying them all out.) dtfunc <- function(dx) { dx[, prev12 := Reduce(`+`, shift(event, 1:12)), by=id] map <- CJ(id=1:N, start=13L, end=36L, event=1L, statusx=1L, prev12x=1L) ans <- dx[map, on=.(id, event, status > statusx, prev12 > prev12x, month >= start, month <= end), .I, allow=TRUE, by=.EACHI, nomatch=0L][, .(id, I)] minans <- ans[, .(I=min(I)), by=id] dx <- dx[, cohort5 := 0L][minans, cohort5 := min(month) - 1L + dx$month[I], on="id", by=.EACHI] return(dx) } system.time(dtfunc(dt)) ## user system elapsed ## 0.195 0.011 0.210 And here is a more complete comparison of the fastest version with this additional approach: benchmark( dt[, cohort6 := cAssignCohort(month, status, event, # combined data.table/Rcpp startMonth=13, thresholdNum = 2), keyby=id], dt2 <- dtfunc(dt), replications = 5, columns = c("replications", "elapsed", "relative")) ## replications elapsed relative ## 1 5 0.112 1.000 ## 2 5 0.899 8.0.
https://www.r-bloggers.com/2017/05/everyone-knows-that-loops-in-r-are-to-be-avoided-but-vectorization-is-not-always-possible-2/
CC-MAIN-2021-04
refinedweb
1,969
51.89
Code Splitting!! Quite a buzzword in web development nowadays. Today, we will explore code splitting and see how can we do it super easily with parcel. What is Code Splitting? If you are already familiar with it… you may skip this part, others, ride along… If you have done frontend web development with any JavaScript framework, you have surely packed all of your modules into one big bundle JavaScript file, which you attach to your webpage and do amazing stuff. But hey, those bundles are quite big! You have written your awesome(and complicated) web app, with so many parts… they ought to produce big bundles; and bigger the things, longer it takes to download them on slow networks. Ask yourself the question, does the user need all of it at once? Imagine it’s an e-commerce single page app. The user logs in to see the product listing, he may have come just to check out the products, but he has already spent a lot of time and data not just to download the JavaScript to render the product listing, but also the JavaScript to render about, filters, product detail, offers… and so on and so forth. By doing this we are doing the users injustice!! Wont it be awesome, if we could give the users what they need,only when they need it?. So, this idea of splitting your large bundle into multiple smaller bundles is called code splitting. These smaller bundles are loaded on demand and asynchronously. It surely sounds tough to do, but modern bundlers like Webpack make it quite easy, and parcel takes this easiness to whole another level. So, what is this new Parcel thing?? Blazing fast, zero configuration web application bundler It makes module bundling really very easy!! If you haven’t heard about it, I recommend this article by Indrek Lasn. Let’s get Splitting! To the coding part… I wont use any framework here(which you normally would), but framework or no framework, the process would remain the same. This example would have really really simple code to demonstrate the process. Create a new empty directory, and init a project, by npm init Or, yarn init Start it with whatever your favorite is(yarn in my case 😉) and create the files like show below. The idea is, we will only include the contents of index.js in our index.html and on an event(it will be a button click in this case) we will load someModule.js and render some content with it. Open index.html and add the following code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http- <title>Code Splitting like Humans</title> </head> <body> <button id="bt">Click</button> <div class="holder"></div> <script src="./index.js"></script> </body> </html> Nothing special, just basic HTML boiler plate, with a button and a div where we will render the content from someModule.js So, lets write the code for the module someModule console.log("someModule.js loaded"); module.exports = { render : function(element){ element.innerHTML = "You clicked a button"; } } We are exporting an object, which has a function render which takes in an element and sets its inner HTML to “You clicked a button”. Now, comes the magic. In our index.js file we have to handle the button click event and dynamically load someModule For the dynamic asynchronous loading we will use the import() function syntax. This function loads a module on demand and asynchronously. Look at the usage, import('./path/to/module').then(function(page){ //Do Something }); As import is asynchronous it returns a promise which we handle with then. In then we pass a function which accepts the object loaded from the module. It is similar to const page = require('./path/to/module');, only done dynamically and asynchronously. In our case, import('./someModule').then(function (page) { page.render(document.querySelector(".holder")); }); We load someModule and call its render function. Lets add it up inside a button’s click event listener. console.log("index.js loaded"); window.onload = function(){ document.querySelector("#bt").addEventListener('click',function(evt){ console.log("Button Clicked"); import('./someModule').then(function (page) { page.render(document.querySelector(".holder")); }); }); } Now that the code is all written, let’s run parcel. Parcel will automatically handle all the configuration work! parcel index.html It produces, the following files. Run it in your browser and observe. Notice in the console output, someModule is loaded only after the button click. In the network tab see how the module is loaded by codesplit-parcel.js after import function call. Code Splitting is something awesome, and if it can be done so easily, there is no reason we should step back from it. 💞💞 Click to see my Youtube channel!!🤓🤓 I need your love there Please hit some claps 👏 if you like the content, your support keeps me going. ❤❤
https://hackernoon.com/code-splitting-with-parcel-web-app-bundler-fe06cc3a20da
CC-MAIN-2019-39
refinedweb
811
67.25
Introduction This is a series of posts about AngularJS and our experiences with it while migrating the client of a complex enterprise application from Silverlight to HTML5/CSS/JavaScript using AngularJS as a framework. Since the migration is a very ambitious undertaken I want to try to chop the overall problem space in much smaller pieces that can be swallowed and digested much more easily by any member of my team. So far I have published the following posts in this series - Sometimes we.). Values In our application we frequently need access to different properties of the currently logged in user. This could be things like the full name of the user, it’s role and so on. Typically we would load this data after the user has successfully logged into the system and keep this data around as long as the user remains logged in. We can define any string, number, date-time, array or object as a value. We can even register a function as a value. To e.g. define a string value as a value service we use this code On line 1 I define my Angular application (module). On line 3 I register a value appTitle with the value “My Angular Application”. If we now want to use this value say in a controller TestCtrl we can do so Angular interferes which service to inject by looking at the name of the parameter. Thus our function parameter has to be named the same way as the registered value. We will discuss dependency injection (DI) and how it is realized in Angular in a future post. As mentioned above, we can also e.g. register an object as value service. The above code defines and initializes a value service called user and assigns it an object with some default values. We can now load the true values e.g. after a successful login of the user. I just quickly put together some pseudo code for this scenario (do not use this in production ) The above code is assuming that the user entered a user name and a password, selected the local and the connection (in our application a user can connect to different sites which we distinguish via unique connection names). The user then clicks on a login button which triggers the execution of the above login function. The data the user has entered is posted to the backend and assuming the user can be authenticated the server will respond with a success status and send back the user data. Note: Make sure that you never overwrite the value service/object as a whole otherwise your assignment is lost. Always reassign the property values of the value object. The following assignment is wrong and does not lead to the expected behavior even if the layout of the response matches the user value object exactly. We have to do a mapping property by property, i.e. Constants The difference between a value and a constant service is that the former can only be injected (and thus be used) in a service or a controller while the latter can also be injected into a module configuration function.. (I will discuss the module configuration function in a future post). Summary Angular value and constant services are an ideal way to provide application wide access to shared data without having to pollute the global namespace. They can be injected similar to any other service into our controllers and services. The only real difference between a value and a constant is that the latter can be injected into a module configuration function while the former cannot. Post Footer automatically generated by Add Post Footer Plugin for wordpress.
http://lostechies.com/gabrielschenker/2014/01/14/angularjspart-9-values-and-constants/
CC-MAIN-2014-41
refinedweb
616
51.58
iLoaderContext Struct Reference This interface gives the context for the loader. More... #include <imap/ldrctxt.h> Detailed Description This interface gives the context for the loader. It basically gives loading plugins a way to find materials, meshes, and sectors. In all these cases region-qualified names can be used (i.e. 'regionname/objectname') or normal object names. WARNING! When a context is created it should not be modified afterwards. Some loader plugins will keep a reference to the context when they support delayed loading. In that case they still need the original contents in the context. So a loader that creates a context should create a new one every time. Definition at line 56. Find a material. If not found, try to use the filename supplied to find a matching texture. If that isn't found, try to load the texture using the filename. If loaded then it is also Prepared. Find a mesh factory. Find a mesh object. Same as FindMaterial but there is no assumption that the name and the filename are the same. This is useful if the filename has /'s in it (a pathname), since region searching will mean that names with /'s will never be found correctly. Find a texture with the given name. If not found, attempt to load the supplied filename and prepare the texture using the supplied name. Find a sector. Find a shader. -. Handle a comment node for a given object. If the engine saveable flag is on then an iObjectComment is created and add to the object. Otherwise nothing happens. This function returns true if a comment was added. False otherwise. If 'replace' is true then previously existing comments (if any) will be overwritten by the new comment. The documentation for this struct was generated from the following file: Generated for Crystal Space 2.1 by doxygen 1.6.1
http://crystalspace3d.org/docs/online/api/structiLoaderContext.html
CC-MAIN-2015-32
refinedweb
310
69.38
Hello, I have having some trouble with my code not working. In my book I am in the file i/o part so this is what the exercise is on. My program is one where the user can: 1) make a record in the categories model, make, year, and mileage, 2) read a record for those same categories 3)exit I have two different functions for the writing and the reading. My problem is that when the user enters to write or read a file the program immediately skips the line that allows the user to type in a file and skips to "the file could not be open" My only clue to what the problem might be is that I use getline and cin in the same program, which I have heard can cause problems. Your help would be much appreciated, styles Below is the code: Code: #include <iostream> #include <fstream> using namespace std; int get_int(int default_value); void write_bin(); void read_bin(); char model[21]; char make[21]; char year [6]; int main() { while (1) { int choice; cout << "Welcome to the car file system" << endl; cout << "******************************" << endl; cout << "Press 1 to write a record." << endl; cout << "Press 2 to read a record." << endl; cout << "Press 3 to exit." << endl; cin >> choice; if (choice == 1) { write_bin(); } if (choice == 2) { read_bin(); } if (choice == 3){ system("PAUSE"); return 0; } } } void write_bin() { char filename[81]; int n; int mileage; int recsize = sizeof(model) + sizeof(make) + sizeof(year) + sizeof(int); cout << "Enter file name: "; cin.getline(filename, 80); // Open file for binary read and write. fstream fbin(filename, ios::binary | ios::in | ios::out); if (!fbin) { cout << "Could not open file " << filename; } // Get record number to write to. while (1) { cout << "Enter file record number: "; n = get_int(0); if (n == -1) { break; } // Get data from end user. cout << "Enter model: "; cin.getline(model, 20); cout << "Enter make: "; cin.getline(make, 20); cout << "Enter year: "; cin.getline(year, 5); cout << "Enter mileage: "; mileage = get_int(0); // Write data to the file. fbin.seekp(n * recsize); fbin.write(model, 20); fbin.write(make, 20); fbin.write(year, 5); fbin.write(reinterpret_cast<char*>(&mileage), sizeof(int)); fbin.close(); } } void read_bin() { char filename[81]; int n; int mileage; int recsize = sizeof(model) + sizeof(make) + sizeof(year) + sizeof(int); cout << "Enter file name: "; cin.getline(filename, 80); // Open file for binary read-write access. fstream fbin(filename, ios::binary | ios::in | ios::out); if (!fbin) { cout << "Could not open file " << filename; } while(1) { // Get record number and go to record. cout << "Enter file record number (-1 to quit): "; n = get_int(-1); if (n == -1) break; fbin.seekp(n * recsize); // Read data from the file. fbin.read(model, 20); fbin.read(make, 20); fbin.read(year, 5); fbin.read(reinterpret_cast<char*>(&mileage), sizeof(int)); // Display the data and close. cout << "The model is: " << model << endl; cout << "The make is: " << make << endl; cout << "The year is: " << year << endl; cout << "The mileage is: " << mileage << endl; } fbin.close(); } int get_int(int default_value) { char s[81]; cin.getline(s, 80); if (strlen(s) == 0) return default_value; return atoi(s); }
https://cboard.cprogramming.com/cplusplus-programming/87940-why-o-why-dosent-work-printable-thread.html
CC-MAIN-2017-30
refinedweb
514
75.2
file system. These two, the shell and the file system, are notorious sources of platform incompatibilities.. "collect" first. Implicit dependencies One cannot criticize the Make mechanism for implicit dependencies detection for a good reason: Make doesn't have such mechanism. In order to deal with requirements of large projects. After I tell people what is wrong with the Make tool, the next question is always the same: "if it is so awkward, then how comes that it. The tools in this category are not really alternatives. They are what people currently understand as Make (virtually nobody is using today the original BSD UNIX Make). I mention three tools in this category: GNU Make, Opus Make and NMake. They all share some compatibility with the format of the original Make from AT&T (Korn shell, graphviz, etc.) is built with it. NMake is open source itself. There is a commercial version from Lucent as well (). The AT&T style source distribution packages rely on NMake and their own configuration tool, iffe. This build system from AT&T is very the perforce SCM tool (). Perforce is commercial software but Jam is fully open-source. Despite some small issues with its syntax, Jam files are expressive enough for the Jam tool to come standard with a decent database of rules. Jam was so influent that it generated a set of clones (FTJam, Boost.Jam, Boost.Jam.v2). The most interesting is Boost.Jam () from the maintainers of the Boost C++ library. This one introduces quite some syntax extensions compared to the original tool. You can tell by those extensions that the authors were C++ programmers (for example, the scoping of variables looks like C++ namespaces). Boost.Jam is not the only or the first attempt to raise the level of the build description but, more than other Make evolutions, Boost.Jam focus on real build issues. For example, it provides canned variant builds, it provides dynamic loading library abstraction for Unix and MS Windows target platforms, it cares about testing the result of the build, etc. If you ever used Make for a real-life sized project, you had to provide such things by your own effort and you will immediately understand what savings this approach of Boost.Jam brings. Unfortunately, Jam doesn You may argue that my preference does not make a lot of sense. Indeed, both Cook and Jam (the original) rely on the GNU build system to get themselves built which in turn relies on GNU Make. So it is not a matter of preference, you'll have to have GNU Make. This gives me the opportunity to introduce a thorny issue: the bootstrapping. The question is how do you build when you don't have the build tool, in particular how do you build the build tool itself? One solution is to cross compile and then distribute binaries for the new platform. Another solution is to go back to shell scripts for the build description of the build tool itself (like Boost.Jam does). Or you can just rely on "good old GNU Make" like many self-proclaimed modern build tools a result of the build: a report, a compiled file, etc. A build system is a set of tools, including a build tool (by the way, a good build system will support several competing build tools). A build system may produce or adapt the build descriptions before they are used by the build tool. A build system may, individual checks for one feature. Hereafter, we will call these steps probes. How results of probes are represented differs from one tool to another but most of them have a caching mechanism in place so that you don't need to run a probe each time you need the result of that probe. Probes can have various granularities, can be independent or can be dependent on the result of other probes. Roughly speaking, the available set of probes is the way a configuration tool represents its knowledge about the platform (actually one central header file, to be included by the C source files). What makes GBS so successful? Certainly not the fact that it was the first attempt or the only attempt. Long before it, the IMake () tool introduced higher-level build descriptions. IMake comes from the C code base of the XWindows is the big deal? I can already use Make to build Make!". The big difference is that, in order to build Make with Make, a version of Make has to be installed on your build machine first. By contrast, you can build autoconf with GBS on a build machine where autoconf was never installed before. If GBS is so smart of the price it pays for its portability. For example, the probes of autoconf are encoded as M4 macros. M4 is a powerful text processor but its syntax is pretty low level and difficult. Difficult enough to make this a major obstacle for extending the reach of GBS. While platform are separate and very different in nature. In that case, automatic inspection of the build platform before the build will not get you very far. In the embedded world, some kind of database holding the characteristics of the different platforms, turns out better. The database is painful to maintain but is the only solution that works. Autoconf has lack of resources for migration. Many build tools evolved to provide some form of source configuration either as an add-on or as a part of the same tool. For example, Boost.Jam has its "feature normalization", SCons has its Configure, etc. I would like to mention here it generates header files that your C files are supposed to include). It does that by processing input files named feature test files. The feature test files are written in a specific language that is interpreted by iffe to generate header files. Because in one configuration process several headers are generated according to your decisions to group probes in feature test files, iffe met metaconfig and the dist package (). Metaconfig is a shell script compiler, older than autoconf, and the configuration tool it generates is called Configure. Unlike the one generated by autoconf, Configure is mainly an interactive tool. The probes used by metaconfig are called units. These units are shell code snippets. Metaconfig was probably the very first tool to do a decent job scanning the source for GBS, the main issue addressed by these tools is the portability of the build description. CMake and Qmake have a lot in common in their design and in their spirit. They are both open-source and they are both implemented in C++ (Qmake had a predecessor, tmake, implemented in Perl). They both support more than one build tool. Most notably, they support the classic Make as well as the Microsoft IDE. They the disadvantage of a more complex distribution of the tool (a set of files to distribute instead of a monolithic executable). Finally, like GBS, these two build systems share the disadvantages of the build tools they use. As already mentioned, that is mainly poor checking that results in high chances call this category "script based" build tools but it is not easy to find a name that will adequately describe them in two words. It is important to understand the new paradigm shift introduced by this category of tools. The approach taken by their authors says "Let's not invent a new syntax. We are not in the business of writing text parsers. Others already did that and they did it better then we will do it in a fraction of our time". They also say "Let's not write and maintain the portability layer for our build tool. Let us reuse some virtual machine already available". So these people focus on the build design and on build design related issues. This seems to me a sound choice when one aims to provide a better build tool. I will mention only two tools in this category: Ant and SCons. But has grown today into a mature build tool that can put to shame many of its competitors. One sign that a piece of software is mature and fulfills a real need is the number of new projects that are taking that software as a base. And there are many software projects based on much development efforts today. This gives an important head start to Ant in the race for the next Make. Like the original Make, Ant was the primary source of inspiration for a set of new build tools like Nant () and, more recently, MSBuild (). They don't aim at file compatibility for build descriptions but their spirit is the same: describe the build as a set of tasks to carry out, each task coded as an XML element. Of course, Ant is no silver bullet. Ant without extensions has a scalability problem. A lot of it comes from the choice of XML as a file format. XML is verbose. XML does not have a convenient way to include a file in another file (the XML Fragments standard is not really supported by XML parsers, XML entities includes work but have limitations, etc.). You need some kind of inclusion because you want to factor out common parts in several build descriptions. Of course, an application using XML files is free to add "include" semantics to one chosen XML element (and that is what Ant finally did with the "import" task in version 1.6). Also XML is not really a programming language. You may want to have the content of one XML element computed from sibling elements (computed strings occurs so often in build descriptions, see Make macros). Or you may want one element to be taken from the parent or the parent if not found at some place (what would correspond to variable scoping in programming languages). I say "you may want" but for projects of real-life size you will need that. Otherwise the build description grows very big and redundant. This is not a hard limitation; the Ant tool does give you the power to express whatever you want. It is just the fact that you have to go back and forth between a purely descriptive part of the build specification available (). SCons is my preferred tool in this category and also my preferred build tool overall. It comes preconfigured with a fair set of rules ("builders" in SCons parlance). Even more compelling, it can be extended in an easy and natural way. Unlike Ant, the build description and the extensions use the same syntax, in this case Python. SCons allows flexibility in the compromise the speed-critical parts to a native compiled code implementation (when the software is stable enough). From another perspective, despite the fact that Python has a clear syntax, some people perceive SCons as being too low level. It is perfectly possible for the release engineer to describe the build of a 50-developer project for several target platforms in only a few dozen lines of SCons code. The release engineer will find this a great time saver but the average developer will find that code cryptic, like shell code in the early UNIX days or worse. The developers will soon ask for easier ways to add new components to the build. SCM tools providing improved build tools, both commercial (Omake in IBM Rational ClearCase,) and open-source software (Vesta,). But comparing the build tools integrated with the SCM systems goes far out of the scope of this discussion. Another area we didn't touch is the automation and reporting of the build (CruiseControl () and Dart () as open source tools, VisualBuilder () and FinalBuilder () as MS Windows commercial software). Yet another area not discussed here is the acceleration of the build when parallel build machines are available (distcc and ccache () as open source tools, IncrediBuild () and ElectricCloud () as commercial software. Finally, there is one last area that we don't want to discuss here: the software distribution tools. Many tools today allow you to connect as a client to some software repository, download the software you want, download automatically other needed parts and install everything on your system while building locally parts that need building. Those systems include a build tool or act as a build tool when needed. They have to act as a configuration tool too. Also, they have to do some form of dependency tracking, much like build tools do. The best known is probably Ports of the BSD OS () and its followers like Gentoo Portage (). Take a look at the A-A-P tool web site () for a list of such systems.
https://bitbucket.org/scons/scons/wiki/FromMakeToScons
CC-MAIN-2018-43
refinedweb
2,113
71.24
Enumerates all IP addresses on all network adapters of the system. Project Description ifaddr is a small Python library that allows you to find all the IP addresses of the computer. It is tested on Linux, OS X, and Windows. This library is open source and released under the MIT License. You can install it with pip install ifaddr. It doesn’t need to compile anything, so there shouldn’t be any surprises. Even on Windows. Let’s get going! import ifaddr adapters = ifaddr.get_adapters() for adapter in adapters: print "IPs of network adapter " + adapter.nice_name for ip in adapter.ips: print " %s/%s" % (ip.ip, ip.network_prefix) This will print: IPs of network adapter H5321 gw Mobile Broadband Driver IP ('fe80::9:ebdf:30ab:39a3', 0L, 17L)/64 IP 169.254.57.163/16 IPs of network adapter Intel(R) Centrino(R) Advanced-N 6205 IP ('fe80::481f:3c9d:c3f6:93f8', 0L, 12L)/64 IP 192.168.0.51/24 IPs of network adapter Intel(R) 82579LM Gigabit Network Connection IP ('fe80::85cd:e07e:4f7a:6aa6', 0L, 11L)/64 IP 192.168.0.53/24 IPs of network adapter Software Loopback Interface 1 IP ('::1', 0L, 0L)/128 IP 127.0.0.1/8 You get both IPv4 and IPv6 addresses. The later complete with flowinfo and scope_id. Documentation The complete documentation (there isn’t much to document) can be found here: ifaddr Documentation. Bug Reports and other contributions This project is hosted here ifaddr github page. 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/ifaddr/0.1.0/
CC-MAIN-2018-17
refinedweb
269
69.68