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
Answered by: Can STL streams run concurrently ? Hello, (This is my first post on MSDN, so please feel free to move this post to a more appropriate place). Working on parallelizing my application I have come across with the issue that STL streams cannot be effectively used concurrently. This conclusion sounds too strong for me, so I decided to ask for a help and (hopefully) unveiling this assumption. Here are the details. I have dozens of thousands of container objects where each contains a char* buffer, and I want to parse them concurrently using std::istream and operator >>. This is simply to avoid reinventing a wheel (a string parser). Here is a code snippet: class DataContainer { public: ... /*! Reads integers from a buffer populated in the constructor. */ void Parse() const { //represent myBuf as STL stream std::strstreambuf aDataBuf (myBuf, mySize); std::istream aDataStream (&aDataBuf); //aDataStream.imbue (std::locale ("C")); int n = 0; aDataStream >> n; for ( int i = 0; i < n; i++) { int k; assert (aDataStream.good()); aDataStream >> k; } } private: char * myBuf; int mySize; }; There is an array of 20,000+ of such DataContainers and a loop where Parse() method is called on each. The code running concurrently executes about 2x-5x slower than one running sequentially !!! Analyzing the hotspots (using Intel Parallel Amplifier) I have found the root-cause as follows: It is connected with critical section used to protect a common locale object. operator >>() inside creates a basic_istream::sentry object on the stack. Its constructor calls (through another method) ios_base::locale() which returns a std::locale object (see syntax below). So its copy constructor is called which calls Incref() to increment a reference counter. Incrementing reference counter is surrounded by a critical section. As all streams have a pointer to a shared locale object then there is a high contention. locale ios_base::getloc( ) const; locale __CLR_OR_THIS_CALL getloc() const { // get locale return (*_Ploc); } Trying to set individual locale objects into each stream (if to remove comments on the line with imbue() above)does not help much though there is some minor performance improvement. Stepping with the debugger into STL code I see that strstreambuf and stream constructors still call Incref() for a global locale object, thereby still causing a high contention. Am I doing something wrong or is it a principal limitation of STL that the streams cannot be used concurrently ? Thank you very much in advance. Roman Question Answers - Ouch. Yup, they forgot that one. Hans Passant. - Thanks. Submitted as All replies - I think this was fixed in VS2008 SP1. The critical section was replaced by InterlockedIncrement(). Check the _MT_INCR() macro in <memory>. Hans Passant. - Marked as answer by Wesley Yao Monday, June 01, 2009 2:27 AM - Unmarked as answer by nobugzMVP, Moderator Tuesday, June 09, 2009 9:19 PM - Just installed VS2008 SP1 and found that ... the bug is still there ! Here is the code. File c:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\xlocale: 116 _CRTIMP2_PURE void __CLR_OR_THIS_CALL _Incref() 117 { // safely increment the reference count 118 _BEGIN_LOCK(_LOCK_LOCALE) 119 if (_Refs < (size_t)(-1)) 120 ++_Refs; 121 _END_LOCK() 122 } 123 124 _CRTIMP2_PURE facet *__CLR_OR_THIS_CALL _Decref() 125 { // safely decrement the reference count, return this when dead 126 _BEGIN_LOCK(_LOCK_LOCALE) 127 if (0 < _Refs && _Refs < (size_t)(-1)) 128 --_Refs; 129 return (_Refs == 0 ? this : 0); 130 _END_LOCK() 131 } (The code fully matches one in VS2005 SP1). The file xlocal is 80188 bytes and is dated March 10, 2007 (though the SP was in August 2008 and there are files in that directory dated July 29, 2008). So the question remains - is this a known bug and is it fixed ? Thank you. Roman - Ouch. Yup, they forgot that one. Hans Passant. - I just checked the xlocale version dated July 16, 2009 (file size 91653 bytes) and see the same code. Hans, could you escalate this to the development team or let me know who to do this ? I am concerned whether the fix can really make the Dev 10 release. It impacts the project I am working on making the respective code serial instead of parallel :-(. Thank you, Roman _CRTIMP2_PURE void __CLR_OR_THIS_CALL _Incref() { // safely increment the reference count _BEGIN_LOCK(_LOCK_LOCALE) if (_Refs < (size_t)(-1)) ++_Refs; _END_LOCK() } _CRTIMP2_PURE facet *__CLR_OR_THIS_CALL _Decref() { // safely decrement the reference count, return this when dead _BEGIN_LOCK(_LOCK_LOCALE) if (0 < _Refs && _Refs < (size_t)(-1)) --_Refs; return (_Refs == 0 ? this : 0); _END_LOCK() } - Thanks. Submitted as
https://social.msdn.microsoft.com/Forums/vstudio/en-US/b049dbda-c115-410b-b5d8-513f727baf4d/can-stl-streams-run-concurrently-?forum=vcgeneral
CC-MAIN-2015-11
refinedweb
729
63.49
On Wed, 2011-05-11 at 00:18 +0200, Linus Walleij wrote:> 2011/5/2 Joe Perches <joe@perches.com>:> > On Mon, 2011-05-02 at 21:16 +0200, Linus Walleij wrote:> >> From: Linus Walleij <linus.walleij@linaro.org>> >> diff --git a/drivers/pinmux/core.c b/drivers/pinmux/core.c> > Trivial comments follow> >> +static inline int pin_is_valid(int pin)> >> +{> >> + return ((unsigned)pin) < MACH_NR_PINS;> >> +}> > Couldn't pin just be declared unsigned or maybe u32?> No, because like in the GPIO subsystem you *may* want to send in invalid> pins, and those are identified by negative numbers.Then I think this is clearer and the compilershould produce the same code.static inline bool pin_is_valid(int pin){ return pin >= 0 && pin < MACH_NR_PINS;}cheers, Joe
https://lkml.org/lkml/2011/5/10/477
CC-MAIN-2016-44
refinedweb
122
57.87
Django Bindings has been deprecated. For more, see the Deprecation Notice. Django Bindings uses Django's URL mappings and Django views to direct URLs to the correct page templates in your Web Framework apps. When you create a new Web Framework app, a URL mapping and view are automatically created for the default Home page. And by default, the Web Framework automatically tries to redirect any URL in the form http://<localhost:port>/dj/your_app_name/template_name to the corresponding template in the app. So, you aren't required to modify or create a URL mapping or view for most templates you create. However, if you want to add your own logic or use custom variables in templates whose values are generated by Python code, creating a custom view and URL mapping is necessary. For example, you could write code that redirects to a template based on URL parameters or that passes a value to the template, so you would need to create your own URL mappings and views. The URL to each page in your Web Framework app is defined by adding a URL pattern to the urls.py file, which is a Python module that is located in your app's directory ($SPLUNK_HOME/etc/apps/your_app_name). The format of URL patterns is: urlpatterns = patterns('', url(URL 1, function_name 1, page_name 1), . . . url(URL n, function_name n, page_name n), ) The URL pattern contains these components: So for an app called "testapp", the Web Framework creates this URL for your app's Home page: urlpatterns = patterns('', url(r'^home/$', 'testapp.views.home', name='home'), ) According to this URL pattern: To add another page to your app called "startup" (for the URL http://<localhost:port>/dj/testapp/startup), with a view called "startup_view" and page name of "startup_page", you'd add the following line to the URL pattern: urlpatterns = patterns('', url(r'^home/$', 'testapp.views.home', name='home'), url(r'^startup/$', 'testapp.views.startup_view', name='startup_page'), ) For more about URL patterns, see URL Dispatcher on Django's website. A Django view is the Python function that is called according to a particular URL mapping for an app page (for example, the home page URL http://<localhost:port>/dj/mycoolapp/home is mapped to a Django view). Each Django view in your Web Framework app needs to be defined in the views.py file, which is a Python module that is located in your app's directory ($SPLUNK_HOME/etc/apps/your_app_name). The format of a typical Django view in the Web Framework is: @render_to('your_app_name:template_name.html') @login_required def view_name(request): # ...python code... return { parameters } This view includes two decorators: So for an app called "testapp", this Django view is created for the app's Home page: @render_to('testapp:home.html') @login_required def home(request): return { "message": "Hello World from testapp!", "app_name": "testapp" } The returned values are sent to the specified template, allowing a template to insert the variable using the {{ message }} or {{ app_name }} tags. This example sends a message and an app_name variable to the home.html template. You can also include code because the views.py is a Python module. Here's an example using a view called "startup_view". This Django view creates a today variable that contains the current date as a string, and sends it to the specified template, startup_template.html: import datetime ... @render_to('testapp:startup_template.html') @login_required def startup_view(request): now = datetime.datetime.now() today = now.strftime("%A, %b %d, %Y") return { "today": today } To interact with Splunk programmatically, use the Splunk SDK for Python. Here's an example that retrieves the collection of search jobs from your Splunk instance and returns the jobs collection object to the startup template: @render_to('testapp:startup_template.html') @login_required def startup_view(request): service = request.service jobs = service.jobs return { "jobs": jobs }
http://dev.splunk.com/view/webframework-djangobindings/SP-CAAAEM5
CC-MAIN-2018-30
refinedweb
629
55.84
Objectives - We keep on playing with DC motors and with the Adafruit Motor Shield V1. - We seek the Rover can find its route autonomously, avoiding obstacles. - We will see the foundations of autonomous movement. Bill of materials Some previous comments At first, this chapter was designed to set up a remote control system of our rover, but given that in this humble site we aspire to put the means so that whoever can learn to program and given that our brand new 4×4 wheel rover is on the way, I can’t help trying to build an autonomous control system. We mean, of course, to equip our Rover with some obstacle sensor so it can take decisions based on its readings, to see what happens. And what better than a sensor we already know from previous chapters: the ultrasonic distance sensor. In a previous tutorial we saw how to handle it and would be quite easy to attach it to our small 4×4 robot at the front side. Naturally we can complicate it as much as we want, using multiple distance, light or sound sensors. But for this first prototype, we will apply a basic rule of engineering: KISS, in short, Keep It Simple St***d . We will complicate our lives later. - An algorithm, just in case we have not talked about it before, is a standardized procedure for solving a specific problem. - In our case, the algorithm will simply turn to the left whenever the ultrasonic distance sensor detects an obstacle within a given distance, which is not a very sophisticated algorithm but we have to start somehow. Connecting the sensor We saw in a previous chapter how to connect the ultrasonic distance sensor to an Arduino UNO. On this occasion we are going to use an Arduino MEGA, because we need to have enough free pins to connect the Distance Sensor (2 pins) and leave room for the remote control ( 6 pins). - We could, of course, use an Arduino UNO, but a MEGA is more comfortable to use, because the Adafruit Motor Shield does not cover all the pins and, in addition, as we are going to load several libraries we are not sure wether the Arduino ONE will run out of memory. Just bear in mind that since the 5V pin is not available, because it is hidden by the Motor Shield, we used the pin 52 to power the ultrasonic distance sensor (as the ultrasonic sensor consumes almost nothing and a MEGA pin is able to drive it) and the GND, which is next to it. - This is a very interesting trick when you want to connect something that does not consume more than 20 mA, which is less than the maximum that an Arduino pin is able to source or sink, and sometimes it prevents us from doing odd things to get 5V. But make sure that you will not exceed this limit. We have chosen these pins for sheer lazyness but you can choose whichever you want, of course. Let’s include here a diagram of the pins which we have connected, so that you can use them without the need to modify the sketches. - Do not trust the drawing and pay attention to the names of the pins and the table of connections above. It’s not easy to burn it, but the cemeteries are full of optimists. In our case, we have fit the ultrasonic sensor into a 3D printered plastic holder (this, for example) and held it to the front of the robot using plastic tape. Let’s see the control sketch. An autonomous sketch for the 4×4 Rover As we have just assembled a simple distance sensor, this is all the information we can use and that is why the autonomous movement has to be based on the distance to the nearest obstacle. It is not the ideal situation but it will be useful as our first approach. So the idea is the following: As long as there is no obstacle at less than 30 centimeters, we move forward. If for whatever reason we have got into a problem without knowing how and the distance to an obstacle is less than, let’s say, 15 cm, we move backward. And if the obstacle is between 15 and 30 cm, we turn left. We apply a delay, after every movement, to make sure that the Rover is moving little by little. We will reuse the code of the previous chapter, in which we had already programmed the movements, and we will simply change the setup, according to the steps described above. We have to install the new_ping library, just in case you have not have installed before. Let’s take a look at the program: Prog_95_0. We start, as usual, including the libraries and some definitions: #include <NewPing.h> #include <AFMotor.h> #define TRIGGER_PIN 50 // Pin connected to the trigger pin. #define ECHO_PIN 48 // Pin connected to the echo pin. #define MAX_DISTANCE 200 The define statements, correspond to the pins we have chosen in the MEGA and the MAX_DISTANCE variable specifies the maximum value that the sonar library can return, it does not matter too much here. We now have to create an instance of a sonar object. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); And as for the setup, it’s simple. We define pin 52 as output and set it to HIGH to power the sonar. After that we put a small delay to make sure that the power is stable. void setup() { pinMode(52, OUTPUT) ; // We will use pin 52 as 5V VCC digitalWrite(52, HIGH) ; delay(50); // Just in case } As for the loop, we have to start by sending a pulse to measure the distance: unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS) int dist = uS / US_ROUNDTRIP_CM ; And now we can proceed to decide the movement according to the rules mentioned above: if (dist > 30) Fordward() ; else if ( dist < 15) { Reverse() ; delay(500); TurnLeft() ; delay(500); } else { TurnLeft() ; delay (400); } delay(250); The result is quite erratic and with a rather strange behavior, a quite robotic movement, in the worst sense. It also gets stuck without knowing very well why, but as a first approximation it may be worth. Enhancing the autonomous navigation To be a first test is not that bad. Surely we could imagine a little more sophisticated algorithm that improve the navigation. For example, we could imagine that the time the robot is turning depends on the distance to the detected obstacle: the closer it is, the more time it turns. Or perhaps the rotation direction could be random. - Although we would have to find some way to prevent it from turning once on each side to end up facing always the obstacle. Another way to improve decision making, would be to include more sensors and rely on them to make the rover turn. We could use a light sensor and move around always looking for the brightest point in the room. Imagine that we use two distance sensors slightly offset from the direction of movement. This way we could consider that if the one on the right, for example, detects an obstacle and the other sensor does not, the conclusion would be to turn to the left and vice versa. Using two ultrasonic sensors, we could make adaptative turns depending on the relative position of the obstacles. We leave the subject here, but if you are interested it would be very easy to think about how to improve the autonomous movement. I leave it as a pending task and if anyone comes up with any ingenious solution, share it with us. Summary - We keep on playing with the Adafruit Motor Shield V1. - We have seen a very basic algorithm to move the rover autonomously. - We have discussed some methods to enhance the movement.
http://prometec.org/a-4x4-autonomous-robot/
CC-MAIN-2019-13
refinedweb
1,317
66.47
Home -> Community -> Mailing Lists -> Oracle-L -> Export-Import Questions All, Our client needs to have a copy of their 9i production database onto another machine which has Oracle 8i installed. What they have already done is create a separate 8i database on another machine. Now is it possible to take an export of the 9i production database and import the data onto the test 8i database ?? Our client at the moment is not really concerned with the version of the test database. Also, can we use the Oracle 8i export utility to export a 9i database or vice versa ?? And if so, can we import the data of the 9i database onto a 8i database ?? Do we necessarily have to use the highest version of the export utility and the import utility ?? I shall be grateful for any help on this. Thanks, Samir Samir Sarkar Oracle DBA SchlumbergerSema Phone : +44 (0) 115 - 957 6028 EPABX : +44 (0) 115 - 957 6418 Ext. 76028 Fax : +44 (0) 115 - 957 6018 -- Please see the official ORACLE-L FAQ: -- Author: SARKAR, Samir INET: Samir.SARKAR_at_nottingham.sema.sl - 05:36:45 CDT Original text of this message
http://www.orafaq.com/maillist/oracle-l/2003/05/09/0878.htm
CC-MAIN-2014-15
refinedweb
192
62.98
This action might not be possible to undo. Are you sure you want to continue? 11/05/2012 text original Introduction to Financial Planning Part - 1 1. What are the common client characteristics for a high income earner? (a) Often debt laden for purchase of home (b) Very focused on post retirement income (c) Employed or self-employed. Taxation strategies more important (d) Starting to accumulate assets, often going into debt to achieve them 2. What is step two of the financial planning process? (a) Identification of financial problems (b) Goal setting (c) Preparation of written alternatives and recommendations (d) Data gathering 3.Which one of the following statements would be INAPPROPRIATE if included in a Statement of Advice for a client? (a) We expect that your investments will return at least 5% per annum on average over the next 5 years (b) Your investments will return at least 5% each year for the next 5 years (c) Investments in these asset classes have averaged 5% return each year. We would be expect that to continue for you (d) Investments in these asset classes returned 5% last year. We anticipate that this return will continue to be achieved over the long term 4. A data collection form should collect: (a) Both qualitative and quantitative information (b) Quantitative information only (c) Qualitative information only (d) Financial information only 5. Which of the following statements is INCORRECT? (a) Quantitative data is facts and figures (b) Qualitative data can be used to make inferences (c) A client's age is an example of qualitative data (d) All data can be divided into either quantitative or qualitative data 6. An example of QUALITATIVE data is: (a) Unit trust balance (b) Age (c) Preferred retirement date (d) Outstanding debts Financial Planning Academy 1 7. If a client has an investment time frame of six years, what is the planning horizon? (a) Intermediate (b) Medium-term (c) Long-term (d) Short-term 8. Clients often have concerns about what is involved in seeing a financial adviser. Raising and discussing those concerns with the clients before they raise them themselves can have many advantages. These advantages include: I. It encourages openness in the discussion between the client and the adviser II. It gives the client confidence in the adviser, since potentially negative issues are being freely raised III. It allows for a quicker interview, thus saving time for all parties IV. It allows the adviser to take control of the interview (a) I and II (b) I and IV (c) II and III (d) I, II and III 9. Which of the following asset classes can produce both income as well as growth? (a) Equities only (b) Property and equities (c) Property, equities, fixed interest, and cash (d) Property, equities, and fixed interest 10. With respect to 'risk/return trade off', what is generally traded away in order to achieve higher returns? (a) Lower investment returns (b) Asset allocation (c) Higher investment returns (d) Stability of income/growth 11. Which of the following is an example of liability risk? (a) Through your actions, causing injury to others, or damage or loss to others' property (b) Death (c) Loss or damage to one's own property (d) Loss of income over an extended period of time 12. Installing a car alarm is an example of: (a) Risk avoidance (b) Risk control (c) Risk transference (d) Risk retention Financial Planning Academy 2 13. Which of the following is NOT a key component of a will? (a) Financial adviser details (b) Revocation clause (c) Appointment of an executor (d) Residuary clause 14. What is an advantage of having a separate account for known bills? (a) It allows the client to keep all their income together. This will reduce the client's spending and ensure that the bills can always be paid (b) It allows the client to ensure that the 'bill account' always has enough money in it to cover recurring expenses (c) It ensures that the client has enough money to spend on discretionary items (d) It allows the client to keep tabs on all the income they are receiving 15. A fixed interest investment is distinguished by two factors. They are: (a) The term and the interest rate are both variable at the start of the investment (b) The term and the interest rate are both fixed at the start of the investment (c) The term is fixed at the start of the investment, but the interest rate is variable (d) The interest rate is fixed at the start of the investment, but the term is variable 16. Which of the following is a DISADVANTAGE of managed investments? (a) Poor liquidity (b) The need for active management (c) Lack of diversity (d) Loss of personal control over decision making 17. When is an investment said to be negatively geared? (a) When the investment income is less than the cost of the investment (b) When the investment income is greater than the cost of the investment (c) When the investment income is the same as the cost of the investment (d) When the investment income is negative 18. Why is retirement planning becoming increasingly important? (a) (b) (c) (d) Governments are less likely to want to support the elderly There are better medical treatments ensuring longevity Clients want to be able to afford expensive overseas holidays when they retire We are moving towards a self-funding retirement structure Financial Planning Academy 3 and recession (b) Recovery. The adviser might suggest that implementation of a recommendation be brought forward in order to take advantage of a rule before it changes (a) I. The adviser might suggest the client retain certain investments in light of changes to their tax treatment III. making it less attractive than it was previously (c) A new product has been introduced that is likely to be a better investment for clients (d) The fund's original management team has left and their replacement team is not as well respected. III and IV (d) II. Consequently. expansion. Determining your client's surplus income and how it can best be used is part of which step in the development of a comprehensive strategy? (a) Step 1 .What are the four phases of the business cycle? (a) Recovery. customers are leaving 21. An adviser is reviewing a client's situation. II.Confirm the client's current financial position and any financial concerns (c) Step 3 . contraction.Establish the client's goals (d) Step 4 . A QUALITATIVE reason for this might be: (a) The return on that asset class is lower than other asset classes. An investment product has experienced a loss of customers. Consequently. contraction.Check that information is complete (b) Step 2 . III and IV (b) I. The adviser might suggest that implementation of a recommendation be delayed in order to take advantage of a new rule IV. contraction. II and III (c) I. contraction. boom.Put in place recommendations to meet the client's desired future financial position Financial Planning Academy 4 . peak. and recession (d) Recovery. and depression (c) Recovery. and recession 22. What might be a practical benefit to the adviser of conducting legislative research? I. III and IV 20. investors are moving out of this product in search of better returns (b) The tax treatment of the product has changed. boom. The adviser might amend the investment strategy in light of an announced change to tax law II.19. 23. A client has had a long-term asset allocation of 70% growth, 30% defensive. She is looking to increase it to 80% growth, 20% defensive due to the strength of the market. Her adviser suggests she retain her existing allocation. This is an example of: (a) Risk profile allocation (b) Planned allocation (c) Strategic allocation (d) Tactical allocation 24. What strategy do advisers use to ensure that the client's long-term goals are met by directing investments into appropriate asset classes? (a) Risk profiling (b) Tactical allocations (c) Cash flow and budgeting (d) Asset allocation strategy 25. Which of the following best describes a master trust? (a) The investor is the owner of the underlying assets (b) A trustee owns the assets on behalf of the investor (c) The assets are owned by a syndicate (d) The assets are owned directly by the members of the trust 26. Which of the following is a benefit TO THE ADVISER of presenting advice in a written form? (a) It reduces the likelihood of being sued for wrongful advice since, if the advice was appropriate, there is a record of that advice (b) It allows the client to have something to which they can return if they become unsure of the strategy suggested (c) It ensures the adviser is presenting appropriate advice (d) It ensures that the licensee is aware of the advice that is going to be given to the client. If the licensee does not like the advice they can prevent it from being presented 27. In a Statement of Advice, how must fees, commissions and costs be presented? (a) (b) (c) (d) In both Fees and percentage amounts In fees only In percentage amounts only In either fees or percentage amounts Financial Planning Academy 5 28. Your clients appear to be happy with the advice presented to them as they are nodding as each part of the advice is explained. Is the nodding a potential problem and if so, what might you do to overcome it? (a) No, there is no problem with nodding as it shows that the client understands the advice being explained (b) Yes, the client might not understand the advice but doesn't want to show it by asking for clarification. Asking s of the client along the way and encouraging them to ask s will help reveal any lack of understanding (c) Yes, the client might be nodding so as to avoid showing any lack of understanding. Taking the initiative and re-explaining the advice is the best way to handle such a response (d) No, the client is nodding because they understand the advice. Once the advice has been fully presented, give the client time to let it sink in before asking the client to commit to proceeding with the advice 29. The IMPLEMENTATION of a Statement of Advice requires the co-ordination of a number of tasks. These could include: I. An action plan for determining who needs to do what (eg. applications submitted) II. II. Bringing in any specialist professionals as necessary (solicitors, general insurers etc) III. III. Retention of client files for later reference IV. IV. Contacting the client to determine a review date V. (a) I, II and III (b) II and III (c) I, II and IV (d) I, II, III and IV 30. Which of the following is an example of a macro level change that may affect a client's financial plan? (a) A change to marital status (b) An increase in annual living expenses (c) Changes to social security legislation (d) Loss of employment Financial Planning Academy 6 Part - 2 1) Money has time value. It derives this value due to existence of several conditions. Which one of the following is not one of the conditions contributing to the existence of this value? (a) The fees and commission sources of the firm (b) Possibility of increase in tax rates over time. (c) Ability to buy/ rent assets generating revenue (d) Cost of foregoing present consumptions 2) You have term deposits of Rs. 4,00,000 with a bank. In order to meet sudden requirements for liquidity and short-term credit, you are applying for an overdraft facility with the bank. What is the rate of interest you will pay on this facility? (a) The bank will apply a flat rate of interest on the amount of overdraft allowed to actually utilize. (b) The bank will apply a flat rate of interest on the amount of overdraft allowed to you. (c) The bank will apply rate of interest linked to the term deposit rate, on the amount of overdraft utilized. (d) The bank will apply rate of interest linked to the term deposit rate, on the average amount of overdraft remaining unutilized from the OD limit. 3) The Nifty has doubled since the last time you advised your client to reduce his equity exposure. The client is annoyed. What might be the most appropriate action to take immediately? (a) (b) (c) (d) Apologize for wrongly forecasting the market Change his asset allocation by increasing his equity exposure Help the client understand the logic of his asset allocation Rebalance his asset allocation by reducing equity investments 4) A professional indemnity policy protects the insured from risk arising out of _________________. (a) Intentional misconduct (b) Misrepresentation of professional competence (c) Negligence (d) Undisclosed conflict of interest 5) White Knight s a financial services firm that specializes in investment advisory services. In its brochure for Financial Planning services, it may state _____________. (a) It can offer superior investment returns on customer portfolios and talk of the arrangements to offer advice in other areas (b) It has the competence to take care of all Financial advisory requirements of the customer (c) Its competence in investment advisory services and the arrangements to offer advice in other areas Financial Planning Academy 7 10) The economy is going through a phase of expansion and growth. Your client has a portfolio that is heavily invested in bonds. (b) Higher rates of growth will require higher imports and expenses. (b) Investing in treasury bills and equities. (c) Laddering the bond portfolio. (d) Moving closer to the efficient frontier in terms of the risk return equation. Industrial production and profitability are high. leading to fall in bond prices. That will depress returns on bonds. (a) Investing in diversified equity funds. (d) The currency will become convertible and interest rates will rise as a consequence. Which of the following fears of the client is well founded? (a) Higher rates of growth will increase demand for funds and interest rates will firm up. (c) The central bank will try to reduce rates to make funding of business cheaper and reduce costs. The government deficits will go up. Financial Planning Academy 8 . 2 & 3 9) The modern portfolio theory suggests that the portfolio returns can be optimized by ________________.(d) Its Financial Planning services are the best available in the market in light of its investment advisory capabilities and arrangements to offer advice in other areas 6) Which of the following is a concurrent indicator of the phase of the business cycle? (a) Wholesale price Index (b) Index of Industrial production (c) Labor costs and capacity utilization (d) Order levels in the manufacturing sector 7) What is the main difference between the personal Financial Planning needs of the employed and the self employed ? (a) Attitude to risk/Risk appetite (b) Need to fund children’s education (c) Need to fund retirement (d) The extent of any employer-provided pension benefits 8) Immunization protects bondholders from which of the following risk/s: 1) Interest rate risk 2) Reinvestment rate risk 3) Maturity risk (a) (b) (c) (d) 1 only 2 only 1 & 2 only 1. (d) Jubin will not violate the Code and the Rules if he does not disclose his wife’s holdings 12) How are financing costs included in NPV and IRR calculations? (a) By including them in the interest payments.to equity from debt and Rs. His wife has some large investments in the shares of a few companies. The sum total of volatility of A and B respectively. represented by standard deviation of the two investments. 8750/-to cash from debt (d) He needs to invest Rs. all original documents prepared or received by the Member in undertaking the advisory task (b) A Member owes to the Member’s partners or co-owners a responsibility to act in good faith (expectations of confidentiality) only while in business together. provide to a person authorized by the client. (a) A and B have a correlation of Zero (b) A and B have a correlation of 1 (c) The portfolio is equally divided between A and B (d) The return on the portfolio is equal to the sum of returns of A and B 14) Which of the following is a correct interpretation of the Rules of Conduct pertaining to the Ethic of Confidentiality? (a) A Member must when requested by the client. will any Member divulge any information or knowledge regarding the FPSB India or its members that they may know or be exposed to 15) Mr. he needs to _____________.2 Lakh in equity. Under the Code of Ethics and Rules of Professional Conduct _______ (a) Jubin must disclose the fact to his client(s) so as to make them aware of any potential conflict of interest (b) Jubin has to disclose these holdings only to his employers.7500/. 70000/. Rs. (a) Do nothing.5 Lakh in debt and Rs. (b) He needs to move Rs. Jubin is required to offer views on almost all of these holdings to clients. not thereafter (c) The Member shall maintain the same standards of confidentiality to employers as to clients (d) Under no circumstance. 1 Lakh in his bank current account. will be equal to the volatility of the portfolio as a whole if _________________.11) Jubin is a Financial Planner in a large firm.from debt to cash.from equity and Rs. Over one year the returns on equity and debt are 5% and 12%. (c) He needs move Rs. 10000/. Sinha’s investment portfolio comprises Rs. (b) By considering the interest rate in the setting of the discount rate (c) As a tax deduction (d) By including them in the earnings 13) Consider a portfolio of two investments viz. At the end of the year to maintain his current asset allocation. 60000/.in debt and equity. if required by the firm’s internal compliance rules (c) Jubin need not follow any code of ethics and rules of professional conduct. Financial Planning Academy 9 . A & B. 1498 17) Spykar a accomplished Financial Planner and is also an expert on derivatives and high yielding bonds. (d) 80% long-term debt. 30% long-term debt. 1168 (d) Rs. without any penalty and with all the accumulated interest (compounded half yearly). 4000 with them 3. You had invested Rs. Comp I.Rs.) -4000 PV. Financial Planning Academy 10 .5%.2%. 3.5 years back. (c) 6. Which of the following is likely to be an appropriate asset allocation strategy for them? (a) 10% sectoral equity. is willing to prepay your Cumulative Fixed Deposit with them. and 40% medium term debt (b) 20% Sectoral equity. 20% medium term debt 19) ABC Ltd. what is the annualized rate of interest you have earned? (a) 6.40% (b) 3. 1149 (c) Rs. If they are giving you back Rs. Both expect to work till they turn 65. 60% diversified equity.to get annualized return.1000. He believes in quickly moving clients from one investment to another through a dynamic process of research and recommendations. What according to the Rules relating to the Code of Ethics is the most applicable in this case? (a) He does not violate the Rules if he explains to the client the reasons and is able to show that the moves are appropriate to the client (b) He does not violate the Rules since he conducts and has access to research and advises on products relevant to clients based on an understanding of their requirements (c) He does not violate the Rules since he is an acknowledged expert and knows what is best for his clients (d) He violates the Rules as it amounts to active churning of client portfolios 18) Mrs. 20% diversified equity.2%. 20% long-term debt (c) 30% Sectoral equity. 2.0%.1. Their only goal is to fund their retirement. 1100 (b) Rs. It is likely to be priced at _______________. 40% cash/ liquid investments.0% bond (Face Value.) Value of I *2 . & Mr. He understands client requirements well and is able to come up with appropriate portfolio restructuring ideas for clients. (d) 7. interest payable semi-annually) maturing 6 years from today is available at a yield to maturity of 6. (a) Rs. 30% diversified equity.16) A 10 year 8. Arora are aged 55 and 58 years respectively.5*2 N. 4985. 4985 FV. Solution:. Comp PV Financial Planning Academy 11 . 1200/.1200 PMT. II & IV Quadrant I.High frequency. Vishal takes medication that he knows makes him drowsy and then proceeds to drive. High Impact Quadrant III . He swings a new golf club on the fairway and the head of the club flies off. What lump sum should he deposit now? (a) Rs.20) Which of the following is a tort of negligence? (a) Mr. Low Impact Quadrant II . Rani in a room to prevent him from leaving the building (d) Mrs.58630 (c) Rs. (b) Mr. . which causes her to lose control of her car and hit another car.59119 HINT :. Low Impact It would not be practical to purchase insurance for events falling in _________________. You can view the classification in four quadrants. can be plotted on a graph with X axis measuring the frequency (low-high) and Y axis measuring the financial impact (low-high).Low frequency. III & IV Quadrant III 22) Karan wants to withdraw Rs. Priti experienced a sudden surge of chest pain while driving.56949 (b) Rs. 5*12 N.56478 (d) Rs. . . High Impact Quadrant IV . (a) (b) (c) (d) Quadrant I & IV Quadrant I. 21) Any possible occurrence which may have a negative financial implication.at the end of each month for the next 5 years. Jaya locks Ms.Low frequency. Joy was playing golf. Quadrant I . (c) Mrs.High frequency. He expects to earn 10% interest compounded monthly on his investments. . 10%/12 I. He gets into an accident injuring the passengers in another car. and hit another golfer who was standing 20 feet away. All the following are characteristics of a typical risk averse except: I. Preference for certainty. The husband’s pension income. II B.02% Q4. III. Over-optimism. Q5. Analyse your present financial position. A. All the following assets are generally considered to be protected from a decline in purchasing power due to increase in inflation except: A. Bank of India D.Part . Reserve Bank of India B. The wife’s rental income. D.950. Compute I% = 6. The wife’s dividend income. Calculate the yield to maturity of a bond with the following details: Face Value : 1. C. B. II. Q2.000.00% (d) 6.29% (c) 5.0% Remaining Te to Maturity : 6 years (a) 5. II. C. III C.000. D. Overestimation of risks. A. SEBI C. Design strategies to attain your financial objectives. I. PV = . Q3. Institute of Economic Research. Determine your specific financial goals and objectives. N = 6. Invest in securities that provide the highest return. Which of the following statements does not reflect the meaning of financial planning? A. Pmt = 50.3 Q1.02% HINT :FV = 1. III Financial Planning Academy 12 .00 Coupon Rate (paid annually) : 5.16% (b) 4. The body responsible for the formulation and implementation of monetary policy in India is ___________________________.00 Market Price : 950. The husband’s employment income. I D. B. D.0%. B.18. C. Term insurance. D. A decrease in the mortality age. Nothing. A decrease in the planned retirement age. B. Revocable by divorce.000 on his life and named his sister as beneficiary.000 is included in his estate? A. C. a discount to face value ) Q9. Half of it. All of it. D. A. Ali owns a life insurance policy for 100. B. Q11. Depends on the amount agreed by the beneficiary. An increase in the rate of inflation.000 N = 5 Pmt = 80 (8% of 1000) I = 10% Compute PV = 924. The prevailing yield to maturity of bonds with similar risk and term is 10. The type of insurance purchased by Alok is: A. Participating endowment insurance.000 death benefit if Alok dies within ten years of purchasing the policy. Identify which amongst the following represents a personal risk: A. Whole of life insurance. The economic loss to a husband when his wife is taken ill. A corporation proposes to issue a 5-year bond with a coupon rate of 8. The economic loss to the owners of a firm brought about by a products liability suit. as long as he continues to pay the annual renewal premiums. Serves as a declaration of intent only. The bond will sell `____________ to its face value. D. Q7. how much of that 100. B. D. Q8.0%. C. Must be in writing. Disability income insurance. The economic loss to the owners of a factory destroyed by a fire. All of the following changes in planning assumptions will increase the amount a person will need in order to achieve his retirement goals except: A. A decrease in the rate of investment earnings. At a discount. The economic loss to a physician brought about by a professional indemnity suit. All forms of coverage cease after the 10-year period. B. At a premium. Only takes effect upon the death of testator. C. B. Ali’s sister is the beneficiary of that sum insured. Financial Planning Academy 13 .Q6. At some indeterminate value. If Ali dies. D. At par. C. Alok purchased an insurance policy on his life that requires ten equal annual premiums. The policy provides a 100. C. ( FV = 1. Q10. Which of the following is not a characteristic/feature of a Will? A. I. V. III. V Financial Planning Academy 14 . VI. IV. VI. VI D. III. I. III. III C. Why is it necessary for a financial planner to establish a well-defined client-planner relationship? I. Q13. Q14. IV. Monitor the plan. It must provide measures to guarantee attainment of goal. Create a financial plan. Q15. II. Assets and liabilities. III. II. II B. II. A. I. IV. It must be within client’s resources to implement the plan. IV D. V. III. II. C. Gathering information and establishing goals. I. II. I. I. V. II. IV D. VI C. III. II B. III. I. B. What is the proper sequence of the process? A. Family relationships. IV.Q12. It must clearly identify the roles of the implementers. Insurance policies. III C. IV. IV. A. Analyze information. II. It must be tailored towards achieving client’s objectives. III. VI B. V. The following are the six basic steps in the financial planning process: I. Establishing and defining client-planner relationship. To facilitate discussion on personal issues. II. D. To develop a sense of confidence in the planner’s ability. To instill a sense of trust between them. All of the above. IV. All of the above. I. II. II. Implement the plan. II. To prove that the planner is an honest person. Investment portfolio. Which of the following may not be considered as essential characteristics of a sound financial plan? A. Which of the following is/(are) considered quantitative information that needs to be gathered by a financial planner from a client: I. C. C. Q19. To avoid intervention from regulators. Duty to disclose information on services offered. D. The confidentiality principle requires a financial planner to do the following. III D. III. Why is it important for a financial planner to practice good professional ethics? I. B. B. Duty to keep abreast with current development in rules and regulations. Q17. I. To avoid being the case of “one rotten apple spoils the entire basket”. Not to disclose a client’s information to a third party without the client’s consent. Principle of competence. D. To maintain continued trust on the profession. D. Disclose client’s information only in response to a proper legal process. except:: A. Principle of integrity. I B. Principle of objectivity.Q16. The rule that says “a CFP designee shall satisfy all minimum continuing education requirements established for CFP designees by FPAM” is related to which principle in the Code of Ethics? A. Principle of fairness. etc. I. C. The following are some of the principles a professional financial planner should observe in performing his fiduciary role. All of the above. Duty to implement the agreed plan. II. II C. A. Treat clients in the same manner the planner wants to be treated. except: A. Financial Planning Academy 15 . Use client’s information only for the purpose of preparing the financial plan. Duty to diagnose client’s financial position and make recommendation. B. Q18. A financial planner who receives commission from companies on sale of investment/insurance products to a client is being unprofessional. The most common client in the early years of financial planning internationally was in the age bracket: (a) 25-35 (b) 55-65 (c) 45-55 (d) Above 70 5.Part . (d) The above statement is true. provided the financial planner discloses the fact to the client at the beginning of the relationship. A professional financial planner may provide limited advice. income and expenditure (cash flow). insurance risk management. provided he also charges service fees from the client. estate planning. 'Empty nesters' usually fall in the age bracket (a) (b) (c) (d) 55-65 35-45 45-55 They could fall in any age bracket Financial Planning Academy 16 . (a) The above statement is true (b) The above statement is false (c) The above statement is false. retirement benefits. soft dollar arrangements and other benefits from product providers which may tend to create a product bias (b) Operates free from any direct or indirect restrictions relating to the securities recommended (c) Operates without any conflict of interest by ownership links to product providers (d) All of the above 4. (a) (b) (c) (d) Both A and B are false A is true but B is false A is false but B is true A is true provided. A professional financial planner provides only comprehensive financial advice to clients encompassing. if he discloses the fact at the outset to the client. Which of the following is true? A. 3. A financial planner in Australia may call his/her services ' independent' provided (a) He/She avoids commissions/trailing commissions. the financial planner is a CFPCM certificant 2. investment planning B.4 1. tax planning and estate planning. By comprehensive financial planning we mean (a) Financial planning by a team of persons (b) Financial planning by a CFP CM certificant (c) Planning which encompasses all areas of a client's life (d) Financial advice on cashflows & budgeting. formalized/written complaints handling procedures for financial planning businesses are a must. In India. by definition financial planning is comprehensive. 8. retirement planning. There are usually _______ meeting/s before a financial plan can be implemented. A professional financial planner is one who (a) Takes pride in his/her work (b) Is committed to quality (c) Is dedicated to the interest of the client (d) All of the above 11. Financial planners are trained to write wills and/or sell insurance (a) The above statement may be true (b) The above statement is false (c) The above statement is true in all cases (d) The above statement is true if the financial planner is a CFPCM certificant 7. investments. 12. This is a requirement of (a) The law (b) The FPSB (c) It is not a requirement (d) It is expected to be introduced shortly in the law. insurances.6. (a) There is no such thing known as a statement of advice (b) The above statement is true (c) The above statement is false (d) There is no such thing as limited financial planning advice. 9. For a successful financial planner (a) Technical skills are more important than people skills (b) People skills are more important than technical skills (c) Both are equally important (d) Neither skill is an essential pre-requisite Financial Planning Academy 17 . A statement of advice is not needed in providing limited financial planning advice. (a) One (b) Two (c) Three (d) Four 10. The most valuable asset of a financial planner/planning firm is: (a) The number of clients (b) The funds under management (c) Customer satisfaction (d) Trust 14. there are _______ types of clients (a) Three (b) Four (c) Five (d) Six 2 Financial Planning Academy 18 .CFP. disclosure regarding compensation needs to be made only at the time of establishing the relationship with a new client. According to Ross Levin. According to the FPSB rules of professional conduct. (a) True (b) False (c) Sources of compensation need not be disclosed (d) Need to be disclosed whenever there is a change in status. 18. It is sound business practice to fill up the client questionnaire at the first meeting with the client (a) True (b) False (c) Give the questionnaire to the client to fill at home at his/her leisure. At the first meeting with the client (a) Get straight to the point (b) Break the ice with small talk and a cup of tea (c) Explain your role and the scope of the engagement (d) b and c 16.13. (d) Could be filled up at any meeting 15. Under the rules of professional conduct of the FPSB. a planner may charge (a) Any amount of fees (b) Only service fees (c) Only investment placement fee (d) Any fees provided it is fair and reasonable 17. Telling a client about research capabilities or the use of computers in your financial planning firm amount to (a) Unprofessionalism (b) Advertising (c) Smart thinking (d) Waste of time 19. etc.20. A planner should approach other professionals associated with a client through (a) The client by taking him/her along (b) Authority letters from the client (c) Directly (d) Need not approach them as the client can gather all the information. 2) Investment time horizon 3) Concern liquidity/flexibility are all examples of qualitative information about a client. for Financial Planning Academy 19 . (a) True (b) False (c) True only according to Mary Rowland (d) False according to Mary Rowland 21. If a planner does not receive sufficient and relevant information from a client he/she should: (a) Terminate the relationship (b) Give restricted (limited) advice (c) Go ahead but give a disclaimer disclaiming all responsibility (d) Either a or b 22. (a) True (b) False (c) Only 1) and 3) are true examples (d) None of them are examples 24. Sometimes clients expect planners to solve every financial problem they have like overspending.Gathering comprehensive information on the client is useful because: (a) It is in compliance with the AFP rules of professional conduct (b) It improves your legal position in case of a legal suit (c) It makes good business sense (d) All of the above 23. losses in the share markets and want to earn 20-30% p. It is best to start a data gathering client interview with (a) Qualitative details (b) Client's finances (c) Planner's fees details (d) Quantitative information 26.a. 1) Investment experience. Risk profiling is (a) A method to determine a client's attitude to risk (b) A method to determine the risk underlying a client's portfolio (c) Measurement of the risk of losing a client (d) Measurement of the risk of erosion of a client's networth 25. Financial planning needs can be categorized into two broad areas: (a) Investment needs & insurance needs (b) Insurance needs and retirement needs (c) Needs for predictable events and needs to provide for unpredictable events (d) Investment needs and retirement needs 28. As part of their job. financial planners have to predict future economic indicators which impact clients. Which of the following is true ? (a) Needs take precedence over wants (b) Needs are the same as wants (c) Financial planning addresses both needs and wants (d) a and c 29. There are two types of product research: (a) Generic and new product research (b) Old and new product research (c) Investment and insurance product research (d) There are nil types of product research Financial Planning Academy 20 .27. The client questionnaire records quantitative data and _______ record/s qualitative data. futures etc. (a) The planner's mind (b) File notes (c) The same client questionnaire (d) A separate questionnaire 31. (c) Derivatives (d) b and c 33. (a) The above statement is true (b) The statement is false (c) It is true in cases of economic turmoil (d) The statement is true for CFP CM certificants 32. A financial planner should (a) Confine himself strictly to the client's brief (b) Point out all flaws in a client's financial position that he may notice (c) Not agree to providing limited or restricted advice (d) Always provide comprehensive financial planning advice 30. Leveraged investments are (a) Investments bought with debts raised (b) Options. . 500 Bn. {Hint: GDP= C+I+G+(X-M)} Financial Planning Academy 21 . G = Rs. 2000 Bn. C= Rs.. 1000 Bn. (c) Rs. I = Rs. Planners may keep abreast of new products and developments through (a) Perusal of the press (b) Industry functions and seminars (c) Fund manager briefings (d) All of the above 35. ________ is India's largest trading partner (a) USA (b) Russia (c) UK (d) Germany 38. 1000 Bn. (b) Rs. 37. The Indian economy lies in-between a capitalist economy and a socialist economy. Construction is classified as a (a) Service industry (b) Manufacturing industry (c) Agricultural activity (d) None of the above 40. 8000 Bn. The fastest growing sector in the Indian economy is the (a) Primary sector (b) Secondary sector (c) Tertiary sector (d) None of these 39. then M = (a) Rs. 3000 Bn. and X = Rs. 2000 Bn. (a) True (b) False (c) Partially true (d) True but it is now moving towards a socialist economy. (d) Rs. 4000 Bn.34. 2000 Bn. Micro-economics refers to the study of economics at (a) National level (b) Level of the firm (c) Personal level (d) b and c 36. If the economic symbols have their usual meanings. GDP = Rs.. For living standards in India to rise. both must grow (c) GDP must grow at a higher rate than population (d) GDP must grow while population should fall 42. Inflation is important to financial planners because (a) It serves as a benchmark for capital growth in an investment portfolio (b) It serves as a benchmark for income growth in an investment portfolio (c) It indicates that the economy is growing (d) It indicates that money should not be kept in banks 44. M3 growth refers to (a) Growth in money supply (b) Growth in GDP (c) Growth in inflation (d) Growth in demand for money 46. a key variable Financial Planning Academy 22 . faltering business. slackening rate of investment activity. High level of employment. higher costs for business firms are indicators of which stage of the business cycle (a) Contraction (b) Recession (c) Recovery (d) Boom 43.41. The advantage with monetary policy is that (a) It can be implemented reasonably quickly (b) It is more effective than fiscal policy (c) Interest rates are more important than taxes (d) It influences money supply. (a) GDP must grow (b) Population and GDP. Government policy which regulates interest rates in the economy to control money supply and hence inflation is called (a) Fiscal policy (b) Monetary policy (c) Interest rate policy (d) None of the above 47. Economic indicators which point to the current state of the economy are called (a) Leading indicators (b) Lagging indicators (c) Coincident indicators (d) None of the above 45. Fiscal policy affects the economy in that: (a) Higher government spending can stimulate the economy (b) Increases in personal taxes can dampen sentiment and hence consumer demand (c) Fiscal deficit funded through borrowings by issuing government securities may raise interest rates (d) All of the above 51.15 (b) 0. A higher exchange rate can (a) Increase GDP (b) Have no effect on GDP (c) Decrease GDP (d) Improve India's export competitiveness 53. The apex bodies for the co-operative banks in India is/are (a) Government (b) RBI (c) NABARD (d) All of the above Financial Planning Academy 23 .06 50. If the long term interest rate sought is 9%.03 (c) 0. the rupee has depreciated against the dollar which has benefited (a) Exporters (b) Importers (c) Both (d) Neither 52.48.04 (d) 0. (a) The above statement is true (b) The above statement is partly true (c) CRR and SLR do not affect interest rates (d) The above statement is false 49. then inflation is likely (a) 0. The bank rate. The body formed on abolition of the CCI was (a) RBI (b) SBI (c) IRDA (d) SEBI 54. Over the past few years. the real rate of interest is 6%. CRR and SLR are key determinants of the long-term interest rates in the economy. it is most essential to keep in mind (a) Income returns from the portfolio (b) Capital growth in the portfolio (c) Liquidity of the portfolio (d) Volatility of the portfolio 61.55. A ____ % cap has been kept on foreign shareholding in an insurance company (a) 26 (b) 51 (c) 75 (d) 40 57. The first step in the strategy development process is to: (a) Check that you have all the information (b) Secure the client's current financial position (c) Establish the client's goals and financial concerns (d) None of the above 58. (b) CARE (c) Fitch Ratings. Asset allocation strategy is guided by (a) Portfolio diversification (b) Objectives of the client (c) Client's risk profile (d) All of the above Financial Planning Academy 24 . India (d) CRISIL 56. you (a) Need to keep them as few as possible (b) Should encourage the client to take on debt to meet all their goals (c) Need to analyse their current position to ensure fulfillment (d) Encourage the client to fulfill their dreams 59. The leading credit rating agency in India is the (a) ICRA Ltd. securities (d) Cash and fixed interest type investments 60. When you establish the client's goals. To meet short term objectives. it is best to invest in (a) Equity shares (b) Bonds (c) Govt. To meet long term objectives. (a) False (b) True (c) True if at least 50% is in shares (d) True if at least 50% is in debt 64. A financial plan should always (a) Be verbal or written (b) Be verbal (c) Be comprehensive (d) Be written 68. In taking investment decisions. While developing a financial plan. you should directly select specific investment products for recommendations to the client. (a) Financial planning software should not be used (b) Financial planning software may be used solely to check your calculatons (c) Financial planning software may be used as a support. A diversified portfolio may still not reduce risk significantly (a) False (b) True (c) Diversification has nothing to do with risk reduction (d) Risk in a portfolio cannot be reduced significantly 67. specially for financial mathematics (d) Financial planning software can write the whole financial plan 66. Some of the important advantage/s of a written financial plan is/are (a) That the client can suggest changes to the plan (b) That the client can raise doubts and questions on the plan (c) That the client cannot proceed legally against the planner (d) All of the above Financial Planning Academy 25 . a balanced portfolio will not show any negative total returns. While selecting investment products. one must (a) Quantify the risk. According to financial consultants. (a) The above statement is partly true (b) The above statement may be true in some circumstances (c) The above statement is true (d) The above statement is false 63. Godfrey Pembroke. returns and time frame (b) Provide for an emergency fund (c) Diversify (d) All of the above 65.62. plans generated on financial planning software are: (a) Acceptable (b) Unacceptable (c) Acceptable. Which of the following is false (a) Significant advantages accrue to a financial planner through a written financial plan (b) Significant advantages accrue to the financial planning firm through a written financial plan (c) Significant advantages accrue to the client through a written financial plan (d) All of the above 70. According to financial planning best practice standards. only if it is a new client (d) True. if the planner is not a CFPTM certificant (d) Acceptable. There is no need to clutter the financial plan with your calculations/analysis (a) True (b) False (c) False. only if the financial planner is a CFP CM certificant (d) True. if the software also generates commentary and produces word-processed documents Financial Planning Academy 26 . The engagement letter should be taken at the time of the first presentation of the plan to the client. 'The financial planner/financial planning firm is/are not responsible for consequences arising out of the action taken on the basis of the financial plan' is an example of a poor disclaimer (a) True (b) False (c) False. 74. you should keep the calculations only for possible use in case of litigation. (a) True (b) False (c) The letter of engagement need not be taken from the client (d) Not true because the plan may be sent to the client by post 72. The following is not an essential component of a financial plan: (a) Executive summary (b) Financial Planning strategy (c) Letter of engagement (d) Summary of services provided 71. only if the financial planner is a CFP CM certificant 73.69. 75. Once a client is ready for implementation of the plan. At the macro level. Presentation of the plan to the client includes: (a) Explanation of the cost structures associated with the financial plan and its implementation (b) Client declaration (c) Authority to proceed (d) All of the above 77. Usually a time lag of ______ week/s is recommended between the tabling of the plan and the next meeting with the client. best practice standards require that you (a) Keep only computer files (b) Keep only paper files (c) Keep both computer and paper files (d) Files need to be maintained at the client's end. 81. Before presenting the plan to the client. (a) Share markets may rise or fall (b) Wages and/or business income may rise or fall (c) The client may lose his/her employment (d) None of the above Financial Planning Academy 27 . As a CFP CM certificant. the planner needs to (a) Prepare the plan document (b) Prepare for the presentation meeting (c) a and b (d) None of the above 76. should be confirmed in writing including reasons thereof 79. (a) One (b) Two (c) Three (d) Four 78. Any changes in recommendations suggested by the client (a) Should be vehemently opposed by the planner (b) Should be rejected outright (c) Should be incorporated in the plan (d) If incorporated. there is need to prepare (a) A letter of engagement (b) An Authority to proceed (c) An Action plan (d) Authorization letters 80. A strategic review of a client' s situation is required in case of (a) Macro level changes (b) Micro level changes (c) Neither (d) Both 84.82. The most appropriate criterion for deciding on the frequency of portfolio reviews of a client is: (a) Client profile (b) Funds under management (c) Fees received from client (d) Planner's discretion 85. A CFPCM certificant in India need not disclose the reasons for moving from one investment to another for a client (a) The above statement is true (b) He/she has to disclose it under law (c) He/she has to disclose it under FPSB rules of professional conduct (d) He/she just has to inform the client of the change 87. A letter of engagement is: (a) A legal document (b) A requirement of the FPSB rules of professional conduct (c) Essential for client-planner relationships (d) Like a memorandum of understanding Financial Planning Academy 28 . The key difference between marketing share broking services and marketing comprehensive financial planning services is that: (a) Share broking is a purely transaction driven business (b) Shares are easier to sell (c) Comprehensive financial planning is easier to sell (d) There is no difference 86. It makes enormous commercial sense to provide an ongoing financial planning service to clients (a) False (b) True (c) It is easier to attract new clients (d) The service is provided because it is mandatory under the AFP rules of professional conduct 83. A 'charge' over an asset is (a) An extra payment to be made to acquire the asset (b) Rental for the asset (c) Same as leasing the asset (d) The right to dispose off the asset by the lender in the event of non-repayment of loan 92. income proof is usually a/an (a) Statement of accounts (b) Remuneration slip (c) Income-tax return (d) Any of the above 94. The difference between a mortgage and an overdraft is that: (a) An overdraft is available for a year (b) An overdraft may be unsecured (c) A mortgage usually has a lower rate of interest (d) All of the above 93. For a self-employed professional. To decide on the frequency of reviews for a client. The drawback/s with credit cards is/are that (a) They are cumbersome to use (b) They charge a high rate of interest (c) With rollover credit. the planner has to consider: (a) The level of funds under management (b) The type of investment portfolio (c) The 'pace of change' in the client's circumstances (d) All of the above 90. Tool/s that can aid a financial planner in conducting reviews/monitoring of client portfolios are : (a) Portfolio management systems (b) Investment research (c) a and b (d) An efficient secretary 91. A review exercise for a client consists of: (a) A strategic review (b) A portfolio review (c) Neither (d) Both 89.88. there is danger of falling into a debt trap (d) b and c Financial Planning Academy 29 . If 2006-07 is the previous year. 101. The surcharge on income tax is now: (a) 0. Under Section 80CCC(1). OASIS stands for (a) Old Age Social & Income Security (b) Old age Social & Investment Scheme (c) Old Age Security Income Scheme (d) None of the above Financial Planning Academy 30 .04 (d) 0. While income tax is an example of direct taxes.95. An income and expense statement for a client is needed to determine (a) Asset base (b) Liabilities & Debts (c) Taxation (d) Cashflow 96. The difference between a deduction and a rebate is that (a) A deduction is a reduction from assessable income while a rebate is a reduction from tax payable (b) Both are same (c) A deduction relates to salary income while a rebate relates to income from business or profession (d) A deduction does not affect tax paid while a rebate does. deduction is available for (a) Interest income (b) Dividend income (c) A notified pension plan (d) Income from house property 100.03 (c) 0. the assessment year would be (a) 2007-08 (b) 2001-02 (c) 2000-01 (d) None of the above 98.02 (b) 0.10 99. indirect taxes are (a) Excise duty (b) Customs duty (c) Local sales tax (d) All of the above 97. Internationally. there is a trend towards (a) Dismantling defined contribution funds (b) Dismantling defined benefit funds (c) Neither (d) Both a and b 103.102. For a defined contribution superannuation fund. contribution is tax exempt upto (a) 5% of salary (b) 8% of salary (c) 10% of salary (d) 15% of salary 107. (a) The above statement is true (b) These tax breaks are available to a recognized provident fund (c) These tax breaks are available to an unrecognized provident fund (d) None of the above 104. all incomes including interest are exempt from tax. No contribution from employees or employers is required in the case of: (a) Employees' provident fund scheme (b) Employees' pension scheme (c) Employees' deposit linked insurance scheme (d) None of the above 105. Standard deduction is available for (Not Applicable from AY 2006 -07) (a) Salary (b) Pension (c) a and b (d) Neither Financial Planning Academy 31 . Under a statutory provident fund. For the purpose of calculating the tax benefit of gratuity. A public provident fund account can be closed after: (a) 4 years (b) 5 years (c) 10 years (d) 15 years 106. a month is assumed to contain (a) 22 working days (b) 28 working days (c) 26 working days (d) 30 working days 108. Fixed interest sector consists of debt instruments with a maturity of (a) More than one year (b) 1-3 years (c) More than 3 years (d) None of the above 111.A co-operative type of organization is useful for (a) Large businesses (b) Small businesses (c) Small and medium sized businesses (d) None of the above Financial Planning Academy 32 .109. The minimum number of members in a public limited company is (a) 10 (b) 20 (c) No limit (d) 7 115. A sole proprietorship is governed by the (a) Negotiable Instruments Act (b) Indian Trusts Act (c) Contract Act (d) None of the above 114. Money market comprises (a) Short term investments (b) Long term investments (c) Cash (money) only (d) None of the above 110. prices of fixed interest securities will (a) Rise (b) Not be affected (c) Fall (d) None of the above 113. If you invest in the fixed interest sector (a) You will always earn a fixed rate of return (b) You will earn a fixed rate of interest (c) You will have enormous capital growth potential (d) None of the above 112. If interest rates are rising. Initial public offerings (IPO) for shares are part of (a) Secondary market for shares (b) Primary market for shares (c) Neither . a public limited company may be required (a) 100 (b) 1000 (c) 50 (d) 150 117. Assets underlying derivatives are: (a) Shares (b) Bonds (c) Other tradeable securities (d) Any of the above 122. have a separate market (d) Derivatives market 118.116. The standard deviation of returns of a financial instrument denotes (a) Risk (b) Return (c) Price (d) Its nature Financial Planning Academy 33 .If the number of members in a Private Limited Company goes above _____. A mutual fund may also be disadvantageous because (a) Risk is higher in a mutual fund (b) You do not have any ownership rights in the fund (c) Management fees may be high (d) It may not declare any dividend 121. Problem/s that plague Indian capital markets are (a) Illiquidity (b) Shallowness (c) Inadequate disclosure standards (d) All of the above 119. Mutual funds are advantageous because (a) Of diversification of risk (b) Access to otherwise inaccessible markets (c) Easy liquidity (d) All of the above 120. Disadvantage/s of investing in cash or fixed interest type of investments are that: (a) They may be subject to fluctuations in total return (b) They show little protection against inflation (c) a and b (d) None of the above 129. A client's attitude towards risk is likely to: (a) Change over time (b) Remain stable over time (c) Remain stable. (a) The higher the return (b) The lower the return (c) The return is independent (d) The less volatile the return 124. The best methods of determining a client's attitude to risk are (a) Quantitative (b) Qualitative (c) A mixture of both (d) None of the above 126.123. A property trust is (a) A sound property investment (b) A scheme of bequeathing a property (c) Trust in property investments (d) A pooling of funds in property investments for mutual benefit Financial Planning Academy 34 . unless there is a major change in the client's situation (d) None of the above 127. Determining a client's attitude to risk is known as (a) Data gathering (b) Risk determination (c) Risk profiling (d) Qualitative data gathering 125. Speculative risk refers to risk (a) Where there may be a loss or no loss (b) Where there is a loss or a gain (c) Where there may be a gain or no gain (d) All of the above 128. The higher the risk. As a part of risk management. Some personal risk/s that people face is/are (a) Risk of early death (b) Risk of living too long (c) Risk of injury (d) All of the above 132.The following type of policy does not have a savings/investment component (a) Whole of life (b) Endowment (c) Convertible whole life (d) Term insurance 135.Trauma insurance covers (a) Total and permanent disability (b) Terminal illness (c) Life threatening medical condition (d) None of the above 134. general insurance relates to (a) The individual (b) Tangible property (c) Property.As opposed to life insurance. if you are short of funds (c) True (d) False 131. From middle age.A life insurance policy may be 'encashed' earlier through a (a) Surrender value (b) Policy loan (c) A and b (d) None of the above 136. a client may need (a) Income protection insurance (b) Life insurance (c) Critical illness insurance (d) Total and permanent disability insurance 133. if you have surplus funds (b) True. (a) True. you may decide to retain some part of risk. whether tangible or intangible (d) Intangible property Financial Planning Academy 35 .130. a life insurance contract has to be renewed each year (b) Unlike life insurance.If an individual dies without drawing up a will.137.A major difference between life and general insurance is that (a) Unlike general insurance.A General Insurance policy generally (a) Places the insured in the same position as before the loss (b) Places the insured in a better position than before the loss (c) Places the insured in a position which may be worse off than before the loss (d) May be any of the above 138. health insurance is the subject matter of (a) Life insurance (b) General insurance (c) Neither. he is said to have died (a) A widower (b) Without a beneficiary (c) Intestate (d) Without an executor 142. it is a separate head (d) Mediclaim is covered under life insurance while other schemes come under general insurance 141.A will may require a change in the event of (a) Death of beneficiary (b) Marriage or divorce (c) Significant change in financial position (d) All of the above 143.A financial planner may prepare a will for a client provided he is a (a) CFPCM certificant (b) A lawyer (c) A chartered accountant (d) None of the above Financial Planning Academy 36 . a general insurance contract may contain an investment component (c) Neither (d) A general insurance contract is for large amounts while a life insurance is for small amounts 140.In India. a general insurance contract has to be renewed each year (c) Life insurance does not cover risk while general insurance does (d) General Insurance does not cover risk while life insurance does 139.A major difference between life and general insurance is that (a) Unlike general insurance. a life insurance contract may contain an investment component (b) Unlike Life insurance. one is a general power of attorney.There is a need for a thorough evaluation of a company before investing in its shares. a 2-in-1 account) is needed because (a) It pays a higher rate of interest (b) It evens out uneven cashflows (c) Both a and b (d) None of the above 149.ALC in the context of cashflow planning and budgeting refers to (a) Average living costs (b) Annual living cashflow (c) Annual living costs (d) None of the above 147.A financial planner should (a) Always suggest his own cashflow management system to the client (b) Not advise on cashflow planning (c) Improve upon an existing system if it is adequately effective otherwise (d) None of the above 148. the required rate of return to maintain the value of an investment is (a) 0. This is because (a) Shares represent part-ownership of a business (b) Shares are risky investments (c) Shares involve heavy cash outlay as compared to other investment avenues (d) a and b Financial Planning Academy 37 .If the inflation rate is 3% and the tax rate is 40%. the other is a (a) Specific power of attorney (b) Residual power of attorney (c) Special power of attorney (d) None of the above 145.For a retired client.There are mainly two types of powers of attorney.06 (d) 0.144.05 (c) 0. a main account (e.g.07 150.04 (b) 0.A person who carries out the instructions in a will on behalf of the deceased is called (a) A Beneficiary (b) A Testator (c) An Executor (d) A Lawyer 146. guaranteed bonds (d) None of the above 156.151.A retiree should not invest in (a) Equity shares/mutual funds (b) Fixed deposits of banks (c) Govt.In the interest of your clients.A popular measure of the valuation of a company's share on the stock markets is (a) Dividend yield (b) Gearing (c) Earnings yield (d) P/E ratio 153.The most important advantage of equity shares is that (a) They provide long term growth over inflation (b) They have low risk (c) They provide risk diversification (d) All of the above 154.An effective equity share investment strategy is to time the market (a) The above strategy is difficult to implement in practice (b) It is more effective to invest for the long term (c) It is more effective to diversify your portfolio (d) All of the above 157.An investment assets portfolio should have (a) Sector risk diversification (b) Legislation risk diversification (c) Company or product risk diversification (d) All of the above 155. for tax advice (a) Refer them to a tax consultant (b) Refer them to a CFP CM certificant (c) Seek expert advice yourself before recommending strategies (d) None of the above Financial Planning Academy 38 .A company's relative capital structure can be known from its (a) Debt-Equity ratio (b) P/E ratio (c) Liquidity ratios (d) None of the above 152. 158.The Indian taxation system is: (a) Progressive (b) Regressive (c) Assertive (d) None of the above 159.Capital assets exempted from capital gains tax include (a) Jewellery (b) Rural agricultural land (c) Shares (d) None of the above 160.An equity share held for 12months is (a) A long term capital asset (b) A short term capital asset (c) Not a capital asset (d) None of the above 161.A distinction is made between long term and short term capital gain because (a) Long term capital gains are taxed at a lower rate of tax (b) Deductions under section 80CCC to 80U are not available against long term capital gains (c) a and b (d) None of the above 162.If you avail indexation benefit on long-term capital gains in respect of listed equity shares, where STT is paid then, the rate of tax is (a) 10 (b) 30 (c) NIL (d) 20 163. Long term capital gains tax can be saved if the capital gains is invested in Bonds issued by (a) National Highways Authority of India (b) Rural Electrification Board (c) Small Industries Development Bank of India (d) Either a or b 164. Long term capital gains can be saved by investing the gain an IPO (a) The above statement is true (b) The statement is false (c) Even short term capital gains can be saved the same way (d) None of the above Financial Planning Academy 39 165.Income may be split between spouses (a) By diverting salary income from one spouse to another (b) By splitting investment income (c) By transferring assets as well as income to the other spouse (d) None of the above 166.In an effective gifting strategy for tax planning, the gift should be (a) Reciprocated (b) Irrevocable (c) Complementary (d) None of the above 167.A partnership is an effective tax planning strategy if (a) All the partners provide services (b) The partners are spouses (c) The partners are family members (d) One of the partners is a sleeping partner 168.Growth based investments, effectively (a) Lower taxes over the long term (b) Defer taxes (c) Avoid taxes (d) a and b 169.Interest on borrowings for investment is (a) Not allowed as a tax deductible expense (b) Allowed as expense for tax purposes (c) Used as a tax planning strategy (d) b and c 170.One of the major common risks of tax planning is that (a) Legislation changes affecting taxes are frequent (b) You may end up paying higher tax (c) You may be prosecuted for tax evasion (d) All of the above 171.An effective retirement planning strategy should commence when (a) The person is born (b) When he is an adult (c) When he joins the workforce (d) When he gets married Financial Planning Academy 40 172.For an effective retirement planning strategy, one should consider (a) Age of retirement (b) Health of retiree (c) Desired lifestyle in retirement (d) All of the above 173.One of the risks inherent in a retirement plan include: (a) Inadequate medical insurance (b) Early death (c) Lack of a will (d) All of the above 174.Insurance covers (a) All risks (b) Pure risks (c) Impure risks (d) None of the above 175.The following risks may not be covered by insurance: (a) Being sued for slander (b) Loss of income through injury/illness (c) Disruption of business through malicious damage (d) None of the above 176.Life insurance is advantageous because (a) It provides liquidity through loans (b) A beneficiary gets the life insurance benefit immediately on death of life insured (c) Proceeds from surrender or maturity of a life insurance policy are exempt from capital gains tax. (d) All of the above 177.If a person is 45 years of age and his gross annual income is Rs. 2,00,000, his life should approximately be insured for (a) Rs. 30,00,000 (b) Rs. 4,00,000 (c) Rs. 15,00,00 (d) Rs. 20,00.00 ( Assumed Approx. 10 times of annual income.) 178.Apart from rules of thumb, the other approach to estimate insurance needs is (a) Estimate approach (b) Needs approach (c) Necessity approach (d) None of the above Financial Planning Academy 41 Insurance to cover doctors.Estate planning objectives would include: (a) Providing for dependents (b) Minimization of taxation (c) Satisfaction of philanthropic objectives (d) All of the above 185. CAs etc.It is important to insure (a) All risks (b) Some risks.In case a client owns a business. the financial planner needs (a) To seek expert advice (b) To consult a CFP CM certificant (c) To be extra careful in giving recommendations (d) All of the above 181.The following are usually attached to life insurance policies as riders: (a) Accident benefit (b) Critical illness (c) Income protection (d) Either a or b 180. some to be retained (c) Risks depending on the individual (d) None of the above 184.The householder's insurance policy covers property risk of (a) Fire (b) Theft (c) Damage in riots (d) All of the above 183. lawyers.179. against professional negligence is called (a) Professional liability insurance (b) Professional indemnity insurance (c) Professional negligence insurance (d) None of the above 182.Estate planning strategies need to be (a) Rigid (b) Changed frequently (c) Flexible (d) Dynamic Financial Planning Academy 42 . the assets are distributed (a) According to respective succession acts (b) By the courts (c) By the deceased’s lawyer (d) To charity 187.Some of the tax benefits available in estate planning are (a) Transfer of capital assets under a will are exempt from capital gains tax (b) Trust created under a will for a dependent relative is exempt from tax (c) Both a and b (d) No tax benefits are available for estate planning 190.A will may need changes in case of (a) Marriage (b) Divorce (c) Re-marriage (d) All of the above 188.If a person dies intestate.The AMC of a mutual fund reports to (a) The sponsor (b) AMFI (c) SEBI (d) The trustee company Financial Planning Academy 43 . a CFP CM certificant should (a) Refer the preparation of a will to a lawyer (b) Know the contents of a will (c) Be aware of estate planning issues (d) All of the above 189.The sponsor of a mutual fund is its (a) Manager (b) Trustee (c) Promoter (d) None of the above 192.For estate planning.The following is/are an important component of estate planning (a) Business succession planning (b) Life insurance policy (c) A and b (d) None of the above 191.186. 193.The management fees of an AMC (a) Is flexible (b) Is fixed (c) Changes with funds under management (d) Is decided by SEBI 194.The following type of mortgage does not require possession to be handed over to the mortgagee (a) Simple mortgage (b) Usufructuary mortgage (c) English mortgage (d) All of the above Financial Planning Academy 44 .A contingent exit load fund (a) Charges no load (b) Charges load only on exit (c) Charges load both at entry and exit (d) Charges load if there is early redemption 196.The following are benefits of mutual funds: (a) They do not carry risk (b) They are cost effective (c) Both a and b (d) None of the above 199.An equity fund may have (a) Only a growth plan (b) Only a dividend plan (c) Both a growth and a dividend plan (d) All of the above 198.Balanced funds have investments in (a) Equity (b) Debt (c) Both equity and debt (d) Short term instruments 197.The NAV of a fund is based on (a) Cash basis (b) Accrual basis (c) Income basis (d) None of the above 195. buy decision. which is (a) Higher than buy alternative (b) Lower than buy alternative (c) Same as with buy alternative (d) Could be any of the above 205. the asset should be (a) Leased (b) Bought (c) Neither leased nor bought (d) (Incomplete information) 204. then the asset should be (a) Leased (b) Bought (c) Neither leased nor bought 203. (d) Commercial Banks 206.If the NPV of both buy alternative and incremental lease effect is positive.While considering the lease vs.The ______ is the lender of last resort (a) RBI (b) SEBI (c) Central Govt.The following mortgage is quite common among bankers (a) Simple mortgage (b) Mortgage by deposit of title deeds (c) Equitable mortgage (d) B and c 202.If the NPV of buy alternative is positive and NPV of incremental lease effect is negative.A combination of two or more investment types is called a (a) Usufructuary mortgage (b) Equitable mortgage (c) Anomalous mortgage (d) None of the above 201. the incremental lease cashflow should be discounted at a discount rate.200.Prepayment of personal loan in a falling interest rate scenario will attract (a) No charges (b) Penal charges (c) Additional benefits (d) None of the above Financial Planning Academy 45 . salvage value can be claimed by (a) Lessee (b) Lessor (c) Neither (d) Either 212. hire-purchase (a) Is more cumbersome (b) Charges more interest (c) Allows transfer of ownership when all installments are paid (d) All of the above 213.207. ownership of assets passes on to hirer (a) On commencement of the hire-purchase agreement (b) On completion of installments (c) On cash down payment (d) None of the above 209. the refinancing arm is primarily (a) RBI (b) Regional rural banks (c) Commercial banks (d) Nabard 208. Depreciation is charged.Entire hire-purchase installment is tax deductible as an expense (a) The above statement is true (b) The above statement is false (c) Only the interest expense is tax deductible (d) A and c 211. by the (a) Hirer (b) Hiree (c) Either.As opposed to installment sale.For the rural sector.The security for a consumer loan is usually (a) A guarantee (b) A pledge agreement (c) Post-dated cheques (d) All of the above Financial Planning Academy 46 . based on the agreement (d) Depreciation is disallowed 210.In hire-purchase. in a hire-purchase agreement.In a lease transaction. the interest (a) Goes on decreasing (b) Goes on increasing (c) Remains the same (d) None of the above 215.214.Liquidity is needed (a) To avail discounts (b) To ensure smooth running of day to day life (c) To ensure peace of life (d) All of the above 218.The term structure of interest rates refers to (a) The interest rates in the longer term (b) The interest rates applicable to a term loan (c) The interest rates in the shorter term (d) Existence of different interest rates at different maturities Financial Planning Academy 47 . Consumer credit is prompted by (a) Consumerism (b) Contingency (c) Children’s education (d) All of the above 217.The yield to maturity of a bond may also be called its (a) Interest rate (b) NPV (c) IRR (d) None of the above 220.An emergency fund could be kept in the form of (a) Gold and silver (b) Saving bank account (c) Fixed deposits (d) b & c 216.When a loan is repaid by equated monthly installments.An aberration in the normal yield curve would be when (a) Long term interest rates are below short term rates (b) Long term interest rates are above short term rates (c) Long term interest rates are same as short term rates (d) None of the above 219. The minimum numbers of members of a society are (a) No minimum is prescribed (b) 10 (c) 20 (d) 7 Financial Planning Academy 48 .Short-term interest rates are lower usually because: (a) Greater risk is associated with the longer term (b) Short term investments imply higher liquidity (c) Investors are concerned about inflation in the longer term (d) All of the above 222.The principal amount of a trust is called (a) The fund (b) The corpus (c) The kitty (d) None of the above 225.A trust created by a will to manage the deceased’s assets is called (a) A revocable trust (b) A irrevocable trust (c) A testamentary trust (d) A charitable remainder unitrust 226.Deflation is (a) A boon (b) Good for developing economies (c) A phenomenon which has a number of negative aspects (d) Good for developed economies 223.Deflation is bad because (a) It reduces profits (b) Debt becomes excessive (c) a and b (d) None of the above 224.A probate is (a) A special type of trust (b) A joint trust (c) A trust formed under the Indian Trusts Act (d) Distribution of estate under court supervision 227.221. 228.Corporations are formed under (a) The Companies Act (b) An Act of Parliament (c) Both a) and b) (d) None of the above 230. (b) The property belonging to a society (c) Both a) and b) (d) None of the above 229.Example/s of national trade associations are (a) FICCI (b) CII (c) ASSOCHAM (d) All of the above 232. 1860 (c) The Companies Act (d) None of the above 230. addresses and occupations of its governors etc.In the interest of investor protection.The following is not a way of taking title to property (a) By gifting (b) By exchange (c) By mortgage (d) None of the above 233. SEBI carries out (a) Market surveillance (b) Action against intermediaries (c) Action against erring companies (d) All of the above 234.The memorandum of a society contains (a) The names.Market surveillance activities of SEBI are mainly concerned with (a) Merchant bankers (b) Erring companies (c) Stock exchanges (d) Department of Company Affairs Financial Planning Academy 49 . 1882 (b) Societies Registration Act.Professional associations are formed usually under the (a) Indian Trusts Act. A small depositor is defined under the Companies Act as one who (a) Deposits less than Rs.000 in a year (b) Deposits less than Rs. 20.000 in a year (d) Deposits less than Rs.000 in the last two years (c) Deposits less than Rs.Some of the market surveillance systems already in place by SEBI are (a) Daily price bands (b) Inspection of intermediaries (c) Both a and b (d) None of the above 236.000 in each of the last two years 239.235.Deposits are normally allowed to be accepted as a multiple of (a) Paid up capital (b) Networth (c) Sales (d) None of the above 238.Fiduciary relationship requires (a) The use of the word trust (b) A written agreement (c) A constructive trusteeship (d) None of the above Financial Planning Academy 50 .An advisor stands in a fiduciary position to his client (a) True (b) False (c) True if there is a written contract (d) False if there is an agreement to the contrary 240.Any advertisement soliciting fixed deposits from the public must contain (a) Paid up capital (b) Networth (c) Balance sheet size (d) None of the above 237. 50. 50. 10. (c) Advice is distinguishable from a recommendation. higher price levels and money wages and rising employment and national income is (a) Boom (b) Contraction (c) Recession (d) Recovery 5 Which of the following is not normally an influence upon short term interest rate? (a) Movements in the current account deficit (b) The trend of interest rates overseas (c) Fiscal policy (d) The rate of long term unemployment Financial Planning Academy 51 . (b) A principal advisor is liable for actions of representative.5 1 Which of the following is true in regard to a Financial Planner’s liability? (a) A disclaimer removes all liability. (d) An advisor may be held liable for failure to predict economic changes 2 Which of the following is not a license/certificate according to present licensing regulations? (a) Stock-broker (b) Sub-broker (c) Insurance agent (d) All of the above are licensees/certificates 3 Which of the following tests apply to reasonable basis for recommendations? (1) Know your client (2) Obey Trade Practices Acts (3) Know relevant rules and regulations (4) Know your products (a) 1&2 (b) 2&3 (c) 3&4 (d) 1&4 4 The stage of the business cycle which is marked by increased consumer and investment spending.PART. 3&4 1.3&4 Financial Planning Academy 52 .2. it is (a) Monetary policy (b) Fiscal policy (c) Incomes policy (d) Exchange rate policy 7 Which of the following measures is most widely used as an indication of inflation? (a) GDP (b) WPI (c) CPI (d) None of these 8 Assuming all other things being equal. if the government increases the circulation of money.6 When the government decides economic policy through the budget. which has no saving element or cash value.&3 3&4 2. is: (a) Term insurance (b) Whole of life policy (c) Endowment policy (d) An annuity 10 What would be the main reason for a small investor using a mutual fund instead of direct investment in shares? (a) Lower market risk (b) Lower charges (c) Access to broad asset allocation (d) Higher returns 11 Which of the following are steps used in preparing a financial plan? 1 Goal setting 2 Identification of financial problems 3 Preparation of alternatives/recommendations 4 Implementation of agreed recommendations (a) (b) (c) (d) 1. interest rates will: (a) Increase (b) Decrease (c) Stabilize (d) Remain unaffected 9 A life policy.2. A is false but B is true. disclosures regarding compensation needs to be made only at the time of establishing the relationship with a new client. 14 Which of the following is true? (A) A professional financial planner provides only comprehensive financial advice to clients encompassing estate planning.12 Which of the following applies at the time alternatives and recommendations are made? (a) The plan should be flexible enough to cope with the client’s situation should it change in any way (b) The main focus should be on the performance of recommended investments (c) The client should be asked to think about plans for the future (d) All of the above 13 A statement of advice is not needed in providing limited financial planning advice. (a) True (b) False (c) Sources of compensation need not be disclosed. by definition financial planning is comprehensive. income and expenditure (cash flow). (a) (b) (c) (d) Both A &B are false A is true but B is false. (B) A professional financial planner may provide limited advice. (b) The above statement is true. (a) There is no such thing known as a statement of advice. (d) Need to be disclosed whenever there is a change in status Financial Planning Academy 53 . retirement benefits. investment planning and taxation. (c) The above statement is False (d) There is no such thing as limited financial planning advice. insurance planning and risk management. A is true provided. the financial planner is a CFP 15 A professional financial planner is one who (a) Takes pride in his/her work (b) Is committed to quality (c) Is dedicated to the interest of the client (d) All of the above 16 According to the FPSB rules of professional conduct. if he discloses the fact at the outset to the client. Financial Planning Academy 54 . hirer (c) Lessor. hirer (d) Lesses. lessee (b) Lessees. nominal rates are ---------than real interest rates (a) Higher (b) Lower (c) Equal (d) None of these 20 Legislation risk ---------. lessor (Hirer will become owner after certain number of years.capacity as regards client’s funds (a) Trustee (b) Beneficiary (c) Fiduciary (d) Professional 19 In periods of inflation. (a) Can be (b) Can’t be (c) Legislation does not have any impact (d) None of these 21 --------is entitled to claim depreciation but not a --------(a) Hirer.the bond price will become (a) 1000 (b) 750 (c) 1333 (d) None of these.minimized by diversifying investments across sectors.17 Any personal information about the client may not be used by the financial planner except. (a) Unprofessional (b) Advertising (c) Smart thinking (d) Waste of time 18 A CFP certificant shall act in a ------. lessee is tenant) 22 A bond with a coupon rate of 8% is available at its face value of Rs 1000. If the market rate of return on an investment with similar risk goes down to 6%. 60=5%) 26 The code of ethic of integrity details conduct rules relating to (a) Member’s compensation (b) Promotional activities (c) Client’s funds (d) B & C 27 The code of ethics of fairness requires (a) That compensation of a financial planner be fair and reasonable (b) That partners in a financial planning firm should act in good faith (c) That a member may provide reference of other clients to establish a relationship (d) All of the above 28 An FPSB member is required to keep all office/client records for a period of ---years (a) Four (b) Seven (c) Eight (d) Five 29 Professional responsibility is based on (a) Contractual obligation (b) A duty of care to the client (c) Fiduciary relationship (d) All of the above Financial Planning Academy 55 .the effective yield on the bond is (a) 10% (b) 8% (c) 12% (d) None of these 24 ALC In the context of cash flow planning and budgeting refers to (a) Average living costs (b) Annual living cashflow (c) Annual living costs (d) None of these 25 If the inflation rate is 3% and the tax rate is 40%.23 A bond with a coupon rate of 10% is available at Rs 1250.The face value of the bond is RS 1000. the required rate to maintain the value of an investment is (a) 4% (b) 5% (c) 6% (d) 7% (Required rate is =Inflation/(1-tax rate)=3/. . A plans to invest Rs 10000 today for a period of 4 years.30 A contract may be discharged by (a) Performance (b) Impossibility of performance (c) Breach (d) All of these 31 Mr. (a) Simple mortgage (b) Usufructuary mortgage (c) English mortgage (d) All of the above 33 A combination of two or more mortgage types is called a (a) Usufructuary mortgage (b) Equitable mortgage (c) Anomalous mortgage (d) None of these 34 The yield to maturity of a bond may also be called its (a) Interest rate (b) NPV (c) IRR (d) None of these 35 As part of their job.a. If interest rate is 10% p. financial planners have to predict future economic indicators which may impact clients (a) True (b) False (c) It is true in cases of economic turmoil (d) The statement is true for CFP Certificants 36 Micro-economics refers to the study at (a) National level (b) Level of the firm (c) Personal level (d) b & c Financial Planning Academy 56 . how much income per year should he receive to recover his investment? (a) Rs 3155 (b) Rs 2500 (c) Rs 2800 (d) Rs 3000 32 The following type of mortgage does not require possession to be handed over to the mortgagee. 15% (d) 8. (a) Contraction (b) Recession (c) Recovery (d) Boom 38 Asset allocation strategy is guided by (a) Portfolio diversification (b) Client’s risk profile (c) Objectives of the client (d) All of the above 39 The following is not an essential component of a financial plan (a) Executive summary (b) Financial planning strategy (c) Letter of engagement (d) Summary of services provided 40 A bank has offered to you an annuity of Rs 1800 for 10 years . The present value of the bond is---------------.37 High level of employment. exercise is possible (a) Only at the date of expiry of option (b) At any time before the expiry of option (c) At any time until the expiry of the option (d) None of these Financial Planning Academy 57 .a.67% ( Pv= -12000. 10= n. compute I) 41 In 2002. higher costs for business firms are indicators of which stage of the business cycle. 1800=pmt. faltering business.67% (b) 8% (c) 8. coupon rate payable at the end of each year during the life of the bond.if the Required rate of return is 14% (a) Rs 10000 (b) Rs 9500 (c) Rs 2758 (d) Rs 15000 42 In an American option . X Ltd has issued bonds of Rs 10000 each due in 2012 with a 14%p. If you invest Rs 12000/today the effective rate of return in this case is (a) 6. slackening rate of investment activity. 43 In a PUT option . (d) Obligation but not the right to buy a specified asset at a specified price at or within a specified price 44 Integrity implies (a) Members shall provide financial planning services in a fair and irrevocable manner (b) Members shall use high standards of honesty in conducting their financial planning business. fee and commission etc (d) Projections (e) All of the above are essential components 46 A financial plan should be reviewed in the light of (a) Micro and Macro level changes (b) Micro and not Macro level changes] (c) Macro and not Micro level changes (d) Generally the financial plans do not require review 47 Which of the following risks falls under the category of Pure risk that people face. at OR WITHIN A SPECIFIED PRICE. (a) Loss of use of property (b) Risk of injury (c) Loss arising from negligence of third party (d) Risk of loss of income through incapacity to work for some extended work (e) All of the above Financial Planning Academy 58 .there is a (a) Right but not the obligation to sell a specified asset at a specified price or within a specified price. (b) Right but not the obligation to buy a specified asset at a specified price. (c) Members shall disclose to their client any limitation on their inability to provide objective financial planning services (d) All of these 45 Which of the following is not an essential components of a written financial plan? (a) Statement of current situation (b) Financial plan summary (c) Services. (c) Obligation but not the right to sell a specified asset at a specified price or within a specified price. 90% (b) 10.The Yield to Maturity of this bond is (a) 9.40% (c) 11. Its value in today’s market is Rs 900.00% (e) None of these Financial Planning Academy 59 .90% (d) 11.48 Which of the following is generally excluded in goal setting step in financial plan development? (a) Cash flow analysis (b) Determining financial objectives (c) An assessment of priorities (d) Establishing basic needs 49 A CFP Certificant will cooperate with FPSB in all respects of an investigation is a requirement of code of ethic of (a) Professionalism (b) Diligence (c) Compliance (d) Confidentiality 50 A Rs 1000 bond has a 6% annual coupon and is due in two years. 38) 2 Mr X receives a PF amount of Rs 1.60.92 Pmt) 9 What is the present value of Rs 2.000 receivable annually for 30 years? The first receipt occurs after 10 years and the discount rate is 10%. He deposits it in a bank which pays 10% interest.18 years) 4 If you deposit RS 5000 today at 12% rate of interest. If Mr Jingo expects to live for 15 years and the interest rate is 15%.000.58 years) 5 A finance company offers to give Rs 8000 after 12 years in return for Rs 1000 deposited today.000 for how long he can do so? (7.000 per year towards loan amortisation. in how many years will this amount grow to Rs 1.6 QUESTION BANK FOR PRACTICE. What should be the maturity period of the loan? (30.000 at an interest rate of 14%. (7268.00.000? (30. You can pay Rs 2.27 years) 3 You want to borrow Rs 15. If he withdraws annually Rs 20. X deposits Rs.1.000. Assume that at the end of 30 years the amount deposited will whittle down to zero.00.FINANCIAL MATHEMATICS 1 You save Rs 2000 a year for 5 years. which option appears more attractive? (option (a) is better PV Rs 58473.000 to buy a flat. Mr Jingo is given a choice between two alternatives: (a) An anuual pension of Rs 10. Figure out the approximate interest offered.92%) 6 A finance company advertises that it will pay a lump sum of Rs 10000 at the end of 6 years to investors who deposit annually Rs 1000.00.PART. How much can he withdraw annually for a period of 30 years.70) 8 Mr.00. (Rs10607.What interest rate is implicit in this? (20.00. (18. Prepare the loan installment amount? (Rs 171602 –Pmt per annum) Financial Planning Academy 60 .000 as long as he lives and (b) A lump sum amount of Rs 50. You approach a housing company which charges 13% interest. The loan is to be repaid in 4 equal annual installments payable at the end of each of the next 4 years . How much these savings will grow into? Assume a rate of interest of 10% (Rs 79482.28%) 7 At the time of his retirement .96 PV) 10 Phoenix company borrows Rs 5.000 in a bank which pays 10% interest. and Rs 3000 a year for 10 years thereafter. (a) 12 (b) 6 (c) 8 (d) 9 (e) 72 5 The term structure of interest rates plots yield verses: (a) All maturities of a particular risk class of bonds at a point in time.180000 (after selling expenses etc) when you sell in 8 years.22.50 per share in dividends and expects these dividends to grow at 6% per annum forever. Investors require a return of 13% on stocks of equivalent risk.67 (Hint: P=D1/r-g where D1 is=D0(1+g).01% 3 What is the value of stock in a company that pays out Rs. (a) Rs. What is your expected rate of return on this property? (a) 17.70 (c) Rs. (b) A single maturity of a particular risk class of bonds of time (c) All maturities of one category of bonds at a point in time (d) All risk classes of bonds at a point in time Financial Planning Academy 61 .67 (d) Rs.36% (d) 17.000 in a commercial real estate property and expect to get Rs.43 (b) Rs.20.63% (b) 18. His topmost priority should be: a) Retirement Planning (b) Income protection (c ) Life Insurance (d) Critical Illness 2 You invest Rs.1.7 1 There is a 25 years old male with no dependants and nominal income.36% (c) 17.Part . g = growth rate D0=dividend for current year) 4 The “Rule of 72” says that if you earn 8% per year. your money will double in -----years.r =required return.50.20.21. the bonds will be priced at (a) Below par (b) Above par (c) Above and below par (d) At par 10 Which of the following best describe a debenture? (a) A long term corporate promissory note (b) An investment in the debt of another corporate entity (c) A long term corporate debt obligation with a claim against securities rather than against physical assets (d) A corporate debt obligation that allows the holder to repurchase the security at specified dates before maturity.6 Mr.25 (d) 8.75 Financial Planning Academy 62 . He purchased the bond at par ( Rs.1000). (a) 8. If the investors’ required rate of return (IRR) on these bonds is 9%.5 (b) 9 (c) 9. (e) Unsecured corporate debt 11 The new Senior citizen’s Savings Bond scheme offers ---------------% interest. If rates fall to 9% what will be the new price of the bond? (a) 1053 (b) 1136 (c) 1193 (d) 900 7 Beta --------------------(a) Is a measure of firm specific risk (b) Is a measure of market risk (c) Is a measure of total risk (d) Is calculated by regressing the market return on the historical market divided yield (e) All of the above are true 8 Firm specific risk is also called --------(a) Market risk (b) Macro risk (c) Undiversifiable risk (d) Non systematic risk (e) Unavoidable risk 9 Six years ago ABC Ltd issued 10 years bond with a coupon rate of 11%. Gupta purchased a 2 year bond bearing a 12% coupon rate. (A) Bank deposit rate (B) Bank lending rate (C) Certificate of deposit rates (a) A (b) B (c) C (d) None of these 14 The recent Union Budget exempts---------------. Consumer durable goods C.------------100000 145000 150000 16 -------------is /are governed by SEBI. Services (a) a and c only (b) a and b only (c) b and c only (d) c and d only (e) b and d only Financial Planning Academy 63 .is regulated by The Reserve Bank Of India . Consumer non durable goods D. Capital goods B. (a) Equity shares (b) Debt mutual funds (c) Property (d) Gold 15 (a) (b) (c) The deduction from Gross Total Income available u/s 80C is Rs. (a) Mutual Funds (b) Stock brokers (c) Portfolio managers (d) All of the above 17 As far as employment and production are concerned which of the following industries are more affected by recession? A.from Long term Capital Gains tax subject to certain conditions.----------70000 60000 80000 90000 13 -----------.12 (a) (b) (c) (d) The maximum amount that can be invested in Public Provident Fund is Rs. 34% (b) 28.00% (c) 22. X invests in a limited partnership. 3) Lowers average cost per share over a period of time (assuming share price fluctuations) 4) Invests the same rupee amount each month to protect the investment from loss of capital (a) (1) & (2) only (b) (1) & (3) only (c) (2) & (3) only (d) (2) & (4) only (e) (1) (2) (3) & (4) only 19 Which of the following are fundamental regarding characteristic of insurance? 1) Probability of loss 2) Law of large numbers 3) Transfer of risk from individual to group 4) Insurance is a form of speculation (a) 1 and 2 only (b) 1 2 and 4 only (c) 1 2 and 3 only (d) 4 only (e) 1 2 3 and 4 20 Mr. 2) Purchase the same number of shares each month over a period of time. Year Cash Flows (Rs.9400 today. At the end of years 1 through 5 he will receive the after tax cash flows of shown below.18 Which combination of the following statements is true regarding the investment strategy known as “ rupee cost averaging”? 1) Invests the same rupee amount each month over a period of time.25% Financial Planning Academy 64 . which require an initial outlay of Rs.) 0 (-9400) cfj 1 600 2 2300 3 2200 4 6800 5 9400 The after tax IRR of this investment is : (a) 23.94% (d) 24. Identify preliminary goals 2. 1. Monitor financial plans 3. equal to or greater than (depending on the correlation between securities) 24 According to the fundamental analysis. Prepare financial plan 4. plans and products 5.21 A client with a large well diversified common stock portfolio expresses concern about a possible market decline. Collect. Implement financial strategies. The possible strategy for him would be (a) Buy an index call option (b) Sell an index call option (c) Buy an index put option (d) Sell an index put option (e) He cannot protect against the decline with these options 22 Arrange the following financial planning functions into the logical order in which a professional financial planner performs these functions. and evaluate client data (a) 1 3 5 4 2 (b) 5 1 3 2 4 (c) 1 5 4 3 2 (d) 1 5 3 4 2 (e) 1 4 5 3 2 23 The standard deviation of the returns of a portfolio of securities will be --------the weighted average of the standard deviation of returns of the individual component securities (a) Equal to (b) Less than (c) Greater than (d) Less than or equal to (depending on the correlation between securities) (e) Less than. which phrase best describes the intrinsic value of a share of common stock? (a) The par value of the common stock (b) The book value of the common stock (c) The liquidating value of the firm on a per share basis (d) The stock’s current price in an inefficient market (e) The discounted value of all future dividends Financial Planning Academy 65 . analyze. However he does not want to incur the cost of selling a portion of their holdings nor the risk of mistiming the market. Interview clients. 1. Purchasing power risk (a) (b) (c) (d) (e) 456 123 562 134 146 Financial Planning Academy 66 . Coefficient of variation 5. Management risk 3. the value of common stock(everything else being equal) would (a) Not change because this does not affect stock values (b) Increase in order to compensate the investor for increased risk (c) Increase due to higher risk free rates (d) Decrease in order to compensate the investor for increased risk (e) Decrease due to lower risk free rates ( risk is related to return. Market risk 5. Beta (a) 5 1 (b) 1 3 (c) 1 4 (d) 1 5 (e) 2 5 27 Which of the following is non-diversifiable risk? 1. while the Treynor Index uses-------------------. Variance 3. the Sharpe index uses---------. otherwise with increased risk nobody will be interested to purchase this share) 26 In computing portfolio performance. therefore price will decrease to provide compensation to new investors. Business risk 2. Standard deviation 2. Interest rate risk 6.for the risk measure. Correlation coefficient 4. Company or industry risk 4.25 If the market risk premium were to increase. 91000 at the end of 19 and 21 years and if the discount rate is 6%.S. Eliminate currency risk 3. Trade foreign securities in U. Finance foreign exports 2. which of the following actions taken by RBI will not increase the bond prices significantly? (a) Selling of Treasury –Bills at low rates (b) Move to privatize and improve tax collections (c) Deficit financing Financial Planning Academy 67 .S. markets (a) 1 3 (b) 1 4 (c) 2 4 (d) 4 (e) 1 2 4 29 If R is the real return. then the formula for calculation of R is: (a) R= r-1 (b) R=1-(r+1)/(r-1) (c) R=1+(R+1)/(r-1) (d) R={(1+r)/(1+I)}-1 30 As a Certified Financial Planner. r is the portfolio return and I is the rate of inflation. securities in overseas market 4. In the circumstances as per code of ethics: (a) You have not violated the code as the product suits the best interest of the client (b) Violated the code as the client is not able to comprehend the product (c) The policy can be cancelled and fresh policy can be issued 31 The “Convertible Term Assurance policy” means: (a) The policy can be surrendered after sometimes for cash value (b) The policy can be converted into endowment plan (c) The policy can be cancelled and fresh policy can be issued 32 You are likely to receive Rs.28 American depository receipts (ADR) are used to 1. what is the present value? (a) 54862 (b) 54678 (c) 54863 (d) 51234 (28093. Sell U.85000 and Rs. but the client is not able to comprehend the product. you have selected a “product” which will be most suitable to the clients’ requirement.14 respectively) 33 In the regime of “soft interest”.61 and 26768. 34 You wish to save for your daughter’s education. it will result in (a) Increase in transaction costs (b) Decrease in transaction costs 37 The difference between Estate planning of a salaried employee and self employed person: (a) Both have to provide for dependants (b) Have to write wills (c) Take insurance policies (d) Employee benefits 38 How many years will it take fort a sum of Rs.a. The portfolio will have low risk 2. If your daughter is 10 years old and is likely to be in the college in another 8 years time. you make the following remarks: 1. what is the amount of investment to be made if it is likely to earn 11% return? (a) 178936 (b) 179836 (c) 173896 (d) 178930 ( calculate FV of Rs.5 (b) 8.240000 @7% for 8 years =412364.10000 to double if the rate of return is is 9% p. then calculate PV FOR THE SAME) 35 While choosing a product for your client which involves investment predominantly in Government securities. (a) 9.5 (c) 10 (d) 9 (e) 8 Financial Planning Academy 68 . the present cost of which is around Rs. which of the following are incorrect as it is violative (a) Statement A (b) Statement B (c) Both (d) None 36 If you are managing a balanced portfolio and frequent changes are made in allocation of assets. The rate of return earned by the fund in the past is 8% In the light of AFP Code of ethics.240000 and is expected to grow every year at the rate of 7%. 81% (b) 3.0% (c) 2. the real rate of return is (a) 3. (a) Volatility (b) Default (c) Inflation (d) Price (e) Currency 42 Refinancing is -------------------(a) Borrowing at lower cost in order to pay off higher cost debt (b) Repaying debt by selling off assets (c) Lending at a higher rate of interest (d) Securitizing your receivables (e) None of these 43 -------------------Asset allocation is not a text book Asset Allocation Model.86% (d) 2. (a) Tactical (b) Discretionary (c) Strategic (d) All of the above (e) None of the above Financial Planning Academy 69 . They are on the verge of a divorce. The Housing Finance company will--------(a) Not interfere as long as the EMI’s are being paid on time (b) Repossess the house after divorce (c) Insist on the house being transferred to one of them (d) Mediate reconciliation between the couple (e) Increase the interest rate in order to compensate for the increased risk 41 Domestic GOI bond holders (holding them up to maturity) have to deal with ---------risk.39 If the post tax rate of return on an investment is 9% and the inflation rate is 5%.74% 40 Radha and Ram are co-applicants of a mortgaged house. 100.06 46 A 10 year 9% bond (face value of Rs. To start an investment plan for funding their child education 2.08 6.10 (c) 108.03 (d) 6.58 (d) 107. To set up a Testamentary trust for their child 3.10000 at the beginning of every six months period to fund his purchase.50000 and he intends to contribute Rs. Assuming that the annual investment rate of return is 8% compounded semi-annually.11 6. His investments are currently worth Rs. To purchase life and health insurance (a) (b) (c) (d) 35142 45231 24513 25134 45 For a nominal interest rate of 6% payable monthly.interest paid annually) maturing 3 years from today is available at a YTM of 5. quarterly and semi annually.13 6. Some of their needs are 1.10 6.00 47 Aman wants to purchase a car 5 years from now.04 6.07 6. what will be the value of the investment in 5 years time? (a) 198875 (b) 195555 (c) 197240 48 Neelu wants to accumulate Rs. To set up a contingency fund amounting to 6 months’ of living expenses 4. Their funds are limited and their needs are many. how much must she invest today in order to achieve her goal? (a) 117591 (b) 119487 (c) 118274 Financial Planning Academy 70 .09 (c) 6.44 Ram and Shyam approach you to be their financial planner. Therefore the current price is ---------(a) 152. the effective rates respectively would be--------------(a) 6. To start saving for retirement 5.01 (b) 6.50 (b) 154. compounded quarterly.02 6.150000 in 3 years time for a one month trip to Europe. Assuming she can get an 8% annual return on her investments.8%.16 6. What did he receive on maturity? (a) 676774 (b) 776774 (c) 931095 (d) 609870 50 A contract with a minor is (a) Is voidable at the option of either party (b) Is absolutely void (c) May be admissible in special cases (d) None of these 51 Inchoate instruments are (a) Currency notes in circulation (b) Bills of exchange (c) Signed blank cheques (d) Signed blank stamp papers 52 Tort does not cover (a) Civil wrong (b) Breach of contract (c) Defamation (d) None of these 53 An investor expects a perpetual sum of Rs.49 Rohan invested Rs.50000 annually from his investment. What is the present value of this perpetuity if rate is 10% p.a.15 Lakhs (b) Rs.10 Lakhs (d) None of these 54 A combination of two or more mortgages is called (a) Usufructuary mortgage (b) Equitable mortgage (c) Anomalous mortgage (d) None of these 55 Liquidity is needed (a) To avail discounts (b) To ensure smooth running of day to day life (c) To ensure peace of mind (d) All of the above Financial Planning Academy 71 . (a) Rs.420000 for 7 years @7% where it was compounded annually for the first 5 years and quarterly for the last 2 years.5 Lakhs (c) Rs. 10000 in each of the two years 59 If a planner does not receive sufficient and relevant information from a client he/she should (a) Terminate the relationship (b) Give restricted (limited) advice (c) Go ahead but give a disclaimer disclaiming all responsibility (d) Either a or b 60 The client questionnaire records quantitative data and-------------------records qualitative data (a) The planner’s mind (b) File notes (c) The same client questionnaire (d) A separate client questionnaire 61 A strategic review of a client’s situation is required in case of (a) Macro level changes (b) Micro level changes (c) Neither (d) Both 62 A letter of engagement is : (a) A legal document (b) A requirement of the AFP ‘s rules of professional conduct (c) Essential for client-planner relationship (d) Like a memorandum of understanding Financial Planning Academy 72 .56 Deflation is (a) A boon (b) Good for developing economies (c) A phenomenon which has a number of negative aspects (d) Good for developed economies 57 A probate is (a) A special type of trust (b) A joint trust (c) A trust formed under the Indian Trusts Act (d) Distribution of estate under court supervision 58 (a) (b) (c) (d) A small depositor is defined under the Companies Act as one who Deposits less than Rs.20000 in a year Deposits less than Rs.50000 in the last two years Deposits less than Rs.50000 in a year Deposits less than Rs. 63 Which of the following can generally be excluded from the definition of “ securities” for general purposes? (Is it from the point of view of Non-tradable “ securities”) (a) A prescribed interest in a unit trust (b) An option contract (c) Interest in a business undertaking (d) Bank certificate of deposit 64 A client of a financial planner who sustains losses and claims the financial planner is at fault. may be able to base a claim under: (a) Law of contract only (b) Law of tort only (c) The law of contract and the law of tort (d) Criminal law 65 The goal setting step in financial plan development would generally not include which of the following? (a) Determining objectives (b) Cash flow analysis (c) Assessing priorities (d) Establishing basic needs 66 Client risk profiling by questionnaires is best used (a) Rather than indirect method s of assessing client risk (b) As an equally valid method of assessing risk compared to more indirect methods (c) As a supplementary adjunct to other means of assessing risk (d) As the only way of assessing the risk profile for the client 67 The principle of subrogation means that: (a) An insurer may bring an action against a third party in the name of the insured after satisfying a claim (b) An insured may not take legal action in respect of a matter which is the subject of a claim (c) An insurer undertakes to take legal action on behalf of its insured and to pay to the insured the net proceeds of such legal action (d) An insurer which has satisfied a claim may recover from the insurer of a third party who admits liability Financial Planning Academy 73 . 55 call options (c) Buy Rs.00% 70 Amount received from the surrender of annuity plan or amount received as pension from the annuity plan by the assessee or his nominee shall be (a) Exempt (b) Taxable (c) Exempt upto limit balance payable (d) None of the above 71 Deductions under section 80D in respect of medical insurance premium is allowed to (a) Any assessee (b) An individual or HUF (c) Individual or HUF who is resident in India (d) Individual only 72 Sudha is optimistic about the long term growth of her share.55 put options (d) Sell Rs.68 The distinction between a futures contract and an options contract is : (a) A futures contract imposes an obligation on the buyer and the seller while an options contract imposes an obligation on the seller only and confers a right on the buyer (b) A future contract imposes an obligation on the buyer and the seller while an option contract confers a right on both buyer and seller but not the obligation (c) A futures contract confers a right on the buyer and seller while an options contract imposes an obligation on the seller only and confers a right on the buyer (d) A futures contract confers a right on the buyer and seller while the options contract confers an obligation on both buyer and seller 69 A firm purchases a machinery for Rs.55 call options (b) Sell Rs.85% (d) 11.800000 by making a down payment of Rs.02% (b) 10.55 put options Financial Planning Academy 74 . What might Sudha do? (a) Buy Rs. However the share price currently priced at Rs.150000 for 6 years. has made a sharp advance in the last week and she wants to lock in minimum price in case the shares drop. How much is the rate of interest that the firm is paying? (a) 12.17% (c) 10.58.150000 and the remainder in equal annual installments of Rs. Which one of the following entities would be impacted most by this decline in portfolio value? (a) Individual participants in the plan (b) Company sponsoring the plan (c) Investment banker handling the plan (d) Plan underwriters 75 Which of the following would result in the largest increase in the price of a diversified common stock mutual fund? (a) Unexpected inflation (b) Expected dividend increases (c) Unexpected corporate earnings growth (d) Expected increase in the prime interest rate 76 Compute liquidity Ratio. (b) In products which produce high income for the client because fixed income products are generally safe (c) In diversified mutual funds because of the protection which diversity provides (d) After determining the client’s risk tolerance. Salary=60000. which of the following is the most crucial action the planner needs to take to have the client achieve the goal of wealth accumulation? Advise investing the client’s current assets (a) In the products which will bring the highest return to the client regardless of risk. Cash expenses per month=30000. (e) In 100% cash equivalents in the portfolio because most software programs recommend this safe approach 74 The investment portfolio for a defined benefit retirement plan has declined in value during a year in which most financial market investments have incurred losses.73 If the client needs to accumulate wealth but is risk averse. Bank savings a/c 150000 (a) 4 (b) 5 (c) 2 (d) 6 77 A person who declare will after the death of a person is called (a) Testator (b) Executor (c) Testate (d) Deceased Financial Planning Academy 75 . At the end of every month he has to pay Rs.3000 for next three years. The implied interest rate per annum is (approx) (a) 20% (b) 25% (c) 28% (d) 35% (e) 42. As a financial planner what would you do instantly? (a) You will explain the logic of your decision to client (b) You will buy more shares (c) You will sell out those shares (d) No step you will take 79 If the loan of Rs. then the equated annual. you have purchased shares of a company.71967 (b) Rs. the present value of the cash flows if the inflows continue for 5 years at a required rate of 11% is (a) Rs.00.2003.78 Your client. now market fall.74005 (d) Rs.9624.9403.1000 for 12 months so that his loan will be totally repaid by December 31.20 (d) Rs.% 81 If the annual cash flow for a bond is Rs.85 (b) Rs. installment will be: (a) Rs.839 (d) Rs.50 (c) Rs.739 (c) Rs.76004 80 A person took a loan of Rs.3.639 (b) Rs.200.869 (e) Rs.2003.a.8860.72967 (c) Rs.10.75995 (e) Rs.9344.2000 for first three years and Rs.939 82 An income stream provides Rs.25 (e) Rs.00 Financial Planning Academy 76 .8650.000 is to be repaid in 6 annual installments with a coupon rate of 12% p.000 on Jan 1. if interest rate is 14%. then the present value of income stream is: (a) Rs. The loan is to be repaid in ten equal annual installments. then each installments is (a) Rs. compounded monthly.111. What is the present value of these cash inflows? (a) Rs.67200 (c) Rs.10000 is being borrowed to be paid in four equal annual payments with 8% interest. Suresh deposited Rs.83 Mr.00% (c) 6. if the interest rate is 12% p.00% (d) 7.50 Lakh (e) Rs. If the annual interest rate is 16%.2500 (d) Rs.10000 86 If a borrower promises to pay Rs.00% (e) 7.a.3281 (e) Rs. If his required rate of return is 12% p. Rahul expects to receive from his friend an amount of Rs.3300 Financial Planning Academy 77 .46 Lakh (c) Rs.20000 (b) Rs.500 Lakh from a bank. how much principal is amortized with the first payment? (a) Rs.1000 every month in a bank for five years.103.11300 (d) Rs.12550 today.42% 87 Rs.132. what interest rate is being offered? (a) 1.15000 (c) Rs.43 Lakh (d) Rs. then the accumulated amount he will get after 5 years is: (a) Rs.102.59% (b) 5.20000 eight years from now in return for a loan Rs.2000 per annum for 10 years.2219 (c) Rs.96000 84 XYZ Ltd had taken a loan of Rs.81600 (d) Rs.44955 (b) Rs.13 Lakh 85 Mr.10500 (e) Rs.78 Lakh (b) Rs.113.a. Approximately.800 (b) Rs.81670 (e) Rs. 00 earning a rate of interest of 12% p.4037 (d) Rs. for 5 years is equal to (a) Rs.42 (d) Rs.6..88 The future value of a regular annuity of Re.114.353 (c) Rs.24 (c) Rs.24 90 Money has time value because (a) The individuals prefer future consumption to present consumption (b) A rupee today is worth more than a rupee tomorrow in terms of its purchasing power (c) A rupee today can be productively deployed to generate real returns tomorrow (d) The nominal returns on investments are always more than inflation thereby ensuring real returns to the investors (e) Both b and c above 91 The present value of Rs.a.6.1000 for five years commencing from the end of first year is (a) Rs.114.1.425 (d) Rs.112.250 (b) Rs.3037 Financial Planning Academy 78 .112.6898 (c) Rs. at a discount rate of 10% is (a) Rs.6.42 (b) Rs. the amount to be invested today to earn an annuity of Rs.112.6.48376 92 If the interest rate is 12% p.6.3605 (e) Rs.a.5672 (c) Rs.3284 (b) Rs.1000 at the end of 6 years is equal to (a) Rs.00.44 (e) Rs.6353 (b) Rs.10.625 89 The amount that has to be invested at the end of every year for a period of 6 years at a rate of interest of 15% in order to accumulate Rs.39440 (e) Rs.18649 (d) Rs.000 receivable after 60 years .538 (e) Rs. (a) Rs95.134330 94 The amount to be invested today to earn an annuity of Rs.00. Has Rs.00 (c) Rs.99 (d) Rs97. Compute the value of the bond if the required rate of return is 16% (a) 94..96. The required return on this bond is 14%.000 worth of debentures to be redeemed after five years from now.29 (c) 95. the coupon rate is 13% of 8-year bond on which interest is paid semi-annually.000 (Hint: 1+yield/yield-number of payments/(1+yield)no of payments-1) page no-337 of Prasanna Chandra-bond valuation Financial Planning Academy 79 .980 (c) 5.3873 (e) Rs.30 (b) Rs.235 (d) 5.10.100 par value bond bears a coupon rate of 14% and matures after 5 years.93 M/S Lee Ltd.4873 95 Calculate the price of the par value Rs.1000 for five years commencing from the end of two years from today if the interest rate is 12% per annum is (a) Rs.3218 (b) Rs.96.5993 (c) Rs. If the interest rate is 14% p.291284 (d) Rs.661010 (b) Rs.25 (d) 93.50 (b) 93.90 97 A 10-year annual annuity has a yield of 9%. the amount that has to be invested every year in a sinking fund to retire the above bonds is (a) Rs.2874 (d) Rs.02 96 A Rs.151284 (e) Rs. Interest is paid semi-annually.798 (b) 4. What is the duration? (a) 4.a.100.343308 (c) Rs. 950 .50% (c) 12.1000 and selling for Rs.63% (b) 13.01% 100 The IDBI deep discount bond offers investors Rs.800.58% (d) 14. 12% coupon bond with a par value of Rs.1000 par value bond.00% (d) 13.50% (e) Not possible to determine from the given data Financial Planning Academy 80 .81% (b) 15.25% 99 A Rs. carrying a coupon rate of 9%. maturing after 8 years is currently selling at Rs.200000 after 25 years.98 Compute the current yield of a 10 year. The interest rate implied in the offer is (a) 14. (a) 12. What is the YTM of the bond? (a) 13.5000.90% (d) 16.2% (b) 14. for an initial investment of Rs.15% (c) 13.00% (c) 15. What is duration? (a) 7. It pays interest semi-annually.798 years (c) 5.Part .40% debt.90 years 1+y . There is a 35 year old man with a wife and 2 children aged 6 and 9 years. What is its duration? (a) 4.10% cash (d) 50% equity.350 years (d) 5. 10% cash (c) 60% equity. Its yield to maturity is 4% per half year period.(1+y)+T(c-y) (c) 8. His topmost priority should be: (a) Retirement Planning (b) Income protection (c) Life Insurance (d) Critical Illness 6 Observing an appropriate standard of care as a professional means that: (a) A mistake or error constitute a breach of standard (b) Standards are defined by the relevant professional body (c) Conformity with current professional standards is always sufficient (d) The professional is expected to demonstrate the standard of the ordinary person professing to have the skill Financial Planning Academy 81 .30% debt.20 years y c[(1+y)t –1]+y (d) 8.15 years 2 A 10 year annual annuity has a yield of 9%.10% cash 4. 10% cash (b) 90% long term debt. Their topmost priority should be (a) Retirement Planning (b) Income Protection (c) Life Insurance (d) Critical illness Insurance 5.56 years (b) 7. There is a 22 year old male with no dependants and nominal income.205 years 3 A well to do individual who has his needs taken care of and is well into his retirement should invest into (a) 90% short term debt.508 years (b) 4.8 1 A 10 percent coupon bond has a maturity of 12 years. Which of the following is an example of qualitative research? (a) Collecting data on the historic performance of funds (b) Comparing the returns from funds (c) Comparing the strengths and weaknesses of management (d) Ranking funds according to assets 12 A research house wishes to carry out quantitative research.7 In simple term the legal term negligence is : (a) Not acting as a reasonable person (b) A basis for liability (c) A breach of contract (d) The same as tort 8 Which of the following are not “securities” ( is it tradable security) (a) A prescribed interest in a unit trust (b) An option contract (c) Interest in a business undertaking (d) Bank certificates of deposit 9 You meet an analyst who believes that a share has specific intrinsic value that can be determined at any point in time. it will eventually move back to this value. Which of the following is an example of quantitative research? (a) Comparison of relative performance against fund managers (b) Comparison of product features (c) Consideration of quality of assets (d) Quality and experience of investment team Financial Planning Academy 82 . Such an analyst is : (a) Technical analyst (b) Fundamental analyst (c) Chartist (d) Speculative analyst 10 Performance measurement by benchmarking normally refers to comparing performance of a fund to: (a) The performance achieved by comparable investment funds (b) The result of key economic data (c) The results achieved by key investment indexes (d) The results achieved by recognized superannuation funds 11 A research house wishes to carry out qualitative research. She states that although the market price will differ from this intrinsic value. and A wishes to pay back the amount in 21 years.50% 15 The difference between the effective rate of return of a bond with a coupon rate of 12% when compounding monthly and quarterly is: (a) 0.5% p. Rate of interest to be charged by company is 8.a. He approaches a housing finance company and explains to them that his paying capacity is Rs.19 (e) 0. A wishes to purchase a house with the help of loan amount. It is either mandated or regarded as best practice under the FPSB Code of Ethics and Rules of Professional Conduct C. It is mandated under Company’s law B.03 (b) 0.000 from a housing finance company on an interest rate of 12% p.6. The terms of payment are Rs.00.00% (b) 10.38% (d) 10.a.100000 cash down and balance in 10 equal annual installments.10 (c) 0.13 (d) 0.25 16 Mr. If the compounding is done semi-annually. then effective annual interest rate is: (a) 10. X has taken a loan of Rs. It provides substantial protection from common law claims of negligence (a) c and d only (b) b c and d only (c) a b and c only (d) a b c and d only 14 The fixed deposit scheme of a bank offers 10% pa interest for a three year deposit. Calculate the amount of annual installment? (a) 106190 (b) 88492 (c) 95496 (d) 75000 17 Mr. Compute the amount of loan which can be availed by him? (a) 450000 (b) 442356 (c) 415376 (d) 415672 Financial Planning Academy 83 .3540 per month.25% (c) 10.13 All recommendations concerning the financial affair’s of a client should be presented in writing because: A. It gives the client the necessary time to fully consider the recommendations D. 66% (c) 5.9500.1% (d) 7.92% (c) 20.5% nominal rate of return while the real rate of return was 14%. has a 12% coupon and was sold for 980 when the inflation rate was 6% (a) 6. then the inflation rate was (a) 4.83% (b) 5.1000. what is the nominal annual rate? (a) 16.10 Lakh at the end of year 10 (a) 45363 (b) 48195 (c) 51714 (d) 65236 Financial Planning Academy 84 .87% then on a debt that has quarterly payments.a.36% 19 If a share of a stock provided a 19.95% 22 M/S D Ltd has placed a deposit of Rs.5% (c) 5.12% (d) 18.5000 with a company at 15% p. The interest rate implied in the offer is: (a) 19.5% 21 The IDBI deep discount bond offers investors Rs. interest being compounded semi-annually.22% (b) 18.00% (b) 5.85% (c) 19.320000 after 20 years.00% (e) 22.86% (d) 6. In three years her investment will grow to: (a) 7250 (b) 7344 (c) 7500 (d) 7604 (e) 7716 23 How much should a company invest at the beginning of each year at 14% so that it can redeem debentures of Rs. for an initial investment of Rs.93% (d) 21.18% 20 What real rate of return is earned by a one year investor in a bond that was purchased for Rs.78% (b) 18.18 If the effective rate of interest is 17. a.18000 per year for the next 10 years 26 If Rs. (a) 15849 (b) 14379 (c) 14916 (d) 15310 Financial Planning Academy 85 .) (a) Rs.464202 in 5 years when for the first 3 years compounding is annually and rate of interest is 9% and for the next 2 years compounding is done quarterly.5 (d) 1 25 Choose the one which gives the highest return among the following (assume interest @14% p.200000 after 6 years (c) Rs.1000 per month for a year and Rs.00% 27 An amount becomes Rs. Find the amount invested? (a) 430000 (b) 418484 (c) 418383 (d) 400000 28 Compute the present value of an amount which becomes Rs.a.a. compounded quarterly and in the 5th year compounding is done annually. (a) 290000 (b) 300000 (c) 310000 (d) 298000 29 Compute the present value of an annuity. in perpetuity (d) Rs.2000 per annum for 10 years when interest rate for the first 5 years is 5% and for the next 5 years is 8%.562778 in 5 years when for the first 4 years rate of interest is 6% p.24 A risk free stock has a beta of (a) -1 (b) Zero (c) 0.95% (d) 16.100000 now (b) Rs. find the annualized rate of return? (a) 16. which pays Rs.150000 in 2.5 years when compounding is done semi annually.50% (c) 15.100000 becomes Rs.15000 p.95000 at the end of the year (e) Rs.89% (b) 16. equity ratios (b) P/E ratios (c) Liquidity ratios (d) None of these 32 The Indian taxation system is: (a) Progressive (b) Regressive (c) Assertive (d) None of these (progressive means increase in tax rates with increase in income) 33 The CFP certificant will not indulge in any practices which are detrimental to the profession is a requirement of which code of ethics? (a) The code of ethics of fairness (b) The code of ethics of professionalism (c) The code of ethics of integrity (d) The code of ethics of compliance 34 Which of the following is true? (a) YTM is dependent on both interest income as well as capital gains (b) The closer to maturity.30 Total risk is measured by: (a) Beta (b) Standard deviation (c) Variance (d) Any of these 31 A company’s relative capital structure can be known from its (a) Debt. the less sensitive a bond is to interest rate risk (c) Callable debt is a debt that may be paid off early (d) All of the above are true 35 Why do firms issue debt? (a) Managers like to have debt on the balance sheet as it gives them more discretion as to investment than does equity (b) Debt has lower cost than equity (c) Debt decreases the financial leverage of the firm (d) None of these Financial Planning Academy 86 . 253.3913 (b) 0.5870 39 The standard deviation of the returns of a portfolio of securities will be ----------. You keep your money in a bank time deposit that pays a nominal annual rate of 5 %.700 at the end of each month for the next 9 months.500 at the end of each month for the next 12 months.62 (c) Rs.509.81 37 Four years ago ABC Corporation issued 10 years bonds with a coupon rate of 11%.4783 (d) 0. (a) Equal to (b) Less than (c) Greater than (d) Less than or equal to (depending on the correlation between securities) Performance fund 19% 23% Benchmark index 17% 21% Financial Planning Academy 87 .253. the bonds will be priced: (a) Below par (b) Above par (c) Above and below par (d) At par 38 Returns Standard deviation Risk free return 8% Calculate the Sharpe index of performance for the fund over the evaluation period.the weighted average of the standard deviation of returns of the individual component securities.36 On your lease you pay Rs.If the investors’ required rate of return (IRR) on this bond is currently 9%.30 (d) Rs. By what amount would your net worth change if you accept the new lease? (a) –Rs.5238 (e) 0. then rental payments of pRs.62 (e) Rs.81 (b) –Rs. (a) 0. which calls for zero rent for 3 months.4286 (c) 0.125. Now your landlord offers you a new 1-year lease.509. 12000 for 8 years at the rate of interest of 6%. (a) 19803.43 (b) 19174.50 (c) 20000. what is the amount of investment to be made if it is likely to earn 12% rate of return? (a) 205993 (b) 205670 (c) 210000 (d) 209553 41 The investment portfolio for a defined benefit plan has declined in value during a year in which most financial market investments have incurred losses.75 (b) 19706.40 You wish to save for your son’s education the present cost of which is Rs.43 Financial Planning Academy 88 .89 (d) 19887.320000 and is expected to increase by 6% every year. Calculate the amount of money accumulated by Sudha in 8 years.What amount she will get after 8 years if amount is compounding annually for first 5 years and semi-annually for last 3 years. Which one of the following entities would be impacted most by this decline in portfolio value? (a) Individuals participating in the plan (b) Company sponsoring the plan (c) Investment banker handling the plan (d) Plan underwriters 42 Which of the following would result in the largest increase in the price of a diversified common stock mutual fund? (a) Unexpected inflation (b) Expected dividend increase (c) Unexpected corporate earnings growth (d) Expected increase in the prime interest rate 43 Sudha has invested Rs. (a) 19205.92 (c) 18976.24 (d) 19203. If your son is 12 years old and will require money in 8 years time.46 44 In the above question if in the first 5 years compounding is annually and next 2 years compounding is quarterly and in the last 1 year compounding is monthly. 25000 & Rs. If rate of return is 6%.Compute the present value of the amount? (a) 17316.88 46 The 8% RBI Bonds cannot be invested by following category of investors? (a) Scientific Research Organization (b) Companies under Companies Act (c) NRI (d) Trusts 47 What is the effective annual rate if the stated nominal rate is 12% per annum compounded monthly? (a) 12. If she had Rs.1000 on every birthday into a retirement plan which paid an interest rate of 8% from the age of 20 years until she retired.00 (d) 17432. at what age did she retire? (a) 55 (b) 60 (c) 59 (d) 57 Financial Planning Academy 89 .49% 48 In the event of a loss due to an insured event the principle of indemnity ensures that (a) The compensation paid to the insured is always less than the loss (b) The compensation is equal to the loss (c) The compensation paid is more than the loss 49 In fire insurance “pro rata” means (a) Rating as per occupancy (b) Proportionate (c) Condition of average (d) None of them 50 Miss Rima works at the post office.15000 at the end of 14 &15 year respectively.36% (c) 12. She deposits Rs.22 in her retirement plan when she retired.50 (c) 18200.55% (b) 12.237941.68% (d) 12.49 (b) 17500.45 Ramesh will receive Rs. Compute cost inflation adjustment factor and calculate the indexed cost of acquisition? (a) 1.5 (c) 5 (d) 6 54 BSE sensex is ------------.1345 & 17650.15000 and sold on 12.389 & 406 respectively.1645 & 16745.150000. (a) Rs. He has Rs.index.Rs.2001.150000 in Bank account. Interest on RBI Bonds Rs.23 52 Radha has received interest on Govt. Equity share of Rs. If cost of inflation index for 1998-99. Compute the amount of deduction he will get under Sec 80L.43 (b) 1.03 1999 for Rs.6000.1567 &17350. securities Rs.6000. (a) Price weighted (b) Market capitalization (c) Market capitalization X price (d) None of these 55 Post office monthly income can be saved through (a) Cheque (b) Cash (c) Draft (d) All of the above 56 Person who declare will after the death of a person is called (a) Testator (b) Executor (c) Testate (d) Deceased Financial Planning Academy 90 .3000. 1999-00.900000 and house property of Rs.10000 for his household expenses.55 (d) 1.2000-01 are 351. Dividend from mutual funds Rs.5000 for maintenance of car per month.15000 (b) Rs.12000 (c) Rs.04.51 Anil has purchased units of mutual fund on 15.1597 & 17890.) 53 Sudha has to incur Rs.34 (c) 1.10000 (d) Nil ( Sec 80L is discontinued.Compute his liquidity ratio? (a) 8 (b) 9.15000 for payment of mortgage loan and Rs. Bonds are issued for duration of 10 years. He has taken adequate insurance.85 (c) 11. Bonds are issued for the duration of 10 years.850. Coupon rate of the bond is 10% and current price of the bond is Rs.5%. (a) 12.1000 face value. Then he should takes (a) Life cover (b) Property Protection (c) Health protection (d) Retirement planning 58 If a partnership firm is filing its income tax return timely then whether it is required audit its accounts (a) Yes (b) No 59 Testamentary Trust comes in the force of from the date of (a) Death (b) Retirement (c) Children become minor 60 Mr. Compute current price of the bond.025 61 Sita has purchased a bond of Rs. YTM of the bond is 8.57 A person is about to be retired.1000 face value.735 (b) 10. He has sufficient income to incur his regular expenses. Y has purchased a bond of Rs. Calculate YTM. coupon rate is 10%. The above rule comes under the following code of ethic of (a) Competence (b) Fairness (c) Confidentiality (d) Professionalism to Financial Planning Academy 91 .56 (d) 8. (a) 1098 (b) 956 (c) 1256 (d) 1245 62 A member shall clearly disclose to all prospective clients the capacity in which they are able to provide financial planning services. He has his wife only in the family. 991 (c) 8.200 (d) 8.4536 (c) 10.2 17% C 20% 0.333 (d) 10.00 (b) 9.63 Which of the following will help us in stock analysis? (a) Standard deviation of stock (b) Beta of stock (c) Return from stock (d) All of the above 64 Fundamental analysis stands for (a) Selecting stocks on the basis of EPS (b) Selecting stocks on the basis of book value (c) Selecting stocks on the basis of market value (d) All of the above (e) None of the above 65 Technical Analysis Stands for (a) Timing the market (b) Analysing demand and supply of stock (c) Comparing book value and market value (d) A and B both (e) B and C both Attempt the following questions based on the information given as under Stock Standard Beta Average return deviation A 23% 1.02 Financial Planning Academy 92 .0 18% B 25% 1.9 16% Return on 18% 21% market security Risk free return 8% 66 Compute Sharpe ratio for security A (a) 0.333 67 Compute Treynor ratio for security A (a) 10.4348 (b) 0. 87 (c) -3.70 (d) 3.56 74 Compute Jensen ratio for security C (a) 3.56 Financial Planning Academy 93 .02 71 Compute Jensen ‘s alpha for security B (a) -6.00 (b) 2.98 (d) 7.40 (d) 0.89 (b) 8.80 (c) 8.456 70 Compute Treynor ratio for security B (a) 7.60 (b) 6.398 (b) 0.360 (c) 0.75 (d) 8.50 (c) 6.45 (b) 0.68 Compute Jensen ratio or Jensen’s alpha for security A (a) 3.60 (c) 5.345 (d) 0.79 (d) 6.12 72 Compute Sharpe ratio for security C (a) 0.70 (b) 3.49 73 Compute Treynor ratio for security C (a) 8.89 (b) 7.67 (c) -3.98 69 Compute Sharpe ratio for Security B (a) 0.39 (c) 0.00 (d) 2. (b) It is a facility to hold investment in G-Sec and T-Bills in the electronic form (c) Trade is settled through delivery verses payment system (d) All of the above are features of SGL account Financial Planning Academy 94 .722 (c) 0.75% (c) 17.25% (Hint: Out of Rs.752 (b) 0.75 Compute Sharpe ratio for market security (a) 0.100 invested by a investor only Rs. How much should the mutual fund scheme earn to provide a return of 15% to you? (a) 17.79% (d) 18. You are considering a recently announced equity mutual fund scheme where the initial issue expenses are 5% and the recurring expenses are expected to be 2%.95 will be invested by Mutual Fund and has to generate return of 15% after deducting 2% recurring expenses) 80 What is a “Subsidiary General Account”? (a) This facility is available to large banks and financial institutions.678 76 Standard deviation is (a) Measure of return (b) Measure of risk (c) Measure of covariance (d) All of the above 77 Standard deviation calculations require (a) Expected Return (b) Actual Return (c) Deviation between actual return and expected return (d) All of the above (e) None of the above 78 What is a “Repo”? (a) Repo is repurchase agreement (b) Repo involves simultaneous sale and repurchase (c) The difference between the sale and repurchase price represents cost of carry (d) All of the above 79 You can earn a return of 15% by investing in equity shares on your own.768 (d) 0.00% (b) 17. 1000000 at an interest rate of 13%. (a) 10.75 (c) -75000. How long will you have to wait if your savings earn an interest rate of 12%. what will be its future value after 80 years? (a) 4932758.00 years (c) 11.00 (d) None of these Financial Planning Academy 95 .1000000 the cost is expected to remain unchanged in nominal terms.5000 today at a compound interest rate of 9%.80 (b) -57463.34 (b) 3205685.99 years 84 Suppose a firm borrows Rs. You can save annually Rs.81 What is the present value of Rs.79 years (b) 11. What is the present value of this stream of benefits if the discount rate is 10%? (a) -56861. (a) 5465 (b) 5675 (c) 5645 (d) 6000 82 Suppose you expect to receive Rs15000 annually for 5 years.10 (c) 5000000.500000 on retirement in a bank which pays 10% annual interest compounded semi annually.The loan is to be paid in 5 equal installments payable at the end of each of the next 5 years. How much can be withdrawn every year for a period of 10 years? (a) 80242.58 (b) 80534.29 86 If you invest Rs.00 83 You want to take a trip to US which costs Rs.50000 to fulfill your desire.00 (d) 55000.20 (c) 82345.10000 receivable after 6 years hence if the rate of discount is 10%.23 years (d) 10.15 (d) 40121. The annual installment payable will be how much? (a) 284314 (b) 284390 (c) 285436 (d) 285467 85 Your father deposits Rs. each receipt occurring at the end of the year. 3% (c) 8. The investors’ required rate of return is on this stock is 15%.30 per share.2% (b) 8. calculate the price of the bond? (a) 1056.78 (c) 9012.87 A 10 year.45 (d) 1056.1050.89 (d) 1089.10000. (a) 8900.67 (c) 1076. Find the value of bond at which it can be sold? (a) 1056. Compute the price of the bond.1000 and number of years remaining to maturity are 8.45 (c) 1059.59 (b) 8765.00. 12% coupon bond has a par value of Rs.If the company will grow at constant rate.35% (c) 12.78 (b) 8956.The required yield on this bond is 14%.45 89 A 10 year 10% coupon bond has a par value of Rs.65 (b) 1089.98% 92 The equity stock of X Ltd is currently valued at Rs.34 (d) 8876.77 88 In the same question find the price of the bond if interest is compounded semi-annually? (a) 8940.99 91 The market price of a Rs. The dividend expected next year is Rs.78 (d) 8900.25 (c) 8956.1000 par value bond carrying a coupon rate of 14% and maturing after 5 years is Rs. Similar bonds in the market are traded at 9% and compounding of interest is quarterly.60% (b) 12.59 90 In the same question if compounding is monthly.59 (b) 1066.9% (d) 10% (P0=D1/r-g) Financial Planning Academy 96 .78% (d) 12. what is the expected growth rate? (a) 9. What is the yield to maturity on this bond? (a) 12.2. (D1) The growth rate of dividend is 5%.21.00 (b) Rs.20.2. Calculate the intrinsic value of the share if the required rate of return is 15%? (a) Rs. g is growth rate and r is required return) 94 What is At The Money option in case of call and put options? (a) In both the options when Exercise price is equal to Market price ( spot price) (b) When Exercise price >Spot price (c) When Exercise price<Spot price (d) All of the above 95 What is In the Money option in case of call option? (a) When X<Spot Price (b) When X > Spot Price 96 What is In the Money option in case of put option? (a) When X>Spot price (b) When X< Spot price 97 What is Out of The money option in case of call option? (a) When X>Spot price (b) When X < Spot price 98 What is Out of the Money in put option? (a) When X < Spot price (b) When X>Spot price 99 Strategic asset allocations refers to the long term normal asset mix sought by the investor (a) Yes (b) No 100 Tactical asset allocations involve a conscious departure from normal asset mix to enhance the performance of fund.75 (d) Rs.20.00 (c) Rs.22. D1 is expected dividend next year.00 (P0= D1/r-g.00.93 The expected dividend per share on the equity share of A Ltd is Rs. (a) Yes (b) No (c) It is something else Financial Planning Academy 97 . Your client has some ABC shares. Which one of the following is the best investment opportunity for John? a) To receive 45. and there are 1 million shares issued.000 at the end of 10 years c) To receive 5.0 percent c) 16.000 of profits last year. ABC Company distributed 500. He asked you to calculate the dividend yield for an ABC share. which of the following is the most crucial action the planner needs to take to have the client achieve the goal of wealth accumulation? Advise investing the client’s assets: a) In the products which will bring the highest return to the client regardless of risk b) In products which produce high income for the client because fixed income products are generally safe c) In diversified mutual funds because of the protection which diversity provides d) After determining the client’s risk tolerance 102. John estimates his opportunity cost on investment at 10. A client provides a current personal balance sheet to the financial planner during the initial data gathering phase of the financial planning process.5% compounded annually. If a client needs to accumulate wealth but is risk-averse. Earnings were 800.500 at the end of each year for 19 years 103. This financial statement will enable the financial planner to gain an understanding of all of the following except the: a) Diversification of the client’s assets b) Size of the client’s net cash flow c) Client’s liquidity position d) Client’s use of debt 104. with low interest rates? a) Peak b) Recession c) Trough d) Expansion 105. d) To receive 5.000 today b) To receive 120.500 at the beginning of each year for 15 years. Which best describes high unemployment. What is ABC’s dividend yield? a) 6.000.00. The market price of a share is currently 5.25 percent b) 10.7 percent d) None of the above Financial Planning Academy 98 .101. 1630% 108. In advising a client on his retirement needs. (3) and (4) only 107. Which of the following statement is correct? a) Insurance is a dispersion of actual from expected results b) A hazard is the cause of financial loss c) Speculative risk involves the chance of loss or no loss d) Insurance is a device for reducing risk by having a large pool of people share in the financial loss suffered by members of the pool 109. (6) and (2) only d) (1). which of the following statements best describes the ‘replacement ratio method’: a) It is a longer-term projection b) Takes into account likely changes in income and expenses.000.5713% c) 10. If the bond matures today and the face value is 1. Which of the following are non-diversifiable risks? (1) Business risk (2) Management risk (3) Company or industry risk (4) Market risk (5) Interest rate risk (6) Purchasing power risk a) (4).5 years ago for 525. (2) and (3) only c) (5). and tries to determine the required savings to meet his or her retirement goals c) Focuses on projected expenses in retirement d) Assumes the standard of living just prior to retirement will determine the standard of living during retirement 110. A client purchased a zero coupon bond 6. (5) and (6) only b) (1).106. A codicil is: a) A document used to make an alteration to a will b) The statement made at the end of a will that it has been duly attested c) A term used to cover grants of probate to the legal personal representative d) A gift of land or real estate in a will Financial Planning Academy 99 .3372% b) 10. Your client is unsure of the meaning of the term ‘codicil’. what is the average annual compound rate of return (calculated semi-annually) that the client realised on her investment? a) 11.4000% d) 10. This action might not be possible to undo. Are you sure you want to continue?
https://www.scribd.com/doc/76150598/IFP-Module-1
CC-MAIN-2015-48
refinedweb
25,193
65.22
Face the live video being fed using your webcam. For initial level we are using this library but next time we will be creating our own model from scratch and will train it and then test it in real time!! Face Detection in Live Video: Know OpenCV OpenCV is a library of python which supports a built in model for detecting faces in an image using Haar Cascades. We can use OpenCV for extracting frames from a video then we will apply Haar Cascade onto those frames and will create square on the face being present in image. NOTE: Before moving onto the code you will be needed to download the “haarcascade_frontalface_default.xml” for running this face detection algorithm. You can find it here. This file basically contains weights for detecting faces The Code [sourcecode language=”python” wraplines=”false” collapse=”false”] #importing OpenCV and Time library import cv2 import time #Reading data from the CSV file we downloaded face_cascade = cv2.CascadeClassifier(‘C:/Documents/MachineLearning/haarcascade_frontalface_default.xml’) #Capturing Video from primary webcam, you can change number from 0 to any Integer ## for other webcams if you have many of them cap = cv2.VideoCapture(0) while (True): #Reading frame from the live video feed ret, frame = cap.read() #Converting frame into grayscale for better efficiency gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #Using Haar Cascade for detecting faces in an image faces = face_cascade.detectMultiScale(gray, 1.3, 5) #Creating the rectangle around face for (x,y,w,h) in faces: frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(120,250,0),2) #Displaying the captured frame in a window cv2.imshow(‘gray’,frame) #Applied 0.5 seconds delay such that a new frame will only be read every 0.5 seconds #This decreases load on machine, because in general webcam captures 15 to 25 frames per second time.sleep(0.5) print(“sleep done!!”) if cv2.waitKey(20) & 0xFF == ord(‘q’): break cap.release() cv2.destroyAllWindows() [/sourcecode] Input – Output The above algorithm was for starters!! In next tutorial we will be creating a face detection algorithm from scratch, then we will train it and use it! Stay tuned for more learning!!
https://mlforanalytics.com/2018/06/11/face-detection-using-opencv-in-live-video/
CC-MAIN-2021-21
refinedweb
360
57.06
Details - Type: Bug - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: None - Fix Version/s: None - Component/s: Non-bug differences from RI - Labels:None Description Compatibility. Different order of exceptions. RI throws unspecified NPE in java.net.URL("ss", null, -3, null) constructor if host ==null while Harmony at first checks port and throws MalformedURLException. If host != null both RI and Harmony throw MalformedURLException. =============test.java============= import java.net.*; public class test { public static void main (String[] args) { try catch (Exception e){ e.printStackTrace(); } try { new URL("ss", null, -3, null); } catch (Exception e) { e.printStackTrace(); } } } ======================================= Output on RI: java.net.MalformedURLException: Invalid port number :-3 at java.net.URL.<init>(URL.java:373) at java.net.URL.<init>(URL.java:283) at test.main(test.java:7) java.lang.NullPointerException at java.net.Parts.<init>(URL.java:1259) at java.net.URL.<init>(URL.java:380) at java.net.URL.<init>(URL.java:283) at test.main(test.java:13) Output on Harmony: java.net.MalformedURLException: Port out of range: -3 at java.net.URL.<init>(URL.java:393) at java.net.URL.<init>(URL.java:367) at test.main(test.java:7) java.net.MalformedURLException: Port out of range: -3 at java.net.URL.<init>(URL.java:393) at java.net.URL.<init>(URL.java:367) Activity - All - Work Log - History - Activity - Transitions Ilya, I agree with you. Spec has explicitly pointed out "No validation of the inputs is performed by this constructor." The tests show that the exception thrown sequence is uncertain and implemention-dependent. If no application and test cases are broken by currenty Harmony code, I suggest not fix the problem. Best regards, Andrew I've also investigated this issue and agree with Andrew and Ilya - RI's logic seems very weird and it's hard to reproduce it. +1 for moving it to Non-bug difference and closing. I believe this case is implementation dependent. If you look in the spec you can find phrase "No validation of the inputs is performed by this constructor." at the end. Thus all thrown exceptions during initialization is based on the inner logics. To be compatible with the RI we have to have the same inner logics that is impossible, because of it is private. I was trying to catch this logics based on the constructor playing with arguments combination (correct/incorrect) and found that it is not trivial on RI: 1. new URL("ss", "0", -3, null); java.net.MalformedURLException: Invalid port number :-3 2. new URL("ss", null, -3, null); java.lang.NullPointerException 3. new URL("ss", "0", -3, "file"); java.net.MalformedURLException: Invalid port number :-3 4. new URL("ss", null, -3, "file"); java.net.MalformedURLException: unknown protocol: ss 5. new URL("ss", "0", -1, null); java.lang.NullPointerException As you can see: in 2 and 4 host is null, but we throw different exceptions. If we assume that NPE depends on file ?= null (see 2 and 5) than it is false for the 1 case!! I would suggest not to make any changes in the URL class constructor if existed implementation of URL class works correct and passes other unit tests.
https://issues.apache.org/jira/browse/HARMONY-1158
CC-MAIN-2017-34
refinedweb
530
53.68
Hello everyone. I am new to coding, taking an introductory C++ class at Baylor University. I am trying to get this standard deviation problem worked out, but I just pulled an all-nighter on it thinking it would be simple, but it is not. I have attached the prompt for the assignment if you would care to take a look: Assignment 1 - sum avg std dev.doc As per the code I have developed, that can be viewed here: /************************************************************************************************************************ Filename: Assignment 1.cpp Author: Myles Daniel Baker Class: CSI 1430 - 05 Description: This C++ Porgram will accept four integers from a user, store them as variables, and prints the sum, average, and standard deviation of the four integers. Date Modified: 09/04/2008 - File Created *************************************************************************************************************************/ include <iostream> include <cmath> include <string> using namespace std; int main() { float integer1, whole1, integer2, whole2, integer3, whole3, integer4, whole4, avg, sum, s_dev; cout << "Hello!" <<endl; cout << endl << endl << endl; cout << "Using C++ we are going to evaluate the sum, average, \n"; cout << "and standard diviation of a set of four integers. \n"; cout << endl; cout << "Please input the 1st of 4 integers \n"; cin >> integer1; cout << endl; whole1 = integer1; cout << "Integer1: " << whole1 << endl; cout << endl; cout << "Please input the 2nd of 4 integers \n"; cin >> integer2; cout << endl; whole2 = integer2; cout << "Integer2: " << whole2 << endl; cout << endl; cout << "Please input the 3rd of 4 integers \n"; cin >> integer3; cout << endl; whole3 = integer3; cout << "Integer3: " << whole3 << endl; cout << endl; cout << "Please input the 4th of 4 integers \n"; cin >> integer4; cout << endl; whole4 = integer4; cout << "Integer4: " << whole4 << endl; cout << endl; sum = (whole1 + whole2 + whole3 + whole4); cout << "The sum of the four integers equals: "<< sum; cout << endl << endl; avg = (sum / 4); cout << "The average of these four integers equals: " << float(avg); cout << endl << endl; s_dev = sqrt(-((4*avg-whole1-whole2-whole3-whole4)/4); cout << "The standard deviation of the four integers equals: " << s_dev <<endl; cout << endl << endl << endl << endl; cout <<"Thank you, have a nice day! \n"; cout << endl << endl; return 0; } The professor allows us to test our programs before we submit them. He has given these values so you can compare them to yours if you run this through C++: Int1: 23 Int2: 56 Int3: 5 Int4: 23 Sum: 107 Avg: 26.75 S_Dev: 18.417 I am wondering whether the equation he has supplied us with is correct. I am a mathematics major and cannot understand why this is so difficult for me. According to the models I have put together (the one above in addition to 5 other attempts or so) the equation should yield the correct results. Please help! Thanks
https://www.daniweb.com/programming/software-development/threads/144146/please-help-standard-deviation-c
CC-MAIN-2017-51
refinedweb
438
57.74
rbb 00/02/10 15:16:14 Modified: src/include ap_ac_config.h Log: We need to make sure we are using signals that interrupt system calls. This was keeping graceful restart from working in the prefork MPM. Currently, this is a real hack, but I am hoping to get a better fix in place tomorrow. Revision Changes Path 1.8 +2 -0 apache-2.0/src/include/ap_ac_config.h Index: ap_ac_config.h =================================================================== RCS file: /home/cvs/apache-2.0/src/include/ap_ac_config.h,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- ap_ac_config.h 2000/01/21 01:25:24 1.7 +++ ap_ac_config.h 2000/02/10 23:16:12 1.8 @@ -231,4 +231,6 @@ #undef USE_MMAP_FILES #endif +#define signal(s, f) ap_signal(s, f) + #endif /* AP_AC_CONFIG_H */
http://mail-archives.apache.org/mod_mbox/httpd-cvs/200002.mbox/%3C20000210231615.14230.qmail@hyperreal.org%3E
CC-MAIN-2015-06
refinedweb
134
64.88
java.lang.Object org.netlib.lapack.Stgevcorg.netlib.lapack.Stgevc public class Stgevc Following is the description from the original Fortran source. For each array argument, the Java version will include an integer offset parameter, so the arguments may not match the description exactly. Contact seymour@cs.utk.edu with any questions. * .. * * * Purpose * ======= * * STGEVC computes some or all of the right and/or left generalized * eigenvectors of a pair of real upper triangular matrices (A,B). * * The right generalized eigenvector x and the left generalized * eigenvector y of (A,B) corresponding to a generalized eigenvalue * w are defined by: * * (A - wB) * x = 0 and y**H * (A - wB) = 0 * * where y**H denotes the conjugate tranpose of y. * * If an eigenvalue w is determined by zero diagonal elements of both A * and B, a unit vector is returned as the corresponding eigenvector. * * If all eigenvectors are requested, the routine may either return * the matrices X and/or Y of right or left eigenvectors of (A,B), or * the products Z*X and/or Q*Y, where Z and Q are input orthogonal * matrices. If (A,B) was obtained from the generalized real-Schur * factorization of an original pair of matrices * (A0,B0) = (Q*A*Z**H,Q*B*Z**H), * then Z*X and Q*Y are the matrices of right or left eigenvectors of * A. * * A must be block upper triangular, with 1-by-1 and 2-by-2 diagonal * blocks. Corresponding to each 2-by-2 diagonal block is a complex * conjugate pair of eigenvalues and eigenvectors; only one * eigenvector of the pair is computed, namely the one corresponding * to the eigenvalue with positive imaginary part. * * Arguments * ========= * * SIDE (input) CHARACTER*1 * = 'R': compute right eigenvectors only; * = 'L': compute left eigenvectors only; * = 'B': compute both right and left eigenvectors. * * HOWMNY (input) CHARACTER*1 * = 'A': compute all right and/or left eigenvectors; * = 'B': compute all right and/or left eigenvectors, and * backtransform them using the input matrices supplied * in VR and/or VL; * = 'S': compute selected right and/or left eigenvectors, * specified by the logical array SELECT. * * SELECT (input) LOGICAL array, dimension (N) * If HOWMNY='S', SELECT specifies the eigenvectors to be * computed. * If HOWMNY='A' or 'B', SELECT is not referenced. * To select the real eigenvector corresponding to the real * eigenvalue w(j), SELECT(j) must be set to .TRUE. To select * the complex eigenvector corresponding to a complex conjugate * pair w(j) and w(j+1), either SELECT(j) or SELECT(j+1) must * be set to .TRUE.. * * N (input) INTEGER * The order of the matrices A and B. N >= 0. * * A (input) REAL array, dimension (LDA,N) * The upper quasi-triangular matrix A. * * LDA (input) INTEGER * The leading dimension of array A. LDA >= max(1, N). * * B (input) REAL array, dimension (LDB,N) * The upper triangular matrix B. If A has a 2-by-2 diagonal * block, then the corresponding 2-by-2 block of B must be * diagonal with positive elements. * * LDB (input) INTEGER * The leading dimension of array B. LDB >= max(1,N). * * VL (input/output) (A,B); * if HOWMNY = 'B', the matrix Q*Y; * if HOWMNY = 'S', the left eigenvectors of (A,B) specified by * SELECT, stored consecutively in the columns of * VL, in the same order as their eigenvalues. * If SIDE = 'R', VL is not referenced. * * A complex eigenvector corresponding to a complex eigenvalue * is stored in two consecutive columns, the first holding the * real part, and the second the imaginary part. * * LDVL (input) INTEGER * The leading dimension of array VL. * LDVL >= max(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. * * VR (input/output) REAL array, dimension (LDVR,MM) * On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must * contain an N-by-N matrix Q (usually the orthogonal matrix Z * of right Schur vectors returned by SHGEQZ). * On exit, if SIDE = 'R' or 'B', VR contains: * if HOWMNY = 'A', the matrix X of right eigenvectors of (A,B); * if HOWMNY = 'B', the matrix Z*X; * if HOWMNY = 'S', the right eigenvectors of (A,B) specified by * SELECT, stored consecutively in the columns of * VR, in the same order as their eigenvalues. * If SIDE = 'L', VR is not referenced. * * A complex eigenvector corresponding to a complex eigenvalue * is stored in two consecutive columns, the first holding the * real part and the second the imaginary part. * * LDVR (input) INTEGER * The leading dimension of the array VR. * LDVR >= max(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. * * MM (input) INTEGER * The number of columns in the arrays VL and/or VR. MM >= M. * * M (output) INTEGER * The number of columns in the arrays VL and/or VR actually * used to store the eigenvectors. If HOWMNY = 'A' or 'B', M * is set to N. Each selected real eigenvector occupies one * column and each selected complex eigenvector occupies two * columns. * * WORK (workspace) REAL array, dimension (6*N) * * INFO (output) INTEGER * = 0: successful exit. * < 0: if INFO = -i, the i-th argument had an illegal value. * > 0: the 2-by-2 block (INFO:INFO+1) does not have a complex * eigenvalue. * * Further Details * =============== * * Allocation of workspace: * ---------- -- --------- * * WORK( j ) = 1-norm of j-th column of A, above the diagonal * WORK( N+j ) = 1-norm of j-th column of B, above the diagonal * WORK( 2*N+1:3*N ) = real part of eigenvector * WORK( 3*N+1:4*N ) = imaginary part of eigenvector * WORK( 4*N+1:5*N ) = real part of back-transformed eigenvector * WORK( 5*N+1:6*N ) = imaginary part of back-transformed eigenvector * * Rowwise vs. columnwise solution methods: * ------- -- ---------- -------- ------- * * Finding a generalized eigenvector consists basically of solving the * singular triangular system * * (A - w B) x = 0 (for right) or: (A - w B)**H y = 0 (for left) * * Consider finding the i-th right eigenvector (assume all eigenvalues * are real). The equation to be solved is: * n i * 0 = sum C(j,k) v(k) = sum C(j,k) v(k) for j = i,. . .,1 * k=j k=j * * where C = (A - w B) (The components v(i+1:n) are 0.) * * The "rowwise" method is: * * (1) v(i) := 1 * for j = i-1,. . .,1: * i * (2) compute s = - sum C(j,k) v(k) and * k=j+1 * * (3) v(j) := s / C(j,j) * * Step 2 is sometimes called the "dot product" step, since it is an * inner product between the j-th row and the portion of the eigenvector * that has been computed so far. * * The "columnwise" method consists basically in doing the sums * for all the rows in parallel. As each v(j) is computed, the * contribution of v(j) times the j-th column of C is added to the * partial sums. Since FORTRAN arrays are stored columnwise, this has * the advantage that at each step, the elements of C that are accessed * are adjacent to one another, whereas with the rowwise method, the * elements accessed at a step are spaced LDA (and LDB) words apart. * * When finding left eigenvectors, the matrix in question is the * transpose of the one in storage, so the rowwise method then * actually accesses columns of A and B at each step, and so is the * preferred method. * * ===================================================================== * * .. Parameters .. public Stgevc() public static void stgevc(java.lang.String, int mm, intW m, float[] work, int _work_offset, intW info)
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/Stgevc.html
CC-MAIN-2017-51
refinedweb
1,218
50.87
React Frontend Quickstart Starter template using React on a website's frontend - without Node Structure This project only needs 3 files to run: - index.html - the homepage. - main.js - the app logic. This loads dependencies from CDN URLs, constructs the app and then mounts it an element in the body of the HTML. - styles.css - some minimal CSS styling. The JS file is is loaded as an ES Module, which means we get to load react and htm with the import syntax and so don't need to load those as separate script tags on the HTML page. This keeps all your JS and dependencies together and separated from the HTML, for easy for formatting, lint and testing (like unit tests) if you choose to add those with Deno or NPM. Or maybe you just use your IDE to format and lint your JS files. Features - Built on React from a CDN. - No build step - locally or for CI/CD. Just start a static server in the project root - locally or with GH Pages or Netlify. - This light React setup on the frontend is great for small and simple projects. - It's also adding interactive behavior to an existing site, without having to rebuild as a Node/React. - You can put your JS code as a separate JS script as done here with main.js, or even directly on your HTML page if you have a short snippet. - This project structure is lighter - no package.json, no ESLint config and no Prettier config. See limitations below around this. Limitations - Developer experience is limited - no CLI tooling to catch syntax or linting errors. - You can't use JSX syntax directly the way this project is setup. But you can use a backticks string with JSX syntax inside it, thanks to the HTM package used here. Or if you don't like that syntax, you can use Babel Standalone for frontend compilation - see my JSX guide. - No linting or formatting tool is supplied.
https://reactjsexample.com/starter-template-using-react-on-a-websites-frontend-without-node/
CC-MAIN-2022-27
refinedweb
331
74.29
React Native On this page, we get you up and running with Sentry's React Native SDK, automatically reporting errors and exceptions in your application. Install Sentry captures data by using an SDK within your application’s runtime. These are platform-specific and allow Sentry to have a deep understanding of how your application works. If you are using expo-cli you need to use another SDK see: This SDK only works for ejected projects or projects that directly use React Native. Add the @sentry/react-native dependency: npm install --save @sentry/react-native Linking Since our SDK also supports native crashes, we need to link the SDK to your native projects. Above react-native >= 0.60 you need to do: npx @sentry/wizard -i reactNative -p ios android cd ios pod install Since our SDK supports auto-linking and iOS relies on CocoaPods, you need to install the dependencies. If you are running a project with react-native < 0.60 you still need to call react-native link. react-native link @sentry/react-native The link step or the sentry-wizard call will patch your project accordingly. The Sentry Wizard will guide you through the process of setting everything up correctly. This has to be done only once, and the files created can go into your version control system. The following changes will be performed: - add the sentry-android package for native crash reporting on Android - add the sentry-cocoa package for native crash reporting on iOS - enable the Sentry Gradle build step for Android - patch MainApplication.java for Android - configure Sentry for the supplied DSN in your index.js/App.js files - store build credentials in ios/sentry.properties and android/sentry.properties. iOS Specifics When you use Xcode, you can hook directly into the build process to upload debug symbols and source maps. However, if you are using bitcode, you will need to disable the “Upload Debug Symbols to Sentry” build phase and then separately upload debug symbols from iTunes Connect to Sentry. Android Specifics For Android, we hook into Gradle for the source map build process. When you run react-native link, the Gradle files are automatically updated. When you run ./gradlew assembleRelease source maps are automatically built and uploaded to Sentry. If you have enabled Gradle's org.gradle.configureondemand feature, you'll need a clean build, or you'll need to disable this feature to upload the source map on every build. To disable this feature, set org.gradle.configureondemand=false or remove it as its default value is disabled, do this in the gradle.properties file. initialize the SDK, you need to call: App.js import * as Sentry from "@sentry/react-native"; Sentry.init({ dsn: "", }); The sentry-wizard will try to add it to your App.js Verify Great! Now that you’ve completed setting up the SDK, maybe you want to quickly test out how Sentry works. You can trigger a JS exception by throwing one in your application: throw new Error("My first Sentry error!"); You can even try a native crash with: Sentry.nativeCrash(); Capturing Errors In most situations, you can capture errors automatically with captureException(). try { aFunctionThatMightFail(); } catch (err) { Sentry.captureException(err); }. To benefit from the health data you must use at least version 1.4.0 of the React Native SDK, and enable the collection of release health metrics when initializing the SDK: import * as Sentry from "@sentry/react-native"; Sentry.init({ dsn: "", enableAutoSessionTracking: true, }); The SDK automatically manages the start and end of sessions when the application is started, goes to background, returns to the foreground, etc. By default, the session terminates once the application is in the background for more than 30 seconds. To change the timeout, use the option sessionTrackingIntervalMillis. For example: import * as Sentry from "@sentry/react-native"; Sentry.init({ dsn: "", enableAutoSessionTracking: true, // Sessions close after app is 10 seconds in the background. sessionTrackingIntervalMillis: 10000, }); For more details, see the full documentation on Release Health. Identify the User By default, we don't apply the user identification provided to the SDK via the API. Instead, we use the installation ID generated with the first use of the application. The ID doesn't contain any private or public data of your users or any public or shared data of their device. More options Under the hood the SDK relies on our Browser JavaScript SDK. That means that all functions available for JavaScript are also available in this SDK. - Package: - npm:@sentry/react-native - Version: - 1.9.0 - Repository: -
https://docs.sentry.io/platforms/react-native/
CC-MAIN-2020-45
refinedweb
753
57.27
Asked by: Create a static library that can be used in both WinRT and Win32 Hi, I'm trying to build a static library that can be used in both WinRT (Metro) and Win32 (for Windows Server 2008 R2). But I don't know how to deal with inconsistent APIs. For example, in WinRT, you have to use CreateFile2, while in earlier Windows, you have to use CreateFile. Similarly, in WinRT, you have to use Microsoft::WRL::ComPtr, while in previous Windows, you have to use CComPtr. I tried to use # ifdef: #ifdef METRO return CreateFile2( lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, nullptr); #else return CreateFile( lpFileName, dwDesiredAccess, dwShareMode, nullptr, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, nullptr); #ifdef METRO throw ref new Platform::Exception(hr); #else throw hr; #endif But the decision is made at compile time, not at link time. Since in the static library project, I don't have METRO defined, it is always compiled as if I target Win32. Is there a way to delay the decision until link time? I'd like to define METRO in my WinRT project, and not define it in the Win32 project. Sining Oh Blue StarMonday, June 11, 2012 10:00 AM Question All replies With static libs, you'd have to have separate build configurations for Metro and Desktop. The alternative is to just add the code to your main project (that way the conditional macros come into play). But this will slow down build time. Monday, June 11, 2012 1:13 PM - Edited by Nishant Sivakumar Monday, June 11, 2012 1:14 PM - Thanks, but what do you mean by "add the code to your main project"? I have two main projects, one for desktop and one for Metro. Do you mean I need to keep two separate code base? Sining Oh Blue StarTuesday, June 12, 2012 1:13 AM Hello, I think you should separate them, the metro need include the winmd file into the library and the native library donot. So we can build a native library first, this can be used in Win32, then we create a WinRT wrapper to include it into Metro application. Best regards, Jesse Jesse Jiang [MSFT] MSDN Community Support | Feedback to us Tuesday, June 12, 2012 8:07 AM Thanks. Can you elaborate? Let me provide some background. At first, I had an existing dll project that worked fine on Windows Server 2008 R2 (where WinRT is not supported). Then I tried to port it to Metro, as a custom WinRT component. The process is somewhat smooth, but I had to make a lot of changes. For example, CreateFile vs. CreateFile2, DrawTextW vs. DrawText, CComPtr vs. ComPtr, etc. Later I needed to add some new features to both projects, and fix some bugs. Whenever I updated the code, I had to remember to update 2 different places. If I forgot, very quickly the projects will be out of sync. Due to those API inconsistance, I could not simply copy the complete souce code from one project to the other. Everytime I had to check where I should update the code, and whether the update is enough. Then I realized I could try to use a single code base. So I created functions like: CreateFileCommon() { // For Win32 CreateFile(); // For WinRT CreateFile2(); } In both projects, I created a file common.h, and put the above functions inside it. Now most code files can use the same code CreateFileCommon. So the only difference is I need 2 common.h. I also learnt to simulate WinRT's ComPtr using ATL's CComPtr. Something like: namespace Microsoft { namespace WRL { class ComPtr : public CComPtr } } At this stage, when I updated one project, I could copy everything except common.h to the other project, and it would work fine. However, this is still a lot of manual work. Ideally I don't want to copy the source code everytime I do some update. If VC++ allows me to add exising items as link (as we can do in C#), the problem will be solved. But this is not supported in VC++... So I think I need to create a common project, and reference it in both Win32 and WinRT's main project. Dll is not supported in WinRT, and WinRT component is not supported in Win32. So I think a static library is what I need. However, now I have this problem... Many code relies on the functions/classes defined in common.h, yet common.h are different for different versions. Without common.h, my static library project won't compile. But #ifdef only works at compile time, not link time. I have to use two different build configurations (for instance, one with /CX and one without). So it seems I still need two different projects... Sining Oh Blue StarTuesday, June 12, 2012 12:29 PM This comment is probably too late, but I've just come across your problem while looking for a solution to one of my own. In any case, I can think of two ways to get out of this situation without having to manually sync two copies of the same source code: 1) Since you're programming for Win RT, I assume you're using VS 2012 in Win8 and VS 2010 in Win 2k8. Both of these support per-project property sheets for their VC++ directories. This means you could divide your project in three logical parts (you can further split them depending on your project's structure and recursively apply this same solution): common code, win RT code and win32 code. You can then have e.g. one copy of your "common.h" file (though this name obviously becomes inappropriate) in a WinRT folder and another one in the a folder, each one tuned to its own platform, and then have the Win8 project only include this WinRT as part of its VC++ directories, and the Win 2k8 project reference the Win32 folder. From your explanations I can't clearly understand whether you aren't doing so already; in case you are, then what copying the source code are you talking about when you're updating? 2) You could set up some form of source control. That's always a good idea, even for your home projects. Then keep on having two copies of the files common to both projects, but don't worry about it. Have two branches, and have them share all the common files. Whenever you change one project, just push the relevant changes to the other one.Friday, July 06, 2012 11:34 PM Write static lib with WRL for winrt instead of C++/CX. C++ DX11Saturday, July 07, 2012 1:08 PM
https://social.msdn.microsoft.com/Forums/en-US/61829316-fff3-43c7-a86a-cf0e13c66845/create-a-static-library-that-can-be-used-in-both-winrt-and-win32?forum=winappswithnativecode
CC-MAIN-2016-22
refinedweb
1,110
72.46
Threads can be suspended using the static sleep() method. The sleep() method is defined in the Thread class and has two overloads: public static void sleep(long millis) public static void sleep(long millis, int nanos) The sleep() will suspend the thread execution until the specified period. It causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Let’s look at an example that will print us date in terms of seconds since 1970. import java.util.Date; public class MrSleep { public static void main(String[] args) { for(;;) { //the number of seconds since January 1, 1970, 00:00:00 GMT long seconds=new Date().getTime()/1000; System.out.println("Seconds: "+seconds); //suspend thread for a second try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } Result Seconds: 1523713737 Seconds: 1523713738 Seconds: 1523713739 Seconds: 1523713740 Seconds: 1523713741 Seconds: 1523713742 Seconds: 1523713743 Seconds: 1523713744 ...... We suspend the thread for a second and print the date. We’ve converted the date to seconds. The date is counted since January 1, 1970, 00:00:00 GMT. This program can theoretically run infinitely, forever upto the end of time. Best Regards.
https://camposha.info/suspending-a-thread-through-sleep/
CC-MAIN-2020-16
refinedweb
204
55.95
Hi. I develop plugins for PyCharm. so, I have a clone from GitHub PyCharm plugins, but this source include import com.jetbrains.python.debugger.remote.PyRemoteDebugConfiguration; because the build is failed. Whrere is that package? Thank you reading. Hi, which source includes the import? This class is a part of PyCharm Professional code base. Thank you Dmitry. I would like make this plugins. So, i arrange it another DCC tool plugins about Houdini. I use PyCharm Professional 2017 3.2 RC from JetBrains ToolBox, and I already searched my local directory PyCharm Professional lib, but i dont found it. Whrere is that package? Please give me more information. Thank you reading.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000784050-Whrere-is-import-com-jetbrains-python-debugger-remote-PyRemoteDebugConfiguration-package-?page=1#community_comment_115000639084
CC-MAIN-2021-43
refinedweb
111
64.37
1,33 Related Items Preceded by: Orange and blue Succeeded by: Independent Florida alligator Full Text Co Op To -LORIDA ALLI GATOR VOL. 38; NO. 6 Co-Op Grocery Quonset Goes Up UNIVERSITY OF FLORIDA NOV. 1, 1946 _41 Construction of the Co-Op, grocery is rapidly nearing completion. Ben Mayberry, President of the student co-operative organization, has announced, that the grocery, located near Flavet 1, will open before Nov. 15. Branch To Open At Air Base Within 6 Weeks- Mayberry By Ted Shurtleff Building of the Student Co-Op Grocery will be com- plete within a week and the opening will be before the 15th of this month, Ben Mayberry announced today. Mayberry, who is president of the board of directors of the students' cooperative exchange, inc., said that all fixtures for the building have t e re been obtained and that a mer- chandise inventory is now being Lee Proposes made. Chris F. Bracewell, general FB manager, has been meeting with wholesalers during the week to secure adequate stocks. He as- sures members that there will be A change in the constitution of plenty of fresh meat for the op- Florida Blue Key was proposed ening. this week by Herman A. Lee, vice Scarce Items Rationed president and nominating commit- Scarce items will be distribut- tee chairman of the organization. ed under a rationing system de- Lee's proposal will allow credit for signed to see ,that each member summer school work toward qual- receives his share. ifications and residence. The pres- The building, which is of quon- ent Blue Key constitution does not set type, is near Flavet Village allow summer school credit. No. 1, or, specifically, between Summer Sessions Count the DuplicaLing Department and Lee has asked that two six the Wood Products Laboratory. A weeks summer sessions equal one $6,000 grant rrom the Florida semester, the amended clause to State Cabinet is financing con- read as follows: "Must have corn- struction. pleted five semesters of college Branch Planned work, of which at least three regu- lar semesters have been at the With the opening of the Uni- University of Florida, and two six versity grocery still a week or weeks sessions of summer school two away, plans are being push- shall constitute one refuilar semes- ed to open a branch store at Weiih ter." A two-thirds majority of the es i tr Choir S t sullivanTo active members present atwo onscutivemeetings is necessary F C to pass the amendment. The first SH ead FSC meeting was held this week and I Hread- W the second is slated for Nov. 12 For B CaWmp s ce r- New members will be selected al By Neil Evans G t rthat t . BNsGatorMen t nApplications Urged The Lyceum Council will present the Westminister In a recent election of student Students who now can qualify Choir, distinguished group of forty voices, on Sunday and officers, John Sullivan was chosen -Continued-on Page THREE Monday, November 3rd and 4th in the University audi- President of the Student Body for torium. the ensuing semester at the Talla- Fl iCSTickets Tickets for the Westminister Choir performance will hassee branch of the University of be reserved for students until five o'clock this afternoon. -ida. a ember of Theta For Non-Frat After today the tickets will no longer be reserved, but Fraternity, formerly attended I available to the general public classes on the main campus in Go On ale also. Student tickets are free. Gainesville. He is from Tallahas- Non-fraternity student tickets Tickets for students' wives and see. Non-fraternity student tickets dates are 50 cents, and general ad- P a er Shorta e for the annual Inter-Fraternity mission tickets will be $1. a Other officials of the student Conference's Fall Frolics went on Tickets in Advance Hits Alliator body are: sale Tuesday afternoon, and will TRickets i Advan s A liao Milton Flack, New York City, continue to be sold every after- "Rich" Richardson, president of vice president; Dean Wentworth, noon from 3 to 5 in the Florida the Lyceum Council, cautions that Due to the paper shortage, Pensacola, secretary; Robert San- Union until Nov. 17, or until the tickets will not be available at which will soon force the clos- ders, Jacksonville, treasurer; Jesse 1,600' available ducats are gone, it the auditorium, but must be ob- ing of an estimated 250 news- Wilson, Okeechobee, social chair- was announced today bv Bill Byrd; taed in desk. advance also at tdvhises sFlotu- papers in Florida if relief is not man. -Continued on Page THREE Union desk. He also advises stu- forthcoming. The Ali-gator was dents to secure tickets for them- force to go from an eight to a selves, wives, dates, and parents four-page tabloid titis week. We A& while they are still reserved, hope to be back to normal byA& m0( U Program-s Divided next week. Both Sunday s anji Monaay's This issue carries only the- programs will be divided into five atre ads due to the shortage of, parts broken by an intermission space for campus news. Our ad- r between the third and fourth parts. vertisers will be allotted a slight i The first half of each program increase in advertising space to consists of choral masterpieces by make up for this issue when such composers as Bach, Brahuns and if the newsprint situation By "Pen" Gaines and Latli. The second halves will imrn-ovs. Comparisons of odd1 deoren'o dominated t heo nnual Fall the Air Base to accommodate the 107 married couples and tne single men who live there or in the vicinity. The Air Base branch will be opened within the next six weeks, Mayberry said. In this connection, Mayberry stressed that membership in the Co-Op Grocery is open to any student, married or single. The fee is $15.50, used for initial cap- ital, but when the student leaves the University he is refunded all except .50. Any money clearing overhead will be returned to the members in shares according to purchases. iembersnip to date is approxi- mately 425. Service Station Next noeting of the board of directors is Tuesday, November 5, in Florida Union. Members will hear a report from a committee, of which J. L. Buggs is chairman, a on the possibility of opening a , Co-Op Service Station at the Air t Base. Present plans a.re for ren- ovating the station which was there when t:e Army had the base. Nc Wl TI alone univ ente consist of music of a lighter na- The Alligator had ordered Frolic' picture this week when the Inter-Fraternity Con- site ture. 6,.300 copies of The Collegiate ference, headed by President Joe Sherouse, announced Beat Sunday's program ni v not com- Digests, a photo supplement., ut the air base gymnasium as the eas Pencunilhe30bse.mniodereas mence until 8:30 p.m. it order to e The Digest has also been site for the two dances. The IFC the same number of couples as the once church who wisth o hear the pattendingr- hit by the pIer shortage, only moved into action to map out the campus floor. It can be heated in ct2.00 copies are available to our attack of certain problems arising -Continued on Page THREE formance that night. Gainesville 6,304) subscribers, from the fact that it will be the - -Continued on Page THREE first social function for the larg- est student body in Florida's his- W estm minister Choir T< I tory. P ans F r 4 Ne B idiandhisnatinally known band flowing from the air base gymna-, ,t Ssumn, a comparison of war-time .d S Ca p s N r Csignificaneetis drawn, President 16 aReason For Site Plans for the addition of many stage is the new S1.200 000 gym- In explaining the reasons for permanent buildings to the cam-'nasium. The pans for the gigantic having to choose the gym off cam- p us are nearing completion, new administration and classroom pus Shearoue lited the's follow- George F. Baughman, Assistant building a-e still in the embryonic ing: (1) "the campus gym's floor Business Manager of the Univer-r stage. The site for such a build- in basketball season, and having sity, revealed this week. ing is still undecided. the floor resurfaced after the two "The plans for the new $500,000 Sewage Plant Bega a dances would cause a great deal cafeteria extension are very near Construction has begun on the of added expense; (2) a basketball ' completion and should be released $230,000 sewage disposal .plant. game is scheduled at the gym for i f t this week," Baughman said. "At When the sewage disposal plant is, Friday night.. (3) bleachers have 'I'. l' | the last meeting of the Board of completed, the pilot plant will be been set up, and it requires two Control we were given authority used extensively as an educational and a half days for their removal to submit the plans to contractors and experiment facility. uen' return. For these reasons, and receive bids," he added. Others Planned we are forced to leave the cam- Library Extension Many other buildings such as the pus." Library ExtChemistry Building Extension, the Many Advantages .. The $900,000 library extension is I Agriculture Building extension, li '--ooking at the other side of The Westminister Choir, coneposed of still in the planning stage, but the and the proposed engineering tta p-L-iure, Sherouse listed the ad- by the Lyceum Council in a concert at plans should be completed .in the buildings are still in the prelimin-vantages of the air base "dance 8:&0 p. m. Nov. 3 and 8:00 p. n., Nov. near future. Also in the pla.niking cry plan.amg ts f all": "The gym will accommodate transcontinental tour taken by the outtst More "Who's ho" Selections ie University of Florida, g with many other large ersities, has discontinued ring men in "Who's Who in erican Colleges and Univer- s" because, Dean R. C. ty sa'd this week. "It has ,ed to hold the significance it did." 40 voices, will be sponsored the University anditoriam at 4. This is the first pf6lwa- tndi&a&g choral group. e y t d Lt v I Open By November 15 j Statistics Show Gators' Offense By Hugo Spitz The UTniyersity of ,,Florida put up a gallant battle against the powerful University of. North Carolina last Saturday and went down- to defeat, 40-19. In -a wide. open football game, 18,000 homecoming fans jammed Kenan Stadium at Chapel Hill to witness -the brilliant running of Charley Justice and the accurate passing of Florida's Doug Belden. Williams Standout: Right -End, Broughton Williams was a big-cog-in the Gators' aerial attack. In the second period he grabbed a short pass from Belden in the end zone for Florida's first score. Late in the third period he took a pass from Hal Griffin, eluded, two Tarheels and ran 37 for the score.. .Williams caught five of the fifteen passes complet- ed to regain the position of lead- ing pass receiver in. the country. Belden To Turner Florida's other score came early in the third period when Belden rifled a short pass to End Bill Turner in the end zone. The Tarheel attack was led by Charley "Choo-Choo" Justice, who ran through the Florida team for two touchdowns, one on a 70 yard punt- return, the other on a 90 yard kickoff return. Although the score read 40-19, the Gators outgained the Tarheels by 95 yards. They completed 15 out of 39 passes and ran up 12 first downs to North Carolina's 11. Midnite Movie Off This Week Since the Gators have an open date. this week there will be no midnight movie at the Florida Theatre this Saturday. night. There will, -however, be one as usual af- ter the Georgia-Florida game. Lee : Continued From Page ONE under the new amelnment, even though- it hasn't been passed, are urged to submit their applications. If-the. new amendment is- carried, those applications will be consid- ered with those previously sub- Dempsey-Standout -Gator Tackle ......... : - x cultiv e Council Passes Committfeej M9i lions By George Kowk'ahany The Executive Council at its regular meeting last week approved the nomination of Sam Gibbons as Secretary of Labor and Walter Timberlake as assistant Secretary of Interior. Also approved was the- nomination by Chancellor Herb constitutional revision committee Stallworth of Ted Camp to fill a with Harold Smith as chairman, vacancy on the Honor Cour.t from and the publicity committee head- the College of Business Adminis- ed by the Secretary of Pdblic Re- tration. lations, Morty Freedman. Crews Reports Speeding Complaint Secretary of VeteiAn6s Affairs, In response to numerous com- John Crews, reported- that a War plaints about speeding in the vicin- Assets Administratiae-man would ity of the campus the council pass- in obtaining surplus..p.roperty. Af- ed a motion to request Gainesville ter Committee reports, President city authorities to establish a re- Harry Parham appoiln'ed a number stricted traffic zone around the of committees to further student campus. mitted, Lee stated. All applica- projects. tions. should be typed, activities projects grouped and submitted at Florida To investigate the. possibilities Union desk before Nov. 5 at 5 p.m of acquiring a printing plant to Won't Lower Standards serve the various campus publica- ". The, proposed changed will not tions, Parham appointed a com- in any way lower the high stand- mittee headed by Frank Duck- ards required for entrance into worth e Florida Blue Key, but will permit New Committees students to become members who Other committees selected were go to school the year around, who the student laundry committee otherwise could never meet the headed by Don Jones, the labor residence requirements," Lee said. committee with Secretary of La- Sbor Sarm Gibbons in charge, the REST AND'RELAX THIS WEEK BE PREPARED FOR "FLA.-GA." GAME TODAY SATURDAY NANCY KELLY BUSTER CRABBE IN .- IN. - "WOMAN WHO "GHOST OF CAME BACK" HIDDEN VALLEY" SUNDAY -MONDAY Lakeland's Own Movie Star Frances Langford and Robert Armstrong I in "ARSON SQUAD" TUESDAY "OUR HEARTS WERE :GROWING UP'.'. WED., THURS. "TO EACH SHIS OW ' His ow," Westminister Continued from Page ONE churches are cooperating by end- ing services Sunday night earlier than usual. Sunday Program The program Sunday will begin with "Exaltabe Te Domine," by Giovanni Pierluigi da Palestrina. It will include such selections as the delightful "Of Time and the River," by Marton Gould (commis- sioned by and composed for the Westminster Choir and being .pre- sented for the first time this sea- son),, and "Cindy," with arrange- ments by Harry Robert Wilson. The last selection of the program will be "Navajo War Dance No. 2," Arthur Farwell.. Monday's p ogram will com- mence at 8 p.m. with numbers from "The Spirit Also Helpeth Us," Johann Sebastian Bach. It will include "Roger Young," by Frank Loesser (which is dedicated to the men of the U. S. Infantry, World War II), with arrangements by rCarlton Martin. The last se- lection is "Navajo War Dance No. 1 ," Arthur Farwell. .Critics Praise Choir Music critics have been lavish in their praise of the bass section of the WestminsternChoir. It might be compared with the famous bass of the Russian choirs in that it acts as the foundation of the choir's structure. The sopranos form a clear but delicate part, like the fine, decorative, interlacing' lines found in a Gothic cathedral spire. Dr. John Finlay Williamson, founder the Westminster Choir, will conduct the concert. Frolics Continued From Page ONE secretary of social affairs, who is in char e of arll ticket sales -I,. Boxing Final Scheduled Tonight; Phi Delis Hold Edge On Murals Trophy rN'S RPA.4 ED No PODTBALL 'TIL HE CAME 5To 'THE Li P 1. Two Events This is one of a series of weekly you for or against a Veteran'S The events, including a band polls conducted by the campus bonus? The results of the tabula. concert on Friday afternoon, Dec. chapter of Alpha Phi Omega, na- tion follows: 6, :and a dance that night ,both tional service fraternity in ordei' to 'For: 640// presided over by Les Brown and obtain a representative cross-sec- Against: 3 his. orchestra, will sell as follows: tion of opinion on questions and is- Aganst: 30% Concert, $1 plus tax, stag or drag; sues that are of particular con- No opinion: 6% Friday night dance for non-frater- cern to the students on the campus Question for next week will bd nity men, $2 plus tax, stag or of the University. "Do"you think the University 'of drag. The question this week: Are Fla. needs a larger infirmary?" ISTA~r I I By Bill Boyd After three nights of fighting the Intramural Boxing tournament has been narrowed down to 22 men with eight eliminated last night as the fights have'been staged before one of the largest crowds ever to witness an ini- tramural contest. S I | |The total attendance for the first 1 three nights has passe',d the 4500 ill I mark. With the last of ,:he semi- S ... .. finals fought off last night the fi- 1 nals of eight matches will be stag- ed tonight. Eight bouts last night P \ass Receiver narrowed the field to sixteen men and from the looks of things, the Phi Delts have a decided edge on Big Broughton ("Brute") Wil- the team trophy. liams, Fighting Gator right end, is Pikes Send back in the No. 1 spot in the list They h ead the list of 'nd he con- of th enation's pass receivers. Not testants still in the thict of the only does he lead all college spiral fight with five men. Onet of their snatchers, but he has racked up men has already reached tie finals nearly twice the yardage of his with four in the semi-finals. Next nearest competitor, Louie Mihajlo- ith four incomes the semi-finals.with Next vich, of Indiana. in line comes the Pikes with two Sn e f Indianmen in the finals, TEP with one in Snagged 23 Passes the finals and one in th, semi- In the North Carolina game last fials, KA with one in finAls and week, Williams snagged eight one in semi-finals, Phi Kaps have throws to add 166 yards to his ex- two left in the semi-finals. There cellent record, which now stands are also two independents-in the at 23 passes caught in five games semi-finals. Having one man n the for a total gain of 433 yards, put- finals are the Pi Kappa Phi, Beta ting him 207 yards ahead of the Theta Pi. Also with-men still in No. 2 receiver, Mihajlovich, who the semi-finals are All-stars, Delts, has snared 18 throws in six games Sigma Nu, Kappa Sig, ATO, Delta for a total of 226 yards. With Sig, CLO. four games remaining on Florida'sSig, CO. slate, Williams has a good chance Feature Bouts Tonight to make an all-time record for' Opening the fights tonight will passes received, be Bresllar, TEP and Robbins, PD'T in 120 class, followed by Davidsoni, V M Ap a KA, and Pena, PKP in the 127, ets ay Appeal Melton of Beta and Hess of Pikes New t' r L_' in the 135. New Earnings Law The other fights with the unlim- B h S Br'y ited as an exception, depend on the By John S. Brady outcome of last night's fights in The highly controversial issue :the semi-final bracket. behind the "Productive Labor" The unlimited matches will pit forms, distributed to campus vet- Bill Widden, Pi Kappa Alpha, 1945 erans last week, has been settled champ against Goldberg TER. as far as the University is conr- This fight has stirred up much in- cerned. "The attitude ,of the terest as both men are top c6noi University will be one of complete tenders and should give a good compliance and cooperation with fight for the large crowd that is the Veterans Administration," said expected to attend. Dean Price, veterans' counselor, Pena-Davidson Bout early this week. Another fight that should be New Deduction tops is the Pena, PKP, and David- The situation arose from the son of KA's. Pena won over Spic- announcement of Public Law 679, 'ola, last years champ, a gruelling passed to amend the existing P.L. battle, and Daviason has shown he 346. .This new law provides for is tops by two decisive wins. the deduction from veterans' sub- In the 13o class Bill Hess of sistence allowance any earnings PKA and Melton of Beta are ex- over $110 a month. The measure pected to stage a battle royal as was directed primarily at correct- both boys are fast and 11ard hitters. ing "on-the-job training" abuses. This could very easily be the top University Cooperates fight of the evening with two such Although the University has de- powerful and fast sluggers. cided to co-operate with the VA in Boxing Rules Aired this matter, veterans, either indi- The Intramural department vidually or through the veterans' wants to call to the attention of organizations, have the right to the fans, according to intercol- appeal the enforcement of the new legiate rules when a fighter is law. However, these appeals .must knocked down he must take the be made to the director of the Vet- count of nine, and also when a eranzs Administration or directly fighter is cut badly enough to war- to Congress, as the measure orig- rant stopping, of the fight that the. inated with them. figher with the most points at that stage of the battle is .named Committee Holds te Forum Monday Air Base On Monday, Nov. '4, at 8 p.m., c c ,,ntii'i From Page ONE the Florida Union Forum Commit- tee will present its first regular case of cold weather, while the forum of the year in the Union Universiity gym cannot. It is much auditorium. The topic of discus- more modern, with excellent light- sion will be "The Crowded Condi- ing effects, and it can be decOrat- tions .of Gainesyille What -Has ed. The air base gym has a stage Been Done and What Can Be for the band instead of having to Done?" construct platform on the cam- Mr. Sam Ham, secretary of the pus. gym floor, and there are con- Chamber of Commerce, and Mr. M. cessi6n rooms off the dance floor B. Parrish, Jr., local contractor, at the base gym." will represent the town of Gaines- Transportation ville and Dan Williams, Mayor of The only great disadvantage is Flavet 1; Ben Mayberry, spark the, transportation difficulty, andi plug in the new grocery co-op, andSherouse quickly added that ade- Tom Fridy will represent the stu-quate transportation by bus will dents. One other representative be furnished to and from the cam.- for the town will be present. pus and city. POLL OF i OIN ION By Alpha Phi Omega Florida4/ gator Editor-in-Chief ...... Morty Freedman PManaging Editor ....... Walter Crews Business Manager ...... Edgar Davis EDITORIAL BOARD F 1 "HoW" Gaines, Executive Editor: Johnny Jenkins, Dee \1i, Wagenen, Associate Editors; Jim Gollacheck, As- s,:scant -Managing Editor; Elliot Shienfeld, Features Edi- ':c,; Harold *Herman and Bobb MacLeish, Co-Ndws Edi- t.-3; Berna'rd Ward, Sports: Editor. EDITORIAL ASSISTANTS CGorge KoWk'aba'ny, Asst. News Editor; Ted Shurt- lef". Asst. Features Editor; Jordan Bittel, Asst. Sports Eo;tor; Leo Selden, Copy Editor; Al Fox, Proof Ea-tor J. Baxley,- Rewrite Editor; Hank Gardner, Head C,'toonist; Horanc Davis, Jr;, Fraternity Editor; Jean -'tmore, Society Editor; Lois Scott Weiss, Asat. ".'iety Ed.; Danny Kohl, Exchange Editor; Lou MNei- se Office Manager; Leo Osheroff, eHad Typist; John .:. 6rady,, Asst. Rewrite Editor; Les GleichenhalAs, A.: .isements Editor. BUSINESS STAFF Fen Richards, Assistant Business Manager; Albert C ;,Iton, Advertising Manager; Walter Martin, Cilec- t, Manager; George F. Gillespie, Jr., Bookkeeper; E,'.l Pearson, Business Assistant. ' Third Party In Offing ? S, -.! - 1n another column of this issue there is a "Letter to the Editor" protesting the in- j -itices perpetrated against non-fratern- Smen on this campus, insofar as politics : social life is concerned. The writer of the letter calls for the i' nationon of a third party to be known as zt.e Independents, and which would be l.'iited solely to non-fraternity men. We n; ree wholeheartedly with the author of .t e. letter that the independents on this V mpus are getting what might conserva- tiv ely be called a "raw deal" so far as rm'resentation goes. Roth political parties, with an equal : loiunt of fraternity backing between tf.em, nominated approximately 50' fra- rrnity candidates and 50% non-fratern- i" candidates in the last election, in spite u- the fact that the 2,000 fraternity men o- this campus comprise only 30% c of the -.'-al enrollment of the University. We agree that the independent has -.en treated shabbily by the existing pol- i,:cal parities; we agree that the time is r'i)e for those two parties to correct these i justices or for a third party to be estab- l.,h.ed to correct these inequities; we dis- za'ree, however, that such a party should, b, formed from non-fraternity men alone. Such a move would tend to create a cl.,avage, a wide breach, between those i.. fraternities and those not in fraterni- ti- s. it would'telnd to set up a social dis- t.iction, which in fact, does not exist. A ti ird party could represent predominant- tl the-interests of the independent-but )n. order to be a true cross-section of e.'mnpus representation, this party should have a proportion of its representation al. Ivted to fraternity men. In ione paragraph of his letter, the writ- ec made reference to the fact that the In- tz'er-Fraternity Conference had allowed Friday r;,'ht's Frolics dance to the no'n- >'atOrnity men while keeping the "choice" SSaturday night date for the fraternity r1en. The writer also called upon non- f aternity men to boycott Fall Frolics. While the letter was obviously written i:- good faith, the real facts relating to t'he. Inter-Fraternity Conference's stand on Frolics do not warrant any criticism of the actions taken by that group. In the first apace, Fall Frolics is, and always has been a function sponsored by the 1FC. in v.addition to that fact there are these to c insider: 1. The IFC must carry the full financial r sponsibility for the success or failure of t e function. 2. Over $3,000 has already been raised b., IFC members and placed in a local bank as security, upon the stipulation of tihe booking agents, 3. The IFC is an independent campus organization, which, like the Rotary Club Co American Legion, may limit attend- ance at its functions to its.members alone if it so desires. 4. In the past, as is being done this year, non-fraternity meni have always at- BY LES GLEICHENHAUS Well, she's here again. Yep, the grandma of all the red-hot mamas is wielding her big stick again. It's B. Stanwyck whNo makes a very fine impression on her aunt's head by parting her hair with lead cane! Yes, a suspenseful, excit- ing melodrama of murder, lust, deceit! and real- istic romance was unltuded on the screen of the Florida last night in the form of "The Strange .Love of Martha Ivers." It was shown to an.au- dience which remained spellbound throughout the telling of this grim, but fascinating drama. In fact, it was so quiet in the Florida. last night that. you.couldn't even hear a popcorn box drop. "The SL of MI" -tells a sensationally unusual tale. an insight into the diabolic mind of a com- pletely evil woman. As a child, she had beaten her wicked ole aunt to death, an act which sets the patten for her dark future. Her outlook and actions shadowed by the guilty knowledge of mur- der, she senids an innocent man to the chair for the crime, flaunts, her infidelity into the face of, and completely dominates her weakling husband, and twice attempts to kill the man she loves in her own warped way. This picture is typical of the Andy Hardy series-bring the kids along- they'll love it. CAMPUS CHATTER-Don't miss the Univer- sity's. Glee Club's "Skit Get-together" on, the eve of the Florida-Georgia game, in the Roose- velt Hotel in Jax .... For that cold weather just around the corner lake a reading in L and L's for those popular corduroy combos of slax and sport ja-ckots woolen tartan shirts in Silver- juan's Jantzen all-wool blazers in Wilson's. The frat houses along mortgage row are bui.zing with plans of decor and festivities for the biggest of all Fall Frolics in December. Midnight show for Gatowis at the Florida Sat- rite is "Personality Kid"-the audience participa- tion is a welcome relief from the featured hami and hammesses that flitter across the silver screen S.. Don't forget to keep Novemoer third and fourth open to hear the Westminster Choir. Trek on over to the gym' tonight and see the finest. of all intra-nmural presentations-boxing-it is the. big- best draw of all intra-mural sports One rea- son the football season is such a popular time of the year is because it's the only time a guy can walk do\mn the street with a blonde on one arm and a blanket over the other and not encounter raised eyebrows. See Joan Davis as a calculus instructor who unknowingly writes a risque novel about a gal named Llulu--it's a riot. Starting Tuesday at the .Florida-"She Wrote the Book." For a book you cannot put dox wn read "The Hucksters" it's out of this xwo:ld. Coming to the Florida this week-end is a gem of a pic--"Anna and the King of Siam," with Irene Dunne. It marks a new high in pic entertainment. See it, by ,all means; it's that rare kind of movie you'll want to see ag-ain and again. tended dances sponsored by the IFC. None have been closed affairs. 5. The only reason the two dances have been divided into fraternity and non- fraternity dances instead of splitting the dances, is because of the limitation on space available for the dance. While we firmly believe that the sug- gestion made in the letter to the effect that the student government should spon- sor its own dances, is a worth-while and progressive one, we are certain that the IFC, if anything, should be commended for its handling of the coming Frolics. leapts Te The Editor University of Florida m d l f d crac for all univer- Gainesville, Florida sities to look up to. U. S. A. I would be interested in receiv- Dear ing comments on .my proposed I will was agreably cheerful if plan, particularly from the staff one of the pupils,, boy, write me of the "Alligator." ... 1. for support correspondence... "- Yours for better representation, - I no knew write good the eng- F. REYES. lish. Please write a long letter as I EDITOR'S NOTE: We do not am waiting impatiently for yours believe, as Mr. Reyes has stated news. Send me one your picture, that the Dixie Party has more The friend, fraternity bonds than the Gator NEUSA PIMENTEL. Party. For further comment-on -.---- Mr.. Reyes lettersee the editorial EDITOR'S NOTE: A picture column. The ALLIGATOR W.el- of the very lovely Miss Pimen- comes such letters of construct- 'tel, age 7, may. e -ben -b ivpe ,*ritic-mrn of campus,affairs. contacting.me in ihe ALLIGA- I .".. 1 TOR office. Her address for Mr. Morty Freedman, those interested, is: Miss Neusa Editor-in-Chief, Florida Alligator, .Pimentel, Piza Almeida 17. i La Gainesville, Florida. Ezabvl. D. Federal, Rio de Jan- Dear Sir:. eiro, Brazil. 1I am penning this note not so "mu:h I.-, ..nr'lanir, but to.point up Editor a .:iib.jet that to my .knowledge The Alligator has been neglected. It concerns University of Florida our library and their book circu- Dear Mort: nation system. Dean Beaty sent me over to see In checking out a tooK you sign you to have an article put in this your name, thus giving anyone a week's "Alligator" as regards the clear record as to who has this Honor System. I have the apple book and the date. This is corn- concession and am having to fix a mendable. Of course this might be box with a slot in it and lock it up mistaken (we will mention this to keep the receipts from being just for the record) by the-bor- stolen. I lost $5.00 the first week. rower as a question of 'honesty, This past Monday $7.85 was stolen after all if he borrows a book (either in apples or money; I have from his instructor or a friend he no way of, telling). Tuesday $7.96 does not have to issue a receipt. was stolen and Wednesday $19.66 However, as we know, in a library was stolen. Naturally, since I was the receipt is useful as an accurate losing money, I couldn't continue count on.the demand for and con- to put out. the apples for sale sequently the popularity of a par- under the old system. ticular book. Under the new system students Our grievance though is in the won't be able to make change, as system of returning these books. the money will be locked up. I just The book is merely laid on the cir- hope the apples aren't all stolen. culation desk and you get no re- F. CLYDE STEVENS, JR. ceipt for its return. Again we state that honesty, this time on EDITOR'S NOTE: Is honor the part of the librarians, is of no dead among Florida men? importance. While the book is laying on this desk the character Mr. Morty Freedman, -ditor just behind you may appropriate The Florida All.at,! it. The book also stands an ex- University of Florida cellent.chance of being shelved be- Dear Morty: fore being checked in and if it is Being an avid reader of the "Al- shelved wi'ongly, it triples the ligator" with particular emphasis chance that the unsuspecting bor- on the last two issues, I am begin- rower wil receive a card asking ning to wonder if the University for return of the book and later of Florida is being run foi the demanding payment. It's at this minority or the majority in res- point, when you dig into your pect to its political and social life. pocketbook, that you .begin to The minority and majority in this wonder if ,an improvement isn't in case being fraternity and non-fra- line! eternity respectively, Just dash us off a receipt with First the political situation, the call number, dates, and a sig- This last election is a disgrace to nature on it. This would, suffice a democratic institution. Not only and would entail very little extra were the candidates mostly frater- work and, even so, there are plenty nity but one party was even ac- of veteran wives that would love caused of holding a fake- primary, a job. the stench of which included the How about some protection ? odors of bossismm." The primary WM. B. SUMNER. is the basis of a democracy, and the voting the duty and privilege Parhar Censur-S of each of its citizens. The best . place to educate our. people in this Camnus Vandals matter is in the school systems of C' V da our country. We have two parties on the Vithin the past two weeks a campus, the Dixie and the Gator.- very base sotf vandalism has The Dixie is considered to be fra- P t id a eternity and the Gator is supposed- toms .antrr tradithe ideaons of cus- ly a middle-of-the-roader, but it tonis and teaditons of Florida still remains that it is primarily newn slo of indignity y reah - fraternity. No matter who wins rating the memorial dedicated the election it is still fraternity. to Doctor Mmrphree. In other words, the minority.rules. Perips ti was done in a To combat this situation I sg- spirit of mischievousness or just gest the -formation of a third par- platn thoughtiessnes. Howev- ty to be known as the "Independ- e it miht hav been I iall ents" and to be composed of non- true men ef Floria toshelp put fraternity men. This party to emenofFloatoheput .foster the principles of a.democ- a, stop to this disgrace to our racy b having primaries, run hon- student body. racy by having primaries, runhen- A a further clinching point, estly, so that the best qualified I ight add that subha dfc- candidates mn-ay be chosen. Fur-. ing o. public memorials Is in their, that this party try to edu- isolation of the ferai law and cate the students as- to their duty unolation aof the feoneral law and and privilege of voting. With these I feel e maintain o owna points in mind we can then have a hos without resor to any out- student government based on dem-I house wtholt restru to .s ot- ocratic principles and representing side forces. Let us do so, the majority. HARRY PARHAM, My second point is that of the ri dent ersy of social aspects of campus life. I Florida Student Body. have just finished reading the ar- ticle on the proposed plans for Fi a.N f il Fall Frolics and was so happy to C. learn that the IFC had gTaciously consented to recognize non-frater- t .FOr N VNO 1 nity men by setting aside one "'- night for them, Friday night, and Technicolor pictures of the Flor- keeping the accepted choice spot. ida-North Carolina football game Saturday night, for themselves. I will be- shown in the University feel that due to this discrimination auditorium on Friday, Nov. 15, at all non-fraternity men should re- 8 p.m., it was announced this week fuse to support this dance, by Bill Moor, chairman of the My solution to the problem is Florida Union picture show-comn- this: that President Harry Par- mittee., ham appoint a committee, repre- Next Tuesday the pictures of the sentative of all factions, to plan Florida-Vandy game will be shown future Frolics or other social ac- in the Florida Union auditorium, tivities on the campus so that the University auditorium being these activities will be for the stu- previously engaged. However, pic- dents of the Univerl-sity and not for 'tur.es of the North Carolina game a selected few. will be shown in the University au- Let us make this University a ditoriun. Staniey Fletcher Murals Boxers Slug It Out Featured Nov.7 Stanley Fletcher, an outstanding i erpreter of the wbrks of Cho- rt, wilt be presented:in a request concert of Chopin numbers in the Cniversit at uditorint Thursday, hree, Univer sity oron of Muist recent- ic announced. Proceeds piano concert are bet will e used for the establishment of a Approximately 1400 students turn out each night to watch the tricounceddin rphrsstated ta n - .uch a library ivould be invaluable tonight in the New G *m. -to music-loves and that the proj- .--t is most worth while.qst h No Ads1nce Sale There will be no advance sale missionn to the concert will be 60 centss e for students and s81.20 for che general public. n Florida Union bBridge Tourney, Victors Named By Charles Geer For the first time in four years the walls of Florida Union echoed 'co the cries of "Four no trump," -'Double':" "Redouble!" Last Fri- day evening the First of a series f* bridge tournaments got under -vay. Over twenty tables were set up in Florida Union Auditorium -o accommodate the large crowd rf bridge addicts who signed up "?or the event. Winners and runners-up of the initial tournament last Friday vith their respective scores are as oll.ows: North-South: Young and AitcLaughlin, 209; Murray and Mil- wr, 188 1-2. East-West: Nelson nmd Walker, 198; Winfrey and hrey, 194. Finki Promises More Friday's event was the first of e v e r a 1 bridge tournaments planned for the current school year by the Florida Union Com- mittee on Tournaments. Abbey Fink, chairman of the committee, "stated that another bridge event is scheduled to be held in about three \veeks. Program For Week Of Nov. 1st LAST TIMES TODAY Penny Singleton ir "Life with Blondie" Basil Rathbone in "Woman In Green" Sat. Sun. Mon. BARIARA That doulte.-rouble dame! " That 'God ii My Co.pilot' guy' C c c a,. SYDN , GREENSTREET REGINALD GARDINER S. Z. SAKALL TOBERT SHAYNE PETER GOODREY screen Play by Lionel Houser naee Commaneini frof a" Original ilory by Aileen inrm and Tues. Wed. Preston Foster 'in "TWICE BLESSED" Basil Rathbone in '"ORESSED TO KILL" Ommitlee Investigates eed For Campus Press By Jack Bryan A long-standing dream of many Florida students and faculty members may become a reality in the. near future. Student Body President Harry Parham announced the appointment this week of Frank Duckworth, Edgar Davis, and Louis Leibovitz to a committee to investigate the feasibility of es- tablishing a University printing plant on the campus. SV V Headed By Duekworth Duckworth, spokesman an d a chairman of the committee, dis- Aclosed Tuesday that the group will Deadline follow two basic plans of inquiry. They- will first canvass the res- By Alan Westin peceive deans, department heads, staffs of student publications to Official deadline for all organ- determine to what extent each is izations to contact the 1947 Semi- handicapped by the present lack nole was set at Nov. 17, announced of a University press to do their Alan Westin. organizations editor. printing tasks. All presidents, secretaries or fac- estimates from each official as to ulty advisors are requested to ap- the amount of material each would pear for an interview beginning desire published if the cost were Nov. 4 from 3:30 to 5 p.m. Monday much cheaper and the quantity un- through Friday, limited, as it would be if we had Dates Set our own press. h eill Secr'c Estimates Sw w'wS lWU !a 6ALw& l a tafia4I 42 a a a At this time dates will be set ... .-. -".... for the taking of photographs Finally, according to Duckworth, By Harold Herman since the section has inaugurated if definite need of a press is prov- Ronald Reagan and Jane Wyman, well known screen the policy of action shots instead en the committee will compile t-of the individual pictures. The their findings, and will turn to au- stars, will do the preliminary judving and pick the final- persons representing the groups thorities in the journalism depart- ist for the Seminole Beauty Queen, who will be accorded should also see Al Sheehan, busi- ment and other experts in the pub- full honors and will reign over Fall Frolics weekend, Pat ness manager as soon as possible, locations field to secure, estimates O'Neal, Editor of the 1947 Semi- to pay for their pages in the book.! and technical data as to the actual nole, announced this weeK. Active Organizations size, type, and cost of a printing Snole announced ths wee Actve Organizations plant which would be adequate to Tew INamtes The queen will be chosen from; The following organizations are meet University requirements. " l An l photographs submitted by mne stu- listed as active this year and must "M ale Animal dents. The deadline for these pic- see the staff before the date men- tures will be on November 22. tioned above: Ig PrOduction Crew Portraits are perferred and the IFC, Blue Key, Florida Players, Phi Eta Sigma pictures should be left at the University Glee Club, University Op T Fr h The managers for the production Florida Union desk with the name Symphony Orchestra, F i g h t i n Open o ros c and the hometown of the girl and Gator Band, Florida Union, Gator crew which will work on the Flor- the name and address of the stu- Pep Club, Cheerleaders,, "F" Club, At a meeting last Tuesday night ,da Players' presentation of the denrts on the back. University Radio Guild, Lyceum of the Campus Chapter of Phi Eta three-act comedy, "The Male An- After the two -screen stars pick Council and University Debate So- Sigma. national freshman honor- imal," to be presented on Nov. 18, the top beautys, the photographs city. Also, all organizations as- ary fraternity. Bob Connelly was 19, 20, have been chosen, it was will be returned and the finalists sociated with colleges and curricu- selected to represent the member- announced this week by Professor will be invited to ,the University la should sign up for their pages; ship at the national convention.to Roy E. Tew, director of the play. of Florida campus for the big these include Law, Business Ad- be held soon at Iowa City, Iowa. Ten Named weekend. ministration, Journalism, Engi- President Frank Stanley then Those chosen were Leldon Mar- neering, Mathematics, Chemistry, appointed .committees to handle tin, assistant to the director; Dick CELEBRITIES CONTACTED Military, Forestry, Horticulture, arrangements for the forthcoming Jones, set designer; George Har- The finalists will be judged at Les e-Medical, Agricultural and th- banquet and initiation. bold, house manager; Ray Noble, Brown's concert on Friday after- 3.5 Average Needed program designer; Dick Jones, Brown's concert on Friday after- Third Group The requirement for member- Marvin Ramber, electricians; Rus- noon and from them, the Seminole The third group arm tne clubs; ship in Phi Eta Sigma is an ay- sell Foland, makeup artist; Jimmy Beauty Queen will be selected, such as the International Relations erage of 3.5 for the first semester Miller, sound effects manager; Those finalists who aren't able to Club, Society for the Advancement or first and second semesters of Elihu Edelson, Oscar Rappaport, attend will appear in the beauty of Management, Fine Arts Club, attendance at the University. poster designers. section of the 1947 Seminole. Well Block and Bridle, Astronomy Club There are a number of students Students are still needed for the known celebrities are bein- con- and all others that may be active on campus who are eligible for production crew. Those interest- or intend to reactivate this semes- ed are asked to watch hthe Orange tacted to appear here, and the ter. Any professors knowing of membership, but have not filled and Blue bulletin for the time and judge for the final selection will clubs that will be started anew are out application forms. If you can place of the next meeting: be announced later, asked to drop their names on a- meet the requirement listed above, postcard and mail it to the Semi-: please see Dean-Price; Language nole office immediately. and file your plication. i, and file your 'application. Weekly Program CONTINUOUS FROM 1.r0 P.M. 40c 44c TODAY & SATURDAY Students 30c on Saturday SUNDAY & MONDAY MAGNIFICENT! A UNFORGETTABLE! . I TUESDAY & WEDNESDAY FUN GOES WHAMOROUS! ." JOAN .- ,, : ' DAVIS "- ,s' ' JACK OAKIE . MISCHA AUERsday "CAESAR CELOATRA" Starts Thursday "CAESAR &t CELOPATRA" The Next Seven Days FRIDAY :: Hillel Foundation, Fla., Union 208, 7:30 p. m. Carnegie Set, Fla., Union 305, 3:00-5:30 p. m. Masonic Grcup, Fla., Union Aud., 7:30 p. m. SATURDAY Exec., Committee, Gator Vets, Fla. Union 208, 1:30 p. m. SUNDAY Westminster Choir, University Aud., 8:30 p. m. Hillel Foundation, Fla., Union 209, 7:00 p. m. Carnegie Set, Fla., Union 305, 2:00-4:00 p. m. MNIONDAY Westminister Choir, University Aud., 8:00 p.m. Alligator Staff, Fla.., Union, 8, 7:30 p. m. Hillel Foundation, Fla., Union 208. 8:30 *p. m. Carnegie Set, FIa. Union 305. 3:00-5:00 n. m. Wanberg Committee Room, Fla.. Union 7:00-8:00 p. m. 6:00-7:30 p. m. Alpha Kanspa Psi Smoker. Fla.. Union 305, 7:30 p. m. Forum, Florida, Union Auditorium, 8:00 p. m. TUESDAY University Flying' Club, Florida Union 210, 7:00 p. m. Coop Grocery, Florida Union 208, 7:30 p. m. I. F. C., Florida Union 209, 7:30 p. m. A. V. C., Florida Union 305, 7:30 p. m. Carnegie Set, Florida Union 305, 3:00-5:00 p. m. Cavaliers, Florida Union 308, 7:00 p. m. Free movies, Same time as Monday. Florirlia Union Auditorium. Florida, football movies, Florida Union Auditorium, 8:00 p. m. APO Poll of Opinion, Commititee Room, 7:00 p. m. Free movies, Florida Union Auditorium, 12:00-1:30 p. m. and WEDNESDAY Carnegie Set, Florida Union 305, 3:0G'5:00 p. m. Veterettes, Florida Union 305, 7:30 p. m. Free movies, 12:00 to 1:30 p. m. and 6:00 p. m. Fla., Union Aud. THURSDAY Mathematics Olub, Fla., Union 209; 4:00 p. m. Christian Science, Fla., Union 210, 7:30 p. m. Los Picaros, Florida Union 210', 8:30 p. m. Carnegie Set, Florida Union 305, 3:00-5:00 p. m. Alpha Phi Omega, Florida Union 305; 7:00 p. m. Newcomers Club, Florida Union Lounge, 3'00 p. m. Free movie shows, Florida Union Audit.rnuir. 7:00 and 11:00 p.m. Stanley Fletcher, Piano Concert, Uri-.ersity AUd., c..15 p. in. Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2011 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Powered by SobekCM
http://ufdc.ufl.edu/UF00028291/00033
CC-MAIN-2017-26
refinedweb
8,406
63.29
WPF Interview Questions WPF Interview Questions Q. Q.. Q. Name the namespace required for working with 3D. The namespace required for working in 3D is System.Windows.Media.Medi3D. Q. Is it right to say that WPF has replaced DirectX? No, WPF can never replace DirectX. WPF cannot be used to create games with stunning graphics. WPF is meant to be a replacement for windows form, not DirectX. Q. What are dependency properties? Properties that belong to a specific class but can be used for another are called the dependency properties. Q. How can the size of StatusBar be increased proportionally? By overruling the ItemsPanel attribute of StatusBar with a grid. The grid’s columns can be appropriately configured to get the desired result. Q.. Q. Why should WPF be preferred over Adobe Flash? WPF is a more recent technology and thus has the latest development tools. It supports a broader range of programming languages and has a robust control reuse. Q.. Q. Name the methods present in the DependencyObject. It has three objects, namely: - SetValue - ClearValue - GetValue Q. Write about PRISM. PRISM is a framework for creating complex applications for WPF, Silverlight or Windows Phone. PRISM utilizes MVVM, IC, Command Patterns, DI and Separation of Concerns to get loose coupling. Q.. Q. Describe CustomControl briefly. CustomControl widens the functions of existing controls. It consists of a default style in Themes/Generic.xaml and a code file. It is the best way to make a control library and can also be styled or templated. Q. Name the common assemblies used in WPF? - PresentationFoundation - WindowsBase - PresentaionCore Q. Define Path animations in WPF Path animation is a type of animation in which the animated object follows a path set by the Path geometry. Q. Can WPF applications be made without XAML? Yes WPF applications can be created without XAML as using XAML in WPF is a matter of choice. Q. What are the types of windows in WPF? WPF has three types of windows: - Normal Window - Page Window - Navigate Window Q.)); Q.. Q. Explain Routed events in WPF. An event, which can invoke handlers on more than one listeners present in an element tree, instead of the single object which called the event, is known as a Routed event. Q.. Q. What are the various layout panels in WPF? They are: - Stack Panel - Grid Panel - Canvas Panel - Dock Panel - Wrap Panel Q. Name the important subsystems in WPF The major subsystems are: - Controls.Control - DependancyObject - FrameworkElement - Media.Visuals - Object - DispatcherObject - UIElements Q.. Q. What is Difference between Page and Window Controls in WPF? The basic difference is that Window Control presides over Windows Application while Page Control presides over the hosted Browser Applications. Also, Window control may contain Page Control, but the reverse cannot happen. Q. What are Attached Properties in WPF? Attached properties are basically Dependency Properties that allows the attachment of a value to any random object. Q.. Q.. Q. What is the method to force close a ToolTip, which is currently visible? It can be closed by setting the tooltip’s IsOpen property to false. Q. Q.. Q.. Q. Write about UserControl in brief. UserControl wraps existing controls into a single reusable group. It contains a XAML file and a code. UserControl cannot be styled or templated. Q. What is the way to determine if a Freezable object is Frozen? “IsFrozen” property of the object can be used to determine if the freezable object is frozen. Q. What is the unit of measurement in WPF? All measurements are made in device-independent pixels, or logical pixels. One pixel is 1/96th part of an inch. These logical pixels are always mentioned as double, this enables them to have a fractional value too. Q.. Q. Explain Serialization? It is the process of converting the state of an object to stream of bytes. Q. Is MDI supported in WPF? MDI is not supported in WPF. UserControl can be used to give the same functionality as MDI. Q.. Q. In what sense are WPF and Silverlight similar? Silverlight and WPF are similar in the sense that they both use XAML and share the same code, syntax and libraries. Q. How to make a ToolTip appear while hovering over a disabled element? For this purpose, the ShowOnDisabled property can be used. It belongs to the ToolTipService class. Q.. Q.. Q. Can Windows Service be created Using WPF? No, Windows Services cannot be created using WPF. WPF is a presentation language. Windows services need specific permissions to execute some GUI related functions. Therefore, if it does not get the required permissions, it gives errors. Q.. Q.. Q.. Q. How can command-line arguments be retrieved in a WPF application? The most preferred method for this is to call System.Environment.GetCommandLineArgs at any random point in the application. Q. 4 State the name of the classes, which contain arbitrary content. - Content Control - HeaderedContent Control - Items Control - HeaderedItems Control Q. Which NameSpace has ‘Popup’ and ‘Thumb’ controls? The namespace system.windows.controls.primitives has ‘Popup’ and ‘Thumb’ controls.
http://mindmajix.com/wpf-interview-questions
CC-MAIN-2016-44
refinedweb
843
60.72
0 Hi I am very new to java as its part of my course and I am stuck I have written part of this basic code below import java.util.Scanner; import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.imageIO; import.java.awt.Color; public class FinalExam { public static void main(String [] args) throws IOException { Scanner keyboardInput = new Scanner(System.in); System.out.println("Input the address of the image (e.g. c:\\myPicture.jpg)"); String imageLocation = keyboardInput.nextLine(); File imageFile = new File(imageLocation); BufferedImage storedImage = ImagIO.read(imageFile); } } does anyone know I would change this code so that you would be allowed to supply the name of an image file a a command line argument when issuing the command to run the program? Edited 6 Years Ago by __avd: Added [code] tags. Encase your code in: [code] and [/code]
https://www.daniweb.com/programming/software-development/threads/244823/command-line-arguments-help
CC-MAIN-2016-50
refinedweb
148
52.76
Why=15 data-cke-widget-drag-handler=1> This command creates a new directory named “personal portfolio” and almost all of the works you do will be saved into this directory. After setting up the file structure, you can check whether your setup is successful or not by starting the server. To do this, run the command: $ python manage.py runserver width=15 height=15 data-cke-widget-drag-handler=1> You can now see your newly created Django site in your browser. Let’s see how to add views and functionalities to your site. The first step is to create the app. $ python manage.py startapp hello_world width=15 height=15 data-cke-widget-drag-handler=1> Here, hello_world is the name of the new app we are going to create. This command will create a directory named hello_world consisting of several other files such as After the successful creation of the app, you have to install the app in your project. To do this, add the following code. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello_world', ] width=15 height=15 data-cke-widget-drag-handler=1> Creating a view Django views are a set of classes or functions that are contained inside the views.py file. Whenever a URL is browsed, each class or function manages the logic that is processed. Add the following piece of code to the already available import render() code in the views.py file in the hello_world directory. from django.shortcuts import render def hello_world(request): return render(request, 'hello_world.html', {}) width=15 height=15 data-cke-widget-drag-handler=1> Here, we have defined a view named hello_world(). Upon function call, this will render the hello_world.html file. Now it is time to create templates inside the app directory. $ mkdir hello_world/templates/ $ touch hello_world/templates/hello_world.html width=15 height=15 data-cke-widget-drag-handler=1> The following HTML lines should be added to your file to get displayed: <h1>Hello, World!</h1> width=15 height=15 data-cke-widget-drag-handler=1> Now, a function for handling the views and templates for displaying it to the user has been created. The last step is to attach the URL which lets you see the page you have created. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello_world.urls')), ] width=15 height=15 data-cke-widget-drag-handler=1> These commands check for a module named urls.py inside the hello_world app and register the URL defined inside that. For creating the hello_world.url, $ touch hello_world/urls.py width=15 height=15 data-cke-widget-drag-handler=1> Import path objects and the views module inside this module. Then a list of URL patterns for the corresponding view functions should be created. from django.urls import path from hello_world import views urlpatterns = [ path('', views.hello_world, name='hello_world'), ] width=15 height=15 data-cke-widget-drag-handler=1> Now you can see your app when you visit localhost:8000. Success! We have created our first-ever Django project! This is a simple project created only with HTML. You can also add CSS styles or bootstrap styles to the project. “We transform your idea into reality, reach out to us to discuss it. Or wanna join our cool team email us at [email protected] or see careers at Startxlabs.” Author: Deep Chand
https://startxlabs.com/django-basics-and-structure/
CC-MAIN-2022-33
refinedweb
581
50.53
operating system. There may be many programs running at the same time. So how does Windows know which program should get a particular message? Mouse messages, for instance, are usually dispatched to the application that created the window over which the mouse cursor is positioned at a given moment (unless an application "captures" the mouse). Most Windows programs create one or more windows on the screen. At any given time, one of these windows has the focus and is considered active (its title bar is usually highlighted). Keyboard messages are sent to the window that has the focus. Events such as resizing, maximizing, minimizing, covering or uncovering a window are handled by Windows, although the concerned program that owns the window also gets a chance to process messages for these events. There are dozens and dozens of types of messages that can be sent to a Windows program. Each program handles the ones that it's interested of Windows API. For now, it's enough to know that LPSTR is in fact a typedef for a char * (the abbreviation stands for Long Pointer to STRing, where string is a null terminated array and "long pointer" is a fossil left over from the times of 16-bit Windows). In what follows, I will consequently prefix all Windows API functions with a double colon. A double colon simply means that it's a globally defined function (not a member of any class or namespace). It is somehow redundant, but makes the code more readable. int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdParam, int cmdShow) { char className [] = "Winnie"; WinClassMaker winClass (WinProcedure, className, hInst); winClass.Register (); WinMaker maker (className, hInst); Window win = maker.Create ("Hello Windows!"); win.Display (cmdShow); // Message loop MSG msg; int status; while ((status = ::GetMessage (& msg, 0, 0, 0)) != 0) { if (status == -1) return -1; ::DispatchMessage (& msg); } return msg.wParam; } First, as the ::RegisterClass API. class WinClassMaker { public: WinClassMaker (WNDPROC WinProcedure, char const * className, HINSTANCE hInst); void Register () { if (::RegisterClassEx (&_class) == 0) throw "RegisterClass failed"; } private: WNDCLASSEX _class; }; In the constructor of WinClassMaker we initialize all parameters to some sensible default values. For instance, we default the mouse cursor to an arrow, the brush (used by Windows to paint our window’s background) to the default window color. We have to provide the pointer to the Window procedure, the name of the class and the handle to the instance that owns the class. WinClassMaker::WinClassMaker (WNDPROC WinProcedure, char const * className, HINSTANCE hInst) { _class.lpfnWndProc = WinProcedure;// window procedure: mandatory _class.hInstance = hInst; // owner of the class: mandatory _class.lpszClassName = className; // mandatory _class.cbSize = sizeof (WNDCLASSEX); _class.hCursor = ::LoadCursor (0, IDC_ARROW); _class.hbrBackground = reinterpret_cast<HBRUSH> (COLOR_WINDOW + 1); _class.style = 0; _class.cbClsExtra = 0; _class.cbWndExtra = 0; _class.hIcon = 0; _class.hIconSm = 0; _class.lpszMenuName = 0; } Class WinMaker initializes and stores all the parameters describing a particular window. class WinMaker { public: WinMaker (char const * className, HINSTANCE hInst); HWND Create (char const * title); private: HINSTANCE _hInst; // program instance char const *_className; // name of Window class DWORD _style; // window style DWORD _exStyle; // window extended }; The constructor of WinMaker takes the title of the window and the name of its Window class. The title will be displayed in the title bar, the class name is necessary for Windows to find the window procedure for this window. The rest of the parameters are given some reasonable default values. For instance, we let the system decide the initial position and size of our window. The style, WS_OVERLAPPEDWINDOW, is the most common style for top-level windows. It includes a title bar with a system menu on the left and the minimize, maximize and close buttons on the right. It also provides for a "thick" border that can be dragged with the mouse in order to resize the window. WinMaker::WinMaker (char const * className, HINSTANCE hInst) : _style (WS_OVERLAPPEDWINDOW), _exStyle (0), _className (className), _hInst (hInst) {} All these paramters are passed to the ::CreateWindowEx API that creates the window (but doesn't display it yet). HWND WinMaker::Create (char const * title) { HWND hwnd = ::CreateWindowEx ( _exStyle, _className, title, _style, _x, _y, _width, _height, _hWndParent, _hMenu, _hInst, _data); if (hwnd == 0) throw "Window Creation Failed"; return hwnd; } Create returns a handle to the successfully created window. We will conveniently encapsulate this handle in a class called Window. Other than storing a handle to a particular window, this class will provide interface to a multitude of Windows APIs that operate on that window. class Window { public: Window (HWND h = 0) : _h (h) {} void Display (int cmdShow) { assert (_h != 0); ::ShowWindow (_h, cmdShow); ::UpdateWindow (_h); } private: HWND _h; }; To make the window visible, we have to call ::ShowWindow with the appropriate parameter, which specifies whether the window should be initially minimized, maximized or regular-size. ::UpdateWindow causes the contents of the window to be refreshed. The window procedure must have the following signature, which is hard-coded into Windows: LRESULT CALLBACK WinProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); Notice the calling convention and the types of parameters and the return value. These are all typedefs defined in windows.h. CALLBACK is a predefined language-independent calling convention (what order the parameters are pushed on the stack,. The relationship between instances of the same program, their windows and the program’s Window class and procedure. The message is just a number. Symbolic names for these numbers are defined in windows.h. For instance, the message that tells the window to repaint itself is defined as #define WM_PAINT 0x000F Every message is accompanied by two parameters whose meaning depends on the kind of message. (In the case of WM_PAINT the parameters are meaningless.) To learn more about window procedure study the help files that come with your compiler. Here’s our minimalist implementation of Window procedure. LRESULT CALLBACK WinProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: ::PostQuitMessage (0); return 0; } return ::DefWindowProc (hwnd, message, wParam, lParam ); } It doesn’t do much in this particular program. It only handles one message, WM_DESTROY, that is sent to the window when it is being destroyed. At that point the window has already been closed--all we have to do is
http://www.relisoft.com/book/win/1hello.html
crawl-001
refinedweb
1,027
55.24
Getting Started With Widgets In this tutorial, you’ll add a widget to a large SwiftUI app, reusing its views to show entries from the app’s repository. Version - Swift 5, iOS 14, Xcode 12 As soon as I saw the new home screen widgets in this year’s WWDC Platforms State of the Union, I knew I had to make one for my favorite app! It would be so great to see it right there on the home screen. And I’m not alone. Everyone’s doing it! Apple knows it’s on a winner and provided a three-part code-along to get everyone started. There are several how-tos already published, so what’s different about this tutorial? Well, I decided to add a widget to a sizable SwiftUI app written by a team of developers — and none of them was me. There’s a huge amount of code to sift through to find what I need to build my widget. And none of it was written with widget-making in mind. So follow along with me as I show you how I did it. You need a raywenderlich.com login, but you don’t need to be a subscriber. If you’re not a subscriber, this version of the app won’t play videos that are subscriber-only. But this tutorial doesn’t require you to play any videos. Most importantly, this is a truly bleeding-edge API at the moment. Things that appeared in the WWDC demos have changed for GM. You might still experience some instability. That said, Widgets are cool and a ton of fun! Getting Started Download the project materials using the Download Materials button at the top or bottom of this tutorial. Before you open the starter project, open Terminal, cd to the starter/emitron-iOS-development folder, then run this command: scripts/generate_secrets.sh You’re generating some secrets files needed to run the project. Now open the Emitron project in the starter/emitron-iOS-development folder. This takes a while to fetch some packages, so here’s some information about the project while you wait. Emitron is the raywenderlich.com app. If you’re a subscriber, you’ve surely installed it on your iPhone and iPad. It lets you stream videos and, if you have a Professional subscription, you can download videos for off-line playback. The project is open source. You can read about it in its GitHub repository, and you’re certainly welcome to contribute to improving it. The starter version you’ve downloaded has a few modifications: - Settings are up-to-date and the iOS Deployment Target is 14.0. - In Downloads/DownloadService.swift, two promisestatements that caused errors in Xcode beta 1 are commented out. The download service is for the Professional subscription, and you don’t need it for this tutorial. - In Guardpost/Guardpost.swift, authSession?.prefersEphemeralWebBrowserSessionis set to false, which avoids the need to enter login details every time you build and run the app. You still have to tap Sign in, which prompts you to use raywenderlich.com to sign in. Tap Continue. The first time you build and run, you might still have to enter your email and password, but in subsequent build and runs, tapping Continue skips the login form. By now, Xcode has installed all the packages. Build and run in a simulator. Ignore the warnings about Hashable and SwiftyJSON. Scrolling and playback don’t work well in Xcode beta 1, but you won’t be fixing that in this tutorial. If you scroll “too much”, the app crashes. Also not your problem. ;] WidgetKit This tutorial is all about adding a shiny new widget to Emitron. Adding a Widget Extension Start by adding a widget extension with File ▸ New ▸ Target…. Name it EmitronWidget and make sure Include Configuration Intent is not checked: There are two widget configurations: Static and Intent. A widget with IntentConfiguration uses Siri intents to let the user customize widget parameters. Your first widget will be static. Click Finish and agree to the activate-scheme dialog: Running Your Widget The widget template provides a lot of boilerplate code you just have to customize. It works right out of the box, so you can set up everything now to make sure everything runs smoothly when you’re ready to test your code. In the Project navigator, select the top level Emitron folder to sign your targets. Change the bundle identifiers and set the team for every version of every target. One last gotcha: Make sure your widget’s bundle ID prefix matches the app’s. This means you will need to insert dev between “ios” and “EmitronWidget” to get your.prefix.emitron.ios.dev.EmitronWidget. OK, now select the Emitron scheme, then build and run. Sign in, then close the app and press on some empty area of your home window until the icons start to jiggle. Tap the + button in the upper right corner, then scroll down to find raywenderlich: Select it to see snapshots of the three sizes: Tap Add Widget to see your widget on the screen: Tap the widget to reopen Emitron. Your widget works! Now, you simply have to make it display information from Emitron. Defining Your Widget It makes sense to make your widget display some of the information the app shows for each tutorial. This view is defined in UI/Shared/Content List/CardView.swift. My first idea was to just add the widget target to this file. But that required adding more and more and more files, to accommodate all the intricate connections in Emitron. All you really need are the Text views. The images are cute, but you’d need to include the persistence infrastructure to keep them from disappearing. You’re going to copy the layout of the relevant Text views. These use several utility extensions, so find these files and add the EmitronWidgetExtension target to them: CardView displays properties of a ContentListDisplayable object. This is a protocol defined in Displayable/ContentDisplayable.swift: protocol ContentListDisplayable: Ownable { var id: Int { get } var name: String { get } var cardViewSubtitle: String { get } var descriptionPlainText: String { get } var releasedAt: Date { get } var duration: Int { get } var releasedAtDateTimeString: String { get } var parentName: String? { get } var contentType: ContentType { get } var cardArtworkUrl: URL? { get } var ordinal: Int? { get } var technologyTripleString: String { get } var contentSummaryMetadataString: String { get } var contributorString: String { get } // Probably only populated for screencasts var videoIdentifier: Int? { get } } Your widget only needs name, cardViewSubtitle, descriptionPlainText and releasedAtDateTimeString. So you’ll create a struct for these properties. Creating a TimelineEntry Create a new Swift file named WidgetContent.swift and make sure its targets are emitron and EmitronWidgetExtension: It should be in the EmitronWidget group. Now add this code to your new file: import WidgetKit struct WidgetContent: TimelineEntry { var date = Date() let name: String let cardViewSubtitle: String let descriptionPlainText: String let releasedAtDateTimeString: String } To use WidgetContent in a widget, it must conform to TimelineEntry. The only required property is date, which you initialize to the current date. Creating an Entry View Next, create a view to display the four String properties. Create a new SwiftUI View file and name it EntryView.swift. Make sure its target is only EmitronWidgetExtension, and it should also be in the EmitronWidget group: Now replace the contents of struct EntryView with this code: let model: WidgetContent var body: some View { VStack(alignment: .leading) { Text(model.name) .font(.uiTitle4) .lineLimit(2) .fixedSize(horizontal: false, vertical: true) .padding([.trailing], 15) .foregroundColor(.titleText) Text(model.cardViewSubtitle) .font(.uiCaption) .lineLimit(nil) .foregroundColor(.contentText) Text(model.descriptionPlainText) .font(.uiCaption) .fixedSize(horizontal: false, vertical: true) .lineLimit(2) .lineSpacing(3) .foregroundColor(.contentText) Text(model.releasedAtDateTimeString) .font(.uiCaption) .lineLimit(1) .foregroundColor(.contentText) } .background(Color.cardBackground) .padding() .cornerRadius(6) } You’re essentially copying the Text views from CardView and adding padding. EntryView_Previews entirely. Creating Your Widget Now start defining your widget. Open EmitronWidget.swift and double-click SimpleEntry in the line: struct SimpleEntry: TimelineEntry { Choose Editor ▸ Edit All in Scope and change the name to WidgetContent. This will cause several errors, which you’ll fix in the next few steps. First delete the declaration: struct WidgetContent: TimelineEntry { let date: Date } This declaration is now redundant and conflicts with the one in WidgetContent.swift. Creating a Snapshot Entry One of the provider’s methods provides a snapshot entry to display in the widget gallery. You’ll use a specific WidgetContent object for this. Just below the import statements, add this global object: let snapshotEntry = WidgetContent( name: "iOS Concurrency with GCD and Operations", cardViewSubtitle: "iOS & Swift", descriptionPlainText: """ Learn how to add concurrency to your apps! \ Keep your app's UI responsive to give your \ users a great user experience. """, releasedAtDateTimeString: "Jun 23 2020 • Video Course (3 hrs, 21 mins)") This is the update to our concurrency video course, which was published on WWDC day 2. Now replace the line in placeholder(in:) with this: snapshotEntry To display your widget for the first time, WidgetKit renders this entry in the widget’s view, using the modifier redacted(reason: .placeholder). This displays text and images in the correct layout, but masks their contents. This method is synchronous, so don’t do any network downloads or complex calculations here. Also replace the first line of getSnapshot(in:completion:) with this: let entry = snapshotEntry WidgetKit displays this entry whenever the widget is in a transient state, waiting for data or appearing in the widget gallery. Creating a Temporary Timeline A widget needs a TimelineProvider to feed it entries of type TimelineEntry. It displays each entry at the time specified by the entry’s date property. The most important provider method is getTimeline(in:completion:). It already has some code to construct a timeline, but you don’t have enough entries yet. So comment out all but the last two lines, and add this line above those two lines: let entries = [snapshotEntry] You’re creating an entries array that contains just your snapshotEntry. Defining Your Widget Finally, you can put all these parts together. First, delete EmitronWidgetEntryView. You’ll use your EntryView instead. Now replace the internals of struct EmitronWidget with the following: private let kind: String = "EmitronWidget" public var body: some WidgetConfiguration { StaticConfiguration( kind: kind, provider: Provider() ) { entry in EntryView(model: entry) } .configurationDisplayName("RW Tutorials") .description("See the latest video tutorials.") } The three strings are whatever you want: kind describes your widget, and the last two strings appear above each widget size in the gallery. Build and run on your device, sign in, then close the app to see your widget. If it’s still displaying the time, delete it and add it again. And here’s what the medium size widget looks like now: Only the medium size widget looks OK, so modify your widget to provide only that size. Add this modifier below .description: .supportedFamilies([.systemMedium]) Next, you’ll provide real entries for your timeline, directly from the app’s repository! Providing Timeline Entries The app displays the array of ContentListDisplayable objects in contents, created in Data/ContentRepositories/ContentRepository.swift. To share this information with your widget, you’ll create an app group. Then, in ContentRepository.swift, you’ll write a file to this app group, which you’ll read from in EmitronWidget.swift. Creating an App Group On the project page, select the emitron target. In the Signing & Capabilities tab, click + Capability, then drag App Group into the window. Name it group.your.prefix.emitron.contents; be sure to replace your.prefix appropriately. Now select the EmitronWidgetExtension target and add the App Group capability. Scroll through the App Groups to find and select group.your.prefix.emitron.contents. Writing the Contents File At the top of ContentRepository.swift, just below the import Combine statement, add this code: import Foundation extension FileManager { static func sharedContainerURL() -> URL { return FileManager.default.containerURL( forSecurityApplicationGroupIdentifier: "group.your.prefix.emitron.contents" )! } } This is just some standard code for getting the app group container’s URL. Be sure to substitute your app identifier prefix. Now, just below var contents, add this helper method: func writeContents() { let widgetContents = contents.map { WidgetContent(name: $0.name, cardViewSubtitle: $0.cardViewSubtitle, descriptionPlainText: $0.descriptionPlainText, releasedAtDateTimeString: $0.releasedAtDateTimeString) } let archiveURL = FileManager.sharedContainerURL() .appendingPathComponent("contents.json") print(">>> \(archiveURL)") let encoder = JSONEncoder() if let dataToSave = try? encoder.encode(widgetContents) { do { try dataToSave.write(to: archiveURL) } catch { print("Error: Can't write contents") return } } } Here, you create an array of WidgetContent objects, one for each item in the repository. You convert each to JSON and save it to the app group’s container. Set a breakpoint at the let archiveURL line. You’ll call this method when contents is set. Add this didSet closure to contents: didSet { writeContents() } If Xcode is on its toes, it’s complaining about WidgetContent. Jump to the definition of WidgetContent and make it conform to Codable: struct WidgetContent: Codable, TimelineEntry { Now build and run the app in a simulator. At the breakpoint, widgetContents has 20 values. Continue program execution and scroll down in the app. At the breakpoint, widgetContents now has 40 values. So you have some control over how many items you share with your widget. Stop the app, disable the breakpoint, then copy the URL folder path from the debug console and locate in in Finder. Take a look at contents.json. Next, go and set up the widget to read this file. Reading the Contents File In EmitronWidget.swift, add the same FileManager code: extension FileManager { static func sharedContainerURL() -> URL { return FileManager.default.containerURL( forSecurityApplicationGroupIdentifier: "group.your.prefix.emitron.contents" )! } } Be sure to update your prefix. Add this helper method to Provider: func readContents() -> [WidgetContent] { var contents: [WidgetContent] = [] let archiveURL = FileManager.sharedContainerURL() .appendingPathComponent("contents.json") print(">>> \(archiveURL)") let decoder = JSONDecoder() if let codeData = try? Data(contentsOf: archiveURL) { do { contents = try decoder.decode([WidgetContent].self, from: codeData) } catch { print("Error: Can't decode contents") } } return contents } This reads the file you saved into the app group’s container. Uncomment the code in getTimeline(in:completion:), then replace this line: var entries: [WidgetContent] = [] With var entries = readContents() Next, modify the comment and for loop to add dates to your entries: // Generate a timeline by setting entry dates interval seconds apart, // starting from the current date. let currentDate = Date() let interval = 5 for index in 0 ..< entries.count { entries[index].date = Calendar.current.date(byAdding: .second, value: index * interval, to: currentDate)! } Delete the let entries line below the for loop. The line after that sets the timeline running and specifies the refresh policy. In this case, the timeline will refresh after using up all the current entries. Build and run on your device, sign in and let the list load. Then close the app, add your widget and watch it update every 5 seconds. I could watch this all day :]. If you didn't scroll the list, the widget will run out of entries after 20 items. If you wait that long, you'll see it pause while it refreshes. Enabling User Customization I picked 5 seconds for the timeline interval, so I wouldn't have to wait long to see the updates. If you want a shorter or longer interval, just change the value in the code. Or ... create an intent that will let you set the interval by editing the widget, right on your home screen! Adding an Intent First, add your intent: Create a new file (Command-N), search for "intent", select SiriKit Intent Definition File and name it TimelineInterval. Make sure its target is both emitron and EmitronWidgetExtension. In the lower left corner of the intent's sidebar, click + and select New Intent. Name the intent TimelineInterval. Set up the Custom Intent as shown, with Category View: And add a Parameter named interval of type Integer with default, minimum and maximum values as shown, and Type Field. Or set your own values and/or use a stepper. Reconfiguring Your Widget In EmitronWidget.swift, reconfigure your widget to IntentConfiguration. Change the Provider protocol to IntentTimelineProvider. struct Provider: IntentTimelineProvider { Change the definition of getSnapshot(in:completion:) to: public func getSnapshot( for configuration: TimelineIntervalIntent, in context: Context, completion: @escaping (WidgetContent) -> Void ) { Now, change the definition of getTimeline(in:completion:) to: public func getTimeline( for configuration: TimelineIntervalIntent, in context: Context, completion: @escaping (Timeline<WidgetContent>) -> Void ) { In getTimeline(for:in:completion), change interval to use the configuration parameter: let interval = configuration.interval as! Int And finally, in struct EmitronWidget, change StaticConfiguration(kind:provider:) to this: IntentConfiguration( kind: kind, intent: TimelineIntervalIntent.self, provider: Provider() ) { entry in Build and run on your device, sign in and let the list load. Close the app, add your widget, then long-press the widget. It flips over to show an Edit Widget button. Tap this button to change the interval value Where To Go From Here? Download the final project using the Download Materials button at the top or bottom of the tutorial. This tutorial showed you how to leverage code from a large app to create a widget that displays items from the app's own repository. Here are a few ideas for you to add to your Emitron widget: - Design a view for the large size widget that displays two or more entries. Look at Apple's EmojiRangers sample app to see how to modify EntryViewfor widget families. - Add a widgetURLto EntryViewso tapping the widget opens Emitron in that item's detail view. - Add intents to let users set the app's filters from the widget. I hope you enjoyed this tutorial! Building widgets is fun! If you have any comments or questions, feel free to join in the forum discussion below!
https://www.raywenderlich.com/11303363-getting-started-with-widgets
CC-MAIN-2021-04
refinedweb
2,924
57.27
"Illegal instruction (core dumped)" on tensorflow >1.6 I am trying to run import tensorflow on various tensorflow version. The one that I really want to use is 1.13.1. My CPU is INTEL Xeon Scalable GOLD 6126 – 12 Cores (24 Threads) 2.60GHz. I’ve already searched for this error on the internet* and most of the time the work-around is to downgrade tensorflow to older versions (typically I tried 1.5.1 and it worked). Sometimes it’s just unresolved**. But it is possible to really solve the issue? Here are my output for various versions of tensorflow. 1.13.1 2020-09-18 15:00:16.308205: F tensorflow/core/platform/cpu_feature_guard.cc:37] The TensorFlow library was compiled to use SSE4.1 instructions, but these aren't available on your machine. Aborted (core dumped) 1.14.0, 1.15.2 and 2.3.0 Illegal instruction (core dumped) It seems that building from source could be a solution, but how to do it properly knowing that I want to run the code inside a docker? * Illegal instruction(core dumped) tensorflow ** Source: Docker Questions
https://dockerquestions.com/2020/09/18/illegal-instruction-core-dumped-on-tensorflow-1-6/
CC-MAIN-2021-04
refinedweb
189
70.39
C0deH4cker,. C0deH4cker So this was a short project I did. It uses a PNG spritesheet downloaded from the internet to display an animation. Just a basic example of how to do this with Pythonista by using PIL. The interesting part is actually my motivation behind writing this. Someone in a chatroom asked if Python could be used to "explode a hamster." I couldn't resist :D Anyways, here's the Gist: C0deH4cker Not right now. C0deH4cker It appears that the C-based module _elementtree is missing. I know there is a pure Python version of this module available, but I'd prefer to use the C module for speed purposes. Here's the attempted import and resulting error: <pre> from xml.etree.cElementTree import * Traceback (most recent call last): File "<string>", line 1, in <module> File "/var/mobile/Applications/3B311422-DFF2-4138-9B78-0D0D33BFFF14/Pythonista.app/pylib/xml/etree/cElementTree.py", line 3, in <module> from _elementtree import * ImportError: No module named _elementtree </pre> Thank you! Edit: Looks like there's another module or two missing: <pre> from xml.parsers import expat #nope import pyexpat as expat #nope </pre> C0deH4cker Ill post my code for an AnimatedSprite class when I'm done with it. It will do all of the work for you. You just need to specify the filename and # of frames. Then, call the instance's draw method from your scene's draw function. There are also methods to control the animation like FPS, jump to frame, pause/play, etc C0deH4cker What if multiple sides are hit, like this? <pre> ######## # # ######## # # # ######### </pre> C0deH4cker @omz Then add the ability for scripts to play music like that. Then, people could play silence and have it running forever lol. C0deH4cker @omz: I know there is somehow a 10 minute limit in the os, and 10 minutes is fine, but some apps (ie pandora) can run presumably forever in the background. Do you know how it does that? C0deH4cker . C0deH4cker If the only issue now is that the script's state isnt kept, you could just pickle everything before you launch app A and then unpickle it for the callback.
https://forum.omz-software.com/user/c0deh4cker
CC-MAIN-2018-43
refinedweb
357
64.71
Hi all, So I’m trying to set up a functional component and get more familiar with the render function. I have a new webpack-simple project setup using the Vue cli. The only fix I can find for this is using this in the webpack config, which is included in the project by default: resolve: { alias: { 'vue$': 'vue/dist/vue.common.js' } }, But… I’m still getting the ‘Failed to mount component: template or render function not defined.’ error. Here is what my component look like: import Vue from 'vue' Vue.component('header-view', { functional: true, // To compensate for the lack of an instance, // we are now provided a 2nd context argument. render: function(createElement, context) { // ... }, // Props are optional props: { // ... } }) which is just the example found here Any ideas?
https://forum.vuejs.org/t/functional-component-render-function-not-found-using-wepback-simple/4414
CC-MAIN-2021-49
refinedweb
130
66.54
Please log in or register to post a reply. indeed. good to get the algorithms and code snippets filled with such stuff. thats what its ment for! hmm… let’s hope people use the search function in this forum, unlike other places we don’t want to mention :…show=4&id=64182 @john bool IsPowerOfTwo (int value) { return (value & -value) == value; } ‘value’ is -1 so the end result doesn’t equal ‘value’, therefore it is not a power of two (this works for every negative value btw) Only the zero is a special case. So it would be: bool IsPowerOfTwo(int value) { return value ? ((value & -value) == value) : false; }.. Alex. Again, portability has never been part of the set of problems C has been designed to solve. It’s just a thin abstraction layer from the metal, some souped assembler. By design and for varied reasons like efficiency and compiler complexity. If portability is your prime concern you shouldn’t be using C (or any of its descendant) in the first place. So, i’m not missing any point, you’re just barking at the wrong tree. Bjarne Stroustrup lists C++ as a general-purpose language with a bias to “generic programming” (among others including OS stuff): Where “Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations.” So I agree that total portability is NOT an explicit! goal of the standard. Reuseability on the other hand means that portability is desired where it doesn’t hurt the standard (or the target specific constrains). Also note that at least I’m talking about C++, not C. Which language(s) to use depends on the problem at hand. I doubt that a desire for portability prohibits using C++. ALex Portability isn’t and never was an explicit goal of the C++ Standard for a good reason, let me cite the prophet himself: @Bjarne Stroustrup C++’s C compatibility was a key language design decision rather than a marketing gimmick. Compatibility has been difficult to achieve and maintain, but real benefits to real programmers resulted, and still result today. You can talk genericity and OOness all day long, C++ is by design compatible with C. Thusly, regarding portability they both stand side by side. The C++0x improvements should be done in such a way that the resulting language is easier to learn and use. Among the rules of thumb for the committee are: Provide stability and compatibility (with C++98, and, if possible, with C) Being compatible with C is nice but rather optional (“if possible”). This is getting no where so this will be my last post on this… ALex Your quote is about C++0x, an extension to C++ (just like C99 was an extension of C). If that compatibility is news to you, i’m sorry, but you should have asked yourself why you could happily (void *) everything, among other things. I don’t see why it would hurt to add an endianness flag to the standard. I for one would find it very useful, but I can definitely get by without it. However, I strongly disagree with a C/C++ compiler “fixing” my code. I want full control over platform specific details like that. Otherwise, their are portable libraries that can abstract those details at a higher-level. For example, the data streams in Qt handle endianness so you can rebuild your Intel Windows GUI on a big-endian Mac with no code changes. @monjardin I don’t see why it would hurt to add an endianness flag to the standard. But then what kind of flag is it, because, you know, there’s cpu out there that can switch endianness per page. It’s not as trivial as it may sound. If i remember Ada has an endianness constant. But don’t quote me on that (and anyway, it’s Ada…). ah..a post with content :), thx monjardin. Why would you want control over these platform specific details? I doubt the compiler will do much worse on elementary oprations like that. Of course you want control over more complex opreations because they might influence performance much more. If the “fixing” of endian etc is a compiler option you could disable it and do it yourself. The compiler applys platform specific optimization anyways so your control over the output is limited. It should be fairly easy (and without any performance loss compared to a handmade fix) to compile for different endians etc (as there are ways to do the exact same logical operation on both big/little endian machines). I don’t quite get where you’re going, Alex. Would you give an example of code that a compiler could know how to correct for endianness? After thinking about it, I guess there is no real need for an endianness flag. It is fairly trivial to figure it out at runtime. ok..example: Let’s say you have an int (e.g. size 32 bits) and you’d like to access its componenets. For our example we do so by casting the int to a char*: int my_int; char* cp=(char*)&my_int; cp[0]=0x1; cp[1]=0x2; cp[2]=0x3; cp[3]=0x4; The final value of my_int (hence the logic of the program) depends on the endianess of the system you run it on.]”. So in case the flag is present the compiler swizzels the index internally to produce the same logical result the program would produce on a little endian system. The process should be totally transparent. So you decide for your endian once, put the flag and then forget about the whole issue. side note: with flag I don’t mean a define or macro but a compiler directive..I don’t want to query the flag and put tons of #ifdef BIG_ENDIAN. That’s exactely what I’d like to avoid. Alex Could you not just extend off a class like bitset, and mask that depending on the endianness you pass in from a #define? You can fix the whole endian issue yourself with #ifdefs or other tricks. It’s just a pain, ugly to maintain and you forget to fix a certain case more often than not. It seems to me that such a compiler flag could cause more confusion than it solves. What code that isn’t meant for a specific platform is written like that? A valid C++ solution is to use data streams with platform specific implementations. Your example could be implemented like this: int my_int; char buffer[] = { 0x1, 0x2, 0x3, 0x4 }; data_stream stream(buffer, 4, data_stream::BIG_ENDIAN); stream >> my_int; So, you handle your #if tricks in your data stream library and then your code is pretty and easy to maintain. When it comes down to it, you need to pick a endianness to use for data exchange (see the htonl family). @Alex]”. I’m sorry but that’s not how the language works. The problem is in how an int is stored in memory, not how you access a char array. What if cp points to a C-style string, and you set that flag (so by cp[0] you actually mean cp[3], etc.), would “Hello” suddenly be read as “lleHo”? And how would you fix that when you read a whole chunk of data into a char array, and map that on a structure and want to read an int at offset 23? No, you need a simple implementation defined macro like CHAR_BIT that lets you define other macros or inline functions that either change the endianness of a type or leave it as-is, depending on the platform. There are only two places where you would want to convert endianness, and that is either at the input or just before the output. How your application internally works is usually not a problem, it’s just that you would like to read or write data (from/to disk or network or something similar) in a cross-platform way. You know what kind of endianness your input and your output should be, the problem is usually the processor architecture itself. monjardin: You can hide the #ifdefs or how ever you abstract the problem in a lib or wherever you want still it’s ugly having to handle it at all. When ever you come across a problem that deals with endianess (which happens not only when serializing) you have to fix it manually somehow. The code was just a stupid sample to clarify what I mean..not production code :) Currently code with similar intend like the sample isn’t portable which is what I’d like to fix. .oisyn: For an array of chars the index would not be swizzled of course (that’s what I meant by the proces being transparent). As said, the program should perform logically EXACTLY like it was run on the little endian system. That means all operations execute normally apart from those that make assumptions about the endianness. Those that make assumptions are “corrected”. The compiler could store internally if you’re accessing a sub section of a larger data type. Only if that’s the case a correction is needed. So in an array of (32 bit) ints casted to char* accessing index 5 means we access the 2nd int and ONLY within that int the offset depends on the flag because the compiler knows that on its target platform the memory mapping of the int depends on the endianess. I’d say the problem is that you cannot specify wether you’d like to to access the most or least significant part(byte or whate ever) of a value. That’s what makes things ambiguous. And how would this work? void foo() { int number = 0x12345678; char buf[] = "1234"; char * ptr1 = reinterpret_cast<char*>(&number); char * ptr2 = buf; for (int i = 0; i < 4; i++) { output(*ptr1++); if (random() > 0.5) std::swap(ptr1, ptr2); } } Now I have absolutely no idea what the above should do, but the fact is that it is valid C++ code and the compiler can do nothing since it doesn’t know the result of random() as it’s a runtime function. As I said, if you can simply convert between known endiannesses and the host’s endianness with functions like little_to_host(T), big_to_host(T), host_to_little(T) and host_to_big(T), you don’t have the trouble of #defines all over the place. You know how the input or output should be represented, you simply don’t know what architecture your program will be compiled for. Of course, you only know what format the input/output is using if it really matters; a simple settings file could be written in the architecture’s native format. Unless it is meant to be exchangeable across platforms, at which point you have to define the endianness for yourself. // data structure, source is assumed to be little endian struct MyData { char name[4]; short aShort; int andAnInt; int anotherInt; }; void read(MyData * pData, FILE * f) { fread(pData, sizeof(*pData), 1, f); pData->aShort = little_to_host(pData->aShort); pData->andAnInt = little_to_host(pData->andAnInt); pData->anotherInt = little_to_host(pData->anotherInt); } Your solution won’t work here, fread is just a basic precompiled C function, it has no idea of the pointer passed to it, it just copies the memory. You’re right..there is limits how far the compiler can trace back what you have done so a flag won’t be sufficient..and doing it runtime is not desireable… In that case I demand that all systems of one type (don’t care which) are destroyed ;) Alex @Alex In that case I demand that all systems of one type (don’t care which) are destroyed ;) Finally, we can agree! :) Good luck convincing the chip makers! Why did Intel go little-endian? I don’t remember. Hm..I found little endian quite handy when writing my virtual machine. When accessing a sub portion of a virtual register (like ax/al from eax) in memory you don’t need to add any offsets to the register’s address. But I kinda doubt that was the reason intel went little endian :) @monjardin Why did Intel go little-endian? I don’t remember. Was it intel that was the black sheep that introduced little-endian, while all others went for big endian? Just curious… I always found the little-endian format more practical. Because if you cast a large integer type pointer to a smaller type, it’s just the same number, but modulo 2\^n, depending on the size of the smaller type (or, you can increase the precision without moving memory). Also, if you start with a bytebuffer of all zeroes, and keep incrementing the first byte until it overflows and you increase the second byte (and so on), you can simply read the value as a word or dword without swapping the bytes. Similarly, if you would to be storing the bits of a large number as an array, you’ll put bit 0 on position 0 in the array, as it is called bit 0. So why not break up the large integer into chunks as well? Of course, with big endian you can more easily read the larger values from memory in the debugger or a hex-editor, as we humans use the same notation in our numbers (which is probably where the whole big endian thing came from)
http://devmaster.net/posts/6026/checking-whether-a-number-is-a-power-of-2
CC-MAIN-2014-10
refinedweb
2,246
69.01
Here I am going to write a simple program to read a text file line by line. We will use the ReadLine method of the StreamReader class. C# Program to read text file line by line: This program reads the content of the text file into a string variable using the ReadLine method of StreamReader class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReadFile { class Program { static void Main(string[] args) { int iCounter = 0; string line; // Read the file and display it line by line. System.IO.StreamReader objFile = new System.IO.StreamReader(@"E:\SampleFile.txt"); while ((line = objFile.ReadLine()) != null) { System.Console.WriteLine(line); iCounter++; } objFile.Close(); System.Console.WriteLine("Total Line Read {0}", iCounter); System.Console.ReadLine(); } } } View More: - C# Program to Print Pyramid Pattern in C#. - C# Program to Print Fibonacci Series. - C# Program to check whether a number is prime or not using Recursion. - C# Program to Swap two numbers without using third variable. Conclusion: I hope this is a useful topic for you. Your feedback and suggestions would always welcome to me. Thank You.
https://debugonweb.com/2018/11/18/read-text-file/
CC-MAIN-2019-09
refinedweb
189
62.14
Ruby and Emacs Tip: Advanced Pry Integration Thiago Araújo Silva Aug 27 '18 Updated on Aug 28, 2018 ・1 min read Pry is one of those tools that you'll despise until you actually learn what it can do for you. It's a window to the Ruby language, a land where things have extreme late-binding and can change at any time. With Pry, you can easily spelunk anything: edit, view, and navigate through source code; debug, play lines of code, and run shell commands. Doing the same with "puts debugging" or metaprogramming requires repetitive typing, tedious plumbing, third-party gems (method_source, anyone?) and won't give you syntax highlighting. You can run Ruby REPLs in Emacs (including Pry) with inf-ruby, a package co-authored by the great Yukihiro Matsumoto, our dear Matz. But there's so much more power to unlock! We will rely on Pry's editor integration, so the good news is that you can apply the same principles to your favorite text editor, as long as it supports a client-server architecture. Neovim is one such example. Emacs, however, has a special trick up its sleeve: it's called elisp. Goals This post will guide you through integrating Pry into Emacs and ironing out a few annoyances that might arise during the process. Also, it will give you an idea of how to create Pry commands that reach back into Emacs via elisp. Note that it won't teach you how to setup or use Emacs. Among others you will: - Run Pry from within Emacs, - Seamlessly integrate Pry into Emacs, - Edit and reload files without leaving Pry (nor Emacs!), - Page through Pry's output, - View a Ruby file in Emacs through Pry, - Open a gem in Dired through Pry. Emacs server With emacsclient, you can interact with a running Emacs session from the outside. For example: $ emacsclient my_file.rb The above command opens my_file.rb in your current Emacs session. Note that before attempting to use emacsclient, you'll need to start a server process with M-x server-start (press M-x in Emacs, type server-start, and press return). I want things to be as automated as possible, so I created an elisp function to start the server for me when I open Emacs: (defun run-server () "Runs the Emacs server if it is not running" (require 'server) (unless (server-running-p) (server-start))) (run-server) The above code can be saved in your ~/.emacs.d/init.el config file. Default editor configuration The next step is to set emacsclient as your default editor. Save the following lines in your shell config file ( .bash_profile for bash or .zshenv for zsh): export EDITOR=emacsclient export VISUAL=$EDITOR If you use a Mac computer and a GUI Emacs, Emacs won't inherit your shell environment variables. To overcome this issue, I recommend installing the exec-path-from-shell package. Be sure to add MELPA to your package archives: (setq package-archives '(("melpa" . "") ("gnu" . ""))) (package-initialize) Then run: M-x package-refresh-contentsto refresh the packages, M-x package-install, exec-path-from-shell, and press returnto install the package. Finally, save this snippet in your init.el file: (defun copy-shell-environment-variables () (when (memq window-system '(mac ns)) (exec-path-from-shell-initialize))) (copy-shell-environment-variables) But there's a gotcha: I prefer nvim when I'm working on the terminal (which is rare these days because I run most of my shell commands within Emacs). For this reason, I set both editor variables via elisp and leave my shell variables unchanged: (setenv "VISUAL" "emacsclient") (setenv "EDITOR" (getenv "VISUAL")) Trying it out Run M-x shell (Emacs' shell), find an existing file, and run the following command: $ $EDITOR existing-file Wow, you are still in Emacs, and the file opened right before your eyes. Meanwhile, the Pry buffer is blocked with the message "Waiting for Emacs...". It's waiting for you to edit the file, save it, and press C-x # ( server-edit) to terminate the connection, which closes the file and unblocks the shell. Configuring Pry You need a few settings to make Pry play nice with Emacs. Save these lines in your ~/.pryrc file: if ENV['INSIDE_EMACS'] Pry.config.correct_indent = false Pry.config.pager = false end Pry.config.editor = ENV['VISUAL'] Pry.config.correct_indent = falsefixes an annoying issue with the command prompt. Pry.config.pager = falsetells Pry not to use lessas a pager. Why? Because Pry runs under comint.el, a library that allows an ordinary Emacs buffer to communicate with an inferior shell process - in our case, a Pry REPL. It doesn't support interactive programs such as less, but on the other hand, the buffer itself is a pager. - Finally, we tell Pry to use whatever is set to the VISUALenvironment variable as its editor. Running Pry from within Emacs Nothing special to do. Just ensure you've installed the inf-ruby package and that your project is configured to use Pry. inf-ruby provides many commands to spin up a Ruby REPL, like inf-ruby-console-rails for example. For Rails projects, you can install the pry-rails gem and call it a day. The projectile-rails package, which I thoroughly recommend, has a convenient shortcut for this: C-c p r ( projectile-rails-console). Editing and reloading code This is where things start to get fun. Let's suppose you're not getting an expected return value out of a certain gem. The name of the troublesome method is MyGem.do_thing, which is called by MyApp.do_thing. Let's edit MyGem.do_thing: [0] pry(main)> edit MyGem.do_thing Waiting for Emacs... And insert a debug statement: class MyGem def self.do_thing(a, b) binding.pry # ... end end Now save the file with C-x C-s and press C-x # to terminate the emacsclient connection. Boom! Pry will load your new changes and you'll be taken back to the Pry prompt! Finally, run MyApp.do_thing: [1] pry(main)> MyApp.do_thing(c) From: /Users/thiago/.asdf/installs/ruby/2.4.2/lib/ruby/gems/2.4.0/gems/my_gem-5.1.3/lib/my_gem.rb @ line 48 MyGem#do_thing: 47: def do_thing(a, b) => 48: require 'pry'; binding.pry Awesome, you've hit the breakpoint, so you might want to inspect the state of your application to figure out what's wrong. Now you can debug the world without leaving Emacs! Pry's edit command is extremely handy because you don't need to know where the gem or the method are stored on disk. Paging through source code In Pry, you can read the source code of anything with the show-source command (or $). Let's take a look at ActiveRecord::Base#establish_connection: [6] pry(main)> show-source ActiveRecord::Base.establish_connection From: /Users/thiago/.asdf/installs/ruby/2.4.2/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/connection_handling.rb @ line 47: Owner: ActiveRecord::ConnectionHandling Visibility: public Number of lines: This snippet fits into a single screen, but what to do when it doesn't? You can press return ( comint-send-input) to run show-source and either: - Scroll back up with M-vuntil reaching the start of the output, then C-vto scroll down, or; - Run C-c C-r( comint-show-output) to make the cursor jump to the start of the output, then C-vto scroll down. The second option is a clear winner. However, I've gotten tired of always running comint-show-output, so I came up with my own automation. I've created the following function and mapped it to <C-return>: ;; Save this code in init.el (defun comint-send-input-stay-on-line () (interactive) (call-interactively 'comint-send-input) (run-with-timer 0.05 nil (lambda () (call-interactively 'comint-show-output)))) (define-key comint-mode-map (kbd "<C-return>") 'comint-send-input-stay-on-line) It runs comint-show-output right after comint-send-input. There's an interval of 0.05 seconds between the commands to avoid a race condition, time enough for the output to be available before you can actually return to it. The cool thing is that this shortcut works with any comint prompt, even M-x shell. I'm not sure if there's an easier solution to this problem, so if you know of any please leave it up in the comments :) Viewing a file through Pry show-source is cool but it's not enough. Often times I want to open the corresponding Ruby file in another buffer, where I have enh-ruby-mode and a bunch of other tools at my disposal. The default edit command is a no-go because it blocks the Pry prompt and waits for an edit to be made. Also, the buffer usually gets closed in the end. Luckily, we can use edit -n to bypass the blocking behavior. For example: [7] pry(main)> edit -n Foo.bar The above command will open the file for the Foo module with the cursor pointed at the bar class method. Open a gem in Dired through Pry Opening a gem is something I need to do surprisingly often. Sometimes I want to look into the files or just search within the gem's source code. And I'll be happy if I can avoid a trip to GitHub, which also requires going through the trouble of pointing the gem at the specific version that my app is using. To showcase what a custom command looks like, I also don't want to use the bundle open command. Here's a supposed Pry command to open a gem in Dired: # `ggem` is a mnemonic to "go to gem" [8] pry(main)> ggem graphql-batch Note that Pry commands have a special syntax. They are not calls to Ruby methods. Let's apply divide and conquer to make it work. First, we need a way to open a directory in Emacs. Go to a terminal and type in the following command: $ emacsclient -e '(dired-jump nil "~")' Flip back to Emacs, and you will see a Dired window with the cursor positioned at your home directory. Awesome! The -e flag to emacsclient allows us to run an arbitrary string of elisp code, so we've run the dired-jump function and passed our home directory ( ~) as the second argument. Now let's create a Ruby method to wrap this call. Save it in ~/.pryrc: # The function accepts an arbitrary path def emacs_open_in_dired(path) system %{emacsclient -e '(dired-jump nil "#{path}")'} end Next, we need to find the gem's directory. In the above example, the gem is graphql-batch. Here's a method that will return the directory as a Pathname object: def gem_dir(gem_name) gem_dir = Gem::Specification.find_by_name(gem_name).gem_dir Pathname(gem_dir) end Now that we've gathered all the pieces, let's create the Pry command: # This is a shorthand to create and add a command at the same time Pry::Commands.create_command 'ggem' do description 'Open a gem dir in Emacs dired' banner <<-'BANNER' Usage: ggem GEM_NAME Example: ggem propono BANNER def process gem_name = args.join('') # Opens the gem's lib folder in Dired emacs_open_in_dired gem_dir(gem_name) / 'lib' rescue Gem::MissingSpecError # do nothing end end Great, the command should now be working! You can use it with any gem, as long as it's declared in your Gemfile! Conclusion I hope this post was useful to you. There's so much you can do with these tools that I haven't even scratched the surface! Emacs is a great editor, and the combination of Ruby and elisp gives you almost endless possibilities. With inf-ruby you can also do cool things such as sending Ruby code from a buffer to the REPL process, so I encourage you to explore it in detail! If Pry isn't already the heart of your Ruby workflow, I recommend you make the leap. If you work with Ruby, it's a life-changing tool. In the next post, I will show you how to run RSpec tests productively. (open source and free forever ❤️) What are your programming blogs? Hi. I need programming blogs to read. So, what are your programming blogs? You ...
https://dev.to/thiagoa/ruby-and-emacs-tip-advanced-pry-integration-33bk
CC-MAIN-2019-04
refinedweb
2,047
64.51
Last week we asked everyone to tell us how many tech books you have. The bulk of people seem to have between 1-9 tech books in their collection. We collected a total of 210 votes, which were distributed as follows: 24% have 1-9 tech books; 22% have between 20-49 tech books; the option for 50-99 was left out accidentally, but if it had been there it probably would have rested between the 20-49 and 100-249 responses or much higher (judging by the bell curve); 17% have between 100-249 tech books; 15% have an amazing 250+ tech books; 13% have between 10-19 tech books; while 9% have no tech books at all. Full results and this week’s poll after the jump. This week’s poll question is: Do You Think Digital Pirates Purchase More Products Than Non-Pirates? A recent study has deemed that people pirating movies are actually the same people who purchase the most movies. A similar study concluded that people who pirate digital music actually purchased more digital music than non-pirates (although fewer physical CDs). I’ve heard many people actually consider pirating products as a try-before-you-buy deal. The entertainment industry obviously sees it differently. How do you see things from where you stand? How do the pirates you know of behave? Do they purchase things or not? More importantly, do they purchase more than the non-pirates you know of? A simple yes/no/maybe poll isn’t going to cut it if you’re keen to elaborate. Feel free to let us know more about your pirating friends’ purchasing habits in the comments! I think pirates end up buying more because they obviously have more money left over from *not* buying so much stuff they’re either unable to return (like software) or would only get a fraction of the full price back once sold secondhand (like games, music, movies, etc.). But the question of “buying more,” I think, deals with quantity (and often quality) of purchases rather than total dollars spent. This is going to run well into TL;DR territory so I’ve decided to split my response into multiple parts. (Like a…dare I say it, *sequel* of sorts.)
http://www.makeuseof.com/tag/digital-pirates-purchase-products-nonpirates-makeuseof-poll/
CC-MAIN-2015-35
refinedweb
379
69.52
Farm Planning Farm Planning Example This model is an example of a production problem. In production planning problems, choices must be made regarding the what resources to use to produce what products. These problems are common across a broad range of industries. In this example we’ll model and solve a multi-period production planning problem: In this case the application is to optimize the operation of a farm over 5 years. The farmer has a certain number of farmable acres and cows. The cows can be sold or used to produce milk, which can also be sold for profit. The food for the cows is grown on the farmable acres. The aim is to create an optimal operation plan for the next 5 years to maximize the total profit. This includes figuring out what is the optimal cultivation of the acres, the optimal operations related to the cows, and the operations for the whole farm. Note: you can download the model, implemented in Python, here. More information on this type of model can be found in the fifth edition of Model Building in Mathematical Programming, by H. Paul Williams. H. Paul Williams, Model Building in Mathematical Programming, fifth edition (Page 262-263, 358-359) Problem Description A farmer with a 200 acre farm wishes to create a five-year production plan. Currently, he has a herd of 120 cows comprising 20 heifers (young female cows) and 100 adult dairy cows. Each heifer requires 2/3rds of an acre and each dairy cow requires one acre to support it. A dairy cow produces 1.1 calves per year on average. Half of these calves will be bullocks that are sold shortly after birth for an average of $30 each. The remaining calves, heifers, can either be sold for $40 or raised until age two when they will be come dairy cows. For the current year, all heifers identified for sale have already been sold. The general practice is to sell all dairy cows at the age of 12 for an average of $120 each. However, each year an average of 5% of heifers and 2% of dairy cows die. At present, the farmer’s herd of 120 cows is evenly distributed with 10 cows per age from newborn to 11 years old. The milk from a dairy cow can be sold for $370 annually. The farmer can currently house up to 130 cows, but this capacity limit can be increased for $200 per additional cow. Each dairy cow requires 0.6 tons of grain and 0.7 tons of sugar beet per year. Both of these can be grown on the farm. Each acre can yield 1.5 tons of sugar beet. However, only 80 acres are suitable for growing grain, and those acres have different levels of productivity as follows: Sugar beet can be bought for $70 a ton and sold for $58 a ton. Grain can be bought for $90 a ton and sold for $75 a ton. The annual labor requirements for cows as well as grain and sugar beet production are as follows: Other annual costs are as follows: Labor currently costs the farmer $4000 per year and that cost provides 5500 hours of labor. Additional labor can be paid for at the rate of $1.20 per hour. Any capital expenditure can be financed with a 10-year loan at 15% interest annually. The interest and principle are paid back in 10 equal annual payments. In no year can the cash flow be negative. The farmer does not want to reduce the total number of dairy cows at the end of the five-year period by more than 50%, nor does he want to increase their number by more than 75%. What plan should the farmer follow over the next five years in order to maximize profit? Model Formulation Let \( T \) be a set of time periods, where \( t_0 \in T \) is the first period and \( t_e \in T \) the last period. Let \( L\) be a set of land groups and \(K\) be a set of cow ages, where \(k_0\) is the first cow age and \(k_e\) is the last cow age. For each time period \(t \in T \) we have the continous variables: \[ \begin{array}{rl} SB_t & \text{how much sugar beet is grown (in tons)} \\ GRBUY_t & \text{how much grain is bought (in tons)} \\ GRSELL_t & \text{how much grain is sold (in tons)} \\ SBBUY_t & \text{how much sugar beet is bought (in tons)} \\ SBSELL_t & \text{how much sugar beet is sold (in tons)} \\ EXLAB_t & \text{how much extra labour is recruited} \\ EXCAP_t & \text{how much capital outlay there is} \\ HFSELL_t & \text{how many heifers are sold at birth} \\ PROF_t & \text{how much profit there is} \\ NEWCOW_t & \text{how many cows of age 0 we have} \\ \end{array} \] For each time period \(t \in T \) and each land group \(l \in L\) we have the followingcontinuous variables: \[ \begin{array}{rl} GR_{tl} & \text{how much grain is grown on that landgroup} \\ \end{array} \] Also, we have given for each land group \(l \in L\) the parameters: \[ \begin{array}{rl} GrainYld_{l} & \text{the grain production factor } \\ GrainArea_{l} & \text{the number of acres available} \\ \end{array} \] For each time period \(t \in T \) and each cow age \(k\in K\) we have the continous variables: \[ \begin{array}{rl} COWS_{tk} & \text{how many cows there are of that age} \\ \end{array} \] We define all the continous variables described above: \begin{multline} SB_t, GRBUY_t, GRSELL_t, SBBUY_t, SBSELL_t, EXLAB_t, EXCAP_t, HFSELL_t, PROF_t, NEWCOW_t \geq 0 \quad \forall t \in T \end{multline} \begin{equation} GR_{tl} \geq 0 \quad \forall t \in T, \forall l \in L \end{equation} \begin{equation} GR_{tk} \geq 0 \quad \forall t \in T, \forall k \in K \end{equation} Next we insert the constraints: There is only a housing capacity for 130 cows per year. It is possible that there are more than 130 cows, but this comes with additional costs related to renting houses, which is covered with the EXCAP variables: \begin{equation} NEWCOW_t + \sum_{k \in K \setminus k_e} COWS_{tk} – \sum_{d \in T : d \leq t} EXCAP_d \geq 130 \quad \forall t \in T \end{equation} There needs to be enough grain produced to feed all cows in the current year. Grain cannot be bought in the model unlike sugar beet. \begin{equation} \sum_{k \in K \setminus \{k_0,k_e\}} 0.6COWS_{tk} \leq \sum_{l \in L} GR_{tl} + GRBUY_t – GRSELL_t \quad \forall t \in T \end{equation} After selling, buying and producing sugar beet, there needs to be enough sugar beet in storage to feed all the cows: \begin{equation} \sum_{k \in K \setminus \{k_0,k_e\}} 0.7COWS_{tk} \leq SB_t + SBBUY_t – SBSELL_t \quad \forall t \in T \end{equation} The grain produced on each land group cannot exceed the specified production capacity of each land group: \begin{equation} GR_{tl} \leq GrainYld_{l} \cdot GrainArea_{l} \quad \forall t \in T, \forall l \in L \end{equation} Each cow needs to certrain number of acres to support it. The amount depends on the age of the cow. There are at most 200 acres available: \begin{equation} \frac{2}{3}SB_t + \frac{2}{3}NEWCOW_t + \frac{2}{3}COWS_{tk_0} + \sum_{k \in K \setminus \{k_0,k_e\}} COWS_{tk}+ \sum_{l \in L} \frac{1}{GrainYld_{l}}GR_{tl} \leq 200 \quad \forall t \in T \end{equation} Each cow and each acre requires a certain amount of worker time to maintain it. The farm is currently able to provide a fixed number of worker hours in the year. Any additional work that needs to be done, can be bought externally at additional cost: \begin{multline} 0.1NEWCOW_t + 0.1COWS_{tk_0} + \sum_{k \in K \setminus \{k_0,k_e\}} 0.42COWS_{tk} + \\ \sum_{l \in L} \frac{0.04}{GrainYld_l}GR_{tl} + \frac{0.14}{1.5} SB_t \leq 55 + EXLAB_t \quad \forall t \in T \end{multline} Each year a certain percentage of the cows die, depending on each age: \begin{equation} COWS_{t+1,k_0} = 0.95 NEWCOW_t \quad \forall t \in T \setminus \{t_e\} \end{equation} \begin{equation} COWS_{t+1,k_0+1} = 0.95 COWS_{t,k_0} \quad \forall t \in T \setminus \{t_e\} \end{equation} \begin{equation} COWS_{t+1,k+1} = 0.98 COWS_{t,k} \quad \forall t \in T \setminus \{t_e\}, k \in K \setminus \{k_0,k_e\} \end{equation} To keep the amount of cows correct, we must capture that cows can come into/out of the model through buying them, selling them or through birth: \begin{equation} NEWCOW_{t} – \sum_{k \in K \setminus \{k_0,k_e\}} 0.55COWS_{tk} + HFSELL_t = 0 \quad \forall t \in T \end{equation} At the end of the five year period, the farmer wants to have at least 50 and at most 175 diary cows: \begin{equation} 50 \leq \sum_{k \in K \setminus \{k_0,k_e\}} 0.55COWS_{t_ek} \leq 175 \end{equation} These constraints make sure that the variable PROF takes the value of the profit in this year. There are currently costs of $4000 for the labor. The profit is influenced by the selling of heifers, selling of 12-year-old-cows, selling of milk, selling of grain, selling of sugar beet, buying of grain, buying of sugar beet, labour, heifer costs, dairy cow costs, grain costs, sugar beet costs, as well as capital costs: \begin{multline} \sum_{k \in K \setminus \{k_0,k_e\}} 16.5COWS_{tk} + 40HFSELL_t + 120COWS_{tk_e} \\ + \sum_{k \in K \setminus \{k_0,k_e\}} 370COWS_{tk} + 75 GRSELL_t \\ + 58SBSELL_t – 90 GRBUY_t – 70 SBBUY_t – 120EXLAB_t \\ – 50 NEWCOW_t – 50COWS_{tk_0} – \sum_{k \in K \setminus \{k_0,k_e\}} 100COWS_{tk} \\ – \sum_{l \in L} \frac{15}{GrainYld_l}GR_{tl} – \frac{20}{3} SB_t – \sum_{d \in T : d \leq t} 39.71EXCAP_d – PROF_t = 4000 \quad \forall t \in T \end{multline} In the first year there are 9.5 cows, respectively, given for age 1 and 2. And there is given 9.8 respectively for the ages 3 till 12. Note that we are solving a LP model for computational easier calculating, this can lead to fractional values for variables, which are in reality integers. The implementation of the action needs to take this into account and round them: \begin{equation} COWS_{t_0k_0} = 9.5 \end{equation} \begin{equation} COWS_{t_0k_0+1} = 9.5 \end{equation} \begin{equation} COWS_{t_0k} = 9.8 \quad \forall k \in K \setminus \{k_0, k_0+1\} \end{equation} The total profit consists of the calculated profit minus the costs for additional work and housing, which needs to be bought. This is modeled as: \begin{equation} \max \sum_{t \in T} PROF_t – 158.85EXCAP_t – 39.71\cdot t \cdot EXCAP_t \end{equation} Implementation with comments First, we import the Gurobi Python Module and initalize the data structures: from gurobipy import * #tested with Python 3.5.2 & Gurobi 7.0.1 GrainYld = [1.1, 0.9, 0.8, 0.65] GrainArea = [20.0, 30.0, 20.0, 10.0] years = range(1,5+1) land_groups = range(1,4+1) cow_ages = range(1,12+1) s_cow_ages = range(2,11+1) max_accommodation = 130 grain_per_cow = 0.6 sugar_beet_per_cow = 0.7 acre_per_heifer = 2/3.0 max_acre = 200 labour_per_heifer = 10/100.0 labour_per_cow = 42/100.0 labour_per_acre_to_grain = 4/100.0 labour_per_acre_to_sb = 14/100.0 total_available_work = 5500/100.0 survivial_rate_cow = 0.98 survivial_rate_heifer = 0.95 initial_heifers = 9.5 initial_cows = 9.8 new_heifers_per_cow = 1.1/2 min_end_total = 50 max_end_total = 175 num_bulldogs_per_cow = 1.1/2 price_selling_bulldogs = 30 price_selling_heifers = 40 price_selling_12year_old_cows = 120 price_selling_milk = 370 price_selling_grain = 75 price_selling_sugar_beet = 58 price_buying_grain = 90 price_buying_sugar_beet = 70 price_extra_labour = 120 heifer_costs = 50 cow_costs = 100 acre_grain_labour_cost = 15 acre_sb_labour_cost = 10 annual_loan_repayment = 39.71 available_labour_cost = 4000 capital_expenditures = 158.85 Next, we create a model and the variables. For each year we have continous variables, which tell us how much sugar beet is grown (in tons), how much grain is bought (in tons), how much grain is sold (in tons), how much sugar beet is bought (in tons), how much sugar beet is sold (in tons), how much extra labour is recruited, how much capital outlay there is, how many heifers are sold at birth, how much profit there is, and how many cows are age 0. For each year and each land group there is a continous variable which tells us how much grain is grown on that land group. For each year and each cow_age, there is a continuous which tells us how many cows exists in the current year of that age. model = Model('Farming') SB = model.addVars(years, vtype=GRB.CONTINUOUS, name="SB") GRBUY = model.addVars(years, vtype=GRB.CONTINUOUS, name="GRBUY") GRSELL = model.addVars(years, vtype=GRB.CONTINUOUS, name="GRSELL") SBBUY = model.addVars(years, vtype=GRB.CONTINUOUS, name="SBBUY") SBSELL = model.addVars(years, vtype=GRB.CONTINUOUS, name="SBSELL") EXLAB = model.addVars(years, vtype=GRB.CONTINUOUS, name="EXLAB") EXCAP = model.addVars(years, vtype=GRB.CONTINUOUS, name="EXCAP") HFSELL = model.addVars(years, vtype=GRB.CONTINUOUS, name="HFSELL") NEWCOW = model.addVars(years, vtype=GRB.CONTINUOUS, name="NEWCOW") PROF = model.addVars(years, vtype=GRB.CONTINUOUS, name="PROF") GR = model.addVars(years, land_groups, vtype=GRB.CONTINUOUS, name="GR") COWS = model.addVars(years, cow_ages, vtype=GRB.CONTINUOUS, name="COWS") Next we insert the constraints: There are only a housing capacities for 130 cows per year. It is possible that there are more than 130 cows, but they come with additional costs related to renting houses, which is covered with the EXCAP variables. # Accommodation for the cows model.addConstrs((NEWCOW[year] + COWS[year,1] + quicksum(COWS[year,i] for i in s_cow_ages) - quicksum(EXCAP[i] for i in years if i <= year) <= max_accommodation for year in years), name="Accommodation") Enough grain needs to be produced to feed all cows in the current year. In the model, Grain cannot be bought, unlike sugar beet. # Grain consumption model.addConstrs((quicksum(grain_per_cow*COWS[year, i] for i in s_cow_ages) <= GR.sum(year, '*') + GRBUY[year] - GRSELL[year] for year in years), name="Grain_consumption") After selling, buying and producing sugar beet, there needs to be enough sugar beet in the storage to feed all the cows. # Sugar beet consumption model.addConstrs((quicksum(sugar_beet_per_cow*COWS[year, i] for i in s_cow_ages) <= SB[year] + SBBUY[year] - SBSELL[year] for year in years), name="Sugar_beet_consumption") The grain produced on each land group cannot exceed the specified production capacity of each land group. # Grain growing capacity model.addConstrs((GR[year, land_group] <= GrainYld[land_group-1]*GrainArea[land_group-1] for year in years for land_group in land_groups), name="Grain_growing_capacity") Each cow needs a certain number of acres to support it. The amount depends on the age of the cow. There are at most 200 acres available. # Acreage limitation model.addConstrs((acre_per_heifer*SB[year] + acre_per_heifer*NEWCOW[year] + acre_per_heifer*COWS[year,1] + quicksum((1/GrainYld[land_group-1])*GR[year, land_group] for land_group in land_groups)+ quicksum(COWS[year, i] for i in s_cow_ages) <= max_acre for year in years), name="Acreage_limitation") Each cow and each acre requires a certain amount of worker time to maintain them. The farm is currently able to provide a fixed number of worker hours in a year. Any additional work that needs to be done can be bought externally at additional cost. # Labour model.addConstrs((labour_per_heifer*NEWCOW[year] + labour_per_heifer*COWS[year,1] + quicksum(labour_per_cow*COWS[year, i] for i in s_cow_ages) + quicksum((labour_per_acre_to_grain/GrainYld[land_group-1])*GR[year,land_group] for land_group in land_groups) + labour_per_acre_to_sb*acre_per_heifer*SB[year] <= total_available_work + EXLAB[year] for year in years), name="Labour") Each year a certain percentage of the cows die, depending on their age. # Continuity model.addConstrs((COWS[year+1,1] == survivial_rate_heifer*NEWCOW[year] for year in years if year < max(years)), "ContinuityA") model.addConstrs((COWS[year+1,2] == survivial_rate_heifer*COWS[year,1] for year in years if year < max(years)), "ContinuityB") model.addConstrs((COWS[year+1,s_cow_age+1] == survivial_rate_cow*COWS[year,s_cow_age] for year in years for s_cow_age in s_cow_ages if year < max(years)), name="Continuity") To keep the number of cows correct, cows can come into/out of the model through buying them, selling them or through birth. # Continuity C model.addConstrs((NEWCOW[year] - quicksum(new_heifers_per_cow*COWS[year,i] for i in s_cow_ages) + HFSELL[year] == 0 for year in years), name="ContinuityC") At the end of the five years, the farmer wants at least 50 and at most 175 diary cows. # End Total model.addConstr(min_end_total <= quicksum(COWS[max(years), i] for i in s_cow_ages) <= max_end_total, "END") The following constraints make sure that the variable PROF takes the value of the profit in this year. The costs for labor current run $4000. The profit is influenced by the selling of heifers, selling of 12-year-old-cows, selling of milk, selling of grain, selling of sugar beet, buying of grain, buying of sugar beet, labor costs, heifer costs, dairy cow costs, grain costs, sugar beet costs, and capital costs. # Profit Constraint model.addConstrs((quicksum(price_selling_bulldogs*num_bulldogs_per_cow*COWS[year, i] for i in s_cow_ages) + price_selling_heifers*HFSELL[year] + price_selling_12year_old_cows*COWS[year, 12] + quicksum(price_selling_milk*COWS[year, i] for i in s_cow_ages) + price_selling_grain*GRSELL[year] + price_selling_sugar_beet*SBSELL[year] - price_buying_grain*GRBUY[year] - price_buying_sugar_beet*SBBUY[year] - price_extra_labour*EXLAB[year] - heifer_costs*NEWCOW[year] - heifer_costs*COWS[year,1] - quicksum(cow_costs*COWS[year, i] for i in s_cow_ages) - quicksum((acre_grain_labour_cost/GrainYld[i-1])*GR[year, i] for i in land_groups) - (acre_sb_labour_cost*acre_per_heifer)*SB[year] - quicksum(annual_loan_repayment*EXCAP[i] for i in years if i <= year) - PROF[year] == available_labour_cost for year in years), "PROFIT") In the first year, there are 9.5 one year old cows and 9.5 two year old cows. In addition, there are 9.8 cows for each age from three to 12. Note that we are solving a LP model to make the model computationally easier to calculate. This can lead to fractional values for variables, which are in reality integers. The implementation needs to take this into account. model.addConstrs((initial_heifers == COWS[1, cow_age] for cow_age in cow_ages if cow_age < 3), name="Initial_condition_heifers") model.addConstrs((initial_cows == COWS[1, cow_age] for cow_age in cow_ages if cow_age >= 3), name="Initial_condition_cows") The total profit consists of the calculated profit minus the costs for additional labor and housing that need to be bought: # Profit model.setObjective(quicksum(PROF[t] - capital_expenditures*EXCAP[t] - annual_loan_repayment*t*EXCAP[t] for t in years), GRB.MAXIMIZE) Next, we start the optimization and Gurobi tries to find the optimal solution. model.optimize() for v in model.getVars(): if v.X != 0: print("%s %f" % (v.Varname, v.X)) Note: If you want to write your solution to a file, rather than print it to the terminal, you can use the model.write() command. An example implementation is: model.write("farm-planning-output.sol") Gurobi Output and Analysis Changed value of parameter UpdateMode to 1 Prev: 0 Min: 0 Max: 1 Default: 0 Optimize a model with 116 rows, 130 columns and 733 nonzeros Coefficient statistics: Matrix range [4e-02, 3e+02] Objective range [1e+00, 4e+02] Bounds range [0e+00, 0e+00] RHS range [6e+00, 4e+03] Presolve removed 84 rows and 66 columns Presolve time: 0.00s Presolved: 32 rows, 64 columns, 252 nonzeros Iteration Objective Primal Inf. Dual Inf. Time 0 1.7920000e+33 5.000000e+30 1.792000e+03 0s 21 1.2171917e+05 0.000000e+00 0.000000e+00 0s Solved in 21 iterations and 0.00 seconds Optimal objective 1.217191729e+05 Analyzing the Output The optimal plan results in a total profit of $121 719 over the five-year period the model covers. The detailed plan for each year is as follows. Note: In order to create the final action plan, the optimal values shown below have been rounded so they are integers. The maximum number of cows limit is only reached in year one. No investment should be made to expand housing.
https://www.gurobi.com/resources/farm-planning/
CC-MAIN-2021-43
refinedweb
3,301
63.29
Presented by Josh Livni and Christopher Schmidt Document contributions from Tim Sutton and Tyler Erickson TOPICS NOTE: This document has been modified from the actual workshop given at FOSS4G. For example, installation instructions have been removed (as they will soon be deprecated by those available at geodjango.org). Various other modifications have also taken place. Code for this project may be downloaded from According to django website (djangoproject.com), Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. For projects where you need to get a robust database driven application online in a timely manner, Django can be an exceptional tool. In line with another popular Django slogan, GeoDjango has been called a Geographic Web Framework for Perfectionists with Deadlines. As of Django v1.0, GeoDjango is part of the core set of Django packages that ship with the default download. Adding Geographic capabilities to a Django project is as simple as ensuring you have the base software stack, and enabling the gis contrib package within Django. This workshop is designed for people who may be new to Django, but have familiarity with python and general web concepts, such as HTML/CSS, templating, and apache or other web servers. Although it is not required, you will likely get more out of this workshop if you try make it through the introductory Django tutorial at djangoproject.com before the FOSS4G conference. GeoDjango can work with different spatial databases, and can function without GDAL/OGR. However, for the purposes of this workshop we will be using PostGIS and GDAL/OGR. 2.1: VMWare Virtual Machine (Recommended): A VMWare image will be provided to workshop participants on DVD at the start of the workshop. The VMWare image has all the required software pre-installed on a linux base, including: Under the assumption we may not have network access, the VMWare image also includes a WMS server that can be used by OpenLayers to display some basic administrative boundaries as a background to the data we'll be interacting with. VMWARE REQUIREMENTS: 2.3: Self Installation: REMOVED 2.4 Test your installation Before we get started with Django, let's be sure we have all the software correctly installed. from django.contrib.gis.gdal import HAS_GDAL HAS_GDAL You should get a result of 'True'. If not, something is amiss with your GDAL installation. For this workshop, we will be creating a project called "cape", a simple database driven web application that lets users add and edit geospatial data via a map interface. NOTE: A django 'project' can contain many django 'applications', which can exist simply as code inside subfolders within your project folder or a folder anywhere on your PYTHONPATH. We will be creating both a project and an application from scratch, and we will also include some other applications to bring in some features for us that we don't want to build ourselves. One nice thing about this is by decoupling our application from a particular website/project, we can reuse the generic application we're building today in any GeoDjango website with just a few simple lines of code saying to include it. django-admin.py startproject cape This will create a folder called cape with some basic python scripts to initiate a django project, including a manage.py script that can be run to do various django tasks and a settings.py file (see below). Note: If django-admin is not in your path you may need to preface the command with the full path of the django binaries, (eg c:\python25\lib\site-packages\django\bin\ on windows) DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'cape' DATABASE_USER = 'postgres' #scroll down to see this INSTALLED_APPS = ( #...don't delete what's already here 'django.contrib.admin', 'django.contrib.gis', ) Note: you will also need to set the DATABASE_PASSWORD to the password for your postgres user if it has one. createdb -T postgis -U postgres cape python manage.py syncdb python manage.py runserver from django.contrib import admin admin.autodiscover() # ... (r'^admin/(. *)', admin.site.root), We're now going to import some administrative boundaries from a shapefile into GeoDjango. Open up the geodjango python shell (python manage.py shell in the command prompt) to start it up again if you need, and inspect the Shapefile: python manage.py startapp lionshead Django has now created some more boilerplate for us, including some empty files that we'll be modifying to add functionality. Note how you now have a new folder called lionshead, and inside the folder are 3 new files. The next step is to tell Django to include this new application, like we did with some of the contributed ones above. Modify your settings.py so the INSTALLED_APPS tuple includes 'lionshead', 4.1 CREATING YOUR CUSTOM MODELS In django lingo, we will have a variety of "models", each of which relates to a spatially enabled table in the PostGIS database. To get an idea of some of the things geodjango offers us, we will be both creating the models by hand, and by auto-generating them from an existing shapefile. Now is the time to break into teams, so you can help eachother out as you work to get your first models in this application up and running. For the first phase, we will be creating models manually. Each team will create the first two models by hand, and ensure they are able to work with the geographic data in these models using the default GeoDjango admin panel. For this application, we're going to build a model for recording Locations of Interest (points), and a model for storing election wards (polygons). Open up your models.py, and let's create our first model. Your models.py should look like this: from django.contrib.gis.db import models class InterestingLocation(models.Model): """A spatial model for interesting locations """ name = models.CharField(max_length=50, ) description = models.TextField() interestingness = models.IntegerField() geometry = models.PointField(srid=4326) #EPSG:4236 is the spatial reference for our data objects = models.GeoManager() # so we can use spatial queryset methods def __unicode__(self): return self.name Because we've added the lionshead application to our INSTALLED_APPS for our project, and created a new model in the lionshead application, we can now run the syncdb command again to have django create the appropriate table for us in our PostGIS database: python manage.py syncdb 5.1 WITH THE PYTHON SHELL python manage.py shell from django.contrib.gis.utils import add_postgis_srs add_postgis_srs(900913) from lionshead.models import InterestingLocation from django.contrib.gis.geos import Point il = InterestingLocation() il.name = 'some place' il.interestingness = 3 il.geometry = Point(-16.57,14.0) il.save() 5.2 IN THE ADMIN At this point, we could start building some views and templates that we will need in order to actually display data from this model in our public facing site. However, since we're lazy (for now), let's register this model with the admin, and then we can use it to modify and view our data. First create a new file called "admin.py" in the lionshead folder, and add these import lines to the top: from django.contrib.gis import admin from models import * Below the imports, create a new OSMGeoAdmin class, and register the model with the admin package. The OSMGeoAdmin uses OpenStreetMap data for the background, and displays points in a 'spherical mercator' projection. class InterestingLocationAdmin(admin.OSMGeoAdmin): list_display = ('name','interestingness') list_filter = ('name','interestingness',) fieldsets = ( ('Location Attributes', {'fields': (('name','interestingness'))}), ('Editable Map View', {'fields': ('geometry',)}), ) # Default GeoDjango OpenLayers map options scrollable = False map_width = 700 map_height = 325 # Register our model and admin options with the admin site admin.site.register(InterestingLocation, InterestingLocationAdmin) Ok - now, assuming no typos, we should be able to reload in the browser and see our new Locations model. Click on it, and then at the top right click 'Add Interesting Location' to add a new Interesting Location. You will need to fill out the name and interestingness values (by default they are required, and we did not specify they are optional), and then you can click the map to add a new location, and save. At this point, we have covered one of the key functionalities of GeoDjango and of building yourself a GIS enabled website: An interactive map that lets you view/modify spatial data that's stored inside PostGIS. To summarize what we've done so far: The next step we'll do is customize some views and associated templates which will be the public facing website. To display our map publicly, we are going to build two basic items: 6.1: OUR FIRST VIEW from django.shortcuts import render_to_response from django.contrib.gis.shortcuts import render_to_kml from lionshead.models import * def all_kml(request): locations = InterestingLocation.objects.kml() return render_to_kml("placemarks.kml", {'places' : locations}) Pretty simple, eh? As you can see, we've imported a few things: render_to_response -- unused in our code so far render_to_kml -- a geodjango shortcut for spitting out kml to our templates all our models (for now, just InterestingLocation) In our all_kml method, we simply retrieved all our InterestingLocation objects from the database, and sent them off to a "placemarks.kml" which can access them via a variable called "places". 6.2 OUR FIRST TEMPLATES Next, we need to make that placemarks.kml. Oh wait - actually we don't, since a basic templates.kml is already included for us with the GeoDjango installation. You can go see it at django/contrib/gis/templates/gis/kml Since Django knows about our contrib.gis package, and it's associated templates, we can use the placemarks.kml by telling our view where this specific template is relative to our base gis templates folder. Change the render_to_kml in the view we made from "placemarks.kml" to the relative path from our gis contrib templates: "gis/kml/placemarks.kml"/ NOTE: If we wanted to customize these (which we will later), we could simply copy them to our own 'templates' subfolder, and they would take precedence over the default contrib templates, but for now these generic ones will do. At this point, we should just be able to access our view and be good to go. But how do we access it? 6.3 URLS We still haven't given Django enough information to know how to direct users to a particular page. This is where the urls.py comes in - it controls which views get loaded based on what URL a user is requesting. Open up the urls.py and add the following import statement: from lionshead.views import * And then, add this line under the admin tuple: (r'^kml/', all_kml) This URL pattern says that if someone goes to ,django will run the all_kml view, and do whatever it says to do (in our case, return some kml placemarks) Now load up 6.4 THE PUBLIC MAP PAGE Not only did GeoDjango automagically set the appropriate KML mime-type for us, but with just a 3 line view and a simple url pattern, we have a nice kml showing all our geodata. Feel free to add a new location or two via the Admin site, and reload the kml. Now that we have a working kml feed, we can add it to a map. But first we need a map to add it to, and for this we're going to create a new view and associated template that will display an openlayers map for the public: Back in your views.py, add the following method: def map_page(request): lcount = InterestingLocation.objects.all().count() return render_to_response('map.html', {'location_count' : lcount}) This view says that it will load a template called "map.html", and that template will get passed the total number of location objects we have in the database. Let's create that template: In your lionshead folder, create a folder called 'templates', and within this folder, create a new file called 'map.html'. This file should look something like this: <html> <head> <script src=""></script> <script type="text/javascript"> var map, base_layer, kml; function init(){ map = new OpenLayers.Map('map'); base_layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "", {layers: 'basic'} ); kml = new OpenLayers.Layer.GML("KML", "/kml/", { format: OpenLayers.Format.KML }); map.addLayers([base_layer, kml]); map.zoomToMaxExtent(); } </script> </head> <body onload="init()"> Hi. There should be a total of {{location_count}} Locations.<br /> <div id="map"></div> </body> </html> And again, we need to create a url mapping so we can get to this view. In urls.py, add: (r'^$', map_page) We've now mapped the root of the site (/) to the index view we created, which in turn will display the map.html with the location_count variable dynamically filled in by Django. This combination of a view and a template (along with an associated url mapping) are how we'll build most of the public facing pages. There are a variety of shortcuts that Django offers, letting you entirely skip the creation of views for common view tasks, and letting you build your views in a generic manner so they can be reused by multiple urls and templates, but all that is out of the scope of this workshop. If we wanted to provide an alternative download form for users who wanted to open the data in something like (for example) Google Earth, we could add a regular HTML link to the /kml/ URL: <body onload="init()"> Hi. There should be a total of {{location_count}} Locations.<br /> To see this data in Google Earth, <a href="/kml/">Open as KML</a>. <div id="map"></div> </body> We're now going to import some administrative boundaries from a shapefile into GeoDjango. Open up the geodjango python shell (python manage.py shell in the command prompt to start it up again if you need , and inspect the Shapefile: from django.contrib.gis.gdal import DataSource wards = DataSource('data/wards_4326.shp') layer = wards[0] print layer.fields print len(layer) # getting the number of features in the layer print layer.geom_type.name # Should a polygon print layer.srs.name # WGS84 Now that we know what attributes the shapefile has, we can create a model for it. Open up your models.py in your text editor, and add a new model: class Ward(models.Model): """Spatial model for Cape Town Wards""" subcouncil = models.CharField(max_length=20) party = models.CharField(max_length=50) ward = models.CharField(max_length=50) cllr = models.CharField(max_length=150) geometry = models.MultiPolygonField(srid=4326) objects = models.GeoManager() def __unicode__(self): return '%s (%s)' % (self.cllr, self.party) Now that the Model is created, we can run syncdb to have django create us the associated table in the database. At the command line, run: python manage.py syncdb And, back in our python shell, we can define the Layer Mapping and import the code from lionshead.models import Ward from django.contrib.gis.utils import mapping, LayerMapping print mapping(wards) lm = LayerMapping(Ward, wards, mapping(wards, geom_name='geometry')) lm.save(verbose=True) This will read the data from the provinces shapefile and load it into our Ward model in PostGIS. As before, we need to hook this up into our Admin, so open up admin.py and add a new class: class WardAdmin(admin.OSMGeoAdmin): list_display = ('cllr','ward') fieldsets = ( ('Location Attributes', {'fields': (('cllr','ward'))}), ('Editable Map View', {'fields': ('geometry',)}), ) scrollable = False map_srid = 4326 debug = True # Register our model and admin options with the admin site admin.site.register(InterestingLocation, InterestingLocationAdmin) admin.site.register(Ward, WardAdmin) NOTE: We could also add more openlayers options to the admin. For example, we can give a different URL for the OpenLayers library, as follows: openlayers_url = '/static/openlayers/lib/OpenLayers/js' (r'^static/(?P<path>. *)$', 'django.views.static.serve', { 'document_root': 'q:\projects\cape\static', 'show_indexes': True}), For a larger list of options we can pass to the map admin, see Once we have done this, we could certainly create a similar KML output to the InterestingPoint KML we created above for all the Ward geometries. But as much fun as displaying one data layer at a time can be, let's instead create a more complex view that displays just one ward (which will be specified in the URL), and have this view feed a map template that highlights the appropriate ward, and all the Interesting Locations that are within 5 miles of that ward. In this section, we'll be creating a ward-specific viewing page. That ward page will list the interesting points inside the ward, and list them in the HTML page, and finally display a map. First, we'll edit the urls.py file. Earlier, we built a urls.py that had in it: (r'^kml/', all_kml), (r'^/$', map_page) Now, we'll be adding one more URL to this list: (r'^kml/', all_kml), (r'^/$', map_page), (r'^wards/(?P<id>[0-9] *)/', ward), We've added an item for viewing a specific ward. You'll see here that there is additional syntax in this URL: This URL matching is a regular expression, and allows us to pull the ID from the URL and use it as a parameter to the ward function we're going to write. There are two different queries we want to perform in order to build the ward page. First, we want to take the passed in ID, and we want to find the associated ward. If the ID is invalid, we want to return a 404 to the user. Django has a shortcut for this type of thing, because it's a relatively common operation. Like all shortcuts, it is in django.shortcuts, and it's called 'get_object_or_404'. We'll use this to get our ward: from django.shortcuts import get_object_or_404 ... def ward(request, id): ward = get_object_or_404(Ward, pk=id) Using this, we get the ward we care about as the ward variable. Then, we'll want to find nearby interesting points -- within 5 miles of the borders of our ward. NOTE xxxxxx Change below to actually use a 5mile buffer xxxxxxxxx def ward(request, id): ward = get_object_or_404(Ward, pk=id) interesting_points = InterestingLocation.objects.filter( geometry__intersects=(ward.geometry)) Then, we'll pass both of these objects -- the ward, and the list of locations -- into the ward template. def ward(request, id): ward = get_object_or_404(Ward, pk=id) interesting_points = InterestingLocation.objects.filter( geometry__intersects=(ward.geometry)) return render_to_response("ward.html", { 'ward': ward, 'interesting_points': interesting_points }) Next, we'll build our template. Because we'll be building a map again, we can start with the same template as we use for our map_page view, so start by copying 'map.html' to 'ward.html' in your lionshead/templates directory. Now, instead of loading data from the KML view we created earlier, we're going to create features directly in our template. You could also create a second view to serve your data up to be loaded asynchronously (as we did with the KML before): this is just demonstrating another way to achieve the same goal. So, remove the 'kml = new OpenLayers.Layer.GML' line and the line that follows it from the new 'ward.html' template. Next, you'll be creating a geometry from GeoJSON created in the template. geojson_format = new OpenLayers.Format.GeoJSON() ward = geojson_format.read({{ ward.geometry.geojson|safe}})[0]; // We mark it 'safe' so that Django doesn't escape the quotes. ward.attributes = { 'name': "{{ward.name}}", 'type': 'ward'}; vectors = new OpenLayers.Layer.Vector("Data"); vectors.addFeatures(ward); Next, change the 'kml' in the addLayers call to 'vectors'. Also, we only care about this ward at this time, so we can change the setCenter call to "map.zoomToExtent(ward.geometry.getBounds());" -- This will zoom the map to just the bounds of the ward. Finally, change the {{location_count}} variable in the text further down the page to simply {{interesting_points.count}} -- this will issue a SELECT COUNT(*) FROM query to the database, giving back a count of the number of matching features. Now, we should be able to loop over the points in the ward, and add each of them to the map as well. We also want to add them to the HTML page, so we'll do one iteration in the main body of the page, and add features to an array to be parsed in the loading function as we go. Directly above the <script> var points = []; </script> <ul> {% for point in interesting_points %} <li>{{ point.name }} -- {{point.interestingness}}</li> <script>points.push({{point.geometry.geojson|safe}});</script> {% endfor %} </ul> Now, each of your points will be displayed on the map. You can then add code to the initialize function to add them to your vector layer. This should go immediately after the 'vectors.addFeatures' call above. for (var i = 0; i < points.length; i++) { point = format.read(points[i])[0]; point.attributes = {'type':'point'}; vectors.addFeatures(point); } Now, you can visit your ward page by going to, for example, . You can compare this to viewing in the admin by visiting . Now, we can go to, and scroll to the Southeast of Cape Town. You will see a label that says "Strand". Place a marker in the residential area here, and then visit again, and you should see a single interesting point listed in this area. Congratulations, you've just combined the data of two different layers in GeoDjango, using a database-backed intersection query. from django.contrib.gis.geos import * from django.contrib.gis.measure import D # D is a shortcut for Distance from lionshead import InterestingLocation, Ward from world.models import Countries #define a point location pnt = fromstr('POINT(18.4 -33.9)', srid=4326) OUTPUT FORMATS pnt.geometry.kml pnt.geometry.geojson pnt.geometry.gml BUFFERING pnt.buffer(1.5).area pnt.buffer(1).kml DISTANCE QUERIES # Distances will be calculated from this point, which does not have to be projected. # If numeric parameter, units of field (meters in this case) are assumed. #queryset of all interesting locations within 500 miles, 50km, or 100 chains of this point qs=InterestingLocation.objects.filter(geometry__distance_lte=(pnt,D(mi=500))) qs=InterestingLocation.objects.filter(geometry__distance_lte=(pnt,D(km=50))) qs=InterestingLocation.objects.filter(geometry__distance_lte=(pnt,D(chain=100))) poly = WorldBorders.objects.get(name='Algeria').geometry for loc in InterestingLocation.objects.distance(poly.centroid): print loc.name, loc.distance.km BOUNDING BOX qs = Ward.objects.filter(name__in=('foo', 'bar')) print qs.extent() It is quite possible workshop attendees will not have internet access. In this case, the default OpenLayers map settings (which assume they will have access to live WMS or other tile services) will fail. We can fix this by: wms_url = '/cgi-bin/mapserv?map=/home/user/wms/cape.map&' wms_layer = 'countries,wards' wms_name = 'Local WMS' var ms_url = '/cgi-bin/mapserv?map=/home/user/wms/cape.map&' var countries = new OpenLayers.Layer.WMS("Countries", ms_url, {layers : 'countries'} ); var wards = new OpenLayers.Layer.WMS("Wards", ms_url, {layers : 'wards'} ); map.addLayers([countries, wards, kml]); William Kyngesburye provides a number of geo-related binary packages that can get you most of the way to having Django working and installed without compiling anything from source. From : From : After you have installed each of these, you'll need the psycopg2 bindings. I could not find a working version of these for OS X, so I did: sudo su PATH="$PATH:/usr/local/pgsql/bin" python easy_install psycopg2 This requires the OS X Developer tools to be installed. Then, just download and install Django itself, and you're all set. If you get a complaint about GEOS_LIBRARY_PATH not being set, add the following to your settings file: GEOS_LIBRARY_PATH="/Library/Frameworks/GEOS.framework/unix/lib/libgeos_c.dylib" Rendering Polygons to KML
http://code.google.com/p/geodjango-basic-apps/wiki/FOSS4GWorkshop
crawl-002
refinedweb
3,929
57.06
[ ] Robert Winslow commented on AMQ-721: ------------------------------------ This issue has been outstanding for some time. While I could use another Language to allow me to use ActiveMQ it is not the prefered language. As such I will not be able to use an ActiveMQ as a solution. Some input or some type of acknowledgment that this issue is being addressed would be fantastic, > Openwire client hangs after receiving 999 messages > -------------------------------------------------- > > Key: AMQ-721 > URL: > Project: ActiveMQ > Type: Bug > Components: JMS client > Versions: 4.0 > Environment: .NET 2.0 ,C# + trunk > Reporter: vincent boilay > Priority: Blocker > > > Openwire client hangs after receiving 999 messages > changing Session.Prefetch postpone the problem... > Current code is : > public class Session : ISession > { > : > : > private int prefetchSize = 1000; > this block at message #999 > changing private int prefetchSize = 2000 ==> blocks at message #1999 -- This message is automatically generated by JIRA. - If you think it was sent incorrectly contact one of the administrators: - For more information on JIRA, see:
http://mail-archives.apache.org/mod_mbox/activemq-dev/200606.mbox/%3C14464948.1151584371670.JavaMail.jira@brutus%3E
CC-MAIN-2017-17
refinedweb
157
52.19
Things that we tried but decided were not good ideas. Using more aggressive calling conventions/inlining in ceval The Py_LOCAL/Py_LOCAL_INLINE macros can be used instead of static to force the use of a more efficient C calling convention, on platforms that support that. We tried applying that to ceval, and saw small speedups on some platforms, and somewhat larger slowdowns on others. List pre-allocation Adding the ability to pre-allocate builtin list storage. At best we can speed up appends by about 7-8% for lists of 50-100 elements. For the large part the benefit is 0-2%. For lists under 20 elements, peformance is actually reduced when pre-allocating. Out-thinking exceptions CPython spends considerable time moving exception info around among thread states, frame objects, and the sys module. This code is complicated and under-documented. Patch 1145039 took a stab at reverse-engineering a weak invariant, and exploited it for a bit of speed. That worked fine so far as it went (and a variant was checked in), but it's likely more remains to be gotten. Alas, the tim-exc_sanity branch set up to try that consumed a lot of time fighting mysteries, and looks like it's more trouble than it's worth. Singleton of StopIteration As part of the new exceptions implementation, we tried making a singleton StopIteration instance. No speedup was detected. This is primarily due to most uses of StopIteration using the type object directly (ie "raise StopIteration" vs. "raise StopIteration()"). Even for a crafted test case where the instance use was forced there was no detectable change in speed. GET_SIZE Macros Making a PyDict_GET_SIZE like PyTuple_GET_SIZE doesn't give a measurable improvement in pybench or pystone. This is likely because the compiler notices that those functions that use it have alreaday done NULL checks and frequently PyDict_Check so we aren't telling it anything it didn't already know. Conversely changing all Py(Tuple|List)_GET_SIZE to point to plain Size has no measurable slowdown! Well, in the range of 0.5%, which may just be noise. Switching the #define to the real functions generates some spurious warnings because the regular methods expect PyObjects and not the more specific types. Specializing Dictionaries One man-day was spent trying to seperate the dicts used in namespaces (module.dict, instance/type/class dicts) the result was changing over a quarter of the PyDict* macros in the trunk to PySymdict (over half if you exclude Modules/). This was such a massive change it was abandoned after sprint Day1. Switching to 64-bit ints on 32-bit platforms Tested out an idea about switching Python "integer" types to use 64 bits instead of 32 bits on 32-bit platforms. In the end, it would have been a major pain to do, and while it would have resulted in 34% performance improvements for apps that use integers between 32 and 64 bits, it would have been around a 10% slow-down for apps that only use 32-bit numbers. Decided not to do it for those reasons. Pymalloc with VC8 Tried not using the pymalloc module in the VC8 windows build environment. MS boasts of its own fast small block allocator, but it turned out not to work. Possibly it needs to be explicitly turned on! Unicode Classification Disabling the Unicode classification stuff (isupper) and using the c-runtime supplied one, turned out to be much slower. no surprises.
https://wiki.python.org/moin/NeedForSpeed/Failures?highlight=PyObjects
CC-MAIN-2017-30
refinedweb
575
62.68
Because these disciplines constitute the foundation of all machine learning algorithms, math and statistics are vital for data science. Moreover, every element of our lives is influenced by mathematics. From shapes, patterns, and colors to counting petals in flowers, everything around us is based on mathematics and statistics. The ability to graphically describe, summarize, and portray data is essential in dealing with data. Python Statistics Libraries are comprehensive, accessible, and widely used tools for working with data. Statistics Library in Python Data collection, analysis, interpretation, and presentation are all part of statistics, which is a mathematical science. Thus, data scientists and analysts can look for relevant data trends and changes using statistics, which are used to solve challenging real-world problems. To put it another way, statistics may be utilized to gain essential insights from data by doing mathematical computations. The statistics module in Python includes utilities for calculating numeric mathematical statistics. The essential concepts of statistics are mean, median, and mode. They’re simple to calculate in Python, both with and without the use of additional libraries. These are the three most used central tendency measures. The central tendency tells us what a dataset’s “normal” or “average” values are. It is the appropriate tutorial for you if you’re just getting started with data science. By the end of this tutorial, you will be able to: But, first, understand the meaning of the terms mean, median, and mode. This section will create our mean, median, and mode functions in Python and quickly use the statistics module to get started with these metrics. A Dataset’s Mean A dataset’s mean, or average, is computed by summing all the values and dividing by the number of items in the collection. For example, the mean of the dataset [4,5,6] is: (4+5+6) / 3 = 5 One of the most frequent approaches to describe statistical findings is to determine the average of a dataset. Thus, people frequently use terms like, typically, or often to indicate the data’s center. In this session, you will learn how to calculate the mean of a dataset, which is a specific measure of a dataset’s average. We’ll use the medium to assist us in answering the question. Calculating the Average The mean, sometimes known as the average, is a method of determining the average of a dataset. A two-step process is used to calculate the average of a set: Step 1: In your dataset, add all of the observations. Step 2: Divide the total sum by the number of points in your dataset. xˉ=(x1 + x2…+xn)/n The mean is calculated using the equation above. Observations x1, x2, … xn come from a dataset of n observations. Example Consider the following scenario: we want to determine the average of a dataset with four observations: data = [4, 6, 2, 8] Step One: Calculation of the total 4 + 6 + 2 + 8 = 20 Step Two: Division of the total by the given count of observations The resultant total is equivalent to 20, while the count of the observation is 4. 20/4 = 5 The resulting average value of this division is 5. Average NumPy While you’ve demonstrated that you can calculate the average on your own, it becomes time-consuming as your dataset grows in size – imagine adding all of the numbers in a dataset with 10,000 observations. The NumPy.average() or.mean() functions can help you with addition and division.np.average() is essential in calculating the average of a dataset with tens of values in the example below. import numpy as np array_list = np.array([27, 19, 33, 13, 15, 31, 41, 5, 7, 39]) average_vals = np.average(array_list) print(average_vals) The code above computes the average of the example array and saves the result in the variable example average. The array’s average, as a result, is 23. Using Python to Calculate the Mean One of the widely known central tendency measures includes the mean, sometimes known as the arithmetic average. Remember that the central tendency of a set of data is a typical value. Because a dataset is a collection of data, a dataset in Python can be any of the built-in data structures listed below: - Objects are organized into lists, tuples, and sets. - Strings are a group of characters. - A dictionary is a set of key-value pairs. Although Python has various data structures such as queues and stacks, we’ll only use the built-in ones. We can find the mean by summing all the values in a dataset and dividing the result by the number of values. In case of the following examples: [4, 5, 6, 7, 8, 9] Because the list’s total length is 6 and its sum is 39, the mean or average would be 6.5. The result of dividing thirty-nine by six is 6.5. This computation can be done using the formula below: (4 + 5 + 6 + 7 + 8 + 9) / 6 = 6.5 User-Defined Mean Function Let’s start by estimating the average (mean) age of the drivers in a racing team. The team will be known as “Pythonic Racing.” pythonic_racing_ages = [22, 25, 37, 29, 35, 33, 27, 27] def custom_mean(data_vals): return sum(data_vals) / len(data_vals) print(custom_mean(pythonic_racing_ages)) The following are the steps to deciphering this code: The “pythonic racing ages” is a list of drivers’ ages. A custom_mean() function is defined, which returns the total of the specified dataset divided by its length. The sum() function, paradoxically, returns the whole sum of the values of an iterable, in this case, a list. So if you try to pass the dataset as an argument, you’ll get a 211 response. If you send the dataset to the len() function, it will return 8 as the length of an iterable. Then, we use the custom_mean() function to calculate the ages of the racing team and then report the result. It is the output of the average age of the drivers. It’s worth noting that the number doesn’t appear in the dataset but accurately describes the age of the majority of players. Using the Python Statistic Module’s mean() function Most developers are familiar with calculating measures of central tendency. Because Python’s statistics module includes various functions for calculating them and other essential statistics topics, this is the case. PIP does not require installing any external packages because it is part of the Python standard library. It is how you should use this module. from statistics import mean racing_ages = [22, 25, 37, 29, 35, 33, 27, 27] print(mean(racing_ages)) Import the mean() function from the statistics module and pass the dataset as an argument in the above code. The result will be the same as the custom function we defined in the previous section: 29.375 Example 1: using statistics module import statistics as stat list_vals= ([2, 5, 6, 9]) mean_val=stat.mean(list_vals) print("The resultant mean of the list is: ", mean_val) Let’s move on to the median measurement now that you’ve grasped the concept of the mean. A dataset’s median The median of a dataset is the value that falls in the middle, provided the dataset is sorted from smallest to greatest. The median is the middle two values in a dataset with an even number of values. Assume we have the following ten numbers in our dataset: 34, 26, 40, 20, 22, 38, 48, 12, 14, 46 The result of ordering this dataset from the smallest to the largest is as follows. 12, 14, 20, 22, 26, 34, 38, 40, 46, 48 This dataset’s medians are 26 and 34, respectively, because they are the fifth and sixth observations in the dataset. Alternatively, there are four observations to the left of 26 and four to the right of 34. If we added a new value (say, 28) near the middle of the dataset, it would look like this: 12, 14, 20, 22, 26, 28, 34, 38, 40, 46, 48 Because there are 5 values smaller than it and 5 values greater than it, the new median equals 28. In Python, how do you find the median? The median of a sorted dataset is the value in the middle. It’s used to provide a “typical” value for a given population once more. The median is the value that divides a sequence into two parts — the lower half and the upper half — in programming. We must first sort the dataset to calculate the median. We could use sorting algorithms or the built-in function sorted() to accomplish this. The next step is to figure out whether the dataset is odd or even in length. Some of the following processes may be affected by this: - Odd: The median is the dataset’s middle value. - Even: The median is a result of dividing the sum of the two middle numbers by two. Let’s continue with our racing team dataset and calculate the median height in cm of the drivers: [181, 187, 196, 196, 198, 203, 207, 211, 215] Since the dataset is odd; we select the middle value median = 198 As you can see, we may use the middle value as the median because the dataset length is odd. What if, on the other hand, one player retired? We’d have to determine the median using the dataset’s two middle values. [181, 187, 196, 198, 203, 207, 211, 215] We select the two middle values and divide them by 2 median = (198 + 203) / 2 median = 200.5 User-Defined Median Function Let’s put the above idea into practice with a Python function. While doing so, remember the three stages we must do to find the dataset’s median: Sort the data in the following order: This can be accomplished using the sorted() function. Subsequently, determine whether the set is odd or even: We can do this by calculating the dataset’s length and applying the modulo operator ( percent ) Calculate the median for each case: - Odd: Return the value in the middle. - Even: In this case, the average of the two middle values should be returned. As a result, the following function would be created: racing_heights = [181, 187, 196, 196, 198, 203, 207, 211, 215] racing_heights_after_retirement = [181, 187, 196, 198, 203, 207, 211, 215] def median(dataset): data = sorted(dataset) index = len(data) // 2 # If the dataset is odd if len(dataset) % 2 != 0: return data[index] # If the dataset is even return (data[index - 1] + data[index]) / 2 Next is printing the desired outcome of the dataset. print(median(racing_heights)) print(median(racing_heights_after_retirement)) At the start of the function, we create a data variable that points to the sorted dataset. Even though the lists above are sorted, we want to create a reusable function, so we’ll have to sort the dataset each time the function is called. Using the integer division operator, the index stores the dataset’s middle value — or upper-middle value. For example, if we passed the “racing heights” list, the value would be 4. Remember that sequence indexes in Python start at zero since we may return the middle index of a list using integer division. Then we compare the result of the modulo operation with any integer that isn’t zero to see if the dataset’s length is odd. In the case of the “racing heights” list, if the condition is true, we return the middle element: racing_heights[4] If the dataset is evenly distributed, we return the total of the middle values split by two. It’s worth noting that data[index -1] offers us the dataset’s lower midpoint, whereas data[index] gives us the upper midway. Using the Python Statistic Module’s median() function Because we’re using an already-existing function from the statistics module, this method is significantly easier. We would utilize something that has already been defined for us because of the DRY principle (don’t repeat yourself) (in this case, don’t duplicate other people’s code). The following code will determine the median of the previous datasets: from statistics import median as md racing_heights = [211, 217, 226, 226, 228, 233, 237, 241, 245] racing_height_after_retirement = [211, 217, 226, 228, 233, 237, 241, 245] print(md (racing_heights)) print(md (racing_height_after_retirement)) Example 1: using median statistics module list_vals= ([5, 8, 9, 12]) import statistics as st median_val=st.median(list_vals) print("The resultant Median of the list is: ", median_val) Median_low When considering an odd number of data points, the middle value is returned. When the two middle values are equal, the smaller of the two is returned. list_vals = [ 4, 6, 8, 10 ] import statistics as stat low_median = stat.median_low(list_vals) print("The Median Low of the list is: ",low_median) Median_high In case there is an odd number of data points, the middle value is returned. When the two central values are equal, the greater of the two is returned. list_vals = [ 4, 6, 8, 10 ] import statistics as stat high_median = stat.median_high(list_vals) print("The resultant Median High of the list is: ", high_median) Median_grouped Return the median of grouped continuous data via interpolation, calculated as the 50th percentile. Statistics Error is triggered if the data is empty. The data are rounded in the following example. Each number reflects the midpoint of data classes, e.g., 1 represents the midpoint of class 0.5-1.5, 2 represents the midpoint of 1.5-2.5, 3 represents the midpoint of 2.5-3.5, and so on. import statistics as stat list_vals = [3, 5, 5, 6, 7, 7, 7, 7, 7, 8] grouped_median = stat.median_grouped(list_vals) print("The Median Group of the list is: ",grouped_median) Example 1.6: grouped median The grouped median with numeric data interval is returned by the median_ grouped () method. The class interval is represented by the optional argument interval, which defaults to 1. The interpolation will alter if the class interval is changed: import statistics as st var_list = [4, 6, 6, 8, 10] median_group_one = st.median_grouped(var_list, interval=1) median_group_two= st.median_grouped(var_list, interval=2) print("The Median Group One of the list is: ", median_group_one) print("The Median Grouped Two of the list is: ", median_group_two) A Dataset’s Mode The mode can be expressed as the value that is very common in a given dataset. We can conceive of it as a school’s “popular” group, which may set a benchmark for all pupils. A tech store’s daily sales could be an illustration of mode. The most popular product on a given day would be the mode of that dataset. ['laptop', 'desktop', 'smartphone', featurephone, featurephone, 'headphones'] The mode of the above dataset is “featurephone,” as you can see because it was the most common value in the list. The significant part about the mode is that it doesn’t require a numeric dataset. So we can, for example, work with strings. Let’s have a look at the sales from another day: ['mouse', 'camera', 'headphones', 'usb', 'headphones', 'mouse'] Because both have a frequency of two, the dataset above contains two modes: “mouse” and “headphones.” Therefore, it indicates that the dataset is multimodal. What if, in a dataset like the one below, we can’t find the mode? ['usb, camera, smartphone, laptop, television'] It is known as a uniform distribution, and it simply means that the dataset has no mode. Let’s compute mode in Python now that you’ve grasped the concept of mode. Creating a User-Defined Mode The frequency of a value can be thought of as a key-value pair or a Python dictionary. Using the basketball analogy again, we can work with two datasets: scores per game and sneaker sponsorship of some players. To find the mode, we must first create a frequency dictionary with all of the values in the dataset, then calculate the maximum frequency and return all elements with that frequency. Let’s examine what this looks like in code: game_points = [6, 18, 26, 45, 33, 13, 13, 15] name_of_sponsor = ['nike', 'deloitte', 'nike', 'adidas', 'adidas', 'rebook', 'puma', 'deloitte'] def mode(dataset): freq = {} for val in dataset: freq[val] = freq.get(val, 0) + 1 frequent_val = max(freq.values()) mode_vals = [key for key, value in freq.items() if value == frequent_val] return mode_vals Using the two lists as arguments, we can check the result: print(mode(game_points)) print(mode(name_of_sponsor)) As observed, the first print statement only returned one mode, whereas the second print statement returned numerous modes. To further explain the code above, consider the following: A freq dictionary is declared. We generate a histogram by iterating over the dataset. A histogram is a statistical term for a set of counters (or frequencies). If the key is found in the dictionary, the value is increased by one. On the other hand, if it isn’t found, a key-value pair with a value of one is created. The most frequent variable, paradoxically, stores the frequency dictionary’s largest value (not key). The modes variable contains all of the keys in the frequency dictionary with the highest frequency. Example 1: user-defined mode def mode_one(first): y ={} for a in first: if not a in y: y[a] = 1 else: y[a] +=1 return [g for g, i in y.items() if i==max(y.values())] print(mode_one([43,45,67,54,56,76,89,89,12,13,14,15,16,17,24,45,45,6,7])) Using the Python Statistic Module’s mode() and multimode() functions The statistics module offers us a simple way to do basic statistics operations once again. There are two functions that we can use: - mode() and - multimode() from statistics import mode, multimode game_points = [6, 18, 26, 45, 33, 13, 13, 15] name_of_sponsor = ['nike', 'adidas', 'nike', 'jordan','jordan', 'rebook', 'under-armour', 'adidas'] The code above defines the datasets we’ve been working with and imports both functions. Here’s where the minor difference comes in: Multimode() produces a list of the most frequent values in the dataset, whereas mode() returns the first mode it sees. As a result, we can call the custom function we created a multimode() function. print(mode(game_points)) print(mode(name_of_sponsor)) Note that the mode() method in Python 3.8 and higher returns the first mode is encountered. You’ll get a StatisticsError if you’re using an older version. The multimode() function can be used in the following ways: print(multimode(game_points)) print(multimode(name_of_sponsor)) Example 1: Using statistics mode list_vals=[5,8,6,5,11,6,12,7,5,8,9] import statistics as stat mode_val= stat.mode(list_vals) print("The resultant mode of the list is: ", mode_val) Example 2: Using statistics mode list_vals = ["green", "orange", "orange", "green", "red", "green", "green"] import statistics as stat mode_val= stat.mode(list_vals) print("The resultant mode of the list is: ", mode_val) Summary Congratulations! If you’ve read this far, you’ve learned how to compute the mean, median, and mode, which are the three primary measures of central tendency. Although you can create custom functions to find mean, median, and mode, the statistics module is suggested because it is part of the standard library and requires no installation. When we understand the central tendency of a sample of data, we usually look at the mean (or average), the median, and the mode first. Overall, we learned Python to determine or compute the mean, median, and mode. In addition, we went over how to develop our functions to compute them step by step and then leverage Python’s statistics module to obtain these metrics quickly.
https://www.codeunderscored.com/mean-median-and-mode-real-world-datasets-in-python/
CC-MAIN-2022-21
refinedweb
3,266
60.85
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives This article points out how open source scripting languages are in vogue in the corporate world:. (via PLNews) it demonstrates that a lot of non-technical people or people without vast knowledges of computer science are building their own, rough, quick-and-dirty in-house applications that work well, develop fast and most likely are hard to mantain ( not necessarily because of said languages lack of features or something ). I am especially disappointed that PHP has become so popular. The article focuses a great deal on PHP and Zend. PHP is the worst language abortion I have used! Even Perl is preferred! Unfortunately, I still use PHP for some web projects because PHP is the only server-side language my web host officially supports! PHP is an abortion from Perl: it comes with some of the same ugly syntax, but none of the conveniences or flexibilty. It's specially bad for its lack of modularization features other than files and classes and for the "convenience" of global variables sprinkled all over your project files ( well, much of that due to stupid wannabe programmers anyway ) and the hated 1-million-inconsistently-named-and-unrelated-functions-in-the-same-namespace thingy... I thought the magic globals were gone with recent versions of PHP. But, yeah, the 'well if you want namespaces you're going to have to manage them like you're using C' and the [some_function, smfunc somefunction] stuff is pretty ugly. yes, automagic global variables are gone. But, in change, now php has this things called "superglobals" :) Just trying to accentuate the positive - programmers are willing to learn new languages. Of course, that begs the question of how adept they are at embracing new paradigms or software engineering techniques. Object Oriented programming has been 15 years in widespread use, and it's still not practiced particularly well. And, of course, the Lispers will remind us that the current batch of programming languages are just variations on ideas that were discovered long ago. Still, I like to see the glass as being half full - new languages do have at least an outside chance of coming into use. "programmers are willing to learn new languages." Given that the number one scripting language on the JVM these days is Groovy -- complete with java-like syntax, but less declarations -- i don't really see that as an evidence that they are willing to _learn_ anything new. Just to unlearn somethings ( think less about types, for instance ) and pretty much keep up the same boring old C-like syntax and imperative style they first learned in college... There is Jython, there's Kawa and the list goes on. Nothing will move them, unless it looks familiar. that's sickening sad. In my job, i just quitted trying to bring a bit of creativity here and there in the Delphi code: my coworkers are copy-and-paste fanatics who just don't give a damn about clearness, expressiveness and code reuse in general. Only thing that matters are stupid hungarian notation and names as long as a road. They already standardized in stupidity and there's no coming back... While certainly not the only reason for these languages catching on, less synthetic code is one of the greatest benefits of dynamic languages. Want to append one list to another in Perl? my @z = (@x, @y); And who cares what data types are in there! By allowing us to focus on solving the actual problem rather than the fiddly bits in the language itself, our productivity is increased and we experience fewer bugs. If we find that we don't need the performance that other languages give us, we save a lot of money. It's natural that the suits are going to notice this (even if they're frequently incapable of making a sound technical decision.) And if you want to get the length of a list... my $len = length(@foo); Oh, I guess it does matter what type you passed to length, huh. :-) it matter it's a list. it doesn't matter what it is a list of, unlike in most mainstream typed languages... unlike in most mainstream typed languages... I don't know if you put C++ in that category, but you can do fairly good dynamic programming with it: list &lsaquo any &rsaquo list1; list &lsaquo any &rsaquo list2; list1 += 1,3.14, 'a'; list2 += "foo", myObject; list &lsaquo any &rsaquo list3 = list1 + list2; with the hack on the AST processing called the template system... Perhaps not as nice as Lisp macros (and the syntax is sure ugly), but I almost consider templates to be the biggest improvement in C++ compared to C. Why? 'Tis much more easy to greenspun up a crude facility for dynamic dispatc than it is to greenspun up anything resembling templates. After all, macro systems come in two flavors that I'm aware of: * Those that work on the abstract syntax level (i.e. C++ templates, Lisp macros) * Those that work on the pre-parsed input text (i.e the C preprocessor) Ample evidence shows that the former is highly preferable to the latter. In my opinion these scripting languages have acheived fame because they meet social and human needs of programmers - the technical and functional requirements are not as critical to becoming popular. There is a huge demand for languages that an average developer or user can be productive in quickly. Many unpopular languages are technically brilliant and extremely productive for skilled users. But they don't meet the social needs so they do not become popular. They then lack a community to help grow the language libraries, grow googleable help, and grow number of applications and code examples. A popular language: Not all the above are needed, but most are. Have I missed any other important social aspects? Comes with deep and useful standard libraries, so you can do things like regular expression matching, XML parsing, fetching email...the kind of stuff people need to do. Has one standard implementation, so you don't have the confusion of multiple, semi-compatible versions of a language (Prolog is a perfect example of the latter). In addition to Prolog, you could mention the Lisp and ML families that have a multitude of implementations. The obvious advantage to dialects is that it provides language designers the freedom to experiment with new ideas without having to go through a committee (watering down any attempts at radical change). Tacking on features to monolithic languages always seems to have a kludge flavor. As for popularity, I don't know that a standard implementation is a prerequisite for popularity. Fortran, COBOL, Basic, C, C++, Pascal, etc... never had a standard implementation and they all gained a wide audience. It's only with the advent of Java that a single vendor has tried to control the implementations, and they did that by keeping it away from a standards committee. Of course, we get C# in response to that effort. On the other hand, the open source languages do tend to have a single implementation based on personal leadership (Wall, GvR, Matz) or just based on common interest. These languages, however, are constantly re-inventing themselves such that they have to convince the users that change is for the common good. Anyhow, related to popularity is not only how good the language is today, but whether you trust the stewards of the language (be the corps, standards committees, or the charisma of the fearless leader). One reason that many open source languages have a single implementation is... because they are open source. (And the open source implementation is first). Not to mention that many of these languages do have "bazaar" development models FMTP. Thus, the two major motiviations towards development of a competing implementation (to make money, and to influence the design of the language) are less relevant. If you look at, say, Common Lisp, many of the implementations are commercial. The ones that aren't commercial either fail to support certain platforms (notably Windows). In addition, many key features needed for computing are not defined by the Common Lisp standard--networking and concurrency, for instance. A similar state of affairs exists with C/C++, one could argue. However, the primary open source C/C++ implementation (gcc) is the most portable C/C++ compiler, rather than the least; and is a robust, actively maintained, production-grade product. Furthermore, while the standards for C/C++ also are silent on topics such as networking and concurrency, C/C++ has the advantage of being the de-facto language for interfacing to both Windows and Unixish operating systems; and both OS's provide APIs for these things (POSIX, Win32) that have become de facto standards. "One reason that many open source languages have a single implementation is... because they are open source." I thought that would rather lead to countless forks, something the Java community always likes to point out when trying to convince themselves why having Sun as the single dictator is a good thing... :) Personaly, i think the success of scripting languages is due to their pragmatic approach to day-to-day job programming, focusing on conveniences -- like the typeless approach and the huge libraries for interfacing with the environment -- for the programmer to achieve results fast, rather than being an academic lab for some awesome but still experimental new programming language features and techniques... I've always been a fan of Python, Perl, Ruby and Tcl myself... I thought that would rather lead to countless forks Why? The evidence points in exactly the opposite way. The only compiler forks I can think of are a) SBCL from CMUCL, and b) GCC forking, and the fork subsequently being installed as the official version. I was just pointing out the Java community take on the issue... ...and forking isn't always bad. It's well established that copyleft licenses prevent permanent forking, wherein one party takes an existing code base, makes it proprietary, introduces useful extensions (to entice people to their camp) and gratuitious incompatiblities (to keep 'em from leaving). The multiple incompatible versions of Unix in the early 90s are the canonical example of this. However, "friendly" forks are common and are healthy for a software ecosystem. Consider projects like Jython and stackless Python for instance. Sometimes the fork overtakes the parent and becomes the new "preferred" version (Cygnus/GCC); sometimes it is content to serve some niche. And sometimes it's just done for research or curiousity. I wrote up some thoughts on "scaling down": The gist of it is that by making something easily accessible, it will be more valuable because more people will find it within their grasp. Because of this, it's also likely to be popular. Your other points are good too.
http://lambda-the-ultimate.org/node/712
CC-MAIN-2018-39
refinedweb
1,822
61.16
Greetings, I bumped into EMF bug (XML loader namespace-scoping problems) during my Tuscany SDO usage that proved to be a show-stopper for us. The bug was fixed in EMF 2.2.1-M200608030000. Do you have plans to build/test with the latest EMF milestone releases or will you stick with stable releases? Since EMF is such an integral part of the Tuscany SDO implementation, we would like to see the latest EMF code incorporated in your interim builds, a little like EMF/SDO currently works. Regards, - Ron --------------------------------------------------------------------- To unsubscribe, e-mail: tuscany-user-unsubscribe@ws.apache.org For additional commands, e-mail: tuscany-user-help@ws.apache.org
http://mail-archives.apache.org/mod_mbox/tuscany-user/200608.mbox/%3C44D1D8DC.3070409@yahoo.com%3E
CC-MAIN-2014-52
refinedweb
111
55.95
Recently I have written a rules engine for a very large menu system in an application I work on. Many of the rules apply many items, so I didn't wish to have to express the same rule many times. To avoid this, the rule engine DSL was born: Concerns.When(item => /* rule of some sort */) .AppliesToAll() .Except(MenuItems.ToggleHidden, MenuItems.Refresh) And rules are rolled together, so a specific menu item must have all of its rules evaluating to true to be displayed. The problem arose when an item was displaying when it shouldn't (or vice versa). Debugging with rules specified like this was a pain, and when I saw the article about ExpressionRules by Daniel Wertheim, I thought it would help solve my problem. He replaces Lambda conditions with a class and implicit operator, allowing code to be changed from something like this: var bonusCustomers = _customers.Where(c => (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) || (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000)); To something like this: var bonusCustomers = _customers.Where(new IsBonusCustomer()); He does this using a base class and then inheriting from it to create the rule: public class IsBonusCustomer : ExpressionRule<Customer>, IIsBonusCustomer { public IsBonusCustomer() : base(c => (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) || (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000)) { } } I took his base class and modified it to this: public abstract class ExpressionRule<T> where T : class { protected abstract bool Rule(T item); public static implicit operator Func<T, bool>(ExpressionRule<T> item) { return item.Rule; } public bool Evaluate(T item) { return Rule(item); } } This means the IsBonusCustomer now becomes this: public class IsBonusCustomer : ExpressionRule<Customer> { protected override bool Rule(Customer customer) { return (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) || (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000) } } Not only do we still have the readability of the first version, but a full function that can have logging added to it, and easier debugging.
http://stormbase.net/2011/02/09/expression-rules-version-2/
CC-MAIN-2017-17
refinedweb
319
50.02
Arduino Uno and Pro Mini are not powered efficiently in situations when you have to run them on batteries. In such situations, every milliampere of current counts. Arduino Uno draws a minimum of 15mA of current which doesn't sound like much but in certain situations quickly adds up. Arduino Uno is a development board built with several different circuits including a USB-serial converter, regulators, indicators, processors, a short circuit protection circuit, damage control circuits, etc. It uses more power than the minimum necessary. In this article, we will look at different ways we can reduce the power consumption of an Arduino by changing some hardware or using code. Low Power Arduino Libraries Arduino’s official website provides low power libraries for Arduinos to enable low power features. Let’s look at two useful codes. 1. External Wake-Up: Using this code, your Arduino will wake up from sleep when an external button is pressed. You can use this code to wake up your Arduino using a sensor. 2. Timed Wake-up: This code wakes up the Arduino after a set amount of sleep. The above sleep modes reduce the continuous idle power usage of an Arduino Uno. However, they are almost useless because everything other than the MCU on the board is still active and continues to consume power. I have tested this mode and haven’t got down from 50mA consumption; it’s the minimum number one can get in this mode. Deep Sleep Mode Deep sleep mode helps an Arduino consume a lot less power than sleep mode. It puts the MCU in deep sleep and everything except the RTC peripheral is stopped. The CPU can be woken up using the RTC or any interrupt in code. Current drawn by a Pro Mini in deep sleep can drop from 25mA to 0.57mA. Slowing Down Arduino Clock Speed The clock speed in your Arduino board determines how many operations it can perform per second. Most Arduino boards run at 16MHz of clock speed. Reducing this to 8MHz can drop the current needed from 12mA to 8.5mA. In the long run, it can cut off much of the power consumption and extend battery life. So, when you don’t need to execute a large number of instructions in a short amount of time, it’s meaningful to reduce your clock speed if you want to save power and also perform some operations. However, this method is not very convenient in most cases and if you can put your board in deep sleep, this method is far more inefficient. Note: Changing clock speed can cause boot loader issues and your Arduino may get damaged. Arduino Clock Speed Code #include <avr/power.h> void setup() { if(F_CPU == 8000000) clock_prescale_set(clock_div_2); if(F_CPU == 4000000) clock_prescale_set(clock_div_4); if(F_CPU == 2000000) clock_prescale_set(clock_div_8); if(F_CPU == 1000000) clock_prescale_set(clock_div_16); } Replacing or Neglecting Power Consuming Components The on-board voltage regulator limits the input voltage to the DC input jack. The regulator is not very efficient and around 58% of the input energy is lost in the form of heat or used for internal supply. It is better to replace this component with more efficient DC-DC step down converters. Some DC-DC step converters or buck converters can be as efficient as 92%. Arduino Uno uses a small linear voltage regulator in a TO223 SMD package. A Traco TSRN1 chip is a great option for the package available on Arduino Uno. Powering a 5V regulated voltage via 7805 IC externally is a far more efficient way. It's a better option to remove the on-board regulator for highly reduced power consumption. Without a voltage regulator, around 2.7mA of current is shaved off. The power LED is ON all the time to indicate that the board is getting enough power. Removing the power LED can shave 2.85mA of current in normal mode. In sleep mode, without the LED, the power consumption of Arduino UNO is just 30.8uA. Lowering the Voltage Supply to an Arduino One of the very easy ways to reduce the power consumption of the Arduino board is to lower the supply voltage. Arduinos can work at a low voltage of 3.3V and by dropping the supply voltage from 5V to 3.3V, current drawn drops from 4mA to less than 1mA. At 3.3V, the recommended maximum frequency is around 13MHz according to the ATmega 328’s datasheet. So, lowering voltage too much without reducing clock speed makes the microcontroller behave strangely. A clock speed of 8MHz is the best option here. How to Make Your Own Arduino If making these changes to your Arduino or working with SMD components doesn't suit you or you fear to damage the board then making your own Arduino could be the best option. No power-hungry components and just the MCU to perform a task is what our main goal is here. The circuit is built around an ATmega IC. You can use ATmega 8/328 or any blank programmable microcontroller for this, along with a crystal and a reset button. You can add a 7805 voltage regulator for your convenience. Here's how I use this circuit: - Prepare the circuit on a general-purpose board or breadboard, but use the 40 pin IC socket for the IC. - Upload the code you require on the Arduino board. - Remove the IC from the Arduino and attach it in your circuit and you’re good to go! This way is easy and you don’t need any external boot-loader for uploading tasks. So Many Power Consumption Reduction Options! To summarize what we have discussed so far, the power consumption of an Arduino can be reduced by the following methods: - Using sleep mode and deep sleep mode - Reducing the clock speed - Replacing or removing unneeded components - Lowering the voltage supply to the board - Making your own Arduino Among these methods, some of them work like magic and some are for specific situations. To further reduce the power consumption of your Arduino-based projects, turn off external devices like SD cards with the help of a MOSFET when not in use. Also, don't use unnecessary backlit or indicating displays!
https://maker.pro/arduino/tutorial/how-to-reduce-arduino-power-consumption
CC-MAIN-2020-29
refinedweb
1,040
63.09
Uncyclopedia talk:Departure of Fun From Uncyclopedia, the content-free encyclopedia edit Hmm... Just thinking off the top of my head, a 'heads or tails' game based on the random coin flip would be good, as would something relating to the random chessboard. --Hindleyite Talk 15:11, 6 May 2006 (UTC) - Those sound good. Should games be created with the Game: prefix or should they be made as subpages of the Departure of Fun? • Spang • ☃ • talk • 15:13, 6 May 2006 (UTC) - Hmm. Game:Departure of Fun/Blah, maybe? --User:Nintendorulez 17:50, 6 May 2006 (UTC) There's a real chessboard template as well. Instructions —rc (t) 17:52, 6 May 2006 (UTC) edit Ideas We need userboxes for members a la Wikipedia [1]. --Hindleyite Talk 15:32, 9 May 2006 (UTC) - Also take a look at Wikipedia's Userpage Competition. [2] It may be something worth considering. -:58, 9 May 2006 (UTC) Like this? {{User DoF}} The colours could be changed to be more happy if that would be better. • Spang • ☃ • talk • 17:23, 12 May 2006 (UTC) - Ha ha, perfect. -:05, 12 May 2006 (UTC) edit Search & Destroy Can we have some sort of safeguard for being banned in there? Maybe making the summary say "Don't blame me!" to ensure that it's someone playing that game, prehaps? --Kalir, Savant of Utter Foolishness! (yell at me) 16:03, 10 May 2006 (UTC) - I think anyone dumb enough to play it for real should just get the ban. ^_^ --User:Nintendorulez 12:50, 12 May 2006 (UTC) - I "almost" removed all instance of the word paper in some article on Armenia. I chickened out and got mauled by savage Wikipedians for another reason. Personally, I would've taken the ban. --Kalir, Savant of Utter Foolishness! (yell at me) 14:57, 12 May 2006 (UTC) - My thoughts: Search and Destroy is named that because anyone stupid enough to play it will be hunted down and banned by the admins. In other words, it's named after what happens to the players. :D —Hinoa KUN (talk) 19:21, 13 May 2006 (UTC) - Well, that about wraps it up. Nobody is supposed to actually play it. --User:Nintendorulez 19:33, 13 May 2006 (UTC) edit Help me. I'm not exactly the best at wiki formatting, so can someone help make this table start to remotely resemble a bingo card? And if anyone can come up with a pretty little graphic for the free space (Perhaps a watermark of Wilde's head with text on top), that'd be nice too. --User:Nintendorulez 19:13, 13 May 2006 (UTC) - Past what's already there, I think the best thing to do is add so many options that repeat is highly improbable. (Or hand-create each bingo card, but no one wants to do that, even if they get randomly assigned. --Kalir, Savant of Utter Foolishness! (yell at me) 04:30, 15 May 2006 (UTC) - Yeah, Splaka already fancied it up, it seems. It looks great now. And yeah, I'm trying to come up with tons of options. --User:Nintendorulez 15:44, 15 May 2006 (UTC) edit Idea for a Contest How about we make a contest for who can design the best specialized Grue page, using the Grues found in Abyss? --Emmzee (flame me here) - Gure? --User:Nintendorulez 18:55, 1 June 2006 (UTC) edit How do i join? Question right there. How do i become a member of the department of fun?--Naughty Budgie 10:35, 13 April 2007 (UTC) - There's a very rigorous test required, outlined below: - Press the edit button above the "Members section" - Type Three Tildes (often refered to as the "Triple T" section) - Press "Save Page" - Hope this helps. :) -AtionSong 21:41, 13 April 2007 (UTC) - Really? That simple? ...I wish i'd known that earlier. --Naughty Budgie 23:10, 14 April 2007 (UTC) edit Trivial Pursuit? How about a trivial pursuit game where we use Uncyclopedia facts? --Naughty Budgie 00:02, 28 April 2007 (UTC) - If you have it planned out, go ahead and do it. -AtionSong 18:02, 28 April 2007 (UTC) - Hmm, i was hoping to get some help.--Naughty Budgie 07:19, 30 April 2007 (UTC) edit Text Input System I created a text input system for an online riddle, Password (or PAS-Sword). You can input 6 characters by it. Does it have any potential for here? (In that game, the first password is LV1 and the second is BLANK. There is no lv3.)--SunnyChow 15:00, 1 September 2007 (UTC) edit Becoming a member Is there any paticular criteria you need to become a member or do you just add your name to the list edit Uncyclopedia croquet We should probably get rid of that link, because it hasn't lead to anything for a while.--Naughty Budgie 21:05, 20 March 2008 (UTC) edit Changing games and DOF Hey. With the recent discussion around the games namespace I've noticed that there is a huge crossover between games and DoF. I'd like to minimise this crossover, and take whatever is DoF from games, and whatever is games from DoF. Given that some users would like to keep DoF alive I'd just like to say this here before I make any changes to either of them, and wait for objections. Any thoughts? User:PuppyOnTheRadio/deb Thursday, 00:49, Mar 18 2010 UTC
http://uncyclopedia.wikia.com/wiki/Uncyclopedia_talk:Departure_of_Fun?oldid=5051000
CC-MAIN-2015-48
refinedweb
907
82.04
GridLayout, ParentChange and ParentAnimation issue Hello, I want a cell of a GridLayout to be zoomed in and out. The zoom process should be animated. Here's my code so far: import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.0 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("ZoomGrid Test") Item { id: window anchors.fill: parent GridLayout { id: grid anchors.fill: parent columnSpacing: 0 rowSpacing: 0 columns: 3 rows: 3 Repeater { model: parent.columns * parent.rows Rectangle { id: rectangle Layout.fillWidth: true Layout.fillHeight: true Layout.preferredWidth: 50 Layout.preferredHeight: 50 Layout.column: model.index % grid.columns Layout.row: model.index / grid.columns color: Qt.darker("lightblue", 1 + model.index * .2) states: State { name: "detached" ParentChange { target: rectangle parent: window x: 0 y: 0 width: grid.width height: grid.height } } transitions: Transition { ParentAnimation { NumberAnimation { properties: "x,y,width,height" duration: 100 } } } MouseArea { anchors.fill: parent onClicked: { rectangle.state = rectangle.state !== "detached" ? "detached" : "" } } } } } } } The issue I have is when zooming back out. It seems the ParentChange gets applied first (put he rectangle back into the GridLayout) and then the ParentAnimation (handling the x,y,width and height changes) gets applied. That means the rectangles at the right hand side and the ones below cover parts of the (still zooming) rectangle which is still larger then the cell. Is there a way to prevent the rectangle from beeing covered? Thanks in advance!
https://forum.qt.io/topic/74993/gridlayout-parentchange-and-parentanimation-issue
CC-MAIN-2017-34
refinedweb
236
54.49
Important: Please read the Qt Code of Conduct - QML COMPONENT IMAGE Hi this is vishal. Above image is the one which i am working on. When you guys see the image you can see a red circle on the qml component. My question to you guys is that can we put image on top of that qml component or not. If we can, can you guys please provide me the code or technique to do so. Thanks.. - A Former User last edited by @vishalreddy can you guys see the image now ? - A Former User last edited by @vishalreddy Yes. Sorry for the inconvenience. @Wieland ok, if anyone know the solution of the problem please provide me. Thanks @vishalreddy said in QML COMPONENT IMAGE: My question to you guys is that can we put image on top of that qml component or not. Yes If we can, can you guys please provide me the code or technique to do so I never used designer, could you show your code? import QtQuick 2.4 import QtQuick.Extras 1.4 import QtQuick.Controls.Styles 1.4 Rectangle { property string vishal: "unit" property int max :100 property int min: 0 property int gaugevalue: 0 width: 400 height: 400 color: "#020202" gradient: Gradient { GradientStop { position: 0 color: "#020202" } GradientStop { position: 1 color: "#000000" } } CircularGauge { id: circularGauge x: 17 y: 54 width:328 height:308 value: gaugevalue maximumValue: max minimumValue: min Text { id: text1 anchors.bottom: parent.bottom anchors.bottomMargin: 52 x:117 y: 225 width: 46 height: 26 color: "#f4f2f2" text: qsTr(vishal) font.pixelSize: 12 } } } Just before Text {put something like: Image { id: myImage source: "MyImage.png" anchors.fill: parent } Hi, thanks for the reply. I have provided the image. So, please go through the image and please help me with the problem. Thanks. oh, you mean you want it to appear in the designer icon? Sorry I misunderstood. As mentioned I never used designer so I'm not qualified to answer that question. Apologies @VRonin ok, Thanks. Do we have a code for the image to appear on the designer icon? I have tried various ways using the designer but its not working. If you have a sample code can you please provide me.
https://forum.qt.io/topic/77733/qml-component-image
CC-MAIN-2021-31
refinedweb
371
75.1
By David Medawar (Intel), Added! I wanted to share this with you because after much searching, I couldn't find a trivial solution for this. Given that it took some effort, I asked myself: why not share my solution? To begin, let's use the following FrameworkElement (viewable) components: - Scrollviewer. This will allow us to build a list that we can scroll through by using a finger - StackPanel. Within each list, we will add "children" to the panel, each of which representing a year, day, or month. - TextBlock. We will display the children via text blocks. Robust design is important, and so we will use Windows.Globalization.Calendar to build the years, months, and days. Let's begin! Start with the XAML designer. I created three stack panels, for months, days, and years, through the XAML designer. I gave these a border and gradient background. Here is what it looks like along with a small snippet of the XAML code: <ScrollViewer x: <ScrollViewer.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black"/> <GradientStop Color="#FF1E5FD1" Offset="1"/> </LinearGradientBrush> </ScrollViewer.Background> <StackPanel x: <StackPanel Height="282"/> </StackPanel> </ScrollViewer> Figure 1: Preview of Calendar Image and Associated XAML Code** For the sake of robustness, rather than hard-code in the number of months, years, etc, I decided to retrieve this programmatically; this is why I don't define the text blocks in XAML above. Notice the use of the Tapped keyword above: we will be handling touch events. Keep reading on. On the C# code-behind, I created some configurable parameters at the top of the .cs file: //font size used for Calendar items const int FONT_SIZE = 24; //increase size of selected item const int DELTA_SIZE = 16; //vertical padding between list items; const int PADDING = 12; //the number of months int MONTH_COUNT; //maximum number of days in a month int MAX_DAYS; //bound the number of calendar years int MIN_YEAR = 1911; int MAX_YEAR = 2012; int NUM_YEARS; Figure 2: Some Configurable Parameters*** There is nothing really novel here; I just wanted to organize my settings to make playing around with the view more easily. I did however want to strictly limit the number of years in my case to the set [1911, 2012]. Next, we need to actually retrieve the calendar information. Microsoft has done a great job providing a Windows.Globalization framework with various calendars to support all the different cultures of the world. Feel free to read more about them here: There are two ways to handle the names of the months; either you can just create an array, or enumerate through the calendar object months (integers), and for each, retrieve the equivalent String name. I will do the former here. using Windows.Globalization; … Windows.Globalization.Calendar date_picker; … String[] month_list = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; TextBlock[] month_text_list; TextBlock[] day_text_list; TextBlock[] year_text_list; Figure 3: Enumerating the Months** Now, while I did hardcode in the month names, I will now show you how more robustly, you can use enumeration to determine the maximum number of days in any given month (for the Calendar in the US, we know this should be 31). //use the default calendar to assign counts MONTH_COUNT = date_picker.NumberOfMonthsInThisYear; //enumerate through month list for this calendar to //determine max number of days possible for a month //also, remember which month we currently are at int current_month = date_picker.Month; for (int i = date_picker.FirstMonthInThisYear; i <= MONTH_COUNT; i++) { date_picker.Month = i; //change the current month if (date_picker.NumberOfDaysInThisMonth > MAX_DAYS) MAX_DAYS = date_picker.NumberOfDaysInThisMonth; } date_picker.Month = current_month; Figure 4: How Many Days are Possible?** OK, so we now have a count for years, months, and days. This is where we will then dynamically add individual text block children to the stack panels, with each child representing a selectable item for the user. I won't show every case here, but will now cover how to do it for the months: month_text_list = new TextBlock[MONTH_COUNT]; stackpanel_month = new StackPanel(); for (int i = 0; i < MONTH_COUNT; i++) { month_text_list[i] = new TextBlock(); month_text_list[i].FontSize = FONT_SIZE; month_text_list[i].Padding = new Thickness(PADDING); month_text_list[i].Text = month_list[i]; stackpanel_month.Children.Add(month_text_list[i]); } scrollviewer_month.Content = stackpanel_month; Figure 5: Adding the Months to the Stack Panel** So, for each month, I give it a name from our array, give it padding so that there is adequate vertical spacing between all months, override the default font size, and create the child. Finally, I set the scroll viewer (what we made in XAML) content to be the stack panel which is an aggregate of text block children! One last step: how do we handle selections? Recall that in XAML, we used the Tapped keyword. Let's peek at the event handler here: SolidColorBrush select_brush, deselect_brush; … select_brush = new SolidColorBrush(); deselect_brush = new SolidColorBrush(); select_brush.Color = Windows.UI.Colors.Yellow; deselect_brush.Color = Windows.UI.Colors.White; … //called when the list of months is tapped private void month_changed(object sender, TappedRoutedEventArgs e) { //highlight selection if selected for (int i = 0; i < MONTH_COUNT; i++) { month_text_list[i].Foreground = deselect_brush; month_text_list[i].FontSize = FONT_SIZE; if (month_text_list[i] == e.OriginalSource) { month_text_list[i].FontSize += DELTA_SIZE; month_text_list[i].Foreground = select_brush; } } } Figure 6: Which Month was Selected?** The event argument identifies which month entry (text block) was tapped. So, we enumerate through the month list to find the match, change the text color as visual feedback to the user, and enlarge the font size to make it stand out. After user selection, it's quite easy to write the selected data back to the calendar object's month/day/year members (simple one-liner). When I finished creating the calendar, it looked like this: There you have it! Now, go have fun! **This sample source code includes XAML code automatically generated in Visual Studio 2012 IDE and is released under the Intel OBL Sample Source Code License (MS-LPL Compatible) *** This sample source code is released under the Microsoft Limited Public
https://software.intel.com/es-es/node/347823
CC-MAIN-2017-04
refinedweb
988
54.93
By Chris Moyer, AWS Community Developer When I first dove into cloud computing, I searched all over the Internet for a feasible solution to my problems using existing softwareall to no avail. Django seemed to be the closest match, but it didn't support using Amazon SimpleDB as a storage engine. I looked at making my own back end for Django but again was halted because of the unique relation-less nature of Amazon SimpleDB. It also seemed like Django, Pylons, and every other Python-based Web application framework out there was simply too complicated for my simple requirements. So, I decided to develop a new framework that covered all of my needs: Meet Marajo. Introducing Marajo Marajo started off as a clone of the Google App Engine (GAE) framework to be run in Amazon Elastic Compute Cloud (Amazon EC2). I then realized that there was a lot of functionality I could implement to make things easier. Eventually, Marajo evolved into a quick framework for spinning up new Web services. Marajo today is similar to the GAE framework but uses power that can only be achieved with Amazon EC2 (and it's much easier to use). At its core, Marajo uses the familiar modelviewcontroller (MVC) pattern. All three of these sections are run from the same server, making it a slower and less efficient system than is possible, but it also makes it quite quick to develop on. It uses the same template style language as Django and GAE, known as Jinja, which makes transitioning from Django or GAE to Marajo quick and easy. Figure 1. Marajo overview As you can see from Figure 1, Marajo handles the Application, Presentation, and Database layers for you. This allows you simply to focus on code and develop your interface quickly without worrying about Amazon Web Services (AWS)specific details. Initializing Your Environment When you first start, you'll want to launch a new Ubuntu image from. Because I'm launching in us-east-1a, I've chosen to use ami-bb709dd2. I assume that you've already followed the steps to set up a key-pair and your boto configuration. To start your Amazon Machine Image (AMI), use the launch_instance command that boto provides: $ launch_instance -a ami-bb709dd2 This command then asks you a series of questions about where exactly you want to put the instance, what security group it should go in, and the key-pair you want to use. You also need to make sure that the security group you choose is open on port 80 to the world. Next, log in to the newly created instance using Secure Shell (SSH) and your key-pair: $ ssh -i /path/to/your/key.pem ubuntu@ec2-host-name Installing Your Software Start by installing boto from Subversion. First, check out a copy of boto locally into your local directory: $ apt-get install python-setuptools $ cd /usr/local/ $ svn co boto $ cd boto $ python setup.py develop Then, set it up as a pyAMI instance by creating a special /etc/rc.local file and some special scripts in your / root directory: #!/bin/sh -e # File: /etc/rc.local # execute firstboot.sh only once # Note that /mnt only stays with us # until we're re-bundled, so this is a # safe place to store this flag if [ ! -e /mnt/firstboot_done ]; then if [ -e /root/firstboot.sh ]; then /root/firstboot.sh fi touch /mnt/firstboot_done fi # We run startup reguardles of if we've been # booted before or not, this lets us # schedule things to be only run on re-boot if [ -e /root/startup.sh ]; then /root/startup.sh fi exit 0 Doing so ensures that the firstboot.sh script is run the first time this instance is run. You'll use this script to make sure the ssh key is regenerated every time a new instance is launched. Because you're not making this image public, it isn't a big deal; but do it anyway, because you should always be concerned about security. #!/bin/bash # File: /root/firstboot.sh # Regenerate the ssh host key rm -f /etc/ssh/ssh_host_*_key* ssh-keygen -f /etc/ssh/ssh_host_rsa_key -t rsa -N '' | logger -s -t "ec2" ssh-keygen -f /etc/ssh/ssh_host_dsa_key -t dsa -N '' | logger -s -t "ec2" # This allows user to get host keys securely through console log echo | logger -s -t "ec2" echo | logger -s -t "ec2" echo "#############################################################" \ | logger -s -t "ec2" echo "-----BEGIN SSH HOST KEY FINGERPRINTS-----" | logger -s -t "ec2" ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub | logger -s -t "ec2" ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub | logger -s -t "ec2" echo "-----END SSH HOST KEY FINGERPRINTS-----" | logger -s -t "ec2" echo "#############################################################" \ | logger -s -t "ec2" update-motd depmod -a /usr/bin/python /usr/local/boto/boto /pyami/bootstrap.py exit 0 Finally, set up a script to automatically update your system on reboot. You do this in /root/startup.sh: #!/bin/bash # File: /root/startup.sh # Things to run just after the boot process is finished # On reboot or first boot # # Update local packages apt-get -y update apt-get -y upgrade # Update boto, marajo, and botoweb cd /usr/local/boto;svn up cd /usr/local/marajo;svn up cd /usr/local/botoweb;hg pull -u /usr/bin/python /usr/local/boto/boto/pyami/startup.py exit 0 Marajo mostly installs itself, but unfortunately, Jinja2 has some features in development that you need. So, install Jinja before installing Marajo: $ easy_install -U jinja2==dev Next, download Marajo from Subversion and install it: $ svn co marajo $ cd marajo $ python setup.py install Installing Apache When you're logged in, install Apache 2 and configure it to work with your system. As with most systems, you'll want to use apt-get and install it normally: $ apt-get install apache2 You also want to configure and install mod_proxy and mod_proxy_balancer: $ apt-get install mod_proxy mod_proxy_balancer $ a2enmod proxy_balancer Next, configure Apache to use your blog application as its proxy, and point the directory to your Web root. Modify the default vhost file located at /etc/apache2/sites-available/default to the following: NameVirtualHost *:80 <VirtualHost *:80> ProxyRequests Off <Proxy *> AddDefaultCharset off Order deny,allow Allow from all </Proxy> <Proxy balancer://blog> BalancerMember BalancerMember BalancerMember </Proxy> <Directory "/usr/local/blog/www"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> DocumentRoot /usr/local/blog/www ProxyPass /api/ balancer://blog/ ProxyPassReverse /api/ balancer://blog/ ErrorLog /var/log/apache2/error.log </VirtualHost> Initializing Your Application Marajo is set up to use four separate directories for each part of an application. Start by creating a directory called /usr/local/blog. In that directory, you create the four directories that house each of the major parts of your application: handlers. This directory houses the individual Web Server Gateway Interface (WSGI) handlers. These handlers deal with any special logic that needs to be overridden. For the most part, every handler will extend marajo.appengine.handlers.db.DBHandler. resources. This directory houses all of your persistent data storage. For your blog application, it stores your Commentobjects. Marajo already handles the Userobject for you, which is located at marajo.appengine.api.users.User. Also, a user handler is available to you at marajo.appengine.handlers.user_handler.UserHandlerthat ensures that you only let users modify their own object, not their authorization group. static. This directory holds all of your static HTML, JavaScript, Cascading Style Sheet (CSS), and other media. templates. This directory holds all of your Jinja2 templates for how to view the data. The template mapper also allows you to create sub-directories that specify the content type requested. Figure 2 indicates how the mapper handles these situations. Figure 2. Template Mapper Creating Your Resources As with any Gui-Over-Database application, you start by defining your data structure. Figure 3 shows the artificial schema you'll be creating. Because Amazon SimpleDB is schema-less, you use the boto.sdb.db module to restrict and persist your objects. Figure 3. DB schema Now, let's take a look at how you go about creating your Comment objects: # File: resources/post.py from boto.sdb.db.model import Model from boto.sdb.db.property import * from marajo.appengine.api.users import User class Post(Model): """A Blog Post""" title = StringProperty(verbose_name="Title") tags = ListProperty(str, verbose_name="Tags") content = BlobProperty(verbose_name="Content") created_at = DateTimeProperty(auto_now_add=True) modified_at = DateTimeProperty(auto_now=True) created_by = ReferenceProperty(User, collection_name='created_posts') modified_by = ReferenceProperty(User, collection_name='modified_posts') The first step is to extend boto's Model class. This base class automatically handles much of the conversions for you, so you don't have to worry about converting properties that are lexicographically sortable for use within Amazon Simple DB. Next, use the related property to set up some properties for your object. You use several different properties to store each of your different property types: StringProperty. Stores a string up to 1024 characters ListProperty. Stores multiple strings (again, up to 1024 characters) BlobProperty. Uses Amazon Simple Storage Service (Amazon S3) to store the actual contents of the property, so it's limitted to 5 GB DateTimeProperty. Stores a Python datetimeobject; set auto_now_addto automatically set it to utcnow()on creation and auto_nowto make it automatically set anytime it's updated ReferenceProperty. Stores a reference to another object; in this case, you're referencing the Userobject, and the collection_nameattribute adds a reverse reference link automatically on the Userobject Next, create a comment object, which allows you to add a comment to your post: # File: resources/comment.py from boto.sdb.db.model import Model from boto.sdb.db.property import * from resources.post import Post class Comment(Model): """A simple Comment object""" post = ReferenceProperty(Post, collection_name='comments') # This is just a string since we # don't require them to log in to post posted_by = StringProperty() content = BlobProperty() created_at = DateTimeProperty(auto_now_add=True) Again, you're using the same type of process. Now, you have the two objects required for your application. Marajo already handles the User object for you, so you don't need to make that. Creating Your Handlers When working with Marajo, you rarely need to create your own handlers. A simple create, read, update, delete (CRUD) interface is automatically implemented for you, so it's easy just to configure and set everything up. You'll create one base handler to show the home template: # File: handlers/__init__.py from marajo.appengine.handlers import RequestHandler class MainPage(RequestHandler): """Simply shows the main page""" def get(self): self.display("index.tmpl") In addition, the basic DBHandler doesn't allow non-users to create anything, so extend it and override the post method: # File: handlers/comments.py from marajo.appengine.handlers.db import DBHandler from marajo.exceptions import Unauthorized class CommentHandler(DBHandler): """Override the POST to allow any user to do a create""" def post(self): """Save or update object to the DB""" obj = self.read() if obj: if not self.user: raise Unauthorized() obj = self.update(obj, self.request.POST) else: obj = self.create(self.request.POST) return self.redirect("posts/%s" % obj.post.id) Configuring Your Application Configuration for a basic CRUD application is quite simple. The entire app.yaml file, which resides in your root folder, is written using YAML. The first section just defines a few simple variables that are accessible throughout your templates and handlers: application: blog auth_db: marajo_users session_db: marajo_sessions version: 1 Next, configure the handlers sub-section of the configuration. This sub-section maps the URL patterns to their respective handlers. The mapper allows you to specify either a handler, static_dir, or static_file directive; everything else is passed in to the handler as an argument. This is how things like the DBHandler can act to serve up any object depending on what you specify as the db_class argument. handlers: - url: / handler: handlers.MainPage - url: /javascript static_dir: static/javascript - url: /images static_dir: static/images - url: /style static_dir: static/style - url: /posts(.*) handler: marajo.appengine.handlers.db.DBHandler edit_template: viewPost.tmpl db_class: resources.post.Post - url: /comments(.*) handler: handlers.CommentHandler db_class: resources.comment.Comment Creating Your Templates You only need a few basic templates to get started. Start with your menu template, which you'll add to the top of each page. This code uses the typical Jinja syntax to insert variables at specific places. Note that you have access to the current user object if the user is logged in; you can use this object to determine whether you need to provide the user with a login or logout option. <!-- menu.tmpl --> <div id="topmenu"> <ul class="left"> <li><a href="/">Home</a></li> <li><a href="/posts">All Posts</a></li> </ul> <ul class="right"> {%if user%} <li><a href="{{logout_url}}">Logout {{user.username}}</a></li> {%else%} <li><a href="{{login_url}}">Login</a></li> {%endif%} </ul> <br style="clear: both;"/> </div> <!-- /menu.tmpl --> It's generally a good idea to add the HTML comments to each template so that when you view the generated source, you can figure out where a specific element is coming from. Templates can be quite tricky to debug if you don't have some sort of reference to where each element was inserted. Next, look at your index page. This one is relatively simple, but feel free to expand on it as needed. {% extends 'base.tmpl' %} {% block content %} <h1>Hello World!</h1> {% endblock %} This template shows the basic concept of making a new regular page for a handler to display. Notice that you always start by extending base.tmpl so that you don't need to re-type all the HTML and menu code that's duplicated on every page. This base template defines blocks, which you can then override. Here, you override the content block to add your Hello World comment. Running Your Application At this point, you have a fully functioning application. You can simply navigate to your application root directory and run marajo_server.py. You can then navigate to and view your entire application. You should see a login button in the upper right of the window. Marajo uses sessions, so the login happens via sessions, not basic HTTP authentication. You'll have to log in before you'll be able to post. Of course, this is just a basic setup for a blog. Now, let's look into customizing your templates. Creating Custom Templates You're now ready to start building some custom templates for your application. There are three basic templates that you can override for the database handler. The List Template The list template is the default template that you see when you go to the URL without any arguments. This template is passed in a few arguments, the most notable of which is objects, which is an iterable object that allows you to query the objects that should be listed. Take a look at the list template for your post handler: {% extends "base.tmpl" %} {% block head %} <link rel="stylesheet" href="{{static_file('/style/blog.css')}}" type='text/css'/> {% endblock %} {% block content %} <!-- listPosts.tmpl --> <div id="posts" class="box"> {% for obj in objects %} <div class="post"> <h3> <a href="{{action_href}}/{{obj.id}}"> {{obj.title}}</a> <small>{{obj.created_at}}</small> </h3> <hr/> <div class="attr content">{{obj.content}}</div> <ul> {% for tag in obj.tags %} <li>{{tag}}</li> {% endfor %} </ul> <br class="clear"/> <br class="clear"/> <br class="clear"/> </div> {% endfor %} </div> {% if user %} <br class="clear"/> <div class="box"> <form method="POST" class="post"> <h4>Title</h4> <input type="text" name="title" style="width: 300px"/> <hr/> <h4>Content</h4> <textarea name="content" rows="20" style="width: 600px;"> </textarea> <br class="clear"/> <hr/> <h4>Tags</h4> <textarea name="tags" rows="10" style="width: 600px;"> </textarea> <br class="clear"/> <input type="submit" value="Create Post"/> </form> </div> {% endif %} <!-- /listPosts.tmpl --> {% endblock %} Here, you introduce a new block called head, which allows you to insert tags into the HTML <head> tag. You've used this to link to a static file using the static_file function passed into your template. Using this function instead of just passing in the link directly allows you to serve these static files out of CloudFront or Amazon S3 if you configure that into your app.yaml file. The next interesting block of code starts with the {% if user %} tag on line 32. This section only appears if the user is logged in, providing him or her with a mechanism to add an additional post to the blog. As tags are multi-value, Marajo allows you to separate the strings by newlines, so you just use a <textarea> tag. You also don't have to add an action URL to your form, because you want to post directly back to the page you're already on. You next have to modify tour posts handler configuration in app.yaml to add the list_template definition. Your new handler section should look like this: - url: /posts(.*) handler: marajo.appengine.handlers.db.DBHandler db_class: resources.post.Post list_template: listPosts.tmpl The Edit Template The edit template is called every time the user goes to an object-specific URL. You can also think of this template as a view template: If the user is logged in, you can provide him or her with the form so the user can edit the post; if the user isn't logged in, you can simply display the post and allow him or her to add a comment. {% extends "base.tmpl" %} {% block head %} <link rel="stylesheet" href="{{static_file('/style/blog.css')}}" type='text/css' /> {% endblock %} {% block content %} <!-- viewPost.tmpl --> {% if user %} {% include "editPost.tmpl" %} {% else %} {% include "displayPost.tmpl" %} {% endif %} <div id="comments" class="box"> {% for comment in obj.comments %} <div class="comment"> <h4>{{comment.posted_by}}</h4> <hr/> <div class="attr content"> {{comment.content}} </div> <br class="clear"/> </div> {% endfor %} </div> {% if not user %} <br class="clear"/> <br class="clear"/> <div class="box"> <form method="POST" action="/comments"> <input type="hidden" name="post" value="{{obj.id}}"/> <label for="posted_by">Your Name: </label> <input type="text" style="width: 210px;" name="posted_by"/> <br/><br/> <textarea name="content" cols="40" rows="20"> </textarea> <br/> <center> <input type="submit" value="Add Comment"/> </center> </form> </div> {% endif %} <!-- /viewPost.tmpl --> {% endblock %} On line 11, notice that you introduce a conditional statement {% if user %}, which signifies that the user is logged in. You could also validate that the user is of a specific authorization group by using {% if user and user.has_auth_group("auth-group-name") %}, but for now, assume that you're the only user. The next directive indicates that you'll include a separate template within the same directory you're currently in called editPost.tmpl. This entire section essentially means that if the user is logged in, you'll show him or her one template; otherwise, you'll show the user another. The next bit of code simply shows how you can iterate over the comments for your given post using the {% for comment in obj.comments %} block. It's important to note that as soon as you call this block of code, it triggers the query against Amazon SimpleDB, so expect that to take a little longer to render. You can also add filters or limits to this query by appending them just like you did in the handler code. Because you don't want to see any spam, change that query: {% for comment in obj.comments.filter("spam_chance <", 50) %} Now, you'll only show comments with a spam chance of less than 50%. Because filter returns the query itself, you can also chain filter, order, and fetch together into one line. Also, add a limit to only show the last 10 comments ordered by date created in descending order: {% for comment in obj.comments.filter("spam_chance <", 50).order("-created_at").fetch(10) %} The next chunk of code uses logic to show a comment box only if the user isn't logged in. You're assuming that if you're logged in to the site, you're not adding comments to your own posts, so this helps clean up some things that you don't want to see. You're adding another box with a custom form in it that performs a POST operation on post option to the current post's ID so the comment is automatically attached to this post, and you let the user fill in his or her name and a brief comment. When the user clicks Submit, he or she hits the comment handler that you previously set up, which re-direct the user to this post, showing the comment the user just added. The displayPost Template Next, take a look at the displayPost template, which shows when the user isn't logged in: <!-- displayPost.tmpl --> <div id="posts" class="box"> <div class="post"> <h3> {{obj.title}} <small>{{obj.created_at}}</small> </h3> <hr/> <div class="attr content">{{obj.content}}</div> <ul> {% for tag in obj.tags %} <li>{{tag}}</li> {% endfor %} </ul> <br class="clear"/> </div> </div> <!-- /displayPost.tmpl --> This template is similar to the comments section of the editPost template, where you simply show the details of the post in an HTML format. Now, take a look at the editPost template that will be shown only when the user is logged in. The only major changes you make here are to replace the simple display of the fields with their proper input types: <!-- editPost.tmpl --> <div id="posts" class="box"> <form method="POST" class="post"> <input type="text" name="title" value="{{obj.title}}" style="width: 300px"/> <small>{{obj.created_at}}</small> <hr/> <textarea name="content" rows="20" class="attr content"> {{obj.content}}</textarea> <br class="clear"/> <hr/> <h4>Tags</h4> <textarea name="tags" rows="10" style="width: 600px;"> {%- for tag in obj.tags -%} {{tag}} {% endfor -%} </textarea> <br class="clear"/> <input type="submit" value="Update Post"/> </form> </div> <!-- /editPost.tmpl --> Here, you use your form with a POST again, but you don't set the action URL, because you simply want to post to the current page. You've also set all the form's default values to the post's current values, and now you have a fully functional editing template for your user. Note that in the textarea for the tags, you use - inside the {% %} tags. These dashes state some formatting codes that allow you to remove the white space before or after the tag so you can still make the code readable but not have the tags show up spaced oddly. You don't strip out the white space before the {% endfor %} block, however, because you do need one newline after each tag. Finally, you modify your post handler once again to add this template: - url: /posts(.*) handler: marajo.appengine.handlers.db.DBHandler db_class: resources.post.Post list_template: listPosts.tmpl edit_template: viewPost.tmpl Setting Up Your Application to Start at Boot The last thing to do is modify your startup.sh script to automatically run your server whenever it's started. For purposes of this example, launch three copies of tour application server. Simply add the following three lines right before the exit 0 line: cd /usr/local/blog; marajo_server.py -p 8080 cd /usr/local/blog; marajo_server.py -p 8081 cd /usr/local/blog; marajo_server.py -p 8082 That's it! Your application is now set up to run on three ports, and your spam filter will start automatically in the background. Bundle Your Image Now, bundle the image using the simple bundle_image command that boto provides. This command is relatively verbose, so make sure to follow through the prompts. You'll need your public and private keys provided to you by Amazon when you first set up your account. You'll also need an Amazon S3 bucket to store the image on and a prefix to identify your image. Use of the bundle_image script is quite simple. Just make sure you run it from your local computer, not the instance you've just launched. % bundle_image --help Usage: bundle_image [options] instance-id [instance-id-2] Options: --version show program's version number and exit -h, --help show this help message and exit -b BUCKET, --bucket=BUCKET Destination Bucket -p PREFIX, --prefix=PREFIX AMI Prefix -k KEY_FILE, --key=KEY_FILE Private Key File -c CERT_FILE, --cert=CERT_FILE Public Certificate File -s SIZE, --size=SIZE AMI Size -i SSH_KEY, --ssh-key=SSH_KEY SSH Keyfile -u UNAME, --user-name=UNAME SSH Username -n NAME, --name=NAME Name of Image For a Ubuntu-based image, use the following command: % bundle_image -b \ ... -p <my_custom_identifier> \ ... -k /path/to/my/key.pem \ ... -c /path/to/my/cert.pem \ ... -s 10240 \ ... -i /path/to/my/ssh-key.pem \ ... -u ubuntu \ ... -n blog This process may take up to an hour to finish, so now is a good time to take a break from all this coding. When the processing is finished, you'll be provided with your new AMI ID, which you'll use to launch all your new instances. Make sure you launch at least one copy of the instance before you terminate your development instance, so you're sure everything worked. Creating the Proxy The last step is to create and set up your proxy system. You're using Elastic Load Balancer for this, so let's use the elbadmin tool, also provided by boto. % elbadmin -l 80,80,http create blog % elbadmin enable us-east-1a % elbadmin add blog <instance-id> You'll probably want to launch a few of these instances and add each one to the load balancer. Also, make sure you set up a CNAME to the address provided to you by the elbadmin script so that you can point your users to something more readable. Your final deployment configuration should look something like Figure 4. Figure 4. Marajo deployment Summary You should now be able to go directly to your proxy URL, click All Posts, and see something similar to Figure 5. Figure 5. The All Posts page Using Marajo is a great way to quickly bring up a new Web application without having to worry about doing a lot of coding. It provides you with sane defaults and the ability to override just about everything to create a custom system. You can find all of the code examples used in this article in the example directory for Marajo.
https://aws.amazon.com/articles/Python/3999
CC-MAIN-2017-09
refinedweb
4,370
54.93
The Twilio Python Helper Library The Twilio Python Helper Library makes it easy to interact with the Twilio API from your Python application. The most recent version of the library can be found on PyPi. The Twilio Python Helper Library supports Python applications written in Python 2.7 and above. If you are interested in migrating to the newer 6.x version of the Twilio Python Helper Library from the 5.x version, check out this guide. Install the Library The easiest way to install the library is from PyPi using pip, a package manager for Python. Simply run this in the terminal: pip install twilio If you get a pip: command not found error, you can also use easy_install. Run this in your terminal: easy_install twilio Manual Installation Or, you can download the source code (ZIP) for twilio-python, and then install the library by running: python setup.py install in the folder containing the twilio-python library. "Permission Denied" If the command line gives you a big long error message that says Permission Denied in the middle of it, try running the above commands with sudo (e.g. sudo pip install twilio). Test Your Installation Try sending yourself an SMS message. Save the code sample on this page to your computer with a text editor. Be sure to update the account_sid, auth_token, and from_ phone number with values from your Twilio account. The to phone number can be your own mobile phone. Save the file as send_sms.py. In the terminal, cd to the directory containing the file you just saved then run: python send_sms.py You should receive the text message on your phone. Using this Library Authenticate Client from twilio.rest import Client account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) Create a New Record from twilio.rest import Client account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) call = client.calls.create( to="+14155551212", from_="+15017250604", url="" ) print(call.sid) Get Existing Record from twilio.rest import TwilioRestClient account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = TwilioRestClient(account_sid, auth_token) call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868") print(call.to) Iterate Through Records from twilio.rest import Client account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) for sms in client.messages.list(): print(sms.to) More Documentation Once you're up and running with the Python helper library, you'll find code samples using the latest version in our REST API docs and in the documentation for every Twilio product. You can also find auto-generated library docs for the latest SDK here. Accessing the 5.x Version of the Helper Library Deprecation notice New functionality will only be added to the new library (Python Helper Library 6.x). The old library (5.x) is no longer supported: Twilio will not provide bug fixes and Support might ask you to upgrade before debugging issues. Learn how to migrate your existing application. The most recent version of the Python Helper Library is not API compatible with the previous 5.x version you may have used in previous Twilio applications. The older version will continue to work, and you will continue to find sample code for this version throughout our documentation. Should you need to install this version you can do so with the following command: pip install twilio==5.7.0 Getting Help We'd love to hear your feedback on the Twilio Python.
https://www.twilio.com/docs/libraries/python
CC-MAIN-2019-51
refinedweb
561
58.28
Created by Simon Monk Last updated on 2013-05-03 08:00:31 PM EDT com/using-an-ir-remote-with-a-raspberry-pi-mediacenter 12 Page 2 of 12 .adafruit.Guide Contents Guide Contents 2 Overview 3 Parts 4 Part 4 Qty 4 Hardware 6 LIRC 7 Configure and Test 9 Using Other Remotes © Adafruit Industries. Before tackling this project.Overview In this tutorial.it/c2S) to set up your Raspberry Pi as a media center. The IR receiver is attached to the GPIO connector on the Raspberry Pi. you need to follow this tutorial ( Page 3 of 12 . you will learn how to use an Infrared remote with a Raspberry Pi configured as a media center. © Adafruit Industries. Parts To build this project.adafruit. © Adafruit Industries Part Qty IR Sensor) and the following items. you will need everything from the Media Center setup tutorial ( Page 4 of 12 .com/products/389 1 Female to Female leads 1 IR Remote 1. © Adafruit Industries Page 5 of 12 . that will connect with three pins on the GPIO connector.3V not 5V when used with the Raspberry Pi.com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 6 of 12 . © Adafruit Industries. Make the connections as shown below. To do the connecting. But selecting adjacent wires that are still in a 'ribbon' will help keep things neat. Note that the IR sensor chip needs to be operated at 3. Note that you do not have to use the same colored jumper wires. we can use female to female jumper leads.adafruit. These make a good reliable connection as the IR sensor has unusually thick leads for an IC.Hardware The IR sensor has just three pins. To make sure that the IR hardware is correct. please see this tutorial.LIRC The interface between the hardware and the Raspberry Pi media centre is managed by a piece of software called LIRC (Linux Infrared Remote Control). So run the Rasbmc Settings program and make sure that the option Enable GPIO TSOP IR Receiver is disabled.adafruit. This is pre-installed on most recent Raspberry Pi distributions and is included in the Rasbmc distribution. so there is nothing to install. there is some setting up to do. you need to make sure that the IR remote feature is turned off. or you will not be able to use LIRC from the SSH. If you have not connected to a Raspberry Pi using SSH before. however. © Adafruit Industries. which is automatically enabled on this distribution. (. we can connect to the Raspberry Pi running Rasbmc using SSH. To be able to test the IR receiver without XBMC.it/cag) You can find the IP address of the Raspberry Pi using the XBMC System Info page.com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 7 of 12 . adafruit. Now connect to the Raspberry Pi using SSH and issue the commands shown below: Now hold the remote in front of the receiver and you should see a series of 'pulse' / 'space' messages appear each time you press a button. © Adafruit Industries. Congratualtions! The IR receiver is working.If you needed to change this you will need to reboot.com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 8 of 12 . conf bits 16 flags SPACE_ENC|CONST_LENGTH eps 30 aeps 100 header 8945 4421 one 594 1634 zero 594 519 ptrail 598 repeat 8949 2187 pre_data_bits 16 pre_data 0xFD gap 106959 toggle_bit_mask 0x0 begin codes KEY_VOLUMEDOWN 0x00FF KEY_PLAYPAUSE 0x807F KEY_VOLUMEUP 0x40BF KEY_SETUP 0x20DF KEY_UP 0xA05F KEY_STOP 0x609F KEY_LEFT 0x10EF © Adafruit Industries. we need to give LIRC a config file to tell it about the keys on the remote that we are using. of remote control: devices being controlled by this remote: begin remote name /home/pi/lircd.de> this config file was automatically generated using lirc-0..conf . before saving the file by clicking CTRL-x then Y. # # # # # # # # # # # # Please make this file available to others by sending it to <lirc@bartelmus.Configure and Test Now that we know that the hardware is okay. issue the command: nano lircd.conf model no.com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 9 of 12 .adafruit.0-pre1(default) on Thu Mar 14 14:21:25 2013 contributed by brand: /home/pi/lircd.. From the SSH session. and then paste the following text into it.9. change the GPIO Remote Profile as shown below: Restart XMBC and when it has rebooted.adafruit.com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 10 of 12 . At the same time. © Adafruit Industries. Now. you should see a small popup message in the bottom right corner like the one below. return to the Rasbmc Settings program and enable the option Enable GPIO TSOP IR Receiver.KEY_LEFT KEY_ENTER KEY_RIGHT KEY_KP0 KEY_DOWN KEY_BACK KEY_KP1 KEY_KP2 KEY_KP3 KEY_KP4 KEY_KP5 KEY_KP6 KEY_KP7 KEY_KP8 KEY_KP9 end codes 0x10EF 0x906F 0x50AF 0x30CF 0xB04F 0x708F 0x08F7 0x8877 0x48B7 0x28D7 0xA857 0x6897 0x18E7 0x9867 0x58A7 end remote This file should be saved in the home directory for the user pi. com/using-an-ir-remote-with-a-raspberry-pi-mediacenter Page 11 of 12 . © Adafruit Industries should now find that your IR remote control will work and that you no longer need the keyboard and mouse to control XMBC. This will tell you the allowed key names that you can use when prompted. Type the command 'irrecord -d /dev/lirc0 ~/lircd.Using Other Remotes I generated the config file for this remote using a utility that is part of LIRC called 'irrecord'.conf out of the way Type the command 'irrecord –list-namespace'.conf' Follow the instructions to the letter. If you have a different remote. © Adafruit Industries Last Updated: 2013-05-03 08:00:32 PM EDT Page 12 of 12 . It all seems a bit odd. but the program has to work out the timings and encodings used by the remote. The process is as follows: Turn the remote off on XMBC using Rasbmc as we did before using 'mode2'. then you can generate a config file for it using this tool. Rename the existing lircd.
https://www.scribd.com/document/251561083/Using-an-Ir-Remote-With-a-Raspberry-Pi-Media-Center
CC-MAIN-2019-13
refinedweb
1,027
67.76
Word count (Haskell) - Other implementations: Assembly Intel x86 Linux | C | C++ | Haskell | J | Lua | OCaml | Perl | Python, functional | Rexx An implementation of the UNIX wc tool, in Haskell.. This is a somewhat more complex implementation of wc than other sample Haskell implementations on the web. This added complexity stems from two things: - Adding command line options; - Avoiding loading an entire file into memory to count it (and instead reading the file line-by-line). [edit] Counting and printing The core of wc's functionality is to count various quantities, and print the results to the screen. This task is accomplished by the wc function, with the help of several supporting functions: <<counting and printing>>= wc countAndPrintFile countFile getCount printCountLine The wc function takes a group of option settings and a list of filenames, and for each file in the list prints the count totals specified by the options. <<wc>>= wc :: Opts -> [FilePath] -> IO () If the file list is empty, or contains only a "-", the input is assumed to arrive via stdin. We therefore simply get the entire contents of the stdin handle lazily using getContents, get the count totals for that, and then print the count. <<wc>>= wc opts [] = wc opts ["-"] wc opts ["-"] = do text <- getContents let count = getCount text printCountLine opts "" count If the file list contains only a single filename, we simply open and count that file, and print the resulting count totals. The situation when the file list has multiple elements is a little more complex. In this case, we need to both find and print the count for each file in the list, and accumulate a total count for all of the files. This is accomplished by folding the function countAndPrintFile across the file list. <<wc>>= wc opts [file] = do count <- countFile file printCountLine opts file count wc opts files = do totalcount <- foldM (countAndPrintFile opts) (0,0,0) files printCountLine opts "total" totalcount [edit] countAndPrintFile At each step of the fold operation countAndPrintFile takes a current total count and a filename, prints the results of counting the file, and returns a new total count (which serves as an input to the next step of the fold). <<countAndPrintFile>>= countAndPrintFile :: Opts -> WordCount -> FilePath -> IO WordCount countAndPrintFile opts total@(tls,tws,tcs) file = do count@(ls,ws,cs) <- countFile file printCountLine opts file count return (tls+ls,tws+ws,tcs+cs) The WordCount type is simply an alias for a tuple consisting of three integers representing the current line, word, and character counts for the corresponding file. <<WordCount>>= type WordCount = (Int, Int, Int) [edit] countFile The countFile function takes a filename as its argument, and returns the line, word, and character counts for that file. The actual counting operation is handled by getCount, while countFile handles getting the contents lazily of the file to be counted. <<countFile>>= countFile :: FilePath -> IO WordCount countFile file = do text <- readFile file return $ getCount text [edit] getCount The getCount function is the workhorse of the counting operation. It gets a string containing the entire contents of the file to be counted (lazily of course). It splits the file into lines and folds across all the lines, accumulating the counts. For each line, the line count is incremented by 1, and the word and characters counts are respectively increased by the numbers of words and characters in the line. The character count is further incremented by 1, to account for the fact that lines strips the newline character off of the lines. <<getCount>>= getCount :: String -> WordCount getCount = foldl' (\(c, w, l) x -> (c+length x+1, w+length (words x), l+1)) (0, 0, 0) . lines [edit] printCountLine The printCountLine function prints out the line, word, and character counts for the file f, in accordance with the option settings. <<printCountLine>>= printCountLine :: Opts -> FilePath -> WordCount -> IO () printCountLine opts f (ls,ws,cs) = putStrLn ("\t" ++ (if showLines opts then (show ls) ++ "\t" else "") ++ (if showWords opts then (show ws) ++ "\t" else "") ++ (if showChars opts then (show cs) ++ "\t" else "") ++ f) [edit] Option handling The handling of command line options makes use of the System.Console.GetOpt library. It uses an approach to process the options inspired by a Haskell mailing list post by Tomasz Zielonka (see References). We first define a new record datatype Opts, which contains three boolean fields representing the different options. <<options setup>>= data Opts = Opts { showLines, showWords, showChars :: Bool } We also define a GetOpts option description list. This defines both short (e.g. -l) and long (e.g. --line) command line flags for each supported option, a function which operates on the Opts datatype and is called when a particular flag is detected, and a usage message for each flag. <<options setup>>= options :: [OptDescr (Opts -> Opts)] options = [ Option ['l'] ["lines"] (NoArg (\o -> o {showLines = True})) "show line count" , Option ['w'] ["words"] (NoArg (\o -> o {showWords = True})) "show word count" , Option ['c'] ["chars"] (NoArg (\o -> o {showChars = True})) "show character count" ] Parsing of the command line flags makes use of the getOpt function, which returns either a tuple containing a list of options and a list of files, or an error. If an error is returned, we simple print a usage message to the screen. <<parseOpts>>= parseOpts :: [String] -> IO ([Opts -> Opts], [String]) parseOpts args = case getOpt RequireOrder options args of (opts,files,[]) -> return (opts,files) (_,_,errs) -> fail (concat errs ++ usageInfo header options) where header = "Usage: wc [OPTION...] [files...]" The tricky part of the option handling is the processing of the options. The getOpt function returns a list of option values, but we would prefer not to have to scan the list every time we want to check whether an option is set. Fortunately, the way in which the options list was defined provides us with a convenient way around this problem. This list was defined such that the "value" of each option in the list returned by is getOpt actually a function that transforms Opts records. As a result it is possible to use a fold to thread an Opts record through the list of option functions. If there are no option flags set on the command line then we default to having all options "on". <<processOpts>>= processOpts :: [Opts -> Opts] -> Opts processOpts [] = allOpts True processOpts opts = foldl (flip ($)) (allOpts False) opts allOpts :: Bool -> Opts allOpts b = Opts { showLines = b, showWords = b, showChars = b } [edit] Putting it all together The remainder of wc.hs is fairly straightforward. It does two things: - Imports the necessary supporting libraries; - Defines a short mainfunction that gathers the command line arguments, handles any command line options, and then applies wcto the list of files provided on the command line. <<wc.hs>>= module Main where import System.Environment import System.Console.GetOpt import Control.Monad import Data.List WordCount options setup counting and printing parseOpts processOpts main :: IO () main = do args <- getArgs (optList, files) <- parseOpts args let opts = processOpts optList wc opts files
http://en.literateprograms.org/Word_count_(Haskell)
CC-MAIN-2014-42
refinedweb
1,144
55.47
I have recently started reading the book Functional Programming in Scala by Paul Chiusano and Rúnar Bjarnason, as a means to learn FP. I want to learn it because it will open my head a bit, twist my way of thinking and also hopefully make me a better programmer overall, or so I hope. In their book, Chp. 3, they define a basic singly-linked-list type as follows:: _*)) } def tail[A](ls: List[A]): List[A] = ls match { case Nil => Nil case Cons(x,xs) => xs } package fpinscala.datastructures object Main { def main(args:Array[String]):Unit = { println("Hello, Scala !! ") val example = Cons(1, Cons(2, Cons(3, Nil))) val example2 = List(1,2,3) val example3 = Nil val total = List.tail(example) val total2 = List.tail(example3) println(total2) } } Hello, Scala !! Cons(2,Cons(3,Nil)) In the default Scala list implementation, attempting to take the tail of an empty list would throw an UnsupportedOperationException. So you might want something more like def tail[A](ls: List[A]): List[A] = ls match { case Nil => throw new UnsupportedOperationException() case Cons(x,xs) => xs } Also, qantik's answer where he suggests using the :: operator would work with Scala's default list implementation, but since there isn't a :: method defined on this custom list implementation it won't work. Finally, you may want to consider defining tail so that instead of doing val list = List(1, 2, 3) val restOfList = tail(list). you could instead do val list = List(1, 2, 3) val restOfList = list.tail That would require defining the method on the List trait, as opposed to in the List object.
https://codedump.io/share/xzmSrFatNJz3/1/functional-programming-exercise-with-scala
CC-MAIN-2017-09
refinedweb
274
61.87
SOAP::Data Expand Messages - Hi folks, First post here. I got past the simple stuff, but now I'm trying to get SOAP::Lite to be compatible with Wasp for C++. It seems WASP for C++ wants namespaces and class names to be exactly as they show up in the WSDL file. SOAP::Lite does some things in its auto serializing (or whatever its called - it really is quite cool) that I'd like to modify slightly. Like disabling the prepending of the package name to the element type(or name). I think I can do so by customizing what SOAP::Data does, but I haven't been able to find an example or tutorial on how it can be done. I'm really just starting with perl, so please don't be shy with the details. If it helps any, what I'm trying to send is an array of structures. The size of the array may vary from 0..many. Thanks. John Powell Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/1216?unwrap=1&var=1
CC-MAIN-2017-34
refinedweb
178
71.55
First, the problem of interface versioning is not unique to Web services. Any software that must integrate with other software does so through an interface. Interfaces range from function call interfaces, to file interfaces to ports on the network that perform specific tasks. Once you have an interface, you typically need a way to describe this interface to the outside world so other folks can interact with your software. This is done by separating the description of the interface from the implementation of the interface. The most common example is the C/C++ header file that contains the prototypes for classes, methods and functions that a developer creates. These files tell other implementers and their tools (e.g., the compiler) how to interact with the developer's compiled code libraries. Interface files such as the C/C++ header are said to represent a "contract" with the outside world. It's a promise by the developer of a code library, for instance, that if other developers follow the contract, then the code will wo While you try very hard from release to release not to break your interface contracts there are lots of times when you just can't avoid this. In this case we create a new version of the interface. Along with the new version, you need to publish a new contract (header, IDL, WSDL file) and that contract must contain information that identifies it as a new version of the interface. So let's now get Web services specific. In Web services, your contract with the world is your WSDL file. This file describes what requests and responses you're capable of handling as well as XML message formats that are passed between the caller and the service. Your service interface is implemented in .Net as an asmx file located at a specific URL. Now, when you change the software behind the asmx file, you have two options. You can treat the change as constituting a brand new interface implementation and consequently dedicate a brand new URL/asmx pair to that service. At that location, you would publish a brand new WSDL and it would be clear to clients that this is a different WSDL from the original as its name, location, namespace etc. would be completely different from the original WSDL. Your other option is to publish a new WSDL file alongside the old one at the original location. The new WSDL file would reflect the changes you made to the service. The second WSDL indicates to the outside world that your service honors two contracts. Now, I know you're thinking "but I don't want two WSDLs I just want to update the WSDL file and change its version somehow". In fact, whether you have two WSDLs or one, the versioning issues are roughly the same. So let's talk about a very specific case where you want to keep one WSDL, you want to modify it and you want to reflect the modification as a change to the WSDL version and you're going to do this in .NET. There are two sub scenarios as well. In one, your changes are all backward compatible (you add a new web method or new XML message type). In the other, you break your contract by changing an existing web method or changing a message type. In both cases, your main mechanism for versioning is the "targetNamespace" for the WSDL file. This the accepted practice for versioning XML schema and the recommended practice for how to version WSDL files. So now your thinking "well why didn't you tell me that in the first place instead of blathering on about contracts and such". The reason is that it's not that easy. If all you do is change the targetNamespace for your WSDL then recompile your Web service, none of your existing clients using the old WSDL version will be able to use your service even if you have not changed anything. The reason is that when your client compiles its proxy stubs that interact with the Web service for you, it takes into account the target namespace for the WSDL file. This namespace is used to qualify messages and SOAP calls. Thus, your old clients will be chatting using the old namespace qualifiers and your newly compiled service will be expecting SOAP calls and messages to be qualified in the old namespace. Your service will not recognize the SOAP calls or the data!! There are two solutions to remedy this. The brute-force method is to copy the service and deploy it on a new URL. Old clients will access the old URL that supports the old namespace and the new clients will use the new URL and the new namespace. This is obviously ugly and difficult to maintain as you are copying code and creating new sites. If you want to upgrade the version (in a backwards compatible way!) and keep it on the same URL and the same code behind, then you need to do some WSDL tinkering. There is a good article that describes how to do this here. The main rub is that the target namespace of the WSDL file is also used to indicate the target namespace for the message definitions in the file and to create the SOAP action portion of the message sent to the Web service. The SOAP action is used by the .NET framework to route your request to the code that handles the request. The action is created by concatenating the target namespace to the name of the method. Thus, a target namespace of and a method name of GetQuote would generate a SOAP action element of. This selects the function to execute when the Web service receives the SOAP message. Obviously if I change the WSDL file to have a target namespace that bumps v1 to v2, then my SOAP action will change to. This is the action that will now be expected by the service for the GetQuote method. All the old clients will be sending actions with v1 in them and your service will act as if it has never heard of such a thing. Likewise, the target namespace for the messages defined in the file will be different from the namespace that the old clients will present along with their message instances and your service will not recognize the data. To fix this, you have to make some specific tweaks to your code. As a first step, you can go into your source and apply attributes to each of your Web methods. Specifically, you can set the soap action for each method. This fixes your SOAP action problem because you can go into your source and add attributes to each web method from v1 with a v1 action and each from v2 with a v2 action. The WSDL generated will appropriately reflect the correct actions. In a similar fashion, you can specify attributes that tell the code generator and the framework which namespace the request and response messages should reside in. Here is an exemplar class. This code will generate a service that is backward compatible with clients created against v1 WSDL while supporting new clients who need the "SayHello" method as defined in the v2 version. That's enough to ingest for now. I will follow up with an article that talks more about how to logically separate new version code into new interfaces when you decide you need to change a method signature or data format (break your contract with existing.
http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci917386,00.html
crawl-002
refinedweb
1,261
69.31
I'm currently working on a little Grails bug tracking application which should see the light of day on Sourceforge sometime in the new year. One of the features I just love about Jira is the RSS support - I'm always watching the Grails recently closed issues to see what's been fixed in the SVN. So I decided to see what's involved in generating a feed. I could use the standard Groovy MarkupBuilder for sure, but then I'd have to work out the details for each of the XML formats in the common RSS and Atom formats. There has to be an easier way. Enter ROME, a fantastic little library for generating ALL the common RSS feed formats. My goal was to have a controller action that takes a parameter for feed type so I could set up a bunch of links for the common cases. Turns out there's a great tutorial to get you started. Using it from Grails makes it even simpler... Copy your rome.jar file to your project/lib directory, create a new FeedController, and you're off and running. Here's a sample controller I've whipped up that generates a ton of standard feeds: import com.sun.syndication.feed.synd.*; import com.sun.syndication.io.SyndFeedOutput; class FeedController { def supportedFormats = [ "rss_0.90", "rss_0.91", "rss_0.92", "rss_0.93", "rss_0.94", "rss_1.0", "rss_2.0", "atom_0.3"] def rss = { render(text: getFeed("rss_1.0"), contentType:"text/xml", encoding:"UTF-8") } def atom = { render(text: getFeed("atom_1.0"), contentType:"text/xml", encoding:"UTF-8") } // or specify your own feed type def all = { def format = params.id if (supportedFormats.contains(format)) { render(text: getFeed(format), contentType:"text/xml", encoding:"UTF-8") } else { response.sendError(response.SC_FORBIDDEN); } } def getFeed(feedType) { def issues = Bug.list(max: 5, sort: "created", order: "desc") def entries = [] issues.each { issue -> def desc = new SyndContentImpl(type: "text/plain", value: issue.description); def entry = new SyndEntryImpl(title: issue.name + " - " + issue.summary, link: '' + issue.name, publishedDate: issue.created, description: desc); entries.add(entry); } SyndFeed feed = new SyndFeedImpl(feedType: feedType, title: 'Recently Closed Bugga Issues', link: '', description: 'Bugga issues closed in the last few days', entries: entries); StringWriter writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed,writer); writer.close(); return writer.toString(); } } Then you just need to point your aggregator to and you're in business. Or if you want to use any of the supported feeds, head on over to or whatever you fancy. Here's a grab from NewzCrawler: Props to the ROME team for a first class little library that does one thing very well.
http://blogs.bytecode.com.au/glen/2006/12/22/1166781151213.html
crawl-001
refinedweb
437
50.73
This post was originally published on Oct 24, 2015 but has been updated to reflect the latest information. Upgrading an existing AngularJS application to Angular 2 is surely one of the most interesting topics when it comes to Angular 2. A long time it has been unclear what a dedicated upgrade path will actually look like, since Angular 2 is still in alpha state and APIs aren’t stable yet, which makes it hard to “assume” where things will go and what’s the best way to get there. Earlier this year however, the Angular team has made an official announcement in which they talk about what are the available upgrade strategies and what things of both frameworks have to interoperate in order to run them side-by-side on the same website. While the blog post is rather a kind of birds-eye view where no code is shown, a dedicated design document has been created that gives a more concrete idea on what the APIs will look like. Meanwhile, first implementations of ngUpgrade have landed in the code base and it’s time to start digging into it. In this article we’re going to explore what we can do to prepare for an upgrade, and of course how we eventually use ngUpgrade to upgrade our application to Angular 2. Why upgrade? One thing that seems to be a bit left out when people get scared that they can’t upgrade to Angular 2 for various reasons, is to think about if an upgrade is needed in the first place. Of course, Angular 2 is the next major version of the framework and it will surely be the version we want to go with when building web applications in the future. However, that doesn’t mean that our existing Angular 1 applications aren’t good enough anymore to survive the next generation of the web. It’s not that once Angular 2 is out, our Angular 1 applications immediately stop working. We still have a massive amount of websites out there that seem to be outdated, old and slow. Believe it or not, even if those websites are over 10 years old, they still work. That’s the nice thing about the web, nothing is as backwards compatible because no one wants to break the web, right? So before we think about going through the process upgrading we should really ask ourselves why we want to do it and if the applications we’ve built so far are really in a state that they need this upgrade. Nonetheless there are some very strong arguments why one wants to upgrade and here are just a few of them: Better Performance - Angular 2 comes with a way faster change detection, template precompilation, faster bootstrap time, view caching and plenty other things that make the framework freakin’ fast. Server-side Rendering - The next version of Angular has been split up into two parts, an application layer and a render layer. This enables us to run Angular in other environments than the browser like Web Workers or even servers. More powerful Templating - The new template syntax is statically analyzable as discussed here, removes many directives and integrates better with Web Components and other elements. Better Ecosystem - Of course, at the time of writing this article, this is not true. But the Angular 2 ecosystem will eventually be better and more interesting to us in the future. There are surely more reasons why Angular 2 is better than Angular 1, but keep in mind that we’re talking about the motivation for upgrade here. Let’s talk about how we can prepare for an actual upgrade. Changes in Angular 2 In order to upgrade, we need to understand in what ways Angular 2 is different. Unfortunately, covering the bigger differences between both version of the framework is out of the scope of this article. However, if you’re entirely new to Angular 2, you might want to checkout our project Exploring Angular 2 and get your feet wet. Here’s a list of changes that are crucial when thinking about upgrading: - Components - Components are the new building blocks when creating applications with Angular 2. Almost everything is a component, even our application itself. - Inputs/Outputs - Components communicate via inputs and outputs, if they run in the Browser, these are element properties and events. Our article on demystifying Angular 2’s Template syntax explains how they work. - Content Projection - Basically the new transclusion, but more aligned with the Web Components standard. - Dependency Injection - Instead of having a single injector for our entire application, in Angular 2 each component comes with its own injector. We have a dedicated article on that too. Of course, there are way more things in Angular 2 that will change or be added to the framework, such as Routing, Forms, the Http layer and more. How do we get there? After doing tons of research at thoughtram with Christoph we realised, that the entire upgrade process can basically be categorized in two phases: Preparation and Upgrade. Preparation This is the phase that we could start off today. What can we do today to make the upgrade process later on easier? This includes several things like how we structure our application, which tools can we use or maybe even a language upgrade. Upgrade The phase of running both frameworks side-by-side. This is where ngUpgrade comes into play to make A1 and A2 components interoperable. Keep in mind that the goal of this phase is to stay in it as little as possible, since running both frameworks on the same website is surely not ideal. Preparing for upgrade Let’s discuss what we can do today to prepare for an actual upgrade. Layer application by feature or component Oldie but goldie. We still see applications using a project structure where all directives go into app/directives, services go into app/services, controllers into app/controllers and so on and so forth. You get the idea.. We should rather go with something like: app |- components |- productDetail | |- productDetail.js | |- productDetail.css | |- productDetail.html | |- productDetail.spec.js |- productList |- checkout |- wishlist This structure allows us to take e.g. productDetail and upgrade it to Angular 2 to integrate it back into the application later on. We don’t have to worry if there’s anything else related to productDetail in the code base that we might forget, because everything is in one place. Use .service() instead of .factory() If we plan to not only upgrade the framework, but also the language in which we’re writing our application, we should definitely consider to use .service() instead of .factory() in all the cases where a service can be potentially a class. In Angular 2, a service is also just a class, so this seems like a logical thing to do. For more information on why .service() might be a better fit, read this article. Write new components in ES2015 or TypeScript This is an interesting one. When we saw Angular 2 code the very first time, some of us were scared because all of a sudden there were classes and decorators. Despite the fact that we don’t have to write our Angular 2 apps in TypeScript (as explained in this article), ES2015 is the next standardized version, which means we will write it sooner or later anyways. We wrote about how to write Angular in ES2015 today and if we do plan to upgrade but can’t do it right now, we should definitely write our new components in ES2015 or TypeScript. That being said, it doesn’t really make sense to upgrade existing code to ES2015 or TypeScript. Even though it seems to be a logical step in preparation for upgrade, it doesn’t help us in any way to take the existing and large code base and upgrade it to ES2015 or TypeScript first, before we upgrade the application to Angular 2. If we have to upgrade to Angular 2, it probably makes more sense to just rewrite component by component, without touching the existing code base. But this of course depends on how big our application is. Again, this is just a language upgrade and it doesn’t really help with the upgrade itself, however, it helps us and our team to get used to the new languages features as we’re building components with it. Use decorators in Angular 1? Of course, we can take our code base closer to what Angular 2 code would look like, by upgrading our language to TypeScript and use e.g. Decorators that have specifically been created for Angular 1. There are plenty community projects out there, some of them are a1atscript, angular2-now, angular-decorators and ng-classy. They try solve the same problem, which is adding semantically useful decorators to Angular 1. But do they really help? I don’t think so. They might improve the developer experience because all of a sudden we can use nice decorators that generate code for us, however, they don’t help when it comes to upgrading an application to Angular 2. One project, ng-forward, tries to make the exact same Angular 2 syntax available in Angular 1. This can be helpful to some extend since you and your team are getting familiar with how to write apps in Angular 2 while writing Angular 1 code. On the other hand, it could also be confusing when trying to squeeze Angular 2 concepts and syntax into the Angular 1 world. We’ll see how practical it is once projects are starting to use it. Upgrade Strategies Now that we know what we can do to prepare for an upgrade, let’s take a look at the different upgrade strategies available to see which one makes more sense to us. There are basically two strategies: - Big Bang - Start a spike in Angular 2 and replace entire app once done - Incremental - Upgrade existing app once service or component at a time Which one should we use? This really depends! If our application is rather small a big bang rewrite is probably the easiest and fastest way to upgrade. If our application is rather large and it’s deployed continuesly, we can’t just upgrade the whole thing at once. We need a way to do it step by step, component by component, service by service. This is where the incremental upgrade comes into play. In the end it’s really a matter of how much time we have available to process the upgrade. We will focus on incremental upgrade, since this is what the majority of developers want to understand and see how it works. Upgrading using ngUpgrade In order to run both frameworks side-by-side and make components interoperable, the Angular projects comes with a module ngUpgrade. The module basically acts as an adapter facade, so we don’t really feel that there are two frameworks running side-by-side. For this to work, four things need to interoperate: - Dependency Injection - Exposing Angular 2 services into Angular 1 components and vice-versa. - Component Nesting - Angular 1 directives can be used in Angular 2 components and Angular 2 components can used Angular 1 directives - Content Projection / Transclusion - Angular 1 components transclude Angular 2 components and Angular 2 component project Angular 1 directives - Change Detection - Angular 1 scope digest and change detectors in Angular 2 are interleaved With these four things being interoperable, we can already start upgrading our applications component by component. Routing is another part that can help but is not necessarily mandatory, since we can totally stick with any Angular 1 routing system while upgrading. The typical upgrade process Here’s what a typical upgrade process would look like: - Include Angular 2 and upgrade module - Pick component to upgrade and change its controller and template Angular 2 syntax (this is now an Angular 2 component) - Downgrade Angular 2 component to make it run in Angular 1 app - Pick a service to upgrade, this usually requires little amount of change (especially if we’re on ES2015) - Repeat step 2 and 3 (and 4) - Replace Angular 1 bootstrap with Angular 2 bootstrap Let’s use ngUpgrade to upgrade our components to Angular 2! Bootstrapping with ngUpgrade The first thing we need to do is to upgrade our Angular 1 application with ngUpgrade. Whenever we upgrade an app to Angular 2, we always have an Angular 1 module being bootstrap at root level. This means, during the process of upgrade, Angular 2 components are always bootstrap inside Angular 1 components. Let’s start with an app we want to upgrade; var app = angular.module('myApp', []); Plain old Angular 1 module. Usually, this module is bootstrapped using the ng-app attribute, but now we want to bootstrap our module using ngUpgrade. We do that by removing the ng-app attribute from the HTML, create an ngUpgrade adapter from the upgrade module, and call bootstrap() on it with myApp as module dependency: import { UpgradeAdapter } from '@angular/upgrade'; var adapter = new UpgradeAdapter(); var app = angular.module('myApp', []); adapter.bootstrap(document.body, ['myApp']); Cool, our app is now bootstrapped using ngUpgrade and we can start mixing Angular 1 components with Angular 2 components. However, in a real world application, you want to create an instance of UpgradeAdapter in a separate module and import it where you need it. This leads to cleaner code when upgrading across your application. Downgrading Angular 2 components Let’s upgrade our first component to Angular 2 and use it in our Angular 1 application. Here we have a productDetail component that needs to be upgraded: app.component('productDetail', () => { bindings: { product: '=' }, controller: 'ProductDetailController', template: ` <h2>{{$ctrl.product.name}}</h2> <p>{{$ctrl.product.description}}</p> ` }); Upgrading this to Angular 2 looks something like this: @Component({ selector: 'product-detail', template: ` <h2>{{product.name}}</h2> <p>{{product.description}}</p> ` }) class ProductDetail { @Input() product: Product; } Note: You might want to define this component in a separate file, for simplicity sake we defined it in place. Perfect! But how do we get this Angular 2 component into our Angular 1 application? The UpgradeAdapter we’ve created comes with a method downgradeNg2Component(), which takes an Angular 2 component and creates an Angular 1 directive from it. Let’s use our Angular 2 component in Angular 1 world. app.directive('productDetail', adapter.downgradeNg2Component(ProductDetail)); Yay! That’s it! The adapter will bootstrap this component from within the Angular 1 template where it’s used. But wait, our Angular 2 component is just an Angular 1 component eventually? Yes and no. The directive is controlled by Angular 1, but the component’s view will be controller by Angular 2. This means the resulting Angular 1 components takes advantage of Angular 2 features and performance. Upgrading Angular 1 components There might be cases where one component has already been upgraded to Angular 2, but it still uses Angular 1 directives in its template. ngUpgrade allows us to use Angular 1 directives in Angular 2 components by upgrading them using upgradeNg1Component(). Let’s say we continued upgrading our application and have a ProductList component like this: @Component({ selector: 'product-list', template: ` <h2>Product List</h2> <ol> <li * <product-list-item [product]="product"> </product-list-item> </li> </ol> ` }) class ProductList { @Input() products: Product[]; ... } <product-list-item> is a component that hasn’t been ported to Angular 2 yet and maybe can’t even for some reason. It needs to be upgraded but how do we get there? As you can see, there’s a directives property in the @Component() metadata. This property defines which directives are used in the component’s template. What we need is a way to add <product-list-item> there too. upgradeNg1Component() enables us to do exactly that. It takes the name of a directive that has been registered somewhere on our Angular 1 module and upgrades it to an Angular 2 component. Here’s what it looks like: @NgModule({ imports: [BrowserModule], declarations: [ AppComponent, ProductList, adapter.upgradeNg1Component('productListItem') ], ... }) export class AppModule {} All we need to do is to downgrade ProductList item and we can use it right away! Adding Angular 2 Providers Upgrading components is probably the most crucial part in the entire upgrade process. Sometimes however, components have service dependencies which need to work in both worlds too. Luckily, ngUpgrade provides APIs for that. Let’s say our ProductDetail component, already upgraded to Angular 2, has a ProductService dependency. class ProductService { } @Component() class ProductDetail { constructor(productService: ProductService) { } } In Angular 2, we have to add a provider configuration for the component’s injector, but since we don’t bootstrap using Angular 2, there’s no way to do so. ngUpgrade allows us to add a provider using the addProvider() method to solve this scenario. adapter.addProvider(ProductService); That’s all we need to do! Upgrading Angular 1 Providers Let’s say our ProductService depends on another lower level DataService to communicate with a remote server. DataService is already implemented in our Angular 1 application but not yet upgraded to Angular 2. class ProductService { constructor(@Inject('DataService') dataService) { ... } } app.service('DataService', () => { ... }); As you can see, we’re using @Inject to specify the provider token for DataService, since we don’t have a DataService type. If this is unclear, you might want to read our articles on DI in Angular 2. However, there’s no provider for 'DataService' in Angular 2 world yet. Let’s make it available using upgradeNg1Provider(). adapter.upgradeNg1Provider('DataService'); Boom! We can make it even better. Let’s assume our Angular 1 service has already been written as class. class DataService { } app.service('DataService', DataService); We can use that class as type and token for dependency injection in Angular 2. All we have to do, is to upgrade our service with that token. adapter.upgradeNg1Provider('DataService', {asToken: DataService}); Now we can inject it using plain old type annotations. @Injectable() class ProductService { constructor(dataService: DataService) { ... } } Note: We added @Injectable() to our service because TypeScript needs at least one decorator to emit metadata for it. Learn more in our article on Injecting Services in Services in Angular 2. Downgrading Angular 2 Providers Last but not least, we might need to be able to use Angular 2 services in Angular 1 components. Guess what, ngUpgrade comes with a downgradeNg2Provider() method. app.factory('ProductService', adapter.downgradeNg2Provider(ProductService)); Conclusion ngUpgrade provides many useful APIs and is a big step forward when it comes to truly upgrading an application from Angular 1 to Angular 2. At AngularConnect we gave a workshop on upgrading and we’ve open sourced a repository that shows all the steps we’ve been through, from preparation to upgrade. Make sure to check out the steps branch. Hopefully this article made a bit more clear what this whole upgrade story is all about! Join over 1000 other developers who get our content first. Author Related Posts Custom Form Controls in Angular 2 Angular makes it very easy to create custom form controls. Read on to learn how to do it! Protecting Routes using Guards in Angular 2 Angular's router enables protecting routes using guards and in this article we're going to discuss how to implement them. Reactive Forms in Angular 2 Angular allows us to build forms in a model-driven fashion. In this article we're going to discuss what that looks... Cold vs Hot Observables In this article we are going to demystify what the term hot vs cold means when it comes to Observables.... Routing in Angular 2 revisited Learn how to implement basic routing in your Angular 2 application using the latest and greatest APIs! Component-Relative Paths in Angular 2 Component-relative enable developers to more easily create maintainable, reusable, portable components in Angular 2. Here's how!
http://blog.thoughtram.io/angular/2015/10/24/upgrading-apps-to-angular-2-using-ngupgrade.html
CC-MAIN-2016-36
refinedweb
3,300
52.29
John Wang wrote: > The solution you proposed is still a derivative of creating a > dummy document stream. Taking the same example, java (5), lucene (6), > VectorTokenStream would create a total of 11 Tokens whereas only 2 is > neccessary. That's easy to fix. We just need to reuse the token: public class VectorTokenStream extends TokenStream { private int term = -1; private int freq = 0; private Token token; public VectorTokenStream(String[] terms, int[] freqs) { this.terms = terms; this.freqs = freqs; } public Token next() { if (freq == 0) { term++; if (term >= terms.length) return null; token = new Token(terms[term], 0, 0); freq = freqs[term]; } freq--; return token; } } Then only two tokens are created, as you desire. If you for some reason don't want to create a dummy document stream, then you could instead implement an IndexReader that delivers a synthetic index for a single document. Then use IndexWriter.addIndexes() to turn this into a real, FSDirectory-based index. However that would be a lot more work and only very marginally faster. So I'd stick with the approach I've outlined above. (Note: this code has not been compiled or run. It may have bugs.) Doug --------------------------------------------------------------------- To unsubscribe, e-mail: lucene-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: lucene-user-help@jakarta.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-java-user/200407.mbox/%3C40ED7E07.8040609@apache.org%3E
CC-MAIN-2016-22
refinedweb
215
59.4
Getting bored of your code? Already tried out hundreds of syntax highlighter but always felt something is missing? Emoji Syntax is what you need! An atom package adding emoji to language keywords. Install Emoji Syntax either via apm apm install emoji-syntax or search for emoji syntax in your Atom settings panel. This package does not actually add emoji characters to your code—don't worry—your linter or tests won't go crazy! Only official language packages are supported. Other language packages might use different selectors to highlight syntax and not work as intended. Note: not all emoji are supported in each of the custom sets yet! Emoji Syntax comes with its own settings page. There you can customise, activate and deactivate every emoji for each language. The settings page is available through Packages > Emoji Syntax > Settings or the emoji-syntax:settings command. Each language has its own section which you can deactivate. Doing that, the entire language won't have any emoji. The following options are available: Emoji: opens a modal of emoji to choose from Position: the position of the emoji around the keyword (e.g. 📦 importor import 📦) Spacing: adds spacing between emoji and keyword (e.g. function 🔧 () {}or function🔧 () {}) If you want to contribute by either extending/improving a language set, adding a new language, fixing a bug or anything else you can do that by simply sending a pull request. API documentation via Doclets. The code is available under MIT License. Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away.
https://api.atom.io/packages/emoji-syntax
CC-MAIN-2021-39
refinedweb
265
67.04
Introduction to React Native FlatList React native flatlist is like a listview which is used to hold items in a list and provide important features like scrolling horizontally and vertically. Flatlist in reacts native is designed to handle large datasets that might not fit on the device screen. This flatlist performs rendering of only current displaying items on a screen and not all items. Syntax: Here is a basic syntax: import {Flatlist } from 'react-native'; <FlatList data={ // data to be rendered in flatlist } SeparatorComponent={ // A separator to separate data items } renderData= {({ singledata}) => // Single data view } /> From the above syntax, we can see that the flatlist can be rendered using two primary props that are data and renderItem. Other props like Separator, Header, Footer, and Pulltoscroll are optional components. How Flatlist Works? It can be compared to the List view and is one of the most used components in react native. Flatlist in reacts native is a built-in component that provides scrolling of data that does not fit into the screen of a mobile device in which the application is running. Flatlist works on the following primary props: - Data: This is an array of data that contains individual items that will be used to create a flatlist in react native. - RenderItem: This is a function whose purpose is to pick up individual items from an array and render it into a section of a react-native flatlist. Features of React Native Flatlist The following are the important features: - Pull to refresh support - Header support - Footer support - Separator support - Scroll loading support - ScrollToIndex support - Cross-Platform support - Configurable callbacks - Optional support for horizontal mode All the above-listed features make flatlist a very commonly used and an efficient component of react native. Example Here is an example showing the use of flatlist: import React, { Component } from 'react'; import { AppRegistry, FlatList, StyleSheet, Text, View,Alert } from 'react-native'; export default class FlatListDemo extends Component { renderHeader= () => { var header= ( <View style ={styles.header_footer_style}> <Text style ={styles.textStyle}> Courses Offered By Edubca </Text> </View> ); return header; }; renderSeparator = () => { return ( <View style={{ height: 1, width: "100%", backgroundColor: "#000", }} /> ); }; //handling item Press event getListViewItem = (item) => { Alert.alert('Clicked Item : ' + item.key); } render() { return ( <View style={styles.container}> <FlatList data={[ {key: 'React Native'},{key: 'Java'}, {key: 'Hadoop'},{key: 'Spark'}, {key: 'AWS'},{key: 'Azure'},{key: 'Phython'}, {key: 'Python'},{key: 'Javascript'}, {key: 'C++'}, {key: 'Data Science'},{key: 'Machine Learning'},{key: 'MYSQL'}, {key: 'Hive'} ]} renderItem={({item}) => <Text style={styles.item} onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>} ItemSeparatorComponent={this.renderSeparator} ListHeaderComponent={this.renderHeader} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, item: { padding: 10, fontSize: 18, height: 44, }, }) AppRegistry.registerComponent('ReactFlatListDemo',()=>FlatListDemo); Output: After Scrolling we can see the below items like: On clicking an item we will see the below: From the above example we can see that the following properties are used in flatlist: - Separator: This is used as a splitter between different views of a flatlist. This is configured using the ItemSeparatorComponent property of flatlist. - Data: Data to be rendered on a flatlist is set using data prop of flatlist. - RenderItem: The function of this prop is to render a flatlist with the content of data such that each part of an array is rendered into different cells of flatlist. This is basically a function that accepts a single argument which is the item to be populated. - Header: Header of a flatlist can be set usingListHeaderComponent and its value can be set using a function. - Footer: Footer of a flatlist can be set using ListFooterComponent prop of a flatlist. Apart from the above properties, there are also other properties like PullToScroll and InfiniteScroll that can be set according to our requirements. Also, we can see how click events of items are handled in flatlist. Conclusion From the above article, we have a clear understanding of flatlist in react native. It provides several useful features some of which have been covered through the above examples. Apart from the above features, other customizations can be performed on flatlist according to the requirement and needs of the application. Recommended Articles This is a guide to React Native FlatList. Here we discuss the Features and How Flatlist Works along with Example. You may also look at the following articles to learn more –
https://www.educba.com/react-native-flatlist/?source=leftnav
CC-MAIN-2022-33
refinedweb
711
51.38
09 September 2010 11:42 [Source: ICIS news] LONDON (ICIS)--World oil demand growth is expected to continue at the current level of 1m bbl/day in 2011 to average 86.6m bbl/day, unchanged from last month’s assessment, OPEC said in its monthly oil market report on Thursday. “The recovery in oil demand will take place in approximately all quarters, although with more strength in the second half of the year,” it said. “The expected growth in oil demand next year comes as a result of not only improved economic activity, but also from the low base in oil demand in 2009 and 2010,” added OPEC. Non-OECD (Organisation for Economic Co-operation and Development) countries were expected to remain the key contributors to demand growth, led by ?xml:namespace> “Global oil demand was higher than expected in the first half of the year, supported by stimulus packages in key consuming countries. With these winding down, demand in the second half is expected to move lower,” said OPEC. Non-OPEC oil production was expected to increase by 920,000 bbl/day over the previous year to average 52.06m bbl/day in 2010, an upward revision of 130,000 bbl/day compared with the previous month. Supply from non-OPEC countries was forecast to grow by 360,000 bbl/day in 2011 to average 52.42m bbl/day. The OPEC reference basket moved within a range of $70-79/bbl in August to average $74.15/bbl, representing an increase of $1.64 or 2.3% over the previous
http://www.icis.com/Articles/2010/09/09/9392053/world-oil-demand-growth-to-remain-at-1m-bblday-in-2011-opec.html
CC-MAIN-2014-10
refinedweb
261
62.98
Versioned file field for django models This package offers a file field for django models, that stores the file contents under a VCS (version control system). Everytime a field of this type is changed for a particular model instance, the new content will be commited as a new version in the repository. Thus, there will be one file in the repository for each vff field and instance. The repository will be at settings.VFF_REPO_ROOT, or, if that is unset, at a vf_repo subdirectory of django’s settings.MEDIA_ROOT. Different VCSs can be used to manage the repository, using pluggable backends. The package only provides a GIT backend out of the box. Install django-vff like you would install any other pypi package: $ pip install django-vff You do not need to add anything into Django’s INSTALLED_APPS. You have to set the following variables in django’s settings.py: For the git backend: If these two settings for the git backend are not set, VFF_REPO_ROOT will assume a value of os.path.join(settings.MEDIA_ROOT, 'vf_repo'), and VFF_REPO_PATH will assume a value of ''. You use it like you would use django.db.models.FileField: from django.db import models from vff.field import VersionedFileField class MyModel(models.Model): name = models.CharField('Name', max_length=128) content = VersionedFileField(name='content', verbose_name='file content') Once you have an instance of the MyModel class, you can use three special methods to list available versions, to get specific versions, and to get diffs between versions: - list revisions:>>> revs = instance.content.list_revisions() >>> from pprint import pprint >>> pprint(revs) [{'author': u'John Smith', 'date': datetime.datetime(2011, 6, 16, 13, 25, 30), 'message': u'second version', 'versionid': 'a64ea785e195bbf4b3064e6701adbdbf4b5d13be'}, {'author': u'Martha Brown', 'date': datetime.datetime(2011, 6, 16, 8, 24, 36), 'message': u'first version', 'versionid': '048848a70205d0e18d836f403e2a02830492cbf9'}] - get the string content of a specific revision:>>> rev1_id = revs[-1]['versionid'] >>> instance.content.get_revision(rev1_id) u'These are the contents of the first version of the file' - get the diff between two revisions:>>> rev2_id = revs[-2]['versionid'] >>> print instance.content.get_diff(rev1_id, rev2_id) --- 048848a70205d0e18d836f403e2a02830492cbf9 +++ a64ea785e195bbf4b3064e6701adbdbf4b5d13be @@ -1,1 +1,1 @@ -These are the contents of the first version of the file +These are the contents of the second version of the file At the moment, saving and deleting has to be explicitly done for this field. So, for example, if you have a model instance with a content vff field, and a view that uses an edit form with a forms.FileField for it, after validating the form you would have to do something like: name = instance.content.name content = form['content'].data username = request.user.username commit_msg = form['commit_msg'].data.encode('utf8') instance.content.save(name, content, username, commit_msg) instance.save() Likewise, when removing an instance, you would: username = request.user.username commit_msg = u'entity removed' instance.content.delete(username, commit_msg) instance.delete() In the future, if there is interest, the package could include a special widget with input space for the necessary data (commit message, etc) so that saving and deleting would be transparent. To develop a new backend for django-vff, you have to subclass the abstract base class vff.abcs.VFFBackend. The methods that need to be implemented are documented in the docstrings of the class. - Fix typo on README.txt - Fix uncaught exception during initialization of GIT repository. - The (git) repo can now be anywhere in the filesystem (not necessarily inside the MEDIA_ROOT), and django-vff can be told to keep its files in a subdirectory iof the repo. - Better fix for error when deleting objects with no file in the repo. - Do not fail deleting objects with no file in the repo. - Remove the files from the repository when deleting objects. - Change the signature of VersionedFieldFile’s save and delete so they are compatible with django’s FieldFile. - Initial version which includes a VersionedFileField and a git backend. Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-vff/
CC-MAIN-2017-26
refinedweb
663
57.98
This example writes to a file using the FileIO classes into the Yún device's filesystem. A shell script file is created in /tmp, and is executed afterwards. There is no circuit for this example. image developed using Fritzing. For more circuit examples, see the Fritzing project page Include the FileIO header, for communicating with the filesystem. #include <FileIO.h> In setup(), initialize Bridge, Serial communication, and FileSystem. Wait for an active serial connection, and call a custom function uploadScript() which will upload your file, before starting loop(). loop() will just execute your script every 5 seconds by calling another custom function, runScript(). Your uploadScript() function will create a shell script in the Linux file system that will check the network traffic of the WiFi interface. Create the file and open it by creating an instance of the File@ class, and calling FileSystem.open()@@ indicating where you would like to create the script. You'll store the script in "/tmp", which resides in RAM, to preserve the limited number of FLASH memory read/write cycles. Write the contents of the script to the file with File.print(). begin by printing the header, "#!/bin/s", then the utility ifconfig. @ifconfig@ is a command line utility for controlling network interfaces. you'll be looking at the WiFi interface, which is referred to as "wlan0". The utility grep will search the output of ifconfig. You're looking for the number of bytes received , so search for the keywords "RX bytes" and close the file. Instantiate a Process to make the script executable. chmod@ is a command that will change the modes of files. By sending the chmod@@ command and filepath, you can make your shell script run like an application. The runScript() function will create a Process that runs the script and prints the results to the Serial Monitor. Create a named Process, and start your script by calling Process.begin(filepath) and Process.run(). Create a string to hold the output, and read the output into it Remove the blank spaces at the beginning and end of the string and print it to the serial monitor : The complete sketch is below : Last revision 2016/05/25 by SM
https://www.arduino.cc/en/Tutorial/FileWriteScript
CC-MAIN-2017-51
refinedweb
366
66.23
A few months ago, I wrote an in-depth article describing how labels work in Loki. Here, I’m consolidating that information into a more digestible “cheat sheet." There are some big differences in how Loki works compared to other logging systems which require a different way of thinking. This is my attempt to convey those differences as well as map out our thought process behind them. As a Loki user or operator, your goal should be to use the fewest labels possible to store your logs. Fewer labels means a smaller index which leads to better performance. I think this is worth repeating: Fewer labels = better performance. This likely sounds counterintuitive. I know my experience with databases has taught me that if you want it to be fast, you need to index it. Loki is built and optimized in the exact opposite way. The design goals around Loki are to keep operating costs and complexity low, which is accomplished by keeping a very small index and leveraging commodity hardware and parallelization. So as a user or operator of Loki, always think twice before adding labels. Examples ts=2020-08-25T16:55:42.986960888Z caller=spanlogger.go:53 org_id=29 traceID=2612c3ff044b7d02 method=Store.lookupIdsByMetricNameMatcher level=debug matcher="pod=\"loki-canary-25f2k\"" queries=16 How can I query all my logs for a given traceID? You might think, “I should extract traceID as a label,” and then I can query like this: {cluster="ops-cluster-1",namespace="loki-dev", traceID=”2612c3ff044b7d02”} Never do this! Avoid extracting content from your logs into labels. If you want to find high cardinality data in your logs use filter expressions like this: {cluster="ops-cluster-1",namespace="loki-dev"} |= “traceID=2612c3ff044b7d02” But what if the label is low cardinality? What if you extracted the log level into a label, and we only have five values for our logging level? {cluster="ops-cluster-1",namespace="loki-dev", level=”debug”} Be careful here! Remember labels have a multiplicative effect on the index and storage. What started as one log stream has now turned into as many as five streams. Then consider if you add another label; even if it only has a few values, things can quickly get out of control: Instead, use filter expressions: {cluster="ops-cluster-1",namespace="loki-dev"} |= “level=debug” |= “status=200” |= “path=/api/v1/query” But if I want to write a metric query and I want to add a sum by (path), how can I do this if pathisn’t a label? Ah, you got me here! Currently you can only aggregate on labels; HOWEVER, that’s not for long! Coming soon in v2 of Loki’s query language, LogQL, we will support extracting log content into query time labels which can be used for aggregations! Have a look at a preview here. Is it ever ok to extract log content into labels? Yes, but please think very carefully before you do so. Labels describe your logs. They help you narrow down the search. They are not intended to hold log content itself and they are never intended to be used to locate an individual line. Another way to think of labels is that they describe your environment or the topology of your applications and servers (i.e. where your logs came from). But when I send logs from my Lambda or function I get “out of order” errors unless I include a request ID or invocation ID? This is currently a tough use case for Loki. We are working hard to remove the limitation on ordered entries, but this is a tricky problem. For now, this kind of environment will require limits on how much parallelism your functions have. Or another workaround involves a fan-in approach of sending your function logs to an intermediate Promtail instance which can do ingestion timestamping. This is an area where Loki needs improvement, and we are actively working on this. Summary Loki leverages horizontal scaling and query time brute force to find your data. Is this as fast as a fully indexed solution? No, it’s probably not! But it’s a heck of a lot easier to run (and still very fast)! Let’s look at some actual data from one of Grafana Lab’s Loki clusters. In the last seven days, it ingested 14TB of data. The corresponding index usage for that time period is about 500MB; the index for 14TB of logs could fit in the RAM of a Raspberry Pi. This is why we focus on keeping the label set small. Maybe your labels can only narrow down your search to 100GB of log data — no worries! It’s a lot cheaper to run 20 queriers which can parallelize searching that 100GB of data at 30GB/s than it is to maintain a 14TB index that can tell you exactly where to look, especially when you consider you can turn them off when you are done. So once more, with feeling: Fewer labels = better performance.
https://grafana.com/blog/2020/08/27/the-concise-guide-to-labels-in-loki/
CC-MAIN-2022-40
refinedweb
837
64.2
steganopy 0.0.1 A steganography tool written in Python Steganopy Steganography is the art and science of writing hidden messages in such a way that no one, apart from the sender and intended recipient, suspects the existence of the message. The word steganography is of Greek origin and means “concealed writing”. Steganopy is a steganographic tool written in Python. It comes with a handy gui and an easy to use api so that it can be integrated into your Python projects. Steganopy allows you to encode data into any PNG image with an RGB or RGBA format. Files are encoded into PNG images using the least significant bit modification method. As long as your original image is sufficiently large enough to hold the data to be encode any type of file could be concealed within an image (Text files, other images, etc). A password can optionally be supplied to encrypt data prior to encoding for a truly unbreakable level of protection. Installation pip install steganopy Usage You have two ways to use steganopy GUI Use the gui by simply issuing the command steganopy will now be able to use the gui to encode data into PNG images as well as extract data from steganographic images In a Python program The api offers two functions to call from within your python programs. NOTE The cipher key is optional but if you use one to encode your data you will have to use the same one again to extract that data. Encode data from os.path import sep, expanduser from steganopy.api import create_stegano_image output_dir = sep.join([expanduser('~'), "Downloads"]) stegano_image = create_stegano_image( original_image=sep.join([expanduser('~'), "Downloads", "cover_image.png"]), data_to_hide=sep.join([expanduser('~'), "doc_to_hide.txt"]), cipher_key="JarrodCTaylor" ) stegano_image.save(sep.join([expanduser('~'), "Downloads", "stegano_image.png"])) Extract data from os.path import sep, expanduser from steganopy.api import extract_data_from_stegano_image extracted_data = extract_data_from_stegano_image( image=sep.join([expanduser('~'), "Downloads", "stegano_image.png"]), cipher_key="JarrodCTaylor" ) with open(sep.join([expanduser('~'), "Downloads", "extracted_content.txt"]), "w") as f: f.write(extracted_data) - Downloads (All Versions): - 0 downloads in the last day - 19 downloads in the last week - 96 downloads in the last month - Author: Jarrod C. Taylor - License: GPL - Categories - Package Index Owner: JarrodCTaylor - DOAP record: steganopy-0.0.1.xml
https://pypi.python.org/pypi/steganopy
CC-MAIN-2015-35
refinedweb
370
50.02
wcscat, wcsncat— #include <wchar.h>wchar_t * wcscat(wchar_t * restrict s, const wchar_t * restrict append); wchar_t * wcsncat(wchar_t * restrict s, const wchar_t * restrict append, size_t count); wcscat() and wcsncat() functions append a copy of the wide string append to the end of the wide string s, then add a terminating null wide character (L'\0'). The wide string s must have sufficient space to hold the result. The wcsncat() function appends not more than count wide characters where space for the terminating null wide character should not be included in count. wcscat() and wcsncat() functions return the pointer s. wcscat() and wcsncat() functions conform to ISO/IEC 9899:1999 (“ISO C99”) and were first introduced in ISO/IEC 9899/AMD1:1995 (“ISO C90, Amendment 1”). wcscat() and wcsncat() functions were ported from NetBSD and first appeared in OpenBSD 3.8. wcscat() and wcsncat() is very error-prone with respect to buffer overflows; see the EXAMPLES section in strcat(3) for correct usage. Using wcslcat(3) is a better choice in most cases.
https://man.openbsd.org/wcsncat.3
CC-MAIN-2018-39
refinedweb
171
62.27
advantage of MACRS v. straight-line depreciation Homework help from our online tutors - BrainMass.com You are interested in a bond. It has a 15 year remaining term and a 7% coupon rate. The price is 100. 1.What is the bond's YTM? 2.What is the formula you used to arrive at the answer? 3.Beacon Products has a project with an NPV of $500,000. a. Should the company accept the project? b. Why/why not? c. What is the impact of acceptance on the company (quantify your answer)? 4. If the real rate is 2%, the inflation premium is 3%, and the risk premium (i.e., Rm - Rf) is 9%: what is the required rate of return (3 decimal places .XXX or xx.x%) for a stock with a Beta of 1.2? 5. What is the formula you used to arrive at the answer? 6. What is the required rate of return (3 decimal places .XXX or xx.x%) for a stock with a Beta of 1.2? 7. AMI Corp. is considering the purchase of a new measuring instrument. It will cost $80,000 and will require another $20,000 to install and get ready for production. It is subject to 5-yr MACRS depreciation. Show the depreciation schedule (and annual amounts) for the new instrument. 8. Sun Hydraulics purchased a milling machine 3 years ago at an "all in" (i.e., fully installed) cost of $1.25 million. It is subject to 5-year MACRS. What is the current book value? 9. What is the formula you used to arrive at the answer? 10. What is the current book value? 11. Your family's business exclusively uses the payback measure when evaluating possible capital projects. No project will be undertaken with a payback of more than 2 years. Family members are pleased because the company has been consistently profitable. However, the company's market value has been declining relative to competitors. How would you advise family members? 12. What are the NPV (in whole numbers) and IRR (2 decimal places) of the following cash flow series (if k = 0.11)? What are the formulas you used to arrive at the answers? YR 0 YR 1 YR 2 YR 3 YR 4 YR 5 (1500) 330 330 330 330 300 13. What is the advantage of MACRS v. straight-line depreciation? 14. The price of a bond is 100. Is the YTM less than, equal to, or greater than the coupon rate? 15. Use the following information, the Gordon DDM model, and a constant growth assumption to compute the firm's stock price. Note: you must compute the next dividend. NOTE: round growth rate to the nearest whole percent; round all dollar values (dividend & price) to the nearest penny. Historic dividends Beta = 1.3 2004 $3.24 Rf = 0.04 2003 $3.15 Rm = 0.12 2002 $2.90 2001 $2.78 2000 $2.66 1999 $2.31 16. Growth rate is (include the formula): 17. k is equal to (include the formula): 18. Dividend for 2005 is (include the formula): 19. Stock price is (include the formula): 20.a. What is the price of a 7% coupon bond with 5 years remaining to maturity if the current market required return (e.g., yield) is 8%? What is the price of the same bond if the current market required return increases to 10%? (Round to the nearest penny) 20.b. Market return at 8%, price is: 20.c. Market return is 10%: 21. Using the following Income Statement, Balance Sheet, and associated data, compute the firm's WACC. [Note: round all costs to 3 decimals ... e.g., xx.x% or 0.xxx] (Note: use the gross approximation method for the cost of debt) Revenues 350,000 beta = 1.50 EBIT 35,000 Rf = 0.048 Interest expense 10,000 Rm = 0.121 EBT 25,000 EAT 15,000 Tax rate = 0.40 Preferred dividends = 2,000 Current Assets 95,000 Current Liabilities 31,000 Net Fixed Assets 110,000 Long term Debt 74,000 Preferred Stock 14,000 Common at par 1,000 Paid in surplus 40,000 Retained earnings 45,000 Tot Equity 100,000 Total Assets 205,000 Tot Liab & Equity 205,000 22. The Cost of Debt is: 23. The Cost of Preferred Stock is: 24. Cost of Common Stock is: 26. AdFlex is considering replacing one of its machines with a newer model. The new machine has a purchase price of $315,000 and an installation cost of $25,000. It will have a 5-yr life, no salvage value, and will be depreciated using the 5-yr MACRS schedule. The firm has been offered $260,000 for the old machine. Its original cost was $280,000; it was purchased 3 years ago; and it is being depreciated using the 5-yr MACRS schedule. The machine has a 5-yr remaining life and no salvage value. The firm's WACC is 0.12 and the marginal ordinary & capital gains tax rates are 0.40. Any purchase will be funded with internal funds. The following table summarizes the operating cash flows of the old machine (provided to expedite processing) and the EBITD expected if the new machine is purchased. Yr - 1 Yr - 2 Yr - 3 Yr - 4 Yr - 5 Current machine (OCF) 55,000 60,000 60,000 60,000 60,000 New machine (EBITD) 95,000 125,000 120,000 150,000 122,000 (NOTE: notice that the OCF of the current machine has already been computed and is available. It does not have to be recomputed.) 27. What is the formula you used to calculate the initial investment? 28. The initial investment is: 29. The OCF by year for the new machine is: 30. The incremental OCF by year are: 31. The NPV for this project is (round to the nearest dollar): 32. What should the company do and why?© BrainMass Inc. brainmass.com September 18, 2018, 3:23 pm ad1c9bdddf Solution Summary The advantage of MACRS v. straight-line depreciation is emphasized.
https://brainmass.com/business/discounted-cash-flows-model/107110
CC-MAIN-2018-39
refinedweb
1,014
78.14
Suppose we have such amount, and we have to find the minimum number of notes of different denominations, that sum up to the given amount. Start from highest denomination notes, try to find as many notes possible for given amount. Here the assumption is that we have infinite amount of {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1}. So if the amount is say 800, then notes will be 500, 200, 100. Here we will use the greedy approach to solve this problem. #include<iostream> using namespace std; void countNotes(int amount) { int notes[10] = { 2000, 500, 200, 100, 50, 20, 10, 5, 2, 1 }; int noteFreq[10] = { 0 }; for (int i = 0; i < 10; i++) { if (amount >= notes[i]) { noteFreq[i] = amount / notes[i]; amount = amount - noteFreq[i] * notes[i]; } } cout << "Note count:" << endl; for (int i = 0; i < 9; i++) { if (noteFreq[i] != 0) { cout << notes[i] << " : " << noteFreq[i] << endl; } } } int main() { int amount = 1072; cout << "Total amount is: " << amount << endl; countNotes(amount); } Total amount is: 1072 Note count: 500 : 2 50 : 1 20 : 1 2 : 1
https://www.tutorialspoint.com/find-minimum-number-of-currency-notes-and-values-that-sum-to-given-amount-in-cplusplus
CC-MAIN-2021-25
refinedweb
181
72.5
Patterns can be kinda dull. Consequences and implementations are pretty damn fun. I got the proxy pattern working in Dart last night without much trouble. Let's see if I can cause trouble with the second implementation (a.k.a. doesNotUnderstand) from the Gang of Four book chapter on the pattern. The doesNotUnderstandmethod is a Smalltalk construct, but I think Dart's noSuchMethodought to serve a similar purpose. The Gang of Four's doesNotUnderstandimplementation was framed as a generic solution. I am going to keep mine somewhat generic. I continue to use last night's protection proxy example for driving automobiles. The protection came in the form of preventing underage drivers from getting behind the wheel: // Proxy Subject class ProxyCar implements Automobile { // ... void drive() { if (_driver.age <= 16) { print("Sorry, the driver is too young to drive."); return; } _car.drive(); } }Instead of protection solely in the drive()method, I am going to switch to a noSuchMethod()implementation. This protection proxy follows standard proxy practices in that it does not create an instance of the real subject (the car) until it is needed. The cargetter method returns the private _carinstance if it has been defined, otherwise it creates and assigns it: class ProxyCar implements Automobile { Driver driver; Car _car; ProxyCar(this.driver); Car get car => _car ??= new Car(); // noSuchMethod will go here... }To make the noSuchMethod()approach work, I am going to need to invoke arbitrary methods on the real subject. That means that I need to import dart:mirrors: import 'dart:mirrors';I next need to delete the existing drive()method. Once gone, invoking the drive()method on ProxyCarwill send the call to noSuchMethod(). If the noSuchMethod()method is not defined in ProxyCar, then the call gets sent to the noSuchMethod()in ProxyCar's superclass, Object. Object's noSuchMethod()throws a NoSuchMethodError, which I do not want, so I declare noSuchMethod()in ProxyCar. With dart:mirrors, I can reflect on the car, then send the message and arguments that reached noSuchMethod()to the carinstance: class ProxyCar implements Automobile { // ... dynamic noSuchMethod(i) { if (driver.age <= 16) throw new IllegalDriverException(driver, "too young"); return reflect(car).invoke(i.memberName, i.positionalArguments); } }I have switched to an exception here to really ensure that this registers as something wrong. With that, my client code is once again working. I create a 25 year-old driver, then send the drive()message to the proxy car: SinceSince // Proxy will allow access to real subject print("* 25 year-old driver here:"); car = new ProxyCar(new Driver(25)); car.drive(); drive()is not defined on ProxyCar, it gets sent to noSuchMethod(), which checks that the driver's age is greater than 16, then tells the car to drive: $ ./bin/drive.dart * 25 year-old driver here: Car has been driven!If a 16 year-old tries to get behind the wheel, the noSuchMethod()guard clause kicks in, giving me the appropriate exception: $ ./bin/drive.dart * 16 year-old driver here: Unhandled exception: IllegalDriverException: 16 year old driver is too young!I can add other gaurd clauses to noSuchMethod()as well. For example, I can guard against the same conditions as in the Gang of Four example—illegal messages: class ProxyCar implements Automobile { // ... dynamic noSuchMethod(i) { if (i.memberName != #drive) throw new IllegalAutomobileActionException(i.memberName); if (driver.age <= 16) throw new IllegalDriverException(driver, "too young"); return reflect(car).invoke(i.memberName, i.positionalArguments); } }Now if the driver tries to do something wrong with the car, an exception will arise regardless of age: The Gang of Four makes this completely generic, but I am hard pressed to think of a situation in which I could define a list of valid methods that would not apply to a single interface (likeThe Gang of Four makes this completely generic, but I am hard pressed to think of a situation in which I could define a list of valid methods that would not apply to a single interface (like print("* 25 year-old driver here:"); car = new ProxyCar(new Driver(25)); car.fly(); // ==> IllegalAutomobileActionException: Symbol("fly") Automobilein this case). Regardless, this noSuchMethod()proxy approach works quite nicely—I think I will be using this in the future. Play with the code on DartPad: #60
https://japhr.blogspot.com/2016/01/dart-doesnotunderstand-proxies.html
CC-MAIN-2017-47
refinedweb
701
56.25
It's possible for a header to be a symlink to another header. In this case both will be represented by clang::FileEntry with the same UID and they'll use the same clang::HeaderFileInfo. If you include both headers and use some single-inclusion mechanism like a header guard or #import, one header will get a FileChanged callback, and another FileSkipped. So that we get an accurate dependency file, we therefore need to also implement the FileSkipped callback in dependency scanning. Patch by Pete Cooper. Hi Pete, Is there any FileSkipped callback invocation that might trigger an unwanted file to be added as a dependency or it will only trigger for the symlink case? It seems that it works for hard links as well right? Is this intended or do you miss a -s? I plan to look into cleaning this up and addressing the review comments. Need to check if DepCollectorPPCallbacks has to be updated too. I suspect we need to call FileMatchesDepCriteria here too. FileSkipped is called when a file has a mechanism for single inclusion (header guards or #import) and it was already included. The callback will be triggered also for // a.h #ifndef A_H_ #define A_H_ #include "b.h" #endif // b.h #ifndef B_H_ #define B_H_ #endif // test.c #include "a.h" #include "b.h" But AddFilename performs Filename uniqueness check, so there will be no duplicate b.h in dependencies. If the same file is included by multiple paths, all paths can end up in dependency file. It is actually what we want to achieve and it shouldn't cause unnecessary rebuilds. It works when files have the same inode. Added -s to capture more common use case. Thanks for the detailed answers. LGTM
https://reviews.llvm.org/D30881
CC-MAIN-2020-45
refinedweb
290
68.67
In the last installment we discussed how language can express dynamic behavior using ActionExpression and how DLR treats such cases. In short summary, DLR will turn the ActionExpression into sophisticated cache which keeps updating itself as new runtime conditions occur. We left off at the point where DLR will cry for help when faced with a new runtime condition that it hasn't seen before and doesn't know how to handle. We even saw the actual code that does the crying (the call to "site1.UpdateBindingAndInvoke"), but beyond that all we know that the response comes in some form and that DLR uses the response to learn - to update the code of the delegate handling the dynamic behavior. Using a little trick that I revealed at the very end of the post, I showed you the actual code of the delegate and we saw that it is very similar to our original attempt to handle dynamic behavior using runtime helper methods. It is worth reiterating that the key is in the question that DLR asks: "Tell me how to perform the operation!" It is the format of the question which allows DLR to learn - to cache the answers and only ask for help when it has no appropriate cached recipe for handling runtime behaviors. In DLR we call these recipes Rules. When DLR asks the question how to perform a given dynamic behavior, it expects a rule back. It is the rule which in the generated code looks like: //// Adding strings//if (((obj1 != null) && (obj1.GetType() == typeof(string))) && ((obj2 != null) && (obj2.GetType() == typeof(string)))) { return StringOps.Add((string)obj1, (string)obj2); } The rule consists of a test and a target. Test is a condition which examines the arguments and target is an operation to be performed if the test succeeds. In the code snippet above, the test is the detection whether obj1 and obj2 are both strings and the target is a return of a result of the call to StringOps.Add. And to close the loop, the rule is expressed as the DLR Tree. When the DLR asks for help determining the exact operation for a given dynamic behavior at runtime, the response comes in the form of a rule which encapsulates two trees. One for the test, the other for the target. By passing "-X:ShowRules" command line parameter we can have DLR print a trace of all rules created during the program's execution so let's run small ToyScript code: def add(a, b) { return a + b} print add("Hello", "ToyScript") with "-X:ShowRules" and see that for the addition we get following rule as an output: //// AST Rule.Test// ((.bound $arg0) .is String && (.bound $arg1) .is String) //// AST Rule.Target// .return .comma { (.bound $retVal) = (String.Concat)( (String)(.bound $arg0), (String)(.bound $arg1), ) (Object)(.bound $retVal)}; If you put the test and target together, you can reconstruct the rule's behavior in the C#-like format: if (arg0 is string && arg1 is string) { return String.Concat((string)arg0, (string)arg1); which is exactly what you would expect for string concatenation. Notice that the generated code for the rule that was created when Python executed string addition is slightly different than the rule created for ToyScript addition. If we look at the rules generated when executing Python code, the rule for string addition will trace as: //// AST Rule.Test// ((((.bound $arg0) != .null) && (((.bound $arg0)).(Object.GetType)() == ((Type)String))) && (((.bound $arg1) != .null) && (((.bound $arg1)).(Object.GetType)() == ((Type)String)))) .return (StringOps.Add)( (String)(.bound $arg0), (String)(.bound $arg1),); yielding exactly the code we saw at the beginning of this post. The difference that may strike you right away is in the rule's test. When we ran ToyScript. the test came out as: "arg0 is string" and with Python, the corresponding part of the test is more complicated: "arg0 != null && arg0.GetType() == typeof(string)". Why the difference, or better yet, why the latter version? It turns out that when we experimented with different ways to implement the test we realized that JIT (the .NET just-in-time compiler) has an optimization for the latter case and while it looks longer in the source code and in the IL, it will amount to almost nothing in the final executable code. In the case of strings, value types, and generally all sealed types, the two are exactly identical, however the latter - longer - version will check for exact type identity, but "is" operator will succeed if the left operand is a subclass of the right, so there's a subtle difference here also. The last question we'll ask today is: "Who makes the rules?" When DLR requests a rule to be made for a given action which is being invoked with given arguments, it will first call "UpdateBindingAndInvoke" on the dynamic site. These method are in DynamicSite.Generated.cs. At the end of each method is a call to "context.LanguageContext.Binder.UpdateSiteAndExecute". The binder is what the individual language implements to define semantic for the dynamic behaviors determined at runtime. Not all answers do come from the language binder itself. The binder can simply decide that it doesn't know what to do with given operation on given arguments and pass the task up to the binder base class (ActionBinder) which implements large set of default behaviors, for example behaviors on 'standard' .NET objects such as what it means to get a member "Count" from an instance of System.Collections.Hashtable. It would be silly to expect each language implementer to provide the rules for all possible situations and that's why DLR provides the large default behaviors. The rule for string addition that we tried with ToyScript is actually implemented in ToyScript, but simply because the DLR default behaviors don't include string addition (in my opinion it is a bug and we'll fix it, but we haven't got to it yet) The implementation for the string addition in ToyScript is in ToyBinder.MakeRule<T>. You can see that the dynamic action "DoOperation" is singled out and passed to MakeDoRule<T> where addition is singled out and implemented as a construction of the tree that we saw above. When the language binder receives the request from the DLR to create the rule, it will look at what action is being performed (operation - add, subtract, ..., get member, call, ...) and then examine the arguments being passed in. With all that knowledge the language binder will construct the resulting tree that captures the semantic of the operation. Sometimes the rule is simple (such as our addition above), sometimes it can get pretty complicated. The DLR will cache the rule and only call back again if new circumstances arise. Charlie Calvert blogged about dynamic support in C# 4.0 . I love this for two reasons. One it will enable So, I can admit, I've been on a bit of a kick with compilers and such after my posts on DSLs, Compilers Good Stuff on Dynamic Language Runtime Your posts was of great help for me. It helps me to build my Simple DLR Language! Hi Martin, please could you clear some points? Here are 2 different calls of add function 1) exp = Ast.Add(left, right) 2) exp = Ast.Action.Operator(Operators.Add, typeof(object), left, right); As I can see, first is not using DynamicSite, so it is not cached and so maybe it is slower .. then questions is why is there Ast.Add(), Atc.Divison(), etc? 2nd. Txs, your articles are very helpful! At first if I understand well, there are functions supported by CLR which we can find under Ast class like Ast.Add(), Ast.Divide() etc. Then there are .. and please ignore last line of my comment...
http://blogs.msdn.com/mmaly/archive/2008/01/22/building-a-dlr-language-dynamic-behaviors-3.aspx
crawl-002
refinedweb
1,292
61.56
Tutorial: How to Create, Upload, and Invoke an AWS Lambda Function This tutorial guides you through the process of a typical AWS Lambda workflow, and provides you with first-hand experience using Lambda with the AWS Toolkit for Eclipse. The tutorial assumes that you have an AWS account, have already installed the AWS Toolkit for Eclipse, and that you understand the basic concepts and features of Lambda. If you’re unfamiliar with Lambda, learn more at the Lambda Create an AWS Lambda Project To begin a Lambda project, you first implement the code as a method in a handler class. The AWS Toolkit for Eclipse provides a new project wizard to help you create a new handler class. The Lambda project is a Maven project that uses a POM.xml file to manage package dependencies. You can use the Maven command line tool for building, testing, and deploying your application. For more information about Maven, see the Maven project documentation To create an AWS Lambda project On the Eclipse toolbar, open the Amazon Web Services menu (identified by the AWS homepage icon), and then choose New AWS Lambda Java project. Or on the Eclipse menu bar, choose File, New, AWS Lambda Java Project. Add a Project name, Group ID, Artifact ID, and class name in the associated input boxes. The Group ID and Artifact ID are the IDs that identify a Maven build artifact. This tutorial uses the following example values: Project name: HelloLambda Group ID: com.example.lambda Artifact ID: demo Class name: Hello The Package Name field is the package namespace for the AWS Lambda handler class. The default value for this field is a concatination of the Group ID and Artifact ID, following Maven project conventions. This field is automatically updated when the Group ID and Artifact ID fields are updated. For Input Type, choose Custom. For information about each of the available input types, see New AWS Lambda Java Project Dialog. Verify that your entries look like the following screenshot (modify them if they are not), and then choose Finish. As you type, the code in the Source preview changes to reflect the changes you make in the dialog box. After you choose Finish, your project’s directory and source files are generated in your Eclipse workspace. A new web browser window opens, displaying README.html(which was created for you in your project’s root directory). README.htmlprovides instructions to guide you through the next steps of implementing, testing, uploading, and invoking your new Lambda function. Read through it to gain some familiarity with the steps that are described here. Next, you implement the function in the HelloLambda Java project that was just created for you in Eclipse. Implement the Handler Method You use the Create New Project dialog box to create a skeleton project. Now fill in the code that will be run when your Lambda function is invoked. (In this case, by a custom event that sends a String to your function, as you specified when setting your method’s input parameter.) To implement your Lambda handler method In the Eclipse Project Explorer, open Hello.javain the HelloLambda project. It will contain code similar to the following. package com.example.lambda.demo; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class Hello implements RequestHandler<Object, String> { @Override public String handleRequest(Object input, Context context) { context.getLogger().log("Input: " + input); // TODO: implement your handler return "Hello from Lambda"; } } Replace the contents of the handleRequestfunction with the following code. @Override public String handleRequest(String input, Context context) { context.getLogger().log("Input: " + input); String output = "Hello, " + input + "!"; return output; } Allow Lambda to Assume an IAM Role For Lambda to be able to access your Lambda function, you have to create an IAM role that gives it access to your AWS resources. You can create the role in two ways, either through the AWS Management Console or by using the AWS Toolkit for Eclipse. This section describes how to create the IAM role in the console. See Upload the Code to create one using the AWS Toolkit for Eclipse. To create an IAM role for Lambda . From the Services menu, open the IAM console . In the Navigation pane, choose Roles, and then choose Create role. For Select type of trusted entity, choose AWS service, and then choose Lambda for the service that will use this role. Then choose Next: Permissions. For Attach permissions policy, choose AWSLambdaBasicExecutionRole. This allows Lambda to write to your CloudWatch Logs resources. Then choose Next: Review. Add a name for your role, such as hello-lambda-role, and a description for the role. Then choose Create role to finish creating the IAM role. Create an Amazon S3 Bucket for Your Lambda Code AWS Lambda requires an Amazon S3 bucket to store your Java project when you upload it. You can either use a bucket that already exists in the AWS Region in which you’ll run your code, or you can create a new one specifically for Lambda to use (recommended). You can create an Amazon S3 bucket in two ways, either through the AWS Management Console or by using the AWS Toolkit for Eclipse. This section describes how to create an Amazon S3 bucket in the console. See Upload the Code to create one using the AWS Toolkit for Eclipse. To create an Amazon S3 bucket for use with Lambda . From the Services menu, open the S3 console . Choose Create bucket. Enter a bucket name, and then choose a region for your bucket. This region should be the same one in which you intend to run your Lambda function. For a list of regions supported by Lambda see Regions and Endpoints in the Amazon Web Services General Reference. Choose Create to finish creating your bucket. Upload the Code Next, you upload your code to AWS Lambda in preparation for invoking it using the AWS Management Console. To upload your function to Lambda Right-click in your Eclipse code window, choose AWS Lambda, and then choose Upload function to AWS Lambda. On the Select Target Lambda Function page, choose the AWS Region to use. This should be the same region that you chose for your Amazon S3 bucket. Choose Create a new Lambda function, and then type a name for your function (for example, HelloFunction). Choose Next. On the Function Configuration page, enter a description for your target Lambda function, and then choose the IAM role and Amazon S3 bucket that your function will use. For more information about the available options, see Upload Function to AWS Lambda Dialog Box. On the Function Configuration page, choose Create in Function Role if you want to create a new IAM role for your Lambda function. Enter a role name in the dialogue box the Create Role dialogue box. On the Function Configuration page, choose Publish new version if you want the upload to create a new version of the Lambda function. To learn more about versioning and aliases in Lambda, see AWS Lambda Function Versioning and Aliases in the AWS Lambda Developer Guide. If you chose to publish a new version, the Provide an alias to this new version option is enabled. Choose this option if you want to associate an alias with this version of the Lambda function. On the Function Configuration page, choose Create in the S3 Bucket for Function Code section if you want to create a new Amazon S3 bucket for your Lambda function. Enter a bucket name in the Create Bucket dialogue box. In the S3 Bucket for Function Code section, you can also choose to encrypt the uploaded code. For this example, leave None selected. To learn more about Amazon S3 encryption, see Protecting Data Using Server-Side Encryption in the Amazon S3 Developer Guide. Leave the Advanced Settings options as they are. The AWS Toolkit for Eclipse selects default values for you. Choose Finish to upload your Lambda function to AWS. If the upload succeeds, you will see the Lambda function name that you chose appear next to your Java handler class in the Project Explorer view. If you don’t see this happen, open the Eclipse Error Log view. Lambda writes information about failures to upload or run your function to this error log so you can debug them. Invoke the Lambda Function You can now invoke the function on AWS Lambda. To invoke your Lambda function Right-click in the Eclipse code window, choose AWS Lambda, and then choose Run Function on AWS Lambda. Choose the handler class you want to invoke. In the input box, type a valid JSON string, such as “AWS Lambda”. Note You can add new JSON input files to your project, and they will show up in this dialog box if the file name ends with .json. You can use this feature to provide standard input files for your Lambda functions. The Show Live Log box is checked by default. This displays the logs from the Lambda function output in the Eclipse Console. Choose Invoke to send your input data to your Lambda function. If you have set up everything correctly, you should see the return value of your function printed out in the Eclipse Console view (which automatically appears if it isn’t already shown). Congratulations, you’ve just run your first Lambda function directly from the Eclipse IDE! Next Steps Now that you’ve uploaded and deployed your function, try changing the code and rerunning the function. Lambda automatically reuploads and invokes the function for you, and prints output to the Eclipse Console. More Info For more information about each of the pages that were covered in this tutorial, as well as a full description of each option, see the AWS Lambda Interface Reference. For more information about Lambda and about writing Java code for Lambda, see Authoring Lambda Functions in Java in the AWS Lambda Developer Guide.
https://docs.aws.amazon.com/toolkit-for-eclipse/v1/user-guide/lambda-tutorial.html
CC-MAIN-2020-45
refinedweb
1,656
63.9
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. optional C extension (generated by Cython) is available, then fastavro will be even faster. For the same 10K records it'll run in about 1.7sec. Usage import fastavro as avro with open('weather.avro', 'rb') as fo: reader = avro.reader(fo) schema = reader.schema for record in reader: process_record(record) You can also use the fastavro script from the command line to dump avro files. Each record will be dumped to standard output in one line of JSON. fastavro weather.avro You can also dump the avro schema: fastavro --schema weather.avro Limitations - Support only iteration - No writing for you! - No reader schema Hacking As recommended by Cython, the C files output is distributed. This has the advantage that the end user does not need to have Cython installed. However it means that every time you change fastavro/pyfastavro.py you need to run make. For make to succeed you need both python and python3 installed, cython on both of them. For ./test-install.sh you'll need virtualenv. Miki Tebeka <miki.tebeka@gmail.com>
https://bitbucket.org/vvkulkarninitk/ramifastavro
CC-MAIN-2017-39
refinedweb
199
69.68
Can generating a PDF file in a React app actually be simple? With KendoReact, YES! A popular question that I see pop up in React communities is how to export HTML, or parts of your React application, to PDF. Normally this can be a bit cumbersome, but I’m here to tell you that, thanks to KendoReact, we can now export any and all content in our React apps as easy as 1-2-3! Today’s blog post is the first of a three-part series that covers how you can generate PDF from HTML in React. As this is Part 1, today we will first create a quick app to be exported, add our React PDF Generator library and see how to generate a PDF file from HTML in React. In Part 2, we’ll build a sample invoice in our React app using HTML and CSS, then generate a PDF file based on this content. In Part 3, we'll learn how to export to PDF advanced React UI components such as the KendoReact Data Grid and React TreeList. In case you prefer to learn through videos rather than reading blog posts, I recorded a video series on how to generate PDF in React apps. Check out Part 1 of the PDF export video series right here. This may be obvious, but to export something to PDF you first have to have that something! As you have stumbled upon this article, I think you have a set of requirements already but for those of you curious here are some common scenarios I’ve seen that folks need to export React apps to PDF: There are, of course, tons more scenarios, but these are just some that I’ve discussed with React developers over the years. For this blog post, I’m going to keep things simple. Before we get started, I’m going to toss out a link to the following GitHub repo. For this blog post, we will be looking at the ExportExample component in the GitHub project. This will contain everything I’m talking about today, and then some (keep an eye out for more content around this project!). For those of you following along with this source code, we’ll be looking at the ExportExample component. Before jumping into the HTML and CSS that makes up my component, I just want to note that this example showcases the following types of HTML and exports it to PDF: <h1/>, <img />, <span />, etc. To kick things off, I’ve just set up a fresh project using create-react-app. All you need to follow along is the following HTML: <div className="app-content"> <div> <h1>KendoReact PDF Processing</h1> <img src={kendoka} <p>This is an example of text that may be <span className="neat-style">styled</span> </p> </div> </div> For the image, I’ve added the following image and defined it as the kendoka variable above. And here is our CSS that we can toss in to our existing App.css: .app-content { text-align: center; background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .page-container { margin: 1em; } .neat-style { color: rgb(255, 142, 166); font-weight: bold; text-decoration: underline; } .button-area button { margin-right: 10px; } .k-pdf-export { background-color: #282c34; } Now that we have our HTML and CSS, let’s get to the next step and add in KendoReact PDF Processing! To get started with generating a PDF in React apps, all we need to do is head over to the KendoReact PDF Generator documentation section. This gives you the instructions for how to install the KendoReact PDF Generator, and it also contains all the documentation articles you need to get started and dive deeper in to the world of React PDF generation on the client side—I highly recommended you bookmark this! That being said, the main bit of information we’re interested in is the following npm command: npm install --save @progress/kendo-react-pdf @progress/kendo-drawing @progress/kendo-licensing A quick note: You may have noticed the @progress/kendo-licensing package included here.. With that out of the way, we are ready to move on to the exporting. That’s right—we’re technically ready to rock and roll. As a bare minimum, all we need is to is add this one single package and one single import statement in our app and we can move on to the next step. Really, that’s all we need! One single package and you can skip straight to Step 3. However, I do also want to take this time to import one extra component, namely the KendoReact Button component. This is purely because I like the look and feel of the KendoReact button. As a part of this, I also installed one of the KendoReact themes to help with the overall look and feel of said buttons and any future KendoReact components. In this case, I added the KendoReact Material theme. If you’re interested in this partial step, or want to include this yourself, you can follow the installation instructions in the linked documentation article. Before I show you how you can export your React app to PDF (Step #3), I’m going to toss some new HTML markup at you. This includes some new KendoReact Buttons and just an extra <div> element, so nothing too crazy. <div className="app-content"> > </div> If you’ve followed along so far, all you would need to do is copy and paste everything above in to your own project and you’ll be good to go! Now that we have everything installed let’s actually get to a point where we can export content! First off, let’s make sure that we import the KendoReact PDF Generator library in our appropriate React component: import { PDFExport, savePDF } from '@progress/kendo-react-pdf'; The two items we have imported here represent two methods of exporting: PDFExport exports content as a component, and savePDF is used when we want to export things via a method. Let’s dive into each approach! All we need to do to export content via the component route is to find the content that we want to export and wrap around the HTML with <PDFExport></PDFExport> tags. You don’t need to wrap around your entire React app—just the content that needs to be exported. To give you an idea of what this looks like, here is our previous HTML wrapped appropriately: <div className="app-content"> <PDFExport ref={pdfExportComponent} > </PDFExport> </div> You may have noticed two things above: one is that we define a reference to this component via React’s ref prop, so we have ref={pdfExportComponent}, and we also define the paperSize to A4. Paper size can be set both via the same prop as I show here, or even through CSS (more on this in a future blog post), but since A4 is the most basic paper size, I just went ahead and added it here. Now that we’ve defined the area that we want to export, let’s go ahead and actually export content on a button click! First, we’ll define our onClick event handler: <Button primary={true} onClick={handleExportWithComponent}>Export with Component</Button> Next, here’s our actual handler: const handleExportWithComponent = (event) => { pdfExportComponent.current.save(); } What we are doing here is grabbing the ref variable we defined as a reference to our <PDFExport></PDFExport> tags. From there we use the available API to call .save() and our content will be exported! Similar to the component approach above, exporting via a method needs to define a parent HTML element that should contain all the content which is set to be exported. The quickest way to do this is to define a <div> element with a ref prop. Of course, we also need a button responsible for exporting on click, so we’ll add that in here as well. Expanding upon the HTML we have so far, we have: <div className="app-content"> <div ref={contentArea}> onClick={handleExportWithFunction}>Export with Method</Button> </div> </div> </div> Then, in our event handler we have the following code: const handleExportWithFunction = (event) => { savePDF(contentArea.current, { paperSize: "A4" }); } What this bit of code is doing is calling the React PDF Generator savePDF method and passing in the HTML through contentArea.current along with an object reflecting the options we want to set for the file we are exporting. In this case, I’m only setting the paperSize option to show you how this all looks in comparison to the declarative and component approach, but you have a huge list of options available to you that you can customize! That’s all there is to it! Through either approach, you now know how to generate a PDF file from HTML in React. Whether you prefer the declarative approach of wrapping around your content, or if you want to just pass in a block of HTML as content in to a method, the power of React PDF Generator is that any and all content can be exported using these two simple approaches. In Part 2 of this series, Generating PDF from HTML in React Demo: Exporting Invoices, we create a more advanced HTML and CSS layout and see how we can customize the size of the layout of the generated PDF file via CSS and even do so dynamically!.
https://www.telerik.com/blogs/generating-pdf-react-easy-as-1-2-3
CC-MAIN-2022-05
refinedweb
1,585
56.79
How it works - A subclass of list to add Vector instances (player locations) - creates/loads a JSON-formatted, Map-based <mapname>.json file in/from your ../addons/source-python/data/plugins/<plugin>/spawnpoints folder - when it saves the JSON file, it converts the Vector instances to lists of [X, Y, Z] coordinates to get the following style:As you can see, the JSON module can save them readable. Code: Select all [ [ -400.03125, -162.86436462402344, 71.14938354492188 ], [ -415.63861083984375, -438.2723693847656, 75.74543762207031 ], [ -162.5885467529297, -988.04736328125, 130.56640625 ] ] Syntax: Select all import json # use indent=4 to get the values as above: json.dump(list_dict_or_whatever, file_object, indent=4) - when it loads the JSON file, it will convert the [X, Y, Z] lists back to Vector instances Files in ../addons/source-python/plugins/<plugin>: Since I have named my plugin flashfunsp, for me it would be: Code: Select all <plugin>.py spawnpoints.py Code: Select all flashfunsp.py spawnpoints.py I'll use flashfunsp as "THE" plugin name for the tutorial's sake :) The Code: spawnpoints.py - 1. Imports Syntax: Select all # Python imports # to load and save a Python list to a file, use the JSON library from json import dump as json_dump from json import load as json_load # Source.Python imports # Mathlib provides the Vector class from mathlib import Vector # ../addons/source-python/data/plugins from paths import PLUGIN_DATA_PATH - 2. Global Variables Syntax: Select all # I'll use the path to my FlashFun.SP plugin: # ../addons/source-python/data/plugins/flashfunsp/spawnpoints spawnpoints_path = PLUGIN_DATA_PATH.joinpath("flashfunsp", "spawnpoints") # some constants: # maximum distance for spawning players DISTANCE_SPAWN = 100.0 # maximum distance to add vectors DISTANCE_ADD = 200.0 # maximum number of vectors per map VECTORS_MAX = 35 - 3. The Class Syntax: Select all # ../addons/source-python/plugins/flashfunsp/spawnpoints.py class _SpawnPoints(list): """ Extends list for handling Vector instances as spawnpoints. """ def __init__(self): """ Instance initlaization """ # call list's __init__() super(_SpawnPoints, self).__init__() def append(self, vector): """ Checks the size of this list before appending the vector. """ # don't continue if the addition would exceed the limit # or it already exists in this list if len(self) >= VECTORS_MAX or vector in self: return # else, add the vector to the list super(_SpawnPoints, self).append(vector) def load(self, mapname): """ Loads the spawnpoints/<mapname>.json file if it exists and adds the vectors to this list. """ # clear the list if it's not empty if self: self.clear() # get the full file path file_path = spawnpoints_path / "{0}.json".format(mapname) # don't continue if it doens't exist if not file_path.isfile(): return # open the file for reading with file_path.open() as file_object: # store the file's contents (lists of [X,Y,Z] coordinates) contents = json_load(file_object) # loop through the file's contents for coords in contents: # convert the coords to a Vector instance # and append them to this list self.append(Vector(*coords)) def save(self, mapname): """ Writes vectors from this list to the spawnpoints/<mapname>.json file. """ # don't continue if there is nothing to save if not self: return # open the file for writing with spawnpoints_path.joinpath("{0}.json".format(mapname)).open("w") as file_object: # dump the vectors from this list as [X,Y,Z] lists to it json_dump(list(map(lambda vector: [vector.x, vector.y, vector.z], self)), file_object, indent=4) def check(self, vector): """ Returns whether the vector can be added to this list. """ # is the vector already in this list? if vector in self: # return False to stop the addition return False # loop through each vector in this list for check in self: # is the check too near? if check.get_distance(vector) < DISTANCE_ADD: # if yes, return False return False # else return True to add it return True # get an instance of the class spawnpoints = _SpawnPoints() Now we have defined a SpawnPoints class that can safely load from and write to JSON files in the ../addons/source-python/data/plugins/<plugin>/spawnpoints folder, and check if a vector can be added to the list. But one feature is still lacking: checking if there is a free SpawnPoint, and teleporting the player there. You can add a function for this to the spawnpoints class, but I don't really feel that it should be there. It should be located either in the main file of the plugin or somewhere else, e.g. utils.py - in my opinion. The function I came up with is a RECURSIVE function! If you haven't head anything about recursive programming, visit's_Tutorial_for_Python_3/Recursion Anyways, here's the function I came up with (in my case within flashfunsp.py): Syntax: Select all # we'll need to choose a RANDOM vector # so let's import choice from random and give it a better name from random import choice as random_choice # import the spawnpoints instance in spawnpoints.py: from flashfunsp.spawnpoints import spawnpoints # we'll need the distance to check from flashfunsp.spawnpoints import DISTANCE_PLAYERS # give us the map name, please (global_vars.map_name) from core import global_vars # let us know when the map has changed from listeners import LevelInit # and when it's about to change from listeners import LevelShutdown # we want to loop through all alive players' locations from filters.players import PlayerIter # store a PlayerIter() generator for alive players that returns their locations playeriter_origins = PlayerIter(is_filters="alive", return_types="location") def get_random_spawnpoint(tried=0): """ Returns a random vector to spawn on. """ # is there anything to check? if not spawnpoints: # if not, return None return None # did we reach the maximum number of tries? if tried == len(spawnpoints): # if yes, return None return None # else, get a random vector vector = random_choice(spawnpoints) # loop trough alive player origins for origin in playeriter_origins: # is a player too near? if vector.get_distance(origin) < DISTANCE_SPAWN: # if yes, go recursive to find another vector... return get_random_spawnpoint(tried + 1) # retrun the random vector return vector Usage Syntax: Select all from events import Event from players.helpers import index_from_userid # somewhere in the script: def get_random_spawnpoint(tried=0): # .... """ Add vectors as SpawnPoints """ @Event def player_death(game_event): # get a PlayerEntity instance of the victim victim = PlayerEntity(index_of_userid(game_event.get_int("userid"))) # add the victim's location as a spawnpoint if it passed the check if spawnpoints.check(victim.origin): spawnpoints.append(victim.origin) """ Teleport the player to a spawnpoint """ @Event def player_spawn(game_event): # get a PlayerEntity instance player = PlayerEntity(index_of_userid(game_event.get_int("userid"))) # is the player alive and on a team? # TeamID 2 = Terrorists, 3 = Counter-Terrorists, for CS:S if player.get_property_int("pl.deadflag") or player.team < 2: # if not, don't go any further return # get a random vector vector = get_random_spawnpoint() # is the vector valid? if not vector is None: # if yes, teleport the player there player.origin = vector """ Load the <mapname>.json file """ # on load def load(): spawnpoints.load(global_vars.map_name) # and on LevelInit @LevelInit def level_init(mapname): # note: here we don't have to get the map name from global_vars since it was passed to the function spawnpoints.load(mapname) """ Save the <mapname>.json file """ # on unload def unload(): spawnpoints.save(global_vars.map_name) # and on LevelShutdown @LevelShutdown def level_shutdown(): spawnpoints.save(global_vars.map_name) That's it! If you have any questions, feel free to post them :)
http://forums.sourcepython.com/viewtopic.php?f=31&t=751&p=4203&sid=938ff62122c5204355ffd0e8fec88d71
CC-MAIN-2017-13
refinedweb
1,195
57.06
The next few SDL tutorials will take a side step from pure Empire coding and look at implementing a Graphical User Interface (GUI). This will be needed for Empire so it's worth looking at on its own. Note, if you are creating your own SDL project (for these sources in Visual Studio 2010 or Visual C++ Express 2010), then you should see How to setup Visual Studio 2010/Visual C++ 2010 Express with SDL. - Want to know more about SDL? SDL Has No Native GUI We've seen in previous Empire tutorials how to use the mouse and keyboard but think how clumsy Windows would be if we had to code everything from scratch. Unfortunately with SDL we do, but that's good in a way. We can leave out all the messy stuff and focus on developing a simple GUI library. We want to be able to easily create a panel and populate it with working controls. What controls do we need? Note there's no code with this tutorial. The next one will have some working controls and will include the code. What Controls are needed? Not the full functionality of Windows GUI, that's for sure. A few buttons, check boxes, a list of clickable text, labels etc. Below is my suggested list. If you want more controls then within a tutorial or two you should have the knowledge and code to create your own. If you do, why not send me the code and I'll add it to this and give you credit. List of Desired GUI Controls This is what I think we need. By the end of implementing these, I may come up with an extra one or two but for now this is the list. - A plain panel - A simple button. Something you click to do something. - A clickable text command. - A check box. Something you can tick or untick - A clickable list box. We'll keep it simple so no scrolling. - A popup box asking a question. - A Text entry box. - A text label - Display an image (not technically a control). That's quite a list. I know a panel isn't really a control (technically controls should be clickable) nor is a displayable graphic but it's useful to have. Remember we're not trying to reimplement Windows here, just creating a GUI toolbox. Using the GUI If I get this right it should be easy to include a library then make calls to create a "Form" (Not a Windows form,- my name for Panel with GUI controls) then add the controls, along with functions they call when clicked etc. Something like: #include "sdlgui.h" ... ppanel = createpanel(x,y,width,height,color,false); pcontrol prodbtn = ppanel-> addbutton("Set Production",x,y,width,height,color, &addproduction); pcontrol checkautoprod = ppanel->addcheckbox("Auto Production",width,&autoprod); ... gui.add(ppanel); First we create a panel. The last parameter is a modal/non modal flag. If true then all input stops until this form is closed. It's for use in a right click popup on units and cities in Empire. The createpanel() returns a pointer that is used for adding controls to this panel. All the add controls function return a pointer to themselves. You may not need this For instance the addcheckbox ()function is passed the name of an int variable (autoprod). If you check the Auto Production checkbox, then autoprod is set to 1 etc. Having a pointer though lets you alter labels etc, or even the checkbox variable and you can have the panel remove the control from it's list (see below). How in this GUI implemented? Each of the controls is implemented as a struct, holding pointers for event handlers, checkbox variables, self draw functions, text labels plus variables for the various state values, width, height and x,y positions. The panel holds a single linked list of these structs and has a function render() that walks the struct list and tells each control to render itself. It's a little like object oriented programming. By default the library provides functions to render each type of control and plugs it into the render function pointer in the struct. You can alter it to point to your own function should you wish making it bit like virtual functions. The main technique I use here is function pointers. There's no GUI designer provided with this (anyone care to write one?), you have to manually figure out the size of controls with a bit of "suck it and see". Fonts and Text Just a word about this. Previously I've used my own mono width, single size font but that is a bit 1980s. So we'll be using SDL_TTF and some open fonts from the GNU Free UCS Outline fonts. Hurray for GNU! This is not quite as quick to execute as my mono width font but it will make it look nicer and let us use different font sizes. I'm still looking to have the scrolling map (and control panel) running at 60 fps. In the next tutorial I'll have a simple working example with some of the controls. - Follow the link to find out more about our free Game Programming tutorials.
http://cplus.about.com/od/programminggames/a/sdl-gui-tutorial-1.htm
CC-MAIN-2014-15
refinedweb
876
74.29
Best Practices for JNDI namingrobert mark waugh May 14, 2002 3:47 PM Hi all: In extension of a previous post of mine (see the FAQ forum; this one is probably more appropriate, but oh well!) I have another best practice question for the community at large. It seems that you have pretty much general control over where things are placed in the JNDI resolution directory. You don't have to specify any sort of hierarchy, and you can name things in whatever way you choose. However this obviously doesn't seem to be a good way to do things. Much like how package naming follows a conventional best practice and file systems are laid out in a standardized way, so it seems should your JNDI names. What are some of your methods for choosing where to place things? In the past, I have done something similar to the package naming structure... and often times mirroring it for EJB components: /com/waughonline/services/jdbc/CatalogConnectionPool-A /com/waughonline/greeting/HelloWorldHome (class is com.waughonline.greeting.HelloWorldHome) How about others? thanks, robert 1. Re: Best Practices for JNDI namingChris McCafferty Jul 19, 2002 10:07 AM (in response to robert mark waugh) Hi, I've seen a couple of 'naming schemes' in projects for JNDI. One common one is to go "com/mycompany/package/structure/etc/MyBeanClass", much as you laid out. This is all well and good...until the java implementation changes to NewBeanClass. Then you are stuck with a class name/jndi name mismatch. Or you have to change the clients of that bean. Another one I've seen is /BeanName, which has the benefit of being a bit more readable and simpler. One of the more amusing things to note is that JNDI is case sensitive. This led to some of our Windows developers (unused to case sensitivity in file-like systems) capitalising the application name in JNDI, and unix programmers keeping things lower case. And when you're debugging a log, "Application/Bean" looks awfully similar to "application/bean"! 2. Re: Best Practices for JNDI namingNoel Hebert Jul 23, 2002 6:50 AM (in response to robert mark waugh) Robert, It really should not matter what *you* use to define your JNDI namespace. What really matters is what the *deployment* environment uses as a namespace standard. If you control both, then whatever you use is right for you. If you don't then you must use the deployment environment standards. Or you could use the ENC and have the best of both worlds! What I mean is you should as a matter of best practice refer to your EJBs and resources (JMS queues for example) using the ENC or Environment Naming Context. This means referring to your EJB's via an alias. Then at deployment time, map that alias to something in the global JNDI namespace. For example if I have an EJB Foo that refers to an EJB Bar, then in Foo I would look up Bar using "java:comp/env/ejb/Bar". "java:comp/env" refers to the ENC which you can think of as a "private" namespace known only to Foo. At deployment time, in the case of JBoss, you can map "ejb/Bar" in the jboss.xml to be mapped to "x/y/z/Bar" or maybe "x.y.z.WhoCares" or whatever. The point is, you can refer to it in your code any way you want to! I use JBoss to quickly proto-type ideas, then deploy them into an IBM WebSphere environment. I have no control over the IBM namespace. Using the ENC I really don't care. Because at deploy time, I can take my EJBs, JMS thingys, JDBC thingys which I named *my way* and map them to "their" namespace standards and *not* change a line of code! The ENC is an under used facility which makes moving J2EE components between different J2EE deployment environments (i.e. app servers) extremely easy. Have a quick read of Scott Stark's chapter on JBoss Naming Services in the JBoss 3.0 Quick Start Guide for a nice introduction to the ENC. The examples he uses are great. Cheers, Noel. 3. Re: Best Practices for JNDI namingBill Siggelkow Jul 23, 2002 11:45 AM (in response to robert mark waugh) Use of the ENC is an excellent point. Too often I have seen code that is dependent on a global (aka absolute) JNDI name. Often this is done to "make things easier". For example, people will provide a EJBHomeFactory that is used to provide easy lookup of home interfaces. However, these implementation often rely on the absolute JNDI name. It is reasonable to want to provide a simplified interface for accessing EJBs -- however, such implementations should do so in a way that does not hard-wire the code to the deployment. Also, the actual code to perform a lookup of an EJB (or any other object in JNDI) is only a couple of lines ... in many cases, the reasons for having the factory interface is simply because the developers accessing the EJBs have not been educated on how to use JNDI ... it is as simple (almost :)as the following two lines ... Context ctx = new InitialContext(); FooHome home = (FooHome) PortableRemoteObject.narrow( ctx.lookup("java:comp/env/foo"), FooHome.class); 4. Re: Best Practices for JNDI namingBill Siggelkow Jul 23, 2002 11:49 AM (in response to robert mark waugh) I would be careful about using a deep hierarchy for a JNDI name. For a package it doesn't really matter as it is not a "true" hierarchy but merely implied. For JNDI, however, using a name like 'com/foo/app/services/bar' means JNDI actually has to create 5 contexts. Instead, I suggest using a shorter name, but still try and maintain uniqueness.
https://developer.jboss.org/thread/68900
CC-MAIN-2018-43
refinedweb
971
64.1
This appears to be an Android+Cordova issue, which is not something we can fix for you. These threads are particularly useful: The changes being suggested are to the AndroidManifest.xml file, not to your config.xml file. To implement such changes into the AndroidManifest.xml file you need to use some special PhoneGap Build-specific notation withing your config.xml file, as outlined by this PhoneGap Build doc page > < (note this requires adding an additional namespace fragment -- xmlns:android="" -- to the <widget> tag in the config.xml file to avoid errors with PhoneGap Build). thank you now I'm trying your suggestion. I will update if it works. But...everything I'm changing manually, will be automatically put into config.xml by next XDK release? (in example density for icons, in example this adding made for the LaunchMode and namespace and so on...). I'm trying to figure out that I will put this into config.additions and they will be put into config.xml file ready to be exported, is it? tell me yes please We are fixing the density issue and I've requested that the additional namespace be added to the <widget> tag, as well as several other fixes that are needed for proper operation of the export feature. In addition, I have an external script you can use that I'm currently updating, in order to address changes that do may be delayed in the product. Regarding the specific instructions you are adding to change the LaunchMode, that is something that is specific to your application, so having us add those tags does not make sense for all users. However, you can put those lines into the intelxdk.config.additions.xml file and they will be transferred, untouched, to the exported config.xml. Other than a few items specific to Crosswalk, everything that is in your intelxdk.config.additions.xml file is transferred without change into the exported config.xml (do a compare and you'll see what I mean). Thank You, I've used apktool to see difference between standard XDK build apk and standard (no modifications) PhoneGap build apk. In particular I've seen difference in manifest.xml file 1) XDK builds with launchmode = "singleTop" 2) Phonegap builds without launchmode option (so standard is assumed) So the problem is not only mine, but for everyone, because the behaviour of the app changes. Anyway the problem is in example when I call custom url scheme to open app and pass to it parameters. Everytime a new instance is open and is pushed on history stack, so going back and back you fill find the original app opened. This is catastrofic because I handle back and push states hello I fixed it by adding namespace to widget tag (as You suggested) and by adding <config-file <activity android: </config-file> to the config.xml of exported zip. but anyway adding it in config.additions.xml is not exported correctly:( infact the snippet is not transferred to config.xml if declared outside android platform tag in config.additions.xml; if I declare it into android platform is transferred without activity tag (the most important thing to transfer). But PhoneGap needs it OUTSIDE the platform tag. You're correct, it's not getting transferred from the additions file to the config file. I'm just finishing a Node.js script that will work with that situation. I believe it is not getting transferred by the export option because they are using a full XML parser to process the contents, whereas my script is simply doing an AWK-like transformation of the files. There's a draft version of the script I am referring to here > < but it won't work the way you want it to until I get the 3.0 version posted, which I'm trying to finish this week. At that point the instructions will change dramatically on that README, so you'll know when it is ready to try. ok, anyway I think you should add for everyone the snippet here, because it lets PhoneGap build to work as XDK build <config-file <activity android: </config-file> and of course namespace in widget tag. This update fixes SingleTop launch mode and the title bar at starting that I posted here What you think about it? I need to check with the build engineer to get the details on how we are setting that parameter in the build system. Alessandro, try adding this preference tag to your intelxdk.config.additions.xml file, it should not be removed and should do what you want: <preference name="AndroidLaunchMode" value="singleTop"/> See these cordova config.xml docs > < and this sample additions.xml file > < I've confirmed what you've found. It appears that PhoneGap Build is stripping or ignoring that standard Cordova CLI preference tag. I built with a local copy of CLI to confirm, and it behaves as expected. I'm asking Adobe why this is the case and will see if this is something we can get into the upcoming hotfix, but I am not able to promise it will be part of that fix, we're trying to address several very pressing issues ASAP.
https://community.intel.com/t5/Software-Archive/PhoneGap-Android-Launchmode-serious-problem/m-p/1063222/highlight/true
CC-MAIN-2020-40
refinedweb
870
64.1
Hi Rhys, Thanks for the plugin. I’ve been using it for quite a while now to start up some screens running presentations. Regrettably one of the 2015 model Panasonic TX-42AS600E screens was broken beyond repair and I had to replaced is with a new model; TX-43FXW654. Sadly the plugin doesn’t seem to work on this model, it reports: VieraControl: Failed to connect to TV on 192.168.1.11:55000 The android TV remote 2 app works fine on the new screen and when sniffing the packets from the android device it seems the IP and port are ok. You can view the packet here: Could it be there was some update in the protocol? I did notice the “GetEncryptSessionID”,cou;d this be the problem? Your help would be much appreciated. Does anyone know if this is still supported on recent Viera systems such Panasonic Viera TX-40ESW404? Hey Rhys I am very late here! But – great work!! I had just begun compiling a powershell script to call from Eventghost. This is much better. What I think is missing, to really unlock the potential – is a “GET” so we can query the status. Example: when Kodi starts,or when the PC wakes, *if* the TV is in standby, turn it on. Currently the power is a toggle so we can’t do anything to ensure that the TV is on and set to the correct inputs etc. Happy to contribute to your project if you are still interested 🙂 I am a beginner in SOAP but learning using this example. Cheers! Matt Hi Thanks for this – it works great with my Panasonic and helps heaps with my MediaPortal integration. I’ve been searching around and have stumbled across a couple more verbs the TV understands which forces it to a particular HDMI Input (Yay). Based on some info I found at I added: self.AddAction(HDMI1) self.AddAction(HDMI2) self.AddAction(HDMI3) and class HDMI1(eg.ActionBase): name = “HDMI1” description = “HDMI1” def __call__(self): self.plugin.SendCommand(“NRC_HDMI1-ONOFF”) class HDMI2(eg.ActionBase): name = “HDMI2” description = “HDMI2” def __call__(self): self.plugin.SendCommand(“NRC_HDMI2-ONOFF”) class HDMI3(eg.ActionBase): name = “HDMI3” description = “HDMI3” def __call__(self): self.plugin.SendCommand(“NRC_HDMI3-ONOFF”) to your EventGhost script and Presto I can now choose the HDMI Input. Could you please incorporate these into your plugin for other Panasonic users. Thanks Ken Hi Ken, Sorry for the late reply. Thanks very much for this, really helpful. I’ll try to update the plugin soon. Cheers, Rhys Dear Rhys, Thanks for this great solution. I’ve been searching the web for hours and finally stumbled upon your solution for automating my Viera with EventGhost. It works great, only I reallly like to control multiple TV’s from the same macro script because I’m trying to setup a Near Casting system for a Diner with multiple screens. Hope this is possible, many thanks in advance. Beste regards, Michael Ots
https://blog.rhysgoodwin.com/htpc/eventghost-plugin-for-panasonic-tv-control/?share=twitter
CC-MAIN-2019-18
refinedweb
498
67.15
I searched but didn't found a clear answer or an example. I want to make a seperate file for inputs, so I did a INPUT() function that links to the other file (input.c als tried input.h), but always I had errors, can someone please give me an example for placing the input as a functon or some other method , witch will work. Thanks very much. Im not quite sure i understand the question. How does your file-structure look at the moment?In general, afaik, it works like this:The .c/cpp file contains the "body" of the functions, and then you include file.h in any file where you want to use test(). //file.c #include "file.h" void test() { printf("whatever\n"); } //file.h void test(); EDIT: ah yes, also header guards -------Sweden: Free from the shackles of Democracy since 2008-06-18! /* input.h - input header */ /* include guard, to prevend this file from being include more then once * inside singe source file */ #ifndef INPUT_H #define INPUT_H /* declaration */ void input(void); #endif /* input.c - input source file */ #include "input.h" void input(void) { /* ... */ } /* main.c */ #include "input.h" int main(void) { /* ... */ input(); /* ... */ return 0; } END_OF_MAIN() I still have errors, INCREDEMENT_X undeclared,... my codes://///////////////////////////////////////////////////#ifndef INPUT_C#define INPUT_Cvoid INPUT(){while (game_time > 0) {if (key[KEY_LEFT])sprite_position.x -= INCREMENT_X;if (key[KEY_RIGHT])sprite_position.x += INCREMENT_X;if (key[KEY_UP])sprite_position.y -= INCREMENT_Y;if (key[KEY_DOWN])sprite_position.y += INCREMENT_Y;if (key[KEY_SPACE])sprite_position.y += 0.30; if (key[KEY_ESC])user_wants_to_quit = TRUE;--game_time;}#endif//////////////////////////////////////////////////////#include <allegro.h>#include "input_now.c"#define INCREMENT_X 0.25#define INCREMENT_Y 0.25volatile int game_time;volatile int sec_counter;typedef struct{double x,y;}VECTOR;int init_timer(void);void game_timer(void) {game_time++;}END_OF_FUNCTION(game_timer);void game_sec_timer(void) {sec_counter++;}END_OF_FUNCTION(game_sec_timer);int init_timer(void) {install_timer();if (install_int(game_timer, 1) < 0)return 1;if (install_int(game_sec_timer, 1000) < 0)return 1;sec_counter = 0;game_time = 0;LOCK_VARIABLE(game_time);LOCK_VARIABLE(sec_counter);LOCK_FUNCTION(game_timer);LOCK_FUNCTION(game_sec_timer);return 0;}int main() {int current_fps = 0;int fps = 0;int user_wants_to_quit = FALSE;BITMAP* le_sprite;BITMAP* buffer;unsigned long last_sec_counter = 0;VECTOR sprite_position;allegro_init();install_keyboard();if (init_timer() != 0) {allegro_message("Erreur lors de l'initialisation des timers!");return 1;}install_mouse();set_color_depth(16);if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640,480, 0, 0) != 0) {allegro_message("Impossible d'initialiser le mode vidéo!");return 1;}le_sprite = load_bitmap("ship105.bmp", NULL);if (!le_sprite) {set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);allegro_message ("Erreur : imposible de charger le bitmap!");return 1;}buffer = create_bitmap(SCREEN_W, SCREEN_H);if (!buffer) {set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);allegro_message ("Erreur : imposible de créer le buffer!");return 1;}sprite_position.x = SCREEN_W / 2;sprite_position.y = SCREEN_H / 2;/* Boucle principale du jeu */while (user_wants_to_quit == FALSE) {INPUT();}if (sec_counter != last_sec_counter) {fps = current_fps;last_sec_counter = sec_counter;current_fps = 0;}current_fps++;clear_bitmap(buffer);draw_sprite(buffer, le_sprite, sprite_position.x, sprite_position.y);text_mode(-1);textprintf_centre(buffer, font, SCREEN_W / 2, 0, makecol(195,125,255), "FPS : %d", fps);textprintf_centre(buffer, font, SCREEN_W / 2, 20, makecol(195,125,255), "Mouse coordinates : %d,%d", mouse_x,mouse_y);blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);}destroy_bitmap(le_sprite);destroy_bitmap(buffer);return 0;}END_OF_MAIN();////////////////////////////////////////////////////// Please use the code tags. Until then i can tell you straight away that it's bad practice to include c files. it's just EVIL.As we said, have a header file (.h) with the declaration (ie, void INPUT();, header guards and such) and a c file which you compile naturally. And then include the header file in any file you want to use INPUT(). You should also consider using a more ... normal namning convention, all-cap names are usualy macros or typedefs. Also, you add increment_x after you include the file, so it never sees them. You should use something like this: // input.h #ifndef INPUT_H #define INPUT_H #define INCREMENT_X 0.25 #define INCREMENT_Y 0.25 typedef struct{ double x,y; }VECTOR; extern int user_wants_to_quit; extern volatile int game_time; #endif --RB光子「あたしただ…奪う側に回ろうと思っただけよ」Mitsuko's last words, Battle Royale If you don't know how to use the code tags, look here. --"The basic of informatics is Microsoft Office." - An informatics teacher in our school"Do you know Linux?" "Linux? Isn't that something for visually impaired people?" You know, your life would be so much easier if you just used STL and OpenLayer. ----<:=The Sword of Fargoal -- Saucelifter -- Now, I made paste what ReyBrujo wrote, I had only one error (and few warnings), it didn't recognize the input function, I made the function extern void INPUT(); in main.cpp. Now the program begins but without input. What is the cause? You don't make function by using extern (or just ending it with semicolon without body), you tell compiler that it's placed in another file. In ReyBrujo code, in input.h INPUT takes pointer to VECTOR, but in main.cpp it's used without parameters. EDIT: You need to change this in main.cpp while (user_wants_to_quit == FALSE) { INPUT(&sprite_position); Oops! Sorry I made the correction, but I have the same problem, I rewrite the code: // input.h #ifndef INPUT_H #define INPUT_H #define INCREMENT_X 0.25 #define INCREMENT_Y 0.25 typedef struct{ double x,y; }VECTOR; extern int user_wants_to_quit; extern volatile int game_time; #endif Add void INPUT(VECTOR *); to input.h. Where exactly? I placed iy before, in the vector and at the end of the vector but I had warnings at the compiler couldn't make an .exe. Thanks. After the VECTOR. Remember to link against Allegro libraries. I have the same problem: Don't forget to do a full recompile after you (only) change a header file. Yet, I have the same problem, can you please try to compile it on your system?I have: no new line at end of file. That is not an error, but a warning. Put a ENTER at the end of all your files. I did what you said, without succes, then I saw that I forgot in input.c the ifndefs, so: I also recompiled all (with and without the addition of ifndefs to input.c), I have: undefined reference to `INPUT(VECTOR*)' You don't need the ifdef/endif in the C files, only in the headers (H files). As for the error, have you compiled the input.cpp too? The INPUT(VECTOR *) function is inside input.cpp, if you don't compile it, you will get that undefined error. And remove that END_OF_FUNCTION(INPUT). I don't even have a input.cpp, only the main.cpp, how must it be written?Thanks very very much. Your input.cpp file is the one you posted here. Just add it to your project (I am guessing you are using MSVC6). The input.c I changed to input.cpp, and it worked. Thanks!!(I use codeblocks)
https://www.allegro.cc/forums/thread/558270
CC-MAIN-2018-17
refinedweb
1,115
61.53
Here's a C program to find sum of all the elements of a matrix using For Loops and Nested Loops with output and explanation. # include <stdio.h> # include <conio.h> void main() { int mat[10][10] ; int i, j, row, col, sum = 0 ; clrscr() ; printf("Enter the order of the matrix : ") ; scanf("%d %d", &row, &col) ; printf("\nEnter the elements of the matrix : \n\n") ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) scanf("%d", &mat[i][j]) ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) sum = sum + mat[i][j] ; printf("\nThe sum of the elements in the matrix is : %d", sum) ; getch() ; } Output of above program - Enter the order of the matrix : 3 3 Enter the elements of the matrix : 1 2 3 4 5 6 7 8 9 The sum of the elements in the matrix is : 45 Explanation of above program - In this program we’ve several variables. Let’s first understand the purpose of each variable – - mat[10][10] – is a two dimensional integer array representing a matrix containing 10 rows (first index) and 10 columns (second index). This is how matrices are represented in C. - i and j – are loop variables of two different for loops where i points to the rows and j points to the columns of our matrix. - row and col – are the number of rows and columns respectively. These values are entered by user. - sum – holds the sum of all the elements of our matrix mat[10][10]. It’s value is initialized to 0. Now, the program first asks the user to enter the order of the matrix i.e. number of rows and columns and stores these values in row and col variables respectively. Next step is to enter the values in our matrix. To do this, we use a nested for loop where the outer for loop (loop variable i) points to every row of the matrix and inner for loop (loop variable j) points to every column of the matrix. (See this program to understand How to Enter and Print Values in a Matrix) Once you have entered the values in your matrix it’s time to calculate the sum of all elements in the matrix. For this, we again use another nested for loop like we did before. Inside this nested for loop we add each element to the value of variable sum and update its value. After this nested loop terminates, we have the sum of all elements of our matrix “mat[10][10]” and print its value. Hello There, Brilliant article, glad I slogged through the C Programming Tutorial it seems that a whole lot of the details really come back to from my past project. write a c program that finds number of any paragraph and sentence in a text. I'm new at this and I really need to do this. Follow my new blog if you interested in just tag along me in any social media platforms! Thank you, Heena Can i get tracing of a program
http://cprogramming.language-tutorial.com/2012/03/find-sum-of-all-elements-of-matrix-in-c.html
CC-MAIN-2021-10
refinedweb
516
66.98
Slick is most popular library for relational database access in Scala ecosystem. When we are going to use Slick for production , then some questions arise like where should the mapping tables be defined and how to join with other tables, how to write unit tests. Apart from this there is lack of clarity on the design guidelines. In this blog post , I am sharing my experience how we are using slick on production. Let us start the example with a simple scenario. Consider there are three tables Bank , BankInfo and BankProduct. Bank and BankInfo have one to one relation (You could possibly argue that we do not need this distinction but for now let us assume that it is meant to be that way for the example) , Bank and BankProduct have one to many relationship. One of the design goals or best practice that we want to follow is that we would like to keep our database access code database agnostic. What does that mean? It means that our Slick code should not care about the ultimate database that we are using. It could be PostgreSQL, MySQL , SQlServer or H2 for unit testing. For the database access Slick need two things: 1) Database drive 2) Slick driver Lets keep abstract from database access methods : JdbcProfile is trait. All drivers for JDBC-based databases implement this profile. Lets define database access methods Bank repo: Bank and BankInfo have one to one relation. Lets define BankInfo repo and write joins with bank repo: Bank and BankProduct have one to many relationship. Lets define BankProduct repo and write joins with bank repo: As we have see all database access code are database independent we don’t mention database name any where in code. It is time to write unit test.For unit testing, It is good if we use in memory database like H2. There are lot framework for writing unit test, I am using ScalaTest(It is my preference). To avoid boilerplating in unit test, define concrete H2 database driver implementation at one place for all repositories like: H2 is in memory database so we need to create database schema each time when you want to run unit test. The good way is provide a script to H2 database so when H2 is going to start it will automatically run this script.Same as schema script we can provide a script for data set which is required for testing purpose. Lets write unit tests of bank repo: Similarity we can write unit test for all repositories. For production use,We need to define concrete database driver implementation. Here, I am taking MySQL as production database. Database Configuration setting look like: Slick recommend, Connection pool size should be larger than the thread pool size.Equal is also ok. A very good answer by Stefan Zeiger on Google group. Database implementation would be like: Happy Hacking!!! 🙂 13 thoughts on “Best Practices for Using Slick on Production7 min read” Reblogged this on Play!ng with Scala. Very elaborate. Many thanks for the ideas. However, as a slick newb, it did put me under some heavy cognitive load. cogniviWhat do yout thing about a simplified version of a Repository, modeled after the ‘simple’ example from? class UserRepository(val dc: DatabaseConfig[JdbcProfile]) { import dc.driver.api._ val db: Database = dc.db def create(user: User): Future[Int] = db.run {userTableAutoInc += user} … class UserTable(tag: Tag) extends Table[User](tag, “user”) { val id = column[Int](“id”, O.PrimaryKey, O.AutoInc) val name = column[String](“name”) def * = (name, id.?) (User.tupled, User.unapply) } val userTableQuery = TableQuery[UserTable] … } case class User(name: String, id: Option[Int] = None) creating a DatabaseConfig: DatabaseConfig.forConfig[JdbcProfile](“h2_dc”) config: h2_dc { driver = “slick.driver.H2Driver$” db { …} } @ksilin This is very good example for starting with Slick. Whenever you want perform joins on multiple tables then it will become a bit complex. In my example, BankProductTable and BankTable are Slick mapping tables. I have put these classes in separate trait because If slick mapping table needs another slick mapping table for defining a foreignKey relationship, you can Mixin it very easily. Simply, I don’t want to Mixin methods of one Repository to another Repository. May be two repository have methods which have same name. private[repo] trait BankProductTable extends BankTable { this: DBComponent => import driver.api._ private[BankProductTable] class BankProductTable(tag: Tag) extends Table[BankProduct](tag, “bankproduct”) { val id = column[Int](“id”, O.PrimaryKey, O.AutoInc) val name = column[String](“name”) val bankId = column[Int](“bank_id”) def bank = foreignKey(“bank_product_fk”, bankId, bankTableQuery)(_.id) def * = (name, bankId, id.?) (BankProduct.tupled, BankProduct.unapply) } protected val bankProductTableQuery = TableQuery[BankProductTable] protected def bankProductTableAutoInc = bankProductTableQuery returning bankProductTableQuery.map(_.id) } I tried to extend the pattern you show. I would like to be able to specify an upper bound for a Slick 3.1.1 query type so the id-related actions can be factored out and usable by other persisted classes. I wrote up a SO question () which points to my fork of your GitHub project (). I would be grateful if you would offer a suggestion. @Mike Slinn Full Working example: [code language=”scala”] package com.knol.db.repo import com.knol.db.connection.DBComponent import com.knol.db.connection.MySqlDBComponent import scala.concurrent.{Await, Future} import concurrent.duration.Duration trait LiftedHasId { def id: slick.lifted.Rep[Int] } trait HasId { def id: Option[Int] } trait GenericAction[T <: HasId]{this: DBComponent => import driver.api._ type QueryType <: slick.lifted.TableQuery[_ <: Table[T] with LiftedHasId] val tableQuery: QueryType @inline def deleteAsync(id: Int): Future[Int] = db.run { tableQuery.filter(_.id === id).delete } @inline def delete(id: Int): Int = Await.result(deleteAsync(id), Duration.Inf) @inline def deleteAllAsync(): Future[Int] = db.run { tableQuery.delete } @inline def deleteAll(): Int = Await.result(deleteAllAsync(), Duration.Inf) @inline def getAllAsync: Future[List[T]] = db.run { tableQuery.to[List].result } @inline def getAll: List[T] = Await.result(getAllAsync, Duration.Inf) @inline def getByIdAsync(id: Int): Future[Option[T]] = db.run { tableQuery.filter(_.id === id).result.headOption } @inline def getById(id: Int): Option[T] = Await.result(getByIdAsync(id), Duration.Inf) @inline def deleteById(id: Option[Int]): Unit = db.run { tableQuery.filter(_.id === id).delete } @inline def findAll: Future[List[T]] = db.run { tableQuery.to[List].result } } trait BankInfoRepository extends BankInfoTable with GenericAction[BankInfo] { this: DBComponent => import driver.api._ type QueryType = TableQuery[BankInfoTable] val tableQuery=bankInfoTableQuery def create(bankInfo: BankInfo): Future[Int] = db.run { bankTableInfoAutoInc += bankInfo } def update(bankInfo: BankInfo): Future[Int] = db.run { bankInfoTableQuery.filter(_.id === bankInfo.id.get).update(bankInfo) } /** * Get bank and info using foreign key relationship */ def getBankWithInfo(): Future[List[(Bank, BankInfo)]] = db.run { (for { info <- bankInfoTableQuery bank <- info.bank } yield (bank, info)).to[List].result } /** * Get all bank and their info.It is possible some bank do not have their product */ def getAllBankWithInfo(): Future[List[(Bank, Option[BankInfo])]] = db.run { bankTableQuery.joinLeft(bankInfoTableQuery).on(_.id === _.bankId).to[List].result } } private[repo] trait BankInfoTable extends BankTable{ this: DBComponent => import driver.api._ class BankInfoTable(tag: Tag) extends Table[BankInfo](tag, "bankinfo") with LiftedHasId { val id = column[Int]("id", O.PrimaryKey, O.AutoInc) val owner = column[String]("owner") val bankId = column[Int]("bank_id") val branches = column[Int]("branches") def bank = foreignKey("bank_product_fk", bankId, bankTableQuery)(_.id) def * = (owner, branches, bankId, id.?) <> (BankInfo.tupled, BankInfo.unapply) } protected val bankInfoTableQuery = TableQuery[BankInfoTable] protected def bankTableInfoAutoInc = bankInfoTableQuery returning bankInfoTableQuery.map(_.id) } object BankInfoRepository extends BankInfoRepository with MySqlDBComponent case class BankInfo(owner: String, branches: Int, bankId: Int, id: Option[Int] = None) extends HasId [/code] Would you please fork my fork of your GitHub repo, and add your code there? I cannot get your code to work. “type QueryType = TableQuery[BankInfoTable]” in BankInfoRepository results in an incompatible override error. @Mike Actually It was very minor issue. I have fixed and created pull request on your repo. Changes: [code language=”scala”] class BankInfoTable(tag: Tag) extends Table[BankInfo](tag, "bankinfo") {] It should be: [code language=”scala”] class BankInfoTable(tag: Tag) extends Table[BankInfo](tag, "bankinfo") with LiftedHasId {] I have used the approach shown above successfully on several table. However, I have a Postgres table that has a key defined like this: id BIGSERIAL PRIMARY KEY The other tables have keys defined exactly the same. This table, throws “java.lang.IllegalArgumentException: Unknown field: id” when autoInc is invoked. Not sure what makes this table different. The database record does get written, even though an exception is thrown. Here is a simplified version of the code: class CourseTable(tag: Tag) extends Table[Course](tag, “courses”) { // … def id = column[Option[Id]](“id”, O.PrimaryKey, O.AutoInc) // … } val sanitize = (course: Course) => { course.copy( /* blah blah */ ) } // Type Course has a public property id of type Id val course: Course = ??? // constructor details are irrelevant val copyUpdate = (course: Course, id: Option[Id]) => sanitize(course) lazy val queryAll = TableQuery[CourseTable] def autoInc = queryAll returning queryAll.map(_.id) into copyUpdate database.run(autoInc += course) // Boom! Suggestions? Mike @Mike: It seems problem with “into” method where you are passing copyUpdate. Have you try without calling “into” method ? Could please share branch name where this code reside then i will take a look in real code and full stack of exception. Satendra, I have updated my fork to incorporate similar code to what I described. It mostly works, except for one of the upsert tests. [code language=”scala”] test("Upsert existing bank") { val bankOne: Bank = getAll.head whenReady(upsertAsync(bankOne)) { bank => // why is bank==None? assert(bank.exists(_.idAsInt >= 0)) } val modifiedBank = bankOne.copy(name="Beyondanana") whenReady(upsertAsync(modifiedBank)) { bank => // why is bank==None? assert(bank.exists(_.idAsInt >= 0)) } } [/code] @Mike: In this case method insertOrUpdate returns None if updated, otherwise return inserted row Some(Bank). I did not know that. Thank you! Could you please suggest how to write the query to handle one to many relation. the below scenario: case class BankWithProducts(bank: Bank, products: Seq[BankProduct]) def getBankWithProducts(): Future[BankWithProducts] = …
https://blog.knoldus.com/best-practices-for-using-slick-on-production/
CC-MAIN-2021-04
refinedweb
1,654
51.04
odore Tso <tytso@MIT.EDU> writes: >". Then let me flip this around and give a much more practical use case. Testing. A very interesting number of cases involve how multiple machines interact. You can test a lot more logical machines interacting with containers than you can with vms. And you can test on all the aritectures and platforms linux supports not just the handful that are well supported by hardware virtualization. I admit for a lot of test cases that it makes sense not to use a full set of userspace daemons. At the same time there is not particularly good reason to have a design that doesn't allow you to run a full userspace. >>>.) Resource guarantees I suspect may be worse. But all of this is to say that the problem control groups are tackling is a hard one. Resource control and resource limits across multiple processes is a challenge problem and in some contexts it is a hard problem. My observations have been that when you want any kind of strong resource guarantee or resource limit, it is currently a lot easier to implement that with hardware virtualization than with control groups (at least for memory). I think the cpu scheduling has been solved but until you also at least solve user space memory there are going to be issues. At the same time getting better resource controls is an area where there is a strong interest from all over the place. >>. It actually isn't much complexity and for the most part the code that I care about in that area is already merged. In principle all I care about are having the identiy checks go from: (uid1 == uid2) to ((user_ns1 == user_ns2) && (uid1 == uid2)) There are some per subsystem sysctls that do make sense to make per subsystem and that work is mostly done. I expect there are a few more in the networking stack that interesting to make per network namespace. The only real world issue right now that I am aware of is the user namespace aren't quite ready for prime-time and so people run into issues where something like sysctl -a during bootup sets a bunch of sysctls and they change sysctls they didn't mean to. Once the user namespaces are in place accessing a truly global sysctl will result in EPERM when you are in a container and everyone will be happy. ;) Where all of this winds up interesting in the field of oncoming kernel work is that uids are persistent and are stored in file systems. So once we have all of the permission checks in the kernel tweaked to care about user namespaces we next look at the filesystems. The easy initial implementation is going to be just associating a user namespace with a super block. But farther out being able to store uids from different user namespaces on the same filesystem becomes an interesting problem. We already have things like user mapping in 9p and nfsv4 so it isn't wholly uncharted territory. But it could get interesting. Just a heads up. >>). My concern is any externally implemented service, but in general browsers and web sites are your most likely candidates. Both because there is more complexity there and because http is used far more often than other protocols. And yes I agree that the first line of defense needs to be in the browser source code, and then the application level sand boxing features that the browser takes advantage of. Last I paid attention one of the layers of defense that chrome is user was to setup different namespaces to make the sandbox tight even at the syscall level. When it is complete I would not be at all surprised if the user namespace wound up being used in chrome as well. Just as one more thing that helps. I have found it very surprising how many of the namespaces are used for what you can't do with them. Eric Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/462789/
CC-MAIN-2013-20
refinedweb
674
67.89
Sunday 3/28/2008 I'm terrible at this keeping wiki's updated thing. I have been blogging more and Nvigorate has gone through some additional design iterations. I'm working on some feature lists, API docs and examples so this wiki should actually start seeing new content. Sunday 7/27/2008 Hard to believe it's been a year since I've updated this wiki. The good news is that the project isn't dead, but there have been a lot of changes. For starters, I'm now hosting the project at codeplex. I also have a new blog where Nvigorate related topics will start popping up:. Friday 7/13/2007 Redesign Time The good news is that by using a new library called PostSharp and moving to the 3.5 version of the framework, Nvigorate will have some very impressive capabilities. The bad news is that I'll have to temporarly drop Mono support and that it will take me a lot longer to develop 2.0 alternatives to some of the functionality. In otherwords, 2.0 development is taking a far back seat. In light of all these changes the design has been changing a lot as well. Hopefully, I'll be making detailed changes to documentation and diagrams shortly. Wednesday 5/30/2007 New source coming soon Well, since the last time I posted I've been in the process of moving (and painting the new place). My honey-do list is nearly completed and so I hope to get back to devoting serious time to Nvigorate. I've been working the bugs out of the Data namespace, I hope to do a new update/code update very soon. In the meantime, I will also try to go back through the documentation here and try to flesh out the designs so that I can actually hand off pieces to those who'd like to participate. Thursday, 5/3/2007 What's Happening? Some of us on the Nvigorate team have been going through time consuming stuff which is keeping us from working on Nvigorate as much as we would like. I've actually just started a new job and I'm having to dedicated a lot of extra time ramping up there. Have no fear though, Nvigorate is not dead. Bugs, bugs and more bugs I've been working hard trying to get all the bugs worked out of the Data namespace. Because I implemented several changes in the code base from my old framework, I made some pretty sloppy errors. It's going to take a while, but I will post here as soon as I can get it working well enough for a commit. Sourceforge bug tracking and task organization Team, we need to start making use of the tracker when possible. I realize that's pretty hard considering there's not a lot to test against or with, but if any of you comes across problems/errors please e-mail them to me or enter them into the tracker on Sourceforge. We also need to start trying to communicate more regularly about who will be working on what and how our individual efforts are progressing. Wednesday 3/27/2007 New Source!!! I've just finished committing my most recent changes to Nvigorate. The Reflection and Data namespaces are nearly complete and I've been busy with design and (some) implementation work on the Relational namespace. Project Tasks!!! If you check out the sourceforge site for the project you'll find that I've begun putting in generalized task descriptions. This is (in the hopes) that I'll start getting some real participants who want to help with the evaluation, development, testing and research. No matter what your speciality, please consider joining the effort. If nothing else, you can always participate in the forum :) Recruiting!!! I've opened recruiting for positions via sourceforge.net. If you don't see the requests, get an account for sourceforge and send me an e-mail (moc.liamg|anihcamxexela#moc.liamg|anihcamxexela) and I'll get you added to the project. Site Updates I've made some changes to the roadmap and namespaces. Because I'm working on so many things at once, I'm afraid this wiki is suffering a bit. Perhaps someone would like to help me maintain it? :) Wednesday 3/14/2007 Site Updates I've put up the first complete UML diagram which lays out the interfaces for the Transport namespace. You can see the diagram under the Nvigorate.Transport namespace page in the Design section. There are a lot more in the works at the moment, but take a look at what's there and let me know what you think. Source Code The first iteration of source code for the Nvigorate.Data namespace is nearly completed and should be released in the next week or so (check this page to see when). The code update will also include the UML diagrams that I'm working on. Assistance If you'd like to help with nunit tests, proof of concepts, documentation or site administration please send an e-mail to moc.liamg|anihcamxexela#moc.liamg|anihcamxexela, if nothing else, participate in the forums! Thursday 3/8/2007 Site Updates I've just discovered that posting any serious amount of source on the wiki is a tad unrealistic, the ajax can't handle the amount of data (at least, that's what appears to be happening). But I have good news, read on! SourceForge SourceForge approved my project request earlier this morning, and I have the SVN repository setup. I will post the SVN's URL and directions for getting the source later on once it's "stable". Here's what you can expect to get when pulling down the source; since we only get one repository and SVN does not support modules, both Nvigorate and Nvigorate.Testing projects are included in one directory. There may be a better way to do this (i'm up for suggestions) but it will support as many projects and solutions as we need as long as we keep them under a central folder and that folder maps to the nvigorate repository. Wednesday 2/28/2007 Site Updates The Architecture & Design section has been started and hopefully you can start getting a feel for where this framework is headed in the near future as well as the approaches/mindset used in designing Nvigorate. Source News While the design for the Reflection namespace isn't complete, you can take a look at the feature list. Technical specifications will soon follow. The code itself (which mostly prexisted this framework) has been brought up to coding guideline compliance and I'm now in the process of finishing NUnit tests. Tuesday 2/27/2007 Site Updates The Coding Guidelines section is starting to come together. While it's all still a work in progress, start looking over it and voice your opinions in the forum. Soon I should have a road map page started which will show the order of all the items that are being worked on. You'll need to sign up with wikidot (free and easy process) in order to make posts to the forum. If that's too much work, shoot me an e-mail: moc.liamg|anihcamxexela#moc.liamg|anihcamxexela.
http://nvigorate.wikidot.com/news
CC-MAIN-2017-51
refinedweb
1,223
71.34
Why does mapToItem return a QVariantMap instead of QPoint? An inconvenience I stumbled upon - it is not possible to assign the result of mapToItem to a point property. That just doesn't seem like a very good design intent. Instead of: @p = mapToItem(null, mouseX, mouseY)@ I have to assign each component individually: @p.x = mapToItem(null, mouseX, mouseY).x p.y = mapToItem(null, mouseX, mouseY).y@ which also has to call the mapToItem function twice. I also noticed that QML elements really don't have the concept of position build in, only the individual components of it. Which means more bindings and more assignment to move elements by their individual position components. - mutaphysis You could always do @ var pos = mapToItem(null, mouseX, mouseY); p.x = pos.x; p.y = pos.y; @ to prevent calling the method twice ;) And it is best to always try to stick to using anchors to align elements to each other, this is faster than bindings and also pretty readable. There are plenty of scenarios where items need to be free and movable by the user, anchoring is applicable to user interface graphics but not to program element graphics. It would make much more sense and it would be much more flexible if there was a position property as well on top of its individual components. Especially considering it is just a matter of accessors, no extra data needs to be stored. I agree it would be bad if individual components were children of the position properti, a.k.a. you have to go "pos.x:" as is it is with anchors, but this can be avoided. - chrisadams How would you avoid exposing the components as subproperties - and why would you want to? Would the "pos" property just be completely "opaque" to JavaScript / QML code? If so, then it becomes useless in bindings. If not, then it would need to be exposed as a value-type (so that binding expressions and signal handlers can do pos.x if they wish) - and as soon as you're using value-types you're incurring a fairly large amount of overhead for absolutely every position-related call. I'd be interested in seeing benchmarks of two animations, one which animates an int property to which another int property is bound, and one which animates an int property to which a value-type subproperty (eg, the x component of a vector3d) is bound. I actually haven't benchmarked this, as far as I can remember, but I would imagine that the second one would take significantly more CPU. Cheers, Chris. bq. I actually haven’t benchmarked this, as far as I can remember, but I would imagine that the second one would take significantly more CPU. Without nitpicking, purely out of technical interest, why? I do seem to have some trouble figuring out what is exactly in your mind in this regard. - chrisadams Limiting it to just dynamic properties (ie, vmemo data properties) since this simplifies the comparison: Purely due to the write semantics of value types. The value type "wrapper" (actually, wrapper is a terrible name, it should be "agent" or something, I guess) takes the subproperty value, composes a "complete" value from the original complete value modified with the subproperty value, and then writes the entire new complete value back to the (qvariant storage type) property cell. There's more work being done there, than for most primitive types (which are actually still stored to a qvariant storage cell, in the case of dynamic properties, but there's no composition step). So I benchmarked this, and found out that the actual difference wasn't nearly as much as I was expecting: @ import QtQuick 2.0 Item { property int changingOne property int changingTwo property int boundOne: changingOne property vector3d v3 v3 { x: changingTwo } Component.onCompleted: { var i console.time("bound int evaluation") for (i = 0; i < 1000; i++) { changingOne = i } console.timeEnd("bound int evaluation") console.time("bound v3 evaluation") for (i = 0; i < 1000; i++) { changingTwo = i } console.timeEnd("bound v3 evaluation") } } @ On my system, I'm getting 41 ms for the first, and 44 ms for the second, on average. That's... not nearly as much difference as I expected to see, to be honest. Interesting! Cheers, Chris. I get between 0 and 1 msec arbitrarily, but boosting the number of iterations to 100k the difference is almost twice: ~47 msec for int, ~77 msec for v3. However I got almost identical results (49 vs 54) for a custom element of type Position that exposes both a pos property as well as individual x and y components, however x and y are non-STORED properties but derived from pos. Which was sort of my idea - that they are not nested inside of pos but available on the same level. No extra hop. Of course, since I implement Position as an element there is some overhead, it maybe possible to reduce that small performance difference further.
https://forum.qt.io/topic/25166/why-does-maptoitem-return-a-qvariantmap-instead-of-qpoint
CC-MAIN-2018-51
refinedweb
829
52.9
Without a doubt, PHP developers are lucky of having awesome debug utilities functions included in PHP as var_dump and debug_backtrace to know graphically (on text description) the content of some variable. Some languages like C, C# and others doesn't offer such an utility by default. This is really helpful when you are debugging why your code doesn't work or you are creating something from scratch. However, some structures of a variable are pretty hard to understand and read even with the magical method var_dump. That's why there libraries that decided to make such feature even better like Kint. Kint for PHP is a pretty useful tool designed to present your debugging data in the absolutely best way possible graphically. In other words, it’s var_dump() and debug_backtrace() on steroids. Easy to use, but powerful and customizable. It is an essential addition to your development toolbox, so if you still don't understand the description of this library, it is used to see what is inside variables: This treeview is displayed in the view, where you can take a look at the data by simply clicking anywhere on the bar to unfold it. Some features of the treeview are: - Double click + to unfold all children - Press d to toggle keyboard navigation. - Press the “⇄” icon on the right to see what you’d need to run to get at a piece of data. - Change tabs to see different views of data. - You can sort tables of data by clicking on the headers. Kint automatically detects, unpacks, and parses common formats like XML, base64, serialize, and JSON. Besides it detects common patterns like colors, filenames, tables, and timestamps and displays extra information about them providing the developer with the exact piece of code they need to access some information nested deep in the hierarchy. Installation You can use this library easily on any PHP project that uses an equal or higher version to 5.1.2. You can either install it with composer by simply running the following command in your project: composer require kint-php/kint Alternatively just download the kint.php file from the repository and then add it in your PHP file like: <?php require 'kint.php'; After the installation by any of the 2 ways, you will be able to use the methods that Kint has to offer to help you with the debugging. Usage The project is made to be easy to use. Just like the default debug methods of the language do, you can use the static method dump of the Kint class to debug variables and even using shortcuts: <?php // If using composer include the kint namespace use Kint; // Debug multiple arguments Kint::dump($GLOBALS, $_SERVER, "Hello World"); // Or use the d shortcut of Kint d($GLOBALS, $_SERVER, "Hello World"); // Debug backtrace Kint::trace(); // Debug backtrace shortcut d(1); // Basic output mode s($GLOBALS); // Text only output mode ~d($GLOBALS); // Disable kint Kint::$enabled_mode = false; // Debugs no longer have any effect d('Get off my lawn!'); Tips and: dd(), sd(), and ddd()were removed in Kint 2, but you can make them yourself with helper aliases - Read the full documentation for more information. How to contribute The source code of Kint is hosted on Github and you can report issues, create pull requests as the project works under the MIT license. Become a more social person
https://ourcodeworld.com/articles/read/572/kint-a-modern-and-powerful-php-debugging-helper
CC-MAIN-2018-17
refinedweb
563
58.82
Tell us what you think of the site. Thanks again. Here’s an icon I made for it. It’s the least I can do. :) 3ds Max 2013, Maya 2013 Windows 7 Ultimate 64 Bit Core i7, 12GB RAM Nvidia Quadro FX 3700 (Driver 267.17) haha that’s great thanks! I’ve included it to the download and a mention in the post. Lee Dunham | Character TD ldunham.blogspot.com i tryed i’m actually trying now but it gives this error when i try to execute it in python import ld_createSoftCluster as sc sc.ld_createSoftCluster() # Error: IndentationError: unexpected indent # i have put the file into documents/maya/2012-x64/scripts but it seems it doesnt work, please help.. Gianluca. im not having that issue with the script, not have I heard it happen yet. try entering it line by line. import ld_createSoftCluster as sc sc.ld_createSoftCluster()
http://area.autodesk.com/forum/autodesk-maya/python/create-cluster-out-of-soft-selection/page-last/
crawl-003
refinedweb
148
68.57
* Vivek Goyal <vgoyal@in.ibm.com> [2007-07-16 06:19]:> On Fri, Jul 13, 2007 at 03:15:50PM +0200, Bernhard Walle wrote:> > * Ken'ichi Ohmichi <oomichi?> > > > Agreed. We need to export PAGESIZE from kernel instead of assuming that> second kernel as got same page size as first kernel.So what about this? Do you think it has a chance to get included?Should the variable not be inside mm/ but otherwhere?Signed-off-by: Bernhard Walle <bwalle@suse.de>--- mm/mmap.c | 10 ++++++++++ 1 file changed, 10 insertions(+)--- a/mm/mmap.c+++ b/mm/mmap.c@@ -35,6 +35,16 @@ #define arch_mmap_check(addr, len, flags) (0) #endif +#ifdef CONFIG_KEXEC++/*+ * Although that variable is not needed for the kernel, initialise it here+ * to have the page size available in the vmlinux binary.+ */+int page_size = PAGE_SIZE;++#endif+ static void unmap_region(struct mm_struct *mm, struct vm_area_struct *vma, struct vm_area_struct *prev, unsigned long start, unsigned long end);-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/7/16/148
CC-MAIN-2016-22
refinedweb
183
66.23
A. 1. Why Unit Tests Anyway? Our main focus when writing software is building new features, fixing bugs. Of course, we need to test what we built, but we get the most joyful moment when our new developed feature works. Next step is to write unit tests… But, we already know it is working, so why spend much effort not breaking anything when changing the code (assuming the unit tests are well written and provide enough code coverage). It is therefore also common practice to run the unit tests as part of your CI/CD pipeline. When you do not like writing unit tests afterwards, you can also consider writing your unit tests first, let 🙂 . 2. Create Your First Unit Test We will build upon the sources of the Jira time report generator. We are using Python 3.7 and PyCharm as IDE. First, let’s create a test directory and right-click the directory in PyCharm. Choose New - Python File and Python unit test. This creates the following default file: import unittest class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, False) if __name__ == '__main__': unittest.main() Running this unit test obviously fails (True does not equals False), but we do have set up the basics for writing our own unit tests now. 3. Mocking a Rest API We want to unit test the get_updated_issues function and this provides us a first challenge: the get_updated_issues function contains a call to the Jira Rest API. We do not want our unit test to be dependent of a third party service and therefore we need a way to mock the Rest API. There are several options to mock a Rest API, but we will make use of the requests-mock Python library which fits our needs. Install the requests-mock Python library: pip install requests_mock 3.1 Test Single Page Response The get_updated_issues function will request the issues which are updated in a certain time period. In our unit test, we will verify the behavior when one page with results is retrieved (the Rest API supports pagination, but that is something for a next unit test):. In line 5, we define the expected result with variable expected_result when the function get_updated_issues returns. At lines 11 up. 3.2 which. 3.3 Test Failed The unit tests above all pass. But do they fail when something is wrong? We can therefore change e.g. the following line in the get_updated_issues function: issues_json.extend(response_json['issues']) Change it with:: AssertionError: Lists differ 3.4 Test Multiple URI’s The Jira work logs are to be retrieved per issue. We therefore")) 4.. Your Way Of Explanation was good. You add some valuable points. Here I am sharing some information about python. Python software engineers are called as Pythonists. Along these lines, trying Pythonists, we should plunge into an ocean of learning and gain proficiency with the significant highlights of Python programming language. Highlights of Python Programming Language: Coherence: Python has a basic and exquisite sentence structure. Lucidness keeps up a huge number of lines of code and you compose less code when contrasted with other programming dialects like C, Java, or C++. Free and Open Source: Python is unreservedly accessible on practically all mainstream Operating Systems. On the off chance that you are utilizing Mac OS, Windows, or any Unix-based OS, for example, Linux or Ubuntu you have a Python mediator in your Operating System as a matter of course. This is only one language that has power over any other language. It is called as All in one language. As python is much simpler and easy to code language than any other. python training institutes in Hyderabad.
https://mydeveloperplanet.com/2020/03/11/how-to-mock-a-rest-api-in-python/?like_comment=19758&_wpnonce=5226efc264
CC-MAIN-2022-05
refinedweb
616
74.39
Steve Loughran wrote: > Anthony Goubard wrote: > >> Hello, >> >>. > > > 1. I dont think new attributes are the right approach -unless you want > to use namespaced attributes. > 2. is it so hard doing it at the target level? Well, I find it quite ugly, let's say you have it 10 times in your build files, it creates more code, when editing your files you also then need to navigate between your target and all the other targets at the bottom of the files which were created only for the if condition and only contains one task like for example <echo>. I also saw a few weeks ago some asking in this list for a "if" "unless" for another task. I don't see the problem of adding new attributes as long as they're useful and optional. >>". > > > you might think this is a good idea, but when you try invoking ant > tasks from other places then you will see why it is trouble and never > likely to be implemented. Support for local definitions inside a > <macrodef> is a different matter. > I think that overwrite should most of the time not be use and the default behaviour should be of course "false". If you use overwrite, it should be explicit that this property is overwritten. In Java you also sometimes call a method that changes a global variable. e.g. <target name="counter-plus-plus" description="Increment the property counter">... >> >>. > > > But the reason for the split is precisely to get classloading right. > Surely this will break it. From the javadoc of AntMain.java * Interface used to bridge to the actual Main class without any * messy reflection And I personnaly did it, it wasn't too messy. > >> -) > > hmmm. What about the others? The same behaviour as today, if they try to use these task without using a third library ClassNotFoundException. Note that because there were too much files in ant lib I couldn't run ANT on Eclipse(Win2000). > >> -. > > > The reason for the split was to deal with classloading stuff; you can > move things out of core and declare them in <taskdefs>. Merging stuff > takes this facility away. Now if you dont want it you can always > recombine your jar files. Can you elaborate? I don't understand what you mean. > > > Show us some of your build files, and perhaps we can suggest ways to > use ant that are more in line with the stuff we added to ant1.6. If we > cant, then you have a better case for your features. > Ok here is a build file that would use the features I mentioned. Try to translate it to a current Ant task and it will be probably less readable. <project dir="." name="demo"> <target name="ask name"> <echo message="--- starting ask name ---"/> <input message="Please enter db-username:" addproperty="db.user"/> <antcall target="define-db-user" keepProperties="true"/> <echo message="The database user is now ${db.user}"/> <echo message="Youpie superuser!!:" if="superuser"/> </target> <!-- useful target that I'd like to use apart --> <target name="define-db-user" description="define the database user in the db.user property"> <condition property="superuser"> <or> <equals arg1="${db.user}" arg2="anthony"/> <equals arg1="${db.user}" arg2="su"/> </or> </condition> <property name="db.user" value="superuser" overwrite="true" if="itsme"/> </target> </project> --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200405.mbox/%3C40980DA7.3030001@chello.nl%3E
CC-MAIN-2014-41
refinedweb
565
65.93
John M. Boyer In this article, we’ll cover how to measure the quality of the TensorFlow neural net model covered in this previous article. The code for this article can be obtained from the Jupyter notebook in my TensorFlow Samples repository. Although the machine learning model is written with TensorFlow, the code for this article is written generically so that you can apply it to machine learning models built with other libraries, too. The neural net model in the previous article was a binary classifier that learned to distinguish those who were likely to default on a bank loan from those who weren't, based on a set of predictor variables. The most basic measure of accuracy for a binary classifier is the rate of correct classifications. This is what the neural net trains to optimize, and the model training in the code gets an accuracy result of just above 80%. For this data, is this a good result? An excellent result? Or could a much better model be produced using this data? The basic accuracy result for our binary classifier was based on selecting the predicted value based on which class (defaulter or non-defaulter) got the higher confidence value. Put another way, there was a confidence threshold of 50% for determining whether (true) or not (false) a loan applicant would default on a bank loan. The accuracy on the positive samples is called the true positive rate (TPR), and the accuracy on the negative samples is the true negative rate (TNR). The negative samples that the classifier gets wrong are the false positives, and so the false positive rate (FPR) is the percentage false positive samples divided by the total number of negative samples. In the terms of the bank loan example, the true positives are those that were predicted to default and that did default, and the false positives are those that were predicted to default but did not. If needed, further details are here. A receiver operating characteristic (ROC) curve is a plot of the TPR versus FPR as we vary some variable related to the model being tested. In this case, we will vary the confidence threshold because it will give a fine grain view of the model’s ability to distinguish, based on confidence values, the true (defaulter) case from the false (non-defaulter) case. In fact, the Area Under the Curve (AUC) corresponds to the probability that the model will produce a higher confidence value for a randomly selected true case than it will for a randomly selected false case. The diagram below shows the ROC curve and AUC value for the bank loan TensorFlow neural net: Due to the sklearn and matplotlib packages, it is easy to write the code that calculates the data for the ROC curve and the AUC: import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc FPR, TPR, _ = roc_curve(dependent_test, dependent_prob[:, 1]) AUC = auc(FPR, TPR) The first parameter to roc_curve() gives the actual predicted values for each sample, and the second parameter is the set of confidence values for the true (1) class for each sample. The method produces the FPR and TPR data that is used by auc() to determine the AUC and that is also used by the plotting code below: plt.figure() plt.plot(FPR, TPR, label='ROC curve (area = %0.2f)' % AUC) plt.plot([0, 1], [0, 1], 'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.02]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.legend(loc="lower right") plt.show() Finally, with an AUC of 0.85, the bank loan TensorFlow neural net is arguably a good model, especially given the variables and data at hand. The conclusion, then, is that it would be difficult to obtain higher accuracy by simply tuning the model. Other variables and/or data would be needed to train a more accurate machine learning model for this problem..!
https://www.ibm.com/developerworks/community/blogs/JohnBoyer?sortby=2&maxresults=5&order=asc&lang=en
CC-MAIN-2018-05
refinedweb
666
52.09
Back to article November 5, 2000 Acronyms and shorthand are as much a part of IT as silicon, or so it seems. In keeping with this time honored tradition, I am proposing here that everyone extend this to include the T-SQL code that they write. C programmers are long familiar with using abbreviations in defining functions, procedures, and variables. Remember the famous Hungarian notation? It helped tremendously in tracking down problems with code by providing the programmer with information about the type of data contained in a variable, this type was expressed as an Abbreviation prefixed to the variable name. This can also be useful in database programming for a number of reasons, it helps to enforce standards, reduce typing, and prevent collisions with reserved words. With a standard list of abbreviations for data elements, your colleagues can more easily understand what data elements your code is working with. Granted long names can do the same thing, but there are other reasons not to use long names. Standards are extremely important in many aspects of life, but in programming these days with distributed teams of workers, they can substantially reduce the amount of time spent working on someone else's code. My advice is to gather existing programmers together and create a list of abbreviations for the commonly used objects in your system. Then publish this list for all programmers to reference as well as an introductory document for new programmers. By agreeing to this list as a team, you will foster communication as well as help to get everyone to agree to a list. I type fairly fast. While not a touch typist, I can type about 70 words a minute when I know what I want to type. If I type shorter words, then I can up this quite a bit. In programming, this means more lines of code per minute/hour/day spent at the keyboard. If I can reduce the amount of typing by using abbreviations, then less work for me. Or I get more done in less time and get a bigger bonus. Or (most importantly) I can spend more time with my family. Look at this code: update customerorders set shiptoaddress = '123 mystreet', shiptocity = 'The Big Apple', extrainstructions = 'drop off with landlady' where customerordersid = 999 With abbreviations, I could easily rewrite the above code to look like the following: update custord set shipaddr = '123 mystreet', shipcity = 'The Big Apple', xtrinstr = 'drop off with landlady' where custordid = 999 In one database I inherited from a development team, there were two tables that constantly bothered me. One was called "Orders" and the other was "OrderItem". Apart from not using abbreviations, the part that I had to think about (and was bothered by) everytime I referenced them was whether "order" was singular or plural. I knew why this was the case; the developer who created the tables wanted them to be "order" and "orderitem", but "order" is a reserved word in SQL Server (and probably more RDBMSes). So he created this inconsistency. I also got burned on a v6.5 to v7.0 database upgrade. "Percent" is not reserved in v6.5, but is in v7.0. Lucky for me there were about ten tables that used this column in the v6.5 database and were queried from a VB app on many desktops across the country (of course the queries were hardcoded). Can you imagine the fun I had? Both of these situations could easily be avoided by using abbreviations. If "order" were changed to "ord" and "percent" to "prcnt", then no problems would have resulted and development would not have been delayed. In fact, the time to setup abbreviations and learn them would probably be offset by the reduced typing and mistakes that could result. In addition, you would not be likely to collide with new keywords that may be created in SQL Server 2001. One note here, with SQL Server 7, you can enclose your variable and object names in brackets [] and embed white space as well as use reserved words. I personally do not like this approach and hate embedded white spaces (I think they create more typos and confusion than they are worth) but this is a perfectly valid approach in the SQL Server world. I cannot speak as to whether other RDBMS systems support this. This is a results oriented arena, so I would be remiss if I did not provide examples of abbreviations as well as a means to maintain them. The example is an Excel 2000 spreadsheet, so apologies to those of you without Excel 2000. Here it is and it includes a macro to re-sort the data. As for the maintenance, what I normally do is setup a share on the network that all developers have access to and put the spreadsheet in there along with other development documents (standards, practices, etc.). Then each developer can check the spreadsheet whenever they are unsure of an abbreviation. Abbreviations.xls For new abbreviations, you have two choices, both of which have worked well in the past. First, you can appoint someone to be the keeper of this document and everyone else has to "request" new abbreviations from this person. The job can be rotated, but this keeps the system ordered. Alternatively, you can have a new abbreviation sent around in email and "voted" on by the group. If everyone agrees, then the requester is responsible for adding it and resporting the sheet. I do not intend this as a universal list of abbreviations. In fact, you should save the spreadsheet and then delete all the data in it and add your own abbreviations that are appropriate to your company. In my last job, we used Pro for Product, though not consistently. In my current company, Prod was chosen as a team. Either one can work, just be consistent and enforce the standard. Abbreviations good, no abbreviations bad! Well, it may not be quite that simple, but it's close. Over time I have found this to be a real time saver with not much work involved. It usually takes more time to explain the rational to someone and then have them nod and agree than it does to implement. I feel and have found that having abbreviations as the standard usually helps enforce this and less programmers take shortcuts and create their own abbreviations in their section of code. It is rare I find a programmer that wants to type more than they have to. I hope this helps and as always, eelcome any feedback from you. I received this from Jim Sally ( I removed the intro and conlusions parapgraphs which were not relevant) First off, yes acronyms and shorthand have had a long time tradition in software development, but... this is the year 2000, memory is a dime a dozen (or so to speak), and in your specific instances, SQL 7 and above have extended the namespace size of its identifiers beyond the 32 character limitations of earlier versions. This wasn't done just for the hell of it, but as a thought out decision to let database developers create VERY self-descriptive names for database objects. In general, software development has refined itself to the point of being able to call some instances of itself 'software engineering'. The engineering part of it is important. And part of some of my most favorite parts of that deal with writing software that is NOT abbreviated, but very specifically spelled out. When I'm working with new folks joining my company, I don't care if they take twice as long to type out stuff using my naming schemes, because once they are done, it is very obvious what they typed since it is spelled out in clear english. Take your example as a perfect example of hard to read stuff if I were to come along and pick up your code after you left. extrainstructions => xtrinstr At first glance, even after the 10+ years of software development experience that I've had, 'xtrinstr' means nothing to me, where as 'ExtraInstructions' (note the proper capitalization too) has a very specific and clear meaning. I also think that your use of Hungarian notation as an example of why people should abbreviate is just wrong. First off, Hungarian notation was not an "abbreviating notation", but a prefixing notation for type information. It was useful information to have as a programmer while coding, but not necessary for following the logic in the code, which is why we name identifiers using english words rather than 'value1', value2', value3', etc. I can see if you were going to suggest using Hungarian notation in naming your fields, but you didn't. Bottom line, your article is yet another reason that young and inexperienced developers turn out half-assed applications that are hard to maintain and understand. And all in the name of saving time typing. I agree with much of what Mr Sally writes and apologize if I misled anyone with the analogy to Hungarian Notation (which is an abbreviation for a type). But I also think that I have a valid method of helping software development. In my experience, using abbreviations is productive and speeds development when used properly. The shorthand notation I am proposing has been used widely in written communication and I think it can be applied here. I do believe that the namespaces were extended precisely as Mr Sally to allow for more descriptive variable and object names. My time as a senior DBA, however, is valuable and saving me time is more efficient than saving a junior DBA time. I would also argue that the meaning of variables, even long, spelled- out descriptive names is not going to help junior programmers who are not familiar with the company's lexicon (which is also where most variable names come from). Is Customer really better than Cust? What does this mean in your company? Is it the same as User or Usr? Maybe, maybe not. The abbreviations I suggest are not intended to be universal, nor are they suited for every environment. I hope that you publish a standard set of abbreviations for your company as well as a set of standards for naming, coding, etc. that is given to every new programmer that joins the company. One of the standards that I learned early on was to use i, j, and k as counter variables. I still do this and let my programmers know that this is a standard that they will find in my code, rather than using counter or some other name. I expect and enure they do the same. There is not substitute for a good data dictionary and there is also no substitute for a well written, clear, and concise set of programming standards as well. I hope that I did not lead anyone to believe that you should remove all the vowels from your coding and expect people to understand the code. Indeed, some of my "abbreviations" are in fact the entire word ( email, fax, etc.). You should develop a set of standards as a team of programmers and then publish them for everyone to use. If you do this, then all existing programmers will easily adapt to the situation and all new programmers can be given a set of documentation that will familiarize them with how your company's code is written. Let me emphasize that Mr. Sally makes a number of perfectly valid (and accurate) points. I appreciate his feedback and agree to disagree with him. To me, this is more a stylistic arguement about how to write code than a right or wrong. If I were to go to work for Mr. Sally, I would argue my case for abbreviations, but if the standards he has set in place are to use long names, then I would code according to those standards at his company. The Network for Technology Professionals About Internet.com Legal Notices, Licensing, Permissions, Privacy Policy. Advertise | Newsletters | E-mail Offers
http://www.databasejournal.com/features/mssql/print.php/1471461
CC-MAIN-2014-35
refinedweb
2,011
61.06
The C# Access specifiers or access modifiers can be used to define the scope of a type and its members. In general, a member of a class that defined with any scope is always accessible within the class. The restrictions will be applicable when we go outside the class. C# supports five access modifiers. They are - Private - Public - Internal - Protected - Protected Internal. So the class members defined with any of the above-defined scopes are always accessible within the C# class. C# Access Modifiers CASE 1: Accessible members of the class within the class using System; namespace CSharp_Tutorial { class Program { public void demo() { Console.WriteLine("public method"); } private void demo1() { Console.WriteLine("private method"); } internal void demo2() { Console.WriteLine("internal method"); } protected void demo3() { Console.WriteLine("protected method"); } protected internal void demo4() { Console.WriteLine("Protected internal method"); } static void Main(string[] args) { Program c = new Program(); c.demo(); c.demo1(); c.demo2(); c.demo3(); c.demo4(); Console.ReadLine(); } } } OUTPUT All the C# members with any scope can be accessed within the class. C# Access Modifiers Points to remember - The C# members declared as private are accessible only within the class. - The default scope for the members of a class is private. - We cannot declare types as private, and we cannot apply private on a class. - Only public and internal can be used in a class, whereas protected, protected internal and private cannot be applied to a class. - If we don’t apply the public to a class, it will become an internal class. C# Access Specifiers CASE 2: Accessing members of a class using the child class Let us now create another class in the same namespace CSharp_Tutorial with the classname Program2. using System; using System.Collections.Generic; using System.Text; namespace CSharp_Tutorial { class Program2:Program { static void Main() { Program2 p = new Program2(); p.demo(); p.demo2(); p.demo3(); p.demo4(); Console.ReadLine(); } } } OUTPUT Since private methods can be accessed only within the class, we tried to access the methods with all the scopes except private in the child class. C# Access Specifiers CASE 3: Accessing members of the class using a non-child class of the same project Let us now create another class Program3 in the same namespace and try to access the methods of class Program by creating an instance for a class Program in class Program3. using System; using System.Collections.Generic; using System.Text; namespace CSharp_Tutorial { class Program3 { static void Main() { Program p = new Program(); p.demo(); p.demo2(); p.demo4(); Console.ReadLine(); } } } OUTPUT Here, we had accessed the members of Program in Program3 by creating an instance for the Program in Program3. But here we had observed that only members with the scope public, internal, protected internal could be accessed in Program3 since it is a non-child class for Program. C# Access Modifiers CASE 4: Accessing members of a class using child class of different project Here, in this case, C# members with the scope of Public, Protected, and Protected internal are accessible outside the project. Still, the members with the scope internal cannot be accessed. Accessing the members of a C# class outside the project can be done by adding the project’s reference containing the members to the project in which the members are to be accessed. And once the reference added, we can access the members either through inheritance or by creating the instance. Remember, every class can be accessed within the project but not outside the project until it changed to the public. That is the reason for saying, “the default scope for a class is internal.” C# Access Modifiers CASE 5 Accessing C# members of a class using a non-child class of different project. Only members with the scope public can be accessed using the non-child class of different projects. i.e., from the example discussed in case 1, only demo() can be accessed outside the project using a non-child class.
https://www.tutorialgateway.org/csharp-access-modifiers/
CC-MAIN-2021-43
refinedweb
656
55.03
atomic_is_lock_free From cppreference.com Determines if the atomic operations on all objects of the type A (the type of the object pointed to by obj) are lock-free. In any given program execution, the result of calling atomic_is_lock_free is the same for all pointers of the same type. This is a generic function defined for all atomic object types A. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and volatile (e.g. memory-mapped I/O) atomic variables. [edit] Parameters [edit] Return value true if the operations on all objects of the type A are lock-free, false otherwise. [edit] Notes C11, as published, specified that this function is per-object, not per-type. This was corrected by DR 465. [edit] Example Run this code #include <stdio.h> #include <stdatomic.h> _Atomic struct A { int a[100]; } a; _Atomic struct B { int x, y; } b; int main(void) { printf("_Atomic struct A is lock free? %s\n", atomic_is_lock_free(&a) ? "true" : "false"); printf("_Atomic struct B is lock free? %s\n", atomic_is_lock_free(&b) ? "true" : "false"); } Possible output: _Atomic struct A is lock free? false _Atomic struct B is lock free? true [edit] References - C11 standard (ISO/IEC 9899:2011): - 7.17.5.1 The atomic_is_lock_free generic function (p: 280)
https://en.cppreference.com/w/c/atomic/atomic_is_lock_free
CC-MAIN-2019-39
refinedweb
216
68.47
I’ve recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition. How about these examples: int* test; int *test; int * test; int* test,test2; int *test,test2; int * test,test2; Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one. The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a “real” int. What about case 6? Same as case 5? 4, 5, and 6 are the same thing, only test is a pointer. If you want two pointers, you should use: int *test, *test2; Or, even better (to make everything clear): int* test; int* test2; White space around asterisks have no significance. All three mean the same thing: int* test; int *test; int * test; The “ int *var1, var2” is an evil syntax that is just meant to confuse people and should be avoided. It expands to: int *var1; int var2; Use the “Clockwise Spiral Rule” to help parse C/C++ declarations;! Also, declarations should be in separate statements when possible (which is true the vast majority of times). Many coding guidelines recommend that you only declare one variable per line. This avoids any confusion of the sort you had before asking this question. Most C++ programmers I’ve worked with seem to stick to this. A bit of an aside I know, but something I found useful is to read declarations backwards. int* test; // test is a pointer to an int This starts to work very well, especially when you start declaring const pointers and it gets tricky to know whether it’s the pointer that’s const, or whether its the thing the pointer is pointing at that is const. int* const test; // test is a const pointer to an int int const * test; // test is a pointer to a const int ... but many people write this as const int * test; // test is a pointer to an int that's const #include <type_traits> std::add_pointer<int>::type test, test2; As others mentioned, 4, 5, and 6 are the same. Often, people use these examples to make the argument that the * belongs with the variable instead of the type. While it’s an issue of style, there is some debate as to whether you should think of and write it this way: int* x; // "x is a pointer to int" or this way: int *x; // "*x is an int" FWIW I’m in the first camp, but the reason others make the argument for the second form is that it (mostly) solves this particular problem: int* x,y; // "x is a pointer to int, y is an int" which is potentially misleading; instead you would write either int *x,y; // it's a little clearer what is going on here or if you really want two pointers, int *x, *y; // two pointers Personally, I say keep it to one variable per line, then it doesn’t matter which style you prefer. In 4, 5 and 6, test is always a pointer and test2 is not a pointer. White space is (almost) never significant in C++. The pointer is a modifier to the type. It’s best to read them right to left in order to better understand how the asterisk modifies the type. ‘int *’ can be read as “pointer to int’. In multiple declarations you must specify that each variable is a pointer or it will be created as a standard variable. 1,2 and 3) Test is of type (int *). Whitespace doesn’t matter. 4,5 and 6) Test is of type (int *). Test2 is of type int. Again whitespace is inconsequential. You can think of 4, 5, and 6 as follows: declaring the type only has to be done once, but if you want to declare a pointer to that type (by adding an asterisk) you have to do so for each variable. When declaring a pointer variable, I always add whitespace between the variable and asterisk, even if I’m declaring more than one in a line. Not doing so makes me confuse it for a dereferencing expression nearly every time. A good rule of thumb, a lot of people seem to grasp these concepts by: In C++ a lot of semantic meaning is derived by the left-binding of keywords or identifiers. Take for example: int const bla; The const applies to the “int” word. The same is with pointers’ asterisks, they apply to the keyword left of them. And the actual variable name? Yup, that’s declared by what’s left of it. The rationale in C is that you declare the variables the way you use them. For example char *a[100]; says that *a[42] will be a char. And a[42] a char pointer. And thus a is an array of char pointers. This because the original compiler writers wanted to use the same parser for expressions and declarations. (Not a very sensible reason for a langage design choice) I would say that the initial convention was to put the star on the pointer name side (right side of the declaration in the c programming language by Dennis M. Ritchie the stars are on the right side of the declaration. by looking at the linux source code at we can see that the star is also on the right side. You can follow the same rules, but it’s not a big deal if you put stars on the type side. Remember that consistency is important, so always but the star on the same side regardless of which side you have choose. Cases 1, 2 and 3 are the same, they declare pointers to int variables. Cases 3, 4 and 5 are the same, as they declare one pointer to, and one int variable respectively. If you want do declare two pointers in one line (which you shouldn’t), you need to put an asterisk in front of each variable name: int *test, *test2; There is no certain correct way that says where the asterisk goes. int* test looks better because it is easier for us to imagine that appending * to the end of a type means “pointer to” that type. However, int *test makes more sense, because you can work with it like the minus sign in maths: -(-x) = x is analogous to *(*test) = test This has always helped me. Sadly, the upshot of it all is that sometimes I use int* test and sometimes int *test.
https://exceptionshub.com/placement-of-the-asterisk-in-pointer-declarations.html
CC-MAIN-2021-21
refinedweb
1,124
76.66
Containerized Applications that need access to relational database systems typically leverage ODBC drivers to do so. This means that if you want to connect to Postgres from an IIS web application, you must install the appropriate ODBC drivers as well as creating the appropriate data source name or DSN. in a Windows environment this is typically achieved by going into the control panel and clicking through a set up program, thus leveraging the user interface of the operating system. Typically installed on virtual machines Generally speaking, ODBC drivers get installed on VMs, making them available to all apps that run on the VM. But in the world of containers, that is different because each container needs to be self-contained with zero dependencies on the host OS on top of which it runs. This means we need to figure out a way to get the ODBC drivers to install on image, not on its host operating system running on the virtual machine. What is post is about Just to be clear what we mean by image is, in fact, a Docker image. building a darker image is achieved by running a build command and using a text file to act as a blueprint when building the image. This post is about how you would automate the installation of ODBC drivers onto a Docker image. to build a darker image using the docker build command along with a Dockerfile is a completely automated process with no ability for a user interface to be used to install programs onto that image. Thus, we need a fully automated way to install the necessary ODBC drivers along with the creation of a data source name. I had to build my own tooling Unfortunately, I could not find a solution to programmatically perform the tasks needed here. So I wrote my own and that’s what this post is about – just to be clear. In a nutshell, all this post will show you how to do is to create a commandline utility that programmatically installs an ODBC driver without any user intervention whatsoever. This is exactly what is needed we are building up your Docker images. The metadata needed to connect to PostGres This metadata includes: - The driver type (Postgres will be the example in this post) - The server domain name or IP address - The port number - The database name - Username and password Must be 100% programmable Dockerfiles are text files that are used to build up an image that will eventually become a running container. Dockerfiles represents the blueprint that takes a base image and adds the appropriate software layers upon this base image. Notice in the code below that there’s a section that states that commands are needed to install the ODBC drivers. The challenge – I provided code that is needed The problem is that there does not exist some easy to use commands to do this and that’s what this post is about. Questions that need answering (Imagine that you want to install Postgres): - What binaries are needed on the Docker host to begin the process? - what code do we need to write to automate the provisioning of not just the ODBC driver, but also the creation of the data source name - The data source name will be needed by the code we write for our IIS web application Sample Dockerfile Note the dockerfile below. it’s a very simple Docker file that begins with a core Windows server operating system. It then uses dism.exe to install IIS. From there it creates a simple index.html file which represents a “Hello World” webpage What you don’t see in this file is an implementation of installing an ODBC driver. That’s the purpose of this post – to show you how to do that. # Sample Dockerfile # Indicates that the windowsservercore image will be used as the base image. FROM windowsservercore # ************************************************************************************** # NEEDED COMMANDS TO INSTALL ODBC DRIVERS AND CONFIGURE DSNs IS WHAT THIS POST IS ABOUT # [commands go here] # ************************************************************************************** # Metadata indicating an image maintainer. MAINTAINER bterkaly@microsoft" ] Dockerfile Building an image Assuming that you are in a directory that contains this Dockerfile, you typically issue a command like this to build an image: docker build . The docker build will construct an image using the declarative syntax within a Dockerfile. There is no user interface to perform this operation. This means that when you build an image it must be 100% programmable, without any user interface whatsoever. The figure below depicts the workflow needed to get a running container. As explained previously, the combination of the docker build command along with the corresponding Dockerfile is how you produce a docker image. From there, you can use the Docker run* command along with that image to finally get to your running container**. Click image for full size Figure 1: dockerbuild.png Creating a commandline utility in Visual Studio Let’s begin building out our command line utility that we can use inside of our Dockerfile. We will start up Visual Studio. You can use the version I’m using, 2015, but practically any version will work here. We will create a console application that leverages the Win32 API. I was going to write this in C (because of the Win32 API) but figured that C# might be more accessible to most. You can begin by clicking New project from the Start page. Click image for full size Figure 2: Creating a new project At this point you will be able to select from the available project types. we are going to choose Console application. Click image for full size Figure 3: Selecting a console application as a project type and specifying a project name At this point we are going to add a class module that will do all the heavy lifting. It will be called ODBCManager and will contain all the necessary code to modify the Windows registry in addition to the ODBC.ini file. Click image for full size Figure 4: adding a class Our class module will need a name. It is called ODBCManager. Click image for full size Figure 5: Naming the class The key take away and this diagram is the fact that the ODBC driver resides within the containerized web application, not at the virtual machine that is hosting the container. This is a great example of the power of containerization, the fact that the containerized web application includes all its dependencies. Containers can be run practically anywhere because they contain all of their dependencies. whereas previously the virtual machine needed to have the ODBC drivers installed to be able to support applications that access relational databases, now the container comes fully self-contained, capable running on a generic virtual machine or even a bare metal machine. Click image for full size Figure 6: Showing that the ODBC driver exists inside the container Paste in this code to ODBCManager.cs At this point we are ready to paste in the code that does the setting up of a data source name. The data source name is an abstraction that allows other code to connect up to a data source, which, as stated earlier, will be Postgres in our case. In the figure below you will note that the code is connecting to PostGres by leveraging the data source name. Click image for full size Figure 7: Example of a client application using a data source name to connect up to PostGres Code to create the data source name In the code snippet below we actually do a few things. At a physical level we are modifying the registry as well as a ODBC.ini file. When you add a data source name those of the two things that get modified on a Windows system. using Microsoft.Win32; using System; using System.Runtime.InteropServices; namespace SetupODBC { public static class SetupODBC { [DllImport("ODBCCP32.DLL")] private static extern bool SQLConfigDataSource(IntPtr hwndParent, RequestFlags fRequest, string lpszDriver, string lpszAttributes); [DllImport("Kernel32.dll", SetLastError = true)] public static extern long WritePrivateProfileSection(string strSection, string strValue, string strFilePath); [DllImport("Kernel32.dll", SetLastError = true)] public static extern long WritePrivateProfileString(string strSection, string strKey, string strValue, string strFilePath); private enum RequestFlags : int { ODBC_ADD_DSN = 1, // Add a new user data source. ODBC_CONFIG_DSN = 2, // Configure (modify) an existing user data source. ODBC_REMOVE_DSN = 3, // Remove an existing user data source. ODBC_ADD_SYS_DSN = 4, // Add a new system data source. ODBC_CONFIG_SYS_DSN = 5, // Modify an existing system data source. ODBC_REMOVE_SYS_DSN = 6, // Remove an existing system data source. ODBC_REMOVE_DEFAULT_DSN = 7 // Remove the default data source specification section from the system information. } public static bool Add(string DSName, string DB, string Server, string Port, string uid, string password) { // Clean up ODBC.ini file WritePrivateProfileString(DSName, null, null, @"c:\windows\odbc.ini"); Console.WriteLine(@"Cleaning up c:\widnows\odbc.ini"); // Delete registry entry for DSN var software = Registry.CurrentUser.OpenSubKey("Software"); if (software == null) return false; using (var odbc = software.OpenSubKey("ODBC", true)) { using (var odbcini = odbc.OpenSubKey("ODBC.INI", true)) { using (var subkey = odbcini.OpenSubKey(DSName, true)) { if(subkey != null) odbcini.DeleteSubKey(DSName); } Console.WriteLine(@"Cleanup the registry HKEY_CURRENT_USER\SOFTWARE\ODBC\ODBC.INI\{0}", DSName); } } // Create DSN from scratch string strAttributes = "Dsn=" + DSName + "\0Server=" + Server + "\0Port=" + Port + "\0Database=" + DB + "\0Uid=" + uid + "\0pwd=" + password + "\0"; bool lngRet = CreateDataSource((IntPtr)0, 1, "PostgreSQL ANSI\0", strAttributes); lngRet = CreateDataSource((IntPtr)0, 2, "PostgreSQL ANSI\0", strAttributes); Console.WriteLine("Created data source = {0}", DSName); return lngRet; } [DllImport("ODBCCP32.dll")] private static extern bool SQLConfigDataSource(IntPtr hwndParent, int fRequest, string lpszDriver, string lpszAttributes); public static bool CreateDataSource(IntPtr hwndParent, int fRequest, string lpszDriver, string lpszAttributes) { return SQLConfigDataSource(hwndParent, fRequest, lpszDriver, lpszAttributes); } } } ODBCManager.cs The main Program.cs looks like this. as you can see parameters will be passed in the defined the necessary metadata. As explained previously, the metadata that will be passed in includes: - The driver type (Postgres will be the example in this post) - The server domain name or IP address - The port number - The database name - Username and password Completing the code namespace SetupODBC { class Program { static void Main(string[] args) { string dsnName = args[0]; string db = args[1].Trim(); string port = args[2].Trim(); string ip = args[3].Trim(); string uid = args[4].Trim(); string pwd = args[5].Trim(); SetupODBC.Add(dsnName, db, port, ip, uid, pwd); } } } Program.cs Building the ODBC installation and configuration application Now that we’ve created a project with all the necessary code, all we have to do next is compile the application and tested on our local laptop. We can prove that it works by verifying that the ODBC driver isn’t on the system and that our web application is unable to connect to the database. Clearly, we can’t connect to Postgres. Click image for full size Figure 8: Proof that we cannot connect up to the database Downloading the driver for PostGres There are two aspects to the work we are doing here. The first task is to actually install the ODBC driver itself. The second task is to define a data source name (DSN). The data source name is where we actually enter the specific connection metadata that is needed to connect to our specific instance of Postgres. Downloading the Postgres ODBC Driver Here is the URL for the downloads: Below you can see the appropriate zip file. Notice that I am installing the x86 version. I had difficulty getting the x64 to work but it may work on other systems. Click image for full size Figure 9: Downloading the ODBC driver in zip format Once the download is complete you may want to unzip the contents into some type of install folder for testing. We are testing on an ordinary laptop right now. Testing within the context of the container and a Dockerfile can be found in other posts. the purpose of this post is simply right the install script and demonstrate its correct use. Click image for full size _Figure 10: The MSI file for the ODBC/PostGres installation. Now you are ready to begin the install. Notice in the image below that I am executing with the /passive flag. you can also use the /quiet flag. Click image for full size Figure 11: Installing the PostGres ODBC Driver To verify correct installation you can go into control panel and see that the psqlODBC driver has been installed. Click image for full size Figure 12: Verifying correct installation Compiling our console application and testing it We have accomplished the following: - Created our console application that will create a data source name - Installed our ODBC driver for PostGres The work that remains is: - To compile our console application - To retrieve the necessary metadata for our Postgres database that is running in Azure on the Ubuntu Linux virtual machine - To run our console application and physically create the data source name - Test that everything is working by connecting up to post grass from a web application To compile our console application We will begin by rebuilding our solution which will produce SetupODBC.exe. Click image for full size Figure 13: Compiling SetupODBC.exe For convenience sake let’s copy the SetupODBC.exe into our local install folder. Click image for full size Figure 14: Copying ODBCSetup.exe to the c:\install folder To retrieve the necessary metadata for our Postgres database that is running in Azure on the Ubuntu Linux virtual machine In order for the ODBC driver to connect a web application to the underlying Postgres database, we will need to understand some information about the virtual machine that runs on, as seen below. Click image for full size Figure 15: Information needed to create a data source name Click image for full size Figure 16: Using the portal to collect the necessary metadata about PostGres The assumption that you’ve installed on a VM somewhere so in my case it is on a VM called VMNAME. To run our console application and physically create the data source name Running our console application can be seen below. Notice that the metadata that describes the connection information to our PostGres database. Click image for full size Figure 17: Running SetupODBC You can verify that the correct entries took place. Click image for full size Figure 18: Locating the place in the registry for the Data Source Name You can validate all the attributes here. Click image for full size Figure 19: The details on the command line properly in place Test that everything is working by connecting up to PostGres from a web application We are now ready to test our connection. We successfully passed the connection.Open(); command. Click image for full size Figure 20: Successful test of connecting to PostGres Conclusion This post showed you had to overcome one of the core challenges when working with containers. It addressed the need to support dependencies that an application needs to run. These dependencies should be part of the container itself, not part of the virtual machine in which the container runs. By putting dependency directly in the container it is now possible to run the container anywhere, as all the dependencies are bundled up along with the application. But the challenge is automating the installation of the dependency in the imager container. Because of the way the building of images is highly automated, it is necessary to install dependent functionality without any user interaction. In the case of this post we showed you how to deploy ODBC drivers in an automated fashion. And what made this post very useful is the fact that sometimes you need to build your own tooling to accomplish this. Installing dependencies doesn’t always come with the ability for automated and silent installation.
https://blogs.msdn.microsoft.com/allthingscontainer/2016/09/23/installing-odbc-drivers-into-windows-containers-and-calling-into-database-systems-that-are-hosted-on-a-linux-vm-2/
CC-MAIN-2017-22
refinedweb
2,614
52.29
wait3() Wait for any child process to change its state Synopsis: #include <sys/wait.h> pid_t wait3( int * stat_loc int options, struct rusage * resource_usage ); Arguments: -3() function allows the calling thread to obtain status information for specified child processes. the status of a child process is available, a value equal to the process ID of the child process for which status is reported. If a signal is delivered to the calling process, -1 and errno is set to EINTR. Zero if wait3() is invoked with WNOHANG set in options and at least one child process is specified by pid for which status isn't available, and status isn't available for any process specified by pid. Otherwise, (pid_t)-1 and errno is set. Errors: - ECHILD - The calling process has no existing unwaited-for child processes, or the set of processes specified by the argument pid can never be in the states specified by the argument options. - EPERM - The calling process doesn't have the required permission; see procmgr_ability() . Classification: Caveats: New applications should use waitpid() .
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/w/wait3.html
CC-MAIN-2021-39
refinedweb
175
60.95
A technique works. - How to use dropout on your input layers. - How to use dropout on your hidden layers. - How to tune the dropout level on your problem. Let’s get started. - Update Oct/2016: Updated examples for Keras 1.1.0, TensorFlow 0.10.0 and scikit-learn v0.18. - Update Mar/2017: Updated example for Keras 2.0.2, TensorFlow 1.0.1 and Theano 0.9.0.). Dropout is a technique where randomly selected neurons are ignored during training. They are “dropped-out” randomly. This means that their contribution to the activation of downstream neurons is temporally removed on the forward pass and any weight updates are not applied to the neuron on the backward pass... This in turn results in a network that is capable of better generalization and is less likely to overfit the training data. Need help with Deep Learning in Python? Take my free 2-week email course and discover MLPs, CNNs and LSTMs (with code). Click to sign-up now and also get a free PDF Ebook version of the course. Start Your FREE Mini-Course Now!! Hi Jason, Thanks for the awesome materials you provide! I have a question, I saw that when using dropout for the hidden layers, you applied it for all of them. My question is, if dropout is applied to the hidden layers then, should it be applied to all of them? Or better yet how do we choose where to apply the dropout? Thanks ! 🙂 Great question. I would recommend testing every variation you can think of for your network and see what works best on your specific problem. My cat dog classifier with Keras is over-fitting for Dog. How do I make it unbiased? Consider augmentation on images in the cat class in order to fit a more robust model. I have already augmented the train data set. But it’s not helping. Here is my code snippet. It classifies appx 246 out of 254 dogs and 83 out of 246 cats correctly. Sorry, I don’t have good advice off the cuff. from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K # dimensions of our images. img_width, img_height = 150, 150 train_data_dir = r’E:\\Interns ! Projects\\Positive Integers\\CatDogKeras\\data\\train’ validation_data_dir = r’E:\\Interns ! Projects\\Positive Integers\\CatDogKeras\\data\\validation’ nb_train_samples = 18000 nb_validation_samples = 7000 epochs = 20 batch_size = 144 if K.image_data_format() == ‘channels_first’: input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation(‘relu’)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation(‘relu’)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation(‘relu’)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128)) model.add(Activation(‘relu’)) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation(‘sigmoid’)) model.compile(loss=’binary_crossentropy’, optimizer=’rmsprop’, metrics=[‘accuracy’]) #=(img_width, img_height), batch_size=batch_size, class_mode=’binary’) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode=’binary’) model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size) input(“Press enter to exit”) model.save_weights(‘first_try_v2.h5’) model.save(‘DogCat_v2.h5’) Also, is it possible to get the probability of each training sample after the last epoch? Yes, make a probability prediction for each sample at the end of each epoch: Thanks a lot. This blog and your suggestions have been really helpful. You’re welcome, I’m glad to hear that. I am struck here. I am using binary cross entropy. I want to see probabilities as the actual ones between 0 and 1. But I am getting only maximum probabilities, ie, 0 or 1. For both test and training samples. Use softmax on the output layer and call predict_proba() to get probabilities. Thanks for the great insights on how dropout works. I have 1 question: what is the difference between adding a dropout layer (like your examples here) and setting the dropout parameter of a layer, for example: model.add(SimpleRNN(…, dropout=0.5)) model.add(LSTM(…, dropout=0.5)) Thanks again for sharing your knowledge with us. Thong Bui Nothing really, they are equivalent. Hello Jason, Thanks for your tutorials 🙂 I have a question considering the implementation of the dropout. I am using an LSTM to predict values of a sin wave. Without, the NN is able to catch quite correctly the frequency and the amplitude of the signal. However, implementing dropout like this: model = Sequential() model.add(LSTM(neuron, input_shape=(1,1))) model.add(Dropout(0.5)) model.add(Dense(1)) does not lead to the same results as with: model = Sequential() model.add(LSTM(neuron, input_shape=(1,1), dropout=0.5)) model.add(Dense(1)) In the first case, the results are also great. But in the second, the amplitude is reduce by 1/4 of its original value.. Any idea why ? Thank you ! I would think that they are the same thing, I guess my intuition is wrong. I’m not sure what is going on. Hi Jason, Thanks for all your posts, they are great! My main question is a general one about searching for optimal hyper-parameters; is there a methodology you prefer (i.e. sklearn’s grid/random search methods)? Or do you generally just plug and chug? In addition, I found this code online and had a number of questions on best practices that I think everyone here could benefit from: ”’) ”’ 1) I was under the impression that the input layer should be the number of features (i.e. columns – 1) in the data, but this code defines it as 1. 2) defining the activation function twice for each layer seems odd to me, but maybe I am misunderstanding the code, but doesn’t this just overwrite the previously defined activation function. 3) For regression problems, shouldn’t the last activation function (before the output layer) be linear? Source: Thanks again for all the great posts! James I use grid searching myself. I try to be as systematic as possible, see here: Yes, the code you pasted has many problems. Hi Jason, Thanks for the nicely articulated blog. I have a question. Is it that dropout is not applied on the output layer, where we have used softmax function? If so, what is the rationale behind this? Regards, Azim No, we don’t use dropout on output only on input and hidden layers. The rationale is that we do not want to corrupt the output from the model and in turn the calculation of error. great explanation, Jason! Thanks Alex. How do I plot this code. I have tried various things but get a different error each time. What is the correct syntax to plot this code? What do you mean plot the code? You can run the code by copying it and pasting it into a new file, saving it with a .py extension and running it with the Python interpreter. If you are new to Python, I recommend learning some basics of the language first. hi i want to know that emerging any two kernels in convolutional layer is dropout technique? Sorry, I don’t follow, can you please restate your question? i run your code on my laptop,, but every time result change.. the deference about 15 % This is a common question that I answer here: Hi Jason, I’ve read a lot of your articles and they are generally pretty good. I question your statements here: .” I don’et think it is correct. The goal is to not create MORE representations but a smaller number of robust representations. (I’ve never really seen a specific plausible explanation of co-adaptation. It’s all hand-waving.) Small note: The paper you cite as the “original” paper on dropout is not, it is their 2nd paper. The oriignal one is the one with “co-adaptation” in the title. Craig Will Thanks for the note Craig. Jason, thanks for the example. Apparently it has been working for everyone. However, I get the following error when I run your code estimators.append((‘mlp’, KerasClassifier(build_fn=create_baseline, epochs=300, batch_size=16, verbose=0))) NameError: name ‘create_baseline’ is not defined I was hoping you could help me figure this out, as I haven’t been able to find anything online nor solve it myself Ensure you have copied all of the code from the tutorial and that the indenting matches. This might help: Thanks for the reply! I’m going to try to use it with my own data now Glad to hear that. Simple and clearly explained …..Thanks for such articles I’m glad it helped. Hi Jason, Thanks for your articles. I am learning a lot from them. Btw I ran your code on the same dataset and I got 81.66% (6.89%) accuracy without the dropout layer and a whooping increase to 87.54% (7.07%) accuracy with just dropout at input layer. What I am not able to understand is why the accuracy increased for the same dataset and same model for me and not for you? Is it overfitting in my case? and how do I test for it? Thank you in advance. Nice work. Dropout reduces overfitting. When using dropout, are results reproducible? Can the randomness of which nodes get dropped each time be seeded to produce the same results? The idea is to evaluate a model many times and calculate the average performance, you can learn more here:
https://machinelearningmastery.com/dropout-regularization-deep-learning-models-keras/
CC-MAIN-2018-34
refinedweb
1,608
60.51
polux wrote: > class a: > def go(self): > self.__del__ # or del(self) I suppose you mean: def go(self): self.__del__() ? > > > and then > b=a() > b.go() > > > b is not destructed Since b is defined at module level del b instead of b.go() might be more appropriate. Note that "del x" does not call x.__del__(), it only removes the reference named x from the namespace. In case the object referred to has it's reference count go to zero because of the del statement, the __del__ method of the object _may_ be called. Regards, Ype -- email at xs4all.nl
https://mail.python.org/pipermail/python-list/2003-January/205454.html
CC-MAIN-2016-44
refinedweb
101
86.71
- Code: Select all from tkinter import * because you may overwrite previously imported stuff. However, ttk has the feature that it allows you to overwrite part of tkinter with drop-in replacement widgets: - Code: Select all from tkinter import * from tkinter.ttk import * Now if I try to put it into a namespace called tk: - Code: Select all import tkinter as tk import tkinter.ttk as tk I end up with a namespace tk containing only tkinter.ttk. I.e. import tkinter as tk is destroyed. How can you import tkinter the right way and use the overwriting feature of ttk? The above asumes python3.
http://www.python-forum.org/viewtopic.php?p=5349
CC-MAIN-2015-40
refinedweb
104
57.16
A Surprising Feature of Python Lists What do you expect the output of the following Python code to be? def mutate_or_not(a_list): a_list[0] = "I've changed" my_list = [1, 2, 3] mutate_or_not(my_list) print(my_list) ["I've changed", 2, 3] Depending on how well you understand how Python works under the hood, you may be surprised at this result. You might reason that since my_list is defined in the global scope, it has no business being changed when its value is passed into mutate_or_not() as a paramter. Let’s explore what is happening here. You can step through the code with a great online visualization tool here. Notice how the list is pointed to by both the my_listvariable in the global frame AND the the a_listparameter inside mutate_or_not(). Compare the situation above to the following: def mutate_or_not(an_int): an_int = 7 my_int = 5 mutate_or_not(my_int) print(my_int) >>> 5 Look at the image below: Code tracing available here. Can you see how there is no link between my_int (in the global frame), and an_int, the function parameter? A Practical Example of Python List Mutation Suppose you wish to rotate the items in a list. After some thinking, you might come up with a solution like this: def rotate_list(lst, n): n = n % len(lst) lst = lst[-n:] + lst[:-n] s1 = [1, 2, 5, 4] rotate_list(s1, 1) print(s1) You might expect the output to be a successfully rotated list: [4, 1, 2, 5]. However, it doesn’t work! But didn’t you just say that lists were mutable? The issue here is that when we reassign lst inside the function, the original assignment is lost, and lst now just references the local parameter lst with the new values. The original lst defined outside of the function remains intact. So what can we do about this? Well one solution is given below, but it is very clumsy and not practical. It does illustrate the issue though so it’s worth looking at: def rotate_list_2(lst): lst[0], lst[1], lst[2], lst[3] = lst[3], lst[0], lst[1], lst[2] s1 = [1, 2, 5, 4] rotate_list_2(s1) print(s1) >>> [4, 1, 2, 5] The reason this works is that we do not redefine lst inside the function. Instead we mutate its elements. However a much better solution is to use Python list slicing, as discussed for example here. In Python, my_list[:] refers to the whole list. Using this fact, we can rewrite our rotate_list() function and leverage the immutability of Python lists to achieve the desired result: def rotate_list(lst, n): n = n % len(lst) lst[:] = lst[-n:] + lst[:-n] s1 = [1, 2, 5, 4] rotate_list(s1, 1) print(s1) Mutable and Immutable Data Types in Python Mutability in Python doesn’t just apply to lists and integers, but other data types as well. We just focused on lists in this article to keep things programmatic. Below is a table for easy reference. Conclusion This article has been about the mutability of lists in Python programming. Knowing how this works will help you to avoid some potentially confusing and time-consuming bugs in your code. Happy coding!
https://compucademy.net/python-programming-list-mutation/
CC-MAIN-2022-27
refinedweb
526
68.6
Ticket #13817 (closed defect: fixed) Memory leak in python vboxapi Description This is an issue with the python library in the sdk: sdk/install/vboxapi/__init__.py If you create, then delete, a WEBSERVICE VirtualBoxManager object then it leaves 2 uncollectable objects in the garbage collector: vboxapi.VirtualBoxManager and ZSI.parse.ParsedSoap. The first is due to a circular reference, and the second due to a typo. To replicate: import gc from vboxapi import VirtualBoxManager creds = {'url': '', 'user': 'USERNAME', 'password': 'PASSWORD'} manager = VirtualBoxManager('WEBSERVICE', creds) del manager gc.collect() gc.garbage This displays the uncollectable objects: [<vboxapi.VirtualBoxManager object at 0x0235DED0>, <ZSI.parse.ParsedSoap instance at 0x0413D7D8>] To workaround: Perform the following instead of "del manager": manager.platform.disconnect() del manager.mgr del manager The circular reference issue: __init__.py has a circular reference at the end of the __init__ method of the VirtualBoxManager class (line 996): self.mgr = self; The VirtualBoxManager class also defines a __del__ method (line 998). A circular reference and a __del__ method mean that the object cannot be collected by the garbage collector (see). The typo: In file __init__.py, class PlatformWEBSERVICE, method deinit it calls disconnect(), where it should call self.disconnect() (line 878). Change History comment:2 Changed 6 years ago by klaus Hopefully fixed SDK package is at - feedback is very welcome. comment:3 Changed 6 years ago by ali123 I've tested the new one and the problem is fixed. Thanks very much. comment:4 Changed 6 years ago by klaus Thanks for the quick feedback... will be included in the next 4.3 release. Thanks for letting us know... the circular reference was trivially replaced by a property and the rest you already served on the silver platter. Will try to wrap this up ASAP and pass you a new SDK package for testing.
https://www.virtualbox.org/ticket/13817
CC-MAIN-2020-45
refinedweb
304
51.24
Not so fast, Brian Noyes, chief architect at the consultancy IDesign, told developers at Tech Ed 2007. It's rather simple to host WPF controls in a WinForms application, he said, and it's just as easy to do it the other way around. This sort of interoperability makes sense for several reasons, Noyes continued. The underlying reason is that, though WinForms and WPF controls render differently, underneath both are just components that are .NET class instances. WinForms is a comprehensive set of controls with a familiar, and mature, designer, while the toolset for building WPF controls is both in its infancy and, at the moment, better suited for designers. At the same time, the video, animation and rich text capabilities of Windows Presentation Foundation are simply not possible with WinForms. Therefore, Noyes said, a company ho To host WPF in a WinForms app, developers simply need to add to the controls collection the ElementHost, which resides in the System.Windows.FormsIntegration namespace. It is also important to add a reference to the custom control library and a reference to where that control and its base classes live. "It takes about four lines of code to get this stuff going," Noyes said. The process for hosting WinForms controls in a WPF app is the same, only in this case the host is called the WindowsFormsHost. Now, this sort of interoperability is not without its challenges, Noyes noted: Ultimately, for the moment it is easier to host WinForms apps in Windows Presentation Foundation that vice versa, Noyes said. At the same time, like all good things WinForms development will eventually come to an end. "The libraries are going to be in the .NET Framework until time eternal, but you're going to want to go to WPF to evolve your application further," he.
http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1260170,00.html
crawl-002
refinedweb
302
59.84
#include <hallo.h> * Chris Cheney [Thu, Feb 12 2004, 02:40:31PM]: > > > Even if you are a DD unless you are in the cabal don't bet on > > > getting anything changed. > > > > Ah, conspiracy theories. > > You very well know what I am talking about... The people in the project > that have priviledged positions that other DD's can't replace even if Seconded. I remember (private mail, no names) an answer looking like "You are still a newbie so better shut up" to constructive critics. Reading this to the time when I had dozens of packages and was very active on debian-boot was like a slap in the face. IIRC Adrian Bunk retired some time later - I did not have exactly the same position but I was near to do the same thing. This feeling of having a shadow cabinet cabinet against you does NOT motivate anyone. It makes people feel sick and turn to other tasks instead of helping on the right place. I would also repeat the statement to NMs and other contributors, seen already on this thread: I and many other developers do appreciate your work! It is often much more than $joe-average-DD does. Do never think that not having a DD status makes you be not worthy to talk to the "leet group" among us. Regards, Eduard.
https://lists.debian.org/debian-devel/2004/02/msg00632.html
CC-MAIN-2016-30
refinedweb
223
70.33
Hi!> > Boot.Like this?> >.I have maybe two more patches around this size (i.e. small). Will youtake this? Pavel--- clean/arch/i386/kernel/acpi/sleep.c 2003-02-15 18:51:10.000000000 +0100+++ linux/arch/i386/kernel/acpi/sleep.c 2003-02-18 23:09:01.000000000 +0100@@ -2,6 +2,7 @@ * sleep.c - x86-specific ACPI sleep support. * * Copyright (C) 2001-2003 Patrick Mochel+ * Copyright (C) 2001-2003 Pavel Machek <pavel@suse.cz> */ #include <linux/acpi.h>@@ -34,10 +35,8 @@ */ int acpi_save_state_mem (void) {-#if CONFIG_X86_PAE- panic("S3 and PAE do not like each other for now.");- return 1;-#endif+ if (!acpi_wakeup_address)+ return 1; init_low_mapping(swapper_pg_dir, USER_PTRS_PER_PGD); memcpy((void *) acpi_wakeup_address, &wakeup_start, &wakeup_end - &wakeup_start); acpi_copy_wakeup_routine(acpi_wakeup_address);@@ -65,17 +64,24 @@ /** * acpi_reserve_bootmem - do _very_ early ACPI initialisation *- * We allocate a page in low memory for the wakeup+ * We allocate a page from the first 1MB of memory for the wakeup * routine for when we come back from a sleep state. The- * runtime allocator allows specification of <16M pages, but not- * <1M pages.+ * runtime allocator allows specification of <16MB pages, but not+ * <1MB pages. */ void __init acpi_reserve_bootmem(void) {+ if ((&wakeup_end - &wakeup_start) > PAGE_SIZE) {+ printk(KERN_ERR "ACPI: Wakeup code way too big, S3 disabled.\n");+ return;+ }+#if CONFIG_X86_PAE+ printk(KERN_ERR "ACPI: S3 and PAE do not like each other for now, S3 disabled.\n");+ return;+#endif acpi_wakeup_address = (unsigned long)alloc_bootmem_low(PAGE_SIZE);- if ((&wakeup_end - &wakeup_start) > PAGE_SIZE)- printk(KERN_CRIT "ACPI: Wakeup code way too big, will crash on attempt to suspend\n");- printk(KERN_DEBUG "ACPI: have wakeup address 0x%8.8lx\n", acpi_wakeup_address);+ if (!acpi_wakeup_address)+ printk(KERN_ERR "ACPI: Cannot allocate lowmem, S3 disabled.\n"); } static int __init acpi_sleep_setup(char *str)--
http://lkml.org/lkml/2003/2/18/231
CC-MAIN-2014-35
refinedweb
276
60.51
- Advertisement BKrenzMember Content Count23 Joined Last visited Community Reputation353 Neutral About BKrenz - RankMember - I suppose I can try to hide it a bit better. The only real thing I've overwritten is the AWTRenderer's (as a JPanel) paintComponent() method, which I don't see how I could have avoided. The draw method is inherited from a Renderer interface. The AWTRenderer is really the only thing that needs to know about JFrames and JPanels. The actual drawing should happen like the AWTImage does. I've tried my best to create a layer of Abstraction over everything that's AWT specific. I think the only thing that's not currently are the Assets, which I'm planning on changing over to the Renderer knowing what kind of AssetFactory to create and having the AssetManager pull from the Renderer to get that. EDIT: To reiterate, as I'm not sure I was clear, the invokeLater isn't part of a function that's overriding a Component function. EDIT 2: The reason I extended the JPanel originally was because in order to draw on it, I needed a reference to its Graphics component, which is given in the paint component function. - I'll look into doing this. I sort of see how, but I need to think through how to hide it behind the interfaces I use since it's AWT specific. Will report back. EDIT: Oh, wait duh. Just changed the draw(GameScreen) method in AWTRenderer to: @Override public void draw(GameScreen p_Screen) { this.m_Screen = p_Screen; SwingUtilities.invokeLater( new Runnable() { @Override public void run() { m_Frame.repaint(); } }); } Seems to be working now! - Here's the full AWTRenderer class: [spoiler] package com.stranded.graphics.awt; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import com.stranded.graphics.interfaces.IRenderer; import com.stranded.reference.GameOptions; import com.stranded.reference.GameStrings; import com.stranded.screens.GameScreen; /** * Shell for the Render Engine * To be implemented later * */ public class AWTRenderer extends JPanel implements IRenderer{ /** * */ private static final long serialVersionUID = -4275037581723785182L; /* Class Members */ private Graphics m_Graphics; private GameScreen m_Screen; private JFrame m_Frame; private int m_TestLocAdd; public AWTRenderer () { this.m_Frame = new JFrame(GameStrings.WINDOW_TITLE + " " + GameStrings.VESION_NUMBER); this.m_Frame.add(this); this.m_TestLocAdd = 0; } public void init() { this.m_Frame.setSize(GameOptions.DISPLAY_RESOLUTION_X, GameOptions.DISPLAY_RESOLUTION_Y); this.m_Frame.setDefaultCloseOperation(3); this.m_Frame.setLocationRelativeTo(null); this.m_Frame.setFocusable(true); this.m_Frame.setVisible(true); this.setVisible(true); } @Override public void destroy() { } @Override public void draw(GameScreen p_Screen) { this.m_Screen = p_Screen; this.repaint(); } public Graphics getGraphics() { return this.m_Graphics; } public JFrame getFrame() { return this.m_Frame; } public void setGraphics(Graphics p_Graphics) { this.m_Graphics = p_Graphics; } @Override public void paintComponent(Graphics g_Old) { super.paintComponent(g_Old); this.m_Graphics = g_Old; if (this.m_Screen != null) this.m_Screen.draw(this); this.m_Graphics.setColor(Color.BLACK); this.m_Graphics.fillRect(7, 7 + 72 + 9 + this.m_TestLocAdd, 201, 25); this.m_Graphics.setColor(Color.BLUE); this.m_Graphics.fillRect(8, 8 + 72 + 9 + this.m_TestLocAdd, 201, 24); this.m_TestLocAdd += 1; } } [/spoiler] Whenever I want to redraw (which is currently done in the main loop, ) I call the draw(GameScreen) function in AWTRenderer. As the AWTRenderer is a JPanel itself, it tells itself to repaint. EDIT: I did a little further investigation that I could think of, and tried have a rectangle on screen that moves around with just a simple move its location every time its drawn. However, it gets drawn the first time, and the screen doesnt seem to refresh. However, print statements there (crappy debugging method, I know ) and later down the call chain show the function is being called. EDIT 2: Just remembered that resizing the screen makes it update. This has caused the image to be drawn, and the rectangle moves, but the screen never refreshes on its own. - Was not aware of this. However, I feel like the draw calls I'm making should be on that thread, as the calls are done when the Render is told to repaint. The draw call is done in the paintComponent method, as seen here: @Override public void paintComponent(Graphics g_Old) { super.paintComponent(g_Old); this.m_Graphics = g_Old; if (this.m_Screen != null) this.m_Screen.draw(this); } Edit: I realize the repaint method isn't called within the AWT thread. I'd have to implement the draw loop into that thread, I suppose, to make that happen. For now, that was just happening in the main loop. Could that be the cause? Java, AWT Image not Appearing BKrenz posted a topic in For Beginners's ForumNot too sure this was the right place for this. Code Repo Here I'm writing under the WorldReconfiguration branch. I'm refactoring and rewriting bits of code for someone else. They were originally using AWT for their rendering basis. I've taken their code, and mostly abstracted it so that I can start moving things over to LWJGL or LibGDX painlessly in the near future. Couple issues left there, but I think it's mostly working. Anyways, I almost finished the basis to the AWTRenderer, but have run into an issue. I'm attempting to render an image onto the panel, though it's not appearing. The code is running, not throwing any errors, but I can't figure out why it's not actually drawing. The code in question is this couple of lines (located here) : Graphics l_Graphics = ((AWTRenderer) p_Renderer).getGraphics(); l_Graphics.drawImage( this.m_Image , p_XCoord, p_YCoord, GameOptions.TILE_SIZE, GameOptions.TILE_SIZE, null); Whenever I currently go to draw a scene, I tell the current GameScreen to draw, which calls the AWTRenderer and it repaints, which should tell the GameScreen to start drawing everything with the reference to the Renderer. The GameScreen tells the World to do its drawing, which currently passes the reference to a TileRegion, which passes the Reference to each Tile. The Tile then gets its GraphicsComponent and tells it to draw, which gets the associated GraphicsAsset and tells it to finally draw using the original reference to the Renderer. Bit convoluted in my opinion, but this is my first time doing this stuff. Tried my first implementation of a CBES, too. At this point, I've verified that l_Graphics is not null, that the code is running, and earlier up the call branch I can draw a rectangle which appears and should be using the same Graphics reference. Google hasn't really given me any answers, though I've always been bad at search strings. Also tried drawing a rectangle inside that function, but it doesn't appear either. The issue, as far as I can tell, is with the Graphics. I don't have a solid understanding of AWT, and wasn't planning on it since I want to move libraries/APIs soon. I think it may be related to AWT paint function being called by what I think is a different thread when repaint is called. Before I'm told to move to an engine or different library entirely, I'd like to just get this working. - I generally don't like it when people give this advice. Yes, OpenGL is cross-platform, but anyone who has any experience with cross-platform (or even cross-vendor!) OpenGL development knows how much of a pain it is to get consistent results across platforms and hardware. I'd choose DirectX over OpenGL any time just to avoid the extension and driver compatibility hell. I actually ended up going with DIrectX, via SharpDX. I'm not concerned with actual development at this point in time, and this is more of a side project type of thing than an actual career decision. - Alright, thank you! Learning Graphics Development BKrenz posted a topic in For Beginners's ForumHello all! I'm a somewhat capable programmer in general, currently taking some time off school for personal reasons. In the meantime, I've been reading books on more generalized software development concepts, and working on a few tiny projects for various things. While I'd have loved to get an internship in the industry, my current situation prevents that. I've been interested in games for a while, and am interested in different aspects of developing them. Most recently, I've been wanting to dive into the world of graphics, and have done a minimal amount of research so far. I have one major concern before I start learning, and it's related to the new Vulkan and DX12 APIs. I've noted from various sources that the way of doing things is going to be changing, and that, at least for Vulkan, it should be public by the end of 2015. My concern is that I would start diving into one of the APIs that are out now, DX11 or OGL4+, and would be harmed by learning about how things are currently accomplished. Doing the math isn't a concern on my end, I'm fairly familiar with a lot of calculus, algebra, and geometry. From my understanding, matrices, and to a lesser extent, quaternions, are a major staple of 3D graphics. My question is this: In order to ensure that I'm learning the more "correct" way of doing things, where should I be starting? Is just getting in and doing something in the current APIs the best way to go? I'm not sure where to start. Conceptually, I would think that many things will carry over well (VBOs, etc). However, implementations, and architectures, seem like they'll be changing drastically. Please do note that I'm wanting to learn how to develop directly in the APIs, and not wanting to learn about different engine's ways of handling it or anything like that. The State of the Indie World BKrenz commented on EDI's blog entry in A Keyboard and the TruthI think there is something to be said for Indies and their innovation - those games that truly are good are what shine and be successful. Look at Minecraft - millions of units sold, because it's one of the widest known (almost pure) sandbox game. The way the player is immersed in the world feels great, and how the game can be manipulated to create huge adventure maps, mini-games, huge mods, etc, just makes the game that much better. This is what I feel Indie development really is. What people call Indie now is.. really just big business, on a small level. Business as usual. Get out as much as we can and sell it as fast as we can so we can fill our wallets. Those games are the ones that are force fed and make the market what it is today. It's just too hard to sift through everything for the actual gems. You occasionally see games pop up on Kickstarter that really do look awesome, and you know that just by listening to what the Devs say, and just how much they've already created, that the game will be awesome and will make an impact. Castle Story generated almost 9 times what they were asking for, and the game really looks like I could sink days of gameplay into it. I feel gameplay innovation is spurred by the real Indie developers out there - those that do this because it's a dream, a passion, an obsession. And what are games without gameplay? Where would we be today without the indie developers who are fueling that innovation? Essentially what I'm saying is that the world of Indie development as it's seen today is filled with garbage. I don't really call those games. I call those products. Something that's marketed because it won't sell otherwise. True Games are those things that market themselves - a friend of a friend of a friend played it and wasn't seen for a week because he got all of his friends and their friends into it. - Likely my fault for not clarifying that in the OP, my apologies. Alright, thanks for the advice regarding that. - How do you mean? I had thought that for a programmer a website may be a good idea. Having a place to display projects and possibly a place to post blog posts if I feel it's something important I want to say. I would like to clarify that programming is what I am interested in mainly. I don't yet know which direction I'll take it, but I definitely want to do something involving coding. - If your goal is to write software professionally, then YES, ABSOLUTELY, if your circumstances allow it. The standard filter that HR uses is a computer science degree. There are of course some exceptions, people who are professional programmers without a four year degree, but they are relatively rare these days and aging out of industry. You don't compete in a vacuum. When people look at your job application they will see other people who do have a degree, and you who do not. Which one will they pick? Also, if they do pick you, it is well documented that workers without degrees are paid less than their peers. I think you misunderstood the question. I wasn't referring to whether or not I should stay in college - I most definitely am doing that. I was asking opinions on how to move forward with degree and class choices. Thank you for the feedback, though. College Considerations BKrenz posted a topic in Games Career Development? C++ IDE/Compiler BKrenz replied to BKrenz's topic in General and Gameplay ProgrammingI'm actually decently proficient with C#/Java/Python, so I'm definitely comfortable with a lot of concepts. Like I said, I'm delving into C++, not general programming. And thanks for the advice! C++ IDE/Compiler BKrenz posted a topic in General and Gameplay Programming! - Advertisement
https://www.gamedev.net/profile/209889-bkrenz/
CC-MAIN-2019-22
refinedweb
2,291
65.22