text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
In this post we're going to take a break from showing off features of Python, and we're instead going to focus on how to write Python well. The Python language was created with readability in mind, so we really should do everything in our power to exploit that potential. The result is really beautiful code in our applications.
Code is for humans
I think one of the things that is very easy to forget when we're programming is that code is for humans, not the computer. Languages like Python are an abstraction layer so that we as developers don't have to work with the really low level instructions that a computer understands.
When we're writing Python code, it's really not for the computer to read, it's for you, and other developers.
Why then, do many people write code that's hard for humans to understand?
It's kind of like writing a children's story and using words and grammatical structures that might look right at home in academic discourse. There's a clear disconnect between the material and the intended audience.
With this in mind, let's look at how we can write good, human-friendly, and beautiful Python code.
Coding Style
Any discussion about writing good code is eventually going to land on the topic of code style, so let's get this out of the way at the start.
Python has an official style guide which is detailed in a Python Enhancement Proposal (PEP), called PEP8. If you're feeling masochistic, you read through the whole thing, but I want to focus on a few common issues that I see very frequently.
Names
Names are a topic we're going to come back to later, but here I just want to say a few words about the format of names in Python.
While languages like JavaScript heavily favour camel case, which uses capital letters to mark new words in longer names (e.g.
myVariableName), Python's style guide stipulates the use of something called snake case,
Snake case names are entirely lowercase, and multi-word names are broken up using underscores. For example,
my_variable_name. This pattern is used for variables, functions, methods, etc.
There are two major exceptions to this naming pattern: classes, and constants.
Classes make use of something called Pascal case, which is just the same as camel case, except we also use an initial uppercase letter. An example might be
MyClassName. This initial capital letter is a good indicator in Python that something is a class.
Constants make use of capital letters, and words are broken up using underscores. It's basically just capital letter snake case:
MY_CONSTANT.
It's a good idea to follow these naming patterns in your code, because seasoned Python developers are able to tell a lot about what a variable is, based on how it was named. Misusing these naming styles might make it harder to understand how your code works at a glance.
Indentation
Indentation in Python is very important, because it's how we define blocks of related code. Many other languages would use something like curly braces for this purpose, with indentation being more of an optional visual aid.
Because it has semantic significance, we need to pay extra attention to our indentation in Python, first so that we don't run into bugs, but also so that other developers can understand the hierarchy of our code very easily.
Python recommends four spaces for each level of indentation. Ultimately, the amount of spaces doesn't really matter: it's more important that you're consistent.
However, it is worth keeping in mind that very small and very large indentation sizes have some downsides. One or two space indentation can be hard for people to parse, especially for developers with conditions like dyslexia. Very wide indentation blocks, such as eight spaces, are obviously much easier to spot, but then line length becomes a very limiting factor.
I would recommend sticking to the style guide on this one, but just make sure you're consistent.
Empty lines and other white space
One of the big issues I see in our students' code is that a lot of newer developers in particular are very concerned with writing short code. They don't want to add any empty lines because it makes their code "longer", and they avoid putting spaces within lines of code wherever they're not required.
Don't be afraid to put spaces in your code. Think about if you were writing in English. We break up large blocks of text with paragraphs, so that it's easier to read. We can do the same in code. If we have a block of related functionality, we can make that very clear by putting empty lines around it to make it a single visual unit.
I like to put spaces around things like for loops, for example, because they're generally pretty self-contained.
When it comes to spaces within lines of code, as a general rule, you want to be putting spaces around all binary operators, including the assignment operator, as well as after commas and colons.
Consider the following two lists:
good = [1243.45, 344535.3, 4465.0043, 4775.393, 565.3] bad = [1243.45,344535.3,4465.0043,4775.393,565.3]
I think the example here speaks for itself. It's clearly much easier to read the first list, and to determine information about its contents, than it is with the second list.
Another a good suggestion in the style guide is to put two empty lines after function and class definitions. Since these blocks often include empty lines, the double empty line makes it very easy to spot where the class or function definition ends.
Keep lines short
Coming back to the idea of newer developers often trying to write very short code, a common side effect is very long lines. This is bad for several reasons.
The first is entirely down to hardware limitations. Screens are only so wide, so if you go to real extremes to keep code on a single line, you inevitably introduce horizontal scrolling. This means that a reader of your code can't read all of the logic in one go, and they have to flick backwards and forwards to parse your code. Of course you can enable text wrapping, but then why not just put the code on two lines? At least then you have a logical break point, rather than the code being split based on how big the reader's monitor happens to be.
A second issue is down to limitations in us as humans. We find it very difficult to read long lines of text quickly, and there's a few good reasons for that.
Very fast readers work in several word chunks, or even whole lines, but our peripheral vision is only so good. As line length increases, the amount of eye movement required to read the lines goes up, and this slows down reading speed.
It's also very common for people to lose which line they're reading, the more the eye has to move. This leads to a lot of re-reading of the same material.
There's a very good reason that larger print formats such as magazines and newspapers break up text into several columns: it's much easier for us to read the information that way. This is also why many websites have very large gutters on either side of the site content, because the main content it limited to a comfortable reading width.
The final major issue with long lines is code complexity. The lines are not longer for no reason: more things have been put on these lines which is what made them longer. This invariably leads to more dense logic, which again, is much harder for human readers.
Complicated logic very quickly becomes difficult for us to reason about, so it's very important that we resist the temptation to chain many operations together in our code. If it takes five more lines to write in a very clear and understandable way, it's worth it.
Automatic formatting
Even the best of us sometimes diverge from good practices now and then, so it's a good idea to make use of tools to automatically format our code after the fact.
One tool you might want to check out is Black. It uses a somewhat liberal interpretation of PEP8, particularly when it comes to things like line length. PEP8 stipulates a very strict maximum line length, but this can sometimes lead to less readable code, especially when we're splitting code over multiple lines because we went one character over the limit.
A final word on PEP8
As I just mentioned, there are times when strictly adhering to PEP8 isn't always the best thing. It's a good rule of thumb for writing code in good style, but it's also useful to know when not to follow PEP8.
Don't treat PEP8 like the 10 Commandments, but make sure you know why you're breaking the rules before you do so.
Using good names
I often say to students on our courses that variables names are basically just built in documentation; it's a total waste not to exploit that. Variable names like
x or
list_1 are throwing away a golden opportunity to describe the values associated with those variables.
Choosing good names is hard, and it's definitely a skill you need to develop, but it's worth putting in the effort to learn.
Take the following example:
list_1 = ["John", "Rolf", "Sarah", "Anne"] for e in list_1: print(e)
This is quite simple code, but even here we can make it far more obvious what the for loop is doing by just using good names:
friends = ["John", "Rolf", "Sarah", "Anne"] for friend in friends: print(friend)
An even more explicit version might look like this:
friends = ["John", "Rolf", "Sarah", "Anne"] for friend_name in friends: print(friend_name)
Now imagine what a difference this makes when the logic is actually complicated.
One final thing to keep in mind with names is the use of the singular and plural. A name like
number indicates to a reader that this is probably a single value, while something like
numbers indicates that something is a collection.
In general, try to reserve plural names for collections, but make sure you do use them when appropriate.
Pythonic Loops
We've already seen an example of a good for loop above, but many people write their Python loops in very different way. It's common to see a pattern like this:
friends = ["John", "Rolf", "Sarah", "Anne"] for i in range(len(friends)): print(friends[i])
The code above is absolutely identical in function to this:
friends = ["John", "Rolf", "Sarah", "Anne"] for friend_name in friends: print(friend_name)
The first example comes from a misunderstanding regarding how Python's for loop works. Python uses a "for each" style loop, where we get direct access to the elements within an iterable. However, many languages use a more traditional for loop, where you create a counter and some stopping condition, and you might use this to access items in a collection by index.
The benefit of the "for each" loop is that we get to use good, descriptive names, and we don't have to faff around with indices. As a general rule, if you're referring to indices in something like a loop in Python, there's probably a better way to do it.
So, what are some of those better ways?
Using
zip
One common place where I see indices used in Python is when somebody is trying to work with two or more iterables at the same time. For example, maybe we have a list of names, and we have a list of corresponding ages, and we want to print out both using the same loop.
A naïve approach might look like this:
names = ["John", "Rolf", "Sarah", "Anne"] ages = [27, 42, 31, 29] for i in range(len(names)): print(f"{names[i]} is {ages[i]} years old.")
To be clear, this code works perfectly. However, I think if the logic was more complicated, this type of approach would quickly get very difficult to read.
We can make this code a great deal cleaner using the
zip function. We have a blog post on this function already, so please check that out to learn more. You can also check out the documentation.
Using
zip the above code now looks like this:
names = ["John", "Rolf", "Sarah", "Anne"] ages = [27, 42, 31, 29] for name, age in zip(names, ages): print(f"{name} is {age} years old.")
Using
enumerate
A less common, but still fairly frequent use of indices in loops, is when somebody needs some kind of a counter, and they think they can kill two birds with one stone by generating this counter first, and using it as an index as well.
Something like this, perhaps:
names = ["John", "Rolf", "Sarah", "Anne"] for i in range(len(names)): print(f"Person {i + 1} is called {names[i]}")
While this code is perfectly functional, we can make things cleaner by using the
enumerate function. Again, we have a post on
enumerate already, so you should check that out for more information. You can also look in the documentation.
Using
enumerate the code above looks like this:
names = ["John", "Rolf", "Sarah", "Anne"] for counter, name in enumerate(names, start=1): print(f"Person {counter} is called {name}")
Destructuring
Both of the examples above made use of a technique called destructuring, which we also have a blog post about, but I want to talk about another situation where destructuring can be very useful.
In our Complete Python Course, we have an exercise in which students create a quiz system, where they have a file containing questions and answers. They need to split each line of the file into questions and answers, where each line looks something like this:
3+8=11.
A lot of students go for something along these lines:
for line in question_file: question = line.split("=")[0] answer = line.split("=")[1]
However, this is another perfect opportunity to do away with indices, and destructuring is our weapon of choice:
for line in question_file: question, answer = line.split("=")
This technique can be used any time we're working with some ordered collection, and we want to split it into its component parts. It's well worth getting familiar with, and it will make your code a great deal cleaner.
Idiomatic conditionals
I feel like conditionals in Python are something of a shibboleth which can quickly identify you as somebody who maybe generally works in another language.
It's quite common to see code like this:
if len(some_list) != 0: ... do something
Or:
if some_string != "": ... do something
This is certainly very explicit code, and I don't think there's anything wrong with it, per se, but it's not very idiomatic: it's not how most experienced Python developers would write something like this. Instead, it's very common to rely on the truth values of certain types.
In Python, very few things evaluate to
False, but empty collections are one of them. This means strings, sets, tuples, dictionaries, lists, etc.
As such, instead of writing the examples above, we could write this:
if some_list: ... do something if some_string: ... do something
In both cases, these conditions just mean, "if the collection isn't empty".
Multiple return values
We can go one step further with this trick when we're using the conditions to control which
return statement is triggered in a function or method.
As an example, we might have a function which asked the user for their name, and then returns either the name, or
"John Doe" if no name was entered by the user. Using what we learnt above, we might write something like this:
def get_name(): name = input("Please enter your name: ") if name: return name return "John Doe"
However, we can make use of the Boolean
or operator to make this a great deal shorter.
def get_name(): name = input("Please enter your name: ") return name or "John Doe"
The
or operator in Python yields the first operand if it evaluates to
True, which in our case means the
name string isn't empty, otherwise it yields the second operand. As such, in any case where the user entered a name,
name is returned by the
get_name function; otherwise, it returns
"John Doe".
This trick also works for assignments as well!
Once again, we have a blog post covering Boolean operators where we talk about this useful property of
or.
Comprehensions
The last thing I want to talk about in this post is using comprehensions. Comprehensions are used to create a new collections from another iterable, and they're an alternative to the more verbose for loop syntax in those instances. Personally, I absolutely love them!
As an example, maybe we have a list of lowercase names, and we want a new list where they're all in title case instead, with an initial capital letter. The for loop version would look like this:
names = ["rolf", "james", "jose", "sarah", "lucy"] title_names = [] for name in names: title_names.append(name.title())
One limitation of this method is that we can't reuse the
names variable name, even if we no longer plan to use the values. It's also got a fair bit of boilerplate code.
A comprehension version would look like this:
names = ["rolf", "james", "jose", "sarah", "lucy"] names = [name.title() for name in names]
Or, if we wanted to preserve the original list:
names = ["rolf", "james", "jose", "sarah", "lucy"] title_names = [name.title() for name in names]
We have a couple of posts on list comprehensions. The first covers basic list comprehensions like we see above, and the second covers list comprehensions with conditionals.
Python also has other types of comprehensions, such as set comprehensions and dictionary comprehension which can be used in a very similar way. I've spoken about these in another post.
Comprehensions are a great tool to have in your repertoire, so definitely get familiar with them.
Wrapping up
This was quite a long one, so thanks for sticking with me to the end! I hope you learnt some new tricks to help you clean up your Python code.
We cover a lot of material like this on our Complete Python Course, so if you're interested in taking your Python to the next level, check it out.
We also have a community on Discord where you can get help and advice, as well as a mailing list so you can keep up to date with all our content. We also send discount codes to our subscribers, so make sure to sign up below to get the best deals on our courses. | https://blog.tecladocode.com/writing-clean-python/ | CC-MAIN-2019-47 | refinedweb | 3,162 | 67.59 |
Installing schemas - starting to give up
Hey,
I'm trying to install schemas with Oracle XE or Enterprise.
I managed to unlock HR user as it's installed with XE but no luck with other schemas. They're not in demo folder, I also tried to download them but when i start oe_main.sql it crashes on creating tables like customers saying something about wrong datatype
I did found information that with full installed all schemas are installed automaticly but sadly nothing like that happened to me
I refered to this doc: but it was crashing like i said before. It's been almost a week strugle and i'm out of ideas. Could you please help
Answers
*** Moderator Note: Now moved to General Database space (I was in two minds whether to put it in installation, but I think this is the better for this question). Please note that the "Community Feedback (No Product Questions)" space is exactly what it says in the title, a space for feeding back on the actual community and NOT a place to ask product related questions. Please ensure you search for the correct product related space for your product questions in future.
- John Thorton Member Posts: 14,493 Silver Crown
For people to be able to help you'll need to post the exact error messages you're receiving and not 'something like'
- Mark D Powell Member Posts: 5,914 Blue Diamond
What full version of Oracle are you using? Did you obtain the oe_main.sql script that matches the version of Oracle you have?
- -
Since as Rob noted you did not post the actual error message you are receiving I was unable to search Oracle support for known issues related to the error but perhaps the following will give you an idea
- -
HTH -- Mark D Powell --
SP2-0310: unable to open file "C:\oraclexe\app\oracle\product\11.2.0\server/demo/schema/order_entry/xdbSupport.sql"SP2-0310: unable to open file "C:\oraclexe\app\oracle\product\11.2.0\server/demo/schema/order_entry/createUser.sql"Connected.Session altered.SP2-0310: unable to open file "C:\oraclexe\app\oracle\product\11.2.0\server/demo/schema/order_entry/xdb03usg.sql"Connected.Revoke succeeded.Revoke succeeded.Revoke succeeded.DROP PACKAGE xdb.xdb_configuration*ERROR at line 1:ORA-04043: object XDB_CONFIGURATION does not existDROP PACKAGE xdb.xdb_namespaces*ERROR at line 1:ORA-04043: object XDB_NAMESPACES does not existDROP PACKAGE xdb.xdb_dom_helper*ERROR at line 1:ORA-04043: object XDB_DOM_HELPER does not existDROP PACKAGE xdb.xdb_utilities*ERROR at line 1:ORA-04043: object XDB_UTILITIES does not existDROP PACKAGE xdb.xdb_tools*ERROR at line 1:ORA-04043: object XDB_TOOLS does not existDROP TRIGGER xdb.no_dml_operations_allowed*ERROR at line 1:ORA-04080: trigger 'NO_DML_OPERATIONS_ALLOWED' does not existDROP VIEW xdb.database_summary*ERROR at line 1:ORA-00942: table or view does not exist
I removed all Oracle instances, installed XE version, unlocked HR and runned oe_main.sql from sqlplus logged as sysdba. It has created tables and views, and i'm attaching log from errors. Are they important for study?
Thanks!
Your log shows three messages of "unable to open file". Show proof that those files exist.
- Mark D Powell Member Posts: 5,914 Blue Diamond
As Ed noted, why are the files that the routine needs unavailable? Do you have the files located in the correct location and owned by the Oracle user? Or at least accessible by the Oracle user?
- -
HTH -- Mark D Powell --
Well they're not there, but i didn't changed anything. Downloaded, copied to folder and run.
74074185-0997-4dd4-b3eb-acbb19b40a1c wrote:Well they're not there, but i didn't changed anything. Downloaded, copied to folder and run.
Due to a warp in the time-space continuum (possibly a gravitational wave discovered by the recipients of this week's Nobel award in physics) I am unable to see over your shoulder to know exactly what you did.
Downloaded what?
Copied to what folder?
What did you run? from where? How?
- Billy Verreynne Software Engineer Member Posts: 28,860 Red Diamond
Also, to add to Ed's comments - the What Downloaded? is important to answer. Oracle XE, as a free and no-cost version, does not have the full Oracle RDMS feature set. The XDB component for example is a limited install. There is no Java VM runtime. Etc.
The what downloaded will point to the Oracle feature set required, whether XE can be used, and how to correctly install it in XE, if at all. | https://community.oracle.com/tech/developers/discussion/comment/14549059/ | CC-MAIN-2022-40 | refinedweb | 754 | 56.25 |
Excuse me for double post. I thought it failed after submitting.
Type: Posts; User: JorgeChemE
Excuse me for double post. I thought it failed after submitting.
This is maybe the last exercise I will do of my course (yet finished). We have 6 exercises that our instructor left in the last class, 6 exercises about memory allocation, this is the fourth one.
...
This is maybe the last exercise I will do of my course (yet finished). We have 6 exercises that our instructor left in the last class, 6 exercises about memory allocation, this is the fourth one.
...
I'm still solving the remaining exercises, 6, but once finished, I will need good books to learn by myself. In fact, I would want to ask about resources to learn about: pointers, string management,...
Insert the number or characters: 10
Insert the text: Unimaginatively
tanigaminU
The thing is to allocate the memory that the user insert through keyboard (my instructor seems to be a fanatic of...
I am trying another cleaner code. What do you think?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
char *ptr;
Thank you for your information. In the meantime I study laser code, what if I want to get the string reverted? For example: Hi my name is Jorge -> egroJ si eman ym iH
Using the same code, I tried...
Thank you for your code Laser. I want to study it, however, I wonder I have not enough knowledge to understand some parts. I didn't study stderr so I have no idea what this function does.
This is the code that does the work:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i=1;
This is the best code I have until now, works good, do what should be doing. Since I am not enrolled in the course (finished) I am open to improvements.
#include <stdio.h>
#include <stdlib.h>
...
I'm not conviced with the results... Program works with small words but if I put a num=10 and write a large word, crashes...
Hi guys,
After messing up the code, according to your recommendations, I changed the loop "for" for "while". This is the code right now:
#include <stdio.h>
#include <stdlib.h>
int main()
Sorry, I forgot to remove using namespace std;. This is C, I am trying to solve it in C. I will fix the code, see now.
Thank you for the printf. I used the fflush(stdin) because the program...
Hi. I am trying to understand dynamic memory allocation. Now I am learning by myself, so any advice will be appreciated and taken into account in the code since nobody but me will see it.
I am...
Yes, I removed num_leidos, took the idea of one of my classes. This is exactly what I am doing, saving and loading the file in every function. After a hard work I will have the chance to submit the...
I know how to make a menu but I need something with a similar appearance to this:
Thanks in advance
Edited: What I don't know...
Never mind, solved by myself, int num_leidos=1; num_leidos= removed and substituted by &primero. Now prints all the records. You can ignore this post.
ok, I have an update I made this changes:
typedef struct {
unsigned int dia;
unsigned int mes;
unsigned int anio;
} fecha;
Hi, I hope someone can clarify me how can I read from a file using a pointer that I need to read all the pets that I am adding through a function. Before reading from a file, everything worked...
Worked perfectly, thank you!
Hi,
I am making an easy program that reads a text from a file and prints the content line by line indicating each number of line and printing >> at the end of each line.
This is the file:...
This is a good and polite manner to say things and I appreciate it. Just remember because I told you lots of times: this is not my field of knowledge, this is not what I must do to earn a salary and...
Ok, thank you for all your support, is appreciated.
Jim, I know how to use fgets but we are required to submit this project to be evaluated, in class we only studied scanf and gets for this purpose, we also studied getch, getchar, getche, puts and...
To protect my work I changed the code a little, the program is not about patients, is about a pets and a vet. Anyway, this is my code, ony this part of modifying pets:
Structure:
typedef... | https://cboard.cprogramming.com/search.php?s=6e13793a39a89897ce865a81b7affe53&searchid=6042679 | CC-MAIN-2020-45 | refinedweb | 767 | 82.95 |
In my last post, I showed how to retrieve a file system ACL (well, technically a security descriptor) via PowerShell. Today I'll show you how to tweak that ACL using System.Security.AccessControl.
$newRule = New-Object Security.AccessControl.FileSystemAccessRule "keith", Modify, Allow
This next line of code in my example creates an "access rule". This is a lot like an Access Control Entry (ACE) in the Win32 API, if you happen to be familiar with that. A rule has several parts that describe a permission that you want to grant or deny:
Note how I created this object in PowerShell. The New-Object cmdlet allows you to specify a .NET type that you want to instantiate. In this case, I'm creating an instance of System.AccessControl.FileSystemAccessRule, although I've saved some space by omitting "System." since PowerShell searches that namespace by default.
Following the type name is an array that contains the ctor arguments. Constructing an access rule is pretty easy since you can pass strings that represent the user or group accounts, and the framework will happily look up the Security Identifier (SID) on your behalf. Little features like this are one reason working with System.Security.AccessControl is so much more pleasant than the underlying Win32 interface! Note that here I'm just using the account name, "Keith", but I could have been more specific and used the fully-qualified MACHINE\ACCOUNT or DOMAIN\ACCOUNT syntax, such as, "MyDomain\Keith". And in practice I'd be using a group instead of an individual user to grant permissions (for this example I decided to stick with something really concrete and easy).
The second and third ctor arguments show off one of my favorite features of PowerShell. I hate typing any more than I have to, and it's great to have context-sensitive evaluation of enumerations like this. By simply passing in the symbol, Modify, PowerShell knows that I mean FileSystemRights.Modify. The same goes for AccessControlType.Allow. This can make your code more readable than even the equivalent C# code because it eliminates so much clutter.
I'll have more to say about enumerations and PowerShell in my next post.
Navigate posts in this series: prev next | http://www.pluralsight.com/community/blogs/keith/archive/2007/10/31/48903.aspx | crawl-002 | refinedweb | 372 | 56.76 |
Setup Error Reporting in React
Let’s start by setting up error reporting in React. To do so, we’ll be using Sentry. Sentry is a great service for reporting and debugging errors. And it comes with a very generous free tier.
In this chapter we’ll sign up for a free Sentry account and configure it in our React app. And in the coming chapters we’ll be reporting the various frontend errors to it.
Let’s get started.
Create a Sentry Account
Head over to Sentry and hit Get Started.
Then enter your info and hit Create Your Account.
Next hit Create project.
For the type of project, select React.
Give your project a name.
And that’s it. Scroll down and copy the
Sentry.init line.
Install Sentry
Now head over to the project root for your React app and install Sentry.
$ npm install @sentry/browser --save
We are going to be using Sentry across our app. So it makes sense to keep all the Sentry related code in one place.
Add the following to the top of your
src/libs/errorLib.js.
import * as Sentry from "@sentry/browser"; const isLocal = process.env.NODE_ENV === "development"; export function initSentry() { if (isLocal) { return; } Sentry.init({ dsn: "" }); } export function logError(error, errorInfo = null) { if (isLocal) { return; } Sentry.withScope((scope) => { errorInfo && scope.setExtras(errorInfo); Sentry.captureException(error); }); }
Make sure to replace
Sentry.init({ dsn: "" }); with the line we copied from the Sentry dashboard above.
We are using the
isLocal flag to conditionally enable Sentry because we don’t want to report errors when we are developing locally. Even though we all know that we rarely ever make mistakes while developing…
The
logError method is what we are going to call when we want to report an error to Sentry. It takes:
- An Error object in
error.
- And, an object with key-value pairs of additional info in
errorInfo.
Next, let’s initialize our app with Sentry.
Add the following to the end of the imports in
src/index.js.
import { initSentry } from './libs/errorLib'; initSentry();
Now we are ready to start reporting errors in our React app! Let’s start with the API errors.
For help and discussionComments on this chapter | https://serverless-stack.com/chapters/setup-error-reporting-in-react.html | CC-MAIN-2021-04 | refinedweb | 370 | 61.33 |
Net::ACL - Class representing a generic access-list/route-map
use Net::ACL; use Net::ACL::Rule qw( :action :rc ); # Constructor $list = new Net::ACL( Name => 'MyACL', Type => 'prefix-list', Rule => new Net::ACL::Rule( .. ) ); # Fetch existing object by name $list = renew Net::ACL( Name => 'MyACL' Type => 'prefix-list' ); $list = renew Net::ACL("$list"); # Object Copy $clone = $list->clone(); # Class methods $type_names_hr = Net::ACL->knownlists(); # Accessor Methods $list->add_rule($rule); $list->remove_rule($rule); $name = $list->name($name); $type = $list->type($type); $rc = $list->match(@data); ($rc,@data) = $list->query(@data);
This module represents a generic access-list and route-map. It uses the Net::ACL::Rule object to represent the rules.
$list = new Net::ACL( Name => 'MyACL', Type => 'prefix-list', Rule => new Net::ACL::Rule( .. ) );
This is the constructor for Net::ACL objects. It returns a reference to the newly created object. The following named parameters may be passed to the constructor.
The name parameter is optional and is only used to identify a list by the renew() constructor.
The type parameter is optional and defaults to the class name. It is used have different namespaces for the Name parameter. It is intended to have values like 'ip-accesslist', 'prefix-list', 'as-path-filter' and 'route-map'. This way the same name or number of an access-list could be reused in each class.
The rule parameter could be present one or more times. Each one can have multiple types:
A Net::ACL::Rule object.
An array reference of Net::ACL::Rule objects.
A hash reference with Net::ACL:Rule objects as values. Keys are currently ignored, but might later be used as sequance numbers or labels.
$list = renew Net::ACL( Name => 'MyACL' Type => 'prefix-list' ); $list = renew Net::ACL("$list");
The renew constructor localizes an existing ACL object from either Name, (Name,Type)-pair or the object in string context (e.g.
Net::ACL=HASH(0x823ff84)). The Name and Type arguments have similar meaning as for the new() constructor.
$clone = $list->clone();
This method creates an exact copy of the Net::ACL object and all the rules. The clone will not have a name unless one is assigned explicitly later.
The name() and type() methods return the access-list name and type fields respectively. If called with an argument they change the value to that of the argument.
The match method implements the basics of a standard router access-list matching.
It gets any arbitrary number of arguments. The arguments are passed to the match() method of each of the Net::ACL::Rule rules except any object which have the action() field set to
ACL_CONTINUE. When a match() method returns
ACL_MATCH, the action() of that entry is returned.
The query method implements the basics of a route-map execution.
It calls the Net::ACL::Rule rules query() method one by one as long as they return
ACL_CONTINUE.
The function returns the result code (
ACL_PERMIT or
ACL_DENY) and the, possibly modified, arguments of the function.
The add() and remove() rule methods can add and remove rules after object construction.
Net::ACL::Rule, Net::ACL::File, Net::ACL::Bootstrap
Martin Lorensen <bgp@martin.lorensen.dk> | http://search.cpan.org/~lorensen/Net-ACL-0.07/lib/Net/ACL.pm | CC-MAIN-2014-35 | refinedweb | 524 | 57.37 |
Exporter::Tidy - Another way of exporting symbols
package MyModule::HTTP; use Exporter::Tidy default => [ qw(get) ], other => [ qw(post head) ]; use MyModule::HTTP qw(:all); use MyModule::HTTP qw(:default post); use MyModule::HTTP qw(post); use MyModule::HTTP _prefix => 'http_', qw(get post); use MyModule::HTTP qw(get post), _prefix => 'http_', qw(head); use MyModule::HTTP _prefix => 'foo', qw(get post), _prefix => 'bar', qw(get head); package MyModule::Foo; use Exporter::Tidy default => [ qw($foo $bar quux) ], _map => { '$foo' => \$my_foo, '$bar' => \$my_bar, quux => sub { print "Hello, world!\n" } }; package MyModule::Constants; use Exporter::Tidy default => [ qw(:all) ], _map => { FOO => sub () { 1 }, BAR => sub () { 2 }, OK => sub () { 1 }, FAILURE => sub () { 0 } };
This module serves as an easy, clean alternative to Exporter. Unlike Exporter, it is not subclassed, but it simply exports a custom import() into your namespace.
With Exporter::Tidy, you don't need to use any package global in your module. Even the subs you export can be lexically scoped.
The list supplied to
use Exporter::Tidy should be a key-value list. Each key serves as a tag, used to group exportable symbols. The values in this key-value list should be array references. There are a few special tags:
If you don't provide an
all tag yourself, Tidy::Exporter will generate one for you. It will contain all exportable symbols.
The
default tag will be used if the user supplies no list to the
use statement.
With _map you should not use an array reference, but a hash reference. Here, you can rewrite symbols to other names or even define one on the spot by using a reference. You can
foo => 'bar' to export
bar if
foo is requested.
Every symbol specified in a tag's array, or used as a key in _map's hash is exportable.
You can export subs, scalars, arrays, hashes and typeglobs. Do not use an ampersand (
&) for subs. All other types must have the proper sigil.
You can use either a symbol name (without the sigil if it is a sub, or with the appropriate sigil if it is not), or a tag name prefixed with a colon. It is possible to import a symbol twice, but a symbol is never exported twice under the same name, so you can use tags that overlap. If you supply any list to the
use statement,
:default is no longer used if not specified explicitly.
To avoid name clashes, it is possible to have symbols prefixed. Supply
_prefix followed by the prefix that you want. Multiple can be used.
use Some::Module qw(foo bar), _prefix => 'some_', qw(quux);
imports Some::Module::foo as foo, Some::Module::bar as bar, and Some::Module::quux as some_quux. See the SYNOPSIS for more examples.
Exporter::Tidy "versus" Exporter
These numbers are valid for my Linux system with Perl 5.8.0. Your mileage may vary.
Exporting two symbols using no import list (@EXPORT and :default) is approximately 10% faster with Exporter. But if you use any tag explicitly, Exporter::Tidy is more than twice as fast (!) as Exporter.
perl -le'require X; print((split " ", `cat /proc/$$/stat`)[22])' No module 3022848 Exporter::Tidy 3067904 Exporter 3084288 Exporter::Heavy 3174400
Exporter loads Exporter::Heavy automatically when needed. It is needed to support exporter tags, amongst other things. Exporter::Tidy has all functionality built into one module.
Both Exporter(::Heavy) and Exporter::Tidy delay loading Carp until it is needed.
Exporter is subclassed and gets its information from package global variables like @EXPORT, @EXPORT_OK and %EXPORT_TAGS.
Exporter::Tidy exports an
import method and gets its information from the
use statement.
Pick your favourite OSI approved license :)
Thanks to Aristotle Pagaltzis for suggesting the name Exporter::Tidy.
Juerd Waalboer <juerd@cpan.org> <> | http://search.cpan.org/~juerd/Exporter-Tidy-0.07/Tidy.pm | CC-MAIN-2015-48 | refinedweb | 624 | 64.91 |
This is a very simple class that will search a given AD group and all groups beneath it and return all user accounts that are members of these groups.
This sounds really simple, and it is, but when I searched the Internet for a solution, I could not find one, so I thought I'd share it here.
There are basically three methods in this class, all are marked
static, so you don't have to instantiate the class to use the
public method.
Just call the method
x(string strGroupName), pass in the name of the group (display name, not the DN), you get an
ArrayList containing the SAM Account Names of all users in this group or any sub-group. If your AD should contain several groups with the same name, which is a bad practice anyway, it will just use the first it finds.
x will then call
getUsersInGroup(string strGroupDN) passing in the DN of the group you chose.
getUsersInGroup will first collect all users that are members of this group, then walk though all groups in the given group and call itself recursively for each group.
In order to avoid endless loops when you have a circular group structure in AD, it keeps track of all "visited" groups in the global variable,
searchedGroups.
using System; using System.Collections; using System.Text; using System.DirectoryServices; namespace ADgroupSearcher { class getGroupMembers { /// <summary> /// searchedGroups will contain all groups already searched, in order to /// prevent endless loops when there are circular structures in the groups. /// </summary> static Hashtable searchedGroups = null; /// <summary> /// x will return all users in the group passed in as a parameter /// the names returned are the SAM Account Name of the users. /// The function will recursively search all nested groups. /// Remark: if there are multiple groups with the same name, /// this function will just /// use the first one it finds. /// </summary> /// <param name="strGroupName">Name of the group, /// which the users should be retrieved from</param> /// <returns>ArrayList containing the SAM Account Names /// of all users in this group and any nested groups</returns> static public ArrayList x(string strGroupName) { ArrayList groupMembers = new ArrayList(); searchedGroups = new Hashtable(); // find group DirectorySearcher search = new DirectorySearcher("LDAP://DC=company,DC=com"); search.Filter = String.Format ("(&(objectCategory=group)(cn={0}))", strGroupName); search.PropertiesToLoad.Add("distinguishedName"); SearchResult sru = null; DirectoryEntry group; try { sru = search.FindOne(); } catch (Exception ex) { throw ex; } group = sru.GetDirectoryEntry(); groupMembers = getUsersInGroup (group.Properties["distinguishedName"].Value.ToString()); return groupMembers; } /// <summary> /// getUsersInGroup will return all users in the group passed in as a parameter /// the names returned are the SAM Account Name of the users. /// The function will recursively search all nested groups. /// </summary> /// <param name="strGroupDN">DN of the group, /// which the users should be retrieved from</param> /// <returns>ArrayList containing the SAM Account Names /// of all users in this group and any nested groups</returns> private static ArrayList getUsersInGroup(string strGroupDN) { ArrayList groupMembers = new ArrayList(); searchedGroups.Add(strGroupDN, strGroupDN); // find all users in this group DirectorySearcher ds = new DirectorySearcher("LDAP://DC=company,DC=com"); ds.Filter = String.Format ("(&(memberOf={0})(objectClass=person))", strGroupDN); ds.PropertiesToLoad.Add("distinguishedName"); ds.PropertiesToLoad.Add("givenname"); ds.PropertiesToLoad.Add("samaccountname"); ds.PropertiesToLoad.Add("sn"); foreach (SearchResult sr in ds.FindAll()) { groupMembers.Add(sr.Properties["samaccountname"][0].ToString()); } // get nested groups ArrayList al = getNestedGroups(strGroupDN); foreach (object g in al) { // only if we haven't searched this group before - avoid endless loops if (!searchedGroups.ContainsKey(g)) { // get members in nested group ArrayList ml = getUsersInGroup(g as string); // add them to result list foreach (object s in ml) { groupMembers.Add(s as string); } } } return groupMembers; } /// <summary> /// getNestedGroups will return an array with the DNs of all groups contained /// in the group that was passed in as a parameter /// </summary> /// <param name="strGroupDN">DN of the group, /// which the nested groups should be retrieved from</param> /// <returns>ArrayList containing the DNs of each group /// contained in the group passed in as a parameter</returns> private static ArrayList getNestedGroups(string strGroupDN) { Array()); } return groupMembers; } } }
This code is provided for your convenience. It certainly needs proper error handling added, and maybe there are better solutions? I will not change the code, as it does what I needed it to do. I used it for a one-time chore only. If you know better/faster solutions, I look forward to your comments.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/nestedADgroups.aspx | crawl-002 | refinedweb | 730 | 52.19 |
CodePlexProject Hosting for Open Source Software
I'm trying to get a registered service in an HtmlHelper extension. How can I get to the autofac container that has all registered services?
I've tried
var ctx = DependencyResolver.Current.GetService<IUserContext>();
and even
var container = new ContainerBuilder().Build();
var ctx = container.Resolve<IUserContext>();
but both don't work.
Is there a way to access the services registered in the container from a static function?
There is an extension method in the namespace Orchard.Mvc.Html, which lets you do Html.Resolve<TService>
You can find its definition in \src\Orchard\Mvc\Html\ContainerExtensions.cs
Works like a charm, thanks!
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/269671 | CC-MAIN-2017-09 | refinedweb | 144 | 62.95 |
As a part of the It’s Okay to Be New series, I’ve been doing a lot of research about containers this week. My goal is to lay the foundation for anyone, regardless of technical background, to be able to start playing with and learning about containers — be it LXC, Docker, or the next big container technology.
Personally, I learn best through stories, and in order to tackle something new, I have to develop the story in my head; I like to understand not only where we are in the learning process, but also how we got here. So I started piecing together the history of container technology, and I found out that to fully understand it, we need to go back much further than you would think. We need to go back to the early days of virtualization in the 1960s.
Development of Virtualization
Back in the ’60s, computers were a rare commodity. It cost well over a thousand dollars a month just to rent one, putting them out of reach for many businesses. To put that into perspective, $1,000 in 1960 had the same buying power as $8,385 in 2018.
They say necessity is the mother of invention, and the history of computers is no exception. The earliest computers were typically dedicated to a specific task that might take days or even weeks to run, which is why in the 1960s and through the 1970s, we saw the development of virtualization. This development was spurred by the need to share computer resources among many users at the same time.
With the creation of centralized computers, we began to see the first hints of what we now call virtualization.
Throughout the 1960s, multiple computer terminals were connected to a single mainframe, which allowed computing to be done at a central location. Centralized computers made it possible to control all processing from a single location, so if one terminal were to break down, the user could simply go to another terminal, log in there, and still have access to all of their files.However, this did have some disadvantages. For example, if the user were to crash the central computer, the system would go down for everyone. Issues like this made it apparent that computers needed to be able to separate out not only individuals but also system processes.
In 1979, we took another step towards creating shared, yet isolated, environments with the development of the
chroot (change root) command. The
chroot command made it possible to change the apparent root directory for a running process, along with all of its children. This made it possible to isolate system processes into their own segregated filesystems so that testing could occur without impacting the global system environment. In March 1982, Bill Joy added the
chroot command to the 7th edition of Unix.
For the purpose of understanding containers, we can skip forward a bit in time to the 1990s when Bill Cheswick, a computer security and networking researcher, was working toward understanding how a cracker would use their time if given access to his system. For those of you unfamiliar with the term cracker, it is used to refer to someone who breaks into a computer system for malicious reasons. Now you may be thinking, “Wait… isn’t that a hacker?” But in the security world, the word hacker is generally used to define someone who identifies security vulnerabilities in order to fix, rather than exploit, them. Though this difference may warrant its own blog post, for now, I will use the term cracker, since that’s the term Cheswick used in his paper “An Evening with Berferd in Which a Cracker Is Lured, Endured, and Studied.” In this research, Cheswick built an environment that allowed him to analyze the cracker’s keystrokes in order to trace the cracker and learn their techniques. His solution was to use a
chrooted environment and make modifications to it. The result of his studies was what we now know as the Linux
jail command.
On March 4, 2000, FreeBSD introduced the
jail command into its operating system. Although it was similar to the
chroot command, it also included additional process sandboxing features for isolating filesystems, users, networks, etc. FreeBSD
jail gave us the ability to assign an IP address, configure custom software installations, and make modifications to each jail. This wasn’t without its own issues, as applications inside the jail were limited in their functionality.
In 2004, we saw the release of Solaris containers, which created full application environments through the use of Solaris Zones. With zones, you can give an application full user, process, and filesystem space, along with access to the system hardware. However, the application can only see what is within its own zone.In 2006, engineers at Google announced their launch of process containers designed for isolating and limiting the resource usage of a process. In 2007, these process containers were renamed control groups (cgroups) to avoid confusion with the word container.
In 2008, cgroups were merged into Linux kernel 2.6.24, which led to the creation of the project we now know as LXC. LXC stands for Linux Containers and provides virtualization at the operating system level by allowing multiple isolated Linux environments (containers) to run on a shared Linux kernel. Each one of these containers has its own process and network space.
In 2013, Google changed containers once again by open-sourcing their container stack as a project called Let Me Contain That For You (LMCTFY). Using LMCTFY, applications could be written to be container-aware and thus, programmed to create and manage their own sub-containers. Work on LMCTFY was stopped in 2015 when Google decided to contribute the core concepts behind LMCTFY to the Docker project libcontainer.
The Rise of DockerDocker was released as an open-source project in 2013. Docker provided the ability to package containers so that they could be moved from one environment to another. Docker initially relied on LXC technology, but in 2014, LXC was replaced with libcontainer, which enabled containers to work with Linux namespaces, libcontainer control groups, capabilities, AppArmor security profiles, network interfaces, and firewall rules. Docker continued its contributions to the community by including global and local container registries, a restful API, and a CLI client. Later, Docker implemented a container cluster management system called Docker Swarm.
Though we could go into container cluster management by diving into Docker Swarm, Kubernetes, and Apache Mesos, for the It’s Okay to Be New series, Docker will be our stopping point. Our next step will be to explore Linux Academy’s Docker Deep Dive course so we can get some real, hands-on experience using Docker. After that, we will move on to the Docker Certified Associate course and put our knowledge to the test. | https://acloudguru.com/blog/engineering/history-of-container-technology | CC-MAIN-2021-04 | refinedweb | 1,139 | 50.06 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
R3 Transaction Codes SAP R3 Tables mySAP Certification Criteria SAP Logistics Modules Material Management Logistics Execution Warehouse Management Sales and Distribution Production Planning and Control Quality Management Plant Maintenance Project System SAP Financial Modules Financial Accounting and Controlling SAP Human Resources Personnel Management
Generic SAP Topics SAP Tickets - What Is That? What Is Maintaining SLA What Are Functional Specification? Role of a SAP Functinal Consultant Role of SAP Consultant In Testing
SAP Books and eBooks Sams Teach Yourself SAP in 24 Hours (3nd Edition) SAP NetWeaver For Dummies Supply Chain Management Based on SAP Systems ... browse more SAP Books
New SAP Tips Just Arrived Roles and Responsibilities of End Extracting Data of Workflow Users Log What Are SAP End User Manual The top ten IT skills to have for the next few years Mini SAP System Requirement and How to Get It What Is User Specific Parameter Implementing SAP R 3 Successfully Implementing SAP Exchange Rate Billing Documents Rebate Management Tables Used Datasource Change Owner Done By Who Options To Handle Manufacturing Materials Restrict Specific Programs In SA38 and SE38 Major Area In Extended warehouse Management Check for Partner on Equipment Master (IE01) What Is SAP Service Management PP/DS Planned Order From APO To ECC Explanation Of LSO Transaction Codes
ABAP/4 FAQ System Administration - Data Dictionary SAP Basis Components - Reporting Administration In SAP - Data Modeler - Dialog Programming ABAP Workbench - SQL/Performance ABAP Programming Hints - SAPscripts BDC Programming Tips - User Exits ABAP Functions Examples - Workbench Organizer BAPI Programming - Sample Exam Questions ABAP Questions Cross-Applications Components SAP Forms Business Information Warehouse Sapscripts Advanced Planner and Optimizer SmartForms SAP Business Workflow Handling Units Management SAP Functional vs ABAP Document Management System
Training Learning ABAP or SAP Application SAP Jobs Forum for SAP Recruiter and Jobs Seekers SAP Jobs Opportunity SAP Links Links of SAP websites
SAP Data Migration with LSMW Production Planning Process Computer Aided Test Tool Industries Flow Customer Relationship Management Customer User Exit For Billing Explanation Of Purchasing Info Record Re-run Released Cost Estimate For Material Network Scheduling In Project System Documenting HR Rules And Schemas Control Of Expiry Date For Inspection Retro Billing And Self-Billing
Miscellaneous Contents Oracle Database, SQL, Application, Programming Tips Java Programming Hints and Tips Unix System Administration Hints and Tips Linux Administration Hints and Tips
SAP¶s software each component (or "layer´ in R/3¶s ³clients´, those components/layers that are providing services are called ³servers´. Thus the term *-- Shailesh Kumar (shailesh_das@yahoo.com) ³client/server´. What is meant by SAP ECC?
SAP is an ERP (Enterprise Resource Planning) module, ECC is the version of SAP, like 4.6, 4.6c and 4.7 in that series new version is ECC-6. Its known as Enterprise core component.
What is SAP Landscape?
By: Kunal Landscape 'database' (if you wanna call it that) or you may rather call it the 'ultimate' Why do we call client 000 as golden client? Golden client contains all the configuration data and master data so some extent. All the configuration settings are done in golden clients and then moved to other clients. Hence this client acts as a master record for all transaction settings, hence the name "Golden Client". What Menu.
SAP SD Transaction codes List
I found a way to know hidden customizing Tcodes. Before executing customizing task you desire, point it and go to Edit-Display IMG Activity. Then mark activity. Go to T.Code se16 and type in CUS_IMGACH table. Execute. Paste IMG Activity and run. You will see Tcode that belongs to IMG Activity. SAP SD Tips by: Javier The most frequently used transaction codes are as follows: 1. VS00 - Master data 2. VC00 - Sales Support 3. VA00 - Sales 4. VL00 - Shipping 5. VT00 - Transportation 6. VF00 - Billing
Others as follows: At Configuration: 1. VOV8 - Define Sales documents type (header) 2. OVAZ - Assigning Sales area to sales documents type 3. OVAU - Order reasons 4. VOV4 - Assign Item categoreies(Item cat determination) 5. VOV6 - Scedule line categories 6. OVAL - To assign blocks to relevant sales documents type 7. OVLK - Define delivery types 8. V/06 - Pricing 9. V/08 - Maintain pricing procedure 10.OVKP - Pricing proc determination 11.V/07 - Access sequence Enduser: 1. Customer Master Creation-VD01 and XD01 (for full inclu company code) VD02 - Change Customer VD03 - Display Customer VD04 - Customer Account Changes VD06 - Flag for Deletion Customer XD01 - Create Customer XD02 - Modify Customer XD03 - Display Customer 2. Create Other material ----MM00 3. VB11- To create material determination condition record 4. CO09- Material availability Overview 5. VL01 - Create outbound delivery with ref sales order 6. VL04 - Collective processing of delivery 7. VA11 - Create Inquiry VA12 - Change Inquiry VA13 - Display Inquiry Sales & Distribution Sales order / Quote / Sched Agreement / Contract · VA01 - Create Order · VA02 - Change Order · VA03 - Display Order · VA02 - Sales order change · VA05 - List of sales orders · VA32 - Scheduling agreement change · VA42 - Contract change
· VA21 - Create Quotation · VA22 - Change Quotation · VA23 - Display Quotation Billing · VF02 - Change billing document · VF11 - Cancel Billing document · VF04 - Billing due list · FBL5N - Display Customer invoices by line · FBL1N - Display Vendor invoices by line Delivery · VL02N - Change delivery document · VL04 - Delivery due list · VKM5 - List of deliveries · VL06G - List of outbound deliveries for goods issue · VL06P - List of outbound deliveries for picking · VL09 - Cancel goods issue · VT02N - Change shipment · VT70 - Output for shipments General · VKM3, VKM4 - List of sales documents · VKM1 - List of blocked SD documents · VD52 - Material Determination
Task Specifc SD Transaction Codes 1
How to configure tax? Use the following Tcodes: OBQ1 --- CONDITION TABLE OBQ2 --- ACCESS OBQ3 --- TAX PROCEDURE CAL OBBG --- ASSIGN COUNTRY TO TAX PROC OVK3 --- CUSTOMER TAX CATEGORY OVK4 --- MATERIAL TAX CATEGORY OVK1 --- TAX DETERMINATION RULES OVK6 --- ASSIGN DELIVERY PLANTS and thenVK11 to maintain the condition record for the tax rate.
I raise a sales order and is getting a error stating that "sales area is not defined". 1) At SPRO-->SD-->Sales header-->Assign Sales area to Sales document - Combine your Sales Organisations, Distribution Channels & Divisons 2) At VOPA-->Assign Partner Determination procedure to your Account Group of Customer Master you are using. 3) At VOPA--> Assign Partner Functions to your Account Group & Partner Determination procedure Steps to create a Vendor Master Data at the client level and how do we extend it to different company codes? Follow the following steps: 1. Create a vendor account group OBD3 2. Define no. range for vendor account group XKN1 3. Assign number range to Vendor account group OBAS 4. Define tolerance Group for vendor OBA3 5. Create 2 GL accounts FS00 a) Purchases A/c b) S. creditors A/c 6. Create Vendor master data XK01 7. change/block vendor master data XK02/XK05 8. Define document type and no. range OBA7 a) KA b) KG c) KR d) KZ *-- Vandna How to find the strategy group in sap sd? Menu path for Strategy Group is: Spro --> Production --> Production Planning --> Demand Management --> Planned Independent Requirements --> Planning Strategy --> Define Strategy Group. OPPT -- Maintain Starategy Group We can see Strategy Group in Material Master Record - MRP 3 - Planning -- Strategy Group.
10 - For Make to Order 20 - For Make to Stock
Task Specifc SD Transaction Codes 2
Where do we maintain "Item Category Usage" at the master level? Spro --> Sales and Distribution --> Sales --> Sales Documents --> Sales Document Item --> Define Item Category Usage Item Category Usage: item category usages which control the usage of an item. Item category usage controls, for example, the system response if during document processing an item does not refer to a material but to a text item. Item category usage can also be maintained via the item categories In contracts we are creating quantity contract and value contracts in that we only put the validity period after validity period that contract will close,but customer want before one month closing the period system should alert with popup box like this contract is going to close, for this sales manager can follow up the customer for renual the contract. Getting a pop-up when the Contract is going to expire is not a Standard SAP thing. For this you need to do some programming. Instead of this the Std system has a reminder system where in the open Contracts and Quotaions are popped up when you about to create a sales order. This setting is in the Sales order header , Goto -- VOV8 --- Quotation and Outline agreement messages If you want to have different number range for different sales area where the settings to be done. Number Rage are use to define what number to be assign to sales document type. Number range can be assign Internal or external. In internal number range system automatically assign a number to sales document according to number range define in system. In External number range user manually assign number to sales document. For Assigning Number Range use T-Code VN01
SAP SD TCodes For India
Transaction
Standard SAP SD Reports
Reports in Sales and Distribution modules (LIS-S
Find the list of SAP Transaction codes
Where I can find the list of transaction codes and their usage, I heard that there is some table which contains all the transaction codes with their descriptions. Does.....
Add Edit Delete Entry In SE11 Database Table
How to edit entries of table in se11 ? To update the data of any table, go to transaction SE16N, type ³&SAP_EDIT´. It will activate SAP editing function. --Go to table and press Ctrl+ shift + F10 where you will go to table entries. Click on F8 (execute). And then select the entries that you want to edit by selecting the checkbox and goto menu Table entry - > select change. There you edit and save the entries. --You cannot edit entries in SE11 unless it contains a Table maintenance generator. So just build a Table maintenance generator. Do not delete any entries using &SAP_EDIT...it is not recommended. --You can edit through debugging.
How to delete a record in SE16 ? To delete the records from particular table its easy. Goto : se11 - Give the table name - Execute the table with the selection fields - Then data (list) screen will be displayed. - Now select the record which has to be deleted - Select that and switch 'on' the Debugging mode press enter - Then press F6 goes to subroutine where there is field called display - Instead change it to edit and then save the changes then it will take you to the screen where you can edit that records & also delete that particular records. Note: After displaying the contents of the list. Switch ON the Debug Mode the select the particular record then click display then it will take u to Debug Screen when there is a program for sy-ucomm then click F7 Button and then Change Code = EDIT then save the code the afterwards it will take u to edit mode of that particular record.
How can I insert new data in the table? Give the transaction code as se11 In that give the table name and press display Then in that field name above there is delivery and maintenance click the same and change it as display maintenance allowed
Transaction Code To View All SAP Tables
What is the transaction code to view all SAP (PP) table,or there is some other way to view? By: Riki Paramita
To browse tables which specified for PP module only, you can use SE16 with a specified application component & sub-component. First, go to SE16, browse the application component (ex : PP), then select the sub-component (ex : PP-SFC, for Production Orders related tables); and all tables within the specified area will be displayed. In tcode SE16, click the Down Arrow next to the Table Name field: Then it will pop-up a screen, look at the bottom of the screen:
Then select components by clicking the + sign to open up the sub-compenent you want. For e.g.:
Some important tables within the PP area : MAST - Material BOM STKO - BOM Header STPO - BOM Positions (detail) MAPL - Assignment for Task Lists to Materials PLKO - Routing Group Header PLSO - Routing Group Sequence PLPO - Routing Group Operations
AFKO - Production Order Header AFPO -Production Order Position (details) Related tables in MM area : MAKT - Material Descriptions MARA - General Material Data MARC - Plant Data for Material MARD - Storage Location Data for Material MAST - Material to BOM Link
Important Tables for SAP SD
Sales and Distribution: Table Customers KNA1 KNB1 reconciliation acct) KNB4 KNB5 KNBK KNKA KNKK limits) KNVV KNVI KNVP KNVD KNVS KLPA Sales Documents VBAKUK VBUK VBAK VBKD VBUP VBAP VBPA VBFA VBEP VBBE Description General Data Customer Master ± Co. Code Data (payment method, Customer Customer Customer Customer Customer Payment History Master ± Dunning info Master Bank Data Master Credit Mgmt. Master Credit Control Area Data (credit
Sales Area Data (terms, order probability) Customer Master Tax Indicator Partner Function key Output type Customer Master Ship Data Customer/Vendor Link VBAK + VBUK Header Status and Administrative Data Sales Document - Header Data Sales Document - Business Data Item Status Sales Document - Item Data Partners Document Flow Sales Document Schedule Line Sales Requirements: Individual Records Delivery Document item data, includes referencing PO Delivery Document Header data Billing Document Header Billing Document Item Shipping Unit Item (Content) Shipping Unit Header
SD Delivery DocumeLIPS LIKP Billing Document SD Shipping Unit VBRK VBRP VEKP VEPO
SD Tcodes
y y y
SAP SD Transaction codes List Task Specifc SD Transaction Codes 1 Task Specifc SD Transaction Codes 2
Get help for your SAP SD problems SAP SD Forums - Do you have a SAP SD Question? SAP Sales and Distribution Books SAP SD Books - Certification, Interview Questions and Configuration
mySAP Certification - Criteria For Application
The:
Delivery Logistics Execution SAP Certification Exam My SAP SD Certification Experience Sample Questions and Answers SAP SD Exam SAP SD Questions and Answers SD Questions on Corporate Structure Short SAP SD Questions 1 Short SAP SD Questions 2 Short SAP SD Questions 3 Interview Questions Important Tips for Interview for SAP SD SAP SD Interview Questions Interview Question and Answers on SAP SD Some SAP SD Interview Questions 1 Some SAP SD Interview Questions 2 Tables/Tcodes in SAP SD Important Tables for SAP SD SAP SD Transaction codes List SAP Sales and Distribution Book Implementing SAP ERP Sales & Distribution Highly Recommended for those who want to become a SAP SD Expert. Provides details SD Implementation and Configuration from Basic to Expert level. SAP SD Interview Questions, Answers, and Explanations Retail Information Systems Based on SAP Products SAP SD Premium Paper SAP Sales Order Processing Overview A Step by Step Guide to the
Task Specifc SD Transaction Codes 1 Task Specifc SD Transaction Codes 2 SAP SD TCodes For India Standard SAP SD Reports SD Frequently Asked Question Sales and Distribution FAQ Link Between SAP SD, MM & FI Why Do We Assign Division to Sales Organisation How To Do Master Record Mass Maintenance Serial Number Management In SAP SD Sales Office Address, Change and Assignment Sales Order How To Create Sales Order Duplicate customer purchase order Default First Date is not Today Sales Order Confirm Quantity Date Auto proposed all the dates when creating Sales Order Define Material used at which Sales and Distri. Process Assign a Cost Center manually in a SO (VBAKKOSTL) Transfer of Requirements What Do You Mean By Transfer of requirements Define Tax Determination Rules Taxation Explain with an example SAP SD: Scheduling Agreement Vs Contract Sales Order Mass Change Release strategy for Sales order How to do rebate processing Rebate Process with Ref. to SO Consignment Sales Process in SAP Issue free goods to selected Customers Supressing Fields in Sale Order Some Light on Batch Determination Diff. between Item Proposal and Material Determination Steps for SD Variant Configuration Number Ranges In Sales Order What is Debit note and Credit note Explain What Is Credit and Debit Memo Configure Intercompany Stock Transport Order Inter Company Sales Process
SAP SD Sales Order Processing Configurations ...more SAP SD Books Free SD Download (PDF) Download: Plain Variant Configuration Download: Sales Process Flow Chart HUM Basic Process of how Packing Works The "Packing Process" with an Example Pricing Difference between Condition Type Accumulate the amt of cond. types in accting document Hiding Price Condition Types on a Sales Document Creating New Pricing Procedure What is alt cal type & alt base value & Req field in Pricing Re-pricing in a Quotation Quantity Based Discounts in Bulk Quantities Sales Determine sales price with shipping point Pricing date based on Deliv. date, Sales Ord, Billing Report to Check the Entered Pricing Condition Price Mass Update of condition pricing Material Master Price as Sales Price Automatically Customer discounts on effort only Steps to Create Commission for Agent SD Questions About Pricing Condition Add a Field To New Condition Table in Pricing Header Condition and Group Condition Steps Involved In Condition Technique Sales Order Freight Condition In Header Condition How To Use Condition Exclusion Type In SO Pricing Report & Condition Index What Is Condition Base Value
Normal Sales Order Cycle Configuration Default Storage Location In Sales Order Explain The Meaning Of An Open Sales Order Sold To Party In Sales Order Screen Profit Center Default In Sales Order Check Whether The Entries Is Maintain in LIS Update or Not 3PL Purchase Order Link To Sales Order What is the Foreign trade data required in SO for doing Exports Material To Be Added or Excluded To a Customer Sales Order Number Blank In MD04 Partner Functions Partner Determination For Sales Doc Setup Partner Determination Procedure Sales and Distribution BOM Sales BOM Implementation How to Know that Sales BOM is working or not? What Is BOM Referring to SAP SD Pricing Customization For Sales BOM Third Party Sales Process Flow for 3rd Party Sales Cross Selling : How To Configure An Example Of Third Party Sales Sales Information System Difference/Similarities between LIS and SIS
Rounding Off Condition Not Appearing In Sales Order How To Create Field in KOMP, KOMG Billing Billing cannot be Release to Accounting Default Start Variant for VF04 Cond. Exclusion will be determined in the billing doc. Steps creating new or changing existing Billing Doc Typ Billing Block will not worked if you did not assign it Billing Plan for Milestone Billing Billing Plan Function and Processing Combine Billing for deliveries with different date Billing Spilt by Item Category Max. No. of items in FI reached Msg no. F5 727 Prepaid process possible Restricting Number Of Items In Billing Doc Document Not Relevant For Billing Procedure To Cancel Billing Documents Schedule VF04 For Individual Billing Run Explain The Concept of Resource Related Billing Cancelled Billing Document Has No Accounting Document Retro Billing And Self-Billing Exchange Rate Billing Documents
Credit Management How To Do Configuration For Credit Availability Check Management Availability Check on Quotation SD material Determination based on availability MRP block for Credit limit attained Customers check Credit Mgmt Dynamic checking Creating Multiple Materials in Material Sales value field not getting updated after Determination creating billing Backward and Forward Scheduling Diff Between Simple and Automatic Credit Configuring Availability Check Through Check Types Checking Groups Back Order Processing Using CO06 and V_V2 Set Up for Credit Card Payment Processing Dunning Process In Credit Management See The Scope of ATP Check What Is Credit Exposure Account Payable
Settlement Downpayment with Installment payment Term Customized SD ABAP Reports Upload Condition Pricing Sales Order Changed History Display User Exits on Sales and Distribution Customer User Exit For Billing
CIN SAP SD CIN Configuration Customer Return material From customer Customer Returns and Replacement Orders Customer Wants To Take The Order Back Usage Of Customer Pricing Group Hierarchy Customizing Customer Hierarchy in SD Basic SD Questions On Product Hierarchies How To Configure Product Hierarchy Product Allocation Implement the Product Allocation Functionality Output/Email Sending a billing document by e-mail Customizing picking output Program for Sales Order by Customer, Date, Sales How To Maintain Output Types in SD Printing Block For Credit Block SO
Set the number range for Deliveries
The internal and external number range for delivery are control by the delivery type. First you define the number range for deliveries in 'VN01'. Then you assign the number range for the delivery type in transaction '0VLK'. Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Set the default start variant for VL10
In transaction SU01, tabstrips Parameters. Assuming you have created a variant TEST
Parameters LE_VL10_USER_VARIANT for Delivery Creation
Value TEST
Text Default Selection Parameters
Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Adding additional fields to Delivery Due List
If you would like to add additional fields to the Delivery Due List Transaction VL04. These fields do not exist in the list of additional fields in the IMG. You will need to have a user exit written. This OSS notes will help you in creating the additional fields :198137 - VL10: Customer-specific enhancements / user exits 415716 - User exits in delivery processing Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Checking Fields with Incompletion procedures for Delivery
Define your incomplete procedures in OVA2. There are 3 levels :Groups Procedures Fields -> 1. here you define the Status Group to used 2. you define whether a warning message should be issued
Assign incompletion procedures to partner functions in SM30 - V_TPAR_VUV
Assign incompletion forms to the delivery types in SM30 - V_TVLK_VUV Assign Incompletion Forms to the Delivery Item Types in SM30 - V_TVLP_VUV
Define the Status Group in SM30 - V_TVUVS You use this function to block a document for delivery, billing, or pricing etc. In an incompletion procedure you group together the fields that are to be checked for completion..
Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Exclude inventory in Storage Locations during Delivery Creation
When you exclude MRP planning for a storage location, SAP will not consider the stocks when you do a delivery creation. You used SM30 - V_T001L_D to include/exclude the storage location for MRP. If you does not wish to include/exclude the storage location for all the materials, you can just goto MM02 -> MRP View 4 to include/exclude it for that particular materials only. Take note that when you set the parameters in SM30 - V_T001L_D, the settings only affect those newly created materials starting from the days you set the parameters. For those materials already created, you have to changed it manually one by one or write an
ABAP program to mass changed it automatically. Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Avoiding delivery creation when items quantity are zero
Deliveries are created collectively using VL10. In the definition of delivery item category 0VLP, there is a field Check Quantity 0. Set the value to B or C. This will prevent delivery with zero lines from being created. However, if you want to include zero quantity items but if they are all zero, you do not want to create the delivery then you have to used the user exit USEREXIT_SAVE_DOCUMENT_PREPARE. Best regards, SAP Basis, ABAP Programming and Other IMG Stuff SAP WMS - Decentralized Warehouse Management System Integration Setup You can operate the SAP Warehouse Management System (WMS) as a stand-alone decentralized system that is independent of a central Enterprise Resource Planning (ERP) System. You make the necessary settings for the ERP (Enterprise Resource Planning) system within the WMS component (Warehouse Management System). The steps are set up as a checklist and guide you through the process of configuring the system parameters. Checklist (For those with the Table Views used transaction code SM30).
1. Customizing for "Enterprise Structure" - Create storage location in OX09 (if necessary). - Define warehouse number in Views V_T3001. (you should not copy the warehouse number in the ERP system) Activities within a warehouse, like goods movements and physical inventory, are assigned to a specific warehouse number. The physical warehouse where these activities take place is identified by the warehouse number. - Assign plant/storage location to warehouse number in Views V_T320. (Valid if the component MM-IM (Inventory Management) is implemented.) Fields : Plant + Sloc + WhN 2. Customizing for "Decentralized WMS integration", section "Central processing" -> Application - Activate decentralized WMS in Views V_T340DM. - Define interface to Inventory Management in Views :V_156S_WM - Assign WM movement type references to IM movement types V_T3211 - Delivery-Relevant Parameters for Reference Movement Type V_T340DL - Delivery-Relevant Data for Warehouse Number - Exclude stock in decentralized WMS in Views V_T321B (if the decentralized WMS is not an SAP R/3 system) - Finally do a consistency check for decentralised WMS in transaction OL20. 3. Customizing for "Application Link Enabling (ALE)", section "Basis Components" Maintaining Logical Systems in Views V_TBDLS. Assign logical system to client in Views T000. 4. Make basic settings for RFC in transaction BD97.(if necessary)
5. Customizing for "Application Link Enabling (ALE)", section "Maintain Distribution Model" You can define the Reduce message types and Activate message types in transaction BD53. SAP recommends that you use message types : "MATMAS" (material master tables) and "DEBMAS" (customer master) as a template. Be aware that only those fields that are absolutely necessary are transferred from the master data tables in the ERP system to the decentralized WMS. 6. Customizing for "Decentralized WMS integration", section "Central processing" -> Distribution Use transaction OL19 to generate distribution model. As far as the application is concerned, when the model is generated, application-specific Customizing parameters are modified or set (for example, activate decentralized WMS). Display or check distribution model Generate partner profile in transaction BD82. (you can also perform this activity using ALE Customizing) Distribute distribution model in transaction BD64 (model view) using menu item "Edit" If both the ERP system and the decentralized WMS are SAP R/3 systems, the distribution model should be distributed on a central basis only, that is, via the ERP system. 7. Customizing for "Application Link Enabling (ALE)", section "Maintain Distribution Model" (transaction BD64) Activate the change pointers for master data distribution using transactin BD61.
If necessary, reduce the message types concerned with transaction BD53. 8. Customizing for "Logistics - General" - "Material Master" - "Tools" - "Data Transfer : Material Master" -> "Define required-field check for ALE/Direct Input" (Views V_T130S) Define whether an error message should be generated in the receiving system for required fields from the material master. Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
SAP Customizing Picking Output. Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Problem in Shipping
I am new to SD. I am facing a problem in Shipping. After finishing the transfer order, and go to change mode of delivery, Press "post goods Issue" I am facing this problem: "The number range for the transaction/event WL in year 2004 does not exist" How to solve this problem. Sailendra Go to TCode SNRO. Put the no Range object as MATBELEG and click on Number Ranges. Then click on Change Groups. Then select the second row (which includes your WL doc type). After selecting click on the change/maintain button. On this you can maintain the desired number range. Here you can put the year as 2004 or any future year. Amol. When a SO is created and Delivery then we proceed to Transfer order and Post goods issue, sometimes there is a problem in Shipping. Could you Kindly clarify whether Shipping point is assigned to the Material in Material Master or you can assign the Storage Location, Plant and Shipping point in Delivery. Also If a Plant has mutliple shipping points,,which one will be assigned for shipping after Delivery created I also had an error log while creating Transfer order LT03 saying Postings not possible for specified date..Is there a way to solve this problem in Deliveries? Pritam When creating a Sales Order, the system first determines the Delivering Plant in the sequence from the following source: 1) Customer-material info record 2) Customer Master 3) Material Master. On determining the Delivering plant, the system determines the shipping point with the customising that you do in Logistics Execution > Shipping > Basic Shiping Funct > Shipping point and Goods Recieving Point Determination > Assign Shipping points
: Here you enter the Shipping point to be determined for the combination of: a) Shipping Condition (which is assigned in the customer master or Salesdocument type) b) Loading group (which is assigned in the material master) c) Delivering Plant (which has already been determined) As regards storage location the same is determined in the delivery from the combination 1) Shipping Point 2) Delivering Plant 3) Storage condition. Hope the above has clarified your querries. Amol. Fast Links: Get help for your SAP SD problems Do you have a SAP SD Question? SAP SD Books SAP Sales and Distribution Reference Books
Movement Type Posting Error In Delivery
After creating the delivery, I could not proceed with the Post goods issue. When I click the post goods issue, the bottom message says posting period possible for 2006/6 and 2006/7 for company code."CO-code". See there is may be two kind of problem: Maybe your system installed in back date so check actual movement date. in T-Code MB1C What actual movement date you used for PG Received into your plant. Secondly, for assigning a posting period do the following T-Code OB52
("please check your Company Code is assign to which Varriant T-code OBBP") Customizing => Financial Accounting => Financial Global Setting => Document => Posting Period => Open and Close Posting Period, and Update your Posting Period as you desire => Open and Close Posting Period, and Update your Posting Period as you desire. *-- Shambhu I have created the outbound delivery and have done PGI & made factory invoice but when I try to make the final invoice , it is not allowing to make the final invoice.S ystem is showing the error "Delivery type ZINC cannot be invoiced with billing type F2 ". Just go to sales Document Type (VOV8), Check for Sales Order - > Delivery Type -> Billing type assignment and correct accordingly. *-- Ratnakar While creating material stock, I am getting an error " Posting Period003 2007 is not open". I have tried all MMPV, OB52, OMSY but still stock is not creating. You go to assign plant to company code and there you de-assign and save it. IMG/ENTERPRISE STRUCTURE/ASSIGNMENT/LOG GENERAL/ ASSIGN PLANT TO CO CODE. Now you go to /NOMSY and go to position give company code then change the year to 2007 and pd to 03(now March month)and save it. Now, again you assign your plant to company code and save it.
Shipping Conditions and Storage Location Determination
Can we configure Shipping conditions at line item level? Shipping conditions is one of the criteria to determine shipping points. Shipping points is determined for each order item in sales order. The system automatically proposes the shipping point at item level. You can change shipping point manually in the order. Shipping point determination-shipping conditions from (Img of S.doc type or customer master record of sold-to party) +loading group of Material master+ delivering plant of customer material infor record.
In r/3 shipping conditions are assigned to Sales document type. If it is not assigned it is proposed from master record of sold-to-party. In your case,you have to define all shipping conditions and assign Shipping points for each shipping conditions.You will have as many shipping points for as shipping conditions. Customizing : Shipping point determination-IMG-Logistic execution-shipping-basic shipping *-- Vrajesh function.
How system determines storage location in sd? -.
Delivery Split Because Of Conflicting Header Data
By: Robin Item 000020 - Delivery split because of conflicting header data (TRAGR 0001<>0002). How this error can be removed? What is the reason for such error? Delivery split can occur for the following reasons. 1. Different delivery dates for line items. 2. Different ship to parties for line items. 3. Different routes for line items. Check whether the above data are same for all the line items. The following data may cause to split as two deliveries:
--> Check the shipping points of the two items it may be different. --> Check the item level partner functions in the Sales order is there different ship to parties available for the two items. --> Check the Delivering plant of the items. --> Check the shipping conditions are different for the two items. --> Check the loading group of the two items. Go to Material Master, select Sales: General/Plant view and compare for both the materials what is maintained in "Trans.Grp". It should be different. Maintain unique value and then retry. Your problem will be solved. Getting a delivery split based on different customer group at header level. This is not the business requirement. How to still create a single delivery document? Item 000020: delivery split due to conflicting header data (KDGRP: Z1 <-> Z2) Message no. VL033 Diagnosis Item 000020 cannot be shipped in the same delivery with the other items in the document because the header data (KDGRP) is different. The KDGRP item field has the value Z2, but in the delivery checked for concatenation it has the value Z1. Delivery split happens because of the customer group also. so as you want to do single delivery, assuming that stock is available for both the materials, check in the item data the schedule lines, the delivery dates of the line items 10&20 and make sure that both are being delivered on same date. And make the customer group (VBKD KDGRP ) same for line items 10 & 20 .then single delivery will happen. for both the line items Please check the below: DELIVERY SPLIT: Delivery Split depends on the following criteria: 1) Ship to party 2) Delivery date 3) Plant 4) Shipping point 5) Shipping conditions 6) Transportation group 7) Loading group 8) Item categories of materials
Delivery split happen when the requested quantity by customer is not full met, then the system proposes different delivery dates or schedule lines dates based on material availability. Example : A sales order is confirmed with 2 schedule lines i.e on 14 feb 2008 and 25 feb 2008 If the first delivery (14 feb 2008) is created and PGI is done this means on this delivery date customer has received the goods. For the second delivery date ( 25 feb 2008), here you can create delivery only on 25 feb not before this due date, this means on this date goods will reach customer after completing the transportation planning, picking, loading, packing and transit, then in system on 25 Feb we create delivery document with PGI. Partial Delivery option will be set in customer master record sales area ----> shipping-> partial deliveries.
Route Determination In Sales Order
Explain the basic concept of route process in Sales Order. By: Kevin Route is determined automatically in the sales order based on: 1. Departure zone or country of the delivering plant. 2. Destination zone or country of the Ship to Party. 3. Shipping condition from the customer master. 4. Transportation group from the material master. 5. Weight Group. Follow this:Step: 1 - Define Modes of Transport Path: Spro²Logistics Execution²Transportation²Basic Transportation Function--Routes²Define Routes²Define²Logistics Execution²Transportation²Basic Transportation Function--Routes²Route Determination²Define redetermine the route in the outbound delivery based on weight (weight group) provided it is allowed in the configuration of the delivery type.
Scheduling takes into account the following times ±
Planned Delivery Cost and Unplanned Delivery Cost
ERP SAP ==> SD SAP ==> LE SAP What is planned delivery cost and unplanned delivery cost? By: Chung 1) A delivery costs that are planned in a purchase order and are entered in the system (invoice). 2) A delivery costs that are not planned in a purchase order and are not entered in the system until the invoice is received. Planned delivery costs: Planned delivery costs are agreed upon with the vendor, a carrier, or a customs office before the purchase order is created. You enter them in the purchase order. Planned delivery costs can be differentiated as follows: Origin of Costs i) Freight charges ii) Customs charges Calculation of Costs i) Fixed amount, irrespective of delivered quantity
ii) Quantity-dependent amount iii) Percentage of value of the goods Unplanned Delivery Costs: Unplanned delivery costs were not agreed on in the purchase order and are not entered until the invoice is received. You can enter the unplanned delivery costs in the invoice document alongside the costs incurred. You can post unplanned delivery costs as follows: - Distribute them prorated to calculated invoice items - Post them to separate G/L accounts The system distributes the unplanned delivery costs automatically in the ratio of the value invoiced so far to the values in the current invoice. The system posts unplanned delivery costs to a separate G/L account. Therefore, the unplanned delivery costs do not debit stock accounts or account assignment objects.
Shipping Condition Route Determination And Loading Group
SAP Functional Modules ==> Logistics Execution Where is the "Shipping Condition" maintained in a customer master? Shipping condition is maintained in the shipping tab under sales area data of customer master. The shipping condition is proposed from the sales document type if a shipping condition has been assigned to it. If not, the shipping condition is proposed from the master record of the sold-to party. Shipping conditions are maintained for which partner function in customer master? Shipping condition is maintain in Ship to Party partner function ( sales area data tab -- shipping.)
Shipping conditions will be defaulted from the CMR of SP. If a value exists in the sales document type (eg. OR) then it will have priority and will replace the value defaulted from CMR.
Does the system takes the shipping condition twice in search of the route? When the system search for the route it will search through route determination like this: Shipping point*(*Sales order)** and Departure Zone **(From the order shipping point*)*+Shipping condition*(*Customer master which you enter in the order*) *+Transportation Group*(*from material master which you entered in the order**)+destination zone*(*transportation zone of the Customer in the order**)->Route System will determine the shipping point in the sales order based on these selection Shipping conditions+Loading group+Plant-->Shipping point. After determining the shipping point then only the system will start to search route. But system will not search the shipping point while searching the route. So shipping conditions will not consider two times while searching the route. What is the significance of the shipping condition and loading group? Both the shipping condition and loading group are useful in Stock transport order. For the Customer assigned to the receiving Plant, check the Delivering Plant in Customer master record in XD02 & check the shipping point assignment in OVXC. Shipping point will be determined only if it is assigned to the plant from the config. Shipping condition and Loading group plays a vital part for shipping point determination . The combination of shipping condition (Master data of customer /Vendor) + Loading group (material master) + Plant, determines the shipping point.
Batch Determination In Delivery
I have configured the batch determination in delivery and it is working fine. But I have one issue in that. Requirement is that during batch determination in delivery system should only pick the batch for which remaining self life is at least 45 days. The days of remaining self life is based on the customer. For customer A it should be 30 and for B 45 etc. I have created customer specific strategy/condition record. So for each customer I have to maintain the days in characteristic (Which characteristics can be used?) There is std Self life expiration date char is exist in the system you have to activate that. LOBM_VFDAT (tcode is BMSM) This function updates the standard characteristics in the classification system reserved for batch management so that they meet the requirements of any new functions. This concerns all characteristics starting with LOBM_*. These are: - LOBM_VFDAT expiration date, shelf life - LOBM_VERAB availability date - LOBM_LFDAT required delivery date - LOBM_RLZ required remaining shelf life of batch - LOBM_MENGE quantity - LOBM_ZUSTD status - LOBM_LVORM deletion flag - LOBM_BWTAR valuation type - LOBM_LGORT storage location - LOBM_QNDAT next batch check date - LOBM_KRT required waiting days for batch - LOBM_MBDAT material availability date
- LOBM_RLZ_PROZ required remaining shelf life as a percentage - LOBM_BPRIO stock determination: priority - LOBM_UDCODE usage decision - LOBM_QSCORE quality score from usage decision You need to execute this function in the following cases: - In newly created clients, after copying other clients - After defining object dependencies for standard characteristic LOBM_RLZ - In every client after a release upgrade When the report for updating the standard characteristics has been completed, you receive a log in which all the activities performed are listed. Update Standard Characteristics in BMSM and also Refer SAPNote 33396 - Batch determ.: Selection w. remaining life LOBM_RLZ, for this.
List Of User Exit Related to VL01N V02V0002 V02V0003 V02V0004 V50PSTAT V50Q0001 V50R0001 V50R0002 V50R0004 V50S0001 V53C0001 - Sales area determination for stock transport order - User exit for storage location determination - User exit for gate + matl staging area determination - User Exit for Staging Area Determination (Item) - Delivery: Item Status Calculation - Delivery Monitor: User Exits for Filling Display Fields - Collective processing for delivery creation - Collective processing for delivery creation - Calculation of Stock for POs for Shipping Due Date List - User Exits for Delivery Processing - Rough workload calculation in time per item
V53C0002 V53W0001 VMDE0001 VMDE0002 VMDE0003 VMDE0004
- W&S: RWE enhancement - shipping material type/time slot - User exits for creating picking waves - Shipping Interface: Error Handling - Inbound IDoc - Shipping Interface: Message PICKSD (Picking, Outbound) - Shipping Interface: Message SDPICK (Picking, Inbound) - Shipping Interface: Message SDPACK (Packing, Inbound)
How To Create Sales Order
What are the steps to create a sales order? To create a standard sales order, proceed as follows: In the initial screen, choose Logistics - Sales and distribution - Sales. Choose Order Create (VA01). Enter the order type and, if necessary, the organizational data. The values for sales organization, for distribution channel and the division are usually proposed from user-defined parameters. Entries for the sales office and the sales group are optional. The sales areas (sales organization, distribution channel, division) are derived from the sold-to or ship-to parties. This means that you do not have to enter the sales area when you create a sales document. If you do not specify a sales area in the initial screen, the system uses the sold-to or ship-to parties, which you entered in the overview screen, to derive the sales area. If there are several sales areas for that particular sold-to or ship-to party, you can choose the right sales area in the following dialog box. The system then copies the selected sales area into the entry screen. Choose Enter. Enter the following data: - Sold-to party or ship-to party require.
An error message appears in the status bar to inform you if the system is not able to determine a sold-to party. If you enter a sold-to party that is also a unique ship-to party, the system automatically copies it as such and informs you in the status bar. - Customer purchase order number - Material numbers - Order quantities for the materials - Choose Enter. If, for example, you defined several unloading points or several ship-to parties in the customer master record of the sold-to party, the system displays the alternatives in a dialog box. The system can display alternatives for any or all of the following data: ± - Unloading point - Ship-to party - Payer - Bill-to party Select the valid data from these proposals by positioning the cursor on the line and choosing Choose. As soon as you have selected this data, the material data that you have entered is displayed. If the system carries out an availability check and finds that there is insufficient stock for an order item to be delivered on the requested date, it displays a screen on which you can choose between several delivery proposals. You can find more information about this in Reactions to the Availability Check in Sales Documents. If you want to enter further data for the header or items, choose the corresponding menu entry. If you want to change data for the items, select the items before you choose a menu entry. Enter all necessary data. Save your document.
Duplicate customer purchase order
If you are facing a problem with duplicate customer purchase order as your company does not allowed a same customer purchase order with the same sales order type. You can activated the check for duplicate purchase order with "VOV8".
In the General Control Section, look for the field Check Purchase Order No and put in "A". Best regards, SAP Basis, ABAP Programming and Other IMG Stuff
Default First Date is not Today
When end user created a new sales order with VA01, default First Date wasn't today, why? Note: 1. Before today, default First Date was always today. 2. Nobody change system configuration. Although you mention that nobody change the system configuration, it is very unlikely that the system will mis-behaved after one day. Usually, after checking, you will find that someone have actually change the configuration as it could not be a software bug since you have been using it for quite sometime without any problems. The date is control by each Sales Order Type for each Sales Document type whether is it a - OR - Standard Order, - RE - Returns etc. Verify the Sales order type configuration with the following path: IMG: Sales and Distribution --> Sales --> Sales Docs --> Sales Doc Hdr --> Define Sales Doc Types (transaction vov8) will let you control this by sales document type. There is one field (Lead time in days) which "specify the number of days after the current date that the proposal for the requested delivery date in the sales document should be". This should be blank if you want the system to propose current day for delivery date.
Sales Order Confirm Quantity Date
SAP SD User Ticket:).
Auto proposed all the dates when creating Sales Order
How can I make the system auto create all the Sales Order date during creation? Each Sales Order can have different date proposal settings. Follows this step to set the default Sales Order Type proposal date: - Goto VOV8, double click on sales order type. - Look and tick the fields Propose delivery date and Propose PO date. After making the necessary IMG changes, you need to input the Delivery Plant field for each Materials that you want the system to propose the default date. To change the Materials field Delivery Plant: Goto MM02, Select the View Sales: Sales Org. Data 1 and fill in the Delivery Plant. Testing: Now, try creating a new sales order for the material and SAP will auto proposed all the dates in the sales order. Define whether the Material can be used at which Sales and Distribution process Here you define how the system responds when entering a sales and distribution document with this material in the differenet reponse for each Sales and Distribution process :1. no dialog 2. warning when entering the document 3. error message (that is, the sales and distribution document cannot be entered on the basis of the material status)
Assign a Cost Center manually in a Sales Order (VBAKKOSTL)
The Cost Center Determination settings is in OVF3 - but there are some cases where the Cost Center must be exceptionally changed. If the document category for order type in IMG VOV8 is defined to be "I" which belong to order type FD - Deliv.Free of Charge, then the field cost center is active for input during transaction VA01. Alternatively, you can specify an order reason and assign a cost center to an order reason. However the standard SAP works only at the header level though, so it would not work if cost center is needed on the line item. The cost center are assign for such business transactions as :
- Free deliveries - Returns - Deliveries of advertising materials You can also make cost center allocation dependent on the order reason, for example: Order reason: Damage in transit Order reason: Free sample Both the IMG settings are done in transaction OVF3, either with/without the order reason. Best regards,
Sales and Distribution - Transfer of Requirements. For controlling..
What Do You Mean By Transfer of requirements
Explain transfer of requirement? How it works and how to configure? It specifies the following points: 1. Whether an availability check and a transfer of requirements is carried out for a transaction (for sales documents, fine tuning using the schedule line category is possible), 2. Whether the requirements are relevant for MRP, 3. The allocation indicator from the sales view which controls the settlement of customer requirements with requirements, 4. Whether an item is to be settled to an auxiliary account assignment, 5. The settlement profile, 6. The results analysis key. When a sales order is raised, then the system check for availability of goods. If the availability of goods is not there, then the system creates a TOR for the supply of goods to PP. Then PP can do procure or produce the goods. This can be configured by creating requirement class and requirement type and in the corresponding schedule line category requirement had to be checked.. The following sections on the transfer of requirements describe how to control the transfer of requirements. The transfer of requirements is basically dependent upon the following factors: - requirements type - requirement class - check group - schedule line category The transfer of requirements is controlled globally using the requirements class which is derived from the requirements type for all sales document types. For the sales document types, fine tuning is also possible at schedule line level. This fine tuning is described in the section "Defining the procedure for each schedule line category". Note that the requirements classes are also used in production so you should coordinate any changes to the requirements classes with production. The requirements type and, eventually, requirements class are determined in the strategy group so all changes made there should also be coordinated with production. For performing. Requirements transferred to planning are further processed in the module MM. You must, therefore, coordinate the transfer of requirements with the module MM.
Define MWST GST 0 1 Tax Exempt Liable for Taxes
Now, you define the Tax Determination in VK12. VK12 - Domestic Taxes/Export Taxes Condition Type Customer Taxes 0 0 MWST Material Taxes 0 1 Rate Taxes 0% 0%
1 1
0 1
0%: 10 11 01 00.
AP SD: Scheduling Agreement Vs Contract
A schedule agreement contains details of a delivery schedule but a contract just contains quantity and price information and no details of specific delivery dates What's the difference between schedulling agreement with normal order? What's the condition for us to choose schedule line or order? Both of them contains schedule line, price, quantity. There are a couple major differences: (1) - Schedule agreements allow you to have 2 different sets of schedule lines (VBEP.
Sales Order Mass Change
I am a SAP SD consultant and recently faced with two new terms, mass order change and ALV , I also need to know about the transaction code. There is transaction MASS which can be used to carry out mass changes in the sales order and other objects..
Release strategy for Sales order
Is it possible to have release strategy for sales order? Satish C Jha As such SAP standard does not provide release strategy for sales orders similar to purchase orders. However this requirement of your can be satisfied through authorisation profiles; what I mean to say is that the sale order to be kept incomplete by the person who does not have the required authorisation & the person with proper authorisation will complete it for further processing. This is only one way of meeting your requirement. Balraj G Saigal In order to emulate a release strategy similar to purchase orders you can use the status profile in sales documents (BS02). IMG-Sales and distribution-Sales-Sales documents-Define and assign status profile.
How to do rebate processing
Rebates Processs in SAP is divided into three components 1) Configuring Rebates 2) Setting Up Rebates 3) Managing rebate agreeeements and payments Pre-requsiistes- Check the following: 1.The payer partner needs toi have the rebate field checked in the customer master on the sales area-billing doc tab. 2.The Billing type must be marked as relevant for rebates. 3.The Sales Organisation must be marked as relevant for rebates.
Condition Technique : Rebates, use the condition technique, but distinguish themselves from pricing in applying to transactions over time, versus on a transaction basis. Rebates have their wn field catalog and their own condition table naming convention.So you could have two condition table "001" one for pricing and one for rebates, which could have different key fields. You need to use the technical names A001 For pricing and KOTe001 for rebates when you use the query type using transaction SE 16.. Use create access sequence (AS). Enter 1 in field category for rebate specific. AS after going thru the right path of maintaining access sequence for rebates. The big difference between the rebate and the pricing access sequence is that there is no exclsuion flag available for rebate related AS. This means multiple tables for an access sequence can be aplied at the same time. Rebate related condition types are identified by codnition class -C. After defining and creating condition types for rebated include them in the pricing proceedure. The requirement should be 24 here which implies that the accruals are calculated on the basis of invoice/bill. The other fields- alctyp and altcbv does not allow you to manipulate how a rebate is calculated. Also, remove the requiremnt 24, if u want to see reabtes at order time. Now payment of rebates: Payments can be maunal or in full settlement. When you do manual payments, it defines how much can be paid out during a partial settlemetn. You use partial settlement only when rebate agreement is defined for a full year but the paoyouts are supposed to happen on a monthly, quarterly or anyother specified period. These accurals are based on sales volume and when they are posted billing is created int eh follwoing manner. Provision for accruals is debited and Sales revenue is credited. When rebate credit memo is created Customer account/ is debited and Accrual provision account is credited. Also, please note that when rebates are created without dependent ona material but on customer/material you need to refer to a material for settlement. With Compliment: Srini I have this same problem found in:
However, can somebody explain it as I have problem in understanding the link. What exactly do you wish to know in Rebates? The total outline of the Rebate process or each and every step in the SAP system? First of all rebates are more or less discounts which are offered to customers. The rebates are based on the volume of the business the customer does with you within a specified time. for eg if the customer agrees for Rs.1 Crore worth of business with u in 1 year, then you activate your rebate porocess. if at the end of the year the customer DOES achieve the target u offer him say 2/3/4 % whatever is decided. The rebates are passed on to the customer in the form of Credit notes. The rebate can be given to the customer at one time or in installments also. This is broadly the outline of the rebate process. R.Sreeram Note : I recomend you to study the theory part of why rebate and why not a discount. This will help you understand better. May be I can help you with rebate process.(IN -IMG) 1. define a rebate agreement type 2. define a condition type group 3. define a condition type and place this condition Type in the pricing procedure.(REQUIREMENT=24) ALSO IN THE PROCEDURE- ACCRUAL KEY = ERU YOU ALSO HAVE TO DO THE ACCOUNT DETERMINATION FOR REBATES. Once you have defined all the 3 and assignment starts. Assign the agreement type to the condition type group Assign the cond type group to the condition type. Condition technique is also used in rebates. REBATE ACTIVATION- IN CUSTOMER MASTER, SALES ORGANISATION AND FOR THE BILLING DOCUMENT. After having done this please proceed to maintain the condition record for the rebates (transaction code-vbo1)
Note: if you maintain the requirement coloumn with the requirement as 24 - the rebate will be affected in the billing document and if you dont give the requirement as 24 your rebate will be affected in the sales order. The rebate process is completed when you have created a credit memo to the customer. The document type for the partial settlement is R3. Please make sure you open two screens SO THAT YOU CAN COMPARE THE NEW ENTRIES WHAT EVER YOU'RE DEFINING WITH THAT OF THE STANDARDS or first you try with the standard condition type boo1, boo2 boo3 boo4. AFTER YOU HAVE FINISHED A COMPLETE SALES CYCLE OF CREATION ORDER , DELIVERY AND BILLING. GO TO THE CONDITION RECORD IN CHANGE MODE (VB02) AND SETTLE THE ACCOUNT PARTIALLY. I hope this will be of any help to you. Praveen In a simple way, 1. First you need to create a Rebate agreement. 2. Create condition record for rebate giving the rebate rate and accrual rate. 3. when the rebate relevent billing doc is generated, the rebate and accruals are determined and posted in a seperate GL account as a noted item - amount to be settled. Also it gets copied in the rebate agreement. 4. create settlement run using credit memo request and then credit memo to settle this amount with the customer. This is what the link says. Shrinivas
Rebate Process with Ref. to SO
If I need to make a rebate for a customer what is the process involved. I am providing some info on rebates which I know.
Rebate agreemnts is based on agreement types.Conditon records which are created like B001 and B002 are linked to the rebate agreeements specifying the rebate rate + the accrual rates.condition records specify the rebate rate and the accrual rates. Consider an example.. You decided to give a rebate of 3% to a customer whose sales vol is $1000 for a particular SO Then the rebate value is $30.. Now when you make the rebate settlement by doiing the Credit memo and you decide to pay $27, then the accounting will be generated saying 27$ paid towards rebate and 3$ is the accrual which you owe to the customer Procedure: Rebate agreement: Transaction code: VB01 When you go to VB01, choose agreement type 0002 and then in conditions give Material rebate 1 20 20 30 Now create a sales order with a material say M-11 for SOrg 1000 12 00 with QTY 6 Now check VB03 and see rebate agreemtent it will say Accruals 120 and payments 0 since your rebate is not settled still. Rebate setllement Now the final settlement will be this way
Accruals:120 Accrual reversed:80 Rebate pay:80 Amount payable:40 So the balance 40 is still the accrual This is an example how a rebate will be processed with ref to a SO with an example. SAP SD Tips by: Priyam
How to do a rebate agreement for a specific customers with settings details?
1. Create a condition by copying a a standard condition like BO03 in V/06 2. Assign this condition in the std pricing procedure with acct key as ERB and accural key as ERU - V/08 3.Create a Rebate Agreement in VBO1 (It is O = Owl and not zero). No will be generated choose 003 - Customer rebates, enter the customer code, the validity and check for the status shld be in Open, click on the conditions enter the percentage and accrual amount. You also can have scales in this. Also you need to maintain the material for the settlement 4. Create a sales order for that customer and check the rebate agreement. 5. You can see the rebate condition in the invoice only. 6. Once you have posted the invoices, then go to rebate agrrement no. clicl on verficayion and it will show the order details. 7. For settlement change the status of the rebate to B - release for the settlement. 8. Credit memo request will b generated copy the no. and go to VA02, remove the blocks if any and create an invoice (credit memo).this will show u the accrual amount. 9. In both the invoice and the credit memo check the posting - accounting document it will show u the accrual as negative. 10. Again go to rebate aggreement and check the status it will show you D - Final settlement of agreement already carried out
Consignment Sales Process in SAP
The consignment process in SAP standard consist of four small processes:
Consignment fillup (send materials to customer consignment). Here you have a consignment fillup order and a consignment fillupup shedule line category E1 In this step, you are not invoicing the customer. document flow is sales order ---delivery item category. It will not be relevent shedule line category: C0 or C1 Here you are invoicing the customer(because he used the goods). you are assigning the delivery documnt and billing document to the sales document. In item category, you are setting relevent for billing, pricing, special stock. In schedule line category, your setting is 633 movement type, relevent for availability check & TOR. 3. Consignment Return: Customer found that some goods are damaged or he not able to sold the goods he want to send it back. that you are creating this document. Sales document type: KR Item category: KRN Shedule line category: D0 You will assign delivery document and billing to sales document. you will create return order, return delivery, return billing. Your setting item category relevent retrun delivery to sales document type. Sales document: KA Item category: KAN schedule line category: F0 & F1 Your setting item category relevent for returns. any shedule line category relevent for 632 movement type, MRP, availability check, delivery.
Now you check your plant stock. Stock will increase. Rao
*-- Ugameswara
Issue free goods to selected Customers
Client wants to issue free goods to selected customers after the said customer buys a specified quantity of a good during the festive season starting 02 December to mid January. for example customer A buys 34 cartons of Corn Icecream,
Supressing Fields in Sale Order
To make optional / mandatory you can use in 'LOO'. With Compliments by: Taner Yuksel Actually suppressing fielding sales orders userwise is quite easy. We are doing it in our company. For this we use userexit FORM USEREXIT_FIELD_MODIFICATION in MV45AFZZ. Below is the sample code IF SCREEN-NAME = 'VBKD-ABSSC'. AUTHORITY-CHECK OBJECT 'ZMV45AFZZ' ID 'SCRFNAME' FIELD SCREENNAME.. With Compliments by: Martishev Sabir
Some Light on Batch Determination
On batch determination, the whole process, how it is determined automatically in the order.
A1) Normaly we use batch determination at delivery level, because at the time of order material may or may not be created.for this material should be configured with batch and batch determination should be checked in sales views of material. A2) Batch Determination during order Creation. For this you need to maintain a Classes d for you Material. Depending on the Manufacturing process you can define the characteristics for your material. Ex: Purity for Medicines, Resistance for Electric Items. You need to create a class (You might have to create a new class type) which incorporates the characteristic. First Create the Characteristic Using Ct04 and then using Cl02 create the Class including this characteristic. Then in your material master Classification View Enter this class. Then Create a Batch for the particular plant and Stor Loc using MSC1N.Give the value of the characteristics in this batch. Then go to SPRO ->Logistics General ->Batch Management and maintain the Condition Technique (Procedure, Strategy Types and assignment to sales docs etc). Then Create the Batch Determination Record using VCH1.
Difference between Item Proposal and Material Determination
What is the difference between the item proposal and material determination product proposal? Item proposal and product proposal are the same. Item proposal is the list of materials and order quantities that can be copied into the sales order from the customer master data. We use VA51 to create the item proposal. Here we get a number.This number is then linked to the customer master data in the sales view. This is very commonly used. Material determination is very closely related to item proposal /product proposal and is used to swap one material for another in the sales order using the condition
technique. I have not seen Material determination procedures used in the projects I have worked. SAP Tips by: Prashanth Harish Item Proposal or Product proposal: "Item proposal is same as product proposal & SAP uses the two terms interchangeably. "An item proposal is a list of materials and order quantities that can be copied into the sales order. Items can also be selected from a list and copied into a sales order." 1) Use transaction [VOV8] to configure the document type ("MS" for product proposal). 2) Use transaction [VA51] to create a proposal. 3) Enter the item proposal on the sales area data (sales tab) of the customer master record. 4) In [VA01] to create a sales order, Select Edit & propose items." Material determination: "Material determination uses the condition technique to swap one material for another when certain conditions apply. Material determination is triggered by the material entered in the line item of the sales order. Use transaction [VB11] to create a material determination condition record. And [OV12] for configuration of material determination. Material determination is useful when old product is becoming obsolete or a new product is released by the company at specific date." SAP Tips by: Minmini
Steps for SD Variant Configuration
Some light on Variant Configuration in Detail. The procedure is as follows:
y y
Create a Material - KMAT type with Item category (002) Create Charateristics in CT04 - Zbike, where in values mention the Color of the bile like Red, Blue etc
y
y y y
y y y y *-- Shaik Zaheeruddin the sales order.
Tell me about variant configaration? What are the type of questions we can expect in that?. Possible questions you can expect are: - What is variant configuration? - What is characteristic? - What is value? - What is class? - What is configuration profile? - What is dependency and what are the types? - What is a variant table? - And the transaction codes for the above.
*-- Balaji
Number Ranges In Sales Order
This
What is Debit note and Credit note
What is Debit note and Credit note? What is the purpose? How we create?: - Assignment to a single invoice - Assignment of a partial amount to an invoice - Assignment to several invoices When you post credit memos, the payment programme: ± Without reference to an order ± With reference to an existing order Here you enter which order the complaint refers to. ±. Tips by : Rajendran
Explain What Is Credit and Debit Memo:
y y y
Assignment to a single invoice Assignment of a partial amount to an invoice Assignment to several invoices
When you post credit memos, the payment programmed:
y y
Without reference to an order With reference to an existing order
Here you enter which order the complaint refers to.
y. Use the same Invoice Script/smartform for Credit/debit memo's INVOICE Output type : RD00 ScriptForm Name : RVINVOICE01
Driver Program Name : RVADIN01 smartform name : LB_BIL_INVOICE Smartform Driver Pgm: RLB_INVOICE
Configure Intercompany Stock Transport Order
Explain STO. STO is Stock Transport order. It is used for inter company transfer of goods. Plant to plant transfer and even transferring raw material to Third party contractors (Job Work). The Process is you create a STO do delivery against the STO and create a Billing Document against the STO. How to configure the inter-company Stock Transport Order? - Prassee Material should exist in both the plants (Delivering & Ordering), Internal customer should be assigned to the ordering plant ( MM -> Purchasing -> Purchase Order -> Setup stock transport order -> assign the internal customer to the ordering plant and assign the Sales area of the internal customer. Tcode : OMGN).
Inter Company Sales Process
Explain the Inter Company Sales Process. customer¶s. --In inter- company sales process, no PO will raise. While creating sales order, if the end user knows there is no stock on their plant, they request for their sister concern company to deliver these ordered goods to the customer directly, after delivery they will receive intercompany invoice from the delivering company code, that¶s the reason you enter delivering plant while creating sales order. Below is the inter-company check list: Check all your settings once again for creating inter-company billing: - Material should exist in both plants. - Stock will be maintained in D-Plant (Delivering). - Now Plant - R (Receiving) become the customer of Plant-D. So create a dummy customer in Plant-D's company code and sales area. - Assign this customer number to Plant -R's details & its selling sales area. - Maintain the intercomapny billing type (IV) in ur sales doc type (OR). - Assign the Plant-D to selling sales org+ dbt channel. - Maintain relevant copy controls between documents. - Determine pricing procedure for Standard (RVAA01) as well as Intercompany (ICAA01) (Note: Dummy customer's CPP, IV doc's DPP along with Delivering plant's sales area)
- Maintain the condition records for Condition type PI01- VK11 (Note: In ICAA01, you won't find any PI01 Ctype, but you'll find IV01-, if you observe the details of IV01 C.type in V/06, it has the ref Ctype as "PI01" , through which the condition record of PI01 is shared to IV01 also..) - Now create VA01, enter the required fields, in delivering plant -enter Plant-D, @ item level as well as @ header level, and save, - Create Delivery VL01n, with ref to SO, - Create Billing VF01 (with ref to DEL)--- observe bill type-F2, - Create Billing VF01 (with ref to DEL again)--observe the bill type-IV.
Normal Sales Order Cycle Configuration
What are those initial sales order config? By: Anuradha.
Default Storage Location In Sales Order
Where to maintain settings if we want to make storage location appear by default at the time of creating the sales order?
There is No storage location determination at Sales order level.. Only we can enter manually. Storage location will be determined at Delivery level only.. System does not determine storage location at sales order level. User has to indicate it at time of creating sales order. The storage location entered in the order item is copied into the outbound delivery. If no storage location for picking is specified in the order item, the system determines the storage location when it creates the outbound delivery and copies it into the delivery item. The system determines the picking location based on a MALA, RETA, MARA rule defined in the delivery type. This functionality is not available in the standard SAP. If you want the system to check the stock at a specific storage location, the storage location has to be entered manually at item level or you have to go for development so that it will be defaulted under the specific conditions specified. You have to create a Z-table and maintain the table with data under which that specific storage location has to be determined. A userexit has to be used so that it will default the appropriate storage location after checking the table. Storage loction determination in Sales order is only possible via a user exit. You cannot configure storage location into sales order: you need to use user exit MV45AFZB USEREXIT_SOURCE_DETERMIN or You can use userexit_save_document Userexit_save_document_prepare or The relevant forms to be used are: USEREXIT_MOVE_FIELD_TO_VBAK -- to default in Header. USEREXIT_MOVE_FIELD_TO_VBAP -- to default in item. User exit: MV45AFZZ ---
Standard SAP can't determine storage location at sales order level. If required to give manually. But at deliver it'll determine automatic. Do the proper settings at Delivery level: SPRO --> LOGISTICS EXECUTION --> SHIPPING --> PICKING --> DETERMINE PICKING LOCATION --> Define Rules for Picking Location Determination. If sales order level by default require, then you have to use user EXIT.
Explain The Meaning Of An Open Sales Order
What is an open sales order? An open sales order is where the order has not been delivered (physical goods). Open Sales order : I will explain taking an example, suppose there is an order for 100 qty and against this order, only 50 are being delivered till its delivery date . i.e. it is partially delivered. then its status will be open . because it is not fully delivered. You can check the open order status in VA02 in status tab. (double click on item and at item level chk the status) or check in transaction VA05 all the open orders. In SAP SD, the document flow will summarize the status of each document. In order, they are: 1. Sales order : once delivery has been created, the status of the order changes from "open" to "completed". 2. Outbound delivery : when items are picked and posted for goods issue, the status remains at "being processed"; the status becomes complete only when billing is done. 3. Billing document : when billing document is created and saved, and posted to accounting, the status of the delivery becomes "complete"; the status of billing becomes "complete" as well; an accounting document is created and the status is "not cleared". 4. Payments posting affects the status of the accounting document; hence, you look at table BSEG. once payment is posted with reference to this accounting document, the status becomes "cleared".
How can we know using data in tables whether a sales order is open or not? Check in Transaction VA05 and in table the status filed will tell you the status of open order. Table VBAP / VBAK / VBUK (header) and VBUP (item) Which table is updated when customer pays against an invoice? Check table VBAK / VBAP / VBRK / VBRP and VBFA you can chk the document flow. Can you tell if a sales order can be considered open if delivery has happened but payment has not been done yet? Yes, that sales order will be considered as complete order. not open order. Delivery will be open against which billing is not happened. How to close any open sales order? Go to transaction VA05, here you can see list of all Sales order open for any particular sales area. You can either do mass maintenance to close all the open order by giving rejection reason. Or you can check one by one order & reject the pending item. Go to VA02, input the sale order and execute. Now select the line item and assign Reason for Rejection which you will find on the right top side. If you have not delivered any quantity, then you can delete the sales order from the tcode VA02 - Enter your doc no- in the menu bar go to sales document-then DELETE.
Sold To Party In Sales Order Screen
After entering sales order (va01) screen, system giving default sold to party. How to disable this?
This is due to activation of userexit V45A0002. You need to deactivate this. Take the help from ABAPer to find the project which is assigned to the userexit and deactivate the same. or Can you also check in your SU3 Parameters whether there is any entry with Parameter ID - VAU? If some value is set for this parameter , it will be copied by default in SOLD-TOPARTY during creation of the Sales Document (VA01) You can remove this ID or clear the Value. You can also check if there is any Transaction Variant associated with your Transaction in SHD0 through which the default sold-to-party can come. --Change sold to party in sales order We have the below requirement of changing sold to party after creation of sales order: Once sales order is created, purchase requisition is created automatically and purchase order is created with reference to the purchase requisition. So when Goods receipt is done, the respective stock is getting reserved for that sales order. We wanted to change the sold to party option. After creation of purchase order, sold to party option in sales order is display only. How to make it changeable? As long as you have not created subsequent document like delivery or invoice, you can change the sold to party in sale order either in creation mode (VA01) or in change mode (VA02). But once you created the subsequent document, you cannot change the sold to party bocz, the said field will become uneditable. --Effect of sold to party in sales order
What is the effect of sold to party in sales order? Suppose we are creating the sales order with customer '11' and material 'abc', but before saving the sales order document we changed the customer and new customer is '21', so after this change which is redetermined in the sales order. These will get redetermine -->Tax -->Price -->Frieght -->Payment terms -->Shipping conditions -->Partner (Ship to party, bill to party and Payer). -->Route. If the Sold to party is changed from 11 to 21, then the new SP (21) may be valid for some other Sales Area, may have different SH,PY &BP. So accordingly those data will change. If different SP, then Price may vary, Shipping condition may vary. So those data may change. As different SH may be different, then Route may be different, Plant may be different, and as Tax is mostly Plant dependent, so Tax may change. If SP is different PY may be different, so Payment Term, Incoterm & Credit limit may be different, so those data will be changed/redetermined accordingly.
Profit Center Default In Sales Order
Question: In sales order we have profit center tab in line item --> account assignment. From where does this profit center comes here? The source I mean. Answer:
Sales order takes profit center from material master view Sales: Plant/General data. Profit center is assigned in (material master record) MMR in sales orgn 2 view. If you assign there automatically it will trigger in the sales order. In the item data -> account assignment tab . profit center to your MMR. In material master, I was created profit center PBB2K for part A but it is showing different profit center when sales order created. Advise why different profit center show in sales order? Check 0KEM for any sales order substitution for profit center. In general, the material master profit center defaults to profit center, but at sales order you can change the profit center otherwise check 0KEM? Please check OKB9, or Simple, It is in substitution, Go to transaction GGB1 and see under the node profit center accounting. You will see that you can substitute the profit center in the sales order using substitution.
You can define your own here. How can I make the Field Profit Center in the line item level of the sales order to mandatory? You can do this by transaction variant. Goto tcode SHD0, give t code as VA01. Make a transaction variant and make the fields mandatory. or Please include the Field Profit Center (PRCTR) in incompletion Procedure of Sales Order Item. So without Profit Center Entry Sales Order will be incomplete. Goto T.code OVA2 copy the procedure you are now working with and add the field vbap-Prctr. In VUP2 you can assign your new procedure to your item category.
Check Whether The Entries Is Maintain in LIS Update or Not
Path: SPRO --> IMG --> Logistics-General -->Logistics Information System --> Logistics Data Warehouse --> Updating --> Updating Control --> Settings: Sales --> Update Group --> Assign Update Group at Header Level Maintain following data, separately in two rows: Sales Org: say,1234 DstCh: Division: Customer Statistic Group: + Statistics group for sales document type: 1 and Sales Org: DstCh:
Division: Customer Statistic Group: + Statistics group for sales document type: 2 SPRO --> IMG --> Logistics-General -->Logistics Information System --> Logistics Data Warehouse --> Updating --> Updating Control --> Settings: Sales --> Update Group --> Assign Update Group at Item Level Maintain following data, separately in two rows: Sales Org: DstCh: Division: Customer Statistic Group: + Material Statistic Group: 1 Statistics group for sales document type: 1 Statistics group for the item category: 1 and Sales Org: DstCh: Division: Customer Statistic Group: + Material Statistic Group: 1 Statistics group for sales document type: 2 Statistics group for the item category: 2 Note: Once, you will maintain Settings for LIS-Update, it will update onwards transactions and will not update for already done transactions.
3PL Purchase Order Link To Sales Order
For third party order, either you can create the material master with item category group as BANS, so the system will automatically pick TAS in the sales order for the material or you can change the item category manually to TAS in the order. This will trigger a PR, based on the PR a PO will be generated. Defining Item Category Group
IMG -> Sales and Distribution -> Sales -> Sales Documents -> Sales Document Item > Define Item category groups Defining Item Category -> Sales and Distribution -> Sales -> Sales Documents -> Sales Document Item -> Define Item Categories Item category TAS Description 3rd party with SN CM Item type Blank Completion rule Blank Special stock Blank Relevant for billing B Billing plan type Blank Billing block Blank Pricing X Statistical value Blank Revenue recognition Blank Delimit. start date Blank Business data item X Sched. line allowed X Item relev. for delivery Blank Returns Blank Weight/Vol.- relevant X Credit active X Determine cost X Aut. batch determ. Blank Rounding permitted Blank Order qty = 1 Blank Incomplete proced. 28 PartnerDetermProced T TextDetermProcedure 01 Item cat. status group 1 Screen seq. group N Status profile Blank Create PO autom. Blank Config. strategy Blank Mat. variant action Blank ATP material variant Blank Structure scope Blank Application Blank Value contract material Blank
Contract release ctrl Blank Repair procedure Blank Billing form Blank DIP profile Blank Assigning Item Category IMG -> Sales and Distribution -> Sales -> Sales Documents -> Sales Document Item > Assign Item categories Creating Material MM01 1. On the screen Create Material (Initial Screen) enter the material number if External. 2. Choose Select View(s). (Basic View 1&2, Sales Views, Purchasing views and accounting views). 3. Enter the relevant data and save the material. Use material group BANS in the item material group field. Creating SD Pricing Conditions for material VK11 Creating Vendor Master XK01
What is the Foreign trade data required in SO for doing Exports
I am doing export sale but while creating billing document system give error that "Missing export data" hence accounting document has not created. Trouble Shooting and Problem Solving :". Solution : This will resolve the issue for current Invoice; but if the same error is occurring for every Invoice, maintain default values. To get the default values for foreign trade data go to 1. IMG --> Sales and Distribution --> Foreign Trade/Customs --> Basic data for foreign trade --> Define Business Transaction Types And Default Value --> Define Default Business Type (SD) In this step maintain assignments for country/sales org/dist channel / item category / and transaction type combination. 2. IMG --> Sales and Distribution --> Foreign Trade/Customs --> Basic data for foreign trade --> Define Procedures and Default Value --> Define procedure default In this step maintain assignments with the combination of country/sales org/dist channel/division/exp.imp group/item category/ procedure. Apart from the above we need to maintain Comm./imp. code no./country of origin and region of origin at material master HINT: Go to VTFL, select your billing type and delivery type and click on blue magnifying lens on top left so that it will take you to a screen where most probably, you would be maintaining "B" for "Determ.export data". Maintain blank field there and save. Now system will not throw incomplete error message.
Material To Be Added or Excluded To a Customer
How to setup material exclusion for customer during sales order creation? If you want specific material to be added or excluded to a customer, you can do it in "Listing and Exclusion".
Here is a small note on listing and exclusion, it may be helpful. Material listing and exclusion: Material listing: Whatever the materials that are placed in the listing for a customer he can access to those materials only. Maintaining records for material listing: Logistics Sales and distribution Master data Products Listing/Exclusion VB01 Create Specify the condition type for listing Select the required key combination Enter the required materials in listing and save it. Material Exclusion: Whatever the materials that are placed in exclusion for a customer he cannot access those materials. Maintaining records for material Exclusion: Logistics Sales and distribution Master data Products Listing/Exclusion VB01 Create Specify the condition type for exclusion Select the required key combination Enter the required materials in exclusion and save it. Maintaining condition technique for listing and exclusion: SPRO Sales and distribution Basic functions Listing/Exclusion
Maintain condition tables for listing/exclusion Maintain access sequence for listing/exclusion Maintain listing/exclusion types Go to new entries and define condition types one each for listing, exclusion Procedure for maintaining listing/exclusion Define the procedure one each for listing and exclusion Activate listing/exclusion by sales document type Select the required sales document type and assign the procedure for listing and exclusion Note: 1. Listing type A001 2. Exclusion type B001 3. Procedure for listing A00001 4. Procedure for exclusion B00001
Sales Order Number Blank In MD04
I have a sales order which is complete in all respects. The sales order appears in MD04 with correct date and quantity. However MD04 does not show the sales order number. (number is blank) Delivery can be created from this sales order. This delivery is seen in MD04 with correct date and quantity, but the delivery number is not shown in MD04. Delivery is successfully PGI'ed subsequently. Why the numbers that are saved in SD not shown in MD04? Solution: Check in Material Master - MRP3 View. Availability Check might be maintained as "01" - Daily requirement. If is, then the sales order number will not appear in MD04 list. SO number will appear for 02- Individual requirement. Fyi:
Once sales order is created - it will be appear in MD04, once delivery is created wrt: SO ( w/o PGI), then delivery number will appear, SO number will not appear. Once PGI is done against to this delivery document. Then the line item from MD04 will be deleted. To recovery / delete the inconsistent entries, you can run the prog: SDRQCR21 It makes sense as well that for 01, the orders on the same day are summarized. Your understanding is perfectly right. This is the reason, why you can't see the SO number in MD04 for Materials which has AC:01. In MD04- line appears as summarized requirement for the whole day, it could consist all the SO numbers on that day. So you can¶t see the SO number in this case. To check the Availability Check rules for existing sales order (VBBE), do the following: 1. Go to the sales order. 2. Select particular line item. 3. Click on Display availability button at the bottom 4. You shall get the availability screen. 5. ON the top , click on SCOPE OF CHECK 6. You shall see that on top left section, there are two fields A) Availability Check ( eg 01, 02 etc) B) Checking rule ( A , B etc ) Your focus should be on Availability Check. If it is 02, it indicates Individual Requirement. If your availability check option is 01, it means table VBBS shall be updated with Daily ( total records / requirements )
If your availability check option is 02, then ideally table VBBE should have been updated for that sales order PS: For existing sales order that were already created, it will still shows blank as the system only copied the MRP Settings once. New sales order or new item line in the same sales order with the materials will work after MM - MRP View 3 - Availability Check had been changed to "02".
Partner Determination For Sales Doc
Explain me how to get partner determination for sales doc header level. By: Micro Irrigation First determine one account group ( Trans code OBD2 ) assign number range for acct group ( Trans code OBAR ). Define partner determination procedure: IMG -> SD -> Basic Functions -> Partner Determination -> Setup Partner Determination -> Partner Determination For Sales Doc Header Click on Partner Type Go To New Entries and Define Partner Types Customer KU Vendor LI Contact Person AP Sales Employ SE Select Partner Type KU and Go To Details Icon and Maintain Partner Functions SP Sold To Party SH Ship To Party BP Bill To Party PY Payer Come Back and Click On Assign Partner Type To Sales Doc Header KU To TA Assign Partner Functions To Account Group
SP To ACC GROUP SH BP PY Same. For Sales Doc Header The Partner Functions Can Be Determined From Customer Master.
Setup Partner Determination Procedure
How kb credit represent pe 09.
Sales BOM Implementation
A bill of material (BOM) describes the different components that together create a product. A BOM for a bicycle, for example, consists of all the parts that make up the bicycle: the frame, the saddle, wheels, and so on. Process Flow The type of processing used by the system is determined by the item category group that you enter in the material master record for relevant materials. Processing at Main Item Level If you want the system to carry out pricing, inventory control, and delivery processing at main item level, enter ERLA in the Item category group field of theSales: sales org. 2 screen in the material master record of the finished product. This means that the components only function as text items and are not relevant for delivery. The following graphic shows how a bill of material is processed at main item level.
Processing at Component Level If you want the system to carry out pricing, inventory control, and delivery processing at the component level, enter LUMF in the Item category group field of theSales: sales org. 2 screen in the material master record of the finished product. In this case, only the components are relevant for delivery. During processing the system automatically creates a delivery group. The latest delivery date among all the components becomes the delivery date for the entire delivery group. recheck your whole config - the truth is out there somwhere. Fast Links:
What Is BOM Referring to SAP SD
What is bill of material? By: Mike BILL OF MATERIALS We need to maintain Material master records for the BOM Item and for the components also. The item category group of the BOM items is µERLA/LUMF¶ and the item category is µNORM¶. ³Manual Alternative´ 24-07-2007 ITEM CATEGORY DETERMINATION FOR BOM ITEM SD type OR OR OR OR OR OR OR NOTE: ITCaGr ERLA NORM LUMF NORM NORM NORM NORM Usg HLItCa TAQ TAE TAP TAN TAN TAE TAE DftItCa
TAQ TAP TAE TAN
A ± Explode single level BOM item B ± Explode multi level BOM item
CS01 ± Transaction code for creating BOM Item Statistical value µx¶ or µy¶ Make TAP relevant for pricing but values for statistical only.
ricing
Process Flow for 3rd Party Sales
Customize the third party sales in summary: 1. Create Vendor XK01 2. Create Material ±
Cross Selling : How To Configure
(1) Cross Selling: How to configure and the menu path details. (2) While creating individual order I face one error 'Plant not assigned to Controlling Area': How to configure controlling area and menu path. (3) Menu of path of subsequent Delivery Free of Charge. By : Ahmednsp" ± dialog box appears only in request. It is blank ± dialog box appears in request and after date is released Check cross selling ATP indicator: If you check it , system carry out ATP check for cross selling product. b) Assign cross selling profile: - Go to new entries, specify sales area - Specify customer cross selling procedure ±B - Specify document cross selling procedure. 4) Path to created controlling area: Img-->Ent Str-->Defintio-->Controlling-->Maintain Controlling Area , here you can create controlling area
An Example Of Third Party Sales
Scenario:'.
What is the Difference/Similarities between LIS and SIS
The Logistics Information System (LIS) is made up of the following information systems:
y y y y y y y y
Sales Information System Purchasing Information System Inventory Controlling Shop Floor Information System Plant Maintenance Information System Quality Management Information System Retail Information System (RIS) Transport Information System (TIS)
Out of this SIS (sales information system ) is one. In the standard system, the following information structures are available in the Sales Information System:
y y y y y y
S001 "Customer" S002 "Sales office" S003 "Sales organization" S004 "Material" S005 "Shipping point" S006 "Sales employee "
These information structures form the data basis for the respective standard analysis of the same name. In addition to the above information structures, the standard shipment also includes information structures that are used internally (S066/67 Credit Management, S060 rebate processing and S009/14 sales support). I am trying to see the standard analysis for the customer in MCTA transaction. But it is not showing all the invoices which I done in a day. It shows only a latest created invoice details.
MCTA is reading data in table S001, which will not give invoice details as this is a summation of data based on the billing date. T-code MCVV will allow you to simulate how a single invoice would update all SIS structures. You would need to create a custom SIS structure and add the invoice as a characteristic. Use S600 - S999 in the customer namespace then MCSI to execute any custom reports. Run MC22 and re-generate your info-structure (make sure you play with S001). Create new invoices and run MCTA again.
Availability Check on Quotation
SAP standard does not do an availability check on the quotation, as it is not a definite order, usually just a pricing quote. When it is converted to an order, the first availability check is carried out, as well as credit checks. The system will check stock in the plant, plus what is contained in the availability checking rule (scope of check) eg: can add POs for replenishment, purchase reqs, different planned orders, and subtract sales orders, deliveries etc already created against that material in that plant (and possibly Storage location). If there is enough stock in the plant/SLoc, the system will give you a confirmed date, or give you a date based on the production time or purchasing time from the material master. The date the system proposes is based on the customer's requested delivery date. SAP first backward schedules looking at the required delivery date, less transportation time, less transportation lead time, less pick and pack time, less production/purchase time if applicable. If the date it calculates is equal or later than today¶s date, then it will confirm the customer¶s required date. If it falls in the past, SAP will then forward schedule for today¶s date, plus the times listed above to get the date when the customer can actually have it. ATP is the single most complex part of the SD module, depending upon how PP and MRP is set up. MRP works semi-separately, depending on how it is set up. Basically, MRP looks at the demand on the plant, and if it the stock does not meet expected sales orders and deliveries, it will create a purchase requisition (outside purchase) or requirement or
planned order (for production) to cover the shortfall. When MRP is started, it will turn the PR into a PO or the requirement into a production order.
SD material Determination based on availability check
For SD material Determination you can create a Substitution reason and on the Strategy field, the following info. is available: Product selection in the background is performed on the basis of the availability check. We want to have the material determination only in case on material shortage. We expect the Substitution reason to give us this functionallity. It does not hovever take the availabilty into account before substitution. We thought the worse case is to create a ABAP which is linked to the "requirement" field in the Procedure (OV13). Has anyone had the same requirement? Is this a bug or just incorrectly documented? I also encountered this abnormally recently using material determination. In order to combat the problem, the first product substitution should be for the original material. I've illustrated this below: Original Product: ABC Substitutes: DEF, XYZ In order to perform product substitution ONLY in the case of ATP failure for product ABC, structure the Material Determination record as follows: Material Entered: ABC Substitutes: ABC DEF XYZ There seems to be a devaition at availability check and or on a conceptual note still. Availability check can be configured both at requiremnt class and at the schedule line categories level.
Whilst the availabilty check at the requirement class level via global and mandatory configuration the schedule line catgry availability check deals with the order. It is mandatory that the reqmnt class is flagged off for avlblty check and the schdelu line cat need not be. The following are the mandatory for Availability check to happen-1. Must be swithced on at the requirment class level and at the schedule line level. 2. Reqmnt type must exist by which a requiremnt class can be found 3. There must exist a plant and is defined 4.Checking group must be defined in Material Master records(it controls whthr the system is to create individual or collective reqmnt) A combination of checking gropup and checking rule will determine the scope of availbaility check.
Creating Multiple Materials in Material Determination
Material Determination is used to swap one material for another.It is possible to get a list of materials for substituiton,but remember you can substitue only one material from the list. This can be done through substituiton reason T Code [OVRQ] See the substitution reason number for Manual Material Selection - check the Entry box - check the Warning box - select A for Stategy - save. Go To VB11 to create Material Determination (taking into consideration that all the previous steps for material determiantion i.e. maintaining condition types,maintaining procedures for material determination and assigning procedures to sales doc. types have been done) Create one material determination,dont forget to give the Subst reason on top and also on the line. Click the Variants Icon on top left-Sreen opens
Specify different materials you want to swap with the material you have enterd Note that the subst reason is already copied on the screen Remember materials should be of the same sales area,atleast Divisions should be same.
Backward and Forward¶s.. The
loading time, pick/pack time, transit time, and transportation lead time are added to the new material availability date to calculate the confirmed delivery date. *-- Manoj Mahajan
Configuring Availability Check Through Checking Groups ± Checking groups are introduced into the sales order based on the setting in the material master record. SAP standard checking groups are 01 ± summarized requirements and 02 ± When controlling the Availability check at the time of the sales order, a purchase requisition does not necessarily indicate by it is going to come into the plant. A shipping notification on the other hand - a confirmed purchase order ± is a good indicator of receiving stock on a specified date. It is always recommended not to select the shipping notifications for the delivery requirements type as you may not actually receive the stock into plant or warehouse for which you are creating a delivery.
Back Order Processing Using CO06 and V_V2:.
See The Scope of ATP Check
How to see the scope of ATP check? When we creat a sales order, we can only confirm the delivery of goods, for the required delivery date if the goods are available for all the necessary processing activities which take place before delivery. Types of availability check: There are 3 types of availability checks in sales document processing: 1. Check on the basis of ATP quantities (Available To Promise) 2. Check against Product Allocation 3. Check against planning. Check on the basis of ATP Quantities The ATP quantity is calculated from the ware house stock, The planned inward movements of stocks (purchase orders, planned orders, production orders, etc) and The planned out ward movements of stock (Sales orders, delivery documents, etc.) This type of check is performed dynamically for each transaction with or without replenishment lead time (RLT).
RLT : It is the time that is needed to order or produce the requested material, the system determines the RLT according to specific times maintained in the material master record. Depending on the material type RLT can be calculated according to various time periods. For ex: In the case of trading goods it is determined according to the planned delivery time, purchase processing time and the goods receipt processing time. Availability check including RLT: Availability is checked up to the end of Replenishment Lead Time. If the material availability data is calculated on the basis of current date to lie after the RLT, item it self can be confirmed despite insufficient stock being available. In this case the system assumes that any quantity requested by the customer can be procured by the material availability date and consider the goods to be available. Controlling availability check in sales document processing. We need to customize SD Specific settings and General Settings General Control Features: The following control elements need to be maintained in customizing and in the material master record. 1. Strategy group: The allowed planning strategies i.e. the main strategy and further possible strategies are combined in a strategy group. It is specified in the Material Master Record in MRP3 view. Note: In customizing, the strategy groups are assigned to MRP groups depending on the Plant so that the strategy group is automatically proposed in the Material Master. 2. MRP group: The MRP group combines the material from the point of material requirements planning which is specified on the MRP1 view in the Material Master Data. SD Specific Control Features: 1. Requirements class: It controls all control features for planning and is also specifies whether the availability check is to take place for materials in the SD documents on the basis of ATP quantities and whether the requirements are to be passed on. SPRO Sales and distribution Basic functions
Availability check and transfer of requirements Availability check Availability check with ATP planning or against planning Define procedure by requirement class Checking groups: Checking group controls whether the system is to create individual or collective requirements in sales and shipping process. In addition a material block for the availability check with transfer of requirements can be set here. The checking group can also be used to deactivate the availability check. SPRO Sales and distribution Basic functions Availability check and transfer of requirements Availability check Availability check with ATP planning or against planning Define checking groups Checking rule: We use the checking rule to control the scope of availability check for each transaction the SD process. Checking rule in the combination of checking group determines the scope of availability check Creating checking rule SPRO Material management Purchasing Purchase order Set up stock transport order Create checking rule Scope of availability check SPRO Sales and distribution Basic functions Availability check and transfer of requirements Availability check
Availability check with ATP planning or against planning Carry out control for availability check Go to New Entries and define the scope of check in the combination of checking group and checking rule. The following elements can be involved in the availability check STOCKS: []Include safety stocks: Minimum stock at plant/ware house []Stock in transfer []Include quality inspection stock []Include Inward movement Out ward movement Purchase orders Sales requirements Purchase requisitions Deliveries Planned orders Release orders etc. Production orders If we do not check the field [] µcheck without RLT¶ the system considers RLT while checking the availability of the material Note: Blocking the material for availability check SPRO Sales and distribution Basic functions Availability check and transfer of requirements Availability check Availability check with ATP planning or against planning Define material block for other users If we check the field Block [] during the availability check of a material the users cannot make changes in the Material Master, cannot create PO, cannot create sales orders. Note: During the Material Master creation the system automatically proposes the checking group. Further the following setting is required. SPRO Sales and distribution Basic functions
Availability check and transfer of requirements Availability check Availability check with ATP planning or against planning Define checking groups default values. We need to assign the checking group to the combination of material type and plant.
ettlement Downpayment with Installment payment Term
Scenario :- Problem with Down payment settlement using installment payment term. 1. When we create Sales order, (sales item value = 100) use payment term : 0009 (Installment Payment term, 30%, 40%, 30%). In the Billing Plan, I specify 2 records, 1st record is Downpayment request 30% of Order value, billing type is FAZ . the 2nd record is Final invoice 100%, billing type is F2. 2. Create Billing type Down payment request , it will document as Noted item in the accounting document. 3. Receive Downpayment from customer via FI screen , at this stage the asccounting document is created as following Dr. Cash/Bank 30 Cr. Advance from customer 30 4. When I create Billing document for the sales item, the down payment value will be proposed for settlement at Billing Creation, I then accept the default value of down payment clearing. The accounting document is as below Dr. AR 30 (*split AR by installment payment term) AR 40 AR 30 Cr. Sales 100 Dr. Advance from customer 30 Cr. AR 9 (DP. 30% * 30) Cr AR 12 (DP. 30% * 40) Cr AR 9 (DP. 30% * 30) It seems SAP settlement Down payment by Installment Payment term. I was wondering that is there are alternative or an option to setup the Down payment settlement independent of Installment term. I meant, I don't want to have the last 3 Credit item as above, I want only 1 line item of credit, the accounting should be
Dr. AR 30 (*split AR by installment payment term) AR 40 AR 30 Cr. Sales 100 Dr. Advance from customer 30 Cr. AR 30 (Not separate by Installment payment term) Solutions : Suggesstions on how I could proceed? Your problem with Down payment settlement is common. Many users object to the down payment or security lodgement mechanism. In our case we often park and apply the advance manually to final invoice. However, following the above case we sometimes use this with our PS This alternative provides a cleaner option with the Downpayment.
Sales and Distribution - Upload Condition Pricing
RV14BTCI - Batch Input for Uploading Condition Pricing After executing the program, you have to use SM35 to process the update program. Envirionment : 4.6x Require flat file :ROW 1 BGR00 ROW 2 BKOND1 ROW 3 BKOND2 - no scale ROW 4 BKOND2 - no scale ROW 5 BKOND3 - with scale ROW 6 BKOND2 - no scale Sample flat file for uploading table A305 - Customer/Material with release status :0BIPRICE 123SAPABAP X 1VK15 A305V PR00 2ALL 990000123456SAP8204142100 2002043020020401 50USD 100PC 2ALL 990000123456SAP8217168100 2002043020020401 50USD 100PC 3 100PC 2 3 200PC 1 2ALL 990000123456SAP8220133910
There a total of 4 flat file format :BGR00 - Session Header Record
-----------------------------------------------------------------------------------------
| Field name | Description Length | Dec. |
| Report header
| Cat.
|
----------------------------------------------------------------------------------------| STYPE | Record type 000001 | 000000 | | GROUP | Group name 000012 | 000000 | | MANDT | Client 000003 | 000000 | | USNAM | User ID 000012 | 000000 | | START | Lock until: 000010 | 000000 | | XKEEP | Keep indicator 000001 | 000000 | | NODATA | No batch input 000001 | 000000 | | 0 | BI Session Name | Your client no | Queue user ID | Queue start date | CHAR | CHAR | CLNT | CHAR | DATS |
|
|
|
|
| X - don't delete SESS| CHAR | / | CHAR
|
|
-----------------------------------------------------------------------------------------
BKOND1 - Header Record
----------------------------------------------------------------------------------------| Field name | Description Length | Dec. | | Report header | Cat. |
----------------------------------------------------------------------------------------| STYPE | Record type 000001 | 000000 | | TCODE | Transaction code 000020 | 000000 | | KVEWE | Usage 000001 | 000000 | | KOTABNR | Table 000003 | 000000 | | 1 | TCode = VK15 | U | Table e.g. 305 | CHAR | CHAR | CHAR | CHAR |
|
|
|
| KAPPL | Application 000002 | 000000 | | KSCHL | Condition type 000004 | 000000 |
| App
e.g V
| CHAR | CHAR
|
| CTyp e.g PR00
|
-----------------------------------------------------------------------------------------
BKOND2 - Main Data Record
-----------------------------------------------------------------------------------------
| Field name | Description Length | Dec. |
| Report header
| Cat.
|
----------------------------------------------------------------------------------------| STYPE | Record type 000001 | 000000 | | VAKEY | VarKey 000100 | 000000 | | DATBI | Valid to 000010 | 000000 | | DATAB | Valid on 000010 | 000000 | | KBETR | Amount 000015 | 000000 | | KONWA | R/2 table 000005 | 000000 | | KPEIN | R/2 table 000005 | 000000 | | KMEIN | 000003 | 000000 | | MWSK1 | Tax code 000002 | 000000 | | KONMS | Scale UoM 000003 | 000000 | | 2 | VarKey | Valid to | Valid on | Amount | R2tab | R2tab | | CHAR | CHAR | DATS | DATS | CHAR | CHAR | CHAR | CHAR | CHAR | UNIT |
|
|
|
|
|
|
|
| Tx | UoM
|
|
| MXWRT | Amount 000015 | 000000 | | GKWRT | Amount 000015 | 000000 | | STFKZ | Scale type 000001 | 000000 | | KZNEP | Exclusion 000001 | 000000 | | LOEVM_KO | Deletion indic. 000001 | 000000 | | SKONWA | R/2 table 000005 | 000000 |
| Amount | Amount | S | CndEx | D | R2tab
| CHAR | CHAR | CHAR | CHAR | CHAR | CHAR
|
|
|
|
|
|
-----------------------------------------------------------------------------------------
BKOND3 - Scale Data Record
----------------------------------------------------------------------------------------| Field name | Description Length | Dec. | | Report header | Cat. |
----------------------------------------------------------------------------------------| STYPE | Record type 000001 | 000000 | | KSTBM | Quantity 000018 | 000000 | | KONMS | Scale UoM 000003 | 000000 | | KBETR | Amount 000015 | 000000 | | 3 | Quantity | UoM | Amount | CHAR | CHAR | UNIT | CHAR |
|
|
|
-----------------------------------------------------------------------------------------
Sales Order Changed History Display
* * Sales Order Changed History Display * * You can execute the report by :
* 1. Change Date * 2. User Name * 3. Sales Order Number * * Submitted by : SAP Basis, ABAP Programming and Other IMG Stuff * * REPORT ZSDCHANGE LINE-SIZE 132 NO STANDARD PAGE HEADING LINE-COUNT 065(001) MESSAGE-ID VR. TABLES: DD04T, CDHDR, CDPOS, DD03L, DD41V, T685T, VBPA, TPART, KONVC, VBUK. DATA: BEGIN OF ICDHDR OCCURS 50. INCLUDE STRUCTURE CDHDR. DATA: END OF ICDHDR. SELECT-OPTIONS: XUDATE FOR ICDHDR-UDATE, XNAME FOR ICDHDR-USERNAME, XVBELN FOR VBUK-VBELN. SELECTION-SCREEN SKIP. SELECTION-SCREEN BEGIN OF BLOCK BLK1 PARAMETERS: SUDATE RADIOBUTTON GROUP SNAME RADIOBUTTON GROUP SOBID RADIOBUTTON GROUP SELECTION-SCREEN END OF BLOCK BLK1. DATA: WFLAG, WCHANGENR LIKE CDHDR-CHANGENR, WUDATE LIKE CDHDR-UDATE, WNAME LIKE CDHDR-USERNAME, WVBELN LIKE VBUK-VBELN, WDEC1 TYPE P DECIMALS 3, WDEC2 TYPE P DECIMALS 3, WDEC3 TYPE P DECIMALS 3, WDEC4 TYPE P DECIMALS 3. DATA: UTEXT(16) VALUE 'has been changed', ITEXT(16) VALUE 'has been created', DTEXT(16) VALUE 'has been deleted'. DATA: BEGIN OF ICDSHW OCCURS 50. INCLUDE STRUCTURE CDSHW. DATA: END OF ICDSHW. DATA: BEGIN OF ITAB OCCURS 10. INCLUDE STRUCTURE CDSHW. WITH FRAME TITLE TEXT-001. R1, R1, R1.
DATA:
UDATE LIKE CDHDR-UDATE, USERNAME LIKE CDHDR-USERNAME, CHANGENR LIKE CDHDR-CHANGENR, VBELN(10), POSNR(6), ETENR(4), INDTEXT(200), END OF ITAB.
SELECT * FROM VBUK WHERE VBELN IN XVBELN. CLEAR CDHDR. CLEAR CDPOS. CDHDR-OBJECTCLAS = 'VERKBELEG'. CDHDR-OBJECTID = VBUK-VBELN. PERFORM READHEADER. PERFORM READPOS. LOOP AT ITAB. CASE ITAB-TABNAME. WHEN 'VBPA'. IF ITAB-FNAME = 'KUNNR' OR ITAB-FNAME = 'LIFNR' OR ITAB-FNAME = 'PARNR' OR ITAB-FNAME = 'PERNR' OR ITAB-FNAME IS INITIAL. MOVE ITAB-TABKEY TO VBPA. SELECT SINGLE * FROM TPART WHERE SPRAS = SY-LANGU AND PARVW = VBPA-PARVW. IF SY-SUBRC = 0. REPLACE '&' WITH TPART-VTEXT INTO ITAB-INDTEXT. ENDIF. ENDIF. WHEN 'VBAP'. IF ITAB-FNAME IS INITIAL. REPLACE '&' WITH 'Item' INTO ITAB-INDTEXT. ENDIF. WHEN 'KONVC'. MOVE ITAB-TABKEY TO KONVC. SELECT SINGLE * FROM T685T WHERE SPRAS = SY-LANGU AND KVEWE = 'A' AND KAPPL = 'V' AND KSCHL = KONVC-KSCHL. IF SY-SUBRC = 0. REPLACE '&' WITH T685T-VTEXT INTO ITAB-INDTEXT. ENDIF. ENDCASE. IF ITAB-INDTEXT(1) EQ '&'. REPLACE '&' WITH ITAB-FTEXT(40) INTO ITAB-INDTEXT. ENDIF. IF ITAB-CHNGIND = 'I'. REPLACE '%' WITH ITEXT INTO ITAB-INDTEXT. ELSEIF ITAB-CHNGIND = 'U'. REPLACE '%' WITH UTEXT INTO ITAB-INDTEXT. ELSE. REPLACE '%' WITH DTEXT INTO ITAB-INDTEXT. ENDIF. CONDENSE ITAB-INDTEXT. MODIFY ITAB.
ENDLOOP. ENDSELECT. IF SUDATE = 'X'. SORT ITAB BY UDATE VBELN POSNR ETENR. ELSEIF SOBID = 'X'. SORT ITAB BY VBELN POSNR ETENR UDATE. ELSE. SORT ITAB BY USERNAME VBELN POSNR ETENR UDATE. ENDIF. LOOP AT ITAB. CLEAR WFLAG. IF SUDATE = 'X'. IF WUDATE NE ITAB-UDATE. SKIP. WRITE:/001 ITAB-UDATE, 023 ITAB-USERNAME, 037(10) ITAB-VBELN. WFLAG = 'X'. WUDATE = ITAB-UDATE. WCHANGENR = ITAB-CHANGENR. ENDIF. ELSEIF SOBID NE 'X'. IF WVBELN NE ITAB-VBELN. SKIP. WRITE:/001 ITAB-VBELN. WVBELN = ITAB-VBELN. ENDIF. ELSE. IF WNAME NE ITAB-USERNAME. SKIP. WRITE:/001 ITAB-USERNAME. WNAME = ITAB-USERNAME. ENDIF. ENDIF. IF WCHANGENR NE ITAB-CHANGENR. WRITE:/023 ITAB-USERNAME, 037(10) ITAB-VBELN. WFLAG = 'X'. WCHANGENR = ITAB-CHANGENR. ENDIF. IF WFLAG = 'X'. WRITE: 013 ITAB-CHNGIND, 049 ITAB-POSNR, 057 ITAB-ETENR, 065 ITAB-INDTEXT(60). ELSE. WRITE: /013 ITAB-CHNGIND, 049 ITAB-POSNR, 057 ITAB-ETENR, 065 ITAB-INDTEXT(60). ENDIF. WRITE:/065 ITAB-F_OLD. WRITE:/065 ITAB-F_NEW. ENDLOOP.
FORM READHEADER. CALL FUNCTION 'CHANGEDOCUMENT_READ_HEADERS' EXPORTING DATE_OF_CHANGE = CDHDR-UDATE OBJECTCLASS = CDHDR-OBJECTCLAS OBJECTID = CDHDR-OBJECTID TIME_OF_CHANGE = CDHDR-UTIME USERNAME = CDHDR-USERNAME TABLES I_CDHDR = ICDHDR EXCEPTIONS NO_POSITION_FOUND = 1 OTHERS = 2. CASE SY-SUBRC. WHEN '0000'. WHEN '0001'. MESSAGE S311. LEAVE. WHEN '0002'. MESSAGE S311. LEAVE. ENDCASE. ENDFORM. FORM READPOS. LOOP AT ICDHDR. CHECK ICDHDR-UDATE IN XUDATE. CHECK ICDHDR-USERNAME IN XNAME. CALL FUNCTION 'CHANGEDOCUMENT_READ_POSITIONS' EXPORTING CHANGENUMBER = ICDHDR-CHANGENR TABLEKEY = CDPOS-TABKEY TABLENAME = CDPOS-TABNAME IMPORTING HEADER = CDHDR TABLES EDITPOS = ICDSHW EXCEPTIONS NO_POSITION_FOUND = 1 OTHERS = 2. CASE SY-SUBRC. WHEN '0000'. LOOP AT ICDSHW. CHECK ICDSHW-CHNGIND NE 'E'. CLEAR ITAB. MOVE-CORRESPONDING ICDHDR TO ITAB. MOVE-CORRESPONDING ICDSHW TO ITAB. CASE ITAB-TABNAME. WHEN 'KONVC'. MOVE ICDHDR-OBJECTID TO ITAB-VBELN. MOVE ICDSHW-TABKEY(6) TO ITAB-POSNR. WHEN OTHERS. MOVE ICDSHW-TABKEY+3(10) TO ITAB-VBELN. MOVE ICDSHW-TABKEY+13(6) TO ITAB-POSNR.
MOVE ICDSHW-TABKEY+19(4) ENDCASE. MOVE '& %' TO ITAB-INDTEXT. APPEND ITAB. CLEAR ITAB. ENDLOOP. WHEN OTHERS. MESSAGE S311. LEAVE. ENDCASE. ENDLOOP. ENDFORM. TOP-OF-PAGE. WRITE:/ SY-DATUM,SY-UZEIT, 50 'SALES ORDER CHANGE HISTORY', 120 'Page', SY-PAGNO. WRITE: / SY-REPID, 60 'SALES ORDERS STATISTICS'. SKIP. ULINE. IF SUDATE = 'X'. WRITE:/001 'Change Date', 013 'Time', 023 'User Name', 037 'Sale Order', 049 'Line', 057 'Sch No', 065 'Changes'. ELSEIF SOBID = 'X'. WRITE:/001 'Sale Order', 013 'Line', 021 'Sch No', 029 'Change Date', 041 'Time', 051 'User Name', 065 'Comment'. ELSE. WRITE:/001 'User Name', 015 'Time', 025 'Change Date', 037 'Sale Order', 049 'Line', 057 'Sch No', 065 'Changes'. ENDIF. ULINE.
TO ITAB-ETENR.
*--- End of.
User Exits on Sales and Distribution
Where to find the User Exits on Sales and Distribution along with functionality? To see the detail go to SPRO --- Sales and Distribution ---- System Modifications --User Exits There you will find all the details by checking IMG Activity Documentation. You will have User exit.
You will find all User Exits on Sales and Distribution along with functionality.
Customer User Exit For Billing
What are the user exit for billing document release to accounting? Please check below exits/customer exits, these all are trigger during VF02. USE. USEREXIT_ACCOUNT_PREP_KOMKCV (Module pool SAPLV60A, program RV60AFZZ) In this user exit additional fields for account determination that are not provided in the standard system are copied into communication structure KOMKCV (header fields). USEREXIT_ACCOUNT_PREP_KOMPCV (Module pool SAPLV60A) In this user exit additional fields for account determination that are not provided in the standard system are copied into communication structure KOMPCV (item fields). USEREXIT_NUMBER_RANGE_INV_DATE (Module pool SAPLV60A, program RV60AFZC) Depending on the number range, table TVFKD is used to set the billing date (countryspecific requirements in Italy). USEREXIT_NUMBER_RANGE is automatically deactivated when this user exit is being applied. USEREXIT_FILL_VBRK_VBRP (Module pool SAPLV60A, program RV60AFZC) This user exit is only called when the billing document is created. It is used to provide the header and the item of the new billing document with deviating or additional data. USEREXIT_PRINT_ITEM (Module pool SAPLV61A, program RV61AFZB) Printing the item line of a billing document can be supplemented or changed. USEREXIT_PRINT_HEAD (Module pool SAPLV61A, Program RV61AFZB) Printing the header line of a billing document can be supplemented or changed. User exits in program RV60AFZD Short descriptions of the user exits are contained in the program: USEREXIT_RELI_XVBPAK_AVBPAK
USEREXIT_NEWROLE_XVBPAK_AVBPAK USEREXIT_NEWROLE_XVBPAP_AVBPAK The following user exits are available in report SAPLV60B for transfer to accounting (function group V60B): EXIT_SAPLV60B_001: Change the header data in the structure acchd You can use this exit to influence the header information of the accounting document. For example, you can change the business transaction, "created on" date and time, the name of the person who created it or the transaction with which the document was created. EXIT_SAPLV60B_002: Change the customer line ACC customer line is filled in differently for costing. You can use exit 003 to influence the ACCIT structure. EXIT_SAPLV60B_004: Change a GL account item ACCIT You can add information to a GL account item (such as quantity specifications) with this exit. EXIT_SAPLV60B_005: User exit for accruals. Note: Use enhancement "SDVFX008", Component : "EXIT_SAPLV60B_008". SDVFX008 will indeed trigger while you create accounting document through VF01 or VF02. We have done similar development to update SGTXT field in BSEG. Check whether the function exit is activated.
Basic Process of how Packing Works
Let's say you want to pack a material shirt_jai in test_pack. Using MM01, create material type=packaging test_pack [SPRO] IMG-Logistics Execution-Shipping-PackingDefine Packaging Material Types Let's say JPAC. The settings that I chose: Plant determ. - Plant is entered manually in handling unit Pack. matl. cat. - Packaging materials Generate Dlv. Items - blank Number assignment - Number range interval 'HU_VEKP' IMG-Logistics Execution-Shipping-PackingDefine material group for packaging material Let's say JGRP IMG-Logistics Execution-Shipping-PackingDefine (Select shirt_jai and Edit - Pack) This is how the basic process of packing works. Content Author : Jairam Author Website :.
Difference between Condition Type
Please explain the difference between Ek01 ( Actual Cost) and EK02 Calculated Cost. 'Q' (costing). 2) The condition type must agree with the condition type defined for unit costing in the pricing procedure.? I think u need to change the validity of the condition record for the condition type K007 defining it not valid for that particular 2 months. And also the settings of the Requirements as it is correct that it overrules the exclusion. Arvind Rana
Accumulate the amount of condition types in accounting document
To accumulate the amount of condition types in accounting document without affecting the pricing display in billing document. As an illustration :ZPXX 3500 ZDXX 1000Z.
Hiding Price Condition Types on a Sales Document
Up to now you, you still cannot exclude certain condition types and subtotal lines from being processed or displayed in the condition screen by restricting the authorizations.
You have to implement SAP Note No. 105621 - Authorization check for the condition screen
Creating New Pricing Procedure
What is the transaction code for creating new pricing procedure and how to attach it to specific plant? You create PP in spro > Sales and Distribution > Basic Functions > Pricing > Pricing Control > Define and Assign Pricing Procedures > Maintain Pricing Procedures You can't attach PP to specific plant. Pricing Procedure is determined thru trx OVKK. The defining parameters for pricing procedure determination are: 1. SalesOrg 2. Distribution Channel 3. Division 4. Document Procedure (defined in Sales doc\Billing doc maintenance) 5. Pricing procedure assigned to customer (defined in customer master) Hope this helps. Sabir Reg pricing procedure. 1. Use transaction code v/07 to create a access sequence and assign tables based on which you want to carry on pricing as accesses. 2. Use transaction code v/06 to define condition type. It can be for base price, discount, freight etc., (Do assign relevant access sequence) 3. Use transaction code v/08 to define pricing procedure. 4. Assign this to your relevant sales area+ dpp+cupp. While specifying requirement, we can give reqt no.22 which specifies that plant has to be set. This is generally done for output taxes since output taxes depend upon the
delivering plant. But directly there is no assignment between plant and pricing procedure. Hope this helps,
What is "alt cal type" & "alt base value" & "Requirement field" in the Pricing Procedure
Can any one explain exactly what is "alt cal type" & "alt base value" and also " Requirement field" in the pricing procedure? The. Now once again, Alternative Calculation Type:. formulae.. *-- Ajay Kumar Veeranki
Re-pricing in a Quotation
How can I, or am I able to find anything on a way of RE-Pricing be done in a QUOTATION?
You can always 'Update" pricing manually in a quotation the same way you do in a sales order, either in create or change modes. Menu path Edit --> New Pricing or press the 'Update pricing' button on the item conditions tab. If you are asking how to reprice a quotation when it converts into a sales order, that can be done with the copy controls of the Item Category. IMG: Sales & Dist --> Sales --> --> Maintain Copy Control for Sales Docs --> Sales Doc to Sales Doc (transaction vtaa). Just choose the combination of documents and the respective item category. The field you need to be concerned with is "Pricing type". However, from a business process perspective it makes absolutely NO sense to reprice a quotation when converting to a sales order. After all, the entire point of using quotations is to firm up details like pricing before creating the sales order.
Quantity Based Discounts in Bulk Quantities Sales
You're looking to implement quantity based discounts in 4.6c. You are trying to sell items in specific bulk quantities, and only give the discount for specific quantity intervals. For example, if a customer orders 1 piece, 2 pieces, 3, etc. of part ABC, the price is $100. If the customer orders 10 pieces of part ABC, the price is $50. However, this is not only a standard minimum quantity discount. If the customer tries to order 11 pieces, 12, 13, etc. it should return $100 again. The only values for which $50 should apply are 10, 20, 30, etc. - multiples of the bulk quantity 10. You have discussed changing your part number to reflect a bulk qty of 10, however you have in house consumption that is allowed to consume only 1 part at a time. You would vastly prefer to keep one part number that you order from the supplier, consume internally and ship externally. You are fairly certain there is basic functionality that covers this, but you're just not sure where to start.
Taking your requirements literally. Standard SAP scale pricing will not do it in that you only want the reduced price to come into effect when the order quantity is multiple of some bulk factor. It is agreed with that creating a separate material number is not a good idea. You can try this :1. Define/Select a UOM for selling in bulk (i.e. cas, pallet, box whatever) 2. Maintain UOM conversion between your base UOM and this new UOM 3. Configure you bulk pricing condition type by usual means (it should be a base price rather than discount). 4. Place this new bulk price behind your normal "PR00" price in the pricing procedure 5. Create a new condition base value routine via VOFM where you check XKWERT to see if it is a whole number. If it is not then set XKWERT to zero. 6. Assign this new routine to your bulk price condition in your pricing procedure in ALT condition base value column. 7. Maintain bulk price conditon record in the Bulk UOM. That should do it.
Determine Sales Price with Shipping Point. Now, you will see in your sales order that the shipping point is filled with information.
Pricing date based on delivery date
Used transaction VOV8. This configuration is by order type. There is a field called proposal for pricing date. There you can select pricing date as requested delivery date. A - Proposed pricing date based on the requested dlv.date (Header) This control is set at the document level as oppose to the condition type level (PR00). That means your other condition types such as surcharges and discounts are also determined using the requested delivery date.
If your requirement is for PR00 to alone to be priced at delivery date then this will not work.
How pricing date is determine in the sales order and billing document? Where is the setting?
The pricing date is proposed based on the setting you make in the Sales document configuration. ( T code : VOV8) You have a field" Prop.f.pricing date " in the Requested delivery date / pricing date / purchase order date segment. Then you can choose the follwoing options: Blank - Indicates the current date as the pricing date A - Indicates the date based on the requested delivery date B - Indicates the date based on the order validity start from date And the pricing in the billing document is copied from thte sales order / Delivery document.. It again depends on the setting u have in the copy control from order - billng or delivery - billing. In the copy control, in the item settings you have two fields relavant for this. One is pricing source and the other is pricing type. The pricing sources are generally the order. But if you want you can change it to other values mentioned in the drop down, but this values have no effect if the pricing type is B. Any other value other than B in the pricing type will take the reference document price mentioned in the pricing source field. but for the pricing type B. The new price is determined in the billing order.
Report to Check the Entered Pricing Condition Price
Which is the best transaction code to check the Pricing condition price entered in "VK11"? Other than "VK13", to display the price, you can use V/LD - Execute Pricing Report to check the prices entered into the Pricing Master.
Normally Pricing Report - "07 Cust.-specific Prices with Scale Display" will do. Other Pricing Reports you can tried are these:
--------------------------------------------------------------------------| | ---------------------------------------------------------------------------
Mass Update of condition pricing
You can update the condition pricing for a range of sales order. For e.g. if you create sales order for 15 months or so, and at the beginning of each year, you have to update the prices for lots of sales orders. Other than using VA02 and make an Update of the conditions at item level which is a big work because you will have lots of open sales order after so many months. Use VA05, select your Orders and on the result screen :click Edit- > Mass Change -> New Pricing (menu).
or if you don't want to do that Online, write your own abap report and use Function SD_BULK_CHANGE (check where-Used at SE37, Trace VA05 on how to fill the parameters, Function MPRF => New Pricing)
Make Material Master Price of a material as sales price automatically V for moving average price. It is this simple if you do not have any other "Prices" in the price procedure.
Customer discounts on effort only
-----Original Message----Subject: Customer discounts on effort only Hi All, We have a requirement of giving a discount to customer based on the total amount invoiced so far (across financial years). Where do we set this up? We have seen so far the discounts are calculated based on the value of the current invoice. The discount should be on a graduated scale basis for example 0 - 100000 No discount 100000 - 200000 5% 200000 - and above 10% This means that discount would only start after the customer's net sale value crosses 100000. For example, if the customer has been billed for 99000 and the current invoice is for 3000, a discount of 5% should be given on 2000 i.e. 100. Another complication is that, the discount is not based on the total amount billed so far, but only on the effort billed and not on reimbursements (like airfares, living expenses, visa charges, beeper charges etc). The discount applies only to the effort and not to the reimbursements. In the above example (invoice of 3000) say the effort billed is only 1500, the rest being reimbursements. The discount is only on the 500. (the rest being taken up by the lower limit for eligibility of 100000) For example the customer might have been billed say 150000 so far but actual effort billed might be only 90000, the rest being reimbursements of actual costs and hence the customer is not eligible for the discount. Kindly help, -----Reply Message----Subject: RE: Customer discounts on effort only
Hi, The solution for this is Using rebate condition types and suitable condition records. Of this to handle your first problem that is the rebate has to be applied only on the "effort" you have to set up a line in the pricing procedure which gives the rebate basis i.e the value to be used for rebate cond types. This I believe solves your problem of rebate only on effort. Your second problem i.e the discount should start getting applied automatically when it reaches the first scale for which the values span few financial years. This I am not really sure whether it can be made possible in the invoice itself. But a work around is not giving the discount directly in the invoice but settling it against the rebate agreements by Credit notes periodically. Hope it helps. Thanks -----Reply Message----Subject: RE: Customer discounts on effort only Hi Arent we looking at rebate agreeement. That appears to be a straightaway solution to your problem. You activate the sales organization and the payer for that Regards -----Reply Message----Subject: RE: Customer discounts on effort only I am in SAP R/3 rel.30F. We have 2 options to meet your requirement. 1. Using scale in condition type ( tcode V/06 ), choose scale basis G.Scale based on a formula ( be: your based amount is invoice ). Define scale formula. You need ABAPER to define it. 2. Using routine in Alt.calc.type ( tcode V/08 , Maintain Pricing Procedure ). Here, you also need ABAPER to create routine.
hope this help -----End of Message-----
Steps to Create Commission for Agent
For creating commission agent, you have to follow below steps. 1) Establish Partner Functions for the Commissionee(s) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PARTNER DETERMINATION ->; DEFINE PARTNER FUNCTIONS Transaction Code: VOPA 2) Assign the Partner Functions to Partner Procedures Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PARTNER DETERMINATION ->; DEFINE PARTNER FUNCTIONS Transaction Code: VOPA 3) Create a Partner Procedure for the Commissionees Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PARTNER DETERMINATION ->; DEFINE PARTNER FUNCTIONS Transaction Code: VOPA 4) Create New Customer Account Group(s) for Commission Agents Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; LOGISTICS GENERAL ->; LOGISTICS BASIC DATA: BUSINESS PARTNERS >; CUSTOMERS ->; CONTROL ->; DEFINE ACCOUNT GROUPS AND FIELD SELECTION FOR CUSTOMER Transaction Code: OVT0 5) Assign the Partner Functions to the Customer Account Group(s) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PARTNER DETERMINATION ->; DEFINE PARTNER FUNCTIONS ->; GOTO ->; PARTNER FUNCTIONS ->; ENVIRONMENT ->; ACCOUNT GROUP ASSIGNMENT Transaction Code: VOPA 6) Assign the Partner Functions to the Partner Procedure for the Sales Document Header
Menu Path: Tools ->; Business Engineer ->; Customizing ->; Sales and Distribution >; Basic Functions ->; Partner Determination ->; Define Partner Functions Transaction Code: VOPA 7) Assign the Partner Functions to the Partner Procedure for the Sales Document Item (OPTIONAL) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PARTNER DETERMINATION ->; DEFINE PARTNER FUNCTIONS Transaction Code: VOPA 8) Edit the Pricing Communication Structure (KOMKAZ) to Hold the New Functions (Client Independent) Menu Path: Menu Path: TOOLS ->; ABAP WORKBENCH ->; DEVELOPMENT ->; DICTIONARY Transaction Code: SE11 9) Edit MV45AFZZ ± userexit_pricing_prepare_tkomk (Client Independent) Menu Path: TOOLS ->; ABAP WORKBENCH ->; DEVELOPMENT ->; ABAP EDITOR Transaction Code: SE38 10) Edit RV60AFZZ - userexit_pricing_prepare_tkomk (Client Independent) Menu Path: TOOLS ->; ABAP WORKBENCH ->; DEVELOPMENT ->; ABAP EDITOR Transaction Code: SE38 11) Edit MV45AFZB - userexit_new_pricing_vbkd changing new_pricing (Client Independent) Menu Path: TOOLS ->; ABAP WORKBENCH ->; DEVELOPMENT ->; ABAP EDITOR Transaction Code: SE38 The following code should be inserted into program MV45AFZZ to allow the system to re-execute pricing if the user makes a change to the relevant partner function (alteration, addition, deletion). 13) Add the KOMKAZ Fields to the Pricing Field Catalog (Client Independent) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PRICING ->; PRICING CONTROL ->; DEFINE ACCESS SEQUENCES ->; MAINTAIN ACCESS
SEQUENCES Transaction Code: OV24 14) Create Condition Tables (Client Independent) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PRICING ->; PRICING CONTROL ->; DEFINE ACCESS SEQUENCES ->; MAINTAIN ACCESS SEQUENCES Transaction Code: V/03 15) Create an access sequence containing the new tables (Client Independent) Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PRICING ->; PRICING CONTROL ->; DEFINE ACCESS SEQUENCES ->; MAINTAIN ACCESS SEQUENCES Transaction Code: V/07 16) Create a new condition type Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PRICING ->; PRICING CONTROL ->; DEFINE CONDITION TYPES ->; MAINTAIN CONDITION TYPES Transaction Code: V/06 17) Add the Condition Type to the Pricing Procedure Menu Path: TOOLS ->; BUSINESS ENGINEER ->; CUSTOMIZING ->; SALES AND DISTRIBUTION ->; BASIC FUNCTIONS ->; PRICING ->; PRICING CONTROL ->; DEFINE AND ASSIGN PRICING PROCEDURES ->; MAINTAIN PRICING PROCEDURES Transaction Code: V/08 11) Create Commsission Report ZZCOMMISSION (Client Independent) Menu Path: TOOLS ->; ABAP WORKBENCH ->; DEVELOPMENT ->; ABAP EDITOR Transaction Code: SE38
SD. Also to inform that, using T-Codes is more smarter than following paths through IMG screen. Utsav Mukherjee - utsavmukherjee143@hotmail.. SAP SD Tips by : Vishwajit. *-- Arvind Rana. *-- Nitin
Add a Field To New Condition Table in Pricing
Add a field to a new condition table in Pricing (Condition Technique):I will explain you the process with below example...Please follow steps in below sequenceTry and Distribution -> Basic Functions > Pricing -> Pricing Control' and execute 'Define Condition Tables'. Choose 'Conditions: customerspecific 'Sales and Distribution -> System Modifications -> Create New Fields (Using Condition Technique) -> New Fields for Pricing' and OSS Note 21040. *-- Manoj Mahajan
Header Condition and Group Condition
What are header conditions? Header conditions are those which appear in the header level of any sales order. these conditions are to be entered manually and get distributed automatically and the basis for distribution are taken from the NET VALUE of items mentioned at item level. When we go to the conditions section in a sales order, where the details of pricing is mentioned, here we add these conditions. Whenever any Header Condition is used, it overrides the PR00 condition type. Examples of header condition. - HA00 - % Based Header Condition. - RB00 - Absolute or numeric value which applies to all items. - HB00 - Numeric value or Absolute value. *-- Vivek Chokshi
What is the difference between group condition and header condition? Group Condition: You can use this is feature of a condition type to apply price or discount for a material based on common property. Header Condition: This is a manual condition which you apply to header (Condition screen) of a sales document. This amount is applicable to all items. Usage of this feature is to apply price / discount for a specific group of materials. 1. You maintained a discount based condition record fbased on material group ( = 01 for example). You maintained scales also.
Qty 1 - 10 11 - 50 51 - 150
Discount Rs. 100.00 Rs. 105.00 Rs. 110.00 etc.
2. You are creating a sales order for a customer with five different items with different quantities as below ITEM 1 - 25 No's ITEM 2 - 3 No's ITEM 3 - 12 No's ITEM 4 - 27 No's ITEM 5 - 62 No's All the material is having the material group = 01. 3. While calculating the discount, because of this group condition, system add the quantities of items which have material group = 01. In the above example total quantity is = 109. System apply a discount of Rs. 110.00 to each item irrespective of the individual quantities. 4. If you have not activated the group condition feature, system determines the discount value based on individual item quantity which is as below. Discount ITEM 1 - 25 No's Rs. 105.00 ITEM 2 - 3 No's Rs. 100.00 ITEM 3 - 12 No's Rs. 105.00 ITEM 4 - 27 No's Rs. 105.00 ITEM 5 - 62 No's Rs. 115.00 5. Is it clear now. Just try a sales order and see the out come Procedure to Test: 1. Create 3 materials. Maintain Material Group of each item is same. 2. Activate the condition type as a group condition. 3. Create a condition record for this condition type with scales. 4. Process a sales order for a customer with these three material with different quantities. *-- Tsr 5. Check the outcome.
Steps Involved In Condition Technique
What are the 8 steps involved in condition technique? By: Rohit Joshi.
I made most of the mistakes that appear above. Hope it helps.
Sales Order Freight Condition In Header Condition
ERP SAP ==> SD SAP Common questions: We are using the Freight in Header Condition. I maintained two line items in the Sales Order. So the Header freight is splitting irregularly for two line items (in item conditions) . How it is happening? Any formula is there?) Header Condition: If this condition is marked as a header condition, it is possible to enter the condition type in the header condition screen. Checks for changing the condition manually are unaffected by this. Group Condition: Group conditions are helpfull incase of discounts. If group condition is selected then the discount percentage or quantity is applicable for the total sum of the quantity in the PO for those materials belonging to the same material group. Suppose if two materials of same matl grp have discounts for 100 qty and above but in PO if the two matls are bieng procured for 50 qty then they cant avail discounts but if group condition is selected then the sum of the quantity of both matl of same matl group is considered (50 + 50) and discount can be availed for 100 qty. Further Group condition: Indicates whether the system calculates the basis for the scale value from more than one item in the document. The nature of header condition is that whatever value you are giving in sale order / billing, line item wise, it will be distributed proportionately.
If you access V/06 and the header condition type, you can see that the condition type - does not have any access sequence - field Group condition is selected Normally Freight Header condition like condition type "HD00" is calculated on the basis of weight. This is a Manual condition and you have to enter it in the header screen. It will be proportionately distributed on each item on the basis of weight. If you will uncheck the group condition field, the same freight amount will be copied to each item, possibly irrespective of different weight which may not be logical. That is the standard behaviour of the header condition type. Based on whether the group condition field is ticked on or off, it will either split the header condition value to the items on pro-rata basis or it will just duplicate the header value to all the items. What you are experiencing with Fixed Amount Header conditions is standard behaviour. Please see below Notes: - 876617 FAQ: Header conditions / Header condition screen - 317112 Behavior of conditions w/ calculation rule B changed - 485740 Conditions with fixed amount in copy activities To achieve what you wish (absolute amount), solution is in the below Notes: - 84605 Transfer absolute amount condition to billing doc. - 25020 Value changes during over/underdelivery - 25144 Freight conditions during milestone billing What is meant by condition exclusion for Condition types and records? Condition Exclusion The system can exclude conditions so that they are not taken into account during pricing in sales documents.. Condition Exclusion Group ± µcondition exclusion groups¶ you can ensure that the customer does not receive all the discounts, but instead only receives the best of the available discount condition types. Menu path ± IMG - Sales & Distribution - Basic functions ± pricing ± condition exclusion ± condition exclusion for groups of conditions (OV31). A condition exclusion group is merely a grouping of condition types that are compared to each other during pricing and result in the exclusion of particular condition types within a group or entire groups. It is important to note that the condition types you want the system to compare must exist in the pricing procedure and must have valid condition records created for them. If for example, a sales order is created using the pricing procedure that the exclusion group is assigned to, you can see that the condition offering the most favorable discount to the customer is represented in the pricing procedure.
For instance, condition type K007 has offered a discount of 10% off the sale price or a real value of $30, while another condition type K005 has offered a real value discount of $10. The system then takes the best discount for the customer between the two, which is K007 and makes the other discount K005 inactive. This can be seen by double clicking on the condition type K005, where you can find a entry saying µInactive A condition exclusion item¶. There are four possible methods of using condition exclusion groups ± A ± best condition between the condition types B ± best condition within the condition types C ± best condition between the two exclusion groups D ± exclusive E ± least favorable within the condition type F ± least favorable within the two exclusion groups Configuring µCondition Exclusion Groups¶ First step is to define a µcondition exclusion group¶ by using a four character alpha numeric key. Next step is to assign the relevant condition types to the exclusion groups such as discount condition types, freight condition types. After completing the assignment of the condition types to the exclusion group, proceed with assigning the condition exclusion group to the relevant pricing procedure. After selecting the pricing procedure for which you want the condition exclusion to be active, select the folder µExclusion¶ where you can assign the relevant condition exclusion procedure to the relevant condition exclusion group. When using the condition exclusion group to find the best condition record in a condition type ± only use one condition type per exclusion group. The most important thing to remember here is to ³deactivate´ the Exclusive Indicator on the access sequence assigned to that condition type. Otherwise, the system will merely find the first condition record and stop searching for other records.
What is difference between pricing report & condition index? Pricing Report: A Pricing report basically helps to get the list of all the pricing details which we have maintained in the system. We can get details of all the condition types including the scales. We can get the details as per our requirement i.e., Sales org/Dc/Division/Plant /material etc wise. The selection criteria would be as per the Key combination which you select in the IMG screen You get following information from pricing report. 1. It informs you about the customer specific price agreements that were made within a certain period 2. From pricing report you can know which condition records exist for freight charges 3. Which condition records exist for customers in a particular region or country You can create your own pricing reports with V/LA. Also V/LD is very useful. This can be customized. The sales personnel use it to 1. get information for price (discounts) that existed at previous period (Say June 200X) 2. Inform potential buyer about the current price (and discounts) 3. Review price and discounts. Though all the above T Codes and there are many More standard SAP Reports have very high utility, it is not widely used. Clients prefer customized reports when it comes to pricing reports - all Z programs and Transactions. These kind of reports are generally required by the Top Management for periodical review // Finance team for price control // Master data team for record purposes // Process audits by Internal/external agency // Of late, for every SOX audit done in the company...especially the change records for prices. Condition Index
Condition index is very useful for searching the condition record for a customer. It becomes easier and faster to search for condition records for a customer or material just like it become easier to search a topics in the book with help of index. You have to mark the "condition index" check box in the condition type and you have to activate the index in customization. You can set the discount for fast ten orders through "condition update". First, in your discount condition type(V/06) activate the "condition update" check box. Second, in the condition record, in additional data put "maximum number of orders" as 10. You may also create the condition record for discount through VK31. Now go to change(VK32), scroll to the right, you will find a column "N". This is maximum number of order field. Here you can put value 10 and save it. Now, system will give the discount to the first 10 orders. Where does the standard condition base value (Default one) is determined for a Condition type? First check the Material Master UOM Conversion - Additional Data - Units of Measure. Condition base value is a concept used in pricing procedure and actual term used is alternate condition base value. This is a formula assigned to a condition type in order to promote an alternate base value for the calculation of the value. If you have to calculate price of a material then you have to have a base value for it. For e value as base value which are derived on some formula. So you create a routine which will do the mathematical operations in the routine and derive you a value which is now used as the base value for calculating the condition value for a particular condition type.
As per my understanding there is Alternative Condition Base Value, It is a routine which is assigned to the condition type in the pricing procedure. Go to transaction V/08 here you select pricing procedure then go in to the control data of the pricing procedure here you can find Alter native Condition Base Value in the 14th column of the pricing procedure control data. What is the difference between: 1. Conditional base value 2. Conditional value. 3. Conditional amount 1. Conditional base value When a value is derived for a condition type, based on certain calculation this value is taken as base. 2. Conditional value. For the number of units ordered depending on the condition amount mentioned this value is derived. 3. Conditional amount This is nothing but the unit list price what you are mentioning for the line item. 1) What is the role of alternative calculation type, condition base value, requirement in pricing procedure? 2) Where do we define value for alternative condition base value and alternative calculation type so that system picks up different value, when the value for alternative condition base value and alternative calculation type is mention in pricing procedure? **Alternative Calculation Type:** This function allows you use a formula as an alternative in finding the value of the condition type, instead of standard condition technique. this can be used to calculate complex tax structures.
Alternative condition base value The alternative condition base value is a formula assigned to a condition type in order to promote an alternative base value for the calculation of a value. Example An absolute header discount is, for example, distributed in the standard system according to the cumulative value of the items. If the system distributes the absolute header discount according to volume based on the Alternative formula for condition base value , a header discount of $30 results in the following discounts: Item Value Volume . 1 $1000 2 cbm 2 $500 4 cbm Stand. disc. Volume disc.(With Formula) $20 $10 $10 $20 Condition formula for alternative calculation type Alternative formula to the formula in the standard system that determines a condition. Requirement.
Rounding Off Condition Not Appearing In Sales Order
In sales order Diff condition type is not coming, when checked in analysis it says requirement 013 is not fulfilled, but in pricing procedure I've assigned the requirement as 013, alt.cal type-16, alt CBV-4.
Please refer to the following documentation for requirement 013: RE LV61A013 Title Rounding as per Table T001R Purpose This is an example of a pricing requirement. This requirement is met if an entry has been made in the 'Unit to be rounded up to' field in Table T001R. Table T001R stores the rounding rules for company code and currency combinations. This requirement can be assigned to the condition type in the pricing procedure that is used to calculate the difference when rounding. Using this requirement, the difference is only calculated when necessary. Example A company has the requirement to carry out rounding for certain company code and currency combinations. This information is stored in Table T001R. In the document pricing procedure, the user has configured the SAP delivered condition type DIFF to calculate the difference when rounding occurs. The user also assigns pricing requirement '13' to the condition type DIFF in the pricing procedure so that the condition is only calculated when a corresponding entry has been maintained in the table T001R. Please check the customizing table T001R. or try this go to IMG path --> SAP Netweaver --> General Settings --> Currencies --> Define rounding rules for currencies. Here maintain the rounding unit which will be stored in Table T001R. then in the t-code ob90 you can maintain that. Go to v/08 maintain in condition base value 16 routine. Purpose This is an example of a condition value formula. This type of formula can be used to influence the value shown for the condition in pricing. A condition value formula is assigned to a condition type or value line in the pricing procedure.
Formula '16' was delivered along with condition type DIFF to support the rounding unit rules that can be defined in T001R for company code / currency combinations. Condition type DIFF was delivered to perform the rounding at the end of the pricing procedure with the total value. Using formula '16', the system computes the rounded value and assigns the difference to the condition type DIFF. In-17 c.base value Round according to T001R Purpose This is an example of a condition value formula. This type of formula can be used to influence the value shown for the condition in pricing. A condition value formula is assigned to a condition type or value line in the pricing procedure. Formula '17' was delivered so that a condition value could be rounded off according to the rounding unit rules (e.g. plus 5 or 10 or 100 units) that can be defined in T001R for company code / currency combinations. When formula '17' is assigned to a condition type, the condition value will always be rounded using T001R.
Where I can do setting of rounding profile for a new created condition type? 1) Create Rounding rule ( Unit of measure rounding rules ) Path : Materials --> SPRO Quantity Optimizing and Allowed --> Order Optimizing --> Purchasing --> Management Unit of Measure Rounding Rules --> Logistics Units of Measure Here give new rounding rule and % rounding up and down values 2) Create Unit of measure groups Path : Order Optimizing --> Purchasing --> Materials Management --> SPRO Unit of Measure --> Quantity Optimizing and Allowed Logistics Units of Measure Groups Create new group for YD and ROL 3) Dynamic rounding profile
Path : Order Optimizing --> Purchasing --> Materials Management --> SPRO Maintain Rounding --> Quantity Optimizing and Allowed Logistics Units of Measure Profile Here give Rounding profile name and plant and click on Dynamic to create new profile In next screen give desc. For rounding profile, rounding off method as 2, and rounding rule which you have created. Assign created Rounding profile in info record also UOM group Maintain minimum order qty as 1 Rol and Order unit as ROL in Info record In material master maintain conversion as 1 Rol = 3500 yards
How To Create Field in KOMP, KOMG
New Fields in Pricing To use a field in pricing, one creates a condition table. This condition table is created using the allowed fields from the field catalog. Should the fields one requires not be included in the list of allowed fields, one can add the fields from the list of available fields. However, one may find that a new field may not be in the list of available fields. For this reason, one must create new fields for pricing. The document and item data in SD is stored in data tables, such as VBAK and VBAP (for the order transaction). Many of the fields from these tables are available in the field catalog. The field catalog is a structure (KOMG) that consists of two tables (KOMK and KOMP). These tables contain the header and item data for pricing respectively. They are called KOM ³x´ because they are communications structures used to communicate the transaction data with the pricing procedure. Table KOMG contains the fields of tables KOMK and KOMP. If you require a field that is not in KOMG, it means that it is not in KOMK or KOMP. This means that the field you require cannot be used in pricing because there is no communication of this field from the transaction to the pricing procedure via the communication structures. To use a field not defined in the field catalog, you need to add this field to the KOMK or KOMP structures, and then write the ABAP code to transfer the data in the field from the transaction tables to the communication structure. Follow these steps:
1. Create the field in the KOMK (header data) and KOMP (item data) tables using the standard includes provided for this requirement. 2. Write the code in the user exit to read the transaction data and transfer it to the KOM ³x´ structures. Menu Path The menu path here is IMG, Sales and distribution, System modification, Create new fields (using the condition technique), New fields for pricing. Adding the Field to KOMK and KOMP This process requires some knowledge of the ABAP dictionary and how to use the ABAP dictionary to create and change fields and tables. You may have to use an ABAP skill to assist you. If the field is from the header table (for example, the order table VBAK), you¶ll need to add it to the include table KOMKAZ in table KOMK. If the field is from the item table (for example, the order item table VBAP), you¶ll need to add it to the include table KOMPAZ in table KOMP. Let¶s say you need to use the ³base material´ to define a price and the base material is not in the pricing field catalog. The base material is a field on the material master basic data screen and is defined as MARA-WRKST. Since this relates to the material, it is at the item level, so you would add the field to the KOMPAZ include table. Note When you add a field to these tables, it must start with ³ZZ.´ Therefore, the field you add would be ZZWRKST. In ABAP, when you add the field, use the same domain as in the field in the original table MARAWRKST. After adding the field, generate the structure KOMP. This field is not available in the field catalog and can be used in condition tables. Writing the ABAP Code The field in the communications structure will be blank unless the ABAP code transfers the data from the material master to the field KOMPZZWRKST. Pricing occurs in the order and in the invoice, so you need to put this code in both places. For the order transaction, write the ABAP code in user exit USEREXIT_PRICING_PREPARE_TKOMP in include program MV45AFZZ. For the billing transaction, write the ABAP code in user exit USEREXIT_PRICING_PREPARE_TKOMP in RV60AFZZ.
Note : The TKOMP is for the item level. If you are writing the code for a field at the header level, you would use the user exits that end with TKOMK. The ABAP code would select the Base material field from the material master table using the material from table VBAP/VBRP. It would then transfer this field to the structure TKOMP from MOVE MARAWRKST to TKOMP-ZZWRKST..
Default Start Variant for VF04
There
Condition Exclusion which will be determined in the billing document
The system can exclude conditions so that they are not taken into account during pricing.
For example: create a condition exclusion procedure which will be determined in the billing document. Assign the procedure to the pricing schema, and maintain copy control so that pricing is not copied from Sales Order. To achieve this, copy the standard pricing to a ZXXXX Pricing. Define new document pricing procedure in SM30 - V_TVKV for billing. Assign new document pricing procedures to billing types in SM30 - V_TVFK_PR Define the Condition Exclusion Groups in OV31. Assign the Condition type for the Condition Exclusion Groups in OV32. Assign the Billing Pricing Procedure in VOK8 for the Condition Exclusion Groups. When billing document is being created just enter manually your new price and the pricing program logic will include only the higher price one, excluding the rest that are lower price. Related Topics: Create/Modify Billing Document Type Steps for creating new or changing existing Billing Doc Type Get help for your SAP SD problems Do you have a SAP SD Question? SAP SD Books SAP Sales and Distribution, Certification, Interview Questions Reference Books
SAP Sales and Distribution Tips SAP SD Discussion Forum and Sales/Distribution Tips
Steps for creating a new or changing an existing Billing Document Types
Create/Change your Billing types configuration in VOFA. Some of the IMG stuff are :1) To block automatic transfer of the billing document to accounting, mark the field. Indicates whether the system blocks automatic transfer of the billing document to accounting. During document processing, you can manually transfer blocked billing documents to accounting by selecting: Billing -> Change -> Release accounting 2) Account determination procedure 3) Output determination procedure etc. ... After customizing, use transaction VCHECKVOFA to check your configuration :1) Proforma billing types: If it is a proforma billing type, (VBTYP = U), the field must be blank and the account determination procedure must be empty. 2) Cancellation billing document types: : A check is made to see if the cancellation billing document type has the right VBTYP. An F2 invoice, for example, (VBTYP 'M') can only be canceled with billing type S1 with VBTYP 'N' . A billing type with VBTYP '5' can only be canceled with the VBTYP '6' and vice versa. 3) Cancellation billing document type partner functions A check is made to see if the cancellation billing document type partner functions are empty or if those that correspond to the billing type used are empty. Next, make sure that you maintain the copy control for the Billing Types:
Sales documents in VTFA Target e.g. F1 - Invoice F1 - Invoice Source OR - Standard Sales Order ZOR - Your Sales Order
Billing documents in VTFF e.g. G2 - Debit Memo F1 - Invoice G2 - Debit Memo F2 - Invoice Deliveries in VTFL e.g. F1 - Invoice LF - Delivery F1 - Invoice ZOR - Your Delivery Usually for copy control, you let the rest of the settings remains as SAP defaults. You only assign the new Billing Document Types. After that use transaction VCHECKTVCPF to check your Copy control customizing. Related Topics: Integration between SD, MM, FI Link Between SAP SD, MM & FI Get help for your SAP SD problems Do you have a SAP SD Question? SAP SD Books SAP Sales and Distribution, Certification, Interview Questions Reference Books SAP Sales and Distribution Tips SAP SD Discussion Forum and Sales/Distribution Tips
Billing Block will not worked if you did not assign it
Define the possible block indicators in SM30 - V_TVFS and allocate them to the billing types concerned in SM30 - V_TVFSP.
Your Billing Block will not worked if you did not assigned it to the desired billing types. You can auto block by :1. sales document type in transaction VOV8, fields Billing Block, or 2. item categories in SM30 - V_TVAP, by filling the fields Billing Block.related milestone billing have different overview screens so that you can enter data relevant to your processing. For example, for milestone billing, you must be able to enter data to identify the individual milestones. IMG configuration requires :1. 2. 3. 4. 5. Maintain billing plan types for milestone billing in OVBO. Define date description in SM30 - V_TVTB. Maintain Date Category for Billing Plan Type IN OVBJ. Allocate date category in SM30 - V_TFPLA_TY. Maintain date proposal for Billing Plan Type in OVBM.
6. 7. 8.
Assign Billing Plan Type to Sales Documents Type in OVBP. Assign Billing Plan Type to Item Categories in OVBR.. 2. Item -> Schedule lines. Mark the schedule line and select Procurement details.
The following figure shows an example of milestone billing where only the Contract have been billed : Order Item Turbine 100,000
Billing Plan Billing date Status 01-10-94 01-03-95 01-04-95 01-05-95 Description Contract Assembly Maintenance Acceptance % 10 30 30 30 Value 10,000 30,000 30,000 30,000 Billing Block x x x Milestone x x x x Billing x
01-06-95
Final invoice ..
..
x
Network/Activities Milestone Assembly Maintenance Acceptance Estimate 01-03-95 01-04-95 01-05-95 Actual 01-03
Explain what is Billing Plan. Billing plan processing includes the following functions:
y y y y y y y y y y y
Automatic creation of billing plan dates Pricing Billing block Billing index Billing status Billing rule for milestone billing Fixed dates in milestone billing Document flow Creating with reference Exchange rate determination Automatic Creation of Billing Plan Dates
In Customizing for Sales, you control how the system automatically creates the schedule of dates in a billing plan. The system determines the schedule of individual dates based on general date information, such as the start and end dates. This general date information is copied either from contract header data or from proposals in the billing plan type. Pricing Sales document items are billed as each billing date in the plan becomes due. The system determines the amount to be billed either from the condition records that are applicable to the item or from the values that are explicitly entered in the billing plan
for a particular billing date. In milestone billing, for example, you can specify a percentage to be billed or an actual amount. Billing block A billing block can be set for each date in a billing plan. The block prevents processing for a particular billing date but does not necessarily affect any of the other dates in the plan. In milestone billing, the system automatically sets a billing block for each billing date. This block remains in effect until the project system reports back that the milestone in the corresponding network has been successfully completed. At this point the system removes the block. Billing index For every billing date in a plan, the system creates and updates a billing index. If a billing date is blocked for billing, the system copies this information into the index. Billing status The system assigns a billing status to each billing date in the plan. The status indicates to what extent the billing has been processed for that particular date. After billing has been carried out successfully, the billing status is automatically set to µC¶. This prevents a billed date from being billed again. Billing Rule for Milestone Billing For every date in the milestone billing plan, you can specify a billing rule. The rule determines how the billing amount for the particular date is calculated. For example, you can specify whether the billing amount is a percentage of the total amount or whether it is a fixed amount. In addition, you can specify that the amount to be billed is a final settlement that takes into account billing that has not yet been processed. For example, price changes may take place after billing dates in the plan have already been processed. The price differences can be taken into account during final settlement. Final settlement is not automatically proposed in the billing plan by the system; you must enter it manually during processing. Fixed dates in milestone billing
You can control for each date in a billing plan, whether the date is fixed or whether the system copies the date from the planned or actual milestone dates in a project. Document flow After a particular date in a billing plan is processed for billing, the system updates the document flow for the corresponding sales document item. The document flow for the sales document displays the following data: Creation date Billing date Billed value
y y y
Creating with reference When you define a billing plan type in Customizing for Sales, you can enter the number of an existing billing plan to serve as a reference during subsequent billing plan creation. During sales order processing for items that require billing plans, the system automatically proposes the reference plan and, if necessary, re-determines the billing dates (based on the current date rules) for inclusion in the new billing plan. Exchange rate determination In the billing plan with partial billing, you can store a certain exchange rate for each date. The amount billed is the amount determined after using this exchange rate to convert from the local currency into the document currency. An exchange rate can also be stored at item level for the sales document (field: Exchange rate for FI on the Billing tab page. This fixed rate is valid for all dates in the item billing plan for which no rate is specified in the billing plan. If an exchange rate is entered both for the date in the billing plan and at item level in the exchange rate field, then the system uses the rate specified for the date during billing. If no exchange rate is entered for the the date or at item level, then the system uses the exchange rate used for invoice creation and it is forwarded to FI. When using a header billing plan, all billing plans linked to this header billing plan are automatically updated. If, for example, you enter an exchange rate manually for the first date in the header billing plan, this is automatically copied to the corresponding dates for the item billing plans.
SAP Billing - Combine Billing for deliveries with different date
When using transaction VF04 or Billing (background), the date of the billing document (e.g. the current date) must be entered (In VF04 : settings, default data.) In VF06 or background: variant with parametrization) to avoid an unwanted split due to the billing date. This OSS notes is very helpful :11162 - Invoice split criteria in billing document 36832 - Invoice split in fields from the sales order
Billing Spilt by Item Category
Is it possible to split invoice Item category wise. I mean If in sales order there is TAN and TANN then the invoice should split,is it possible? Naina Yes, it is possible. Create a modification of copy control routine for billing and use VBAP-PSTYV as an additional split criteria there. Martishev Sabir Thank you for your reply. Can you please tell me the exact steps what should I add under that(additional split criteria). Naina In trx VTFA (if your billing is sales order based) choose your billing type and SO type, there select your item categories and there select the field VBRK/VBRP data. In that field you will see the currently used routine. With the help of your ABAP guy create a copy of that routine under a different number and add your lines of code. Let's say you use routine 001. FORM DATEN_KOPIEREN_001.
* Header data * VBRK-xxxxx = ............ * Item data * VBRP-xxxxx = ............ * Additional. ENDFORM. This is how it should look after modification:
* Header data * VBRK-xxxxx = ............ * Item data * VBRP-xxxxx = ............ * Additional split criteria DATA: BEGIN OF ZUK, MODUL(3) VALUE '001', VTWEG LIKE VBAK-VTWEG, SPART LIKE VBAK-SPART, PSTYV LIKE VBAP-PSTYV, <- New line END OF ZUK. ZUK-SPART = VBAK-SPART. ZUK-VTWEG = VBAK-VTWEG. ZUK-PSTYV = VBAP-PSTYV. <- New line VBRK-ZUKRI = ZUK. ENDFORM.
After this routine is created and activated place it as the default copy control routine instead of the old ones. Martishev Sabir
Maximum number of items in FI reached Message no. F5 727 FI documents have a 3-digit item counter that limits the number of items permitted per document. Procedure If the documents with an excessive number of items come from another application area (e.g. sales, logistics, order accounting), you can configure the system to the effect that these documents are summarized in FI. " How could this error be solved as none of your invoices are getting accounted in FI? To overcome this, the only way was to break the accounting invoices, 1 with 950 items and the other with the rest.
Prepaid process possible
-----Original Message----Subject: Prepaid process possible I am looking for information on how we could implement a prepaid process. By "prepaid
process" prepaid process could be a 100% required down payment) but it does not seem that it would work. From what I understood it looks like the billing plan is handled based upon the item category, which implies the processing is "material" specific not "customer" specific. What we do now: - We have defined a risk category "prepaid" which is assigned to our prepaid customer. This risk category automatically block the sales order for delivery. - We receive the sales orders and produce a Pro Forma invoice from it, and send it to customer - Once we receive the payment, we release the sales order for delivery and produce the invoices. - We post the payment we received earlier against this last invoice. As you see, this requires a lot of manual work and a lot of time is wasted to match all documents together. There most be a more efficient way to handle this, anybody have any hints? -----Reply Message----Subject: RE: Prepaid process possible Hi again! You are right! However, if you create a new item category for the prepaid scenario, you can select what item category (and process) to use at order entry. It is also possible to code a user exit so that only certain customers will get the prepaid process. This can be done also with item category groups (can be used to determine what default item category that
should appear). This would mean that you either have different materialnumbers for the different processes or use different distribution channels in the sales order. DC 10 could be the normal process and DC 20 the prepaid process. Then you need to create the sales views in material master for DC 20 for all materials that should be possible to run in the prepaid scenario, and enter the "prepaid item category group in the sales item category group field in material master. Here is a proposal of customizing activities to achieve this: 1. Create a new item category as a copy of the normal item category used for nonprepaid sales. (Change the billing in the item category to order related billing with no billing plan) 2. Create a new item category group "ZXXX" or something of your choice with the description "Prepaid" or something like that. 3. In item category assignment, add or check entries so that you have the order type used, and item category group defaulting the new item category. 4. Check copy control from sales document to billing document for the new item category. Also delivery copy control could be good to check. 5. Create a new distribution channel and assign it to the company structure (plant, sales org etc) 6. Extend your material(s) with views for the new distribution channel and enter the "ZXXX" item category group in the field for sales item category group (I think it is on sales 2 screen but I am not sure, can't access a system right now). Now you should be able to create a sales order with the new distribution channel where the new item category is defaulted. Check that the sales order is completed when both billing and goods issue for the delivery is posted. If not check the completion rule in the new item category. Good luck
-----End of Message-----
Restricting Number Of Items In Billing Doc billing document at item level under "Data VBRK/VBRP" and maintain routine 006 "individual invoice limited" or a similar routine that accesses the data maintained here. SAP SD Tips by : Amol
Document Not Relevant For Billing
How to resolve "Document not relevant for billing" error message? Check the detailed error log in VF01 screen. We may get more information on error. Then,. After delivery while creating billing document system showing error that no billing document is generated for material no 395. So how I can solve this issue. Check if Item Category is checked for Billing or not.. Note: Ensure that Copy The configuration differs from scenario to scenario & requirement of the client.
Procedure To Cancel Billing Documents
ERP SAP ==> SD SAP Tickets from users: After the following process: Sales Order --> Outbound Delivery (Goods issue) --> Billing, what happens if there is a cancellation? How to perform cancellation for this process: Billing --> Goods receipt --> Sales Order ? (Is this the correct reversal to perform in order for cancellation?) After performing the process Sales Order --> Outbound Delivery (Goods issue) --> Billing, the billing document will be passed on to the FI consultants. But if there is a
cancellation then, this billing doc. which will have a accounting document also that will also get cancelled. In the FI customer open line items. Cancellation of billing - VF11 Cancellation of delivery - VL09 Then go to VL02N and remove the picking qty and make it blank then Goto VA02 and cancel the order. You can delete the Sales Order if transaction have been done: In VA02 , just enter into the sales order goto menu path -> Files-> Cancel or delete option will be there will be there. After deletion / cancellation of that sales order that order doesn't exist in the database. For example , if your sales order number is 1055 and you have deleted or cancelled that sales order, then that sales order number doesn't exist in the database and you cant create another sales order with the same order number 1055. When you create another sales order the number will skip to the next one i.e, 1056. You can only reject the Sales order if there are existing transations: 1. First you need to cancel the billing document using T-code VF11, so it will reverse all the updated accounting entries. 2. Now you need to cancel the Post goods Issue using VL09, once it is reversed, the delete the delivery using VL02N. 3. Once the delivery is deleted, the sales order will be open. Now put a reason for rejection in the line item/s, and reject the order, the order will get closed. It is not advicable delete a sales order. Match Billing Cancel Document How to find out the link between the original and cancelled billing documents? Goto to tcode SE16 Table: VBRK
Field: VBRK-ZUONR - Assignment (this field link the original and cancelled billing documents) Cancel billing documents must be successfuly released to accounting. Usually it failed when user tried to cancelled current period with previous date.
Schedule VF04 For Individual Billing Run
SAP Functional ==> SD In SAP How to schedule billing to be run automatically? You can create individual Billing documents in VF04, with out any saving of each and every billing document. Select all the deliveries which you want to create billing documents, using Cntr Button, and click on individual billing. Then all the deliveries will go for billing individually in a single run. And you can also see all the billing documents numbers, which are created. No need to select single delivery each time. If you want to do a batch job for billing, proceed for the following process 1. goto VF04, in the selection screen Delivery document range, for which you want to create billing documents e.g., in SD Document field, give delivery 1 to 10. 2.Now Click on GOTO -> Variant -> Save as Variant, then it will take you to another screen, give the variant name, e.g., test, and save it. 3. goto SM36, this is used to do batch job, if you dont know any thing also, you can do the entire process, using JOB WIZARD, click on Job Wizard which is on the screen. 4. It will take you to different steps, just you need to give your variant name, (in job name field) (in the first screen) the continue for further steps, In the ABAP Progamme Name give SDBILLDL, (this is the programme used to create billing documents) continue to give the specified time which you want to run this batch job, like immediate, after an hour, or a specific day like so. 5. Continue further to complete the task, now you batch job will run at a specified time which you mentioned, if you mentioned as immediately, then once you comple this process, your vairant will run, and billing documents will be created.
6. Plese ensure that all the deliveries are perfect, meaning there is no billing block or any thing. You can check the status of your batch job using t. code SM37. Difference between the RSNAST00 and SDBILLDL program. RSNAST00 is a program which is related to output related activities. Using this program, we can schedule the creation of outputs (PDFs, email etc) in total for any document created in any of the applications. The details are read and stored in the database table NAST. The same program is customised for each applications using programs like SD70AV1A which are also used for the same purpose but only for sales orders. SDBILLDL is the program for Billing due list. This program finds out all the orders or deliveries or both which are due for billing and it will trigger the billing creation. It reads tables like VBAK, VBAP, VBUK, VBUP, LIKP, LIPS etc and the created billing documents are stored in tables VBRK, VBRP.
Explain The Concept of Resource Related Billing
Common Errors: AD01-155: Error during material determination for sales document item. Material Origin field was not checked in the Costing tab of the material master. IX-057: No cost management is provided for sales document (contract) item. This is usually because there is no requirements type assigned to the contract item (see procurement tab). No material appears in DMR/CMR. In the material master costing view, set the "Material Origin" checkbox (see OSS note 174382) No expenditure item found. Go back to the service order and check there are actual costs
Check your DIP Profile; specifically the sources section to ensure you are not filtering out any dynamic items. CO Configuration: KL03: Check activity type validity dates KA03: Check cost element validity dates KA03: For labour, KP26: Check are you using the correct version
Cancelled Billing Document Has No Accounting Document
Real SD Support Question: I have cancelled a billing document through vf11. That means the cancellation billing document did not generate accounting document. Where to checked?. As the rates picked in the sales order as default exchange rates maintained for the day; if the sales order is MTO and goods will dispatched after 2 months and within these 2 month the exchange rate got floated by a large amount and during the billing with VF01 t-code;DK
How To Do Configuration For Credit Management
Credit.
MRP block for Credit limit attained Customers LIKE VBUK-CMGST. SELECT SINGLE * INTO W_ZSDCRD FROM ZSD_CREDITBLCK WHERE KKBER = VBAK-KKBER AND CTLPC = VBAK-CTLPC. IF SY-SUBRC = 0 AND VBUK-CMGST CA 'B'. IMPORT VBUK-CMGST TO W_CMGST FROM MEMORY ID 'CREDIT'. IF W_CMGST = SPACE. MESSAGE I706(Z1). EXPORT VBUK-CMGST TO MEMORY ID 'CREDIT'. ENDIF. *} REPLACE *{ INSERT DEVK966908 1 *} INSERT * Read the subsequent function information for the message PERFORM FOFUN_TEXT_READ USING GL_FOFUN CHANGING FOFUN_TEXT.
MESSAGE ID 'V1' TYPE 'E' NUMBER '849' WITH FOFUN_TEXT RAISING ERROR. *{ INSERT DEVK966908 2 *} INSERT ENDIF. ENDFORM. Do you have a SAP SD Question?
Credit Mgmt Dynamic checking
---- From: Swami Subramanyan Program RVKRED08? Or manually execute function module SD_ORDER_CREDIT_RECHECK. Regards Swami -----Reply Message----Subject: Re: Credit Mgmt Dynamic checking From: Leslie Paolucci We check credit at the time of the delivery (at delivery creation and before picking) and use the blocked sales doc process/list to release them. This can be set up in customizing under risk management-> credit management.
-----End of Reply Message-----
Sales value field in not getting updated after creating the billing
-----Original Message----Subject: Sales value field in not getting updated after creating the billing we are on 4.6b. we are going for credit management but facing one problem. in fd32customer credit management change - the sales value feild in not getting updated after creating the billing. eg. when i create the order - the order value get updated in the sales value in fd32. after creating the delivery - that value remains same in the feild of sales value. but when i am going for billing (delivery related), the bill value is appearing in 'receivables' but the amount in 'sales value' is not getting reduced. because of this the credit exposure is increasing continuously. update group for corrosponding credit ctrl area is 12. also the item is mark for credit update. can anyone tell the missing link? thanking in advance -----Reply Message----Subject: RE: Sales value field in not getting updated after creating the billing Hi, You need to check couple of settings like: 1. Your customer should be assigned the credit control area. 2. In your Item Category Credit should be active. Regards, -----Reply Message----Subject: RE: Sales value field in not getting updated after creating the billing
customer is assign to concorn CCA and item category is mark for credit active -----Reply Message----Subject: RE: Sales value field in not getting updated after creating the billing Hi, Check the credit update group in the transaction OB45. The credit update group controls when the values of open sales orders, deliveries and billing documents are updated. It should be '000012'. Further also refer to the OSS note 18613. Have fun -----End of Message-----
Difference Between Simple and Automatic Credit Check Types credit facilities to the particular customer. STATIC CREDIT LIMIT DETERMINATION :Checking Group + Risk Catageory + Credit Control Area. A) Credit Checking Groups : Types of Checking Groups. 01) Sales 02) Deliveries 03) Goods Issue At all the above 3 levels orders can be blocked. B) Risk Catageory : Based on the risk catageories company decide how much credit has to give to the customer. HIGH RISK (0001) : LOW CREDIT LOW RISK (0002) : MORE CREDIT MEDIUM RISK(0003) : Average Credit Then assign the Sales Doc & Del Documents. Sales Doc.Type(OR) + credit Check(0) + Credit Group (01)
Credit Limit Check for Delivery Type : Del.Type (LF) + Del Credit Group (02) + Goods Issue Credit Group (03)
Set Up for Credit Card Payment Processing
Given below is the set up for credit card payment processing: Set Up Credit Control Areas: Define Credit Control Area Transaction: OB45 Tables: T014 Action: Define a credit control area and its associated currency. The Update Group should be µ00012¶. This entry is required so the sales order will calculate the value to authorize Assign Company Code to Credit Control Area Transaction: OB38 Tables: T001 Action: Assign a default credit control area for each company code Define Permitted Credit Control Area for a Company Code Transaction: Tables: T001CM Action: For each company code enter every credit control area that can be used Identify Credit Price Transaction: V/08 Tables: T683S Action: Towards the end of the pricing procedure, after all pricing and tax determination, create a subtotal line to store the value of the price plus any sales tax. Make the following entries: Sub to: ³A´ Reqt: ³2´ AltCTy: ³4´ Automatic Credit Checking Transaction: OVA8 Tables: T691F Action: Select each combination of credit control areas, risk categories and document
types for which credit checking should be bypassed. You need to mark the field ³no Credit Check´ with the valid number for sales documents. Set Up Payment Guarantees Define Forms of Payment Guarantee Transaction: OVFD Tables: T691K Action: R/3 is delivered with form ³02´ defined for payment cards. Other than the descriptor, the only other entry should be ³3´ in the column labeled ³PymtGuaCat´ Define Payment Guarantee Procedure Transaction: Tables: T691M/T691O Action: Define a procedure and a description. Forms of Payment Guarantee and make the following entries Sequential Number ³1´ Payment Guarantee Form ³02´ Routine Number ³0´ Routine Number can be used to validate payment card presence. Define Customer Payment Guarantee Flag Transaction: Tables: T691P Action: Define a flag to be stored in table. Create Customer Payment Guarantee = ³Payment Card Payment Cards (All Customers can use Payment Cards)´. Define Sales Document Payment Guarantee Flag Transaction: Tables: T691R Action: Define the flag that will be associated with sales document types that are relevant for payment cards Assign Sales Document Payment Guarantee Flag Transaction: Tables: TVAK Action: Assign the document flag type the sales documents types that are relevant for payment cards. Determine Payment Guarantee Procedure Transaction: OVFJ
Tables: T691U Action: Combine the Customer flag and the sales document flag to derive the payment guarantee procedure Payment Card Configuration Define Card Types Transaction: Tables: TVCIN Action: Create the different card types plus the routine that validates the card for length and prefix (etc«) Visa , Mastercard, American Express, and Discover Create the following entries for each payment card AMEX American Express ZCCARD_CHECK_AMEX Month DC Discover Card ZCCARD_CHECK_DC Month***** MC Mastercard ZCCARD_CHECK_MC Month VISA Visa ZCCARD_CHECK_VISA Month The Routines can be created based on the original routines delivered by SAP. *****SAP does not deliver a card check for Discover Card. We created our own routine. Define Card Categories Transaction: Tables: TVCTY Action: Define the card category to determine if a payment card is a credit card or a procurement card. Create the following two entries Cat Description One Card Additional Data CC Credit Cards No-check No-check PC Procurement Cards No-check Check Determine Card Categories Transaction: Tables: TVCTD Action: For each card category map the account number range to a card category. Multiple ranges are possible for each card category or a masking technique can be used. Get the card number ranges from user community. Below is just a sample of what I am aware are the different types of cards.
Visa Credit Expires in 7 days. 400000 405500 405505 405549 405555 415927 415929 424603 424606 427532 427534 428799 428900 471699 471700 499999 Visa Procurement Expires in 7 days. 405501 405504 405550 405554 415928 415928 424604 424605 427533 427533 428800 428899 Mastercard Credit Expires in 30 days 500000 540499 540600 554999 557000 599999 Mastercard Procurement Expires in 30 days 540500 540599 555000 556999 American Express Credit Expires in 30 days 340000 349999 370000 379999 Discover Card Credit Expires in 30 days 601100 601199 Set Sales Documents to accept Payment Card Information Transaction: Tables: TVAK Action: Review the listing of Sales Document types and enter ³03´ in the column labeled ³PT´ for each type which can accept a payment card Configuration for Authorization Request Maintain Authorization Requirements Transaction: OV9A Tables: TFRM Action: Define and activate the abap requirement that determines when an
authorization is sent. Note that the following tables are available to be used in the abap requirement (VBAK, VBAP, VBKD, VBUK, and VBUP). Define Checking Group Transaction: Tables: CCPGA Action: Define a checking group and enter the description. Then follow the below guidelines for the remaining fields to be filled. AuthReq Routine 901 is set here. PreAu If checked R/3 will request an authorization for a .01 and the authorization will be flagged as such. (Insight does not use pre-authorization check). A horizon This is the days in the future SAP will use to determine the value to authorize (Insight does not use auth horizon period). Valid You will get warning message if the payment card is expiring within 30 days of order entry date. Assign Checking Group to Sales Document Transaction: Tables: TVAK Action: Assign the checking group to the sales order types relevant for payment cards Define Authorization Validity Periods Transaction: Tables: TVCIN Action: For each card type enter the authorization validity period in days. AMEX American Express 30 DC Discover card 30 MC Master card 30 VISA Visa 7 Configuration for clearing houses Create new General Ledger Accounts Transaction: FS01 Tables: Action: Two General Ledger accounts need to be created for each payment card type. One for A/R reconciliation purposes and one for credit card clearing. Maintain Condition Types Transaction: OV85
Tables: T685 Action: Define a condition type for account determination and assign it to access sequence ³A001´ Define account determination procedure Transaction: OV86 Tables: T683 / T683S Action: Define procedure name and select the procedure for control. Enter the condition type defined in the previous step. Assign account determination procedure Transaction: Tables: Action: Determine which billing type we are using for payment card process. Authorization and Settlement Control Transaction: Tables: TCCAA Action: Define the general ledger accounts for reconciliation and clearing and assign the function modules for authorization and settlement along with the proper RFC destinations for each. Enter Merchant ID¶s Transaction: Tables: TCCM Action: Create the merchant id¶s that the company uses to process payment cards Assign merchant id¶s Transaction: Tables: TCCAA Action: Enter the merchant id¶s with each clearinghouse account SAP SD Tips by : Radhakrishna Srinivas
Dunning Process In Credit Management doesnt respond, we will send at least further reminder (dunning notice) may be 9 times (9 reminders) (Dunning level) and what intervels of time (dunning frequency) c) Still if the customer doesnt resopond for the reminders, you will file a law suit against the customer for recovering the Payments. d) Finally, after getting veridict, you may proceed for auction of his property or as per the order for Law. Now in SAP, the definition of Dunning procedure is a pre-defined procedure specifying how customers or vendors are dunned. For each procedure, the user defines - Number of dunning levels - Dunning frequency - Amount limits - Texts for the dunning notices In SAP, you will maintain the Dunning Procedure at customer master. Referring to this your SD Team / FI Team (user team) will effect Dunning PS: You might remembered the dunning procedure laid by Relaince Mobile, sometime back, sending street rowdies for recovering the bad debts from users. That is dunning. Remember Reliance, you will not forget dunning forever. Tips by : Kumar What do you mean by credit exposure?
They are the transactions with a customer that are relevant for credit limits on a specified date. The credit exposure is updated based on the update algorithm assigned to the credit control area. 000012 - updated at Sales Order 000015 - updated at Delivery 000018 - updated at Billing To look at only Receivables for a customer look in FD32. If you have bad data run the reorganization program through SE38. Check Note 425523 - Collection of consulting notes: Credit update and related. Surely you must run report RVKRED77 (Note 400311 - RVKRED77: Reorganization credit data, new documentation and related will help you). 1. How is credit exposure calculated (seen in FD32)? It¶s simple summation of Receivables + Special liabilities (like down payments, advance) + Sales value 2. If Update=000012 in CCAr then on creating Sales Order, the exposure increases by SO value. But if update=000015, then also on creating Sales Order, the exposure increases by SO value. Is this correct? I think in case of 000015 Open sales order values should not be considered. 3. What role exposure play in the credit management process. I mean does the system match the value of credit exposure with credit limit to find that it is exceeded or it does it differently? Credit exposure is in fact the main player. In credit management if the customer¶s credit limit is 10000 and credit exposure is 9900 then customer can only be able to buy now worth of 100 only. It¶s the credit exposure which should not crossed over the credit limit. For reporting purpose, where we can get customer credit exposure which showing in FD32.
Go to t.code F.31 for an overview of the credit exposure, and also you can use s_ALR_8701212218 to overview the credit exposure.
SAP SD CIN Configuration
By Shesagiri What is CIN? CIN Means Country India Version In Indian Taxing procedure, Excise Duty plays a vital role in manufacturing cenario¶ define which tax procedure and pricing condition types are used in calculating excise taxes using formula-based excise determination.. ± ±. Let¶s ³Foreign ± 0001 and instead add SAPLJ1I_MATERIAL_MASTER and in the screen no. 2205. 6. Save the setting. 7. Create a Material Master and check whether in Screen Foreign Trade ± Import, Excise related sub screen appears. Do you have a SAP SD Question?. Usage of price group in customer master Have a business requirement like this: The price group field is used for different discount rates for the customers. There are 2 types of customers wholesale and retail. I am not sure of the usage of price groups in customer master to use for the discount for the customers.
Answer: Generally the usage of customer group is to group the customers into One group so that whenever you want to give some additional discount to that customer group then you can give Example : Say you have 2 customers and 2 customers have 2 pricing groups. Customer A belongs to Wholesale Pricing grp and Customer B belongs to Retail Pricing grp. Maintain a condition record With the help of the Customer / Pricing grp key combination. Now for wholesale you give extra discount and for retail you give less discount. Now when you create the sales order with Customer A then he will be getting extra discount But if you create the sales order with Customer B then he will be getting normal discount Price group is a field where you can group certain customers under one umbrella. Suppose if you have 3 price groups say price group1 price group2 and price group3. Say there are 10 customers A to J. - You are assigning customers A to D in price group 1. - You are assigning customers E to G in price group 2. - You are assigning customers H to J in price group 3 in their respective CMRs. Price group can be added as filed in pricing condition table and you can maintain condition records for them: In VK11 the table with price group 1 is maintained discount of 5 % In VK11 the table with price group 2 is maintained discount of 6 % In VK11 the table with price group 3 is maintained discount of 7 % So in sales order the customers A to D will get 5 % discount and customers E to G will get 6 % discount and customers H to J will get 7 % discount.
How can I create a customer price group?
Please go through this IMG path then define the Customer pricing group. SPRO --> IMG --> Sales and Distribution --> Basic Functions ------> Pricing --> Maintain Price relevant master data fields ---> Define Pricing group for Customers. Transaction code --> OVSL
Customizing Customer Hierarchy in SD
How to configure and maintain the SD Customer Hierarchy? All the customizing is in SD/Master Data/Bussiness Partner/Customers/Customers hierarchy 1) Define hierarchy type: just put and ID and a name to the new hierarchy. 2) Set partner determination: if you want to user the hierarchy in price determination, then, in the orders, at the header level, you have to have a Partner Procedure with a partner function for each level. In the partner procedure, in each partner function you must indicate the source partner function. With this informacition, in the order, you obtain the bussiness partner for each partner function. 3) Assign acount groups: you indicate which accounts groups are allowed for being part or your hierarchy. 4) Assign sales areas: symple you indicate wich sales areas are allowed in your hierarchy. (Here you can customize common sales areas, just for not having to build de hierarchy in all the different sales areas). 5) Assigning hierarchy type for pricing: you indicate which classes of documentos uses hierarchy in pricing determination. It is possible to maintain so called customer hierarchies. This might be useful when for example you create a condition discount for a customer that is part of such a hierarchy structure. All subnodes in the hierarchy below that customer, will thus receive the same discount. Customer hierarchy setup, firstly decide the hierarchy type to be used. The standard is type A.
You can also assign a partner function to the customer so that the higher level customer in the hierarchy is copied into a sales order as a partner function - but you don't need that right? Next assign your customer account group to the hierarchy type. And enter the combinations that will be allowed for creating the hierarchy. You want to assign a ship-to to a payer. So enter the ship to account group and enter the payer account group as the higher level. You must also make an entry for permitted sales area assignments. So if you want to a hierarchy for customers in the same sales area then enter the sales area and enter the same one as the higher level sales area. All these settings can be found in the IMG. Under SD - master data - business partners - customers - customer hierarchy You use for example customer hierarchy when you have an company like Unilever and you agree both on a discount. Unilever does have different locations / businesses and you have to maintain the discount for all customers. If you use a customer hierarchy you can maintain the discount for the partner in the top of the hierarchy and in this way it will be valid for all customers in the hierarchy. SAP SD Tips by : Sam
Basic SD Questions On Product Hierarchies
What is the significance of product hierarchy? Alphanumeric character string for grouping materials by combining various characteristics. The product hierarchy is used for evaluation and pricing purposes. A product hierarchy is an alphanumeric character string which consists of 18 characters at the most. Product hierarchy thus define the product and its composition. To take an example, a product hierarchy could be 00010002000300040005. The first four characters 0001 could indicate that the product is a car. The next four characters could indicate 0002 the plant in which the car has been manufactured. The third set of characters could indicate the color of the car. The next set may determine its engine capacity and so on. Thus, the product hierarchy helps in defining the product composition.
Product hierarchy is defined in tcode v/76 according to levels. Then it is added as a user defined characteristic in tcode KES1. It is used for sales reporting functionality based on the product hierarchy. It is used for profitability analysis reporting. Different material codes can have same product hierarchy (assigned to material master in basic data view). When a sales cycle happen then after billing document a PA (profitability analysis) document is created in which product hierarchy is populated and used in CO-PA reporting. Explain the use of product hierarchy and the step by step procedure to define and use it? Product Hierarchy is used for Profitability analysis. You can have maximum of three level in SAP for a product. You have to give the product hierarchy in Material master Sales- Sales Org -2 view. You can define the product hierarchy in IMG settings from the following path Customizing is to be made in: IMG -- Logistics General --> Material Master --> Settings for Key Fields --> Data Relevant to Sales and Distribution --> Define Product Hierarchies --> Maintain Product Hierarchy Product hierarchies can be created using code OVSV. A product hierarchy is assigned to the material master record. The hierarchy is broken down into specific levels, each level containing its own characteristics. A product hierarchy is recorded by the sequence of digits within a hierarchy number. The hierarchy number can have a maximum of 18 digits with a maximum number of nine levels. Thus by assigning the hierarchy number to the material, one can determine a classification of the material. This hierarchy can be used in pricing with each level being used as field in the condition technique.
It¶s like if you are having category CAR. In that many cars come into picture. CAR>>MARUTI>>SX4, Swift, zen, alto. B>> 01 >>01 Then from above example B0101 is the hierarchy for SX4. So in that hierarchy many cars come, like variants and all the things. In this way you can take e.g. of wood products also. It shows the next level of the product. How many levels that product are having.
How To Configure Product Hierarchy: 15 25 38 We are required to implement product allocation functionality in SAP R/3 (Enterprise Version). We tried to do the elaborate steps as per the implementation guide but are not successful. Can you kindly help by giving the simple steps for implementation. Please see if the following helps: Configuration Overview; Allocation Specific Usage 1.Allocation Procedure (OV1Z) The product allocation procedure is the parent of the entire allocation process. All materials that are to be included in the allocation scheme are required to have an allocation procedure assigned to it in the material master. In addition, as of release 4.0, it is in the procedure that the method of allocation is defined. The user has the opportunity).
Sending a billing document by e-mail)
Program for Sales Order by Customer, Date, Sales Selection - Sales Organisation - Date - Customer this will be usefull when Selecting the Checkbox Standard Variants - Output - Sales Order Example Date SalesOrderNo Material Amount Currency 10.01.2007 8530 732 1000 INR
*&---------------------------------------------------------------------* *& Report ZCHE_SALES_ORDER *&--------Done by V.Chellavelu on 11.01.2007 --------------------------* REPORT zche_sales_order .
****************************Declarations******************************** TABLES: vbkd,vepvg.",vbak,vbap,vbpa,vakpa, vapma. DATA: BEGIN OF sal OCCURS 0, ch TYPE checkbox, vbeln LIKE vbak-vbeln, netwr LIKE vbak-netwr, matnr LIKE vbap-matnr, waerk LIKE vbak-waerk, dat LIKE vbak-erdat, END OF sal. DATA: newsal LIKE sal OCCURS
" sales document "Net Value of the SalesOrder "material no. "curr. "date. 0 WITH HEADER LINE.
DATA: amount LIKE vbak-netwr, date2(15),date3(8),date4(1), date5(2),date6(2). DATA: lin LIKE sy-curow VALUE 1,"Screens, vertical cursor position at "PAI available in SYST struc. checkbox TYPE c , dat LIKE vbak-erdat. *******************Selection**Screen**Design**************************** SELECTION-SCREEN BEGIN OF BLOCK blk1 WITH FRAME TITLE text-001. PARAMETERS: vkorg LIKE vepvg-vkorg, vtweg LIKE vepvg-vtweg, spart LIKE vepvg-spart. SELECT-OPTIONS date FOR vbkd-bstdk DEFAULT sy-datum TO sy-datum OBLIGATORY. SELECTION-SCREEN END OF BLOCK blk1. SELECTION-SCREEN BEGIN OF BLOCK blk2 WITH FRAME TITLE text-002.
SELECTION-SCREEN BEGIN OF LINE. SELECTION-SCREEN POSITION 10. PARAMETERS: chk1 AS CHECKBOX. SELECTION-SCREEN POSITION 20. PARAMETERS: kunnr1 LIKE vbpa-kunnr. SELECTION-SCREEN END OF LINE. SELECTION-SCREEN END OF BLOCK blk2. ********************First**Level**Operation***************************** IF chk1 <> 'X'. IF vkorg <> ''. PERFORM organisation. ELSE. PERFORM organisation_else. ENDIF. ELSE. IF vkorg <> ''. PERFORM cus_orga. ELSE. PERFORM cus_orga_else. ENDIF. ENDIF. * Displaying the contents which is selected from table by * -selection conditions SORT sal BY dat. LOOP AT sal. ON CHANGE OF sal-dat. * FORMAT HOTSPOT ON. IF sy-tabix = 1. WRITE: sy-vline, sal-ch AS CHECKBOX,sal-dat . CLEAR amount. ELSE. WRITE:sy-vline, amount,/ sy-vline, sal-ch AS CHECKBOX,sal-dat. CLEAR amount. ENDIF. ENDON. amount = amount + sal-netwr. AT LAST. WRITE:sy-vline, amount. ULINE. SUM. * FORMAT HOTSPOT OFF. FORMAT COLOR = 3. WRITE:/ ' Total Amount:', sal-netwr UNDER amount. ENDAT. ENDLOOP. **********************Interaction with report************************** SET PF-STATUS 'BANU'. " To create Application ToolBar for Display Button * To verify Double click on BANU
AT USER-COMMAND. " This will execute after pressing Display Button CASE sy-ucomm. WHEN 'DISP'. free newsal. DO. READ LINE lin FIELD VALUE sal-ch INTO checkbox. IF sy-subrc NE 0. EXIT. ENDIF. IF checkbox = 'X'. PERFORM datecon. PERFORM process. ENDIF. lin = lin + 1. ENDDO. PERFORM selection. ENDCASE. ************************ SUB ROUTINE Area ****************************** *This Process SubRoutine will assign the values from current * -InternalTable (sal) into other IT(newsal), by date which is * - selected by CheckBox FORM process. LOOP AT sal WHERE dat = dat. newsal-ch = 'X'. newsal-vbeln = sal-vbeln. newsal-netwr = sal-netwr. newsal-matnr = sal-matnr. newsal-waerk = sal-waerk. newsal-dat = sal-dat. APPEND newsal. ENDLOOP. ENDFORM. "process *&---------This will display the values for selected dates from new --* *---------------------internal Table (newsal)-------------------------* *& Form SELECTION *&--------------------------------------------------------------------* *---------------------------------------------------------------------* FORM selection. ULINE. FORMAT COLOR = 1. WRITE:sy-vline,'Date',AT 14 sy-vline, 'Order NO', AT 27 sy-vline, 'Order Material', AT 48 sy-vline,'Order Value(AMT) Currency '. FORMAT COLOR OFF. ULINE. LOOP AT newsal. ON CHANGE OF newsal-dat. IF sy-tabix <> 1. WRITE:/ sy-vline, AT 14 sy-vline,AT 27 sy-vline,AT 48 sy-vline. WRITE:/ sy-vline,newsal-dat,sy-vline,AT 27 sy-vline,AT 48 sy-vline. ELSE. WRITE: sy-vline,newsal-dat,sy-vline,AT 27 sy-vline,AT 48 sy-vline. ENDIF. ENDON. WRITE:/ sy-vline, AT 14 sy-vline,newsal-vbeln,sy-vline, newsal-matnr, sy-vline, newsal-netwr, newsal-waerk.
AT LAST. SUM. ULINE. FORMAT COLOR = 3. WRITE:/ sy-vline, AT 15 'Total Amount for selected month:', newsal-netwr UNDER newsal-netwr. FORMAT COLOR OFF. ULINE. ENDAT. ENDLOOP. lin = 1. FREE newsal. ENDFORM. "SELECTION * This Date convertion is must for pick the particular Date from the * -displayed line, and here we are reversing the Date like YYYY/MM/DD * -because to Check or assign the date we need to give in reverse order *&--------------------------------------------------------------------* *& Form DATECON *&--------------------------------------------------------------------* * text *---------------------------------------------------------------------* FORM datecon. date2 = sy-lisel(17). SHIFT date2 LEFT BY 4 PLACES. WHILE date2 <> ''. SHIFT date2 RIGHT. date4 = date2+11. IF date4 <> '.'. CONCATENATE date4 date3 INTO date3. ENDIF. ENDWHILE. date5 = date3(2). date6 = date3+2. date3 = date3+4. CONCATENATE date3 date6 date5 INTO date3. dat = date3. * SORT dat BY dat. * DELETE ADJACENT DUPLICATES FROM dat COMPARING dat. ENDFORM. "DATECON * Here we are doing different kinds of selections by the EndUser's needs *&---------When user selectiong an Sales Organisation-----------------* *& Form ORGANISATION *&--------------------------------------------------------------------* * text *---------------------------------------------------------------------* FORM organisation..
APPEND sal. ENDSELECT. ENDFORM.
"ORGANISATION
*&---------Without Sales Organisation i.e All Organisation------------* *& Form ORGANISATION_ELSE *&--------------------------------------------------------------------* * text *---------------------------------------------------------------------* FORM organisation. APPEND sal. ENDSELECT. ENDFORM.
"ORGANISATION_ELSE
*&------------When Selecting Customer by choosing CheckBox------------* *& Form CUS_ORGA *&--------------------------------------------------------------------* * text *---------------------------------------------------------------------* FORM cus_orga. AND p~kunnr = kunnr1. APPEND sal. ENDSELECT. ENDFORM.
"CUS_ORGA
*&------------Without Customer by without choosing CheckBox-----------* *& Form CUS_ORGA_ELSE *&--------------------------------------------------------------------* * text *---------------------------------------------------------------------* FORM cus_orga~kunnr = kunnr1. APPEND sal. ENDSELECT.
By Chellavelu .V - chella.velu@gmail.com
How To Maintain Output Types in SD
ER) lease follow the below path: IMG - Logistics Execution - Shipping - Deliveries - Define Reasons for Blocking in Shipping - Execute - Define Reasons for Blocking in Shipping Here select the delivery block that is blocking your order/delivery, and uncheck if the option Print is checked. Display View "Deliveries: Blocking Reasons/Criteria": Overview DB Delivery block descr Order Conf. 01 Credit limit 02 Political reasons 03 Bottleneck material 04 Export papers missng 05 Check free of ch.dlv 06 No printing 07 Quantity Change Print DDueList SpK SpW
08 Kanban Delivery Printing block field: Indicates whether the system automatically blocks output for sales documents that are blocked for delivery. Example : In the case of sales orders that are blocked for delivery because of credit reasons, you may want to block the printing of order confirmations. Note: The particular output that is affected by a delivery block is determined in output control. PS: If the document is exceeds by the credit limit output type will not determine and as well as we should not give the output type in sales order. We have to assign the routine 2 to sales order output types and 3 routine to delivery output types to restrict from output if the docuement exceeds by credit limit.
SAP Sales Order Processing Overview
SAP Sales Order Processing system allowed you to manage customer orders in a logical ways. This paper will introduce to you the various features of the Sales Order Processing under the SD modules. Table of Contents
Purpose of SAP Sales Order Processing System Integrated Function Modules Business Flow of the SAP Sales Process SAP Sales Organisation Key Fields In Sales Order Transaction Codes In Sales Order Processing Important Master Record Material Master Record Sales Views In Material Master Customer Master Record Sales Unit of Measure Delivery Plant Pricing Master Record
Sales Document Flow Goods Movement In SD Stock Overview Availability Checks For Customer Order Credit Management In SD Sales Information System Report Sample : List of Sales Orders Change Logging In SD Similar Interface Output Determination Delivery To Customer Customer Invoice Automatic Accounting Posting Appendix A: SAP User Menu Appendix B: Short Cut Keys In SAP Menu
SAP Tickets - What Is That?
Handling tickets is called Issue Tracking system. The errors or bugs forwarded by the end user to the support team are prioritized under three seviority High, Medium and Low. Each and every seviority as got its time limits before that we have to fix the error. The main job of the supporting consultant is to provide assistance on line to the customer or the organisation where SAP is already implemented for which the person should be very strong in the subject and the process which are implemented in SAP at the client side to understand,to analyse,to actuate and to give the right solution in right time.This is the job of the support consultant. The issues or the tickets(problems) which are arised is taken care of on priority basis by the support team consultants..
What Is Maintaining SLA - Service Level Agreement
What is maintaining *--.,).
What Are Functional Specification in SAP?
To. The Functional Specification describes the features of the desired functinality.. It describes the product's features as seen by the stake holders,and contains the technical information and the data needed for the design and developement. The Functional Specification defines what the functionality will be of a particulat detchnical developement process. b) Clearly and unambiguously provides all the information necessary for the technical consultants to develop the objects. At the consultant level the functional spects are preapred by functinal consultants on any functionality for the purpose of getting the same functinality designed by the technical pepole * This documents are preapared in Vanilla SAP Standards -- Things differ from one implementation to another, and it always depends on the type of business which is opting for SAP. Tips by: Madhuuri, Fahad
Role of a mySAP Functional Consultant
What - Methodlogy, some companies follow typical SDLC steps, ASAP stands for Accerlated) Tips by: Teresa Pittari, Gregrobinette What. During the SAP Implementation Project, what is the Role of Core Team Membere & Consultants? The main responsibility of the core team member will to impart knowledge about the companies processes to the SAP Consultants. The consultants will be providing the core team members with templets, that will describe the format of the AS-IS documentation wherein the core team members will write the different processes of the company into these documents and submit it to the SAP Consultants. The SAP consultants will then start mapping this into the system and provide the best possible solution that can be incorporated using the TO-BE documents. The main aim is to map the companies processes into the system. The SAP consultants will then train the core team members for how to use the SAP system.
What Are SAP End User Manualusers.
The top ten IT skills to have for the next few years
This.
Mini SAP System Requirement and How to Get it
Mini SAP System Requirement The system Requirements are : General Requirements Operating System: Windows 2000 (Service Pack2 or higher); Windows XP (Home or Professional); Windows NT Linux Internet Explorer 5.01 or higher At least 192 MB RAM (recommended to have 256 MB of RAM) At least 512 MB paging file At least 3.2 GB disk space (recommended to have 6 GB hard disk drive space) (120 MB DB software, 2.9 GB SAP data, 100 MB SAP GUI + temporary free space for the installation) The file C:\WINNT\system32\drivers\etc\services (Windows 2000) or C:\Windows\system\32\drivers\etc\services (Windows XP) must not include an entry for port 3600. A possible entry can be excluded by using the symbol '#'. No SAPDB must be installed on your PC. The hostname of the PC must not be longer than 13 characters. The Network must be configured for installation and the MS Loopback Adapter must be configured when you start the system without a network connection! Special Requirements for Installations on Windows XP In the file C:\Windows\system\32\drivers\etc\hosts the current IP address and the host name must be defined as <IP address><Host name> Open the network connectivity definition with start->control panel->network connections for defining the network connection. Select ->extended-> allow other users in network. Activate new configurations. Select remote desktop within extended configuration menu. *********
What is MiniSAP? How to get Mini SAP? In order to get the free Mini SAP, you need to buy the following book where in you will get two CD's of SAP WAS (Web Application Server) which can be installed in your system and practice ABAP programming etc... ******* You can get your MiniSAP with the book :ABAP Objects: An introduction to Programming SAP Applications by Horst Keller, Sascha Kruger. SAP Press. ISBN 0-201-75080-5. It comes with 2 cds (Mini Basis SAP kernel + database). It also includes the SQL server. or ABAP Objects Reference Book H. Keller, J. Jacobitz The first complete language reference book for ABAP! This book represents the first complete and systematic language reference book Expressions, Shared Objects, class-based exception handling, assertions, Web Dynpro for ABAP, Object Services, dynamic programming, interface technologies (RFC, ICF, XML), and test tools, among others. Procedural techniques are also covered where necessary. Highlights:
y y y y y y y y y
SAP NetWeaver Application Server ABAP Development basics: ABAP Workbench, Object Navigator, Class Builder, etc. Basic elements of ABAP Objects Classic modularisation and program execution Avoiding erros and error handling GUI programming: dynpros, lists, selection screens, controls and Web Dynpro Persistent data: DB access, Object Services, file interface, data clusters Dynamic programming: field symbols, RTTS, dynamic tokens and procedure calls Data und communication interfaces: RFC, ICF, web services, XML
The book also includes two CDs carrying a fully operational SAP Basis System, and containing all the example programs from the book. ************** Alternatively, if you are a customer of SAP and have an OSS user-id, then you can also buy the Minisap software directly from the Sap service market. Search for "MiniSAP Basis 4.6D November 2000 (English)" (Item nbr. : 50043446). Minisap contains only SAP BASIS where you can do your ABAP. It will costs you 25 EURO.
What Is User Specific Parameter
Explain what is user specific parameter. User parameter: You can fill fields on screens with default values from SAP memory using parameter IDs. For example, a user only has authorization for company code 0001. By entering the value '0001' in field COCD in the Parameter register in this user¶s master record (SU01), the system automatically fills the field Company code with the value µ001¶ on all screens he or she calls. If this company code is not predetermined using a parameter ID in the user master record, the system automatically adopts the first value entered by the user at the beginning of the transaction for the rest of the current terminal session. However, this value has to be re-entered the next time the user logs on to the system Fields on screens are only ever automatically filled with the value saved under the parameter ID of a data element if the Set Parameter/Get Parameter attributes for the corresponding fields have been explicitly set in the Screen Painter. Choose Tools -> Administration, then User maintenance -> Users. Enter the IDs you want in the Parameter register during user maintenance How to create a new user parameter id , so that i can assign the same in SU01? You can do in SE80, choose Other Objects, Enter name and Create. If you want create paramenter id 'TEST' means:
STEP 1: First add value 'TEST' in TPARA Table. STEP 2 : Assign value to paremeter id DATA : LV_TEST TYPE CHAR10. LV_TEST = 'TEST'. SET PARAMETER ID 'TEST' FIELD LV_TEST. To create a Parameter Id for a Data Element. In se11 --> Data element name --> Futher Charactersitics --> Parameter Id --> Type name example ZPARA --> Dbl click in it and create. What are thses User parameter EFB & EVO? What is the full form of this? When it is used? Parameter IDs are used to ease the daily activities of a user. For example: If the user is responsible with one Purchasing grp/Pur Org/Plant then they adds WERKS/EKGRP parameter here, to have this Plant/Pur Group id filled when they calls the related transaction. Parameter IDs are usually only used to memorize certain user-specific settings. They can be included in the T code SU3 in the parameter tab. EFB - This parameter id will define certain Purchasing authorizations For one or more users. Here you can display certain user can display the conditions. EVO - You assign default values that you have maintained in the Customizing to a particualt user by entering the key of the default value in the user master record under the parameter ID "EVO".
Successfully Implementing SAP
Implementing. *-- Satynarayana. *-- V. Sridhar What is roll out of SAP Project? As per dictionary, Rollout means ³Inauguration.
Check for Partner on Equipment Master (IE01)
We have a requirement to check that sold-to partner function is mandatory during equipment creation (IE01). This can be done via configuration. However, the
requirement is also to allow users to delete this partner using IE02. Hence they only want the partner to be mandatory during IE01 and not IE02. I believe only way to do this is using a user-exit. We know of a user-exit IEQM0003 that is allows us to put in logic before equipment is saved. However, this user-exit doesn't have parameters to partner data. Is there any other user-exit that can be used? Answer: You could check to see if you could read the partner from the memory within the FM. However you could potentially accomplish the same using the following steps without programming. You could use the View profile settings in configuration and transaction variant functionality (SHD0) to accomplish this. -> As a first step Make sure to add the Partner view as a sub screen to the very first screen using View profile settings for the equipment category in SPRO. (This will force the partner field to be available directly on the initial screen when a piece of equipment is created). ---> Now create a Transaction variant for the standard transaction IE01 and here select the sold to partner custom type and leave the value field blank. - Now on the configuration for the Transaction set the Partner type to be imported with value "SP" and mark the content field to be mandatory. -- Leave all other settings to default and save and exit. ---> Now set this Transaction variant as a standard variant for this transaction. This should do the trick. The user will be forced to enter the sold to party on the screen. - However for change transaction (IE02) the user can delete this partner type without any issues.
Explanation Of Purchasing Info Record
Usage: Purchasing Info Record is a source of information for the procurement of certain material from certain vendor. It includes : 1. Pricing conditions that you can store for relevant Purchasing Organization or Plant. 2. Reminders 3. Number of last Purchase Order 4. Planned Delivery Time ( Lead time required by the vendor to deliver the material ) 5. Tolerance Limits for Over Deliveries & Under deliveries 6. Availability Period during which the Vendor can supply the material. Creation: We can create info record by: 1. Manual 2. Automatic If you create info record manually and then create PO manually, the price will be picked from the info record. If info record does not exists and you create PO manually with info record update indicator set, the info record will be created automatically without price updation, and the last PO number will be updated. Again if you create a PO for the same material the Price will be picked from the last PO which is updated in info record. For creation auto PO , you have to create info record manually first and then maintain the source list. Then only you will be able to create auto PO. You cannot create auto PO without info record, History: If info update indicator is ticked in PO, it will update the order price history in inforecord ( Env.tab) & not the price in condition record. It will update 'Order price history'----path is 'environment' and 'order price history' in tcode ME13
Logs: Is there a way where you can get to know who create a Purchase Info record? In transaction ME13, please go to Extras -> Administrative Data. You will see who created on what date. Sending: What ME18 (send purchase info record ) does?
Network Scheduling In Project System
How does the network scheduling happens in PS? Networks and network activities are more suitable for planning resources and scheduling than WBS's and WBS elements. For Networks, Scheduling calculates the earliest and latest dates for the execution of the activities, and the capacity requirements and floats Scheduling types include: 1. Forward scheduling: scheduling starting from the start date. 2. Backward scheduling: scheduling starting from the finish date. 3. Scheduling to current date: scheduling starting from the current date. 4. "Today" scheduling: a scheduling type for rescheduling an order if the start date is in the past. You need to define scheduling parameters in Customizing. Check img path: SPRO -> Project System -> Dates -> Scheduling -> Specify parameters for Network Scheduling Secondly, WBS can be assigned as Account Assignment in Sales order. Check Account assignment tab of sales order. Thirdly about procurement,
When procuring services externally (outsourcing), you can create services or externally-processed activities. Example: You commission a freelance engineer to design and build a machine. When you create such an activity, a purchase requisition is also created, and processed further in Purchasing. You can access data from Purchasing for external processing (a purchasing info record, for example, which contains prices and delivery times for external processing). Externally-processed activities give rise to planned costs equivalent to the prices from the purchasing info record or the price in the activity. The valuation variant for the network costing variant determines which price is used for the valuation. When the purchase requisition is activated and converted to a purchase order, the activity is also shown as a purchase requisition commitment or purchase order commitment. The account assignment category in the purchase order determines whether the goods/invoice receipt is valued - that is, whether it gives rise to actual costs. If the goods receipt is valuated, actual costs are posted to the activity and the commitment is reduced by the amount of the purchase order. This means that the invoice receipt may correct the actual costs. Service activities are maintained for the purchase of services. Creating such an activity establishes the link to MM Services (MM-SRV). Unlike externally-processed activities, service activities contain a service specification containing planned activities and value limits for unplanned activities. This service specification is copied to the purchase order where Purchasing can then modify it. Service activities also give rise to planned costs or purchase requisition/order commitments. Instead of goods receipts, services are later entered and accepted. | https://www.scribd.com/doc/47259273/SAP-Certification-Exam-Full-Material | CC-MAIN-2017-39 | refinedweb | 37,260 | 52.8 |
.
Run Lambda functions on the AWS IoT Greengrass core
AWS IoT Greengrass provides a containerized Lambda runtime environment for user-defined code that you author in AWS Lambda. Lambda functions that are deployed to an AWS IoT Greengrass core run in the core's local Lambda runtime. Local Lambda functions can be triggered by local events, messages from the cloud, and other sources, which brings local compute functionality to connected devices. For example, you can use Greengrass Lambda functions to filter device data before transmitting the data to the cloud.
To deploy a Lambda function to a core, you add the function to a Greengrass group (by referencing the existing Lambda function), configure group-specific settings for the function, and then deploy the group. If the function accesses AWS services, you also must add any required permissions to the Greengrass group role.
You can configure parameters that determine how the Lambda functions run, including permissions, isolation, memory limits, and more. For more information, see Controlling execution of Greengrass Lambda functions by using group-specific configuration.
These settings also make it possible to run AWS IoT Greengrass in a Docker container. For more information, see Running AWS IoT Greengrass in a Docker container.
The following table lists supported AWS Lambda runtimes and the versions of AWS IoT Greengrass Core software that they can run on.
* You can run Lambda functions that use these runtimes on supported versions of AWS IoT Greengrass, but you can't create them in AWS Lambda. For more information, see Runtime support policy in the AWS Lambda Developer Guide.
SDKs for Greengrass Lambda functions
AWS provides three SDKs that can be used by Greengrass Lambda functions running on an AWS IoT Greengrass core. These SDKs are contained in different packages, so functions can use them simultaneously. To use an SDK in a Greengrass Lambda function, include it in the Lambda function deployment package that you upload to AWS Lambda.
- AWS IoT Greengrass Core SDK
Enables local Lambda functions to interact with the core to:
Exchange MQTT messages with AWS IoT Core.
Exchange MQTT messages with connectors, devices, and other Lambda functions in the Greengrass group.
Interact with the local shadow service.
Invoke other local Lambda functions.
Access secret resources.
Interact with stream manager.
AWS IoT Greengrass provides the AWS IoT Greengrass Core SDK in the following languages and platforms on GitHub.
To include the AWS IoT Greengrass Core SDK dependency in the Lambda function deployment package:
Download the language or platform of the AWS IoT Greengrass Core SDK package that matches the runtime of your Lambda function.
Unzip the downloaded package to get the SDK. The SDK is the
greengrasssdkfolder.
Include
greengrasssdkin the Lambda function deployment package that contains your function code. This is the package you upload to AWS Lambda when you create the Lambda function.
Only the following AWS IoT Greengrass Core SDKs can be used for stream manager operations:
Java SDK (v1.4.0 or later)
Python SDK (v1.5.0 or later)
Node.js SDK (v1.6.0 or later)
To use the AWS IoT Greengrass Core SDK for Python to interact with stream manager, you must install Python 3.7 or later. You must also install dependencies to include in your Python Lambda function deployment packages:
Navigate to the SDK directory that contains the
requirements.txtfile. This file lists the dependencies.
Install the SDK dependencies. For example, run the following
pipcommand to install them in the current directory:
pip install --target . -r requirements.txt
Install the AWS IoT Greengrass Core SDK for Python on the core device
If you're running Python Lambda functions, you can also use
pip
to install the AWS IoT Greengrass Core SDK for Python on the core device. Then you can deploy your functions without including the SDK in the Lambda function deployment package. For more information, see greengrasssdk .
This support is intended for cores with size constraints. We recommend that you include the SDK in your Lambda function deployment packages when possible.
- AWS IoT Greengrass Machine Learning SDK
Enables local Lambda functions to consume machine learning (ML) models that are deployed to the Greengrass core as ML resources. Lambda functions can use the SDK to invoke and interact with a local inference service that's deployed to the core as a connector. Lambda functions and ML connectors can also use the SDK to send data to the ML Feedback connector for uploading and publishing. For more information, including code examples that use the SDK, see ML Image Classification connector, ML Object Detection connector, and ML Feedback connector.
The following table lists supported languages or platforms for SDK versions and the versions of AWS IoT Greengrass Core software they can run on.
For download information, see AWS IoT Greengrass ML SDK software.
- AWS SDKs
Enables local Lambda functions to make direct calls to AWS services, such as Amazon S3, DynamoDB, AWS IoT, and AWS IoT Greengrass. To use an AWS SDK in a Greengrass Lambda function, you must include it in your deployment package. When you use the AWS SDK in the same package as the AWS IoT Greengrass Core SDK, make sure that your Lambda functions use the correct namespaces. Greengrass Lambda functions can't communicate with cloud services when the core is offline.
Download the AWS SDKs from the Getting Started Resource Center
.
For more information about creating a deployment package, see Create and package a Lambda function in the Getting Started tutorial or Creating a deployment package in the AWS Lambda Developer Guide.
Migrating cloud-based Lambda functions
The AWS IoT Greengrass Core SDK follows the AWS SDK programming model, which makes it easy to port Lambda functions that are developed for the cloud to Lambda functions that run on an AWS IoT Greengrass core.
For example, the following Python Lambda function uses the AWS SDK for Python (Boto3)
to publish a
message to the topic
some/topic in the cloud:
import boto3 iot_client = boto3.client('iot-data') response = iot_client.publish( topic='some/topic', qos=0, payload='Some payload'.encode() )
To port the function for an AWS IoT Greengrass core, in the
import statement and
client initialization, change the
boto3 module name to
greengrasssdk, as shown in the following example:
import greengrasssdk iot_client = greengrasssdk.client('iot-data') iot_client.publish( topic='some/topic', qos=0, payload='Some payload'.encode() )
The AWS IoT Greengrass Core SDK supports sending MQTT messages with QoS = 0 only. For more information, see Message quality of service.
The similarity between programming models also makes it possible for you to develop your Lambda functions in the cloud and then migrate them to AWS IoT Greengrass with minimal effort. Lambda executables don't run in the cloud, so you can't use the AWS SDK to develop them in the cloud before deployment.
Reference Lambda functions by alias or version
Greengrass groups can reference a Lambda function by alias (recommended) or by version. Using an alias makes it easier to manage code updates because you don't have to change your subscription table or group definition when the function code is updated. Instead, you just point the alias to the new function version. Aliases resolve to version numbers during group deployment. When you use aliases, the resolved version is updated to the version that the alias is pointing to at the time of deployment.
AWS IoT Greengrass doesn't support Lambda aliases for $LATEST versions. $LATEST versions aren't bound to immutable, published function versions and can be changed at any time, which is counter to the AWS IoT Greengrass principle of version immutability.
A common practice for keeping your Greengrass Lambda functions updated with code changes
is to
use an alias named
PRODUCTION in your Greengrass group and
subscriptions. As you promote new versions of your Lambda function into production,
point
the alias to the latest stable version and then redeploy the group. You can also use
this method to roll back to a previous version.
Communication flows for Greengrass Lambda functions
Greengrass Lambda functions support several methods of communicating with other members of the AWS IoT Greengrass group, local services, and cloud services (including AWS services).
Communication using MQTT messages
Lambda functions can send and receive MQTT messages using a publish-subscribe pattern that's controlled by subscriptions.
This communication flow allows Lambda functions to exchange messages with the following entities:
Devices in the group.
Connectors in the group.
Other Lambda functions in the group.
AWS IoT.
Local Device Shadow service.
A subscription defines a message source, a message target, and a topic (or subject) that's used to route messages from the source to the target. Messages that are published to a Lambda function are passed to the function's registered handler. Subscriptions enable more security and provide predictable interactions. For more information, see Managed subscriptions in the MQTT messaging workflow.
When the core is offline, Greengrass Lambda functions can exchange messages with devices, connectors, other functions, and local shadows, but messages to AWS IoT are queued. For more information, see MQTT message queue for cloud targets.
Other communication flows
To interact with local device and volume resources and machine learning models on a core device, Greengrass Lambda functions use platform-specific operating system interfaces. For example, you can use the
openmethod in the os
module in Python functions. To allow a function to access a resource, the function must be affiliated with the resource and granted
read-onlyor
read-writepermission. For more information, including AWS IoT Greengrass core version availability, see Access local resources with Lambda functions and connectors and Accessing machine learning resources from Lambda function code.
Note
If you run your Lambda function without containerization, you cannot use attached local device and volume resources and must access those resources directly.
Lambda functions can use the
Lambdaclient in the AWS IoT Greengrass Core SDK to invoke other Lambda functions in the Greengrass group.
Lambda functions can use the AWS SDK to communicate with AWS services. For more information, see AWS SDK.
Lambda functions can use third-party interfaces to communicate with external cloud services, similar to cloud-based Lambda functions.
Greengrass Lambda functions can't communicate with AWS or other cloud services when the core is offline.
Retrieve the input MQTT topic (or subject)
AWS IoT Greengrass uses subscriptions to control the exchange of MQTT messages between devices, Lambda functions, and connectors in a group, and with AWS IoT or the local shadow service. Subscriptions define a message source, message target, and an MQTT topic used to route messages. When the target is a Lambda function, the function's handler is invoked when the source publishes a message. For more information, see Communication using MQTT messages.
The following example shows how a Lambda
function can get the input topic from the
context
that's passed to the handler.
It does this by accessing the
subject key from the context hierarchy
(
context.client_context.custom['subject']). The example also parses the input JSON message and
then publishes the parsed topic and message.
In the AWS IoT Greengrass API, the topic of a subscription
is represented by the
subject property.
import greengrasssdk import logging client = greengrasssdk.client('iot-data') OUTPUT_TOPIC = 'test/topic_results' def get_input_topic(context): try: topic = context.client_context.custom['subject'] except Exception as e: logging.error('Topic could not be parsed. ' + repr(e)) return topic def get_input_message(event): try: message = event['test-key'] except Exception as e: logging.error('Message could not be parsed. ' + repr(e)) return message def function_handler(event, context): try: input_topic = get_input_topic(context) input_message = get_input_message(event) response = 'Invoked on topic "%s" with message "%s"' % (input_topic, input_message) logging.info(response) except Exception as e: logging.error(e) client.publish(topic=OUTPUT_TOPIC, payload=response) return
To test the function, add it to your group using the default configuration settings. Then, add the following subscriptions and deploy the group. For instructions, see Module 3 (part 1): Lambda functions on AWS IoT Greengrass.
After the deployment is completed, invoke the function.
In the AWS IoT console, open the Test page.
test/topic_resultstopic.
Publish a message to the
test/input_messagetopic. For this example, you must include the
test-keyproperty in the JSON messsage.
{ "test-key": "Some string value" }
If successful, the function publishes the input topic and message string to the
test/topic_resultstopic.
Lifecycle configuration for Greengrass Lambda functions
The Greengrass Lambda function lifecycle determines when a function starts and how it creates and uses containers. The lifecycle also determines how variables and preprocessing logic that are outside of the function handler are retained.
AWS IoT Greengrass supports the on-demand (default) or long-lived lifecycles:
On-demand functions start when they are invoked and stop when there are no tasks left to execute. An invocation of the function creates a separate container (or sandbox) to process invocations, unless an existing container is available for reuse. Data that's sent to the function might be pulled by any of the containers.
Multiple invocations of an on-demand function can run in parallel.
Variables and preprocessing logic that are defined outside of the function handler are not retained when new containers are created.
Long-lived (or pinned) functions start automatically when the AWS IoT Greengrass core starts and run in a single container. All data that's sent to the function is pulled by the same container.
Multiple invocations are queued until earlier invocations are executed.
Variables and preprocessing logic that are defined outside of the function handler are retained for every invocation of the handler.
Long-lived Lambda functions are useful when you need to start doing work without any initial input. For example, a long-lived function can load and start processing an ML model to be ready when the function starts receiving device data.
Note
Remember that long-lived functions have timeouts that are associated with invocations of their handler. If you want to execute indefinitely running code, you must start it outside the handler. Make sure that there's no blocking code outside the handler that might prevent the function from completing its initialization.
These functions run unless the core stops (for example, during a group deployment or a device reboot) or the function enters an error state (such as a handler timeout, uncaught exception, or when it exceeds its memory limits).
For more information about container reuse, see Understanding
Container Reuse in AWS Lambda
Lambda executables
This feature is available for AWS IoT Greengrass Core v1.6 and later.
A Lambda executable is a type of Greengrass Lambda function that you can use to run binary code in the core environment. It lets you execute device-specific functionality natively and benefit from the smaller footprint of compiled code. Lambda executables can be invoked by events, invoke other functions, and access local resources.
Lambda executables support the binary encoding type only (not JSON), but otherwise you can manage them in your Greengrass group and deploy them like other Greengrass Lambda functions. However, the process of creating Lambda executables is different from creating Python, Java, and Node.js Lambda functions:
You can't use the AWS Lambda console to create (or manage) a Lambda executable. You can create a Lambda executable only by using the AWS Lambda API.
You upload the function code to AWS Lambda as a compiled executable that includes the AWS IoT Greengrass Core SDK for C
.
You specify the executable name as the function handler.
Lambda executables must implement certain calls and programming patterns in their
function code. For example, the
main method must:
Call
gg_global_initto initialize Greengrass internal global variables. This function must be called before creating any threads, and before calling any other AWS IoT Greengrass Core SDK functions.
Call
gg_runtime_startto register the function handler with the Greengrass Lambda runtime. This function must be called during initialization. Calling this function causes the current thread to be used by the runtime. The optional
GG_RT_OPT_ASYNCparameter tells this function to not block, but instead to create a new thread for the runtime. This function uses a
SIGTERMhandler.
The following snippet is the
main method from the
simple_handler.c
int main() { gg_error err = GGE_SUCCESS; err = gg_global_init(0); if(err) { gg_log(GG_LOG_ERROR, "gg_global_init failed %d", err); goto cleanup; } gg_runtime_start(handler, 0); cleanup: return -1; }
For more information about requirements, constraints, and other implementation
details, see AWS IoT Greengrass Core SDK for C
Create a Lambda executable
After you compile your code along with the SDK, use the AWS Lambda API to create a Lambda function and upload your compiled executable.
Your function must be compiled with a C89 compatible compiler.
The following example uses the create-function CLI command to create a Lambda executable. The command specifies:
The name of the executable for the handler. This must be the exact name of your compiled executable.
The path to the
.zipfile that contains the compiled executable.
arn:aws:greengrass:::runtime/function/executablefor the runtime. This is the runtime for all Lambda executables.
For
role, you can specify the ARN of any Lambda execution role.
AWS IoT Greengrass doesn't use this role, but the parameter is required to create
the
function. For more information about Lambda execution roles, see AWS Lambda
permissions model in the
AWS Lambda Developer Guide.
aws lambda create-function \ --region
aws-region\ --function-name
function-name\ --handler
executable-name\ --role
role-arn\ --zip-file fileb://
file-name.zip \ --runtime arn:aws:greengrass:::runtime/function/executable
Next, use the AWS Lambda API to publish a version and create an alias.
Use publish-version to publish a function version.
aws lambda publish-version \ --function-name
function-name\ --region
aws-region
Use create-alias to create an alias the points to the version you just published. We recommend that you reference Lambda functions by alias when you add them to a Greengrass group.
aws lambda create-alias \ --function-name
function-name\ --name
alias-name\ --function-version
version-number\ --region
aws-region
The AWS Lambda console doesn't display Lambda executables. To update the function code, you must use the AWS Lambda API.
Then, add the Lambda executable to a Greengrass group, configure it to accept binary input data in its group-specific settings, and deploy the group. You can do this in the AWS IoT Greengrass console or by using the AWS IoT Greengrass API. | https://docs.aws.amazon.com/greengrass/v1/developerguide/lambda-functions.html | CC-MAIN-2021-31 | refinedweb | 3,036 | 55.13 |
Hey guys, I've run into a small problem on this program I was creating. It's supposed to be a simple database using arrays to store names in strings and ages in a separate array. Unfortunately, when I try to have the program echo back all the inputted data, it fails and just inputs the first name and age entered. Take a look:
Thanks in advance for any help :)Thanks in advance for any help :)Code:
//This is a program that allows you to create a simple database and output it all to a text file
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string name[10];
int age[10];
int input;
int i; //counting
int a;//counting
a = 0;
i = 0;
mainmenu:
cout << "Database Manager" << endl;
cout << "1: New Database" << endl;
cout << "2: Load Database" << endl;
cout << "3: View Database" << endl;
cout << "4: Edit Database" << endl;
cin >> input;
switch (input) {
case 1:
while (i < 10) {
cout << endl;
cout << "Enter the info for each person. Limit of 10 people."<< endl << "Type 'back' to return to the main menu"<< endl; //back function not implemented yet
cout << "Input Name: " << endl;
cin >> name[i];
cout << "Input Age: "<< endl;
cin >> age[i];
i++;
}
break;
case 3:
for (a=0; a<10; a++) {//tried different kinds of loops, can't get it to print the arrays correctly
cout << name[a] << endl << age[a] << endl << endl; //should print out every name and age
}
break;
}
goto mainmenu;
} | http://cboard.cprogramming.com/cplusplus-programming/144688-cplusplus-novice-needs-help-printable-thread.html | CC-MAIN-2015-22 | refinedweb | 244 | 57.57 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
A REFRESHING STUDY
ON THE RESURRECTION
by
E. W. Bullinger
Scripture shuts us up to the blessed hope of being reunited
in resurrection. That is why the death of believers is so often
called "sleep"; and dying is called "falling asleep"; because of
the assured hope of awakening in resurrection. It's.
2.
So effectually has Satan's lie, "thou shalt not surely die",
succeeded and accomplished its purpose that, though the Lord
Jesus said "I will come again and receive you unto Myself",
Christendom says, with one voice, "No! Lord. Thou needest.
In Phil. 2:27, we read that Epaphraditus "was sick nigh unto
death; but God had mercy on him"..So that it was mercy to
preserve Epaphraditus from death. This could hardly be called
"mercy" if death were the "gate of glory", according to
popular tradition.
In 2 Cor. 1:10-11, it was deliverance of no ordinary kind
when Paul himself he would be unclothed, but clothed upon (i.e. in
resurrection and "change") that mortality might be swallowed
up of LIFE"; not of death. This is what he was so "earnestly
desiring" (v.2)
Hezekiah also had reason to praise God for delivering him
from "the king of terrors". It was "mercy" shown to
Epaphraditus; it was "a gift" to Paul; it was "love" to
Hezekiah. He says (Isa. 38:17- 19): "For the grave (Heb.
sheol) cannot praise thee, death cannot celebrate thee: They
3 1 Thes. 4:15, we read: "This we say unto you by the
Word of the Lord, that we which are alive and remain shall not
precede them which are asleep."
To agree with Tradition this ought to have been written,
"shall not precede them which are already with the Lord". But
this would have made nonsense; and there is nothing of that in
the Word of God.
While we may draw our own inferences from what the
Scriptures state, we shall all agree that it is highly important
that we should clothe these views in Scriptural terms, and that
we should ask and answer how far it is that these popular
sayings have practically, at any rate until recent years, blotted
out the hope of resurrection, the hope of the Lord's coming
again to fulfill His promise, to receive us to Himself. You
remember how the apostle speaks to some in the 15th chapter
of 1st Corinthians, who say that there is "no resurrection of the
dead"; and in writing to Timothy he refers to Hymenaeus &
Philetus, who had led some away from the faith by saying that
"the resurrection is past already". of
revelation.";
from which man was "taken" (Gen. 2:7; 3:23), and to which he
must return (Gen. 3:19; Eccl. 12:7).
Psalm 146:4 declares of man, "His breath goes forth, He
returneth to his earth; In that very day his thoughts perish."
The passage says nothing about the "body". It is whatever has
done the thinking. the "body" does not think. The "body",
apart from the spirit, has no thoughts. Whatever has had the
"thoughts" has them no more; and this is "man".
There is Eccl. 9:5, which declares that "The living know
that they shall die; But the dead know not anything". It does
not say dead bodies know not anything, but "the dead", i.e.
dead people, who are set in contrast with the "living". As one
of these "living", David says, by the Holy Spirit (Psa. 146:2;
104:33):"While I live will I praise the Lord: I will sing praises
unto my God while I have any being". There would be no
praising the Lord after he had ceased to "have any being".
Why? Because "princes" and the "son of man" are helpless
(Psa., beyond what God has told us in the Scriptures. | https://www.scribd.com/document/177714889/Bullinger-a-Refreshing-Study-on-the-Resurrection | CC-MAIN-2018-05 | refinedweb | 657 | 81.12 |
Flex 3 > FB4 Migration TipJason Villmer Jul 7, 2009 10:41 PM
Thanks to the help of several Adobe members I was able to successfully import a styled (.css) Flex 3 project into Flash Builder 4 and have it retain its aesthetic and functional attributes. I wanted to take a moment and share what I found with everyone, in case you may find yourself confronted with the same issues.
1.First, to bring in my Flex 3 project to Flash Builder 4 I needed to add a single line in my .css file:
@namespace "library://ns.adobe.com/flex/halo";
1. Re: Flex 3 > FB4 Migration Tiptinylion_uk Jul 8, 2009 12:58 AM (in response to Jason Villmer)
Hi
Glad to here it all went to plan.
Was just the same here.
After all the talk of things breaking it's good to hear a success story.
I used a similar approach to this, rather than using the compiler argument I just grabbed the css file from the halo components and included that above my other style sheets includes at the top on main.mxml. Im not sure if this just gives exactly the same result in the end, but it defiantly worked for me.
I know that almost all of the styles that were set by using the default.css (i think that was the file i used) and then overriding the values with subsequently included style may seem kind of redundant, but my thinking was, well at least when my custom style are being added they are working from the same base that they were expecting in sdk3.
All in all our projects transition to sdk4 has been very smooth. This is a large project (it's an intranet application for a uk architects and bespoke joiners, and when complete will be used at just about every stage of their workflow. I was expecting a lot more pain during the conversion than we had)
It's my opinion (and it's a very strong one) that the advantages of moving to sdk4 are more than worth the initial conversion.
At present the application uses a mix of sdk3 and 4. And this mix is quite deep. As time goes by more and more has been changed to sdk4. It was my initial intention to get the project working as was, then continue to use new features as and when they were advantageous. What has happened though, is that having found new sections of the application written in sdk4 being so much better, easier to read, flexible, that we've started re-writing perfectly useable sections of the app over to sdk4. Trust me when I say we wouldn’t have done his extra work if there wasn't some pay off.
Anyway, good to hear how things went for you
Cheers
glenn
tinylion
2. Re: Flex 3 > FB4 Migration TipJason Villmer Jul 8, 2009 1:17 AM (in response to tinylion_uk)
Glenn,
There is always the lure to immediately embrace the newest
technologies. I'd been considerably eager to see what Flash Builder
had to offer and it does, indeed, provide a broader landscape of
possibilities. After everything has been said and done I believe the
Flash Builder team should consider a Migration Assistant to help
transition Flex 3 projects to the Flash Builder 4 code architecture.
Upon importing a Flex 3 project the user could be asked if they would
like to formally convert the entire codebase into a native FB 4
project. It would then go through the document, possibly stopping
occasionally asking for approval to do something, and update all
relevant code so it becomes a true FB4 app. There could also be a list
provided after this conversion that specifically outlines all changes
made.
I've been working in Flex for a number of months now. Prior to this I
was using the Flash IDE. Upon exploring Flex, the advantages were
clear and substantial. Flex is absolutely outstanding for both
designers and developers in my opinion. The issue, however, is that
Flex users should be, above all, anxious to migrate to Flash Builder
4, not worried. If a Flex 3 developer has finished a huge project
(like you and I apparently) in Flex 3 we shouldn't have to go through
all of our code trying to figure out what needs to be changed. There
should be something that helps developers do that automatically.
Technology is relentlessly changing. Monthly, weekly, daily even.
That's great but for something like Flex, new versions shouldn't have
developers searching everywhere trying to find patchwork solutions.
The folks over at the Flash Builder 4 team have been great assisting
both myself and the multitude of other users with their issues, so I'm
pretty confident things will unfold well.
Jason Villmer | https://forums.adobe.com/thread/459008 | CC-MAIN-2017-39 | refinedweb | 804 | 68.1 |
The POSIX liasion report to the LWG at the Bellevue meeting requested the reservation of possible namespaces for future standardization work. Two namespaces were mentioned as candidates: std::posix and ::posix.
The LWG wasn't planning on using either of these namepaces. However, during the Sophia Antipolis meeting, it was believed that there may be issues with regard to std::posix, so it it was suggested to formalize simply the request for ::posix in the working draft.
This subclause describes restrictions on C++ programs that use the facilities of the C++ Standard Library. The following subclauses specify constraints on the program's use of namespaces (17.4.3.1) the namespace std (17.4.3.1), its use of various reserved names (17.4.3.2), its use of headers (17.4.3.3), its use of standard library classes as base classes (17.4.3.4), its definitions of replacement functions (17.4.3.5), and its installation of handler functions during execution (17.4.3.6).Change 17.4.3.1 [namespace.std] as follows:
17.4.3.1 Namespace Use [namespace.constraints]Add the following new subclause to the new 17.4.3.1 [namespace.constraints]:
17.4.3.1.1Namespace std [namespace.std]17.4.3.1.1Namespace std [namespace.std]
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.
17.4.3.1.2 Namespace posix [namespace.posix]
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace posix or to a namespace within namespace posix unless otherwise specified. The namespace posix is reserved for use by ISO/IEC 9945 and other POSIX standards. | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2667.htm | CC-MAIN-2019-39 | refinedweb | 293 | 60.01 |
PEP 677 -- Callable Type Syntax
Contents
- Abstract
- Motivation
- Rationale
- Specification
- Typing Behavior
- Grammar and AST
- Implications of the Grammar
- Runtime Behavior
- Rejected Alternatives
- Extended Syntax Supporting Named and Optional Arguments
- Syntax Closer to Function Signatures
- Other Proposals Considered
- Alternative Runtime Behaviors
- Backward Compatibility
- Reference Implementation
- Open Issues
- Resources
Abstract
This PEP introduces a concise and friendly syntax for callable types, supporting the same functionality as typing.Callable but with an arrow syntax inspired by the syntax for typed function signatures. This allows types like Callable[[int, str], bool] to be written as (int, str) -> bool.
The proposed syntax supports all the functionality provided by typing.Callable and typing.Concatenate, and is intended to work as a drop-in replacement.
Motivation
One way to make code safer and easier to analyze is by making sure that functions and classes are well-typed. In Python we have type annotations, the framework for which is defined in PEP 484, to provide type hints that can find bugs as well as helping with editor tooling like tab completion, static analysis tooling, and code review.
Consider the following untyped code:
def flat_map(func, l): out = [] for element in l: out.extend(func(element)) return out def wrap(x: int) -> list[int]: return [x] def add(x: int, y: int) -> int: return x + y flat_map(wrap, [1, 2, 3]) # no runtime error, output is [1, 2, 3] flat_map(add, [1, 2, 3]) # runtime error: `add` expects 2 arguments, got 1
We can add types to this example to detect the runtime error:
from typing import Callable def flat_map( func: Callable[[int], list[int]], l: list[int] ) -> list[int]: .... ... flat_map(wrap, [1, 2, 3]) # type checks okay, output is [1, 2, 3] flat_map(add, [1, 2, 3]) # type check error
There are a few usability challenges with Callable we can see here:
- It is verbose, particularly for more complex function signatures.
- It relies on two levels of nested brackets, unlike any other generic type. This can be especially hard to read when some of the type parameters are themselves generic types.
- The bracket structure is not visually similar to how function signatures are written.
- It requires an explicit import, unlike many of the other most common types like list and dict.
Possibly as a result, programmers often fail to write complete Callable types. Such untyped or partially-typed callable types do not check the parameter types or return types of the given callable and thus negate the benefits of static typing. For example, they might write this:
from typing import Callable def flat_map( func: Callable[..., Any], l: list[int] ) -> list[int]: .... ... flat_map(add, [1, 2, 3]) # oops, no type check error!
There's some partial type information here - we at least know that func needs to be callable. But we've dropped too much type information for type checkers to find the bug.
With our proposal, the example looks like this:
def flat_map( func: (int) -> list[int], l: list[int] ) -> list[int]: out = [] for element in l: out.extend(f(element)) return out ...
The type (int) -> list[int] is more concise, uses an arrow similar to the one indicating a return type in a function header, avoids nested brackets, and does not require an import.
Rationale
The Callable type is widely used. For example, as of October 2021 it was the fifth most common complex type in typeshed, after Optional, Tuple, Union, and List.
The others have had their syntax improved and the need for imports eliminated by either PEP 604 or PEP 585:
- typing.Optional[int] is written int | None
- typing.Union[int, str] is written int | str
- typing.List[int] is written list[int]
- typing.Tuple[int, str] is written tuple[int, str]
The typing.Callable type is used almost as often as these other types, is more complicated to read and write, and still requires an import and bracket-based syntax.
In this proposal, we chose to support all the existing semantics of typing.Callable, without adding support for new features. We made this decision after examining how frequently each feature might be used in existing typed and untyped open-source code. We determined that the vast majority of use cases are covered.
We considered adding support for named, optional, and variadic arguments. However, we decided against including these features, as our analysis showed they are infrequently used. When they are really needed, it is possible to type these using callback protocols.
An Arrow Syntax for Callable Types
We are proposing a succinct, easy-to-use syntax for typing.Callable that looks similar to function headers in Python. Our proposal closely follows syntax used by several popular languages such as Typescript, Kotlin, and Scala.
Our goals are that:
- Callable types using this syntax will be easier to learn and use, particularly for developers with experience in other languages.
- Library authors will be more likely to use expressive types for callables that enable type checkers to better understand code and find bugs, as in the decorator example above.
Consider this simplified real-world example from a web server, written using the existing typing.Callable:
from typing import Awaitable, Callable from app_logic import Response, UserSetting def customize_response( response: Response, customizer: Callable[[Response, list[UserSetting]], Awaitable[Response]] ) -> Response: ...
With our proposal, this code can be abbreviated to:
from app_logic import Response, UserSetting def customize_response( response: Response, customizer: async (Response, list[UserSetting]) -> Response, ) -> Response: ...
This is shorter and requires fewer imports. It also has far less nesting of square brackets - only one level, as opposed to three in the original code.
Compact Syntax for ParamSpec
A particularly common case where library authors leave off type information for callables is when defining decorators. Consider the following:
from typing import Any, Callable def with_retries( f: Callable[..., Any] ) -> Callable[..., Any]: def wrapper(retry_once, *args, **kwargs): if retry_once: try: return f(*args, **kwargs) except Exception: pass return f(*args, **kwargs) return wrapper @with_retries def f(x: int) -> int: return x f(y=10) # oops - no type error!
In the code above, it is clear that the decorator should produce a function whose signature is like that of the argument f other than an additional retry_once argument. But the use of ... prevents a type checker from seeing this and alerting a user that f(y=10) is invalid.
With PEP 612 it is possible to type decorators like this correctly as follows:
from typing import Any, Callable, Concatenate, ParamSpec, TypeVar R = TypeVar("R") P = ParamSpec("P") def with_retries( f: Callable[P, R] ) -> Callable[Concatenate[bool, P] R]: def wrapper(retry_once: bool, *args: P.args, **kwargs: P.kwargs) -> R: ... return wrapper ...
With our proposed syntax, the properly-typed decorator example becomes concise and the type representations are visually descriptive:
from typing import Any, ParamSpec, TypeVar R = TypeVar("R") P = ParamSpec("P") def with_retries( f: (**P) -> R ) -> (bool, **P) -> R: ...
Comparing to Other Languages
Many popular programming languages use an arrow syntax similar to the one we are proposing here.
TypeScript
In TypeScript, function types are expressed in a syntax almost the same as the one we are proposing, but the arrow token is => and arguments have names:
(x: int, y: str) => bool
The names of the arguments are not actually relevant to the type. So, for example, this is the same callable type:
(a: int, b: str) => bool
Kotlin
Function types in Kotlin permit an identical syntax to the one we are proposing, for example:
(Int, String) -> Bool
It also optionally allows adding names to the arguments, for example:
(x: Int, y: String) -> Bool
As in TypeScript, the argument names (if provided) are just there for documentation and are not part of the type itself.
Scala
Scala uses the => arrow for function types. Other than that, their syntax is the same as the one we are proposing, for example:
(Int, String) => Bool
Scala, like Python, has the ability to provide function arguments by name. Function types can optionally include names, for example:
(x: Int, y: String) => Bool
Unlike in TypeScript and Kotlin, these names are part of the type if provided - any function implementing the type must use the same names. This is similar to the extended syntax proposal we describe in our Rejected Alternatives section.
Function Definitions vs Callable Type Annotations
In all of the languages listed above, type annotations for function definitions use a : rather than a ->. For example, in TypeScript a simple add function looks like this:
function higher_order(fn: (a: string) => string): string { return fn("Hello, World"); }
Scala and Kotlin use essentially the same : syntax for return annotations. The : makes sense in these languages because they all use : for type annotations of parameters and variables, and the use for function return types is similar.
In Python we use : to denote the start of a function body and -> for return annotations. As a result, even though our proposal is superficially the same as these other languages the context is different. There is potential for more confusion in Python when reading function definitions that include callable types.
This is a key concern for which we are seeking feedback with our draft PEP; one idea we have floated is to use => instead to make it easier to differentiate.
The ML Language Family
Languages in the ML family, including F#, OCaml, and Haskell, all use -> to represent function types. All of them use a parentheses-free syntax with multiple arrows, for example in Haskell:
Integer -> String -> Bool
The use of multiple arrows, which differs from our proposal, makes sense for languages in this family because they use automatic currying of function arguments, which means that a multi-argument function behaves like a single-argument function returning a function.
Specification
Typing Behavior
Type checkers should treat the new syntax with exactly the same semantics as typing.Callable.
As such, a type checker should treat the following pairs exactly the same:
from typing import Awaitable, Callable, Concatenate, ParamSpec, TypeVarTuple P = ParamSpec("P") Ts = TypeVarTuple('Ts') f0: () -> bool f0: Callable[[], bool] f1: (int, str) -> bool f1: Callable[[int, str], bool] f2: (...) -> bool f2: Callable[..., bool] f3: async (str) -> str f3: Callable[[str], Awaitable[str]] f4: (**P) -> bool f4: Callable[P, bool] f5: (int, **P) -> bool f5: Callable[Concatenate[int, P], bool] f6: (*Ts) -> bool f6: Callable[[*Ts], bool] f7: (int, *Ts, str) -> bool f7: Callable[[int, *Ts, str], bool]
Grammar and AST
The proposed new syntax can be described by these AST changes to Parser/Python.asdl:
expr = <prexisting_expr_kinds> | AsyncCallableType(callable_type_arguments args, expr returns) | CallableType(callable_type_arguments args, expr returns) callable_type_arguments = AnyArguments | ArgumentsList(expr* posonlyargs) | Concatenation(expr* posonlyargs, expr param_spec)
Here are our proposed changes to the Python Grammar <>:
expression: | disjunction disjunction 'else' expression | callable_type_expression | disjunction | lambdef callable_type_expression: | callable_type_arguments '->' expression | ASYNC callable_type_arguments '->' expression callable_type_arguments: | '(' '...' [','] ')' | '(' callable_type_positional_argument* ')' | '(' callable_type_positional_argument* callable_type_param_spec ')' callable_type_positional_argument: | !'...' expression ',' | !'...' expression &')' callable_type_param_spec: | '**' expression ',' | '**' expression &')'
If PEP 646 is accepted, we intend to include support for unpacked types in two ways. To support the "star-for-unpack" syntax proposed in PEP 646, we will modify the grammar for callable_type_positional_argument as follows:
callable_type_positional_argument: | !'...' expression ',' | !'...' expression &')' | '*' expression ',' | '*' expression &')'
With this change, a type of the form (int, *Ts) -> bool should evaluate the AST form:
CallableType( ArgumentsList(Name("int"), Starred(Name("Ts")), Name("bool") )
and be treated by type checkers as equivalent to or Callable[[int, *Ts], bool] or Callable[[int, Unpack[Ts]], bool].
Implications of the Grammar
Precedence of ->
-> binds less tightly than other operators, both inside types and in function signatures, so the following two callable types are equivalent:
(int) -> str | bool (int) -> (str | bool)
-> associates to the right, both inside types and in function signatures. So the following pairs are equivalent:
(int) -> (str) -> bool (int) -> ((str) -> bool) def f() -> (int, str) -> bool: pass def f() -> ((int, str) -> bool): pass def f() -> (int) -> (str) -> bool: pass def f() -> ((int) -> ((str) -> bool)): pass
Because operators bind more tightly than ->, parentheses are required whenever an arrow type is intended to be inside an argument to an operator like |:
(int) -> () -> int | () -> bool # syntax error! (int) -> (() -> int) | (() -> bool) # okay
We discussed each of these behaviors and believe they are desirable:
- Union types (represented by A | B according to PEP 604) are valid in function signature returns, so we need to allow operators in the return position for consistency.
- Given that operators bind more tightly than -> it is correct that a type like bool | () -> bool must be a syntax error. We should be sure the error message is clear because this may be a common mistake.
- Associating -> to the right, rather than requiring explicit parentheses, is consistent with other languages like TypeScript and respects the principle that valid expressions should normally be substitutable when possible.
async Keyword
All of the binding rules still work for async callable types:
(int) -> async (float) -> str | bool (int) -> (async (float) -> (str | bool)) def f() -> async (int, str) -> bool: pass def f() -> (async (int, str) -> bool): pass def f() -> async (int) -> async (str) -> bool: pass def f() -> (async (int) -> (async (str) -> bool)): pass
Trailing Commas
Following the precedent of function signatures, putting a comma in an empty arguments list is illegal: (,) -> bool is a syntax error.
Again following precedent, trailing commas are otherwise always permitted:
((int,) -> bool == (int) -> bool ((int, **P,) -> bool == (int, **P) -> bool ((...,) -> bool) == ((...) -> bool)
Allowing trailing commas also gives autoformatters more flexibility when splitting callable types across lines, which is always legal following standard python whitespace rules.
Disallowing ... as an Argument Type
Under normal circumstances, any valid expression is permitted where we want a type annotation and ... is a valid expression. This is never semantically valid and all type checkers would reject it, but the grammar would allow it if we did not explicitly prevent this.
Since ... is meaningless as a type and there are usability concerns, our grammar rules it out and the following is a syntax error:
(int, ...) -> bool
We decided that there were compelling reasons to do this:
- The semantics of (...) -> bool are different from (T) -> bool for any valid type T: (...) is a special form indicating AnyArguments whereas T is a type parameter in the arguments list.
- ... is used as a placeholder default value to indicate an optional argument in stubs and callback protocols. Allowing it in the position of a type could easily lead to confusion and possibly bugs due to typos.
- In the tuple generic type, we special-case ... to mean "more of the same", e.g. a tuple[int, ...] means a tuple with one or more integers. We do not use ... in a a similar way in callable types, so to prevent misunderstandings it makes sense to prevent this.
Incompatibility with other possible uses of * and **
The use of **P for supporting PEP 612 ParamSpec rules out any future proposal using a bare **<some_type> to type kwargs. This seems acceptable because:
- If we ever do want such a syntax, it would be clearer to require an argument name anyway. This would also make the type look more similar to a function signature. In other words, if we ever support typing kwargs in callable types, we would prefer (int, **kwargs: str) rather than (int, **str).
- PEP 646 unpacking syntax would rule out using *<some_type> for args. The kwargs case is similar enough that this rules out a bare **<some_type> anyway.
Compatibility with Arrow-Based Lambda Syntax
To the best of our knowledge there is no active discussion of arrow-style lambda syntax that we are aware of, but it is nonetheless worth considering what possibilities would be ruled out by adopting this proposal.
It would be incompatible with this proposal to adopt the same a parenthesized ->-based arrow syntax for lambdas, e.g. (x, y) -> x + y for lambda x, y: x + y.
Our view is that if we want arrow syntax for lambdas in the future, it would be a better choice to use =>, e.g. (x, y) => x + y. Many languages use the same arrow token for both lambdas and callable types, but Python is unique in that types are expressions and have to evaluate to runtime values. Our view is that this merits using separate tokens, and given the existing use of -> for return types in function signatures it would be more coherent to use -> for callable types and => for lambdas.
Runtime Behavior
The new AST nodes need to evaluate to runtime types, and we have two goals for the behavior of these runtime types:
- They should expose a structured API that is descriptive and powerful enough to be compatible with extending the type to include new features like named and variadic arguments.
- They should also expose an API that is backward-compatible with typing.Callable.
Evaluation and Structured API
We intend to create new builtin types to which the new AST nodes will evaluate, exposing them in the types module.
Our plan is to expose a structured API as if they were defined as follows:
class CallableType: is_async: bool arguments: Ellipsis | tuple[CallableTypeArgument] return_type: object class CallableTypeArgument: kind: CallableTypeArgumentKind annotation: object @enum.global_enum class CallableTypeArgumentKind(enum.IntEnum): POSITIONAL_ONLY: int = ... PARAM_SPEC: int = ...
The evaluation rules are expressed in terms of the following pseudocode:
def evaluate_callable_type( callable_type: ast.CallableType | ast.AsyncCallableType: ) -> CallableType: return CallableType( is_async=isinstance(callable_type, ast.AsyncCallableType), arguments=_evaluate_arguments(callable_type.arguments), return_type=evaluate_expression(callable_type.returns), ) def _evaluate_arguments(arguments): match arguments: case ast.AnyArguments(): return Ellipsis case ast.ArgumentsList(posonlyargs): return tuple( _evaluate_arg(arg) for arg in args ) case ast.ArgumentsListConcatenation(posonlyargs, param_spec): return tuple( *(evaluate_arg(arg) for arg in args), _evaluate_arg(arg=param_spec, kind=PARAM_SPEC) ) if isinstance(arguments, Any return Ellipsis def _evaluate_arg(arg, kind=POSITIONAL_ONLY): return CallableTypeArgument( kind=POSITIONAL_ONLY, annotation=evaluate_expression(value) )
Backward-Compatible API
To get backward compatibility with the existing types.Callable API, which relies on fields __args__ and __parameters__, we can define them as if they were written in terms of the following:
import itertools import typing def get_args(t: CallableType) -> tuple[object]: return_type_arg = ( typing.Awaitable[t.return_type] if t.is_async else t.return_type ) arguments = t.arguments if isinstance(arguments, Ellipsis): argument_args = (Ellipsis,) else: argument_args = (arg.annotation for arg in arguments) return ( *arguments_args, return_type_arg ) def get_parameters(t: CallableType) -> tuple[object]: out = [] for arg in get_args(t): if isinstance(arg, typing.ParamSpec): out.append(t) else: out.extend(arg.__parameters__) return tuple(out)
Additional Behaviors of types.CallableType
As with the A | B syntax for unions introduced in PEP 604:
- The __eq__ method should treat equivalent typing.Callable values as equal to values constructed using the builtin syntax, and otherwise should behave like the __eq__ of typing.Callable.
- The __repr__ method should produce an arrow syntax representation that, when evaluated, gives us back an equal types.CallableType instance.
Rejected Alternatives
Many of the alternatives we considered would have been more expressive than typing.Callable, for example adding support for describing signatures that include named, optional, and variadic arguments.
To determine which features we most needed to support with a callable type syntax, we did an extensive analysis of existing projects:
- stats on the use of the Callable type;
- stats on how untyped and partially-typed callbacks are actually used.
We decided on a simple proposal with improved syntax for the existing Callable type because the vast majority of callbacks can be correctly described by the existing typing.Callable semantics:
- Positional parameters: By far the most important case to handle well is simple callable types with positional parameters, such as (int, str) -> bool
- ParamSpec and Concatenate: The next most important feature is good support for PEP 612 ParamSpec and Concatenate types like (**P) -> bool and (int, **P) -> bool. These are common primarily because of the heavy use of decorator patterns in python code.
- TypeVarTuples: The next most important feature, assuming PEP 646 is accepted, is for unpacked types which are common because of cases where a wrapper passes along *args to some other function.
Features that other, more complicated proposals would support account for fewer than 2% of the use cases we found. These are already expressible using callback protocols, and since they are uncommon we decided that it made more sense to move forward with a simpler syntax.
Extended Syntax Supporting Named and Optional Arguments
Another alternative was for a compatible but more complex syntax that could express everything in this PEP but also named, optional, and variadic arguments. In this “extended” syntax proposal the following types would have been equivalent:
class Function(typing.Protocol): def f(self, x: int, /, y: float, *, z: bool = ..., **kwargs: str) -> bool: ... Function = (int, y: float, *, z: bool = ..., **kwargs: str) -> bool
Advantages of this syntax include: - Most of the advantages of the proposal in this PEP (conciseness, PEP 612 support, etc) - Furthermore, the ability to handle named, optional, and variadic arguments
We decided against proposing it for the following reasons:
The implementation would have been more difficult, and usage stats demonstrate that fewer than 3% of use cases would benefit from any of the added features.
The group that debated these proposals was split down the middle about whether these changes are desirable:
- On the one hand, they make callable types more expressive. On the other hand, they could easily confuse users who have not read the full specification of callable type syntax.
- We believe the simpler syntax proposed in this PEP, which introduces no new semantics and closely mimics syntax in other popular languages like Kotlin, Scala, and TypesScript, is much less likely to confuse users.
We intend to implement the current proposal in a way that is forward-compatible with the more complicated extended syntax. If the community decides after more experience and discussion that we want the additional features, it should be straightforward to propose them in the future.
Even a full extended syntax cannot replace the use of callback protocols for overloads. For example, no closed form of callable type could express a function that maps bools to bools and ints to floats, like this callback protocol.:
from typing import overload, Protocol class OverloadedCallback(Protocol) @overload def __call__(self, x: int) -> float: ... @overload def __call__(self, x: bool) -> bool: ... def __call__(self, x: int | bool) -> float | bool: ... f: OverloadedCallback = ... f(True) # bool f(3) # float
We confirmed that the current proposal is forward-compatible with extended syntax by implementing a grammar and AST for this extended syntax on top of our reference implementation of this PEP's grammar.
Syntax Closer to Function Signatures
One alternative we had floated was a syntax much more similar to function signatures.
In this proposal, the following types would have been equivalent:
class Function(typing.Protocol): def f(self, x: int, /, y: float, *, z: bool = ..., **kwargs: str) -> bool: ... Function = (x: int, /, y: float, *, z: bool = ..., **kwargs: str) -> bool
The benefits of this proposal would have included:
- Perfect syntactic consistency between signatures and callable types.
- Support for more features of function signatures (named, optional, variadic args) that this PEP does not support.
Key downsides that led us to reject the idea include the following:
- A large majority of use cases only use positional-only arguments. This syntax would be more verbose for that use case, both because of requiring argument names and an explicit /, for example (int, /) -> bool where our proposal allows (int) -> bool
- The requirement for explicit / for positional-only arguments has a high risk of causing frequent bugs - which often would not be detected by unit tests - where library authors would accidentally use types with named arguments.
- Our analysis suggests that support for ParamSpec is key, but the scoping rules laid out in PEP 612 would have made this difficult.
Other Proposals Considered
Functions-as-Types
An idea we looked at very early on was to allow using functions as types. The idea is allowing a function to stand in for its own call signature, with roughly the same semantics as the __call__ method of callback protocols:
def CallableType( positional_only: int, /, named: str, *args: float, keyword_only: int = ..., **kwargs: str ) -> bool: ... f: CallableType = ... f(5, 6.6, 6.7, named=6, x="hello", y="world") # typechecks as bool
This may be a good idea, but we do not consider it a viable replacement for callable types:
- It would be difficult to handle ParamSpec, which we consider a critical feature to support.
- When using functions as types, the callable types are not first-class values. Instead, they require a separate, out-of-line function definition to define a type alias
- It would not support more features than callback protocols, and seems more like a shorter way to write them than a replacement for Callable.
Hybrid keyword-arrow Syntax
In the Rust language, a keyword fn is used to indicate functions in much the same way as Python's def, and callable types are indicated using a hybrid arrow syntax Fn(i64, String) -> bool.
We could use the def keyword in callable types for Python, for example our two-parameter boolean function could be written as def(int, str) -> bool. But we think this might confuse readers into thinking def(A, B) -> C is a lambda, particularly because Javascript's function keyword is used in both named and anonymous functions.
Parenthesis-Free Syntax
We considered a parentheses-free syntax that would have been even more concise:
int, str -> bool
We decided against it because this is not visually as similar to existing function header syntax. Moreover, it is visually similar to lambdas, which bind names with no parentheses: lambda x, y: x == y.
Requiring Outer Parentheses
A concern with the current proposal is readability, particularly when callable types are used in return type position which leads to multiple top-level -> tokens, for example:
def make_adder() -> (int) -> int: return lambda x: x + 1
We considered a few ideas to prevent this by changing rules about parentheses. One was to move the parentheses to the outside, so that a two-argument boolean function is written (int, str -> bool). With this change, the example above becomes:
def make_adder() -> (int -> int): return lambda x: x + 1
This makes the nesting of many examples that are difficult to follow clear, but we rejected it because
- Currently in Python commas bind very loosely, which means it might be common to misread (int, str -> bool) as a tuple whose first element is an int, rather than a two-parameter callable type.
- It is not very similar to function header syntax, and one of our goals was familiar syntax inspired by function headers.
- This syntax may be more readable for deaply nested callables like the one above, but deep nesting is not very common. Encouraging extra parentheses around callable types in return position via a style guide would have most of the readability benefit without the downsides.
We also considered requiring parentheses on both the parameter list and the outside, e.g. ((int, str) -> bool). With this change, the example above becomes:
def make_adder() -> ((int) -> int): return lambda x: x + 1
We rejected this change because:
The outer parentheses only help readability in some cases, mostly when a callable type is used in return position. In many other cases they hurt readability rather than helping.
We agree that it might make sense to encourage outer parentheses in several cases, particularly callable types in function return annotations. But
We believe it is more appropriate to encourage this in style guides, linters, and autoformatters than to bake it into the parser and throw syntax errors.
Moreover, if a type is complicated enough that readability is a concern we can always use type aliases, for example:
IntToIntFunction: (int) -> int def make_adder() -> IntToIntFunction: return lambda x: x + 1
Making -> bind tighter than |
In order to allow both -> and | tokens in type expressions we had to choose precedence. In the current proposal, this is a function returning an optional boolean:
(int, str) -> bool | None # equivalent ot (int, str) -> (bool | None)
We considered having -> bind tighter so that instead the expression would parse as ((int, str) -> bool) | None. There are two advantages to this:
- It means we no would longer have to treat None | (int, str) -> bool as a syntax error.
- Looking at typeshed today, optional callable arguments are very common because using None as a default value is a standard Python idiom. Having -> bind tighter would make these easier to write.
We decided against this for a few reasons:
- The function header def f() -> int | None: ... is legal and indicates a function returning an optional int. To be consistent with function headers, callable types should do the same.
- TypeScript is the other popular language we know of that uses both -> and | tokens in type expressions, and they have | bind tighter. While we do not have to follow their lead, we prefer to do so.
- We do acknowledge that optional callable types are common and having | bind tighter forces extra parentheses, which makes these types harder to write. But code is read more often than written, and we believe that requiring the outer parentheses for an optional callable type like ((int, str) -> bool) | None is preferable for readability.
Introducing type-strings
Another idea was adding a new “special string” syntax and putting the type inside of it, for example t”(int, str) -> bool”. We rejected this because it is not as readable, and seems out of step with guidance from the Steering Council on ensuring that type expressions do not diverge from the rest of Python's syntax.
Improving Usability of the Indexed Callable Type
If we do not want to add new syntax for callable types, we could look at how to make the existing type easier to read. One proposal would be to make the builtin callable function indexable so that it could be used as a type:
callable[[int, str], bool]
This change would be analogous to PEP 585 that made built in collections like list and dict usable as types, and would make imports more convenient, but it wouldn't help readability of the types themselves much.
In order to reduce the number of brackets needed in complex callable types, it would be possible to allow tuples for the argument list:
callable[(int, str), bool]
This actually is a significant readability improvement for multi-argument functions, but the problem is that it makes callables with one arguments, which are the most common arity, hard to write: because (x) evaluates to x, they would have to be written like callable[(int,), bool]. We find this awkward.
Moreover, none of these ideas help as much with reducing verbosity as the current proposal, nor do they introduce as strong a visual cue as the -> between the parameter types and the return type.
Alternative Runtime Behaviors
The hard requirements on our runtime API are that:
- It must preserve backward compatibility with typing.Callable via __args__ and __params__.
- It must provide a structured API, which should be extensible if in the future we try to support named and variadic arguments.
Alternative APIs
We considered having the runtime data types.CallableType use a more structured API where there would be separate fields for posonlyargs and param_spec. The current proposal was was inspired by the inspect.Signature type.
We use "argument" in our field and type names, unlike "parameter" as in inspect.Signature, in order to avoid confusion with the callable_type.__parameters__ field from the legacy API that refers to type parameters rather than callable parameters.
Using the plain return type in __args__ for async types
It is debatable whether we are required to preserve backward compatiblity of __args__ for async callable types like async (int) -> str. The reason is that one could argue they are not expressible directly using typing.Callable, and therefore it would be fine to set __args__ as (int, int) rather than (int, typing.Awaitable[int]).
But we believe this would be problematic. By preserving the appearance of a backward-compatible API while actually breaking its semantics on async types, we would cause runtime type libraries that attempt to interpret Callable using __args__ to fail silently.
It is for this reason that we automatically wrap the return type in Awaitable.
Backward Compatibility
This PEP proposes a major syntax improvement over typing.Callable, but the static semantics are the same.
As such, the only thing we need for backward compatibility is to ensure that types specified via the new syntax behave the same as equivalent typing.Callable and typing.Concatenate values they intend to replace.
There is no particular interaction between this proposal and from __future__ import annotations - just like any other type annotation it will be unparsed to a string at module import, and typing.get_type_hints should correctly evaluate the resulting strings in cases where that is possible.
This is discussed in more detail in the Runtime Behavior section.
Reference Implementation
We have a working implementation of the AST and Grammar with tests verifying that the grammar proposed here has the desired behaviors.
The runtime behavior is not yet implemented. As discussed in the Runtime Behavior portion of the spec we have a detailed plan for both a backward-compatible API and a more structured API in a separate doc where we are also open to discussion and alternative ideas.
Open Issues
Details of the Runtime API
We have attempted to provide a complete behavior specification in the Runtime Behavior section of this PEP.
But there are probably more details that we will not realize we need to define until we build a full reference implementation.
Optimizing SyntaxError messages
The current reference implementation has a fully-functional parser and all edge cases presented here have been tested.
But there are some known cases where the errors are not as informative as we would like. For example, because (int, ...) -> bool is illegal but (int, ...) is a valid tuple, we currently produce a syntax error flagging the -> as the problem even though the real cause of the error is using ... as an argument type.
This is not part of the specification per se but is an important detail to address in our implementation. The solution will likely involve adding invalid_.* rules to python.gram and customizing error messages.
Resources
Background and History
PEP 484 specifies a very similar syntax for function type hint comments for use in code that needs to work on Python 2.7. For example:
def f(x, y): # type: (int, str) -> bool ...
At that time we used indexing operations to specify generic types like typing.Callable because we decided not to add syntax for types. However, we have since begun to do so, e.g. with PEP 604.
Maggie proposed better callable type syntax as part of a larger presentation on typing simplifications at the PyCon Typing Summit 2021.
Steven brought up this proposal on typing-sig. We had several meetings to discuss alternatives, and this presentation led us to the current proposal.
Pradeep brought this proposal to python-dev for feedback.
Acknowledgments
Thanks to the following people for their feedback on the PEP and help planning the reference implementation:
Alex Waygood, Eric Traut, Guido van Rossum, James Hilton-Balfe, Jelle Zijlstra, Maggie Moss, Tuomas Suutari, Shannon Zhu.
This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive. | https://www.python.org/dev/peps/pep-0677/ | CC-MAIN-2022-05 | refinedweb | 5,804 | 50.77 |
Cached Queries
The system automatically maintains a cache of prepared SQL statements (“queries”). This permits the re-execution of an SQL query without repeating the overhead of optimizing the query and developing a Query Plan. A cached query is created when certain SQL statements are prepared. Preparing a query occurs at runtime, not when the routine containing the SQL query code is compiled. Commonly, a prepare is immediately followed by the first execution of the SQL statement, though in Dynamic SQL it is possible to prepare a query without executing it. Subsequent executions ignore the prepare statement and instead access the cached query. To force a new prepare of an existing query it is necessary to purge the cached query.
All invocations of SQL create cached queries, whether invoked in an ObjectScript routine or a class method.
Dynamic SQL, ODBC, JDBC, and the $SYSTEM.SQL.DDLImport() method create a cached query when the query is prepared. The Management Portal execute SQL interface, the InterSystems SQL Shell, and the %SYSTEM.SQL.Execute() method use Dynamic SQL, and thus use a prepare operation to create cached queries.
They are listed in the Management Portal general Cached Queries listing for the namespace (or specified schema), the Management Portal Catalog Details Cached Queries listings for each table being accessed, and the SQL Statements listings. Dynamic SQL follows the cached query naming conventions described in this chapter.
Class Queries create a cached query upon prepare (%PrepareClassQuery() method) or first execution (CALL).
They are listed in the Management Portal general Cached Queries listing for the namespace. If the class query is defined in a Persistent class, the cached query is also listed in the Catalog Details Cached Queries for that class. It is not listed in the Catalog Details for the table(s) being accessed. It is not listed in the SQL Statements listings. Class queries follow the cached query naming conventions described in this chapter.
Embedded SQL creates a cached query upon first execution of the SQL code, or the initiation of code execution by invoking the OPEN command for a declared cursor. Embedded SQL cached queries are listed in the Management Portal SQL Statements listings. They are not listed in the Management Portal Cached Queries listings, nor do the follow the cached query naming conventions described in this chapter.
Cached queries of all types are deleted by all purge cached queries operations.
SQL query statements that generate a cached query are:
SELECT: a SELECT cached query is shown in the Catalog Details for its table. If the query references more than one table, the same cached query is listed for each referenced table. Purging the cached query from any one of these tables purges it from all tables. From the table’s Catalog Details you can select a cached query name to display cached query details, including Execute and Show Plan options. A SELECT cached query created by the $SYSTEM.SQL.Schema.ImportDDL("IRIS") method does not provide Execute and Show Plan options.
DECLARE name CURSOR FOR SELECT creates a cached query. However, cached query details do not include Execute and Show Plan options.
CALL: creates a cached query shown in the Cached Queries list for its schema.
INSERT, UPDATE, INSERT OR UPDATE, DELETE: create a cached query shown in the Catalog Details for its table.
TRUNCATE TABLE: creates a cached query shown in the Catalog Details for its table. Note that $SYSTEM.SQL.Schema.ImportDDL("IRIS") does not support TRUNCATE TABLE.
SET TRANSACTION, START TRANSACTION, %INTRANSACTION, COMMIT, ROLLBACK: create a cached query shown in the Cached Queries list for every schema in the namespace.
A cached query is created when you Prepare the query. For this reason, it is important not to put a %Prepare() method in a loop structure. A subsequent %Prepare() of the same query (differing only in specified literal values) uses the existing cached query rather than creating a new cached query.
Changing the SetMapSelectability() value for a table invalidates all existing cached queries that reference that table. A subsequent Prepare of an existing query creates a new cached query and removes the old cached query from the listing.
A cache query is deleted when you purge cached queries. Modifying a table definition automatically purges any queries that reference that table. Issuing a Prepare or Purge automatically requests an exclusive system-wide lock while the query cache metadata is updated. The System Administrator can modify the timeout value for the cached query lock.
The creation of a cached query is not part of a transaction. The creation of a cached query is not journaled.
Cached Queries Improve Performance
When you first prepare a query, the SQL Engine optimizes it and generates a program (a set of one or more InterSystems IRIS® data platform routines) that will execute the query. The optimized query text is then stored as a cached query class. If you subsequently attempt to execute the same (or a similar) query, the SQL Engine will find the cached query and directly execute the code for the query, bypassing the need to optimize and code generate.
Cached queries provide the following benefits:
Subsequent execution of frequently used queries is faster. More importantly, this performance boost is available automatically without having to code cumbersome stored procedures. Most relational database products recommend using only stored procedures for database access. This is not necessary with InterSystems IRIS.
A single cached query is used for similar queries, queries that differ only in their literal values. For example, SELECT TOP 5 Name FROM Sample.Person WHERE Name %STARTSWITH 'A' and SELECT TOP 1000 Name FROM Sample.Person WHERE Name %STARTSWITH 'Mc' only differ in the literal values for TOP and the %STARTSWITH condition. The cached query prepared for the first query is automatically used for the second query. For other considerations that result in two “identical” queries resulting in separate cached queries, see below.
The query cache is shared among all database users; if User 1 prepares a query, then User 1023 can take advantage of it.
The Query Optimizer is free to use more time to find the best solution for a given query as this price only has to be paid the first time a query is prepared.
InterSystems SQL stores all cached queries in a single location, the IRISLOCALDATA database. However, cached queries are namespace specific. Each cached query is identified with the namespace from which it was prepared (generated). You can only view or execute a cached query from within the namespace in which it was prepared. You can purge cached queries either for the current namespace or for all namespaces.
A cached query does not include comments. However, it can include comment options following the query text, such as /*#OPTIONS {"optionName":value} */.
Because a cached query uses an existing query plan, it provide continuity of operation for existing queries. Changes to the underlying tables such as adding indices or redefining the table optimization statistics have no effect on an existing cached query. For use of cached queries when changing a table definition, refer to the “SQL Statements and Frozen Plans” chapter in this manual.
Creating a Cached Query
When InterSystems IRIS Prepares a query it determines:
If the query matches a query already in the query cache. If not, it assigns an increment count to the query.
If the query prepares successfully. If not, it does not assign the increment count to a cached query name.
Otherwise, the increment count is assigned to a cached query name and the query is cached.
Cached Query Names
The SQL Engine assigns a unique class name to each cached query, with the following format:
%sqlcq.namespace.clsnnn
Where namespace is the current namespace, in capital letters, and nnn is a sequential integer. For example, %sqlcq.USER.cls16.
Cached queries are numbered sequentially on a per-namespace basis, starting with 1. The next available nnn sequential number depends on what numbers have been reserved or released:
A number is reserved when you begin to prepare a query if that query does not match an existing cached query. A query matches an existing cached query if they differ only in their literal values — subject to certain additional considerations: suppressed literal substitution, different comment options, or the situations described in “Separate Cached Queries”.
A number is reserved but not assigned if the query does not prepare successfully. Only queries that Prepare successfully are cached.
A number is reserved and assigned to a cached query if the query prepares successfully. This cached query is listed for every table referred to in the query, regardless of whether any data is accessed from that table. If a query does not refer to any tables, a cached query is created but cannot be listed or purged by table.
A number is released when a cached query is purged. This number becomes available as the next nnn sequential number. Purging individual cached queries associated with a table or purging all of the cached queries for a table releases the numbers assigned to those cached queries. Purging all cached queries in the namespace releases all of the numbers assigned to cached queries, including cached queries that do not reference a table, and numbers reserved but not assigned.
Purging cached queries resets the nnn integer. Integers are reused, but remaining cached queries are not renumbered. For example, a partial purge of cached queries might leave cls1, cls3, cls4, and cls7. Subsequent cached queries would be numbered cls2, cls5, cls6, and cls8.
A CALL statement may result in multiple cached queries. For example, the SQL statement CALL Sample.PersonSets('A','MA') results in the following cached queries:
%sqlcq.USER.cls1: CALL Sample . PersonSets ( ? , ? ) %sqlcq.USER.cls2: SELECT name , dob , spouse FROM sample . person WHERE name %STARTSWITH ? ORDER BY 1 %sqlcq.USER.cls3: SELECT name , age , home_city , home_state FROM sample . person WHERE home_state = ? ORDER BY 4 , 1
In Dynamic SQL, after preparing an SQL query (using the %Prepare() or %PrepareClassQuery() instance method) you can return the cached query name using the %Display() instance method or the %GetImplementationDetails() instance method. See Results of a Successful Prepare.
The cached query name is also a component of the result set OREF returned by the %Execute() instance method of the %SQL.Statement class (and the %CurrentResult property). Both of these methods of determining the cached query name are shown in the following example:
SET randtop=$RANDOM(10)+1 SET randage=$RANDOM(40)+1 SET myquery = "SELECT TOP ? Name,Age FROM Sample.Person WHERE Age < ?" SET tStatement = ##class(%SQL.Statement).%New() SET qStatus = tStatement.%Prepare(myquery) IF qStatus'=1 {WRITE "%Prepare failed:" DO $System.Status.DisplayError(qStatus) QUIT} SET x = tStatement.%GetImplementationDetails(.class,.text,.args) IF x=1 { WRITE "cached query name is: ",class,! } SET rset = tStatement.%Execute(randtop,randage) WRITE "result set OREF: ",rset.%CurrentResult,! DO rset.%Display() WRITE !,"A sample of ",randtop," rows, with age < ",randage
In this example, the number of rows selected (TOP clause) and the WHERE clause predicate value change with each query invocation, but the cached query name does not change.
Separate Cached Queries
Differences between two queries that shouldn’t affect query optimization nevertheless generate separate cached queries:
Different syntactic forms of the same function generate separate cached queries. Thus ASCII('x') and {fn ASCII('x')} generate separate cached queries, and {fn CURDATE()} and {fn CURDATE} generate separate cached queries.
A case-sensitive table alias or column alias value, and the presence or absence of the optional AS keyword generate separate cached queries. Thus ASCII('x'), ASCII('x') AChar, and ASCII('x') AS AChar generate separate cached queries.
Using a different ORDER BY clause.
Using TOP ALL instead of TOP with an integer value.
Literal Substitution
When the SQL Engine caches an SQL query, it performs literal substitution. The query in the query cache represents each literal with a “?” character, representing an input parameter. This means that queries that differ only in their literal values are represented by a single cached query. For example, the two queries:
SELECT TOP 11 Name FROM Sample.Person WHERE Name %STARTSWITH 'A'
SELECT TOP 5 Name FROM Sample.Person WHERE Name %STARTSWITH 'Mc'
Are both represented by a single cached query:
SELECT TOP ? Name FROM Sample.Person WHERE Name %STARTSWITH ?
This minimizes the size of the query cache, and means that query optimization does not need to be performed on queries that differ only in their literal values.
Literal values supplied using input host variables (for example, :myvar) and ? input parameters are also represented in the corresponding cached query with a “?” character. Therefore, the queries SELECT Name FROM t1 WHERE Name='Adam', SELECT Name FROM t1 WHERE Name=?, and SELECT Name FROM t1 WHERE Name=:namevar are all matching queries and generate a single cached query.
You can use the %GetImplementationDetails() method to determine which of these entities is represented by each “?” character for a specific prepare.
The following considerations apply to literal substitution:
Plus and minus signs specified as part of a literal generate separate cached queries. Thus ABS(7), ABS(-7), and ABS(+7) each generate a separate cached query. Multiple signs also generate separate cached queries: ABS(+?) and ABS(++?). For this reason, it is preferable to use an unsigned variable ABS(?) or ABS(:num), for which signed or unsigned numbers can be supplied without generating a separate cached query.
Precision and scale values usually do not take literal substitution. Thus ROUND(567.89,2) is cached as ROUND(?,2). However, the optional precision value in CURRENT_TIME(n), CURRENT_TIMESTAMP(n), GETDATE(n), and GETUTCDATE(n) does take literal substitution.
A boolean flag does not take literal substitution. Thus ROUND(567.89,2,0) is cached as ROUND(?,2,0) and ROUND(567.89,2,1) is cached as ROUND(?,2,1).
A literal used in an IS NULL or IS NOT NULL condition does not take literal substitution.
Any literal used in an ORDER BY clause does not take literal substitution. This is because ORDER BY can use an integer to specify a column position. Changing this integer would result in a fundamentally different query.
An alphabetic literal must be enclosed in single quotes. Some functions permit you to specify an alphabetic format code with or without quotes; only a quoted alphabetic format code takes literal substitution. Thus DATENAME(MONTH,64701) and DATENAME('MONTH',64701) are functionally identical, but the corresponding cached queries are DATENAME(MONTH,?) and DATENAME(?,?).
Functions that take a variable number of arguments generate separate cached queries for each argument count. Thus COALESCE(1,2) and COALESCE(1,2,3) generate separate cached queries.
DynamicSQLTypeList Comment Option
When matching queries, a comment option is treated as part of the query text. Therefore, a query that differs from an existing cached query in its comment options does not match the existing cached query. A comment option may be user-specified as part of the query, or generated and inserted by the SQL preprocessor before preparing the query.
If an SQL query contains literal values, the SQL preprocessor generates a DynamicSQLTypeList comment option, which it appends to the end of the cached query text. This comment option assigns a data type to each literal. Data types are listed in the order that the literals appear in the query. Only actual literals are listed, not input host variables or ? input parameters. The following is a typical example:
SELECT TOP 2 Name,Age FROM Sample.MyTest WHERE Name %STARTSWITH 'B' AND Age > 21.5
generates the cached query text:
SELECT TOP ? Name , Age FROM Sample . MyTest WHERE Name %STARTSWITH ? AND Age > ? /*#OPTIONS {"DynamicSQLTypeList":"10,1,11"} */
In this example, the literal 2 is listed as type 10 (integer), the literal “B” is listed as type 1 (string), and the literal 21.5 is listed as type 11 (numeric).
Note that the data type assignment is based solely on the literal value itself, not the data type of the associated field. For instance, in the above example Age is defined as data type integer, but the literal value 21.5 is listed as numeric. Because InterSystems IRIS converts numbers to canonical form, a literal value of 21.0 would be listed as integer, not numeric.
DynamicSQLTypeList returns the following data type values:
Because the DynamicSQLTypeList comment option is part of the query text, changing a literal so that it results in a different data type results in creating a separate cached query. For example, increasing or decreasing the length of a literal string so that it falls into a different range.
Literal Substitution and Performance
The SQL Engine performs literal substitution for each value of an IN predicate. A large number of IN predicate values can have a negative effect on cached query performance. A variable number of IN predicate values can result in multiple cached queries. Converting an IN predicate to an %INLIST predicate results in a predicate with only one literal substitution, regardless of the number of listed values. %INLIST also provides an order-of-magnitude SIZE argument, which SQL uses to optimize performance.
Suppressing Literal Substitution
This literal substitution can be suppressed. There are circumstances where you may wish to optimize on a literal value, and create a separate cached query for queries with that literal value. To suppress literal substitution, enclose the literal value in double parentheses. This is shown in the following example:
SELECT TOP 11 Name FROM Sample.Person WHERE Name %STARTSWITH (('A'))
Specifying a different %STARTSWITH value would generate a separate cached query. Note that suppression of literal substitution is specified separately for each literal. In the above example, specifying a different TOP value would not generate a separate cached query.
To suppress literal substitution of a signed number, specify syntax such as ABS(-((7))).
Different numbers of enclosing parentheses may also suppress literal substitution in some circumstances. InterSystems recommends always using double parentheses as the clearest and most consistent syntax for this purpose.
Cosharding Comment Option
If an SQL query specifies multiple sharded tables, the SQL preprocessor generates a Cosharding comment option, which it appends to the end of the cached query text. This Cosharding option shows whether or not the specified tables are cosharded.
In the following example, all three specified tables are cosharded:
/*#OPTIONS {"Cosharding":[["T1","T2","T3"]]} */
In the following example, none of the three specified tables are cosharded:
/*#OPTIONS {"Cosharding":[["T1"],["T2"],["T3"]]} */
In the following example, table T1 is not cosharded, but tables T2 and T3 are cosharded:
/*#OPTIONS {"Cosharding":[["T1"],["T2","T3"]]} */
Runtime Plan Choice
Runtime Plan Choice (RTPC) is a configuration option that allows the SQL optimizer to take advantage of outlier value information at run time (query execution time). Runtime Plan Choice is a system-wide SQL configuration option.
When RTPC is activated, preparing the query includes detecting whether the query contains a condition on a field that has an outlier value. If the prepare detects one or more outlier field conditions, the query is not sent to the optimizer. Instead, SQL generates a Runtime Plan Choice stub. At execution time, the optimizer uses this stub to choose which query plan to execute: a standard query plan that ignores outlier status, or an alternative query plan that optimizes for outlier status. If there are multiple outlier value conditions, the optimizer can choose from multiple alternative run time query plans.
When the query is prepared, SQL determines if it contains outlier field conditions. If so, it defers choosing a query plan until the query is executed. At prepare time it creates a standard SQL Statement and (for Dynamic SQL) a corresponding cached query, but defers the choice of whether to use this query plan or to create a different query plan until the query is executed. At prepare time, it creates what appear to be a standard SQL Statement, such as the following: DECLARE QRS CURSOR FOR SELECT Top ? Name,HaveContactInfo FROM Sample.MyTest WHERE HaveContactInfo=?, representing literal substitution variables with question marks. However, if you view the SQL Statement details, the Query Plan contains the statement “execution may cause creation of a different plan” At prepare time, a Dynamic SQL query also creates what appears to be a standard cached query; however, the cached query Show Plan option displays the Query Text with the SELECT %NORUNTIME keyword, indicating that this is a query plan that does not use RTPC.
When the query is executed (OPEN in Embedded SQL), SQL creates a second SQL Statement and a corresponding cached query. The SQL Statement has a hash generated name and generates a RTPC stub, such as the following: DECLARE C CURSOR FOR %NORUNTIME SELECT Top :%CallArgs(1) Name,HaveContactInfo FROM Sample.MyTest WHERE HaveContactInfo=:%CallArgs(2). The optimizer then uses this to generate a corresponding cached query. If the optimizer determines that outlier information provides no performance advantage, it creates a cached query identical to the cached query created at prepare time, and executes this cached query. However if the optimizer determines that using outlier information provides a performance advantage, it creates a cached query that suppresses literal substitution of outlier fields in the cached query. For example, if the HaveContactInfo field is an outlier field (the vast majority of records have the value ‘Yes’), the query SELECT Name,HaveContactInfo FROM t1 WHERE HaveContactInfo=? would result in the cached query: SELECT Name,HaveContactInfo FROM t1 WHERE HaveContactInfo=(('Yes')).
Note that RTPC query plan display differs based on the source of the SQL code:
The Management Portal SQL interface Show Plan button may display an alternative run time query plan because this Show Plan takes its SQL code from the SQL interface text box.
The SQL Statement, when selected, displays the Statement Details which includes the Query Plan. This Query Plan does not display an alternative run time query plan, but instead contains the text “execution may cause creation of a different plan” because it takes its SQL code from the statement index.
If RTPC is not activated, or the query does not contain appropriate outlier field conditions, the optimizer creates a standard SQL Statement and a corresponding cached query.
If an RTPC stub is frozen, all associated alternative run time query plans are also frozen. RTPC processing remains active for a frozen query even when the RTPC configuration option is turned off.
You can manually suppress literal substitution when writing the query by specifying parentheses: SELECT Name,HaveContactInfo FROM t1 WHERE HaveContactInfo=(('Yes')). If you suppress literal substitution of the outlier field in a condition, RTPC is not applied to the query. The optimizer creates a standard cached query.
Activating RTPC
You can configure RTPC system-wide using either the Management Portal or a class method. Note that changing the RTPC configuration setting purges all cached queries.
Using the Management Portal, configure the system-wide Optimize queries based on parameter values SQL setting. This option sets an appropriate combination of Runtime Plan Choice (RTPC) optimization and Bias Queries as Outlier (BQO) optimization.().
You can activate RTPC for all processes system-wide using the $SYSTEM.SQL.Util.SetOption() method, as follows: SET status=$SYSTEM.SQL.Util.SetOption("RTPC",flag,.oldval). The flag argument is a boolean used to set (1) or unset (0) RTPC. The oldvalue argument returns the prior RTPC setting as a boolean value.
Application of RTPC
The system applies RTPC to SELECT and CALL statements. It does not apply RTPC to INSERT, UPDATE, or DELETE statements.
The system applies RTPC to any field that Tune Table has determined to have an outlier value, when that field is specified in the following query contexts.
The outlier field is specified in a condition where it is compared to a literal. This comparison condition can be:
A WHERE clause condition using an equality (=), non-equality (!=), IN, or %INLIST predicate.
An ON clause join condition with an equality (=), non-equality (!=), IN, or %INLIST predicate.
If RTPC is applied, the optimizer determines at run time whether to apply the standard query plan or an alternative query plan.
RTPC is not applied if the query contains unresolved ? input parameters.
RTPC is not applied if the query specifies the literal value surrounded by double parentheses, suppressing literal substitution.
RTPC is not applied if the literal is supplied to the outlier field condition by a subquery. However, RTPC is applied if there is an outlier field condition within a subquery.
Overriding RTPC
You can override RTPC for a specific.
Cached Query Result Set
When you execute a cached query it creates a result set. A cached query result set is an Object instance. This means that the values you specify for literal substitution input parameters are stored as object properties. These object properties are referred to using i%PropName syntax.
Listing Cached Queries
You can count and list existing cached queries in the current namespace:
Displaying cached queries using the InterSystems IRIS Management Portal
Listing cached queries using the ^rINDEXSQL global
Exporting cached queries to a file using the ExportSQL^%qarDDLExport utility
Counting Cached Queries
You can determine the current number of cached queries for a table by invoking the GetCachedQueryTableCount() method of the %Library.SQLCatalog class. This is shown in the following example:
SET tbl="Sample.Person" SET num=##class(%Library.SQLCatalog).GetCachedQueryTableCount(tbl) IF num=0 {WRITE "There are no cached queries for ",tbl } ELSE {WRITE tbl," is associated with ",num," cached queries" }
Note that a query that references more than one table creates a single cached query. However, each of these tables counts this cached query separately. Therefore, the number of cached queries counted by table may be larger than the number of actual cached queries.
Displaying Cached Queries
You can view (and manage) the contents of the query cache using the InterSystems IRIS Management Portal. From System Explorer, select SQL. Select a namespace with the Switch option at the top of the page; this displays the list of available namespaces. On the left side of the screen open the Cached Queries folder. Selecting one of these cached queries displays the details.
The Query Type can be one of the following values:
%SQL.Statement Dynamic SQL: a Dynamic SQL query using %SQL.Statement.
ODBC/JDBC Statement: a dynamic query from either ODBC or JDBC.
Embedded SQL cached queries are not listed in this display.
When you successfully prepare an SQL statement, the system generates a new class that implements the statement. If you have set the Retain cached query source system-wide configuration option, the source code for this generated class is retained and can be opened for inspection using Studio. To do this, go to the InterSystems IRIS Management Portal. From System Administration, select Configuration, then SQL and Object Settings, then SQL. On this screen you can set the Retain cached query source option. If this option is not set (the default), the system generates and deploys the class and does not save the source code.
You can also set this system-wide option using the $SYSTEM.SQL.Util.SetOption() method, as follows: SET status=$SYSTEM.SQL.Util.SetOption("CachedQuerySaveSource",flag,.oldval). The flag argument is a boolean used to retain (1) or not retain (0) query source code after a cached query is compiled; the default is 0. To determine the current setting, call $SYSTEM.SQL.CurrentSettings().
Listing Cached Queries Using ^rINDEXSQL
You can use the ^rINDEXSQL global to list all of the cached queries and all of the SQL Statements for the current namespace:
ZWRITE ^rINDEXSQL("sqlidx",2)
A typical global in this list looks like this: ^rINDEXSQL("sqlidx",2,"%sqlcq.USER.cls4.1","oRuYrsuQDz72Q6dBJHa8QtWT/rQ=")="".
The third subscript is the location. For example, "%sqlcq.USER.cls4.1" is a cached query in the USER namespace; "Sample.MyTable.1" is an SQL Statement.
The fourth subscript is the Statement hash.
Exporting Cached Queries to a File
The following utility lists all of the cached queries for the current namespace to a text file.
ExportSQL^%qarDDLExport(file,fileOpenParam,eos,cachedQueries,classQueries,classMethods,routines,display)
The following is an example of evoking this cached queries export utility:
DO ExportSQL^%qarDDLExport("C:\temp\test\qcache.txt","WNS","GO",1,1,1,1,1)
When executed from the Terminal command line with display=1, export progress is displayed to the terminal screen, such as the following example:
Export SQL Text for Cached Query: %sqlcq.USER.cls14.. Done Export SQL Text for Cached Query: %sqlcq.USER.cls16.. Done Export SQL Text for Cached Query: %sqlcq.USER.cls17.. Done Export SQL Text for Cached Query: %sqlcq.USER.cls18.. Done Export SQL Text for Cached Query: %sqlcq.USER.cls19.. Done Export SQL statement for Class Query: Cinema.Film.TopCategory... Done Export SQL statement for Class Query: Cinema.Film.TopFilms... Done Export SQL statement for Class Query: Cinema.FilmCategory.CategoryName...Done Export SQL statement for Class Query: Cinema.Show.ShowTimes... Done Export SQL statement for Class Query: Cinema.TicketItem.ShowItem... Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%BuildAllFacts...Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%BuildTempFile...Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%Count...Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%DeleteFact...Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%ProcessFact...Done Export SQL statement from Class Method: Aviation.EventCube.Fact.%UpdateFacts...Done Export SQL statement from Class Method: Aviation.EventCube.Star1032357136.%Count...Done Export SQL statement from Class Method: Aviation.EventCube.Star1032357136.%GetDimensionProperty...Done Export SQL statement from Class Method: Aviation.EventCube.Star1035531339.%Count...Done Export SQL statement from Class Method: Aviation.EventCube.Star1035531339.%GetDimensionProperty...Done 20 SQL statements exported to script file C:\temp\test\qcache.txt
The created export file contains entries such as the following:
-- SQL statement from Cached Query %sqlcq.USER.cls30 SELECT TOP ? Name , Home_State , Age , AVG ( Age ) AS AvgAge FROM Sample . Person ORDER BY Home_State GO
-- SQL statement from Class Query Cinema.Film.TopCategory #import Cinema SELECT TOP 3 ID, Description, Length, Rating, Title, Category->CategoryName FROM Film WHERE (PlayingNow = 1) AND (Category = :P1) ORDER BY TicketsSold DESC GO
-- SQL statement(s) from Class Method Aviation.EventCube.Fact.%Count #import Aviation.EventCube SELECT COUNT(*) INTO :tCount FROM Aviation_EventCube.Fact GO
This cached queries listing can be used as input to the Query Optimization Plans utility.
Executing Cached Queries
From Dynamic SQL: A %SQL.Statement Prepare operation (%Prepare(), %PrepareClassQuery(), or %ExecDirect()) creates a cached query. A Dynamic SQL %Execute() method using the same instance executes the most recently prepared cached query.
From the Terminal: You can directly execute a cached query using the ExecuteCachedQuery() method of the $SYSTEM.SQL class. This method allows you to specify input parameter values and to limit the number of rows to output. You can execute a Dynamic SQL %SQL.Statement cached query or an xDBC cached query from the Terminal command line. This method is primarily useful for testing an existing cached query on a limited subset of the data.
From the Management Portal SQL Interface: Follow the “Displaying Cached Queries” instructions above. From the selected cached query’s Catalog Details tab, click the Execute link.
Cached Query Lock
Issuing a Prepare or Purge statement automatically requests an exclusive system-wide lock while the cached query metadata is updated. SQL supports the system-wide CachedQueryLockTimeout option of the $SYSTEM.SQL.Util.SetOption() method. This option governs lock timeout when attempting to acquire a lock on cached query metadata. The default is 120 seconds. This is significantly longer than the standard SQL lock timeout, which defaults to 10 seconds. A System Administrator may need to modify this cached query lock timeout on systems with large numbers of concurrent Prepare and Purge operations, especially on a system which performs bulk purges involving a large number (several thousand) cached queries.
SET status=$SYSTEM.SQL.Util.SetOption("CachedQueryLockTimeout",seconds,.oldval) method sets the timeout value system-wide:
SetCQTimeout SET status=$SYSTEM.SQL.Util.SetOption("CachedQueryLockTimeout",150,.oldval) WRITE oldval," initial value cached query seconds",!! SetCQTimeoutAgain SET status=$SYSTEM.SQL.Util.SetOption("CachedQueryLockTimeout",180,.oldval2) WRITE oldval2," prior value cached query seconds",!! ResetCQTimeoutToDefault SET status=$SYSTEM.SQL.Util.SetOption("CachedQueryLockTimeout",oldval,.oldval3)
CachedQueryLockTimeout sets the cached query lock timeout for all new processes system-wide. It does not change the cached query lock timeout for existing processes.
Purging Cached Queries
Whenever you modify (alter or delete) a table definition, any queries based on that table are automatically purged from the query cache on the local system. If you recompile a persistent class, any queries that use that class are automatically purged from the query cache on the local system.
You can explicitly purge cached queries via the Management Portal using one of the Purge Cached Queries options. You can purge cached queries using the SQL Shell PURGE command.
You can use the $SYSTEM.SQL.Purge(n) method to explicitly purge cached queries that have not been recently used. Specifying n number of days purges all cached queries in the current namespace that have not been used (prepared) within the last n days. Specifying an n value of 0 or "" purges all cached queries in the current namespace. For example, if you issue a $SYSTEM.SQL.Purge(30) method on May 11, 2018, it will purge only the cached queries that were last prepared before April 11, 2018. A cached query that was last prepared exactly 30 days ago (April 11, in this example) would not be purged.
You can also purge cached queries using the following methods:
$SYSTEM.SQL.PurgeCQClass() purges one or more cached queries by name in the current namespace. You can specify cached query names as a comma-separated list. Cached query names are case sensitive; the namespace name must be specified in all-capital letters. The specified cached query name or list of cached query names must be enclosed with quotation marks.
$SYSTEM.SQL.PurgeForTable() purges all cached queries in the current namespace that reference the specified table. The schema and table name are not case-sensitive.
$SYSTEM.SQL.PurgeAllNamespaces() purges all cached queries in all namespaces on the current system. Note that when you delete a namespace, its associated cached queries are not purged. Executing PurgeAllNamespaces() checks if there are any cached queries associated with namespaces that no longer exist; if so, these cached queries are purged.
To purge all cached queries in the current namespace, use the Management Portal Purge ALL queries for this namespace option.
Purging a cached query also purges related query performance statistics.
Purging a cached query also purges related SQL Statement list entries. SQL Statements listed in the Management Portal may not be immediately purged, you may have to press the Clean stale button to purge these entries from the SQL Statements list.
When you change the system-wide default schema name, the system automatically purges all cached queries in all namespaces on the system.
Remote Systems
Purging a cached query on a local system does not purge copies of that cached query on mirror systems. Copies of a purged cached query on a remote system must be manually purged.
When a persistent class is modified and recompiled, the local cached queries based on that class are automatically purged. InterSystems IRIS does not automatically purge copies of those cached queries on remote systems. This could mean that some cached queries on a remote system are “stale” (no longer valid). However, when a remote system attempts to use a cached query, the remote system checks whether any of the persistent classes that the query references have been recompiled. If a persistent class on the local system has been recompiled, the remote system automatically purges and recreates the stale cached query before attempting to use it.
SQL Commands That Are Not Cached
The following non-query SQL commands are not cached; they are purged immediately after use:
Data Definition Language (DDL): CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE VIEW, ALTER VIEW, DROP VIEW, CREATE INDEX, DROP INDEX, CREATE FUNCTION, CREATE METHOD, CREATE PROCEDURE, CREATE QUERY, DROP FUNCTION, DROP METHOD, DROP PROCEDURE, DROP QUERY, CREATE TRIGGER, DROP TRIGGER, CREATE DATABASE, USE DATABASE, DROP DATABASE
User, Role, and Privilege: CREATE USER, ALTER USER, DROP USER, CREATE ROLE, DROP ROLE, GRANT, REVOKE, %CHECKPRIV
Locking: LOCK TABLE, UNLOCK TABLE
Miscellaneous: SAVEPOINT, SET OPTION
Note that if you issue one of these SQL commands from the Management Portal Execute Query interface, the Performance information includes text such as the following: Cached Query: %sqlcq.USER.cls16. This appears in indicate that a cached query name was assigned. However, this cached query name is not a link. No cached query was created, and the incremental cached query number .cls16 was not set aside. InterSystems SQL assigns this cached query number to the next SQL command issued. | https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=GSQLOPT_cachedqueries | CC-MAIN-2020-45 | refinedweb | 6,088 | 56.35 |
strncat() prototype
char* strncat( char* dest, const char* src, size_t count );
The
strncat() function takes three arguments: dest, src and count. This function appends a maximum of count characters of the string pointed to by srcncat() Parameters
dest: Pointer to a null terminating string to append to.
src: Pointer to a null terminating string that is to be appended.
count: Maximum numbers of characters to copy.
strncat() Return value
The strncat() function returns dest, the pointer to the destination string.
Example: How strncat() function works
#include <cstring> #include <iostream> using namespace std; int main() { char dest[50] = "Using strncat function,"; char src[50] = " this part is added and this is ignored"; strncat(dest, src, 19); cout << dest ; return 0; }
When you run the program, the output will be:
Using strncat function, this part is added | https://www.programiz.com/cpp-programming/library-function/cstring/strncat | CC-MAIN-2020-16 | refinedweb | 135 | 57.61 |
The Pure attribute was added to .NET in version 4 as part of the Code Contracts initiative. Use of the PureAttribute Class indicates that a type or method is functionally "pure", i.e. it does not make any visible state changes. The idea was that Pure and other attributes/functions in the System.Diagnostics.Contracts namespace would be used to decorate classes and methods throughout .NET's Base Class Library (BCL).
Once that was done, the Code Contracts tooling could be used to perform advanced analysis and bug detection. However, the Code Contracts project failed. While there were several reasons for this, some of the more compelling ones include:
- The syntax was verbose, requiring full lines where developers would prefer to use attributes.
- The contracts were not exposed via reflection, eliminating the possibility for 3rd party tooling.
- The contracts were not exposed XML docs, meaning they could not be automatically included in documentation.
- When a contract was violated for any reason, the application crashed immediately with no chance for logging or corrective action.
- The tooling was outside the normal compilation path, requiring additional steps and making the use of build servers more difficult.
Since the end of the Code Contracts project, the Roslyn analyzers have taken over as the static analysis tool of choice. Roslyn analyzers are part of the normal VB/C# compiler pipeline, so their use doesn't add any complexity to the build process.
This leaves the question, "What to do with the code contract attributes?" Dan Moseley of Microsoft reports, "We don't use or enforce those and generally have been removing contract annotations."
Andrew Arnott, another Microsoft employee, counters with the idea that the Pure attribute specifically could still be of use:
But [Pure] is useful because one can write analyzers that will flag a warning when a [Pure] method is executed without doing anything with the result.
The basic idea behind this is any method marked as Pure should never have side effects. Its only purpose is to return a value. If it returns a value, and that value is subsequently ignored, then there was no reason to call the method in the first place. Therefore, the warning would always indicate a mistake.
And that's what should happen. If you are using Microsoft.CodeQuality.Analyzers, then rule CA1806 will warn you about ignoring the results of a Pure method. But there are two catches:
First, it cannot warn you if a method is improperly marked as Pure. That capability is theoretically possible, as Pure methods should only read from other pure methods.
Secondly, you must include the compiler constant "CONTRACTS_FULL". The Pure attribute itself is marked with a Conditional attribute. This means that without the aforementioned compiler constant, the Pure attribute will be stripped away from your compiled code. This actually happened to some methods in .NET's immutable collections library.
InfoQ asks: What other Code Contracts features would you like to see in modern .NET development?
Community comments | https://www.infoq.com/news/2019/01/pure-attribute-net-core/ | CC-MAIN-2022-05 | refinedweb | 496 | 57.06 |
Pre-trip orientation weekend
Monday, 25. August 2008, 12:58:47
One of the big part of this formation was about the Guatemala reality. Their history, the Spanish conquest of the Mayas, the 1960-1996 civil war, etc. We also learned about the 21st century Mayas who still today form the majority of the population with the Ladinos(Mixed aborigine). What I retained the most about this civilization, was the fact that the are a proud population loving their country who prefer to live as refugees in their own land or beg in the street than leaving their birthplace.
The rest of the weekend was used to talk about the practical aspects of the trip: The humanitarian projects, A typical day of work, The security precautions we need to take while working in the most criminal part of the capitol, etc.
To conclude this short weekend report I would like to talk about one of the trainer who was there: Hugo, a Guatemalan political refugee. This authentic aboriginal really gave me the taste of Guatemala with his amazing knowledge about the politics, culture and history of his country and with his interesting and funny way of explaining it. He became even more funnier Saturday night when a few of us sat around a camp fire to talk and have a couple of beers. Nothing beats a half drunk Guatemalan telling Newfie jokes!
Although, later that night the conversation took a more serious but interesting turn when we talked about men and women respect and relationships. First, the different cultural realities appeared between our two countries but soon after, many different perceptions about love and respect appeared among the Quebecois group itself...
No consensus was found when I went to bed that night, but on my way to the dormitory, I saw a shooting star and I made a wish.
gdare # 25. August 2008, 17:16
Cynthia23 # 25. August 2008, 18:01
cakkleberrylane # 25. August 2008, 19:38
hungryghost # 25. August 2008, 20:22
good luck with the rest of the orientations. It sounds like an eye-opener.
And the wish..may it come true.
volkuro # 25. August 2008, 23:48
like the organizers of this mission clearly made us understand, the work that will do there will help the people there somehow but no miracle will be done. But it's not the most important part of this trip because the real motive behind this project is to sensitize more fortunate people like us to the third world countries realities and by this, they hope that we will become ambassadors of socially responsible consumption behaviours like buying fair trade certified products.
volkuro # 25. August 2008, 23:48
But like I said to Darko, the more important gestures are the ones anyone can do on a daily basis, you don't have to go to Guatemala to make this planet a better place too!
volkuro # 25. August 2008, 23:50
And you should try it too! And the age is not a factor. This year, with this organization, 275 participants will experiment this mind-evolving experience and among those 275 participants, I would say that 2/3 of them are over 55 years old!
And one of the most interesting trip companion I have met during my orientation weekend is a 71 years old man who has worked with his hands all his life and has a heart full of compassion. It's funny because I was probably the youngest participant and him, the oldest but we had a good contact right from the start and I even invited him to come to my place when he will go visit his son living nearby.
volkuro # 25. August 2008, 23:51
Ok now you have to explain me why you had to go to Thetford Mines?? There is nothing to do there!
Yes I hope my wish will come true...
sanshan # 26. August 2008, 00:01
volkuro # 26. August 2008, 00:40
hungryghost # 26. August 2008, 02:49
I was young then. I was foolish then. But not anymore. Now, I'm just old, cynical and bitter. And I love it.
sanshan # 26. August 2008, 03:28
volkuro # 26. August 2008, 12:13
12 years ago? You were in your mid-twenties, eh Hungry?
cakkleberrylane # 26. August 2008, 12:29
hungryghost # 26. August 2008, 14:57
Cynthia23 # 26. August 2008, 17:26
volkuro # 28. August 2008, 05:10
FrogBoots # 2. September 2008, 18:10
I look forward to hearing about your trip, when you return (with many photos?).
Mickeyjoe_irl # 2. September 2008, 23:45
I'm glad to head you had such a good weekend. Sounds like you will really enjoy Guatemala. | http://my.opera.com/volkuro/blog/2008/08/25/pre-trip-weekend | crawl-002 | refinedweb | 780 | 72.66 |
Brian has blogged about some of the smaller features in the latest release of F# which weren't explicitly called out in the detailed release notes.
I'll add a few here as well:
A note on version numbers
A note on .fsproj file portability
PowerPack: Adding "module" declarations to FsLex and FsYacc
Power Pack: Unicode Lexing
PowerPack: HashMultiMap constructor needs HashIdentity.Structural parameter
PowerPack: Explicit "open Microsoft.FShap.Math" needed for "complex"
A note on version numbers. In previous releases of F# we've used one version number for everything: language, library, power pack etc. This doesn't make quite so much sense when we now ship F# bits for use with both .NET 2.0 and 4.0. On the whole you won't need to be aware of this difference, but in this release we use:
You'll also see 1.9.7.4 reported as the F# compiler version number for VS2010, and 1.9.7.8 for the compiler in the CTP ZIP and MSI. These compilers are the same apart from some very minor differences such as this.
FSharp.Core.dll has version number 2.0.0.0 or 4.0.0.0 in this release, depending on whether you're running on .NET 2.0 or 4.0. For .NET 4.0 references to the former are redirected to the latter automatically.
.fsproj files
For various reasons unrelated to F#, Visual Studio project files (.fsproj, .csproj etc.) can't be authored in a way that makes them imediately usable with both VS2008 and VS2010. I personally prefer to edit project files by hand, and if you don't mind doing that, then to make an F# VS2008 project file usable with VS2010 you just have to do two things:
<Import Project="$(MSBuildExtensionsPath)\FSharp\1.0\FSharp.PowerPack.Targets" />
with
<Import Project="$(ProgramFiles)\Microsoft F#\v4.0\Microsoft.FSharp.Targets" />
at the bottom of the file. You may need to adjust some of the contents of the files as well, particularly project references.
The F# Power Pack includes tools fslex and fsyacc, which are lexer generators and parser generators. You can use these in F# projects using an entry like the following in your .fsproj file:
<FsYacc Include="Parser.fsy"> <OtherFlags>--module Parser</OtherFlags> </FsYacc>
<FsLex Include="Lexer.fsl" > <OtherFlags>--unicode</OtherFlags> </FsLex>
The "module" argument to FsYacc is recommended because F# now requests that you prefix compiled .fs files with a namespace or module declaration. FsYacc must add this to both generated .fs and .fsi. You can also add "--internal" if you want this module to be internal.
To specify a module declaration for an FsLex file, use a definition at the top of the .fsl file, e.g.
lex.fsl:
{
module internal Microsoft.FSharp.Compiler.Lexer
....
The different ways of treating this for FsLex and FsYacc are a little non-orthogonal, but this is how the F# Power Pack does work for this release, and we'll continue to support this going forward.
Since we're on the topic of lexing and the power pack, we may as well mention unicode lexing. The "unicode" argument to FsLex is optional, but if enabled generates a unicode lexer.
A unicode lexer works with a LexBuffer<char> rather than LexBuffer<byte>. This means extracting the text from of a lexeme is a little different. There are basically two ways:
lexbuf.Lexeme -- returns a character array
LexBuffer<_>.LexemeString lexbuf -- returns a string
For example, the MegaCalc example in the F# tutorial includes this rule:
| ['-']?digit+ { INT32 (Int32.Parse(LexBuffer<_>.LexemeString lexbuf)) }
In a unicode lexer, you can use Unicode character classes and individual Unicode characters in your rules. For example, the following may be used as definitions in an FsLex file (note, these are definitions in the FsLex domain specific language, and not F# code)
let letter = '\Lu' | '\Ll' | '\Lt' | '\Lm' | '\Lo' | '\Nl'
let surrogateChar = '\Cs'
let digit = '\Nd'
let connecting_char = '\Pc'
let combining_char = '\Mn' | '\Mc'
let formatting_char = '\Cf'
let ident_start_char =
letter | '_'
let ident_char =
letter
| connecting_char
| combining_char
| formatting_char
| digit
| ['\'']
PowerPack: HashMultiMap constructor needs HashIdentity.Structural parameter.
PowerPack: Explicit "open Microsoft.FShap.Math" needed for "complex"
The F# Power Pack includes a complex type and a function "complex" for making complex number values from rectangular coordinates. You now need to both reference the F# Power Pack and use "open Microsoft.FSharp.Math" to acccess this function..
The F# Power Pack includes a complex type and a function "complex" for making complex number values from rectangular coordinates. You now need to both reference the F# Power Pack and use "open Microsoft.FSharp.Math" to acccess this function. | http://blogs.msdn.com/b/dsyme/archive/2009/10/21/some-smaller-features-in-the-latest-release-of-f.aspx?Redirected=true | CC-MAIN-2014-23 | refinedweb | 772 | 57.87 |
i know there is atoi and atof for string to int, and double...but wat bout for bool?
Printable View
i know there is atoi and atof for string to int, and double...but wat bout for bool?
i found it i think....i'll post it here, incase anyone want's it too....
atob()
Not standard.
Use a stringstream. It will parse "1" and "true" to true, "0" and "false" to false, and everything to an error state.
Edit: atob might be in the C99 standard. But it is not in any C++ standard.
yea..the function didn't work..i was checkin that string consists of only a 1 or 0 then converting it to atob but didn't work...
how exactly do use that function u mentioned.....?
Nvm...
Something like this you mean?
Output 1:Output 1:Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
bool val = true;
cout << "Enter a boolean value (true/false): "
cin >> boolalpha >> val;
cout << "You entered: " << boolalpha << val << endl;
return 0;
}
Output 2:Output 2:Code:
Enter a boolean value (true/false): false
You entered: false
The strings entered via the cin need to be in all lowercase for that to work I think.The strings entered via the cin need to be in all lowercase for that to work I think.Code:
Enter a boolean value (true/false): true
You entered: true
To be precise, the string entered needs to case-sensitively match either the return value of truename() or of falsename(), both methods of the numpunct facet of the stream locale. These return values are "true" and "false" for the C locale. A German locale might set them to "wahr" and "falsch". | http://cboard.cprogramming.com/cplusplus-programming/65776-string-bool-printable-thread.html | CC-MAIN-2015-27 | refinedweb | 284 | 83.36 |
Here is the code:
from pyspark.sql import SQLContext from pyspark.context import SparkContext from pyspark.sql.types import * from typing import List sc = SparkContext() sqlContext = SQLContext.getOrCreate(sc) schema = StructType([StructField('id', LongType(), True), StructField('gid', LongType(), True), StructField('pid', LongType(), True), StructField('firstlogin', IntegerType(), True) ]) row = ['2', '29', '29', '29'] df = sqlContext.createDataFrame(row, schema) df.show()
It will report error after running ‘cat xxx.py|bin/pyspark’:
TypeError: StructType can not accept object '2' in type
I used to think it was because ‘2’ is a string, so I changed ‘row’ to be ‘[2, 29, 29, 29]’. But the error also changed to:
TypeError: StructType can not accept object 2 in type
Then I searched on google, and find this article. Looks like I forgot to transfer ‘list’ of python to ‘RDD’ of Apache Spark.
But at last, I found the real reason: I just need to add ‘[]’ between my ‘list’!
The right code is here:
row = ['2', '29', '29', '29'] df = sqlContext.createDataFrame([row], schema) | http://donghao.org/tag/pyspark/ | CC-MAIN-2020-50 | refinedweb | 169 | 67.25 |
Basic Ethereum Smart Contract Syntax
If you plan to do any Ethereum development, you’ll likely be using Solidity, one of the most popular programming languages for smart contracts. Let’s take a look at some basic Solidity syntax. When you write Solidity source code, you save that code in a file with the extension .sol.
A Solidity program has several main sections, as follows:
- Pragma: This tells Solidity what versions of the compiler are valid to compile this file.
- Import: An import defines an external file that contains code that your smart contract needs.
- Contract(s): This section is where the body of your smart contract code resides.
Declaring valid compiler version in Ethereum smart contracts
The
pragma directive should be the first line of code in a Solidity file. Because the Solidity language is still maturing, it is common for new compiler versions to include changes that would fail to compile older programs. The
pragma directive helps avoid compiler failures due to using a newer compiler.
Here is the syntax for the
pragma directive:
pragma Solidity <<version number>>;
Here is a sample
pragma directive:
pragma Solidity ^0.4.24;
All statements in Solidity end with a semicolon.
The version number starts with a 0, followed by a major build number and a minor build number. For example, the version number 0.4.24 refers to major build 4 and minor build 24. The caret symbol (^) before the version number tells Solidity that it can use the latest build in a major version range. In the preceding example, Solidity can use a compiler from any build in the version 4 build range. This is a way to tell readers that your program was written for 0.4.24 but will still compile for subsequent version 4 builds.
Although using the caret in the
pragma directive provides flexibility, it is a better practice to drop the caret and tell Solidity exactly what compiler version you expect.
Commenting your Solidity code
Adding comments to your code is an extra step that adds a professional look and feel to your Solidity code. A well-commented source code file is easier to read and understand and helps other developers quickly understand what your code is supposed to do. Even simple comments can cut down on the time required to fix bugs or add new functionality. Comments can also provide input for utilities to generate documentation for your smart contracts.
You can use single-line or multiline regular comments. Single-line comments start with two forward slashes. Multiline comments start with the
/* characters and end with the
*/ characters. Here is an example of Solidity comments:
// Here is a single line Solidity comment /* I have a lot more to say with this comment, so I’ll use a multiline comment. The compiler will ignore everything after the opening comment characters, until it sees the closing comment characters. */
A third type of Solidity comment is called the Ethereum Natural Specification (NatSpec) directive. You can use NatSpec to provide information about your code for documentation generators to use to create formatted documentation the describes your smart contracts. NatSpec directives start with three forward slashes and include special tags with data for the documentation. Here is an example of using NatSpec directives:
/// @title Greeter smart contract /// @author Joe Programmer /// @notice This code takes a person's name and says hello /// @param name The name of the caller /// @return greeting The greeting with the caller's name
Importing external code into your Ethereum smart contract
The import section is optional but can be powerful when used correctly in your Ethereum smart contract. If your smart contract needs to refer to code in other files, you’ll have to import those other files first. Importing files makes it as though you copied the other code into the current file. Using imports helps you avoid actually copying code from one place to another. If you need to access code, just import the Solidity file that contains it.
The syntax for importing other files is simple. You use the
import keyword and then provide the filename for the file you want to import. For example, to import the file myToken.sol, use this syntax:
Import 'myToken.sol';
Defining your Ethereum smart contracts
In the last main section of Solidity, you define the contents of your smart contract. It starts with the keyword
contract and contains all of the functional code in your smart contract. You can have multiple
contract sections in Solidity. That means a single .sol file can define multiple contracts. Here is an example
contract section:
contract HelloWorld { string private helloMessage = "Hello world"; function getHelloMessage() public view returns (string) { return helloMessage; } }
Inside the
contract section is where you define all of your variables, structures, events, and functions. There’s a lot more to the
contract section of your code, but for now, you know how to set up a Solidity smart contract.
Once you master the basics of Solidity, you can continue to develop more complex code and the sky’s the limit. | https://www.dummies.com/personal-finance/basic-ethereum-smart-contract-syntax/ | CC-MAIN-2019-47 | refinedweb | 843 | 54.12 |
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
Vagrant, Puppet & Chef #FTW: Managing Development Environments, Made Easy40:38 with Thijs Feryn
Everyone has used the term and is suitable for both individual developers and development teams. This talk will cover the basics of Vagrant including a brief introduction of configuration management tools like Puppet and Chef to provision your machines. "vagrant up" will be a command you'll learn to love. Aimed at developers looking for an easy way to manage their development environment and sharing it with team members, you'll learn Hassle-free setup of your development environment, how to improve collaboration and avoid dependency clashes between different projects, moving one step closer to continuous delivery.
- 0:00
[MUSIC]
- 0:11
Hello everyone.
- 0:13
Welcome to FOWA.
- 0:14
How are we doing so far?
- 0:16
Let's see some hands, let's see some thumbs.
- 0:17
Are we doing fine?
- 0:19
How was the schedule, how was the coffee?
- 0:22
How is the vibe, everything doing great?
- 0:24
Okay let's start off.
- 0:26
As I mentioned my name is Thijs and if you
- 0:28
want to follow me on Twitter you can do so.
- 0:30
This is my Twitter handle my full name.
- 0:31
I know it's a bit of a weird name but that's a Belgian thing.
- 0:35
I'm a tech evangelist at a company called Combell we
- 0:37
do web hosting, and as Ian mentioned I'm also involved with
- 0:41
the PHP community run a local community called PHP Benelux,
- 0:45
where we just run the Belgian, Dutch, and Luxembourg PHP community.
- 0:49
Not much happening in Luxembourg, though.
- 0:51
So let's talk about Vagrant right now.
- 0:54
Let's see a show of hands, who uses Vagrant right now?
- 0:56
[SOUND] Oh, that's interesting, that's good.
- 1:01
Cuz maybe you'll learn a thing or two.
- 1:03
Now, Vagrant, and that's a definition I got
- 1:05
off the site, allows you to create and configure
- 1:08
lightweight, reproducible, and portable development environments and I've
- 1:12
marked development environments because that's what it's all about.
- 1:15
It's not about having a production system up and running or a staging system.
- 1:19
No, it's about the box you develop your code on.
- 1:22
Though it's written in Ruby by Mitchell Hashimoto in 2010.
- 1:26
And it's actually an orchestration layer, on top of, first of all, Virtual Box.
- 1:30
And in later stages, they added support for vmware.
- 1:33
So it's basically a scriptable way of maintaining your virtual machine.
- 1:37
So let's see some more show of hands.
- 1:40
Who develops codes on its local machine?
- 1:42
Let's say, WAMP, MAMP kind of stuff.
- 1:46
Oh.
- 1:46
That's a lot of people.
- 1:48
Sorry.
- 1:48
You are disappointing me with that, but hopefully at
- 1:50
the end of this talk we will be changing this.
- 1:52
Now, who has a separate development, virtual environment on its local machine?
- 2:00
I asked the question, who uses Vagrant.
- 2:01
I see more hands right now, so that means you are doing it differently.
- 2:04
How are you doing it?
- 2:05
Just shout out.
- 2:08
Who uses Virtual Box without Vagrant?
- 2:12
VMware fusion or regular VMware.
- 2:15
Okay.
- 2:16
So maybe at the end of this talk you'll be using
- 2:18
this nice little tool to easily deploy, create and manage your VMs.
- 2:24
So who uses a remote development box at the office?
- 2:28
Okay.
- 2:28
It's perfectly viable.
- 2:31
So it, let's get back to Vagrant.
- 2:33
Vagrant tries to solve a specific problem, so why would you use Vagrant?
- 2:36
This is the main reason why we do it, we all
- 2:38
know the guise it works on my machine, and then you have
- 2:41
this awful joke, well, backup your laptops if you're gonna put
- 2:43
your laptop in production, this is what we're trying to avoid here.
- 2:46
I work at a hosting company.
- 2:48
I've did six and a half years of tech support, and my,
- 2:51
I have to worry about other people's code, and that's a bad thing.
- 2:54
That's a really bad thing.
- 2:55
And, other people say, well it works on
- 2:56
my machine, why doesn't it work on your server?
- 2:58
So, we're trying to avoid that, and that is actually the main goal of this talk.
- 3:02
This is what we're here for, or what I'm here for.
- 3:05
So wanna do is, have an environment per project, not
- 3:07
a monolithic system on which you run all your code.
- 3:10
Cuz some code is gonna run a specific version
- 3:12
of PHP, or Ruby, or Python, or whatever you use.
- 3:15
Some things will be clashing, so you want sort of separate
- 3:19
silos per project it can easily set up, easily tear down.
- 3:23
And easily to script.
- 3:24
And what you wanna do is, if you script
- 3:26
it, it needs to be in a very understandable way.
- 3:28
It shouldn't be really complicated, like complicated XML now.
- 3:31
Just a file with a certain markup that says how you want your machine being done.
- 3:35
What software should needs be configured.
- 3:38
All, all sorts of properties.
- 3:39
And make sure that your development is like test, staging and production.
- 3:43
I added the tilde.
- 3:44
It's, you'll never, or hardly ever have an exact copy of production.
- 3:49
Having an exact 100% copy is, ambitious.
- 3:54
But if it's very similar to test staging and production, at least you
- 3:58
can get your hopes up that your code will be working on that system.
- 4:01
So, easy to define, transport, and also and this is an important one, easy to
- 4:04
tear down as well, because all these
- 4:07
images, all these virtual images will consume resources.
- 4:10
Especially disk.
- 4:11
And if you're done working on a project for a while, you might wanna tear
- 4:14
it down and work on something else, And this is an important one as well, here.
- 4:19
Shared across the team, so that configuration
- 4:21
which I will show you later on.
- 4:22
You can just transport that along in your
- 4:25
version control system, shared amongst your team members.
- 4:28
And if we would run Vagrant, and I hope you can read this.
- 4:30
I tried to make it, the print as big as possible.
- 4:32
If you run the Vagrant command, because it's basically a command line
- 4:36
tool, if you run it, it will show you a bunch of options.
- 4:39
And this is what this talk will be about, showing what
- 4:40
these options mean and how we can reach the end goal.
- 4:44
So, if you run Vagrant in it, because that's the main one we're gonna do.
- 4:48
And it's, it's such an easy job, right, being in it?
- 4:51
In it, using the term in it here.
- 4:52
I'll be light on the jokes.
- 4:53
You had plenty of jokes during the opening keynote I guess.
- 4:56
So so vagrant in it if you run that
- 4:58
one it will give you some verbose information on how
- 5:01
you can create your Vagrant file and what does that
- 5:03
Vagrant file do because that's an important one to know.
- 5:06
Vagrant file is a, that's scripted way of selecting a base box,
- 5:10
and a base box is what the next chapter will be about because
- 5:13
you need a basic VM that is prepped in which you can
- 5:16
deploy all sorts of things or install or so, all sorts of things.
- 5:19
And then you can choose your virtualization provider
- 5:21
that will mainly be either VirtualBox or VMware.
- 5:24
Twiggle around with VM parameters such as CPUs, number of
- 5:27
CPUs, you wanna configure RAM settings, et cetera, et cetera.
- 5:31
Networking settings such as H settings.
- 5:33
Mounting your local file system.
- 5:34
Which is very convenient for developers.
- 5:36
And finally, provisioning the machine.
- 5:38
So that, that's what we're gonna do.
- 5:40
So if you run Vagrant in it without any options it will drop you a Vagrant file.
- 5:44
And if you open it in your text setter, you'll
- 5:46
basically see that it's, has the Ruby markup for your editor.
- 5:49
So it's plain old Ruby but in a specific syntax.
- 5:51
So you're gonna configure a machine.
- 5:53
The two means that we're gonna use,
- 5:55
Vagrant verion twowhich is important because it
- 5:57
adds a lot of nice features, and
- 5:58
we're gonna namespace all the properties as config.
- 6:00
And then you could say config VM box is base.
- 6:03
So there's this sort of convention that you have a base box.
- 6:05
A base box that represents your, that
- 6:08
Linux image you're gonna run everything on.
- 6:11
And that base box is gonna be cloned every time you make a box.
- 6:16
You could also add some specific parameters, say,
- 6:19
we're not going to use a base box.
- 6:20
We're going to name it precise32, which is an Ubuntu version.
- 6:24
And this is where I'm gonna download it, and it's gonna just put it in the file.
- 6:27
It's not gonna actually download it.
- 6:28
That happens when you start it up, but it's gonna pre-provision
- 6:31
everything you need, and you can add whatever box you want.
- 6:34
You can have whatever distro you want as long as you stick with Linux.
- 6:39
And then the magic commands and they, this is like if you have
- 6:42
to remember one thing from this talk and one thing only is this command.
- 6:45
Vagrant up, it's all you need in life Vagrant up.
- 6:49
And then you just press the Return button
- 6:51
and it will just give you some verbose information.
- 6:53
Since the precise 32 box is not really on the
- 6:56
system right now is gonna download it you can see the
- 6:58
progress here with a sort of an estimation, and once
- 7:01
it's added, it's going to store it in your system globally.
- 7:04
So in the future, when you have that box in there and
- 7:06
you want another project using it, you don't need to download it anymore.
- 7:10
So, it's there.
- 7:11
And then it says all the stuff it does to your machine.
- 7:13
It, imports the bulks.
- 7:15
Does some netting.
- 7:16
Setting the name of the VM.
- 7:18
Port forwarding, networking interfaces.
- 7:21
This is a specific one I'll mention.
- 7:23
Booting it up, configuring it, and mounting a folder.
- 7:25
So you see what it does.
- 7:27
But back to base boxes, because boxes are important.
- 7:30
There is a place where you can download them.
- 7:31
It's a sort of community site called Vagrant Boxes.
- 7:34
And it has a bunch of those, it's a community initiative.
- 7:37
If you want to tailor your own boxes, there's
- 7:41
project called VWii by a guy named Patrick DuBoise.
- 7:44
He's the guy who invented Devops, the term Devops.
- 7:46
And he maintains this project and it's an easy way
- 7:48
to start from a basic ISO and create a Vagrant Box.
- 7:52
You can tune it you can strip off stuff you don't need.
- 7:54
It's a really good tool, so when we type in Vagrant Box.
- 7:58
You're gonna see this kind of stuff happening.
- 8:00
The basic stuff, right?
- 8:01
Adding, removing, listing, repackaging.
- 8:04
And I have some code examples here.
- 8:05
Like, this slide is heavy on code examples.
- 8:07
So you'll see lots of this.
- 8:09
So, if you box list it, you'll, you'll see
- 8:11
that the, the machine we previously imported is there.
- 8:13
It's a virtual box machine called Precise 32.
- 8:16
We could remove it, we can add it again.
- 8:18
And mention where it needs to be.
- 8:20
Now.
- 8:22
Contrary to the previous slides where we did the Vagrant
- 8:24
in it with this box, this will actually download the box.
- 8:27
This could be a URL or a local file.
- 8:29
It will import it and make sure it's available when you boot a machine.
- 8:32
And if you want to redistribute that box, let's say you
- 8:35
just did a, a Vagrant box add from a specific file.
- 8:38
The file is no longer on your local folder.
- 8:41
It's, it's just stored in, internally in the system.
- 8:44
You can make it reappear by doing vagrant
- 8:46
box repackage, and it will come as a packaged
- 8:49
box and you can put it online, redistribute
- 8:51
it to your team, whatever you want to do.
- 8:54
Now, I would like to remind you that all of this, the
- 8:56
box management or downloading boxes, can be done in your Vagrant file.
- 9:00
Just mention config.vm box and URL and it will download it if you don't have it.
- 9:04
And this is what a box look like.
- 9:06
It's, the box is just a TRGZ, sort of archive, containing an VMDK and
- 9:10
OVF file, an meta adjacent, and the
- 9:13
meta adjacent usually contains a virtualization provider.
- 9:15
Either Virtual Box or VMWare.
- 9:17
And a Vagrant file that bootstraps other Vagrant
- 9:20
files, because that's the cool part, when you
- 9:21
type Vagrant up, in a folder that contains
- 9:24
a Vagrant file, it will bootstrap the entire thing.
- 9:26
So now that we know what Vagrant does.
- 9:28
And now that we know how we can work with base boxes.
- 9:31
Let's get up and running.
- 9:32
So, let's get starting.
- 9:34
Let's start, stop, suspend.
- 9:36
Let's do all the cool stuff.
- 9:37
So if you do Vagrant up again.
- 9:39
That's the command you'll love by the end of this talk.
- 9:41
Or, or maybe next week, when you toy around with it.
- 9:44
You'll, just send me a tweet if you like it.
- 9:46
For the people who haven't tried it, just send me a tweet.
- 9:48
So if you do Vagrant output, it will do all
- 9:50
of that stuff again, when the VM does not exist.
- 9:52
But when it, it exists, it will just show you some basic information,
- 9:56
like it was already running, I'm not gonna bother making it boot now.
- 9:59
A reminder, I may be a hint for you.
- 10:02
Who has a laptop containing an SSD?
- 10:05
Who doesn't?
- 10:07
This will take some time doing a Vagrant up, if you don't
- 10:10
have SSD, could take some time, could take a couple of minutes.
- 10:14
So, if you don't want it destroyed, because Vagrant destroys
- 10:17
the command, you're gonna tear down your entire environment with.
- 10:20
If you just want to suspend it or, or
- 10:22
halt your machine, there are commands for that as well.
- 10:24
So with the status you can see
- 10:24
what is happening, it's running, it's actually running.
- 10:27
And when you do suspend, it will just pause
- 10:29
your VM and keep the current machine state on disk.
- 10:31
And when you resume when you do Vagrant resume or
- 10:34
just Vagrant up again it will just restart a machine.
- 10:36
There are cases where you don't want to do that, and you just say
- 10:39
I want to shut down, and you do Vagrant alt and it shuts the machine
- 10:42
down, and it's still in your, when you open your virtual box or when
- 10:45
you open your VMware you'll still see the machine, but it'll just be shut down.
- 10:50
And as I mentioned before, if we wanna destroy the
- 10:52
machine, if we wanna tear it down just Vagrant destroy.
- 10:55
It won't only shut it down, it will remove it from your virtualization provider.
- 11:00
So it will be completely gone.
- 11:01
It won't be consuming any RAM CPU nor will
- 11:04
it be consuming disk, so that's what it basically does.
- 11:07
So what have we learned so far?
- 11:08
We've learned how to set up what a Vagrant file does.
- 11:12
We know how we can import boxes.
- 11:13
We know how to set it up, tear it down
- 11:15
but now we have that we need to connect with it.
- 11:17
So connecting is is an important part of
- 11:19
Vagrant and a part that is made incredibly simple.
- 11:23
You just type the vagrant ssh command and it will automatically log in.
- 11:26
No need to know the IP, no need to care about passwords, or your own keys.
- 11:32
It will just go in there, do pseudo su, and your root, in the machine.
- 11:37
Now in the background, so when you go on that machine, and when you root, and you
- 11:40
go to the all trice key files, you'll
- 11:41
see that there is a public key automatically provisioned.
- 11:45
And it says here very specifically, vagrant insecure public key.
- 11:49
So it's something that Vagrant manages for you.
- 11:50
And when you type the command Vagrant as
- 11:52
SSH Config, you will get SSH Config for that.
- 11:55
So there's been a default there.
- 11:56
Where there's a default host, default user, a default
- 12:00
port and what this does actually is make sure
- 12:02
that you do a local ssh connection to port
- 12:05
222, and it will be port forwarded to the IP.
- 12:08
In this case the, the machine itself will log in using the user Vagrant
- 12:13
and will be using this insecure private key to match the public key.
- 12:18
On a private key this is my computer user stays on
- 12:21
Vagrant here, so there's this global space on my laptop here where
- 12:25
the key is stored and this is what it looks like,
- 12:28
nothing spectacular, you can use the key there's no privacy involved here.
- 12:34
The key aspect when we run these Vagrant machines when it's up and
- 12:38
running when we connect it is also the portability of the Vagrant file.
- 12:41
I want to briefly also touch on that because that's important.
- 12:43
I mentioned already that you can use the Vagrant file.
- 12:46
This is a GitHub project of an open
- 12:48
source tool or an open source project called Joinedin.
- 12:52
And a lot of people want to contribute to it.
- 12:54
And having the machine requirements often requires some documentation.
- 12:57
Like set up your machine as such you need these versions.
- 13:00
Instead of going through all that hassle, the maintainers just dropped in a vagrant
- 13:04
file, which is versionable as well, so if you need to change the specs,
- 13:07
you could easily do so and just, clone it, clone the GitHub repository, just
- 13:11
type vagrant up, and you have some puppet manifests that will provision the machine.
- 13:15
And we'll touch on puppet as well, as well as Chef.
- 13:18
So, what we wanna do is share that vagrant
- 13:20
file and as a consequence, share your entire development
- 13:23
environment with contributors of public open source projects, or
- 13:27
just people within the company who are on your team.
- 13:30
So what we're basically saying is infrastructure as code and this is a
- 13:34
big term coming from the Dev
- 13:35
Apps community, having infrastructure there as codes.
- 13:39
So you remember this one?
- 13:40
Our little Vagrant file only containing the box, and the box URL.
- 13:44
Well, let's do some actual stuff.
- 13:46
Let's provision it.
- 13:47
Let's start with some networking because that's something you want
- 13:50
to care about, if you want to connect, not only
- 13:52
to raise its age but with a web browser, let's
- 13:54
say, you need to make sure how to connect to it.
- 13:57
There are three ways of networking.
- 13:59
Public networking, private networking.
- 14:01
And just doing port forwarding.
- 14:03
The public networking just bridges to a, a network interface.
- 14:06
And just let it handle everything networking related.
- 14:09
So you're part of the public network.
- 14:10
Everyone else could manage or access your box.
- 14:13
If you don't want that, you can do some regular port forwarding.
- 14:16
It doesn't, the next string that we're interfaced to the machine.
- 14:19
It just says while the port 80, which is by convention
- 14:22
the web server port, will be linked on your computer to 8080.
- 14:25
So if I type local host 8080, I will end up pinging within the machine.
- 14:29
So that's what it does.
- 14:31
And personally, I prefer private networking because it's simple, it's
- 14:35
straightforward, you just choose an ip, within the private ip space.
- 14:39
Watch out if that is the same ip space of your
- 14:42
internal network or your company that my, the, generate some ip issues.
- 14:48
And let's see the examples here.
- 14:49
This is how you do, do it into Vagrant files.
- 14:51
So private network just add within the global configure.
- 14:55
At config VM network.
- 14:57
Private network ip.
- 14:59
One vagrant up will take care of everything.
- 15:01
Now, mind you, we didn't choose port forwarding,
- 15:04
but we're still seeing some port forwarding here.
- 15:06
Is this still something we see, why?
- 15:08
If you pay close attention, this means 22 goes to the 2222.
- 15:12
This is for Vagrant as it is h.
- 15:14
So, you ssh on this port, and you end up in this machine.
- 15:16
So, this is required for just ssh connections.
- 15:21
If you use port forwarding you can see the extra line being added.
- 15:24
So it's added to adapter 1 port 80 internally is matched to 80/80.
- 15:28
So it's pretty clear when you do a vagrant number
- 15:29
you see what's happens and finally when we choice public networking.
- 15:33
And when you do the vagrant up you will get an option, you
- 15:36
will get an option, which interface do you want to bind it to?
- 15:39
And I chose 1, to my WiFi, I tapped Enter.
- 15:42
And which is linked.
- 15:44
If you wanna pre-link it, there's an option of bridging, and then
- 15:47
you have to mention your network interface you wanna link it to.
- 15:51
I don't consider this very convenient.
- 15:53
In some cases you might use it.
- 15:54
I always stick with private networking.
- 15:57
This is the number one reason synced folders, why you should pick, fragrant
- 16:03
over constantly deploying to a VM, because it has a built in system, of
- 16:08
mounting your local file system, of just the local file system of the current
- 16:11
directory, in which the fragrant file re, resides, just mounting it to the system.
- 16:15
So when you're in you IBE, you can have your local file system available.
- 16:20
And you can just save directly from your editor or IDE,
- 16:23
which is very convenient for developers, because you don't want to change
- 16:26
a piece of code, upload it to your VM, and then
- 16:29
test it, and the uploading or deployment process might take some time.
- 16:32
No, it's instant.
- 16:33
You press Save, you refresh your browser, you see results.
- 16:37
And by default, there is a mount a slash vagrant mount.
- 16:40
So that means your current folder is available on your guest OS, and
- 16:44
when you go to the slash vagrant you just see your local system.
- 16:47
And when you change something on your computer, it's going to be changed there.
- 16:50
So, in a lot of the cases people will link this folder to their web server root.
- 16:54
What I tend to do is add another sync folder.
- 16:57
Say you have your project and, public files are located in web.
- 17:01
Or I'm gonna link them to /var/www, and when you install
- 17:03
Apache, you immediately have a link and can immediately navigate through it.
- 17:06
And you can see it here when you do vagrant up, you will see this happening.
- 17:11
So we did quite a number of things already.
- 17:14
Let's tune some VM properties.
- 17:17
This happens also through the syntax.
- 17:19
This is not a complete vagrant file, this is just the snippets that
- 17:21
is relevant, you just have to shove it within the main configuration block.
- 17:25
What we do here, these are some stuff, this is some stuff.
- 17:27
I put a Vagrant file online because I do some training as well,
- 17:30
and I added varnish installation and I wanted to distributed it to Vagrant.
- 17:34
And I did it.
- 17:35
And then some clever person said, you might want to add these parameters.
- 17:38
Some of these solve kernel panics, other ones
- 17:41
help you have a better deal as a result.
- 17:43
It's just internal magic from from virtual bugs but it, it actually helps.
- 17:48
The only parameters that are very useful to you is memory and CPU.
- 17:51
This is how you can tune how big the box
- 17:52
is, like if you need some extra horse power in it.
- 17:54
You could-, might want to increase this this is the way it works.
- 17:58
So these are the basic steps.
- 18:00
This is how you manage a Vagrant box when you have
- 18:02
it up and running, you won't have any specific software on it.
- 18:06
This is the next chapter.
- 18:07
But you will have it tuned, the machine tuned the way you want.
- 18:10
And we will be dealing with the most important part, provisioning it.
- 18:13
Making it lot like production.
- 18:15
Making it look like test and stage.
- 18:17
Now, provisioning could mean anything, but what it basically
- 18:21
means to me is adding specific software to it.
- 18:23
So, using packages to do that.
- 18:25
Creating configuration files where you need them.
- 18:27
Execute certain commands to prep your system.
- 18:29
Create users.
- 18:31
Manage services, and this all needs to happen automatically.
- 18:34
You don't need to care about that in theory.
- 18:36
You have people in your team who are going to write all the provision
- 18:39
you need, and just type again, and I'll be repeating that a number of times.
- 18:43
Vagrant up.
- 18:44
Machine comes up.
- 18:45
Provisions automatically.
- 18:46
So, having an exact copy or a similar or as good
- 18:51
as an exact copy of your environment is the main goal here.
- 18:54
And we're gonna use, there's several tools out there.
- 18:56
There's a bunch of tools out there.
- 18:57
I just marked the ones that I'm going to mention.
- 18:59
Now, this talk is called Vagrant, Chef and Puppet for the win.
- 19:02
While it's gonna be mainly focused on Chef and Puppet.
- 19:05
But you can do plain old shell, just Linux commands.
- 19:08
Ansible is getting a lot of traction these
- 19:10
days, as well, Anyone who's heard of Ansible?
- 19:13
It seems like the cool thing to use these days.
- 19:17
I like Chef, I like Puppets.
- 19:19
I personally prefer Puppets.
- 19:20
I'd like to standardize on Puppet.
- 19:21
By Chef is, is pretty awesome, itself.
- 19:24
You see different kinds here.
- 19:25
Solo clients apply agent.
- 19:27
You can do a stand alone, wave provisioning, where
- 19:30
all the scenarios, how you're gonna set up the software.
- 19:33
Are also in your code repository.
- 19:34
You saw the screenshot of the join in project had a Puppet folder, so it locally
- 19:39
stores all the software you wanna install, all
- 19:41
the configuration files, services you want to manage.
- 19:44
When you don't want that and when you just wanna connect to
- 19:47
a configuration management server, gonna use a Puppet agent or Chef clients.
- 19:51
So it connects over TCPIP to a centralized
- 19:53
server, the same server that deploys all the code
- 19:56
and the infrastructure to your production environment, while
- 19:59
you're gonna connect and hook into the same one.
- 20:01
Let's start with the beginning.
- 20:03
Let's start with Shell.
- 20:04
Shell is plain, shell is simple, and shell is pretty powerful.
- 20:08
Like, I run into this problem a colleague of mine who is sitting on the third row
- 20:12
there, wanted to deploy a Symphony app in
- 20:14
PHP and it was insanely slow on it's system.
- 20:17
So I said well the cash folder, which is located in vagrant app cache.
- 20:21
You wanna have a rundisk for it.
- 20:23
So instead of just writing a complicated Puppet script for just the config vm
- 20:27
provision, what kind of provision shell, where
- 20:30
is the, where does the description reside?
- 20:32
Well, it's inline and then mount tmpf, 50 mgs of RAM disk good to go.
- 20:38
Pretty simple, you can do even more than that.
- 20:40
You can you can op, you can use full Ruby because it's has full Ruby
- 20:45
syntax, and you can do whatever you want
- 20:46
there in Ruby to manipulate what's coming in.
- 20:49
And if you wanna petition it separately, have
- 20:52
separate files for that, you can either use
- 20:53
local files using like in this case, script
- 20:56
dot sh, or you could download it remotely.
- 21:00
But we're not, or we're no longer gonna talk about that.
- 21:02
We're gonna talk about the stuff that has
- 21:03
actually built the provision machines, either Chef or Puppet.
- 21:06
Anyone using Chef these days?
- 21:09
Anyone using Puppet these days?
- 21:13
How do you, have the other people provisioned their machines on their,
- 21:17
or are you not involved with the deploying of code or configuration.
- 21:22
How does it happen in your companies, manually or
- 21:26
have all the hosting company take care of it?
- 21:29
Probably.
- 21:30
Okay Chef and Puppet.
- 21:31
Chef is a tool created by OPSCODE.
- 21:33
It's written in Ruby.
- 21:34
In 2009, now it's an open source project but it's company
- 21:37
backed they have an enterprise revenue model, and the same thing applies
- 21:41
to Puppet, see the pattern here, this one is written in Ruby
- 21:43
as well by Puppet Labs in 2005, that's the company backing it.
- 21:48
Chef and Puppet again, such a, so Vagrant is written In Ruby.
- 21:53
Chef is written Ruby, Puppet is written in Ruby, a lot of stuff happening in Ruby.
- 21:57
Now as the introduction went I'm a PHP guy, but I
- 22:00
have to accept this Ruby is big, Ruby is out there.
- 22:03
And I think next year, next time around I'm
- 22:05
gonna be learning Ruby to master this stuff more.
- 22:08
So both of these tools written in Ruby,
- 22:11
open source, enterprise model behind it, similar features.
- 22:14
Both stand alone or server-side.
- 22:16
You can choose.
- 22:16
It's supported by a large community.
- 22:19
So, if I had to say which community is
- 22:20
better, I wouldn't be able to answer that question.
- 22:22
It, it depends on the flavor you want.
- 22:26
It's modularized.
- 22:27
So, the components you gonna download there are parametrized, modularized.
- 22:31
So, you don't need to figure out the nitty-gritty.
- 22:34
It, they offer a nice little interface.
- 22:36
That you can add parameters.
- 22:37
Let's say for MySQL server, the root password or the location
- 22:41
of the data file is just gonna abstract that for you.
- 22:44
And they're gonna use all kinds of stuff
- 22:46
for file system, for templating,uh, it's, it's pretty easy.
- 22:50
If I have to say how they differ, I would say
- 22:53
in terms of the lingo, so, modules, the way you modualize things.
- 22:57
Chefs call these cookbooks.
- 22:58
They're gonna stick to the culinary, naming there.
- 23:01
You're gonna have cookbooks.
- 23:03
And within the cookbooks, the specific items are
- 23:05
recipes Whereas, Puppet just calls 'em modules and manifests.
- 23:09
Now, the main difference, language wise is that the Puppet
- 23:13
just has a, it's own DSL you could work with.
- 23:15
Whereas Chef, it's for Ruby, extended with a DSL.
- 23:19
So if you're a Ruby guy, in a lot of the cases you're gonna pick Chef.
- 23:22
Because it's just the way you like doing things.
- 23:25
The approach here is, it's, it defines actions.
- 23:28
Whereas Puppet more or less defines states or how, on how you want it.
- 23:32
It doesn't really say, do this, do that.
- 23:34
It's says, make sure its like this, it's make sure its like that.
- 23:38
Whereas it is more procedural on the end of Chef, it
- 23:40
will be more object oriented on the side of of Puppet.
- 23:45
So instead of talking about it, let's just do it, right?
- 23:48
How to use it.
- 23:49
There's a GitHub repo, by Ox Code itself.
- 23:51
It contains modules for all the popular open source projects.
- 23:54
You could figure out web servers, database servers, all the components you want.
- 23:58
You can just clone it to your, your directory where you want it.
- 24:01
Make sure you link it in your vagrant file through chef.cookbookpot.
- 24:05
And if you want to include recipes, just use chef@recipe in your vagrant file.
- 24:09
I'll show you later on.
- 24:11
And if you wanna interface with all the attributes you can modify, you can
- 24:14
just use chef.json, json, and have inline JSON with all the parameters you want.
- 24:19
And, or, when necessary, you can create your own cookbook.
- 24:23
But in a lot of cases, I will
- 24:24
advise you, don't reinvent the wheel unless truly necessary.
- 24:28
So this is what it looks like in the grand scheme of things.
- 24:30
Again, this is not the complete Vagrant file,
- 24:32
this is just a config, that is relevant.
- 24:35
So we're gonna say, we're gonna provision our
- 24:37
vm using Chef Solo, name space, everything, under chef,
- 24:40
and then say, the cookbooks are located in the,
- 24:42
in the current directory under a directory called tools/chef/cookbooks.
- 24:46
And the recipe I want to add basically comes from the MySQL Cookbook.
- 24:50
And it's called server.
- 24:51
So we're gonna install a MySQL server on the system.
- 24:55
And then we use chef JSON to to parameterize whatever we need to do.
- 25:00
And we're gonna say the password for
- 25:02
application for server, just server authentication using root,
- 25:06
or the Debian built in user is gonna be foo, and you can connect with foo.
- 25:10
Now, the layout of the cookbook is
- 25:12
pretty plate, straightforward, pretty plain and simple.
- 25:14
There's a lot of directories and files there,
- 25:16
but I marked the ones that are specially relevant.
- 25:19
So we get, gonna have the recipes and the default recipe
- 25:22
is called default.rb, and there you're gonna specify the main one, so.
- 25:25
In terms of bootstrapping This one is going to get loaded first.
- 25:29
Templates are stored in the templates default folder, so, it's erb style.
- 25:32
So, if you can just drop Ruby style templates in there.
- 25:36
And everything that it needs to
- 25:37
be parametrized resides in the attributes folder.
- 25:40
I'm going to show you some quick examples.
- 25:41
These are not going to be full examples because the
- 25:43
code base is so extensive, it hardly fits on the slides.
- 25:47
So this is for MySQL.
- 25:48
All stuff you could, configure.
- 25:50
But please note that the configurations might depend on platform families.
- 25:54
So you're gonna have a difference between Debian style, or, red hat style.
- 25:59
So you need to make sure, if you download
- 26:01
one, it fits the infrastructure you have, at the office.
- 26:06
This is a server recipe, a pretty simple one.
- 26:08
And this actually shows the power of Chef, in this case.
- 26:12
So we're gonna have a group.
- 26:13
So this is gonna define a group on your
- 26:15
Linux operating system, called MySQL, is gonna create it.
- 26:18
You're gonna create a user called MySQL.
- 26:20
It's gonna reside in the MySQL group.
- 26:23
And the location so the home directory of that user is pre-defined.
- 26:27
No MySQL data there.
- 26:28
So that comes from attributes.
- 26:29
You can tune that.
- 26:31
And in the end, it's going to have a no login shell.
- 26:35
And then based on all the packages, that are located in the attributes as well.
- 26:39
So in the configuration, you can loop through it.
- 26:41
And it will use the package manager of your operating system to install it.
- 26:44
So, on Debian systems and Ubuntu systems that would be apt-gets.
- 26:48
On Red Hat, Fedora, or CentOS, that's going to be yum.
- 26:51
Packages can also be Ruby, Gems or even PHP para installs or whatever you want.
- 26:56
You can even configure it and write your own providers for it.
- 27:00
Templates as mentioned, basic ERB, so you can just
- 27:03
add variables and they will be dropped into there.
- 27:07
That's, it's just that simple, it does require a change in mind set to work
- 27:10
with these kind of tools but this is infrastructure as code in the purest form.
- 27:15
Most of us are developers.
- 27:17
Infrastructure sometimes is a strange concept that
- 27:19
we like to hand over to Cis admins.
- 27:21
But this is just giving you the power to find the things you need.
- 27:24
You'll turn your Sysadmin into a developer.
- 27:27
And a developer into a Sysadmin which is a developers way of thinking.
- 27:32
Typical resources you can tune.
- 27:34
This is just a short list I added the three dots, there's more than this.
- 27:37
So Users Cron's Directories executing command files
- 27:41
installing packages running services, so everything you need.
- 27:46
Again, I will advise you to download components that are offered
- 27:50
through the community, but if you want to do it yourself.
- 27:53
This is a way of doing it yourself, say we create
- 27:55
a project cookbook and in the recipes we add a default recipe.
- 27:59
We're gonna do an, an update of our
- 28:01
channel, so we have the freshest channel, so we
- 28:04
know when we install a package called MySQL server,
- 28:07
or Apache, that these are the most recent ones.
- 28:10
After installing the MySQL server, you're gonna you're gonna make
- 28:14
sure the system starts, so you're gonna invoke the service.
- 28:17
The Apache server, when it's installed, make sure it's started as well.
- 28:21
You're gonna do this delayed here.
- 28:22
Why?
- 28:22
Because there is a next step coming.
- 28:24
And that will require a restart of the server, as well.
- 28:26
So you can actually schedule and script what the entire installation procedure is.
- 28:31
And then we continue to assign a root password to
- 28:33
the system only if there's not a root password present.
- 28:37
We're gonna manage a service, so this is an actual
- 28:39
service definition that allows us to start, stop, restart system.
- 28:43
So this is your system, your entire
- 28:45
installation wrapped into a couple of files.
- 28:48
And when we wanna do it ourselves, this is what our
- 28:50
Vagrant file, this is what gets exposed to the front looks like.
- 28:54
So we're gonna say we're gonna use Chef
- 28:56
slo, solo, this is where the cookbooks are located.
- 28:59
We have a project recipe, and the root password of the project is foo.
- 29:03
We just do Vagrant Up boom, MySQL server, Apache web server, and a bit of PHP.
- 29:09
When you do Vagrant Up, you're gonna see
- 29:11
that there's a provisioning run happening as well.
- 29:13
So there's an extra mount being added to
- 29:16
tmp Vagrant Chef, and it contains all the cookbooks.
- 29:19
Cuz the local machine needs to run the Chef true.
- 29:21
And you get a lot of verbose information.
- 29:23
A hell of a lot of verbose information.
- 29:25
I marked the ones that are useful to us.
- 29:27
So, the services, the execution of all this stuff.
- 29:29
So we can really see what's happening.
- 29:31
And you can use that to debug, in case something goes wrong.
- 29:35
That was Chef.
- 29:37
Puppet is pretty similar.
- 29:38
I think it would be easier for you to follow along right now.
- 29:40
Because you already have a vague.
- 29:42
Idea of what configuration management can do,
- 29:45
and Puppet is very, very similar to Chef.
- 29:48
It's just a different flavor.
- 29:49
You have your cookbooks as well, or modules as they're called.
- 29:53
And Puppet Labs has it's own GitHub channel as well.
- 29:57
Everything is stored in there.
- 29:59
It's a bit different how you interact with them.
- 30:01
So you have a module path as well, very similar to the cookbook path.
- 30:05
But you don't add recipes in your Vagrant file, you just include a manifest,
- 30:09
and that manifest is just your bootstrapping
- 30:11
ugh file, that does all the installations.
- 30:13
If you want to transport custom variables,
- 30:17
custom attributes from your custom Vagrant file.
- 30:19
To the internal Puppet manifests.
- 30:22
You can use Puppet dot factor and add custom
- 30:24
effects, and these will become variables put into your scripts.
- 30:28
So, Vagrant file looks a bit like this.
- 30:31
Manifest paths, module paths, manifest file, so the init dot ppp resides
- 30:35
within the puppet manifest folder and it looks a bit like this.
- 30:39
So with this single line you can setup a MySQL server, just install it.
- 30:42
It won't contain a password, so if you connect to
- 30:45
your local host, just MySQL enter, and you're in the system.
- 30:48
If you wanna tune it, you have to turn this into an actual
- 30:51
class, and add a parameter root password equals foo, figuring up, good to go.
- 30:56
Now the layout of this module, it's pretty similar to chef if you ask me chef
- 31:00
or, or puppet, it likes choosing between Pepsi
- 31:03
and Cola, everyone has its own its own preference.
- 31:07
Manifests instead of recipes.
- 31:08
You have your init.pp this is the one that's going to get bootstrapped first.
- 31:13
And instead of having an attributes folder where all the attributes are located, by
- 31:16
convention people are mostly going to use
- 31:18
parmas.pp and this contains bunch of parameters.
- 31:21
Again there is a templates folder, containing all the basic templates.
- 31:25
I have a screen dump of what this looks like.
- 31:28
This is, you see a more object oriented approach.
- 31:31
Oh ho, all the parameters you can tune.
- 31:33
This is just a, a, a piece of, of the action.
- 31:36
There's plenty more.
- 31:37
I added some doves there, you can see there's some differences for Red Hats.
- 31:40
You can do this for Debians, you can do other stuff.
- 31:42
It's a huge list of options to tune.
- 31:45
The manifest itself see MySQL Server, so we're gonna install a server.
- 31:50
It inherits from the parameters.
- 31:54
You have some templates too so very, very, very similar.
- 31:58
And again, the resources are simple too.
- 32:00
I mean, files, execution, computers, cron, host, whatever
- 32:04
is in Chef is probably also in Puppet.
- 32:07
And if you want to do it yourself, this is what it looks like.
- 32:09
Now there's a very important difference, between Chef and
- 32:11
Puppet in terms of writing it into a file.
- 32:14
In Chef it's going to go top down as you expect.
- 32:17
In Puppet it is not, and that freaked me out when I learned Puppet at first.
- 32:21
You have to chain events to each other.
- 32:23
So, this is gonna be executed whenever Puppet
- 32:27
feels like it, so we're gonna update our channel.
- 32:29
But the way we gonna make sure there's a logical order
- 32:31
is by using require and notify the change things to each other.
- 32:35
So if we install the mySQL server package, before we
- 32:38
do that we're gonna make sure our channels are updated.
- 32:40
And after that we're gonna make sure the server is started.
- 32:43
So that's the way you order things.
- 32:45
When you install Apache, it could be that MySQL is installed first.
- 32:48
It could be on the next run that Apache stall, installed first.
- 32:51
But that doesn't really matter.
- 32:53
What does matter is when you want to
- 32:55
ins, install Apache, make sure the channel is updated.
- 32:57
And right after that, make sure you install PHP.
- 33:00
And when you install PHP there, make sure in the end
- 33:03
after you install both of these components that you reload Apache.
- 33:06
That freaked me out.
- 33:07
That was really complicated.
- 33:08
And this is the, the remainder before you assign
- 33:12
a root password, make sure the MySQL server is installed.
- 33:16
And do this only if you can just execute that command and get in.
- 33:19
If you get an access denied, it means you already have a password,
- 33:23
no need to reconfigure it, and then at the end you have your
- 33:25
two services, a MySQL service an Apache service whereas Chef was just
- 33:31
blocks, this is like more curly braces style it depends on what you wanna do.
- 33:36
And this is just a basic file, manifest
- 33:39
part, module part, main file you're gonna includes the
- 33:42
Puppet factory see foo, and foo has used their
- 33:45
root bother you see, just a dollar sign password.
- 33:48
You define it here, it finds its way from your vagrant
- 33:51
all the way up to the system internally, and you're done.
- 33:55
And this is what happens when you type vagrant
- 33:57
up two new mounts, a manifest mount, a module mount.
- 34:00
And you can see all sorts
- 34:01
of information: services, executions, packets being installed.
- 34:05
This is the random order that happens.
- 34:08
That being said so we're true to chef.
- 34:10
We've already done puppet as well.
- 34:12
In a lot of cases I said Vagrant up is the main command you need.
- 34:15
In a lot of the cases the machine will already
- 34:17
be there and you made an error in your provioning.
- 34:20
You can just type vagrant provision.
- 34:22
It won't reboot the machine, it will just run Puppet or
- 34:25
the Chef or both because you can combine all of them.
- 34:27
You can have Chef run, a Puppet run.
- 34:29
A shell run, a ansible run, all run through each other Main
- 34:33
question at the ends chef or puppet, what are we gonna choose?
- 34:38
After this, who's gonna prefer chef, puppet?
- 34:44
A slight majority for puppets, if I can say so.
- 34:47
But there are problems as well when using chef and
- 34:50
puppet, and I noticed it, so my colleague Bram who's
- 34:51
sitting on the third row there asked me, Thijs, make
- 34:53
me a dev box and this is my list of requirements.
- 34:56
And, I, I scripted it all, and then, I typed vagrant up,
- 35:00
and it took bout half an hour to boot the entire system up.
- 35:03
Because it had so much dependency, that went over the network, cause
- 35:05
using a package manager, implies that you make connections outbound, and I
- 35:10
didn't configure my system as such, that it took Geo locality into
- 35:15
account, so it just, went off, to connect to the US servers.
- 35:19
And started downloading.
- 35:20
So, it was very cumbersome, very time consuming.
- 35:22
So, I decided we needed a different approach.
- 35:25
So, what I did is, instead of just, installing
- 35:28
everything on the fly, I created a new base box.
- 35:33
Because it can be slow from time to time.
- 35:37
Maybe some other lessons learned before we dive into the final piece.
- 35:41
The quality of public cookbooks and manifests
- 35:44
and the support you get may vary.
- 35:45
So, when you choose a specific cookbook or module for shareware Puppet, make
- 35:52
sure it fits your requirements so that it is built around your distribution.
- 35:56
Because I have found some pretty awesome scripts Puppet scripts that only work
- 36:00
on Red Hat systems and I use a Debian, But make sure it works.
- 36:06
Make sure the quality is there.
- 36:07
Make sure it's updated regularly.
- 36:08
My main advice is stick with, if you stick with Chef
- 36:11
go to the ops code get up and get one of those.
- 36:14
These are well maintained, and for puppet it's the very same thing.
- 36:17
We are getting back to the story of the, the VM I had to create for my colleague.
- 36:20
It was so time consuming to set it up it wasn't really working.
- 36:24
We have, we have several projects we have to work on.
- 36:26
And if you type vagrant up for the enti, for this project, and, and
- 36:29
in the afternoon you have to work on another project, it doesn't really work.
- 36:32
So what I did is use the Vagrant package command,
- 36:34
and the Vagrant package will just take the current vm
- 36:37
you're working on, and repackages it as a box file
- 36:41
and that box file, you can reload upload it elsewhere.
- 36:43
So, what I did, is I installed all the software he
- 36:45
needed, all the configuration files were in place, and the only thing
- 36:48
he needed to do, was make sure he had that box in
- 36:51
his vagrant file and in a full blown box, ready to go.
- 36:54
There is this is time consuming as well to package it, because it has to export
- 36:59
the entire VM, turn it into a box file, tar gz it, so it's a trade off.
- 37:03
And another thing you can do, and this is
- 37:05
a, a very good practice is do light provisioning.
- 37:08
So everything that is pretty heavy weight, so in terms of installing
- 37:11
software, making connections with packages, you can do that in the box file.
- 37:15
And all the configurations, like
- 37:17
configuration settings, virtual host files.
- 37:19
You can still do that using puppet chef
- 37:21
shell cuz that doesn't really take any time.
- 37:23
It's just file system action.
- 37:25
When you have to connect outbound, you might wanna figure out a way.
- 37:28
There are people who, who just use depth files, so,
- 37:31
or, or rpm files and just store them on the system.
- 37:34
So, they don't need to connect through the network.
- 37:36
They have all the packages at hand.
- 37:38
There are even people who boot a specific VM that servers
- 37:42
as a sort of package server and they connect to that.
- 37:45
It, it's pretty much up to you.
- 37:46
I have three minutes left in this talk, and I want to dedicate it to multi-machine
- 37:50
setups which is a very interesting concept when
- 37:53
you want to take it to the next level.
- 37:56
When you work at a decent company and, or work on
- 37:58
a product, it's hardly going to be run on a single machine.
- 38:02
In a lot of cases you're going to have multiple machines, two web
- 38:04
servers, two My SQL servers, an Oracle, some red hats, whatever you want.
- 38:10
So it would be nice to see this in action too.
- 38:13
I'll show you Vagrant file, I hope this is readable at the back.
- 38:17
This was usually done in the main piece, but what I
- 38:19
do now is conflict VM define and I'm given the name.
- 38:22
We have a web server.
- 38:23
We have a DB server.
- 38:25
This is shared along so these are both DB and weezies.
- 38:29
So, we just say that once, we just mention it once.
- 38:32
DB and 7 1 0.
- 38:34
and on every other machine, I'm gonna do a
- 38:36
shell inline script update a channel, update the packages.
- 38:39
And then the specifics are noted here.
- 38:41
We're gonna define a host name for the
- 38:43
machine because default won't really cut it right now.
- 38:45
So we're gonna have a webpp node, and a DB node, and
- 38:48
when you log in you're gonna be vagrant at webpp, Vagrant at db.
- 38:52
You assign a specific IP address ten, 11, the web
- 38:56
server is gonna be the mounted folder on var www.
- 39:00
Then the autorun is gonna require a specific, positive for the MySQL.
- 39:05
And the only difference, here, is that we connect to web.pp in the manifest folder.
- 39:11
Or db.pp.
- 39:12
And these are separate scenarios that run.
- 39:13
And you can have.
- 39:14
MySQL server and Apache web server running in parallel, and
- 39:18
this is what it mainly looks like when you do it.
- 39:21
We had default and all the other slides that were default here, now it gets
- 39:24
named to the host name you give the machine, either web or DB in our case.
- 39:28
And you can see what happens here.
- 39:32
And the very final thing is controlling these machines, because
- 39:34
if you have multiple machines and you do vagrant SSH.
- 39:36
Where we're going to end up.
- 39:39
These are the, these are all the commands again.
- 39:41
So, vagrant up will boot up all the machines.
- 39:43
If you have ten machines, you define in the vagrant
- 39:45
file, your system is going to set up ten machines.
- 39:48
Be careful with that cuz it might consume a lot of CPU, might consume a lot of ram.
- 39:52
So, be careful.
- 39:53
When you do vagrant ssh, you're going to log in to the primary vm.
- 39:57
And the primary vm, I'm at its primary here.
- 40:01
So that's your primary one.
- 40:02
When you type vagrant SSH, you're gonna end up in this one.
- 40:06
When you do vagrant destroy, all your boxes will be destroyed.
- 40:08
And then you could name them.
- 40:10
Vagrant up web.
- 40:11
I just wanna, boot up the web vm.
- 40:14
SSH into the web vm, Vagrant ssh web.
- 40:18
Vagrant destroy web.
- 40:19
Vagrant up db.
- 40:21
Vagrant ssh db.
- 40:23
And vagrant destroy db.
- 40:26
And that's all I have to say for today.
- 40:28
Remember people.
- 40:29
Vagrant up saves your life.
- 40:32
Thank you.
- 40:33
[SOUND] | https://teamtreehouse.com/library/vagrant-puppet-chef-ftw-managing-development-environments-made-easy | CC-MAIN-2019-18 | refinedweb | 10,349 | 81.63 |
setting up a new sub project for an implementation of JSR-301 is
definitely a good idea. I think we should start a discussion at
dev@myfaces.apache.org.
On 6/7/07, Scott O'Bryan <darkarena@gmail.com> wrote:
> So... What are the next steps for this? Much debate and voting?
>
> :)
>
> Scott
> Scott O'Bryan wrote:
> > I'm totally cool with that and I'm pretty sure the EG would be fine
> > with that as well. We just can't do things the same way as we did the
> > old bridge.
> >
> > Also, JSR-301 has 1.2 as it's minimum Faces version, so I imagine this
> > could become the bridge implementation for MyFaces' 1.2 implementation
> > since I'm not sure much work was done with the existing bridge on it.
> >
> > I believe Stan Silvert would also be interested in working on this as
> > well. He's currently on the 301 EG as well and wrote the existing
> > MyFaces bridge.
> >
> > Scott
> >
> > Matthias Wessendorf wrote:
> >> Well,
> >>
> >> things like tomahawk, tobago and trinidad are also able to run w/o
> >> MyFaces core.
> >> So why not making the bridge an own subproject?
> >>
> >> -M
> >>
> >> On 6/7/07, Scott O'Bryan <darkarena@gmail.com> wrote:
> >>> That's certainly an option except that the Bridge in MyFaces is
> >>> distributed with MyFaces project. Right now the work that I have time
> >>> for will be needed for an R.I. This means it'll need to be able to be
> >>> distributed independently. That being said, I'm all ok with getting it
> >>> developed as part of MyFaces...
> >>>
> >>> Scott
> >>>
> >>> Matthias Wessendorf wrote:
> >>> > Scott,
> >>> >
> >>> > since we have already a protlet bridge here in MyFaces, why not
> >>> making
> >>> > it a "301 bridge"?
> >>> >
> >>> > -Matthias
> >>> >
> >>> > On 6/6/07, Scott O'Bryan <darkarena@gmail.com> wrote:
> >>> >> Hey Martin,
> >>> >>
> >>> >> I am sort of scanning the list but the past few weeks have been
> >>> spotty.
> >>> >> I'll post back to the list. :) To answer your question,
> >>> documentation
> >>> >> is totally not there since most of the work I did for Trinidad
was
> >>> >> running only in a "Proof of Concept" environment similar to the
> >>> bridge
> >>> >> that will be provided for JSR-301. I don't think this work
> >>> currently
> >>> >> works with the existing MyFaces bridge.
> >>> >>
> >>> >> In this proof-of-concept, trinidad works with the following
> >>> limitations:
> >>> >>
> >>> >> 1. Some of the popup support does not work. I had a JIRA ticket
> >>> on this
> >>> >> when Trinidad was in incubator but I haven't checked to see if
it's
> >>> >> still there. I'll check it out.
> >>> >> 2. The javascript libraries are not namespaced meaning two trinidad
> >>> >> portlets on the screen at the same time may conflict. Again, I
> >>> had a
> >>> >> JIRA ticket on this and I'll check the current status.
> >>> >> 3. PPR in Trinidad has been disabled in a portal environment.
> >>> Things
> >>> >> that would normally do a ppr, will do a full-page submit instead
> >>> >>
> >>> >> Other then that, everything including FileUploads should work.
> >>> >>
> >>> >> Now I notices in the past month or so there has been much
> >>> interest in
> >>> >> fully supporting Trinidad in a Portlet environment. It's almost
> >>> there
> >>> >> but the biggest hurdle we have is the lack of a JSR-301 compliant
> >>> bridge
> >>> >> (or something that comes close). Some of the preliminary drafts
> >>> of the
> >>> >> spec have been released, but the Project is still looking for a
> >>> home to
> >>> >> host its R.I. Is this something people would be interrested in
> >>> doing as
> >>> >> part of MyFaces or the Bridges project? If so, how do we start
the
> >>> >> process?
> >>> >>
> >>> >> Scott O'Bryan
> >>> >>
> >>> >> Martin Marinschek wrote:
> >>> >> > Hi Scott,
> >>> >> >
> >>> >> > a while ago, I sent the inlined mail to the MyFaces user list
-
> >>> I'm
> >>> >> > sending it to you personally now, as I thought that maybe
you
> >>> are not
> >>> >> > scanning the list, and therefore missed it. I don't want to
> >>> bother you
> >>> >> > too much - but even a small pointer to any documentation on
> >>> this would
> >>> >> > be very helpful...
> >>> >> >
> >>> >> > regards,
> >>> >> >
> >>> >> > Martin
> >>> >> >
> >>> >> > -------------
> >>> >> >
> >>> >> > Hi *,
> >>> >> >
> >>> >> > I have skimmed through the online documentation for Trinidad,
but
> >>> >> > haven't found anything useful about portlet compatibility.
Is
> >>> there
> >>> >> > anyone in the Trinidad team who knows more about using portlets
> >>> with
> >>> >> > Trinidad, and can provide a link to more information?
> >>> >> >
> >>> >> > Especially I would be interested in:
> >>> >> >
> >>> >> > - file-upload - how's that handled in portlets?
> >>> >> > - including the script/style-elements in the header of the
page
> >>> >> > (obviously, tr:document won't help in a portlet environment,
> >>> right?)
> >>> >> > - serving out resources with the resources servlet/filter
(it's
> >>> clear
> >>> >> > that neither one will work in a portlet environment)
> >>> >> >
> >>> >> > I've heard about some jsf-portlet-bridge helping out here,
but
> >>> that's
> >>> >> > RI, right?
> >>> >> >
> >>> >> > regards,
> >>> >> >
> >>> >> > Martin
> >>> >>
> >>> >>
> >>> >
> >>> >
> >>>
> >>>
> >>
> >>
> >
> >
>
>
--
Your JSF powerhouse -
JSF Consulting, Development and
Courses in English and German
Professional Support for Apache MyFaces | http://mail-archives.apache.org/mod_mbox/myfaces-users/200706.mbox/%3C18ff88f90706080404u24eeb676s6fabae67a1a70ec0@mail.gmail.com%3E | CC-MAIN-2018-51 | refinedweb | 786 | 72.76 |
In this talk, I will show how to simplify an app’s architecture by letting the database drive the UI. We’ll explore powerful features of Realm such as change notifications and automatic updates to ensure we never have to manually update the UI again.
Introduction
My name is Nik, and I lead the .NET team at Realm. I want to cover the topic of simplicity and elegance in code. A few years ago, when I was in college, I made the most important decision of my life. I chose theoretical physics rather than computer science. It was the best decision ever because I got to explore the inner workings of the universe from subatomic particles all the way to black holes. What stuck with me most was how simple the laws of nature are, yet how complex it is to derive them.
For example, look at Schrödinger’s equation. It lays out the foundations of modern quantum mechanics, the field that deals with phenomena at a very small scale. Below that, on the other end of the spectrum is the Schwarzschild radius which tells us when an object becomes a black hole. You see a huge range of those equations, but they’re both really simple and elegant.
How is this relevant to us? If we can express the most complex of phenomena in the known universe in these really simple and elegant equations, then why do I need to write 120 lines of code just to update the label on my UI when some property changes on the backend?
Get more development news like this
I strongly believe that code elegance and simplicity are just as important to the success of your product as design.
What is MVVM?
MVVM was conceived by Microsoft architects in 2005 when they were trying to figure out a way to showcase the power of data binding in their cool new frameworks, WPF and Silverlight.
In its very essence, MVVM is an architectural pattern that defines a very strict chain of ownership and awareness of who knows what and who reports to whom. The three components are the Model, the View Model, and the View. The Model and the View Model are highly testable view-agnostic components, and a single UI component, the View, is separated from the rest, which front-end developers can work on individually.
Model
The Model is usually the most unambiguous and well-understood component in this pattern. Models contain all your business networking and persistence logic, and other things that are not directly related to your UI.
View
The View is responsible for defining the structure, the layout, the appearances, colors, animations, of your application. They should contain no business logic, no conversions. Ideally, they should contain no code at all.
For example, with XAML, which is Microsoft’s way of defining user interfaces, views are defined in an HTML-like syntax. With Cocoa or Swift, you may need to write some code for Interface Builder classes. Typically, views are not reusable outside of a single application unless they’re something very generic, such as a login screen or a settings screen may be reused across applications.
View Model
View models are something in between views and models. View models are responsible for massaging the models in a way that can be consumed by the view. For example, this can be done by combining data from several different models or converting data in the model to a view consumable format. For example, you can convert Boolean properties to colors or string paths to images. This is what the view model would look like in Swift:
public class PersonViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string firstName; public string FirstName { get { return this.firstName; } set { Set(value, ref this.firstName ); } } ... private void Set<T>(T value, ref T field, [CallerMemberName] string propertyName = null) { field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
View models can also contain commands that the view can invoke, such as when saving or deleting items, or changing the value in response to pressing a button. Those commands or events are later proxied to your models which are responsible for persisting the data or sending it to your services over the internet.
Unit Testing
The main selling points of your models are not so much their reusability, but their unit-testability. Because View Models do not depend on UI code, They should have no reference to UI frameworks, you can unitize them: you can invoke their commands from your unit tests, pretending you are the view and inspect how their properties change.
Lightweight Objects with Realm
Realm is a database that is mostly used on mobile. It is different from SQLite or Core Data or similar databases in that it is an object database.
The objects you work with in your application are the same objects that get persisted on disk. There is no intermediate layer, and there is no type conversion like in traditional SQL. As a result, objects in Realm are extremely lightweight. They never copy their data from disk to memory. Instead, internal functions and some metadata allow us to figure out the exact address at which the data is stored.
So, for example, when you access a
firstName property on an object, you do not get some cache throughout data that’s an in-memory representation of this string. Instead, we look it up, look at this property, find the offset and the length of the property on disk, read it, and return it to you. When you access it the second time, Realm does this again, and you will get the most up-to-date version that is saved in the database.
There are two ways in which Realm simplifies MVVM code. First, it eliminates the need for the view model to make complicated decisions about what the view is going to need. For example, if I want to display a
Person, I don’t need to fetch the entire
Person. I can just fetch the Realm model and pass it to the UI. Secondly, is that since we no longer need pagination; we don’t need to hook up scrolling events and go into the view model to fetch new data all the time.
Realm is a Live Object Database
When there’s no intermediate layer between your objects and your database, Realm objects and collections can be notified whenever something changes from the disk, regardless of where it originated from. This makes Realm a live object database. This puts Realm objects at the intersection of models and view models and allows you to pass them directly to your view and have the view data bind to properties.
Data Binding
Suppose that you want to expose all the people in your database ordered by the first name property. You can create the Realm query and data bind to it. As new data comes into the database, regardless of where it originates, Realm will emit notifications and tell your list view that the order has changed, or that new objects have been inserted or deleted.
In .NET, there’s a single data binding engine that is a built-in mechanism for that. Realm objects are supported out of the box. In Swift or Java where there are many third party data binding libraries, you may need to manually handle the notifications, or you could use some of the third party data binding libraries. One of the most popular of these for Swift is Bond. Obviously, you can use ReactiveExtensions.
Simplified Data Updates Demonstration
Let’s see some of the steps involved with fetching data from the server in a non-Realm scenario. First, the user requests an update by pressing a button. This, in turn, triggers a REST API call which fetches information from your server, and you deserialize and process the returning data.
The views contain references to different View Models, and you have to find all that may potentially be affected by these changes - this is a difficult task. You have to keep a reference to all the View Models you created and then walk through them and find them. You can either
diff them, or you can reload the data.
A talk called offline-first by Miguel Quinones illustrates why reloading data is an extremely poor user experience.
In a shared shopping list, for example, I only want what needs to be updated to be updated. Suppose you decide to
diff the changes, you are still faced with the problem of notifying all your view models or the affected view models that something has changed, or notifying their parents that their underlying view models have changed. Only if everything has been wired correctly, your UI will update correctly.
If you use Realm, you eliminate that complexity. You just save to disk and let Realm handle the rest. Realm sits at the bottom of your application at the persistence layer. As a result, it knows when a property or collection has changed and will notify the Realm objects that are still alive. The MVVM benefits are free out of the box, and you lose nothing from using Realm.
new
About the content
This talk was delivered live in October 2017 at Mobilization. The video was transcribed by Realm and is published here with the permission of the conference organizers and speakers. | https://academy.realm.io/posts/mobilization-2017-nikola-irinchev-mvvm-realm/ | CC-MAIN-2018-43 | refinedweb | 1,562 | 61.26 |
!
Hi Raymond,
If you need to select data from a set of data tables and insert them into another you can take a look at LINQ to DataSet to greate a join between the three tables:
You can also use the dataset functions themselves to select data out, take a look at the ADO.NET documentation in the MSDN library for that.
HTH,
-B
Hi Jenn,
I'm not quite sure what you're asking. This example creates a spreadsheet using pure XML so it sould be in almost any type of application including Windows Forms.
Thanks Beth for your kind reply.
HELP!! AARRGGHH!! I'm new to VB 2008 or whatever its called. I need to import from an Excel spredsheet that has about twenty tabs and LOADS of info on each tab and I need to import all of it into a database where they will input each record one at a time after that. but the import is killing me! what do i do? :(
The thing is, datasets and adapters and that stuff is too complicated to work with. the xml is a good thing but the datasets aren't. and ... ... i just want to import. that's all. after that it'll be pretty easy.
Hi Beth,
Good stuff.
If using your given example and there duplicated abbrev in xml files.
How do i import to dataset make abbrev unique?
Tx Alot
Cheers
Dim sheet = <?xml version="1.0"?>
This is a phrase in the Private Sub btnExport_Click.
When I copied this in my source it gives me the remark: 'Variable declaration without an As clause....'
How can I make this being accepted without creating the declaration?
By the way, your solution is very helpfull.
Ivo.
Hi Ivo,
You need to make sure Option Strict is Off and Option Infer is ON. See msdn.microsoft.com/.../bb384665.aspx
Thanks for your reply. i have my solution running.
Carl Kelly did a nice job. Now i have a guestion about If statements in XML.
My columns have different widths. Now, while looping through de columns I want to set the widths in XML language.
Here you have my source for now:
<%= From t In source.Tables _
Let excelColumnDataType = GetColumnDataTypes(t.columns) _
Select <Worksheet ss:Name=<%= t.TableName %>>
<Table ss:ExpandedColumnCount=<%= t.Columns.Count %> ss:ExpandedRowCount=<% = t.Rows.Count + 1 %> x:
<%= From c In Enumerable.Range(0, t.Columns.Count) _
Select <Column ss:Index=<%= (c + 1) %> ss:
<ss:if test=<%= c = 1 %>>>
<column ss:Index=<%= c %> ss:
</ss:if>
</Column> %>
<Row>
<%= From c In Enumerable.Range(0, t.Columns.Count) _
Select <Cell ss:<Data ss:<%= t.Columns(c).Caption %></Data></Cell> %>
</Row>
</Table>
</Worksheet> %>
Maybe, you have a solution for the if statement.
Thanks in advance,
Great job Beth.
But I'm having this same problem:
"The problem I am experiencing is when a cell in the spreadsheet for a given field is blank, the data in the columns next to it are all shifted over to the left and end up basically in the wrong columns."
Could you suggest a solution ? Thanks, Marzio
The exporting part worked excellently but i have been trying to import the data but I couldn't
This example is good enough for simple exporting to Excel if you aren't trying to generate reports. It is fraught with a host of problems especially related to formatting and indexing of rows if you attempt reports. Better stick with your ExcelWriter or SSRS if you are trying that.
@Swami - correct this is meant for simple export/import of data. If you need to format it more like a report you can also take a look at Open XML.
How can i get rid of the namespaces on each tag?
<Row xmlns="urn:schemas-microsoft-com:office:spreadsheet">
<Cell ss:
<Data ss:</Data>
</Cell>
</Row>
i followed ur example, changed a few to functions that generate XElements (like getWorksheetXML, etc..)
But when i export it, it puts all these namespaces on each tag..
Heres what my Code looks like
Dim xmlExport = <>Nard</Author>
<LastAuthor>Nard</LastAuthor>
<Created>2011-09-13T00:53:42Z</Created>
<Version>14.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>7995</WindowHeight>
<WindowWidth>17235</WindowWidth>
<WindowTopX>120</WindowTopX>
<WindowTopY>75</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<%= getStyles() %>
<%= Me.ActiveWorksheet.ToXML %>
</Workbook>
... where getStyles() produces the Styles Tags and Me.ActiveWorkSheet.ToXML produces the Worksheet xml Tag. How can i get rid of the namespaces on each tag? Thanks
Hi Beth - followed your video to export to Excel, but am trying to adapt to using an existing XML file. The XML is structured like this - note the element DIMS:
<TRUCKS>
<TRUCK Counter="0">
<CARRIER>A. BLAIR ENTERPRISES</CARRIER>
<CARRIERPHONE>(502)326-0500</CARRIERPHONE>
<UNITNO>421</UNITNO>
<UNITTYPE>SMALL STRAIGHT </UNITTYPE>
<DISTANCE>0</DISTANCE>
<AVAILABLE>06/26/2012 17:00</AVAILABLE>
<STATUS>On A Load</STATUS>
<LOCATION>JACKSONVILLE, FL</LOCATION>
<NOTE> TEAM REAL TIME GPS TRACKED</NOTE>
<PAYLOAD>3300</PAYLOAD>
<DIMS>
<BOXLENGTH>0</BOXLENGTH>
<BOXWIDTH>0</BOXWIDTH>
<BOXHEIGHT>0</BOXHEIGHT>
</DIMS>
<DOMICILE>US</DOMICILE>
<SATELLITE>N</SATELLITE>
</TRUCK>
...
My code looks like this:
Imports Excel stuff....
Imports System.Xml.XPath
Public Class ExportToExcel
Shared Sub ExportData(ByVal xmlBuffer As String)
Dim xDoc = XDocument.Parse(xmlBuffer)
Dim trucks = From s In xDoc.Descendants("TRUCKS")
Select <Row>
<Cell><Data ss:<%= s.XPathSelectElement("CARRIER") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("CARRIERPHONE") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("UNITNO") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("UNITTYPE") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("DISTANCE") %></Data></Cell>
<Cell ss:<Data ss:<%= s.XPathSelectElement("AVAILABLE") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("STATUS") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("LOCATION") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("NOTE") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("PAYLOAD") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("LENGTH") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("WIDTH") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("HEIGHT") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("DOMICILE") %></Data></Cell>
<Cell><Data ss:<%= s.XPathSelectElement("SATELLITE") %></Data></Cell>
</Row>
I'm getting the spreadsheet, but not the values - any idea what I'm doing wrong? | http://blogs.msdn.com/b/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx?PageIndex=6 | CC-MAIN-2013-48 | refinedweb | 1,039 | 51.55 |
D (The Programming Language)/d2/Slicing
Lesson 9: Slicing and a Deeper Look into Dynamic Arrays[edit]
Slicing in D is one of the language's most powerful and useful aspects. This lesson is really more of a continuation of the last lesson - you will also get a deeper look into how D's arrays work.
Introductory Code[edit]
import std.stdio; void writeln_middle(string msg) { writeln(msg[1 .. $ - 1]); } void main() { int[] a = [1,3,5,6]; a[0..2] = [6,5]; writeln(a); // [6, 5, 5, 6] a[0..$] = [0,0,0,0]; writeln(a); // [0, 0, 0, 0] a = a[0 .. 3]; writeln(a); // [0, 0, 0] a ~= [3,5]; writeln(a); // [0, 0, 0, 3, 5] int[] b; b.length = 2; b = a[0 .. $]; writeln(b.length); // 5 b[0] = 10; writeln(b); // [10, 0, 0, 3, 5] writeln(a); // [10, 0, 0, 3, 5] writeln_middle("Phobos"); // hobo writeln_middle("Phobos rocks"); }
Concepts[edit]
What are Slices?[edit]
You can take slices of arrays in D with this syntax:
arr[start_index .. end_index]
The element at
end_index is not included in the slice. Remember that dynamic arrays are just structures with a pointer to the first element and a length value. Taking a slice of a dynamic array simply creates a new one of those pointer structures that points to the elements of that same array.
string a = "the entire part of the array"; string b = a[11 .. $]; // b = "part of the array" // b points to the last 17 elements of a // If you modify individual elements of b, a will also // change since they point to the same underlying array!
Three Ways to Do the Same Thing[edit]
Notice that the
$ is automatically replaced with the length of the array being sliced from. The following three lines are equivalent and both create slices of the entirety of an array
arr.
char[] a = arr[0 .. $];
char[] a = arr[0 .. arr.length];
char[] a = arr[]; // shorthand for the above
A Visual Representation[edit]
The
.capacity Property[edit]
All dynamic arrays in D have a
.capacity property. It is the maximum amount of elements that can be appended to that array without having to move the array somewhere else (reallocation).
int[] a = [1,2,3,45]; writeln("Ptr: ", a.ptr); writeln("Capacity: ", a.capacity); a.length = a.capacity; // the array reaches maximum length writeln("Ptr: ", a.ptr, "\nCapacity: ", a.capacity); // Still the same a ~= 1; // array has exceeded its capacity // it has either been moved to a spot in memory with more space // or the memory space has been extended // if the former is true, then a.ptr is changed. writeln("Capacity: ", a.capacity); // Increased
Maximizing Efficiency by Only Reallocating When Necessary[edit]
It is good for efficiency to make sure that appending and concatenation do not cause too many reallocations because it is an expensive procedure to reallocate a dynamic array. The following code may reallocate up to 5 times:
int[] a = []; a ~= new int[10]; a ~= [1,2,3,4,5,6,7,8,9]; a ~= a; a ~= new int[20]; a ~= new int[30];
Make sure that the array
capacity is big enough at the beginning to allow for efficient non-reallocating array appends and concatenations later if performance is a concern. You can't modify the
.capacity property. You are only allowed to either modify the length, or use the
reserve function.
int[] a = [1,2,3,45]; a.reserve(10); // if a's capacity is more than 10, nothing is done // else a is reallocated so that it has a capacity of at least 10
When Passed to Functions[edit]
Remember that D's arrays are passed to functions by value. When static arrays are passed, the entire array is copied. When a dynamic array is passed, only that structure with the pointer to the underlying array and the length is copied - the underlying array is not copied.
import std.stdio; int[] a = [1,2,3]; void function1(int[] arr) { assert(arr.ptr == a.ptr); // They are the same // But the arr is not the same as a // If arr's .length is modified, a is unchanged. // both arr and a's .ptr refer to the same underlying array // so if you wrote: arr[0] = 0; // both arr and a would show the change, because they are both // references to the same array. // what if you forced arr to reallocate? arr.length = 200; // most likely will reallocate // now arr and a refer to different arrays // a refers to the original one, but // arr refers to the array that's reallocated to a new spot arr[0] = 0; writeln(arr[0]); // 0 writeln(a[0]); // 1 } void main() { function1(a); }
As you can see, there are a few possibilities if you pass a dynamic array to a function that looks like this:
void f(int[] arr) { arr.length = arr.length + 10; arr[0] += 10; }
- First possibility: the array's capacity was large enough to accommodate the resizing, so no reallocation occurred. The original underlying array's first element was modified.
- Second possibility: the array's capacity was not large enough to accommodate the resizing, but D's memory management was able to extend the memory space without copying the entire array. The original underlying array's first element was modified.
- Third possibility: the array's capacity was not large enough to accommodate the resizing. D's memory management had to reallocate the underlying array into a completely new space in memory. The original underlying array's first element was not modified.
What if you want to make sure that the following works?
int[] a = [0,0,0]; f(a); assert(a[0] == 10);
Simply change the function
f so that dynamic arrays are passed by reference:
void f(ref int[] arr) { arr.length = arr.length + 10; arr[0] += 10; }
Appending to Slices[edit]
When you take a slice of a dynamic array, and then append to that slice, whether the slice is reallocated depends on where the slice ends. If the slice ends in the middle of the data from the original array, then appending to that slice would cause a reallocation.
int[] a = [1,2,3,4]; auto b = a[1 .. 3]; writeln(b.capacity); // 0 // b cannot possibly be appended // without overwriting elements of a // therefore, its capacity is 0 // any append would cause reallocation
Lets say you took a slice of a dynamic array, and that slice ends at where the dynamic array ends. What if you appended to the dynamic array so that the slice no longer ends at where the dynamic array's data ends?
int[] a = [1,2,3,4]; writeln(a.capacity); // 7 auto b = a[1 .. 4]; writeln(b.capacity); // 6 a ~= 5; // whoops! // now the slice b does *not* end at the end of a writeln(a.capacity); // 7 writeln(b.capacity); // 0
The
.capacity property of a slice does indeed depend on other references to the same data.
Assignment-To-Slices[edit]
An Assignment-To-Slice looks like this:
a[0 .. 10] = b
You are assigning
b to a slice of
a You have actually seen Assignment-to-Slices in the last two lessons, even before you learned about slices. Remember this?
int[] a = [1,2,3]; a[] = 3;
Remember that
a[] is shorthand for
a[0 .. $] When you assign a
int[] slice to a single
int value, that
int value is assigned to all the elements within that slice. An Assignment-To-Slice always causes data to be copied.
int[4] a = [0,0,0,0]; int[] b = new int[4]; b[] = a; // Assigning an array to a slice // this guarantees array-copying a[0] = 10000; writeln(b[0]); // still 0
Beware! Whenever you use Assignment-To-Slice, the left and right sides'
.length values must match! If not, there will be a runtime error!
int[] a = new int[1]; a[] = [4,4,4,4]; // Runtime error!
You also must make sure that the left and right slices do not overlap.
int[] s = [1,2,3,4,5]; s[0 .. 3] = s[1 .. 4]; // Runtime error! Overlapping Array Copy
Vector Operations[edit]
Let's say you wanted to double each and every integer element of an array. Using D's vector operation syntax, you can write any of these:
int[] a = [1,2,3,4]; a[] = a[] * 2; // each element in the slice is multiplied by 2
a[0 .. $] = a[0 .. $] * 2; // more explicit
a[] *= 2 // same thing
Likewise, if you wanted to perform this operation:
[1, 2, 3, 4] (int[] a) + [3, 1, 3, 1] (int[] b) = [4, 3, 6, 5]
You would write this:
int[] a = [1, 2, 3, 4]; int[] b = [3, 1, 3, 1]; a[] += b[]; // same as a[] = a[] + b[];
Just like for Assignment-To-Slice, you have to make sure the left and right sides of vector operations have matching lengths, and that the slices do not overlap. If you fail to follow that rule, the result is undefined (There would be neither a runtime error nor a compile-time error).
Defining Array Properties[edit]
You can define your own array properties by writing functions in which the first argument is an array.
void foo(int[] a, int b) { // do stuff } void eggs(int[] a) { // do stuff } void main() { int[] a; foo(a, 1); a.foo(1); // means the same thing eggs(a); a.eggs; // you can omit the parentheses // (only when there are no arguments) }
Tips[edit]
- Steven Schveighoffer's article "D Slices" is an excellent resource if you want to learn more. | http://en.wikibooks.org/wiki/D_(The_Programming_Language)/d2/Lesson_9 | CC-MAIN-2014-42 | refinedweb | 1,595 | 63.39 |
Email has been around for a pretty long time, 45 years to be exact. But even as old as it is, email is still a critical part of our lives. So it’s inevitable that whether you are writing a server script or a website, you need to be able to send out an email. Most modern programming frameworks have the ability to send email, but they usually rely on the local computer being able to relay email. Sometimes that is fine, but other times it becomes a bit of a pain to depend on the local system being configured correctly. That’s where SparkPost comes in. SparkPost is an email delivery service. They provide an API and your code can generate emails that SparkPost will send. Now that’s a 30 second summary of what they do, but there’s a lot more you can do with SparkPost and emails. Of course, one thing that makes SparkPost attractive to developers is that you can send 100,000 emails a month for free. So if you’re just learning about their service, or just writing a small application that needs to send email, SparkPost is a free service for you.
Getting Started with SparkPost
To get started using Sparkpost is pretty simple. First, you should have the ability to manage your domain’s email and DNS. Now head over to sparkpost.com. Click Try for Free, provide your email address and a password.
Next, you’ll be prompted to confirm control of the sending domain. The easiest way is to select the postmaster@domain.com option. I went into my Email System and created the postmaster@domain.com address, forwarding it to my email. SparkPost will then send a confirmation email to that address. Click the link and you’re done.
Then you’ll be asked if you want to create emails via SMTP or REST API. I think most people will want to go with API. Choose Get a Key and then an API Key will be generated for you. Make sure you save the API Key because you won’t be able to access it later. You’ll need this key in your applications.
At this point your ready to start sending email. Now SparkPost has a number other features which are pretty powerful and you may want to check. For this post, I’m just to focus on basic email sending. But some of the other available features include Email List management, including people who have opted-out. Email templating is also available, as well as real-time tracking of email delivery and message, opens.
One more thing I want to highlight is the SparkPost message tracking features. From the Dashboard, this is available under Reports. SparkPost shows you in near-realtime, the tracking of emails as they’re created, sent, received, and even opened. This makes troubleshooting email problems really easy because you can see where emails are in the delivery process.
SparkPost with WordPress
If you want to configure your WordPress site to use SparkPost for sending email, they have their own WordPress Plugin available. I have to say using SparkPost in WordPress is really simple, and it has saved me a lot of headaches. I’ve used the SparkPost plugin with some of my clients whose hoster started blocking their email. Switching over to SparkPost completely bypasses the SMTP nightmare with some hosters (GoDaddy, Bluehost, I’m looking at you). Once you have the plugin installed and configured, all email will automatically route through SparkPost
The setup is pretty easy. Install the Plugin from WordPress repository, activate it, and then go to the Plugin Settings (located as a submenu under Settings).
To get the Plugin working you just need to check the “Send email using SparkPost” checkbox. Then paste in the API Key you created earlier. Click Save at the bottom and you’re done. There’s a few optional setting you may want to use. For example, you can override the WordPress default email address and name. You can also utilize SparkPost Templates in WordPress.
SparkPost with Python
I’m a big fan of using SparkPost in Python scripts. Instead of having to setup and configure Sendmail on each server I can just use SparkPost.
A fully function Python client is available on Github including full documentation. Setup is pretty easy with PIP
sudo pip install sparkpost
Sending email is equally simple in Python. I usually create a Function like the one below. To simplify storing my API Keys I have one config file on my server with various API Keys. I then load them as needed.
from sparkpost import SparkPost Config = ConfigParser.ConfigParser() Config.read("/opt/agnet/conf/agnet.conf") def get_config_value(section): dict1 = {} options = Config.options(section) for option in options: try: dict1[option] = Config.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1 def Send_Message(sendto, message, subject): sp = SparkPost(get_config_value("cloud")['sparkpost_key']) response = sp.transmissions.send( recipients=[sendto], html=message, from_email='WireandFrost <postmaster@wireandfrost.com>', subject=subject ) print(response) return
SparkPost with PHP
If you’re writing PHP code and want to tap into SparkPost there’s a PHP client published on Github. Just like the Python client, its easy to setup and get working. The Readme on Github provides all the details to get started, but the basic PHP code to send email looks like this:
<?php require 'vendor/autoload.php'; use SparkPost\SparkPost; use GuzzleHttp\Client; use Http\Adapter\Guzzle6\Client as GuzzleAdapter; $httpClient = new GuzzleAdapter(new Client()); $sparky = new SparkPost($httpClient, ['key'=>'YOUR_API_KEY']); $promise = $sparky->transmissions->post([ 'content' => [ 'from' => [ 'name' => 'WireandFrost', 'email' => 'portsmater@wireandfrost.com', ], 'subject' => 'First Mailing From PHP', 'html' => '<html><body><h1>Congratulations, {{name}}!</h1><p>You just sent your very first mailing!</p></body></html>', 'text' => 'Congratulations, {{name}}!! You just sent your very first mailing!', ], 'substitution_data' => ['name' => 'YOUR_FIRST_NAME'], 'recipients' => [ [ 'address' => [ 'name' => 'YOUR_NAME', 'email' => 'YOUR_EMAIL', ], ], ], ]); ?>
So if you’re looking for a framework to making managing email just a little bit easier, I think SparkPost is really the tool for the job. The promise fast (and cheap/free) and efficient email delivery, with real-time tracking. From what I’ve seen, they really deliver on these promises. And with many official and non-official clients available, it’s very easy to get started. | https://wireandfrost.com/sparkpost-coding/ | CC-MAIN-2019-39 | refinedweb | 1,062 | 66.54 |
I looked at the calendar today, and it turns out that I've been back from New Zealand for four weeks now. That's hard to believe: I haven't achieved a great deal in all that time, and it sucks to be back.
There's an interesting post on the binutils list about printf as a macro:
printf ("%*s", #ifdef BFD64 16, #else 8, #endif "");
If printf is a macro, this is nonportable because the preprocessor is not required to be able to handle directives while it's reading the arguments in a macro invocation (ISO/IEC 9899:1999 6.10.3 para 11). In particular, current GCC doesn't handle it.
But what kind of freak would define printf as a macro?
It turns out that doing that is valid: (ibid 7.1.3, and the same language is in C89 too)
[U]nless explicitly stated otherwise [for that function] [...] Any function declared in a header may be additionally implemented as a function-like macro defined in the header
Perhaps it's just me, but I find that surprising. I knew simple things like abs() were allowed to be macros and expected them to be, but I didn't realise the implementer was allowed to provide macro versions of pretty much everything. I'm sure I've written code like the above in the past (or maybe it was just with my own functions, but I don't think so).
The obvious fix is to write the whole printf twice. There's two other solutions too: one cute (but possibly hard on moronic maintainence programmers), and the other surprising at first that it is acceptable, but not when you think about it. IMHO.
The nice thing is that the standard actually tells you all about these solutions. That's unusually friendly for the C standard. :-) | http://www.advogato.org/person/johnm/diary.html?start=12 | CC-MAIN-2014-42 | refinedweb | 307 | 69.01 |
FIN 515 Week 8 Final Exam (Version 2)
Purchase here
Product Description
1. (TCO A) Which of the following statements is NOT correct? (Points : 5)
2. (TCO F) Which of the following statements is correct? (Points : 5) (a) (TCO F) Which of the following statements is correct? (Points : 5)
3. 3 (TCO D) The Ackert Company's last dividend was $1.55. The dividend growth rate is expected to be constant at 1.5% for 2 years, after which dividends are expected to grow at a rate of 8.0% forever. The firm's required return (rs) is 12.0%. What is the best estimate of the current stock price? (a) (TCO D) Church Inc. is presently enjoying relatively high growth because of a surge in the demand for its new product. Management expects......?
4. (TCO G) Singal Inc. is preparing its cash budget. It expects to have sales of $30,000 in January, $35,000 in February, and $35,000 in March. If 20% of sales are for cash, 40% are credit sales paid in the month......?
5. (TCO G)?.......
6. (TCO H) The Dewey Corporation has the following data, in thousands. Assuming a 365-day year, what is the firm's cash conversion cycle?
7. (TCO C) Your company has been offered credit terms of 4/30, net 90 days. What will be the nominal annual percentage cost of its nonfree trade credit if it pays 120 days after the purchase? (Assume a 365-day year.)
8. ... | http://www.brainia.com/essays/Fin-515-Week-8-Final-Exam/368099.html | CC-MAIN-2017-13 | refinedweb | 249 | 77.53 |
OpenGL windows and contexts
There are many ways you can perform OpenGL rendering in Qt. The most straightforward way that we will mainly use is to subclass QOpenGLWindow. It allows OpenGL to render your content directly to a whole window and is suitable if you draw everything in your application with OpenGL. You can make it a fullscreen window if you want. However, later we will also discuss other approaches that will allow you to integrate OpenGL content into a widget-based application.
The OpenGL context represents the overall state of the OpenGL pipeline, which guides the process of data processing and rendering to a particular device. In Qt, it is represented by the QOpenGLContext class. A related concept that needs explanation is the idea of an OpenGL context being "current" in a thread. The way OpenGL calls work is that they do not use any handle to any object containing information on where and how to execute the series of low-level OpenGL calls. Instead, it is assumed that they are executed in the context of the current machine state. The state may dictate whether to render a scene to a screen or to a frame buffer object, which mechanisms are enabled, or the properties of the surface OpenGL is rendering on. Making a context "current" means that all further OpenGL operations issued by a particular thread will be applied to this context. To add to that, a context can be "current" only in one thread at the same time; therefore, it is important to make the context current before making any OpenGL calls and then marking it as available after you are done accessing OpenGL resources.
QOpenGLWindow has a very simple API that hides most of the unnecessary details from the developer. Apart from constructors and a destructor, it provides a small number of very useful methods. First, there are auxiliary methods for managing the OpenGL context: context(), which returns the context, and makeCurrent() as well as doneCurrent() for acquiring and releasing the context. The class also provides a number of virtual methods we can re-implement to display OpenGL graphics.
We will be using the following three virtual methods:
initializeGL() is invoked by the framework once, before any painting is actually done so that you can prepare any resources or initialize the context in any way you require.
paintGL() is the equivalent of paintEvent() for the widget classes. It gets executed whenever the window needs to be repainted. This is the function where you should put your OpenGL rendering code.
resizeGL() is invoked every time the window is resized. It accepts the width and height of the window as parameters. You can make use of that method by re-implementing it so that you can prepare yourself for the fact that the next call to paintGL() renders to a viewport of a different size.
Before calling any of these virtual functions, QOpenGLWindow ensures that the OpenGL context is current, so there is no need to manually call makeCurrent() in them.
GUI scalability—most.
What just happened?
First,
rod variable that will hold the last Rod object for all the closures.
Time for action – Adding an import
The default object palette contains a very minimal set of types provided by the QtQuick module. To access a richer set of controls, we need to add an import directive to our document. To do this, locate the Library pane in the top-left corner of the window and go to its Imports tab. Next, click on Add Import and select QtQuick.Controls 2.2 in the drop-down list. The selected import will appear in the tab. You can click on the × button to the left of the import to remove it. Note that you cannot remove the default import.
Adding the import using the form editor will result in adding the import QtQuick.Controls 2.2 directive to the .ui.qml file. You can switch the main area to the Text Editor mode to see this change.
Now you can switch back to the QML Types tab of the Library pane. The palette will contain controls provided by the imported module.
The error signal
Instead of dealing with errors in the slot connected to the finished() signal, you can use the reply's error() signal, which passes the error of the QNetworkReply::NetworkError type to the slot. After the error() signal has been emitted, the finished() signal will, most likely, also be emitted shortly.
Properties
In Chapter 3, Qt GUI Programming, we edited predefined properties of widgets in the form editor and used their getter and setter methods in the code. However, until now, there wasn't a real reason for us to declare a new property. It'll be useful with the Animation framework, so let's pay more attention to properties.
Only classes that inherit QObject can declare properties. To create a property, we first need to declare it in a private section of the class (usually right after the Q_OBJECT mandatory macro) using a special Q_PROPERTY macro. That macro allows you to specify the following information about the new property:
The property name—a string that identifies the property in the Qt meta system.
The property type—any valid C++ type can be used for a property, but animations will only work with a limited set of types.
Names of the getter and setter method for this property. If declared in Q_PROPERTY, you must add them to your class and implement them properly.
Name of the signal that is emitted when the property changes. If declared in Q_PROPERTY, you must add the signal and ensure that it's properly emitted.
There are more configuration options, but they are less frequently needed. You can learn more about them from the The Property System documentation page.
The Animation framework supports the following property types: int, unsigned int, double, float, QLine, QLineF, QPoint, QPointF, QSize, QSizeF, QRect, QRectF, and QColor. Other types are not supported, because Qt doesn't know how to interpolate them, that is, how to calculate intermediate values based on the start and end values. However, it's possible to add support for custom types if you really need to animate them.
Similar to signals and slots, properties are powered by moc, which reads the header file of your class and generates extra code that enables Qt (and you) to access the property at runtime. For example, you can use the QObject::property() and QObject::setProperty() methods to get and set properties by name.
What just happened?
The qApp macro is a shortcut for a function that returns a pointer to the application singleton object, so when the action is triggered, Qt will call the quit() slot on the QApplication object created in main(), which, in turn, will cause the application to end.
Time for action – Showing the download progress
Especially when a big file is downloaded, the user usually wants to know how much data has already been downloaded and approximately how long it will take for the download to finish.
In order to achieve this, we can use the reply's downloadProgress() signal. As the first argument, it passes the information on how many bytes have already been received and as the second argument, how many bytes there are in total. This gives us the possibility to indicate the progress of the download with QProgressBar. As the passed arguments are of the qint64 type, we can't use them directly with QProgressBar, as it only accepts int. So, in the connected slot, we can do the following:
void SomeClass::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
qreal progress = (bytesTotal < 1) ? 1.0
: static_cast<qreal>(bytesReceived) / bytesTotal;
progressBar->setValue(qRound(progress * progressBar->maximum()));
}
What just happened?
We created a new private slot in the MainWindow class and connected the clicked() signal of the Start new game button to the slot. When the user clicks on the button, Qt will call our slot, and the code we wrote inside it gets executed.
Ensure that you put any operations with the form elements after the setupUi() call. This function creates the elements, so
ui->startNewGame will simply be uninitialized before setupUi() is called, and attempting to use it will result in undefined behavior.
qDebug() << ... is a convenient way to print debug information to the stderr (standard error output) of the application process. It's quite similar to the std::cerr << ... method available in the standard library, but it separates supplied values with spaces and appends a new line at the end.
Putting debug outputs everywhere quickly becomes inconvenient. Luckily, Qt Creator has powerful integration with C++ debuggers, so you can use Debug mode to check whether some particular line is executing, see the current values of the local variables at that location, and so on. For example, try setting a break point at the line containing qDebug() by clicking on the space to the left of the line number (a red circle indicating the break point should appear). Click on the Start Debugging button (a green triangle with a bug at the bottom-left corner of Qt Creator), wait for the application to launch, and press the Start new game button. When the application enters the break point location, it will pause, and Qt Creator's window will be brought to the front. The yellow arrow over the break point circle will indicate the current step of the execution. You can use the buttons below the code editor to continue execution, stop, or execute the process in steps. Learning to use the debugger becomes very important when developing large applications. We will talk more about using the debugger later (Online Chapter,).
The client
The GUI of the client (TcpClient) is pretty simple. It has three input fields to define the server's address (ui->address), the server's port (ui->port), and a username (ui->user). Of course, there is also a button to connect to (ui->connect) and disconnect from (ui->disconnect) the server. Finally, the GUI has a text edit that holds the received messages (ui->chat) and a line edit (ui->text) to send messages.
Optimization
When adding many items to a scene or using items with complex paint() functions, the performance of your application may decrease. While default optimizations of Graphics View are suitable for most cases, you may need to tweak them to achieve better performance. Let's now take a look at some of the optimizations we can perform to speed up the scene.
Using other encodings
As we've already mentioned, QString has convenient methods for decoding and encoding data in the most popular encodings, such as UTF-8, UTF-16, and Latin1. However, Qt knows how to handle many other encodings as well. You can access them using the QTextCodec class. For example, if you have a file in Big-5 encoding, you can ask Qt for a codec object by its name and make use of the fromUnicode() and toUnicode() methods:
QByteArray big5Encoded = big5EncodedFile.readAll();
QTextCodec *big5Codec = QTextCodec::codecForName("Big5");
QString text = big5Codec->toUnicode(big5Encoded);
QByteArray big5EncodedBack = big5Codec->fromUnicode(text);
You can list the codecs supported on your installation using the QTextCodec::availableCodecs() static method. In most installations, Qt can handle almost 1,000 different text codecs.
What just happened?
We created a very simplistic API for implementing chess-like games by introducing the newGame() and move() virtual methods to the algorithm class. The former method simply sets up everything. The latter uses simple checks to determine whether a particular move is valid and whether the game has ended. We use the m_fox member variable to track the current position of the fox to be able to quickly determine whether it has any valid moves. When the game ends, the gameOver() signal is emitted and the result of the game can be obtained from the algorithm. You can use the exact same framework for implementing all chess rules.
Handling user input
The first way of receiving events in Qt 3D is to use Qt GUI capabilities. The Qt3DQuickWindow class we use inherits from QWindow. That allows you to subclass Qt3DQuickWindow and reimplement some of its virtual functions, such as keyPressEvent() or mouseMoveEvent(). You are already familiar with this part of Qt API because it's roughly the same as provided by Qt Widgets and Graphics View. Qt 3D doesn't introduce anything special here, so we won't give this approach much attention.
Similar to Qt Quick, Qt 3D introduces a higher-level API for receiving input events. Let's see how we can use it.
Accessing OpenGL functions
Interaction with OpenGL is usually done through calling functions provided by the OpenGL library. For example, in a regular C++ OpenGL application, you can see calls to OpenGL functions such as glClearColor(). These functions are resolved when your binary is linked against the OpenGL library. However, when you write a cross-platform application, resolving all the required OpenGL functions is not trivial. Luckily, Qt provides a way to call OpenGL functions without having to worry about the platform-specific details.
In a Qt application, you should access OpenGL functions through a family of QOpenGLFunctions classes. The QOpenGLFunctions class itself only provides access to functions that are part of OpenGL ES 2.0 API. This subset is expected to work at most desktop and embedded platforms supported by Qt (where OpenGL is available at all). However, this is a really limited set of functions, and sometimes you may want to use a more recent OpenGL version at the cost of supporting less platforms. For each known OpenGL version and profile, Qt provides a separate class that contains the set of available functions. For example, the QOpenGLFunctions_3_3_Core class will contain all functions provided by the OpenGL 3.3 core profile.
The approach recommended by Qt is to select the OpenGL functions class corresponding to the version you want to use and add this class an the second base class of your window or widget. This will make all OpenGL functions from that version available within your class. This approach allows you to use code that was using the OpenGL library directly without changing it. When you put such code in your class, the compiler will, for example, use the QOpenGLFunctions::glClearColor() function instead of the global glClearColor() function provided by the OpenGL library.
However, when using this approach, you must be careful to only use functions provided by your base class. You can accidentally use a global function instead of a function provided by Qt classes if the Qt class you choose does not contain it. For example, if you use QOpenGLFunctions as the base class, you can't use the glBegin() function, as it is not provided by this Qt class. Such erroneous code may work on one operating system and then suddenly not compile on another because you don't link against the OpenGL library. As long as you only use OpenGL functions provided by Qt classes, you don't have to think about linking with the OpenGL library or resolving functions in a cross-platform way.
If you want to ensure that you only use Qt OpenGL function wrappers, you can use the Qt class as a private field instead of a base class. In that case, you have to access every OpenGL function through the private field, for example, m_openGLFunctions->glClearColor(). This will make your code more verbose, but at least you will be sure that you don't accidentally use a global function.
Before using Qt OpenGL functions, you have to call the initializeOpenGLFunctions() method of the functions class in the current OpenGL context. This is usually done in the initializeGL() function of the window. The QOpenGLFunctions class is expected to always initialize successfully, so its initializeOpenGLFunctions() method doesn't return anything. In all the other functions' classes, this function returns bool. If it returns false, it means that Qt was not able to resolve all the required functions successfully, and your application should exit with an error message.
In our examples, we will use the QOpenGLFunctions_1_1 class that contains all OpenGL functions we'll use. When you're creating your own project, think about the OpenGL profile you want to target and select the appropriate functions class.
Time for action - Making Benjamin move
The next thing we want to do is make our elephant movable. In order to achieve that, we add a QTimer m_timer private member to MyScene. QTimer is a class that can emit the timeout() signal periodically with the given interval. In the MyScene constructor, we set up the timer with the following code:
m_timer.setInterval(30);
connect(&m_timer, &QTimer::timeout,
this, &MyScene::movePlayer);
First, we define that the timer emits the timeout signal every 30 milliseconds. Then, we connect that signal to the scene's slot called movePlayer(), but we do not start the timer yet. The timer will be started when the player presses a key to move.
Next, we need to handle the input events properly and update the player's direction. We introduce the Player * m_player field that will contain a pointer to the player object and the int m_horizontalInput field that will accumulate the movement commands, as we'll see in the next piece of code. Finally, we reimplement the keyPressEvent virtual function:
void MyScene::keyPressEvent(QKeyEvent *event)
{
if (event->isAutoRepeat()) {
return;
}
switch (event->key()) {
case Qt::Key_Right:
addHorizontalInput(1);
break;
case Qt::Key_Left:
addHorizontalInput(-1);
break;
//...
}
}
void MyScene::addHorizontalInput(int input)
{
m_horizontalInput += input;
m_player->setDirection(qBound(-1, m_horizontalInput, 1));
checkTimer();
}
As a small side note, whenever code snippets in the following code passages are irrelevant for the actual detail, we will skip the code but will indicate missing code with //... so that you know that it is not the entire code. We will cover the skipped parts later when it is more appropriate.
Exposing C++ objects and functions to JavaScript code
So far, we were only evaluating some standalone scripts that can make use of built-in JavaScript features. Now, it is time to learn to use data from your programs in the scripts. This is done by exposing different kinds of entities to and from scripts.
Have a go hero – Extending the game
There are a couple of ways for you to improve the game implementation. For example, you can detect when a player has won and display a pop-up message. You can also allow an arbitrary number of players. You just need to replace the TEAM_COUNT constant with a new property in the Scene class and define more team colors. You can even create a GUI for users to provide their scripts instead of passing them as command-line arguments.
The scripting environment can also be improved. You can provide more helper functions (for example, a function to calculate the distance between two tiles) to make creating scripts easier. On the other hand, you can modify the rules and reduce the amount of available information so that, for example, each entity can only see other entities at a certain distance.
As discussed earlier, each script has ways to break the global object or emit the signals of the exposed C++ objects, affecting the other players. To prevent that, you can create a separate QJSEngine and a separate set of proxy objects for each player, effectively sandboxing them.
Using Vulkan types and functions
We can let Qt handle loading the Vulkan library and resolving functions for us. It works similar to the QOpenGLFunctions set of classes. Qt provides two functions classes for Vulkan:
The QVulkanFunctions class provides access to the Vulkan functions that are not device-specific
The QVulkanDeviceFunctions class provides functions that work on a specific VkDevice
You can obtain these objects by calling the functions() and deviceFunctions(VkDevice device) methods of the QVulkanInstance class, respectively. You will usually use the device functions a lot in the renderer, so a common pattern is to add the QVulkanDeviceFunctions *m_devFuncs private field to your renderer class and initialize it in the initResources() virtual function:
void MyRenderer::initResources()
{
VkDevice device = m_window->device();
m_devFuncs = m_window->vulkanInstance()->deviceFunctions(device);
//...
}
Now you can use m_devFuncs to access the Vulkan API functions. We won't use them directly, so we don't need to figure out how to link against the Vulkan library on each platform. Qt does this job for us.
As for structures, unions, and typedefs, we can use them directly without worrying about the platform details. It's enough to have the Vulkan SDK headers present in the system.
Pop quiz
Q1. Which component can be used to rotate a 3D object?
CuboidMesh
RotationAnimation
Transform
Q2. Which component is the most suitable for emulating the light of the sun?
DirectionalLight
PointLight
SpotLight
Q3. What is a Qt 3D material?
An object that allows you to load a texture from a file.
A component that defines the physical properties of the object.
A component that defines the visible properties of the object's surface.
Have a go hero – Extending the game
You can polish your game development skills by implementing new game mechanics in our jumping elephant game. For example, you can introduce a concept of fatigue. The more the character jumps, the more tired they get and the slower they begin to move and have to rest to regain speed. To make the game more difficult, at times moving obstacles can be generated. When the character bumps into any of them, they get more and more tired. When the fatigue exceeds a certain level, the character dies and the game ends. The heartbeat diagram we previously created can be used to represent the character's level of fatigue—the more tired the character gets, the faster their heart beats.
There are many ways these changes can be implemented, and we want to give you a level of freedom, so we will not provide a step-by-step guide on how to implement a complete game. You already know a lot about Qt Quick, and this is a good opportunity to test your skills!
Implementing a chess game
At this point, you are ready to employ your newly gained skills in rendering graphics with Qt to create a game that uses widgets with custom graphics. The hero of today will be chess and other chess-like games.
What just happened?
For the instance of QPropertyAnimation created here, we define the item as a parent; thus, the animation will get deleted when the scene deletes the item, and we don't have to worry about freeing the used memory. Then, we define the target of the animation—our MyScene class—and the property that should be animated, jumpFactor, in this case. Then, we define the start and the end value of that property; in addition to that, we also define a value in between, by setting setKeyValueAt(). The first argument of the qreal type defines time inside the animation, where 0 is the beginning and 1 the end, and the second argument defines the value that the animation should have at that time. So your jumpFactor element will get animated from 0 to 1 and back to 0 in 800 milliseconds. This was defined by setDuration(). Finally, we define how the interpolation between the start and end value should be done and call setEasingCurve(), with QEasingCurve::OutInQuad as an argument.
Qt defines up to 41 different easing curves for linear, quadratic, cubic, quartic, quintic, sinusoidal, exponential, circular, elastic, back easing, and bounce functions. These are too many to describe here. Instead, take a look at the documentation; simply search for QEasingCurve::Type.
In our case, QEasingCurve::OutInQuad ensures that the jump speed of Benjamin looks like an actual jump: fast in the beginning, slow at the top, and fast at the end again. We start this animation with the jump function:
void MyScene::jump()
{
if (QAbstractAnimation::Stopped == m_jumpAnimation->state()) {
m_jumpAnimation->start();
}
}
We only start the animation by calling start() when the animation isn't running. Therefore, we check the animation's state to see whether it has been stopped. Other states could be Paused or Running. We want this jump action to be activated whenever the player presses the Space key on their keyboard. Therefore, we expand the switch statement inside the key press event handler using this code:
case Qt::Key_Space:
jump();
break;
Now the property gets animated, but Benjamin will still not jump. Therefore, we handle the changes of the jumpFactor value at the end of the setJumpFactor function:
void MyScene::setJumpFactor(const qreal &jumpFactor)
{
//...
qreal groundY = (m_groundLevel - m_player->boundingRect().height()
/ 2);
qreal y = groundY - m_jumpAnimation->currentValue().toReal() *
m_jumpHeight;
m_player->setY(y);
//...
}
When our QPropertyAnimation is running, it will call our setJumpFactor() function to update the property's value. Inside that function, we calculate the y coordinate of the player item to respect the ground level defined by m_groundLevel. This is done by subtracting half of the item's height from the ground level's value since the item's origin point is in its center. Then, we subtract the maximum jump height, defined by m_jumpHeight, which is multiplied by the actual jump factor. Since the factor is in the range of 0 and 1, the new y coordinate stays inside the allowed jump height. Then, we alter the player item's y position by calling setY(), leaving the x coordinate as the same. Et voilà, Benjamin is jumping!
Graphics View architecture
The Graphics View Framework is part of the Qt Widgets module and provides a higher level of abstraction useful for custom 2D graphics. It uses software rendering by default, but it is very optimized and extremely convenient to use. Three components form the core of Graphics View, as shown:
An instance of QGraphicsView, which is referred to as View
An instance of QGraphicsScene, which is referred to as Scene
Instances of QGraphicsItem, which are referred to as Items
The usual workflow is to first create a couple of items, add them to a scene, and then show that scene on a view:
After that, you can manipulate items from the code and add new items, while the user also has the ability to interact with visible items.
Think of the items as Post-it notes. You take a note and write a message on it, paint an image on it, both write and paint on it, or, quite possibly, just leave it blank. Qt provides a lot of item classes, all of which inherit QGraphicsItem. You can also create your own item classes. Each class must provide an implementation of the paint() function, which performs painting of the current item, and the boundingRect() function, which must return the boundary of the area the paint() function paints on.
What is the scene, then? Well, think of it as a larger sheet of paper on to which you attach your smaller Post-its, that is, the notes. On the scene, you can freely move the items around while applying funny transformations to them. It is the scene's responsibility to correctly display the items' position and any transformations applied to them. The scene further informs the items about any events that affect them.
Last, but not least, let's turn our attention to the view. Think of the view as an inspection window or a person who holds the paper with the notes in their hands. You can see the paper as a whole, or you can only look at specific parts. Also, as a person can rotate and shear the paper with their hands, so the view can rotate and shear the scene's content and do a lot more transformations with it. QGraphicsView is a widget, so you can use the view like any other widget and place it into layouts for creating neat graphical user interfaces.
You might have looked at the preceding diagram and worried about all the items being outside the view. Aren't they wasting CPU time? Don't you need to take care of them by adding a so-called view frustum culling mechanism (to detect which item not to draw/render because it is not visible)? Well, the short answer is "no", because Qt is already taking care of this.
Time for action – Taking the zoom level into account
Our graph currently contains points with integer x values because we set DX = 1. This is exactly what we want for the default level of zoom, but once the view is zoomed in, it becomes apparent that the graph's line is not smooth. We need to change DX based on the current zoom level. We can do this by adding the following code to the beginning of the paint() function():
const qreal detail = QStyleOptionGraphicsItem::levelOfDetailFromTransform(
painter->worldTransform());
const qreal dx = 1 / detail;
Delete the DX constant and replace DX with dx in the rest of the code. Now, when you scale the view, the graph's line keeps being smooth because the number of points increases dynamically. The levelOfDetailFromTransform helper function examines the value of the painter's transformation (which is a combination of all transformations applied to the item) and returns the level of detail. If the item is zoomed in 2:1, the level of detail is 2, and if the item is zoomed out 1:2, the level of detail is 0.5.
A limitation of automatic property updates
QML does its best to determine when the function value may change, but it is not omnipotent. For our last function, it can easily determine that the function result depends on the value of the textField.text property, so it will re-evaluate the binding if that value changes. However, in some cases, it can't know that a function may return a different value the next time it is called, and in such situations, the statement will not be re-evaluated. Consider the following property binding:
Label {
function colorByTime() {
var d = new Date();
var seconds = d.getSeconds();
if(seconds < 15) return "red";
if(seconds < 30) return "green";
if(seconds < 45) return "blue";
return "purple";
}
color: colorByTime()
//...
}
The color will be set at the start of the application, but it will not work properly. QML will only call the colorByTime() function once when the object is initialized, and it will never call it again. This is because it has no way of knowing how often this function must be called. We will see how to overcome this in Chapter 12, Customization in Qt Quick.
Time for action – creating disks
Our next task is to create eight disks that will slide onto rods. We'll do it in a similar way to how we handled rods. First, create a new file called Disk.qml for our new component. Put the following content into the file:
import Qt3D.Core 2.10
import Qt3D.Render 2.10
import Qt3D.Extras 2.10
Entity {
property int index
property alias pos: transform.translation
components: [
DiffuseSpecularMaterial {
ambient: Qt.hsla(index / 8, 1, 0.5)
},
TorusMesh {
minorRadius: 1.1
radius: 2.5 + 1 * index
rings: 80
},
Transform {
id: transform
rotationX: 90
scale: 0.45
}
]
}
Like rods, disks are identified by their index. In this case, index influences the color and size of the disk. We calculate the disk's color using the Qt.hsla() function that takes hue, saturation, and lightness values and returns a color value that can be assigned to the ambient property of the material. This formula will give us eight colorful disks of different hues.
The position of the disk is defined by the translation property of the Transform component. We want to be able to read and change the position of the disk from the outside, so we set up a property alias called pos that exposes the transform.translation property value.
Next, we use the TorusMesh component to define the shape of our disks. A torus shape is not really suitable for playing the Tower of Hanoi game in reality, but it will have to do for now. Later in this chapter, we'll replace it with a more suitable shape. The properties of the TorusMesh component allow us to adjust some of its measurements, but we also have to apply rotation and scale to the object to achieve the desired size and position.
Instead of putting all the disk objects into a single array, let's create an array for each rod. When we move a disk from one rod to another one, we'll remove the disk from the first rod's array and add it to the second rod's array. We can do that by adding a property to the Rod component. While we're at it, we should also expose the rod's position to the outside. We'll need it to position the disks on the rods. Declare the following properties in the top level Entity in Rod.qml:
readonly property alias pos: transform.translation
property var disks: []
The pos property will follow the value of the translation property of the Transform component. Since this value is calculated based on the index property, we declare the pos property as readonly.
Next, we need to adjust the Component.onCompleted handler of the Scene component. Initialize the diskComponent variable, just like we did with rodComponent. Then you can create disks using the following code:
var startingRod = rods[0];
for(i = 0; i < 8; i++) {
var disk = diskComponent.createObject(sceneRoot, { index: i });
disk.pos = Qt.vector3d(startingRod.pos.x, 8 - i, startingRod.pos.z);
startingRod.disks.unshift(disk);
}
After creating each disk, we set its position based on its index and the position of the chosen rod. We accumulate all disks in the disks property of the rod. We choose the order of disks in the array so that the bottom disk is at the beginning and the top disk is at the end. The unshift() function adds the item to the array at the beginning, giving the desired order.
If you run the project, you should see all eight tori on one of the rods:
The next piece of functionality we'll need is the ability to move disks from one rod to another. However, it's the player who makes the decision, so we'll also need some way to receive input from the user. Let's see what options we have for handling user input.
Qt Quick Designer
We can use QML to easily create a hierarchy of objects. If we need a few input boxes or buttons, we can just add some blocks to the code, just like we added the TextField and Label components in the previous example, and our changes will appear in the window. However, when dealing with complex forms, it's sometimes hard to position the objects properly. Instead of trying different anchors and relaunching the application, you can use the visual form editor to see the changes as you make them.
What just happened?
During this exercise, we made use of the powerful API of Qt's raster graphics engine to complement an existing set of Qt Quick items with a simple functionality. This is otherwise very hard to achieve using predefined Qt Quick elements and even harder to implement using OpenGL. We agreed to take a small performance hit in exchange for having to write just about a hundred lines of code to have a fully working solution. Remember to register the class with QML if you want to use it in your code:
qmlRegisterUncreatableType<OutlineTextItemBorder>(
"OutlineTextItem", 1, 0, "OutlineTextItemBorder", "");
qmlRegisterType<OutlineTextItem>(
"OutlineTextItem", 1, 0, "OutlineTextItem");
Packt is searching for authors like you
If.
Time for action – Adding widgets to the form
Locate the Label item in the toolbox (it's in the Display Widgets category) and drag it to our form. Use the property editor to set the objectName property of the label to player1Name. objectName is a unique identifier of a form item. The object name is used as the name of the public field in the Ui::MainWindow class, so the label will be available as ui->player1Name in the MainWindow class (and will have a QLabel * type). Then, locate the text property in the property editor (it will be in the QLabel group, as it is the class that introduces the property) and set it to Player 1. You will see that the text in the central area will be updated accordingly. Add another label, set its objectName to player2Name and its text to Player 2.
You can select a widget in the central area and press the F2 key to edit the text in place. Another way is to double-click on the widget in the form. It works for any widget that can display text.
Drag a Push Button (from the Buttons group) to the form and use the F2 key to rename it to Start new game. If the name does not fit in the button, you can resize it using the blue rectangles on its edges. Set the objectName of the button to startNewGame.
There is no built-in widget for our game board, so we will need to create a custom widget for it later. For now, we will use an empty widget. Locate Widget in the Containers group of the toolbox and drag it to the form. Set its objectName to gameBoard:
What just happened?
Rendering in Qt Quick can happen in a thread different that is than the main thread. Before calling the updatePaintNode() function, Qt performs synchronization between the GUI thread and the rendering thread to allow us safely access our item's data and other objects living in the main thread. The function executing the main thread is blocked while this function executes, so it is crucial that it executes as quickly as possible and doesn't do any unnecessary calculations as this directly influences performance. This is also the only place in your code where at the same time you can safely call functions from your item (such as reading properties) and interact with the scene-graph (creating and updating the nodes). Try not emitting any signals nor creating any objects from within this method as they will have affinity to the rendering thread rather than the GUI thread.
Having said that, you can now register your class with QML using qmlRegisterType and test it with the following QML document:
Window {
width: 600
height: 600
visible: true
RegularPolygon {
id: poly
anchors {
fill: parent
bottomMargin: 20
}
vertices: 5
color: "blue"
}
}
This should give you a nice blue pentagon. If the shape looks aliased, you can enforce anti-aliasing by setting the surface format for the application:
int main(int argc, char **argv) {
QGuiApplication app(argc, argv);
QSurfaceFormat format = QSurfaceFormat::defaultFormat();
format.setSamples(16); // enable multisampling
QSurfaceFormat::setDefaultFormat(format);
qmlRegisterType<RegularPolygon>("RegularPolygon", 1, 0, "RegularPolygon");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
If the application produces a black screen after enabling anti-aliasing, try to lower the number of samples or disable it.
QNetworkAccessManager
All network-related functionality in Qt is implemented in the Qt Network module. The easiest way to access files on the internet is to use the QNetworkAccessManager class, which handles the complete communication between your game and the internet.
What just happened?
We set up a very simple scene consisting of three images stacked up to form a landscape. Between the background layer (the sky) and the foreground (trees), we placed a yellow circle representing the sun. Since we will be moving the sun around in a moment, we anchored the center of the object to an empty item without physical dimensions so that we can set the sun's position relative to its center. We also equipped the scene with a dayLength property, which will hold information about the length of one day of game time. By default, we set it to 60 seconds so that things happen really quickly and we can see the animation's progress without waiting. After all things are set correctly, the length of the day can be balanced to fit our needs.
The graphical design lets us easily manipulate the sun while keeping it behind the tree line. Note how the stacking order is implicitly determined by the order of elements in the document.
Fluid user interfaces
So far, we have been looking at graphical user interfaces as a set of panels embedded one into another. This is well reflected in the world of desktop utility programs composed of windows and subwindows containing mostly static content scattered throughout a large desktop area where the user can use a mouse pointer to move around windows or adjust their size.
However, this design doesn't correspond well with modern user interfaces that often try to minimize the area they occupy (because of either a small display size like with embedded and mobile devices or to avoid obscuring the main display panel like in games), at the same time providing rich content with a lot of moving or dynamically resizing items. Such user interfaces are often called "fluid", to signify that they are not formed as a number of separate different screens but contain dynamic content and layout where one screen fluently transforms into another. The QtQuick module provides a runtime to create rich applications with fluid user interfaces.
Have a go hero – Creating a supporting border for RegularPolygon
What is returned by updatePaintNode() may not just be a single QSGGeometryNode but also a larger tree of QSGNode items. Each node can have any number of child nodes. By returning a node that has two geometry nodes as children, you can draw two separate shapes in the item:
As a challenge, extend RegularPolygon to draw not only the internal filled part of the polygon but also an edge that can be of a different color. You can draw the edge using the GL_QUAD_STRIP drawing mode. Coordinates of the points are easy to calculate—the points closer to the middle of the shape are the same points that form the shape itself. The remaining points also lie on a circumference of a circle that is slightly larger (by the width of the border). Therefore, you can use the same equations to calculate them.
The GL_QUAD_STRIP mode renders quadrilaterals with every two vertices specified after the first four, composing a connected quadrilateral. The following diagram should give you a clear idea of what we are after:
Time for action – Sending a text via UDP
As an example, let's assume that we have two sockets of the QUdpSocket type. We will call the first one socketA and the other socketB. Both are bound to the localhost, socketA to the 52000 port and socketB to the 52001 port. So, if we want to send the string Hello! from socketA to socketB, we have to write in the application that is holding socketA:
socketA->writeDatagram(QByteArray("Hello!"),
QHostAddress("127.0.0.1"), 52001);
The class that holds socketB must have the socket's readyRead() signal connected to a slot. This slot will then be called because of our writeDatagram() call, assuming that the datagram is not lost! In the slot, we read the datagram and the sender's address and port number with:
while (socketB->hasPendingDatagrams()) {
QNetworkDatagram datagram = socketB->receiveDatagram();
qDebug() << "received data:" << datagram.data();
qDebug() << "from:" << datagram.senderAddress()
<< datagram.senderPort();
}
As long as there are pending datagrams—this is checked by hasPendingDatagrams()—we read them using the high-level QNetworkDatagram API. After the datagram was received, we use the getter functions to read the data and identify the sender.
Have a go hero – Caching the oscillogram in a pixmap
Now, it should be very easy for you to implement this approach for our example widget. The main difference is that each change to the plot contents should not result in a call to update() but in a call that will rerender the pixmap and then call update(). The paintEvent method then becomes simply this:
void Widget::paintEvent(QPaintEvent *event)
{
QRect exposedRect = event->rect();
QPainter painter(this);
painter.drawPixmap(exposedRect, m_pixmap, exposedRect);
}
You'll also need to rerender the pixmap when the widget is resized. This can be done from within the resizeEvent() virtual function.
While it is useful to master the available approaches to optimization, it's always important to check whether they actually make your application faster. There are often cases where the straightforward approach is more optimal than a clever optimization. In the preceding example, resizing the widget (and subsequently resizing the pixmap) can trigger a potentially expensive memory allocation. Use this optimization only if direct painting on the widget is even more expensive.
Time for action – Reacting to an item's selection state
Standard items, when selected, change appearance (for example, the outline usually becomes dashed). When we're creating a custom item, we need to implement this feature manually. Let's make our item selectable in the View constructor:
SineItem *item = new SineItem();
item->setFlag(QGraphicsItem::ItemIsSelectable);
Now, let's make the graph line green when the item is selected:
if (option->state & QStyle::State_Selected) {
pen.setColor(Qt::green);
}
painter->setPen(pen);
Qt Quick and C++
While QML has a lot of built-in functionality available, it will almost never be enough. When you're developing a real application, it always needs some unique functionality that is not available in QML modules provided by Qt. The C++ Qt classes are much more powerful, and third-party C++ libraries are also always an option. However, the C++ world is separated from our QML application by the restrictions of QML engine. Let's break that boundary right away.
Event handlers
Qt Quick is meant to be used for creating user interfaces that are highly interactive. It offers a number of elements for taking input events from the user. In this section, we will go through them and see how you can use them effectively.
Property animations
We implemented the horizontal movement using a QTimer. Now, let's try a second way to animate items—the Animation framework.
Time for action – Converting data between C++ and Python
Create a new class and call it QtPythonValue:
class QtPythonValue {
public:
QtPythonValue();
QtPythonValue(const QtPythonValue &other);
QtPythonValue& operator=(const QtPythonValue &other);
QtPythonValue(int val);
QtPythonValue(const QString &str);
~QtPythonValue();
int toInt() const;
QString toString() const;
bool isNone() const;
private:
QtPythonValue(PyObject *ptr);
void incRef();
void incRef(PyObject *val);
void decRef();
PyObject *m_value;
friend class QtPython;
};
Next, implement the constructors, the assignment operator, and the destructor, as follows:
QtPythonValue::QtPythonValue() {
incRef(Py_None);
}
QtPythonValue::QtPythonValue(const QtPythonValue &other) {
incRef(other.m_value);
}
QtPythonValue::QtPythonValue(PyObject *ptr) {
m_value = ptr;
}
QtPythonValue::QtPythonValue(const QString &str) {
m_value = PyUnicode_FromString(qPrintable(str));
}
QtPythonValue::QtPythonValue(int val) {
m_value = PyLong_FromLong(val);
}
QtPythonValue &QtPythonValue::operator=(const QtPythonValue &other) {
if(m_value == other.m_value) {
return *this;
}
decRef();
incRef(other.m_value);
return *this;
}
QtPythonValue::~QtPythonValue()
{
decRef();
}
Then, implement the incRef() and decRef() functions:
void QtPythonValue::incRef(PyObject *val) {
m_value = val;
incRef();
}
void QtPythonValue::incRef() {
if(m_value) {
Py_INCREF(m_value);
}
}
void QtPythonValue::decRef() {
if(m_value) {
Py_DECREF(m_value);
}
}
Next, implement conversions from QtPythonValue to C++ types:
int QtPythonValue::toInt() const {
return PyLong_Check(m_value) ? PyLong_AsLong(m_value) : 0;
}
QString QtPythonValue::toString() const {
return PyUnicode_Check(m_value) ?
QString::fromUtf8(PyUnicode_AsUTF8(m_value)) : QString();
}
bool QtPythonValue::isNone() const {
return m_value == Py_None;
}
Finally, let's modify the main() function to test our new code:
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QtPython python;
QtPythonValue integer = 7, string = QStringLiteral("foobar"), none;
qDebug() << integer.toInt() << string.toString() << none.isNone();
return 0;
}
When you run the program, you will see that the conversion between C++ and Python works correctly in both directions.
Summary
In this chapter, you learned that providing a scripting environment to your games opens up new possibilities. Implementing a functionality using scripting languages is usually faster than doing the full write-compile-test cycle with C++, and you can even use the skills and creativity of your users who have no understanding of the internals of your game engine to make your games better and more feature-rich. You were shown how to use QJSEngine, which blends the C++ and JavaScript worlds together by exposing Qt objects to JavaScript and making cross-language signal-slot connections. You also learned the basics of scripting with Python. There are other scripting languages available (for example, Lua), and many of them can be used along with Qt. Using the experience gained in this chapter, you should even be able to bring other scripting environments to your programs, as most embeddable interpreters offer similar approaches to that of Python.
In the next chapter, you will be introduced to Qt Quick—a library for creating fluid and dynamic user interfaces. It may not sound like it's related to this chapter, but Qt Quick is based on Qt QML. In fact, any Qt Quick application contains a QJSEngine object that executes JavaScript code of the application. Being familiar with this system will help you understand how such applications work. You will also be able to apply the skills you've learned here when you need to access C++ objects from Qt Quick and vice versa. Welcome to the world of Qt Quick.
Summary
In this chapter, you deepened your knowledge about items, about the scene, and about the view. While developing the game, you became familiar with different approaches of how to animate items, and you were taught how to detect collisions. As an advanced topic, you were introduced to parallax scrolling.
After having completed the two chapters describing Graphics View, you should now know almost everything about it. You are able to create complete custom items, you can alter or extend standard items, and with the information about the level of detail, you even have the power to alter an item's appearance, depending on its zoom level. You can transform items and the scene, and you can animate items and thus the entire scene.
Furthermore, as you saw while developing the game, your skills are good enough to develop a jump-and-run game with parallax scrolling, as it is used in highly professional games. We also learned how to add gamepad support to our game. To keep it fluid and highly responsive, finally we saw some tricks on how to get the most out of Graphics View.
When we worked with widgets and the Graphics View framework, we had to use some general purpose Qt types, such as QString or QVector. In simple cases, their API is pretty obvious. However, these and many other classes provided by Qt Core module are very powerful, and you will greatly benefit from deeper knowledge of them. When you develop a serious project, it's very important to understand how these basic types work and what dangers they may pose when used incorrectly. In the next chapter, we will turn our attention to this topic. You will learn how you can work with text in Qt, which containers you should use in different cases, and how to manipulate various kind of data and implement a persistent storage. This is essential for any game that is more complicated than our simple examples.
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "This API is centered on QNetworkAccessManager,which handles the complete communication between your game and the Internet."
A block of code is set as follows:
QNetworkRequest request;
request.setUrl(QUrl(""));
request.setHeader(QNetworkRequest::UserAgentHeader, "MyGame");
m_manager->get(request);
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
void FileDownload::downloadFinished(QNetworkReply *reply) {
const QByteArray content = reply->readAll();
_edit->setPlainText(content);
reply->deleteLater();
}
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "On the Select Destination Location screen, click on Next to accept the default destination."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Creating C++ objects from JavaScript
We've only exposed the existing C++ objects to JavaScript so far, but what if you want to create a new C++ object from JavaScript? You can do this using what you already know. A C++ method of an already exposed object can create a new object for you:
public:
Q_INVOKABLE QObject* createMyObject(int argument) {
return new MyObject(argument);
}
We use QObject* instead of MyObject* in the function signature. This allows us to import the object into the JS engine automatically. The engine will take ownership of the object and delete it when there are no more references to it in JavaScript.
Using this method from JavaScript is also pretty straightforward:
var newObject = originalObject.createMyObject(42);
newObject.slot1();
This approach is fine if you have a good place for the createMyObject function. However, sometimes you want to create new objects independently of the existing ones, or you don't have any objects created yet. For these situations, there is a neat way to expose the constructor of the class to the JavaScript engine. First, you need to make your constructor invokable in the class declaration:
public:
Q_INVOKABLE explicit MyObject(int argument, QObject *parent = nullptr);
Then, you should use the newQMetaObject() function to import the meta-object of the class to the engine. You can immediately assign the imported meta-object to a property of the global object:
engine.globalObject().setProperty("MyObject",
engine.newQMetaObject(&MyObject::staticMetaObject));
You can now invoke the constructor by calling the exposed object with the new keyword:
var newObject = new MyObject(42);
newObject.slot1();
Summary
You are now familiar with multiple methods that can be used to extend Qt Quick with your own item types. You learned to use JavaScript to create custom visual items. You also know how to use C++ classes as non-visual QML elements fully integrated with your UI. We also discussed how to handle mouse, touch, keyboard, and gamepad events in Qt Quick applications. However, so far, despite us talking about "fluid" and "dynamic" interfaces, you haven't seen much of them. Do not worry; in the next chapter, we will focus on animations in Qt Quick as well as fancy graphics and applying what you learned in this chapter for creating nice-looking and interesting games. So, read on!
What just happened?
The QtPythonValue class wraps a PyObject pointer (through the m_value member), providing a nice interface to convert between what the interpreter expects and our Qt types. Let's see how this is done. First, take a look at the three private methods: two versions of incRef() and one decRef(). PyObject contains an internal reference counter that counts the number of handles on the contained value. When that counter drops to 0, the object can be destroyed. Our three methods use adequate Python C API calls to increase or decrease the counter in order to prevent memory leaks and keep Python's garbage collector happy.
The second important aspect is that the class defines a private constructor that takes a PyObject pointer, effectively creating a wrapper over the given value. The constructor is private; however, the QtPython class is declared as a friend of QtPythonValue, which means that only QtPython and QtPythonValue can instantiate values by passing PyObject pointers to it. Now, let's take a look at public constructors.
The default constructor creates an object pointing to a None value, which represents the absence of a value. The copy constructor and assignment operator are pretty standard, taking care of bookkeeping of the reference counter. Then, we have two constructors—one taking int and the other taking a QString value. They use appropriate Python C API calls to obtain a PyObject representation of the value. Note that these calls already increase the reference count for us, so we don't have to do it ourselves.
The code ends with a destructor that decreases the reference counter and three methods that provide safe conversions from QtPythonValue to appropriate Qt/C++ types.
Pens and brushes
The pen and brush are two attributes that define how different drawing operations are performed. The pen (represented by the QPen class) defines the outline, and the brush (represented by the QBrush class) fills the drawn shapes. Each of them is really a set of parameters. The most simple one is the color defined, either as a predefined global color enumeration value (such as Qt::red or Qt::transparent), or an instance of the QColor class. The effective color is made up of four attributes: three color components (red, green, and blue) and an optional alpha channel value that determines the transparency of the color (the larger the value, the more opaque the color). By default, all components are expressed as 8-bit values (0 to 255) but can also be expressed as real values representing a percentage of the maximum saturation of the component; for example, 0.6 corresponds to 153 (0.6⋅255). For convenience, one of the QColor constructors accepts hexadecimal color codes used in HTML (with #0000FF being an opaque blue color) or even bare color names (for example, blue) from a predefined list of colors returned by a static function—QColor::colorNames(). Once a color object is defined using RGB components, it can be queried using different color spaces (for example, CMYK or HSV). Also, a set of static methods are available that act as constructors for colors expressed in different color spaces.
For example, to construct a clear magenta color any of the following expressions can be used:
QColor("magenta")
QColor("#FF00FF")
QColor(255, 0, 255)
QColor::fromRgbF(1, 0, 1)
QColor::fromHsv(300, 255, 255)
QColor::fromCmyk(0, 255, 0, 0)
Qt::magenta
Apart from the color, QBrush has two additional ways of expressing the fill of a shape. You can use QBrush::setTexture() to set a pixmap that will be used as a stamp or QBrush::setGradient() to make the brush use a gradient to do the filling. For example, to use a gradient that goes diagonally and starts as yellow in the top-left corner of the shape, becomes red in the middle of the shape, and ends as magenta at the bottom-right corner of the shape, the following code can be used:
QLinearGradient gradient(0, 0, width, height);
gradient.setColorAt(0, Qt::yellow);
gradient.setColorAt(0.5, Qt::red);
gradient.setColorAt(1.0, Qt::magenta);
QBrush brush = gradient;
When used with drawing a rectangle, this code will give the following output:
Qt can handle linear (QLinearGradient), radial (QRadialGradient), and conical (QConicalGradient) gradients. Qt provides a Gradients example (shown in the following screenshot) where you can see different gradients in action:
As for the pen, its main attribute is its width (expressed in pixels), which determines the thickness of the shape outline. A pen can, of course, have a color set but, in addition to that, you can use any brush as a pen. The result of such an operation is that you can draw thick outlines of shapes using gradients or textures.
There are three more important properties for a pen. The first is the pen style, set using QPen::setStyle(). It determines whether lines drawn by the pen are continuous or divided in some way (dashes, dots, and so on). You can see the available line styles here:
The second attribute is the cap style, which can be flat, square, or round. The third attribute—the join style—is important for polyline outlines and dictates how different segments of the polyline are connected. You can make the joins sharp (with Qt::MiterJoin or Qt::SvgMiterJoin), round (Qt::RoundJoin), or a hybrid of the two (Qt::BevelJoin). You can see the different pen attribute configurations (including different join and cap styles) in action by launching the Path Stroking example shown in the following screenshot:
Time for action – Registering C++ class as QML type
So far, what we did was expose ourselves to QML single objects created and initialized in C++. However, we can do much more—the framework allows us to define new QML types. These can either be generic QObject-derived QML elements or items specialized for Qt Quick.
We will start with something simple—exposing the CarInfo type to QML so that instead of instantiating it in C++ and then exposing it in QML, we can directly declare the element in QML and still allow the changes made to the widget to be reflected in the scene.
To make a certain class (derived from QObject) instantiable in QML, all that is required is to register that class with the declarative engine using the qmlRegisterType template function. This function takes the class as its template parameter along a number of function arguments: the module uri, the major and minor version numbers, and the name of the QML type we are registering. The following call will register the FooClass class as the QML type Foo, available after importing foo.bar.baz in Version 1.0:
qmlRegisterType<FooClass>("foo.bar.baz", 1, 0, "Foo");
You can place this invocation anywhere in your C++ code; just ensure that this is before you try to load a QML document that might contain declarations of Foo objects. A typical place to put the function call is in the program's main function. Afterward, you can start declaring objects of the Foo type in your documents. Just remember that you have to import the respective module first:
import QtQuick 2.9
import foo.bar.baz 1.0
Item {
Foo {
id: foo
}
}
What just happened?
In the preceding code, we created a basic boilerplate code for using a canvas. First, we created a Canvas instance with an implicit width and height set. There, we created a handler for the paint signal that is emitted whenever the canvas needs to be redrawn. The code placed there retrieves a context for the canvas, which can be thought of as an equivalent to the QPainter instance we used when drawing on Qt widgets. We inform the canvas that we want its 2D context, which gives us a way to draw in two dimensions. A 2D context is the only context currently present for the Canvas element, but you still have to identify it explicitly—similar to HTML. Having the context ready, we tell it to clear the whole area of the canvas. This is different from the widget world in which when the paintEvent handler was called, the widget was already cleared for us and everything had to be redrawn from scratch. With Canvas, it is different; the previous content is kept by default so that you can draw over it if you want. Since we want to start with a clean sheet, we call clearRect() on the context. Finally, we use the strokeRect() convenience method that draws a rectangle on the canvas.
Reading and writing files
Once you know the path to a file (for example, using QDir::entryList(), QFileDialog::getOpenFileName(), or some external source), you can pass it to QFile to receive an object that acts as a handle to the file. Before the file contents can be accessed, the file needs to be opened using the open() method. The basic variant of this method takes a mode in which we need to open the file. The following table explains the modes that are available:
Mode
Description
ReadOnly
This file can be read from.
WriteOnly
This file can be written to.
ReadWrite
This file can be read from and written to.
Append
All data writes will be written at the end of the file.
Truncate
If the file is present, its content is deleted before we open it.
Text
When reading, all line endings are transformed to \n. When writing, all \n symbols are transformed to the native format (for example, \r\n on Windows or \n on Linux).
Unbuffered
The flag prevents the file from being buffered.
The open() method returns true or false, depending on whether the file was opened or not. The current status of the file can be checked by calling isOpen() on the file object. Once the file is open, it can be read from or written to, depending on the options that are passed when the file is opened. Reading and writing is done using the read() and write() methods. These methods have a number of overloads, but we suggest that you focus on using those variants that accept or return the already familiar QByteArray objects, because they manage the memory automatically. If you are working with plain text, then a useful overload for write is the one that accepts the text directly as input. Just remember that the text has to be null terminated. When reading from a file, Qt offers a number of other methods that might come in handy in some situations. One of these methods is readLine(), which tries to read from the file until it encounters a new line character. If you use it along with the atEnd() method that tells you whether you have reached the end of the file, you can realize the line-by-line reading of a text file:
QStringList lines;
while(!file.atEnd()) {
QByteArray line = file.readLine();
lines.append(QString::fromUtf8(line));
}
Another useful method is readAll(), which simply returns the file content, starting from the current position of the file pointer until the end of the file.
You have to remember, though, that when using these helper methods, you should be really careful if you don't know how much data the file contains. It might happen that when reading line by line or trying to read the whole file into memory in one step, you exhaust the amount of memory that is available for your process. If you only intend to work with small files that fit into memory, you can check the size of the file by calling size() on the QFile instance and abort if the file is too large. If you need to handle arbitrary files, however, you should process the file's data in steps, reading only a small portion of bytes at a time. This makes the code more complex but allows us to manage the available resources better.
If you require constant access to the file, you can use the map() and unmap() calls that add and remove mappings of the parts of a file to a memory address that you can then use like a regular array of bytes:
QFile f("myfile");
if(!f.open(QFile::ReadWrite)) {
return;
}
uchar *addr = f.map(0, f.size());
if(!addr) {
return;
}
f.close();
doSomeComplexOperationOn(addr);
The mapping will automatically be removed when the QFile object is destroyed.
The cross-platform programming.
OpenGL and Vulkan in Qt applications
Hardware acceleration is crucial for implementing modern games with advanced graphics effects. Qt Widgets module uses traditional approach optimized for CPU-based rendering. Even though you can make any widget use OpenGL, the performance will usually not be maximized. However, Qt allows you to use OpenGL or Vulkan directly to create high-performance graphics limited only by the graphics card's processing power. In this chapter, you will learn about employing your OpenGL and Vulkan skills to display fast 3D graphics. If you are not familiar with these technologies, this chapter should give you a kickstart for further research in this topic. We will also describe multiple Qt helper classes that simplify usage of OpenGL textures, shaders, and buffers. By the end of the chapter, you will be able to create 2D and 3D graphics for your games using OpenGL and Vulkan classes offered by Qt and integrate them with the rest of the user interface.
The main topics covered in this chapter are as listed:
OpenGL in Qt applications
Immediate mode
Textures
Shaders
OpenGL buffers
Vulkan in Qt applications
Using QPainter interface in Qt Quick
Implementing items in OpenGL is quite difficult—you need to come up with an algorithm of using OpenGL primitives to draw the shape you want, and then you also need to be skilled enough with OpenGL to build a proper scene graph node tree for your item. However, there is another way—you can create items by painting them with QPainter. This comes at a cost of performance as behind the scenes, the painter draws on an indirect surface (a frame buffer object or an image) that is then converted to OpenGL texture and rendered on a quad by the scene-graph. Even considering that performance hit, it is often much simpler to draw the item using a rich and convenient drawing API than to spend hours doing the equivalent in OpenGL or using Canvas.
To use that approach, we will not be subclassing QQuickItem directly but QQuickPaintedItem, which gives us the infrastructure needed to use the painter for drawing items.
Basically, all we have to do, then, is implement the pure virtual paint() method that renders the item using the received painter. Let's see this put into practice and combine it with the skills we gained earlier.
Time for action – Exposing the game state to the JS engine
Before we move on to executing the players' scripts, we need to create a QJSEngine and insert some information into its global object. The scripts will use this information to decide the optimal move.
First, we add the QJSEngine m_jsEngine private field to the Scene class. Next, we create a new SceneProxy class and derive it from QObject. This class will expose the permitted API of Scene to the scripts. We pass a pointer to the Scene object to the constructor of the SceneProxy object and store it in a private variable:
SceneProxy::SceneProxy(Scene *scene) :
QObject(scene), m_scene(scene)
{
}
Add two invokable methods to the class declaration:
Q_INVOKABLE QSize size() const;
Q_INVOKABLE QJSValue entities() const;
The implementation of the size() function is pretty straightforward:
QSize SceneProxy::size() const {
return m_scene->fieldSize();
}
However, the entities() function is a bit trickier. We cannot add Entity objects to the JS engine because they are not based on QObject. Even if we could, we prefer to create a proxy class for entities as well.
Let's do this right now. Create the EntityProxy class, derive it from QObject, and pass a pointer to the underlying Entity object to the constructor, like we did in SceneProxy. Declare two invokable functions and a signal in the new class:
class EntityProxy : public QObject
{
Q_OBJECT
public:
explicit EntityProxy(Entity *entity, QObject *parent = nullptr);
Q_INVOKABLE int team() const;
Q_INVOKABLE QPoint pos() const;
//...
signals:
void killed();
private:
Entity *m_entity;
};
Implementation of the methods just forward the calls to the underlying Entity object:
int EntityProxy::team() const
{
return m_entity->team();
}
QPoint EntityProxy::pos() const
{
return m_entity->pos().toPoint();
}
The Entity class will be responsible for creating its own proxy object. Add the following private fields to the Entity class:
EntityProxy *m_proxy;
QJSValue m_proxyValue;
The m_proxy field will hold the proxy object. The m_proxyValue field will contain the reference to the same object added to the JS engine. Initialize these fields in the constructor:
m_proxy = new EntityProxy(this, scene);
m_proxyValue = scene->jsEngine()->newQObject(m_proxy);
We modify the Entity::setAlive() function to emit the killed() signal when the entity is killed:
void Entity::setAlive(bool alive)
{
m_alive = alive;
setVisible(alive);
if (!alive) {
emit m_proxy->killed();
}
}
It's generally considered bad practice to emit signals from outside the class that owns the signal. If the source of the signal is another QObject-based class, you should create a separate signal in that class and connect it to the destination signal. In our case, we cannot do that, since Entity is not a QObject, so we choose to emit the signal directly to avoid further complication.
Create the proxy() and proxyValue() getters for these fields. We can now return to the SceneProxy implementation and use the entity proxy:
QJSValue SceneProxy::entities() const
{
QJSValue list = m_scene->jsEngine()->newArray();
int arrayIndex = 0;
for(Entity *entity: m_scene->entities()) {
if (entity->isAlive()) {
list.setProperty(arrayIndex, entity->proxyValue());
arrayIndex++;
}
}
return list;
}
Pointer invalidation
First,.
Communicating between games
After having discussed Qt's high-level network classes such as QNetworkAccessManager and QNetworkConfigurationManager, we will now take a look at lower-level network classes and see how Qt supports you when it comes to implementing TCP or UDP servers and clients. This becomes relevant when you plan to extend your game by including a multiplayer mode. For such a task, Qt offers QTcpSocket, QUdpSocket, and QTcpServer.
What just happened?
We created an encryption object and set its key to 3. We also told it to use a QBuffer instance to store the processed content. After opening it for writing, we sent some data to it that gets encrypted and written to the base device. Then, we created a similar device, passing the same buffer again as the base device, but now, we open the device for reading. This means that the base device contains ciphertext. After this, we read all data from the device, which results in reading data from the buffer, decrypting it, and returning the data so that it can be written to the debug console.
Time for action – Property binding
QML is much more powerful than simple JSON. Instead of specifying an explicit value for a property, you can use an arbitrary JavaScript expression that will be automatically evaluated and assigned to the property. For example, the following code will display "ab" in the label:
Label {
text: "a" + "b"
//...
}
You can also refer to properties of the other objects in the file. As we saw earlier, you can use the textEdit variable to set relative position of the label. This is one example of a property binding. If the value of the textField.bottom expression changes for some reason, the anchors.top property of the label will be automatically updated with the new value. QML allows you to use the same mechanism for every property. To make the effect more obvious, let's assign an expression to the label's text property:
Label {
text: "Your input: " + textField.text
//...
}
Now the label's text will be changed according to this expression. When you change the text in the input field, the text of the label will be automatically updated!:
The property binding differs from a regular value assignment and binds the value of the property to the value of the supplied JavaScript expression. Whenever the expression's value changes, the property will reflect that change in its own value. Note that the order of statements in a QML document does not matter as you declare relations between properties.
This example shows one of the advantages of the declarative approach. We didn't have to connect signals or explicitly determine when the text should be changed. We just declared that the text should be influenced by the input field, and the QML engine will enforce that relation automatically.
If the expression is complex, you can replace it with a multiline block of text that works as a function:
text: {
var x = textField.text;
return "(" + x + ")";
}
You can also declare and use a named JavaScript function within any QML object declaration:
Label {
function calculateText() {
var x = textField.text;
return "(" + x + ")";
}
text: calculateText()
//...
}
Time for action – Creating a menu and a toolbar
Let's replace our boring Start new game button with a menu entry and a toolbar icon. First, select the button and press the Delete key to delete it. Then, locate Action Editor in the bottom-center part of the form editor and click on the New button on its toolbar. Enter the following values in the dialog (you can fill the Shortcut field by pressing the key combination you want to use):
Locate the toolbar in the central area (between the Type Here text and the first label) and drag the line containing the New Game action from the action editor to the toolbar, which results in a button appearing in the toolbar.
To create a menu for the window, double-click on the Type Here text on the top of the form and replace the text with &File (although our application doesn't work with files, we will follow this tradition). Then, drag the New Game action from the action editor over the newly created menu, but do not drop it there yet. The menu should open now, and you can drag the action so that a red bar appears in the submenu in the position where you want the menu entry to appear; now you can release the mouse button to create the entry.
Now we should restore the functionality that was broken when we deleted the button. Navigate to the constructor of the MainWindow class and adjust the connect() call:
connect(ui->startNewGame, &QAction::triggered,
this, &MainWindow::startNewGame);
Actions, like widgets, are accessible through the ui object. The ui->startNewGame object is now a QAction instead of a QPushButton, and we use its triggered() signal to detect whether the action was selected in some way.
Now, if you run the application, you can select the menu entry, press a button on the toolbar, or press the Ctrl + N keys. Either of these operations will cause the action to emit the triggered() signal, and the game configuration dialog should appear.
Like widgets, QAction objects have some useful methods that are accessible in our form class. For example, executing ui->startNewGame->setEnabled(false) will disable all ways to trigger the New Game action.
Let's add another action for quitting the application (although the user can already do it just by closing the main window). Use the action editor to add a new action with text Quit, object name quit, and shortcut Ctrl + Q. Add it to the menu and the toolbar, like the first action.
We can add a new slot that stops the application, but such a slot already exists in QApplication, so let's just reuse it. Locate the constructor of our form in mainwindow.cpp and append the following code:
connect(ui->quit, &QAction::triggered,
qApp, &QApplication::quit);
Animations in Qt Quick Games
In the previous two chapters, we introduced you to the basics of Qt Quick and QML. By now, you should be fluent enough with the syntax and understand the basic concepts of how Qt Quick works. In this chapter, we will show you how to make your games stand out from the crowd by introducing different kinds of animations that make your applications feel more like the real world. You will also learn to treat Qt Quick objects as separate entities programmable using state machines. A significant part of this chapter will introduce how to implement a number of important gaming concepts using Qt Quick. All this will be shown while we build a simple 2D action game using the presented concepts.
The main topics covered in this chapter are as follows:
Animation framework in Qt Quick
States and transitions in depth
Implementing games in Qt Quick
Sprite animations
Using state machines for animation
Parallax scrolling
Collision detection
Time for action – Animating the sun's horizontal movement
The everyday cruise of the sun in the sky starts in the east and continues west to hide beneath the horizon in the evening. Let's try to replicate this horizontal movement by adding animation to our sun object.
Open the QML document of our last project. Inside the root item, add the following declaration:
NumberAnimation {
target: sun
property: "x"
from: 0
to: root.width
duration: dayLength
running: true
}
Running the program with such modifications will produce a run with a horizontal movement of the sun. The following image is a composition of a number of frames of the run:
Advanced Visual Effects in Qt Quick
Sprite animations and smooth transitions are not always enough to make the game visually appealing. In this chapter, we will explore many ways to add some eye candy to your games. Qt Quick provides a decent amount of built-in visual effects that will come in handy. However, from time to time, you will want to do something that is not possible to do with standard components—something unique and specific to your game. In these cases, you don't need to limit your imagination. We will teach you to dive deep into the C++ API of Qt Quick to implement truly unique graphics effects.
The main topics covered in this chapter are these:
Auto-scaling user interfaces
Applying graphical effects to the existing items
Particle systems
OpenGL painting in Qt Quick
Using QPainter in Qt Quick
Summary
By now, you should be able to install Qt on your development machine. You can now use Qt Creator to browse the existing examples and learn from them or to read the Qt reference manual to gain additional knowledge. You should have a basic understanding of Qt Creator's main controls. In the next chapter, we will finally start using the framework, and you will learn how to create graphical user interfaces by implementing our very first simple game.
Qt documentation
Qt project has very thorough documentation. For each API item (class, method, and so on), there is a section in the documentation that describes that item and mentions things that you need to know. There are also a lot of overview pages describing modules and their parts. When you are wondering what some Qt class or module is made for or how to use it, the Qt documentation is always a good source of information.
Qt Creator has an integrated documentation viewer. The most commonly used documentation feature is context help. To try it out, open the main.cpp file, set the text cursor inside the QApplication text, and press F1. The help section should appear to the right of the code editor. It displays the documentation page for the QApplication class. The same should work for any other Qt class, method, macro, and so on. You can click on the Open in Help Mode button on top of the help page to switch to the Help mode, where you have more space to view the page.
Another important feature is the search in documentation index. To do that, go to the Help mode by clicking on the Help button on the left panel. In Help mode, in the top-left corner of the window, there is a drop-down list that allows you to select the mode of the left section: Bookmarks, Contents, Index, or Search. Select Index mode, input your request in the Look for: text field and see whether there are any search results in the list below the text field. For example, try typing qt core to search for the Qt Core module overview. If there are results, you can press Enter to quickly open the first result or double-click on any result in the list to open it. If multiple Qt versions are installed, a dialog may appear where you need to select the Qt version you are interested in.
Later in this book, we will sometimes refer to Qt documentation pages by their names. You can use the method described previously to open these pages in Qt Creator.
Have a go hero – Applying multiple transformations
To understand the concept of transformations and their origin point, try to apply rotate() and scale() to an item. Also, change the point of origin and see how the item will react. As a second step, use QTransform in conjunction with setTransform() to apply multiple transformations to an item in a specific order.
Text input fields
Apart from the attached properties we described, Qt Quick provides built-in elements for handling keyboard input. The two most basic types are TextInput and TextEdit, which are QML equivalents of QLineEdit and QTextEdit. The former are used for single-line text input, while the latter serves as its multiline counterpart. They both offer cursor handling, undo-redo functionality, and text selections. You can validate text typed into TextInput by assigning a validator to the validator property. For example, to obtain an item where the user can input a dot-separated IP address, we can use the following declaration:
TextInput {
id: ipAddress
width: 100
validator: RegExpValidator {
// four numbers separated by dots
regExp: /\d+\.\d+\.\d+\.\d+/
}
focus: true
}
The regular expression only verifies the format of the address. The user can still insert bogus numbers. You should either do a proper check before using the address or provide a more complex regular expression that will constrain the range of numbers the user can enter.
One thing to remember is that neither TextInput nor TextEdit has any visual appearance (apart from the text and cursor they contain), so if you want to give the user some visual hint as to where the item is positioned, the easiest solution is to wrap it in a styled rectangle:
Rectangle {
id: textInputFrame
width: 200
height: 40
border { color: "black"; width: 2 }
radius: 10
antialiasing: true
color: "darkGray"
}
TextInput {
id: textInput
anchors.fill: textInputFrame
anchors.margins: 5
font.pixelSize: height-2
verticalAlignment: TextInput.AlignVCenter
clip: true
}
Note that the highlighted | https://pl.b-ok.org/book/3629213/cf4a8f | CC-MAIN-2019-26 | refinedweb | 14,189 | 60.65 |
hi, everyone
I am a Java newbie. I have followed a bunch of tutorials and examples from the web but they all failed miserably at teaching me how to properly apply this library: com.google.gson.
First how do I receive properly in the java servlet a json request that has been encoded with JSON.stringify(myRequest) in javascript? I can use String password = request.getParameter("passwordTxt"); but that works only if the requests are not encoded with stringify. So first how do I do that?
I learnt how to send responses by using just:
Gson gson = new Gson(); gson.toJson(myClass);
But I think that this useful only if the content of toJson function is an already made class. I want to create the response dynamically.
All I am trying to create is a simple custom response like this:
Let's say I want my request to look like this:
{test: "myValue"} or like this {test: "myValue", myArr: [1, 5, 10]}
I have the following classes:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonObject;
Do I need to use all of them to achieve what I want? How should I proceed? thank you | https://www.daniweb.com/programming/software-development/threads/468888/how-to-receive-and-send-json-with-the-com-google-gson-library | CC-MAIN-2017-17 | refinedweb | 216 | 60.82 |
Quantum Generative Adversarial Networks with Cirq + TensorFlow¶
This demo constructs a Quantum Generative Adversarial Network (QGAN) (Lloyd and Weedbrook (2018), Dallaire-Demers and Killoran (2018)) using two subcircuits, a generator and a discriminator. The generator attempts to generate synthetic quantum data to match a pattern of “real” data, while the discriminator tries to discern real data from fake data (see image below). The gradient of the discriminator’s output provides a training signal for the generator to improve its fake generated data.
Using Cirq + TensorFlow¶
PennyLane allows us to mix and match quantum devices and classical machine learning software. For this demo, we will link together Google’s Cirq and TensorFlow libraries.
We begin by importing PennyLane, NumPy, and TensorFlow.
import pennylane as qml import numpy as np import tensorflow as tf
We also declare a 3-qubit simulator device running in Cirq.
dev = qml.device('cirq.simulator', wires=3)
Generator and Discriminator¶
In classical GANs, the starting point is to draw samples either from some “real data” distribution, or from the generator, and feed them to the discriminator. In this QGAN example, we will use a quantum circuit to generate the real data.
For this simple example, our real data will be a qubit that has been rotated (from the starting state \(\left|0\right\rangle\)) to some arbitrary, but fixed, state.
def real(phi, theta, omega): qml.Rot(phi, theta, omega, wires=0)
For the generator and discriminator, we will choose the same basic circuit structure, but acting on different wires.
Both the real data circuit and the generator will output on wire 0, which will be connected as an input to the discriminator. Wire 1 is provided as a workspace for the generator, while the discriminator’s output will be on wire 2.
def generator(w): qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RY(w[2], wires=0) qml.RY(w[3], wires=1) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(w[6], wires=0) qml.RY(w[7], wires=0) qml.RZ(w[8], wires=0) def discriminator(w): qml.RX(w[0], wires=0) qml.RX(w[1], wires=2) qml.RY(w[2], wires=0) qml.RY(w[3], wires=2) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=2) qml.CNOT(wires=[1, 2]) qml.RX(w[6], wires=2) qml.RY(w[7], wires=2) qml.RZ(w[8], wires=2)
We create two QNodes. One where the real data source is wired up to the
discriminator, and one where the generator is connected to the
discriminator. In order to pass TensorFlow Variables into the quantum
circuits, we specify the
"tf" interface.
@qml.qnode(dev, interface="tf") def real_disc_circuit(phi, theta, omega, disc_weights): real(phi, theta, omega) discriminator(disc_weights) return qml.expval(qml.PauliZ(2)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(2))
QGAN cost functions¶
There are two cost functions of interest, corresponding to the two stages of QGAN training. These cost functions are built from two pieces: the first piece is the probability that the discriminator correctly classifies real data as real. The second piece is the probability that the discriminator classifies fake data (i.e., a state prepared by the generator) as real.
The discriminator is trained to maximize the probability of correctly classifying real data, while minimizing the probability of mistakenly classifying fake data.
The generator is trained to maximize the probability that the discriminator accepts fake data as real.
def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights)
Training the QGAN¶
We initialize the fixed angles of the “real data” circuit, as well as the initial parameters for both generator and discriminator. These are chosen so that the generator initially prepares a state on wire 0 that is very close to the \(\left| 1 \right\rangle\) state.
phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 8) + \ np.random.normal(scale=eps, size=(9,)) init_disc_weights = np.random.normal(size=(9,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights)
We begin by creating the optimizer:
opt = tf.keras.optimizers.SGD(0.1)
In the first stage of training, we optimize the discriminator while keeping the generator parameters fixed.
cost = lambda: disc_cost(disc_weights) for step in range(50): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val))
Out:
Step 0: cost = -0.10942014679312706 Step 5: cost = -0.3899883683770895 Step 10: cost = -0.6660191221162677 Step 15: cost = -0.8550836374051869 Step 20: cost = -0.9454460255801678 Step 25: cost = -0.9805878275074065 Step 30: cost = -0.9931367967510596 Step 35: cost = -0.9974893236067146 Step 40: cost = -0.9989861474605277 Step 45: cost = -0.9994997430330841
At the discriminator’s optimum, the probability for the discriminator to correctly classify the real data should be close to one.
print("Prob(real classified as real): ", prob_real_true(disc_weights).numpy())
Out:
Prob(real classified as real): 0.9998971883615013
For comparison, we check how the discriminator classifies the generator’s (still unoptimized) fake data:
print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy())
Out:
Prob(fake classified as real): 0.00024289608700200915
In the adversarial game we now have to train the generator to better fool the discriminator. For this demo, we only perform one stage of the game. For more complex models, we would continue training the models in an alternating fashion until we reach the optimum point of the two-player adversarial game.
cost = lambda: gen_cost(gen_weights) for step in range(200): opt.minimize(cost, gen_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val))
Out:
Step 0: cost = -0.00026636153052095324 Step 5: cost = -0.00042660595499910414 Step 10: cost = -0.0006873353268019855 Step 15: cost = -0.0011113660875707865 Step 20: cost = -0.001800207479391247 Step 25: cost = -0.0029180023120716214 Step 30: cost = -0.004727608757093549 Step 35: cost = -0.007646640995517373 Step 40: cost = -0.012325902469456196 Step 45: cost = -0.019754532724618912 Step 50: cost = -0.03136847913265228 Step 55: cost = -0.04909771494567394 Step 60: cost = -0.07520400732755661 Step 65: cost = -0.11169053986668587 Step 70: cost = -0.15917328000068665 Step 75: cost = -0.21566066145896912 Step 80: cost = -0.27637405693531036 Step 85: cost = -0.3354172706604004 Step 90: cost = -0.38835008442401886 Step 95: cost = -0.4337175488471985 Step 100: cost = -0.4728485941886902 Step 105: cost = -0.5087772309780121 Step 110: cost = -0.5451968759298325 Step 115: cost = -0.585662230849266 Step 120: cost = -0.6327883154153824 Step 125: cost = -0.6872449368238449 Step 130: cost = -0.7468433082103729 Step 135: cost = -0.8066394627094269 Step 140: cost = -0.8607337176799774 Step 145: cost = -0.9048400558531284 Step 150: cost = -0.937667777761817 Step 155: cost = -0.9604097697883844 Step 160: cost = -0.9753705067560077 Step 165: cost = -0.984874417539686 Step 170: cost = -0.9907763195224106 Step 175: cost = -0.9943897356279194 Step 180: cost = -0.9965827631531283 Step 185: cost = -0.9979065986117348 Step 190: cost = -0.9987028733594343 Step 195: cost = -0.9991812075313646
At the optimum of the generator, the probability for the discriminator to be fooled should be close to 1.
print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy())
Out:
Prob(fake classified as real): 0.9994220492662862
At the joint optimum the discriminator cost will be close to zero, indicating that the discriminator assigns equal probability to both real and generated data.
print("Discriminator cost: ", disc_cost(disc_weights).numpy()) # The generator has successfully learned how to simulate the real data # enough to fool the discriminator.
Out:
Discriminator cost: -0.00047513909521512687
Total running time of the script: ( 0 minutes 31.196 seconds)
Gallery generated by Sphinx-Gallery
Contents
Downloads | https://pennylane.ai/qml/demos/tutorial_QGAN.html | CC-MAIN-2020-16 | refinedweb | 1,317 | 54.69 |
Java class named JOptionPane that produce dialog boxes. A dialog box is a GUI object in which you can place messages that you want to display on the screen. The showMessageDialog() method that is part of the JOptionPane class. The showMessageDialog() method is followed by a set of parentheses. The showMessageDialog() are two arguments. The first argument is null. its means the message box should be shown in the center of the screen. After the comma, second argument is the string that should be output.
Here is the java code for the program Dialog Box in Java Example :
import javax.swing.JOptionPane;
public class DialogBoxinJavaExample
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, " Dialog Box in Java | http://ecomputernotes.com/java/swing/dialogboxinjavaexample | CC-MAIN-2019-39 | refinedweb | 118 | 61.02 |
. r~
typedef unsigned long word; #define ldq(X) (*(const word *)(X)) #define ldq_u(X) (*(const word *)((X) & -8)) #define cmpbge __builtin_alpha_cmpbge #define extql __builtin_alpha_extql #define extqh __builtin_alpha_extqh #define insbl __builtin_alpha_insbl #define insqh __builtin_alpha_insqh #define zap __builtin_alpha_zap #define unlikely(X) __builtin_expect ((X), 0) #define prefetch(X) __builtin_prefetch ((void *)(X), 0) #define find(X, Y) cmpbge (0, (X) ^ (Y)) void *memchr (const void *xs, int xc, word n) { word s = (word)xs; word c; word current, found; word s_align; if (unlikely (n == 0)) return 0; current = ldq_u (s); /* Replicate low byte of C into all bytes. */ { word t = insbl (xc, 1); /* 000000c0 */ c = (xc & 0xff) | t; /* 000000cc */ c = (c << 16) | c; /* 0000cccc */ c = (c << 32) | c; /* cccccccc */ } if (unlikely (n < 9)) goto only_quad; /* Align the source, and decrement the count by the number of bytes searched in the first word. */ s_align = s & -8; n += (s & 7); n -= 8; /* Deal with misalignment in the first word for the comparison. */ { word mask = insqh (-1, s); found = cmpbge (0, (current ^ c) | mask); if (found) goto found_it; } s_align += 8; /* If the block is sufficiently large, align to cacheline (minimum 64-bytes), prefetch the next line, and read entire cachelines at a time. */ if (unlikely (n >= 256)) { prefetch (s_align + 64); while (s_align & 63) { current = ldq (s_align); found = find (current, c); if (found) goto found_it; s_align += 8; n -= 8; } while (n > 64) { word c0, c1, c2, c3, c4, c5, c6, c7; prefetch (s_align + 64); c0 = ldq (s_align + 0*8); c1 = ldq (s_align + 1*8); c2 = ldq (s_align + 2*8); c3 = ldq (s_align + 3*8); c4 = ldq (s_align + 4*8); c5 = ldq (s_align + 5*8); c6 = ldq (s_align + 6*8); c7 = ldq (s_align + 7*8); found = find (c0, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c1, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c2, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c3, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c4, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c5, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c6, c); if (unlikely (found)) goto found_it; s_align += 8; found = find (c7, c); if (unlikely (found)) goto found_it; s_align += 8; n -= 64; } } /* Quadword aligned loop. */ while (1) { current = ldq (s_align); if (n < 8) goto last_quad; found = find (current, c); if (found) goto found_it; s_align += 8; n -= 8; } only_quad: { word end = zap (n, 0x80) - 1; word last = extqh (ldq_u (s + end), s); word first = extql (current, s); current = first | last; /* We've read one word and aligned it in the register. Thus the bit offset in current is relative to S. */ s_align = s; } last_quad: { word mask = (-1ul >> -n); found = find (current, c) & mask; if (found == 0) return 0; } found_it: { word offset; #ifdef __alpha_cix__ offset = __builtin_alpha_cttz (found); #else /* Extract LSB. */ found &= -found; /* Binary search for the LSB. */ offset = (found & 0x0f ? 0 : 4); offset += (found & 0x33 ? 0 : 2); offset += (found & 0x55 ? 0 : 1); #endif return (void *)(s_align + offset); } } | https://lists.debian.org/debian-alpha/2009/07/msg00014.html | CC-MAIN-2017-39 | refinedweb | 489 | 59.91 |
Sqlite3 Browser
Hi All,
I thought I would share something that I have been working on and off for a week or so now, it is a sqlite3 browser. I have been trying to teach my self python and this is currently a very much work in progress so please ignore the quality of the code etc.
The file browser is currently only set to show files with the extension db, but that can be changed.
I have only tested this with the 1.6 beta but I don't think I have used anything that would stop it working with 1.5
The code is available here so please share any comments or suggestion you have.
I did just want to mention that pythonista is a great application and I wanted to thank @omz for it.
@shaun-h This is a cool tool and I have been using it a lot lately to understand sqlite tables.
Based on studying it, I created a few utility functions that might be of use... converts an sqlite database table into a list of namedtuples or a dict of namedtuples. Thanks for the inspiration!
Thanks, I am glad someone found some use from it.
I have a few more features I want to add to it in the near future when I get some time. Like the ability to run your own queries and create tables/views etc, so I will take a look at the utilities functions you have created, they might come in handy.
If you do have any suggestions for features or just thoughts please let me know. moves an sqlite database into a series of lists or dicts which contain namedtuples which match the columns of each table. Probably not a good idea for huge databases but it is quite useful for understanding databases that will fit in RAM.
Hi shaun-h,
your sqlite3 browser looks great and it's working fine with Pythonista 1.5 btw.
Maybe you think about showing the current relative path in the file browser (e.g. in view.name) and don't hiding the eXit button. And I hope you have time to implement the new features (queries, ...) that would be awesome.
thanks @brumm I have been meaning to get back to it, I have been getting a bit distracted with istaflow which is on my github at the moment,.
I do have queries, and some more "wizard" like features to help create tables, databases, etc on the list if you have any ideas for feature happy to take them on board.
I will take a look at showing the current relative path in view.name that is a good idea.
A little nifty code I wrote to show the current working directory in the file browser. It works by pasting into class FilebrowserController in filebrowser.py. Tell me what you think :)
def tableview_title_for_header(self, tableview, section): lst = str(os.getcwd()).split("/") for idx, item in enumerate(lst): if len(item) > 20: item = item[:20]+".." lst[idx] = item if len(lst) > 3: return "../"+"/".join(lst[-3:]) else: return "/".join(lst) | https://forum.omz-software.com/topic/2326/sqlite3-browser/3 | CC-MAIN-2019-35 | refinedweb | 517 | 81.22 |
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Data.List -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : stable -- Portability : portable -- -- Operations on lists. -- ----------------------------------------------------------------------------- module Data.List ( -- * Basic functions (++) , head , last , tail , init , findIndices p ls = loop 0# ls where loop _ [] = [] loop n (x:xs) | p x = I# n : loop (n +# 1#) xs | otherwise = loop (n +# 1#) xs . -- Both lists must be finite. isSuffixOf :: (Eq a) => [a] -> [a] -> Bool isSuffixOf x y = reverse x `isPrefixOf` reverse] #ifdef USE_REPORT_PRELUDE nub = nubBy (==) #else -- stolen from HBC nub l = nub' l [] -- ' where nub' [] _ = [] -- ' nub' (x:xs) ls -- ' | x `elem` ls = nub' xs ls -- ' | otherwise = x : nub' xs (x:ls) -- ' #endif -- | mapAccumL _ s [] = (s, []) mapAccumL f s (x:xs) = (s'',y:ys) where (s', y ) = f s x (s'',ys) = mapAccumL f s' x) -- | The 'tails' function returns all final segments of the argument, -- longest first. For example, -- -- > tails "abc" == ["abc", "bc", "c",""] -- -- Note that 'tails' has the following strictness property: -- @tails _|_ = _|_ : _|_@ tails :: [a] -> [[a]] tails xs = xs : case xs of [] -> [] _ : xs' -> tails xs' -- |] -- | https://hackage.haskell.org/package/base-4.7.0.2/docs/src/Data-List.html | CC-MAIN-2018-26 | refinedweb | 193 | 54.46 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
In the Spirit of C, by Greg Colvin.
A somewhat biased and over enthusiastic overview of the evolution of C and ilk.
I am sure LtU readers will find a lot they disagree with. I suggest starting with the quote from the ANSI C Rationale...
I kind of liked this aside:
real programmers can write FORTRAN in any language
Is that a good thing or a bad thing? ;-)
Indeed, here's FORTRAN in Hebrew: פורטרן
So easy to become a real programmer... So long job security ;-)
For some reason, this reminds me of one of the responses in an article about The Two Things:
Software is easy except for the special cases.
Unfortunately, stopping and starting are special cases.
Ehud, I've noticed that your comments appear to be made on the top level, rather than beneith the actual post that you comment on.
With the new superior presentation engine in LtU (which does indent the posts according to their tree depth), could I ask whether it is intentional?
I don't always remember to click the "reply to this comment" link. Sorry.
There's a note from the editor in there that implies that D has a more convenient template syntax.
From what I've read, it seems like D's syntax is the most cumbersome of all because template parameter types aren't inferred when invoking a template function. Am I mistaken?
When I was involved with D (and the documentation still says so) you had to explicit instantiate a template and always mention it (because templates are namespaces too). So a template function isn't invoked, instead you have to deal with the explicit instances. | http://lambda-the-ultimate.org/node/26 | CC-MAIN-2019-13 | refinedweb | 299 | 61.46 |
I created this method for testing/experimenting with a kernel on a 32 bit Intel/AMD system. The programs can easily be port to a 64 bit Intel/AMD processor with some reference to the Intel/AMD manuals..I actually have it here somewhere if you really need it.
Please Note - This is a hack that will only work on a 32 bit Intel/AMD system, paying special attention to the lines "don't need this line for some compilers/systems - i.e slackware 13.0"
So what does the module and program do?
The module basically sets up an interrupt "0x81" and a simple handler so that the programmer can interact with the kernel in a free and controlled way by calling the interrupt and executing the handler.
I know, not much of an example, its basic allowing the programmer to pass the address of a variable into the kernel an then set it to 99999 but this implementation can be expanded to cover a whole host of interests.
test1.c - The Kernel Module
testit.c - The test user space executabletestit.c - The test user space executableCode:
#include <linux/kernel.h>
#include <linux/module.h>
struct id//interrupt description table
{
unsigned short limit;
void *base;
}__attribute__((packed)) myidtr;
struct intgate//interrupt gate struct
{
unsigned short off1;
unsigned short sel;
unsigned short none;
unsigned short off2;
}__attribute__((packed)) *idttr1, *idttr2, orig, orig2;
unsigned int myint = 99999;//value to set user variable to
void myfunc(void)//our simple handler
{
__asm__
(
"movl %ebp, %esp\n\t"//don't need this line for some compilers/systems - i.e slackware 13.0
"popl %ebp\n\t"//don't need this line for some compilers/systems - i.e slackware 13.0
"pushl %eax\n\t"
"pushl %ebx\n\t"
"movl myint, %ebx\n\t"
"movl %ebx, (%eax)\n\t"
"popl %ebx\n\t"
"popl %eax\n\t"
"iret\n\t"
);
}
union myaddr
{
void *addr;
struct
{
unsigned short a;
unsigned short b;
}__attribute__((packed)) iaddr;
}__attribute__((packed)) theaddr;
int init_module()
{ __asm__ ("sidt myidtr\n\t");
idttr1 = (struct intgate*)(myidtr.base + (128 * 8));//interrupt 0x80
idttr2 = (struct intgate*)(myidtr.base + (129 * 8));//interrupt 0x81
orig2 = *idttr2;
*idttr2 = *idttr1;//short cut - set 0x81 interrupt equal to interrupt 0x08
theaddr.addr = (void*)myfunc;//interrupt handler
idttr2->off1 = theaddr.iaddr.a;//set myfunc to 0x81 handler
idttr2->off2 = theaddr.iaddr.b;//set myfunc to 0x81 handler
return 0;
}
void cleanup_module()
{
*idttr2 = orig2;
printk("setting everything back...we're out of here!\n");
}
Note - this is from months of reading the AMD/Intel manuals...I thought I would save you the pleasure of that task..Note - this is from months of reading the AMD/Intel manuals...I thought I would save you the pleasure of that task..Code:
#include <stdio.h>
#include <stdlib.h>
unsigned int testval = 0;
int main(int argc, char**argv)
{
fprintf(stdout, "initial testval->%d\n", testval);
__asm__
(
"movl $testval, %eax\n\t"
"int $0x81\n\t"
);
fprintf(stdout, "final testval->%d\n", testval);
exit(EXIT_SUCCESS);
} | http://www.linuxforums.org/forum/kernel/creating-test-interrupt-intel-amd-32-bit-processor-print-158869.html | CC-MAIN-2017-51 | refinedweb | 499 | 57.98 |
Hello,
I am currently trying to build an app with a new feature for mobile platforms (iOS and Android). The added feature consists of downloading a list of movies (up to 60). At first glance, using the www class to download movies seemed to work fine on all platforms but unfortunately, an OutOfMemoryException occurs after downloading several movies. On iOS this occurs after downloading approximately 6-16 movies (the file size varies between 10 and 50 MB). Since I have read about other people having similar problems with downloading "large" files, the size may be relevant.
I am using Unity 4.6.2p1 and testing the app on an iPad3 and 4 (iOS 8.1.3) as well as on a Samsung Note 10.1 (2014 Edition) (Android 4.3). Please see the relevant code below:
public class MovieController{
WWW www;
List<string> downloadableMovies;
public void StartDownload(List<string> movies){
downloadableMovies = movies;
StartCoroutine("DownloadMovies");
}
IEnumerator DownloadMovies() {
int i = 1;
foreach(string fileName in downloadableMovies){
www = new WWW(url+"/"+videoInfos[id].basename+movieExtension);
yield return www;
if (www != null && string.IsNullOrEmpty() &&) {
FileStream stream = new FileStream(Application.persistentDataPath+ "/"+ fileName, FileMode.Create);
try{
stream.Write(, 0,);
}
catch(Exception ex){
DeleteMovie(fileName); // delete incomplete file
yield break;
}
finally{
stream.Close();
stream.Dispose();
stream = null;
}
};
www = null;
i++;
}
}
}
Obviously there has been a known memory leak issue on iOS prior to Unity 4.6.1 (see the issue tracker) but since I am using a newer version, this should have been resolved. I have already tried using a "using" statement and have added Dispose-calls for both the www and Stream instances. After several time-consuming rebuilds and tests on iOS, I even tried implementing another download solution using the System.Net.Sockets library based on this Unity Answer but that doesn't seem to work with the 64-bit version for iOS (required since Feb 1st).
Are there any mistakes in my code that I am oblivious of? Or can anybody confirm that using the www class for downloading files causes memory problems? If the alternative socket solution does currently not work with 64-bit iOS builds, what else could? Any help would be much appreciated.
EDIT: I uploaded the iOS log, in case that may prove helpful. EDIT 2: I also tried downloading the movies via the WebClient API which is currently not functioning, see the Unity blog.
Check this nice blog, working perfectly for big files downloading
Answer by sdnj
·
Feb 13, 2015 at 05:24 PM
Yesterday's Unity Patch 4.6.2p2 fixed the System.Net.Socket incompatibility with iOS 64-bit builds. My solution based on this Unity Answer using sockets now works fine and I will be able to submit my app to the store next week. I'm still not sure whether the memory problem with the www-class is a known issue or not, maybe I will send a bug report to Unity.
Here is the great plugin to download any small/big files without memory leak.
For more details, visit this.
See Request of WWW or UnityWebRequest, 403 error only from android in a specific url (GET)
2
Answers
Sending to API special french characters
0
Answers
Download then open image on IOS
0
Answers
Open a PDF on Android and iOS
2
Answers
Downloading iOS games for free?
2
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/899637/www-download-outofmemoryexception-ios-and-android.html | CC-MAIN-2021-17 | refinedweb | 559 | 65.01 |
Created on 2007-04-16 10:05 by iceberg4ever, last changed 2007-05-03 17:12 by doerwalter.
This bug is similar but not exactly the same as bug215974. ()
In my test, even multiple write() within an open()~close() lifespan will not cause the multi BOM phenomena mentioned in bug215974. Maybe it is because bug 215974 was somehow fixed during the past 7 years, although Lemburg classified it as WontFix.
However, if a file is appended for more than once, by an "codecs.open('file.txt', 'a', 'utf16')", the multi BOM appears.
At the same time, the saying of "(Extra unnecessary) BOM marks are removed from the input stream by the Python UTF-16 codec" in bug215974 is not true even in today, on Python2.4.4 and Python2.5.1c1 on Windows XP.
Iceberg
------------------
PS: Did not find the "File Upload" checkbox mentioned in this web page, so I think I'd better paste the code right here...
import codecs, os
filename = "test.utf-16"
if os.path.exists(filename): os.unlink(filename) # reset
def myOpen():
return codecs.open(filename, "a", 'UTF-16')
def readThemBack():
return list( codecs.open(filename, "r", 'UTF-16') )
def clumsyPatch(raw): # you can read it after your first run of this program
for line in raw:
if line[0] in (u'\ufffe', u'\ufeff'): # get rid of the BOMs
yield line[1:]
else:
yield line
fout = myOpen()
fout.write(u"ab\n") # to simplify the problem, I only use ASCII chars here
fout.write(u"cd\n")
fout.close()
print readThemBack()
assert readThemBack() == [ u'ab\n', u'cd\n' ]
assert os.stat(filename).st_size == 14 # Only one BOM in the file
fout = myOpen()
fout.write(u"ef\n")
fout.write(u"gh\n")
fout.close()
print readThemBack()
#print list( clumsyPatch( readThemBack() ) ) # later you can enable this fix
assert readThemBack() == [ u'ab\n', u'cd\n', u'ef\n', u'gh\n' ] # fails here
assert os.stat(filename).st_size == 26 # not to mention here: multi BOM appears
append mode is simply not supported for codecs. How would the codec find out the codec state that was active after the last characters where written to the file?
I suggest you close this as wont fix.
Closing as "won't fix"
If such a bug would be fixed, either StreamWriter or StreamReader should do something.
I can understand Doerwalter that it is somewhat not comfortable for a StreamWriter to detect whether these is already a BOM at current file header, especially when operating in append mode. But, IMHO, the StreamReader should be able to detect multi BOM during its life span and automatically ignore the non-first one, providing that a BOM is never supposed to occur in normal content. Not to mention that such a Reader seems exist for a while, according to the "(extra unnecessary) BOM marks are removed
from the input stream by the Python UTF-16 codec" in bug215974 (
detail).
Therefore I don't think a WontFix will be the proper FINAL solution for this case.
But BOMs *may* appear in normal content: Then their meaning is that of ZERO WIDTH NO-BREAK SPACE (see for more info).
The longtime arguable ZWNBSP is deprecated nowadays ( the suggests a "U+2060 WORD JOINER" instead of ZWNBSP ). However I can understand that "backwards compatibility" is always a good concern, and that's why SteamReader seems reluctant to change.
In practice, a ZWNBSP inside a file is rarely intended (please also refer to the topic "Q: What should I do with U+FEFF in the middle of a file?" in same URL above). IMHO, it is very likely caused by the multi-append file operation or etc. Well, at least, the unsymmetric "what you write is NOT what you get/read" effect between "codecs.open(filename, 'a', 'UTF-16')" and "codecs.open(filename, 'r', 'UTF-16')" is not elegant enough.
Aiming at the unsymmetry, finally I come up with a wrapper function for the codecs.open(), which solve (or you may say "bypass") the problem well in my case. I'll post the code as attachment.. //shrug
Hope the information above can be some kind of recipe for those who encounter same problem. That's it. Thanks for your patience.
Best regards,
Iceberg
File Added: _codecs.py
.
This seems to be wrong. Looking at the source code (Objects/unicodeobjects.c) reveals that only the first BOM is skipped.
OK, I've updated the documentation (r55094, r55095) | http://bugs.python.org/issue1701389 | crawl-002 | refinedweb | 740 | 74.08 |
Hi Per-Olof,
thanks for your patch! It's applied to the HEAD of the cvs.
Your question "What is a complete fix?" is actually very
interesting.
I think there are two answers you can choose from:
1. A fix is never complete.
2. The source is enough.
Ok, just a joke. Let's get more seriously again.
The usual (but not optimal) procedure is to first send
a patch for the source and afterwards (hopefully) send
more patches for documentation.
This is mainly done, as you never know if your patch
will be applied. So if you submit 10pages of documentation
you worked very hard on, and the committers ignore your
patch, well, this might not be your best day.
Unfortunately (and this includes myself often) after
the source is accepted, the submitter forgets about
sending documentation updates.
So, we would be very happy to receive always source
and at least a small docs update in one patch. This
docs can then completed later on.
I think documentation in general includes source code
documentation in java doc format and a user documentation
(see in the documentation/xdocs directory for examples).
So in case of your SQLTransformer patch, the documentation
for the sql transformer in the userdocs/transformers section
should be updated.
Depending on the patch, examples are welcome to be included
in the webapp.
I hope this answers your question.
Carsten (waiting for more patches :-) )
> Per-Olof Norén wrote:
Hi comitters,
I have now implemented namespace handling for the SQLTransformer.
Since this is my first commit, I´d like some pointers to what needs to be
shipped along with the patch itself,
ie what documents needs to be updated for it to be a "complete fix". I´m
thinking of docs etc?
I´m asking this, because there´s possibly more patches and additions on the
way :-)
Regards
Per-Olof Norén
Stochholm, Sweden
---------------------------------------------------------------------
To unsubscribe, e-mail: cocoon-dev-unsubscribe@xml.apache.org
For additional commands, email: cocoon-dev-help@xml.apache.org | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200110.mbox/%3CGMEBIBHGAOFGJCDPJANDOEKDCOAA.cziegeler@sundn.de%3E | CC-MAIN-2017-09 | refinedweb | 334 | 66.74 |
#include <db.h> int db_env_set_func_pread(ssize_t (*func_pread)(int fd, void *buf, size_t nbytes, off_t offset));
Replace Berkeley DB calls to the IEEE/ANSI Std 1003.1 (POSIX) pread function with func_pread, which must conform to the standard interface specification.
The
db_env_set_func_pread() configures all operations performed
by a process and all of its threads of control, not operations
confined to a single database environment.
Although the
db_env_set_func_pread() may be called at any time
during the life of the application, it should normally be called
before making calls to the db_env_create or
db_create methods.
The
db_env_set_func_pread()
function returns a non-zero error value on failure and 0 on success. | http://docs.oracle.com/cd/E17276_01/html/api_reference/C/db_env_set_func_pread.html | CC-MAIN-2015-14 | refinedweb | 107 | 50.97 |
> matlab7.x.rar > wgfcnkey.cpp
/*================================================================= * wgfcnkey ---- traps pressing of function keys (F1, F2, ..., F12) * and Shift, Ctrl, Alt keys in an MATLAB figure window * * Use this command-line to compile in MATLAB: * mex wgfcnkey.cpp user32.lib * * Input ---- None * Output ---- a scaler * = 0, no function was pressed * = 1, F1 was pressed * ... * = 12, F12 was pressed * = 13, left Shift was pressed * = 14, left Ctrl was pressed * = 15, left Alt was pressed * = 16, right Shift was pressed * = 17, right Ctrl was pressed * = 18, right Alt was pressed * * Created by: Dong Weiguo, 22 Jan. 2004 * Updated on 29 Jan. 2004, included the left and right instances of * Shift, Ctrl, and Alt keys. * *=================================================================*/ /* $Revision: 1.10 $ */ #include
#include "mex.h" void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { double *x; char *input_buf; int buflen,status; /* Check for proper number of arguments */ if (nrhs >= 1) { mexErrMsgTxt("No input argument required."); } /* create output array*/ plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); x = mxGetPr(plhs[0]); x[0] = 0.0; /* Do the actual computations in a subroutine */ /* HWND hWnd; hWnd = FindWindow(NULL, input_buf); MSG msg; //PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE); //GetMessage(&msg, hWnd, 0, 0); TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_KEYDOWN) { switch(msg.wParam) { case VK_F1: //AfxMessageBox("Test"); x[0] = 1; } } */ //x[0] = GetKeyState(VK_F1); int i; short keystatus = 0; for (i = VK_F1; i | http://read.pudn.com/downloads50/sourcecode/math/174049/ch03/wgfcnkey.cpp__.htm | crawl-002 | refinedweb | 222 | 63.59 |
desired language:
desired language:
Game Jam survival guide
The Decentraland September Game Jam (previously ‘Hackathon’) will take place from September 16th to September 30th. This Survival Guide is all you need to get started and get creative in the Metaverse.
Install the CLI and get started
See the Docs Home for first steps to get started.
Tutorials
Read our tutorials for detailed instructions for building basic scenes.
Engage with other Jammers
Visit Discord, join a lively discussion about what’s possible and how!
You can also enrol in free courses at the Decentraland University channel.
Team up
While you’re welcome to work on a project by yourself, the Game Jam experiences are often team efforts. Why not reach out to friends who might be a good match?
You can also check this spreadsheet to post searches for team mates or find teams to join.
Debug decentraland-ecs-utils
Import the library into the scene’s script. Add this line at the start of your
game.tsfile, or any other TypeScript files that require it:
import utils from "../node_modules/decentraland-ecs-utils/index"
In your TypeScript file, write
utils.and let the suggestions of your IDE show the available helpers.
Read the full documentation of the Utils library here
Project Examples
Here are some examples submitted from our Hackathon back in June that you can take inspiration from…
To see our official example scenes, with links to their code, see scene examples. | https://docs.decentraland.org/getting-started/game-jam/ | CC-MAIN-2019-35 | refinedweb | 242 | 64.3 |
In this tutorial, you will learn how to perform Laravel localization and present your application in multiple languages. You will learn how to work with translation files, perform pluralization, create a language switcher, and more.
Localization is the second phase of the Laravel internationalization (i18n) process. In Laravel i18n, an application is designed to fit various languages and cultures. Localization is adapting said internationalized applications to a specific language through translation.
So, shall we begin?
Huge thanks go to my colleague Andrejs Bekešs, who prepared the code samples and technical explanations for this article.
- Prerequisites and assumptions
- Working with translation files
- Simple translations
- Locales in Laravel
- Translation files
- Switching locales in Laravel
- Advanced translation options in PHP Laravel
- Simplifying the translation process with Lokalise
- Conclusion
- Further reading
Prerequisites and assumptions
- We will be using Laravel version 8.x in this tutorial.
- This tutorial has been created with the assumption that you have the necessary knowledge of the PHP programming language and the Laravel framework.
- Your domain is
localhost. If not, then replace
localhostwith your domain name or IP address (depending on your installation).
Working with translation files
So, in Laravel, just like in many other frameworks, you will store translations for different languages in separate files. There are two ways to organize Laravel translation files:
- An old approach which involves storing your files under the following path:
resources/lang/{en,fr,ru}/{myfile.php}.
- A new approach of having
resources/lang/{fr.json, ru.json}files.
For languages that differ by territory, you should name the language directories/files according to ISO 15897. For example, for British English you would use
en_GB rather than
en-gb. In this article, we will focus on the second approach, but the same applies to the first one (with the exception of how translation keys are named and retrieved). Also, we’ll be using the default
welcome.blade.php file as our playground.
Simple translations
Now, let’s head over to the
resources/views/welcome.blade.php file and replace the contents of the
body tag with our own, like so:
"> <div class="flex justify-center pt-8 sm:justify-start sm:pt-0"> Welcome to our website </div> </div> </div> </body>
We’ll start by preparing our welcome message for localization, which is really easy in Laravel. All you need to do is replace the “Welcome to our website” text with the following code:
{{ __('Welcome to our website') }}. This will instruct Laravel to display “Welcome to our website” by default and look for translations of this string if a non-English language is set (we’ll get to this later on). English will be set as a default language of our app, so by default we will simply display the “Welcome to our website” text. If the locale is different, we’ll try to search for the corresponding translation that will be created in a moment.
Locales in Laravel
But how does Laravel know what the current language is or what languages are available in the application? It does this by looking at the locale setup in the
config/app.php app. Open up this file and look for these two array keys:
/* |-------------------------------------------------------------------------- |',
The descriptions shown above the keys should be self-explanatory, but in short, the
locale key contains the default locale of your application (at least, if no other locale was set in the code). The
fallback_locale is the one being activated in the case that we set a non-existent locale in our application.
While we have this file open, let’s add a new key in here for our convenience later on by listing all the locales that our application is going to support. We’ll use this later when adding a locale switcher. However, this is an optional task as Laravel does not require us to do it.
/* |-------------------------------------------------------------------------- | Available locales |-------------------------------------------------------------------------- | | List all locales that your application works with | */ 'available_locales' => [ 'English' => 'en', 'Russian' => 'ru', 'French' => 'fr', ],
Great! Now our application supports three languages: English, Russian, and French.
Translation files
Now that we have established all the locales we’ll work with, we can go ahead and move on to translating our default welcome message.
Let’s start by adding new localization files in the
resources/lang folder. First, create a
resources/lang/ru.json file and add the corresponding translations, as follows:
{ "Welcome to our website": "Добро пожаловать на наш сайт" }
Next, create a
resources/lang/fr.json file:
{ "Welcome to our website": "Bienvenue sur notre site" }
As you can see, we’re always referencing the default message that we added in the
welcome.blade.php file (which was
{{ __('Welcome to our website') }}). The reason we don’t have to create an
en.json file is because Laravel already knows that messages we pass in by default to the
__() function are for our default locale, which is
en (as explained in the section above).
Switching locales in Laravel
At this point, Laravel does not know how to switch locales so let’s perform translations directly inside the route for now. Edit the default welcome route as shown below:
Route::get('/{locale?}', function ($locale = null) { if (isset($locale) && in_array($locale, config('app.available_locales'))) { app()->setLocale($locale); } return view('welcome'); });
We can now visit our website, specifying any of the available languages as the first route segment: for example,
localhost/ru or
localhost/fr. You should see the localized content. In the case that you specify a non-supported locale or don’t specify a locale at all, Laravel will use
en by default.
Middleware
Passing the locale for every site link might not be what you want and could look not quite so clean esthetically. That’s why we’ll perform language setup via a special language switcher and use the user session to display the translated content. Therefore, create a new middleware inside the
app/Http/Middleware/Localization.php file or by running
artisan make:middleware Localization.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Session; class Localization { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { if (Session::has('locale')) { App::setLocale(Session::get('locale')); } return $next($request); } }
This middleware will instruct Laravel to utilize the locale selected by the user if this selection is present in the session.
Since we need this operation to be run on every request, we also need to add it to the default middleware stack at
app/http/Kernel.php for the
web middleware group:
*, /* <--- add this */ ],
Changing routes
Next, we have to add a route to change locale. We’re using a closure route, but you can use exactly the same code inside your controller if you wish:
Route::get('language/{locale}', function ($locale) { app()->setLocale($locale); session()->put('locale', $locale); return redirect()->back(); });
Also, don’t forget to remove the previously added locale switching previously added in our default welcome route:
Route::get('/', function () { return view('welcome'); });
With this being done, the only way for the user to switch the currently set language is by entering
localhost/language/{locale}. The
locale selection will be stored inside the session and redirect users back to where they came from (check the
Localization middleware). To test it out, head over to
localhost/language/ru (as long as your session cookie is present in your browser), and you will see the translated content. You can freely move around the website or try to refresh the page and see that the selected language is being preserved.
The actual switcher
Now we need to create something that the user can click on to change the language instead of entering locale codes into the URL manually. To do this, we’ll add a very simple language control. Therefore, create a new
resources/views/partials/language_switcher.blade.php file with the following code:
<div class="flex justify-center pt-8 sm:justify-start sm:pt-0"> @foreach($available_locales as $locale_name => $available_locale) @if($available_locale === $current_locale) <span class="ml-2 mr-2 text-gray-700">{{ $locale_name }}</span> @else <a class="ml-1 underline ml-2 mr-2" href="language/{{ $available_locale }}"> <span>{{ $locale_name }}</span> </a> @endif @endforeach </div>
Include the newly created switcher into the “welcome” view:
"> @include('partials/language_switcher') <div class="flex justify-center pt-8 sm:justify-start sm:pt-0"> {{ __('Welcome to our website') }} </div> </div> </div> </body>
Open the
app/Providers/AppServiceProvider.php file and add the code to be shared when our language switcher is composed. Specifically, we’ll share the current locale that can be accessed as
{{ $current_locale }}.
* Bootstrap any application services. * * @return void */ public function boot() { view()->composer('partials.language_switcher', function ($view) { $view->with('current_locale', app()->getLocale()); $view->with('available_locales', config('app.available_locales')); }); }
Advanced translation options in PHP Laravel
We will mostly be working with
resources/views/welcome.blade.php, so everything needs to happen in our welcome view unless specified otherwise.
Parameters in translation strings
For instance, let’s greet our imaginary user (Amanda) instead of simply displaying a generic message:
{{ __('Welcome to our website, :Name', ['name' => 'amanda']) }}
Please note that we have used the name with a lowercase first letter, but the placeholder with an uppercase first letter. In this way, Laravel can help you capitalize the actual word automatically. This will occur if the placeholder starts with a capital letter, i.e.,
:Name produces “Amanda” or a full uppercase word,
:NAME, produces “AMANDA”.
Additionally, let’s update our
resources/lang/fr.json and
resources/lang/ru.json translation files, since right now we’ll only see the English version everywhere as the translation keys do not match the translations.
{ "Welcome to our website, :Name": "Bienvenue sur notre site, :Name" }
Russian:
{ "Welcome to our website, :Name": "Добро пожаловать на наш сайт, :Name" }
Great job!
Pluralization
To see pluralization in action, let’s add a new paragraph of text. To perform pluralization, you have to use the
trans_choice function instead of
__(), for instance:
{{ __('Welcome to our website, :Name', ['name' => 'amanda']) }} <br> {{ trans_choice('There is one apple|There are many apples', 2) }}
As you can see, the plural forms are separated with a
|.
Now, what if we need more plural forms? This is possible as well:
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 24) }}
In this case, we allow the numbers
0,
1, from
2 to
19, and finally from
20 onwards. Of course, you can add as many rules as you need.
Next, what if we want placeholders in our plural forms? No problem with that either:
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 24, ['form' => 'is']) }}
We can also use count passed into `trans_choice`, if needed, by using a special
:count placeholder:
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 1, ['form' => 'is']) }}
Finally, don’t forget to update your translation files with all the changes we made to the base translation.
Russian:
{ "Welcome to our website, :Name": "Добро пожаловать на наш сайт, :Name", "{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples": "{0} Нет яблок|{1} Только :count яблоко|[2,19] :count яблок" }
{ "Welcome to our website, :Name": "Bienvenue sur notre site, :Name", "{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples": "{0} Il n'y a pas de pommes|{1} Il n'y :form :count pomme|[2,19] Il y :form :count pommes" }
Working with localized dates in Laravel
To localize dates, we will be leveraging the power of Carbon, which is shipped with Laravel by default. Take a look at the Carbon documentation; you can do lots of cool things with it. For instance, we could invent our own locale with rules for date and time localization.
For our simple example, we will display the current date localized for the selected language. In our
routes/web.php, let’s update the welcome page route and pass the localized date message over to our welcome view:
<?php Route::get('/', function () { $today = \Carbon\Carbon::now() ->settings( [ 'locale' => app()->getLocale(), ] ); // LL is macro placeholder for MMMM D, YYYY (you could write same as dddd, MMMM D, YYYY) $dateMessage = $today->isoFormat('dddd, LL'); return view('welcome', [ 'date_message' => $dateMessage ]); });
Let’s update
resources/views/welcome.blade.php and add our date message, like so:
{{ __('Welcome to our website, :Name', ['name' => 'amanda']) }} <br> {{ trans_choice('{0} There :form :count apples|{1} There :form just :count apple|[2,19] There :form :count apples', 1, ['form' => 'is']) }} <br> {{ $date_message }}
Try switching languages on the
localhost homepage — you’ll see that the dates are now localized, for example:
Formatting numbers and currencies with NumberFormatter
In different countries, people use different formats to represent numbers, for example:
- The United States → 123,123.12
- France → 123 123,12
Thus, to reflect these differences in your Laravel app, you could use NumberFormatter in the following way:
<?php $num = NumberFormatter::create('en_US', NumberFormatter::DECIMAL); $num2 = NumberFormatter::create('fr', NumberFormatter::DECIMAL);
You can even spell out the number in a particular language and display something like “one hundred twenty-three thousand one hundred twenty-three point one two”:
<?php $num = NumberFormatter::create('en_US', NumberFormatter::SPELLOUT); $num2 = NumberFormatter::create('fr', NumberFormatter::SPELLOUT);
On top of that, NumberFormatter enables you to localize currencies with ease, for example:
<?php $currency1 = NumberFormatter::create('fr', NumberFormatter::CURRENCY); $currency2 = NumberFormatter::create('en_US', NumberFormatter::CURRENCY);
So, for
fr you will see Euros, while for
en_US the currency will be US dollars.
Simplifying the translation process with Lokalise
The actual translation of all your text is probably the most time-consuming process of Laravel localization. However, finding a good translation management solution like Lokalise can rescue you from ending up with a lot of work on your hands. With Lokalise, the translation process can be carried out in just a few steps. Here are some basic guidelines on how to do it:
- Grab your free trial to continue.
- Next, install the Lokalise CLI. You can use it to create projects and upload and download translation files. Of course, there’s also a GUI available.
- Open the Lokalise website and proceed to the “API tokens” section on your personal profile page. Generate a new read/write token.
- Create a new translation project and set English as the base language.
- Open project settings and copy the project ID.
- Next, to upload your Laravel translation files to Lokalise, run:
lokalise2 file upload --token <token> --project-id <project_id> --lang_iso en --file PATH/TO/PROJECT/resources/lang/en.json.
- Return to the newly created Lokalise project. All your translation keys and values should be there. You can modify them as much as you like by editing, deleting, and adding new ones. You can filter the keys; for example, you can find the untranslated ones which is very convenient.
- When you are ready, download the edited translations back to Laravel by running:
lokalise2 file download --token <token> --project-id <project_id> --format json --dest PATH/TO/PROJECT/resources/lang.
Lokalise supports many platforms and formats. With its multiple features, you have the ability to order translations from professionals, upload screenshots in order to read text from them, and lots more. So, integrate your applications with Lokalise today and make your life a whole lot easier.
Conclusion
In this article, we have seen how to get started with Laravel localization. We’ve discussed how to perform translations, use placeholders, take advantage of pluralization, and how to add a language switcher. Hopefully, you found this article interesting and useful. Thank you for dropping by today and until the next time! | https://lokalise.com/blog/laravel-localization-step-by-step/ | CC-MAIN-2022-05 | refinedweb | 2,629 | 51.99 |
Provided by: manpages-dev_5.02-1_all
NAME
link, linkat - make a new name for a file
SYNOPSIS
#include <unistd.h> int link(const char *oldpath, const char *newpath); : _POSIX_C_SOURCE >= 200809L Before glibc 2.10: _ATFILE_SOURCE". required. POSIX.1-2001 says that link() should dereference oldpath if it is a symbolic link. However, since kernel 2.0,. POSIX.1-2008 changes the specification of link(), making it implementation-dependent whether or not oldpath is dereferenced if it is a symbolic link. For precise control over the treatment of symbolic links when creating a link, use link.02 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.ubuntu.com/manpages/eoan/man2/linkat.2.html | CC-MAIN-2021-43 | refinedweb | 122 | 59.3 |
50. Permanent Income II: LQ Techniques¶
Contents
In addition to what’s in Anaconda, this lecture will need the following libraries:
!conda install -y quantecon
Collecting package metadata (current_repodata.json): -
\
|
/
-
\
|
/
-
\
|
/
-
\
done Solving environment: /
-
\
|
/
-
\
|
/
-
\
|
/
-
\
|
/
-
\
|
/
-
\
done
# All requested packages already installed.
50.1. Overview¶
This lecture continues our analysis of the linear-quadratic (LQ) permanent income model of savings and consumption.
As we saw in our previous lecture on this topic, Robert Hall [Hal78] used the LQ permanent income model to restrict and interpret intertemporal comovements of nondurable consumption, nonfinancial income, and financial wealth.
For example, we saw how the model asserts that for any covariance stationary process for nonfinancial income
consumption is a random walk
financial wealth has a unit root and is cointegrated with consumption
Other applications use the same LQ framework.
For example, a model isomorphic to the LQ permanent income model has been used by Robert Barro [Bar79] to interpret intertemporal comovements of a government’s tax collections, its expenditures net of debt service, and its public debt.
This isomorphism means that in analyzing the LQ permanent income model, we are in effect also analyzing the Barro tax smoothing model.
It is just a matter of appropriately relabeling the variables in Hall’s model.
In this lecture, we’ll
show how the solution to the LQ permanent income model can be obtained using LQ control methods.
represent the model as a linear state space system as in this lecture.
apply QuantEcon’s LinearStateSpace class to characterize statistical features of the consumer’s optimal consumption and borrowing plans.
We’ll then use these characterizations to construct a simple model of cross-section wealth and consumption dynamics in the spirit of Truman Bewley [Bew86].
(Later we’ll study other Bewley models—see this lecture.)
The model will prove useful for illustrating concepts such as
stationarity
ergodicity
ensemble moments and cross-section observations
Let’s start with some imports:
%matplotlib inline import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (11, 5) #set default figure size import quantecon as qe import numpy as np import scipy.linalg as la
50.2. Setup¶
Let’s recall the basic features of the model discussed in the permanent income model.
Consumer preferences are ordered by
where \(u(c) = -(c - \gamma)^2\).
The consumer maximizes (50.1) by choosing a consumption, borrowing plan \(\{c_t, b_{t+1}\}_{t=0}^\infty\) subject to the sequence of budget constraints
and the no-Ponzi condition
The interpretation of all variables and parameters are the same as in the previous lecture.
We continue to assume that \((1 + r) \beta = 1\).
The dynamics of \(\{y_t\}\) again follow the linear state space model
The restrictions on the shock process and parameters are the same as in our previous lecture.
50.2.1. Digression on a Useful Isomorphism¶
The LQ permanent income model of consumption is mathematically isomorphic with a version of Barro’s [Bar79] model of tax smoothing.
In the LQ permanent income model
the household faces an exogenous process of nonfinancial income
the household wants to smooth consumption across states and time
In the Barro tax smoothing model
a government faces an exogenous sequence of government purchases (net of interest payments on its debt)
a government wants to smooth tax collections across states and time
If we set
\(T_t\), total tax collections in Barro’s model to consumption \(c_t\) in the LQ permanent income model.
\(G_t\), exogenous government expenditures in Barro’s model to nonfinancial income \(y_t\) in the permanent income model.
\(B_t\), government risk-free one-period assets falling due in Barro’s model to risk-free one-period consumer debt \(b_t\) falling due in the LQ permanent income model.
\(R\), the gross rate of return on risk-free one-period government debt in Barro’s model to the gross rate of return \(1+r\) on financial assets in the permanent income model of consumption.
then the two models are mathematically equivalent.
All characterizations of a \(\{c_t, y_t, b_t\}\) in the LQ permanent income model automatically apply to a \(\{T_t, G_t, B_t\}\) process in the Barro model of tax smoothing.
See consumption and tax smoothing models for further exploitation of an isomorphism between consumption and tax smoothing models.
50.2.2. A Specification of the Nonfinancial Income Process¶
For the purposes of this lecture, let’s assume \(\{y_t\}\) is a second-order univariate autoregressive process:
We can map this into the linear state space framework in (50.4), as discussed in our lecture on linear models.
To do so we take
50.3. The LQ Approach¶
Previously we solved the permanent income model by solving a system of linear expectational difference equations subject to two boundary conditions.
Here we solve the same model using LQ methods based on dynamic programming.
After confirming that answers produced by the two methods agree, we apply QuantEcon’s LinearStateSpace class to illustrate features of the model.
Why solve a model in two distinct ways?
Because by doing so we gather insights about the structure of the model.
Our earlier approach based on solving a system of expectational difference equations brought to the fore the role of the consumer’s expectations about future nonfinancial income.
On the other hand, formulating the model in terms of an LQ dynamic programming problem reminds us that
finding the state (of a dynamic programming problem) is an art, and
iterations on a Bellman equation implicitly jointly solve both a forecasting problem and a control problem
50.3.1. The LQ Problem¶
Recall from our lecture on LQ theory that the optimal linear regulator problem is to choose a decision rule for \(u_t\) to minimize
subject to \(x_0\) given and the law of motion
where \(w_{t+1}\) is IID with mean vector zero and \(\mathbb E w_t w'_t= I\).
The tildes in \(\tilde A, \tilde B, \tilde C\) are to avoid clashing with notation in (50.4).
The value function for this problem is \(v(x) = - x'Px - d\), where
\(P\) is the unique positive semidefinite solution of the corresponding matrix Riccati equation.
The scalar \(d\) is given by \(d=\beta (1-\beta)^{-1} {\rm trace} ( P \tilde C \tilde C')\).
The optimal policy is \(u_t = -Fx_t\), where \(F := \beta (Q+\beta \tilde B'P \tilde B)^{-1} \tilde B'P \tilde A\).
Under an optimal decision rule \(F\), the state vector \(x_t\) evolves according to \(x_{t+1} = (\tilde A-\tilde BF) x_t + \tilde C w_{t+1}\).
50.3.2. Mapping into the LQ Framework¶
To map into the LQ framework, we’ll use
as the state vector and \(u_t := c_t - \gamma\) as the control.
With this notation and \(U_\gamma := \begin{bmatrix} \gamma & 0 & 0 \end{bmatrix}\), we can write the state dynamics as in (50.5) when
Please confirm for yourself that, with these definitions, the LQ dynamics (50.5) match the dynamics of \(z_t\) and \(b_t\) described above.
To map utility into the quadratic form \(x_t' R x_t + u_t'Q u_t\) we can set
\(Q := 1\) (remember that we are minimizing) and
\(R :=\) a \(4 \times 4\) matrix of zeros
However, there is one problem remaining.
We have no direct way to capture the non-recursive restriction (50.3) on the debt sequence \(\{b_t\}\) from within the LQ framework.
To try to enforce it, we’re going to use a trick: put a small penalty on \(b_t^2\) in the criterion function.
In the present setting, this means adding a small entry \(\epsilon > 0\) in the \((4,4)\) position of \(R\).
That will induce a (hopefully) small approximation error in the decision rule.
We’ll check whether it really is small numerically soon.
50.4. Implementation¶
Let’s write some code to solve the model.
One comment before we start is that the bliss level of consumption \(\gamma\) in the utility function has no effect on the optimal decision rule.
We saw this in the previous lecture permanent income.
The reason is that it drops out of the Euler equation for consumption.
In what follows we set it equal to unity.
50.4.1. The Exogenous Nonfinancial Income Process¶
First, we create the objects for the optimal linear regulator
# Set parameters α, β, ρ1, ρ2, σ = 10.0, 0.95, 0.9, 0.0, 1.0 R = 1 / β A = np.array([[1., 0., 0.], [α, ρ1, ρ2], [0., 1., 0.]]) C = np.array([[0.], [σ], [0.]]) G = np.array([[0., 1., 0.]]) # Form LinearStateSpace system and pull off steady state moments μ_z0 = np.array([[1.0], [0.0], [0.0]]) Σ_z0 = np.zeros((3, 3)) Lz = qe.LinearStateSpace(A, C, G, mu_0=μ_z0, Sigma_0=Σ_z0) μ_z, μ_y, Σ_z, Σ_y, Σ_yx = Lz.stationary_distributions() # Mean vector of state for the savings problem mxo = np.vstack([μ_z, 0.0]) # Create stationary covariance matrix of x -- start everyone off at b=0 a1 = np.zeros((3, 1)) aa = np.hstack([Σ_z,
The next step is to create the matrices for the LQ., σ, 0., 0.]).reshape(4,1) β_LQ = β
Let’s print these out and have a look at them
print(f"A = \n {ALQ}") print(f"B = \n {BLQ}") print(f"R = \n {RLQ}") print(f"Q = \n {QLQ}")
A = [[ 1. 0. 0. 0. ] [10. 0.9 0. 0. ] [ 0. 1. 0. 0. ] [ 0. -1.05263158 0. 1.05263158]] B = [[0. ] [0. ] [0. ] [1.05263158]] R = [[0.e+00 0.e+00 0.e+00 0.e+00] [0.e+00 0.e+00 0.e+00 0.e+00] [0.e+00 0.e+00 0.e+00 0.e+00] [0.e+00 0.e+00 0.e+00 1.e-09]] Q = [1.]
Now create the appropriate instance of an LQ model
lqpi = qe.LQ(QLQ, RLQ, ALQ, BLQ, C=CLQ, beta=β_LQ)
We’ll save the implied optimal policy function soon compare them with what we get by employing an alternative solution method
P, F, d = lqpi.stationary_values() # Compute value function and decision rule ABF = ALQ - BLQ @ F # Form closed loop system
50.4.2. Comparison with the Difference Equation Approach¶
In our first lecture on the infinite horizon permanent income problem we used a different solution method.
The method was based around
deducing the Euler equations that are the first-order conditions with respect to consumption and savings.
using the budget constraints and boundary condition to complete a system of expectational linear difference equations.
solving those equations to obtain the solution.
Expressed in state space notation, the solution took the form
Now we’ll apply the formulas in this system
# Use the above formulas to create the optimal policies for b_{t+1} and c_t b_pol = G @ la.inv(np.eye(3, 3) - β * A) @ (A - np.eye(3, 3)) c_pol = (1 - β) * G @ la.inv(np.eye(3, 3) - β * - β)]) G_LSS = np.hstack([G_LSS1, G_LSS2]) # Use the following values to start everyone off at b=0, initial incomes zero μ_0 = np.array([1., 0., 0., 0.]) Σ_0 = np.zeros((4, 4))
A_LSS calculated as we have here should equal
ABF calculated above using the LQ model
ABF - A_LSS
array([[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [-9.51248175e-06, 9.51247915e-08, 0.00000000e+00, -1.99999923e-08]])
Now compare pertinent elements of
c_pol and
F
print(c_pol, "\n", -F)
[[65.51724138 0.34482759 0. ]] [[ 6.55172323e+01 3.44827677e-01 -0.00000000e+00 -5.00000190e-02]]
We have verified that the two methods give the same solution.
Now let’s create instances of the LinearStateSpace class and use it to do some interesting experiments.
To do this, we’ll use the outcomes from our second method.
50.5. Two Example Economies¶
In the spirit of Bewley models [Bew86], we’ll generate panels of consumers.
The examples differ only in the initial states with which we endow the consumers.
All other parameter values are kept the same in the two examples
In the first example, all consumers begin with zero nonfinancial income and zero debt.
The consumers are thus ex-ante identical.
In the second example, while all begin with zero debt, we draw their initial income levels from the invariant distribution of financial income.
Consumers are ex-ante heterogeneous.
In the first example, consumers’ nonfinancial income paths display pronounced transients early in the sample
these will affect outcomes in striking ways
Those transient effects will not be present in the second example.
We use methods affiliated with the LinearStateSpace class to simulate the model.
50.5.1. First Set of Initial Conditions¶
We generate 25 paths of the exogenous non-financial income process and the associated optimal consumption and debt paths.
In the first set of graphs, darker lines depict a particular sample path, while the lighter lines describe 24 other paths.
A second graph plots a collection of simulations against the population distribution that we extract from the
LinearStateSpace instance
LSS.
Comparing sample paths with population distributions at each date \(t\) is a useful exercise—see our discussion of the laws of large numbers
lss = qe.LinearStateSpace(A_LSS, C_LSS, G_LSS, mu_0=μ_0, Sigma_0=Σ_0)
50.5.2. Population and Sample Panels¶, μ_0, Σ_0, T=150, npaths=25): """ This function takes initial conditions (μ_0, Σ_0) and uses the LinearStateSpace class from QuantEcon to simulate an economy npaths times for T periods. It then uses that information to generate some graphs related to the discussion below. """ lss = qe.LinearStateSpace(A, C, G, mu_0=μ_0, Sigma_0=Σ_0) #): μ_x, μ_y, Σ_x, Σ_y = next(moment_generator) cons_mean[t], cons_var[t] = μ_y[1], Σ_y[1, 1] debt_mean[t], debt_var[t] = μ_x[3], Σ_x[3, 3] return bsim, csim, ysim, cons_mean, cons_var, debt_mean, debt_var def consumption_income_debt_figure(bsim, csim, ysim): # Get T T = bsim.shape[1] # Create the(title="Nonfinancial Income, Consumption, and Debt", xlabel="t", ylabel="y and c") # Plot debt ax[1].plot(bsim[0, :], label="b", color="r") ax[1].plot(bsim.T, alpha=.1, color="r") ax[1].legend(loc=4) ax[1].set(xlabel="t", ylabel="debt") fig.tight_layout(), ax = plt.subplots(2, 1, figsize=(10, 8)) xvals = np.arange(T) # Consumption fan ax[0].plot(xvals, cons_mean, color="k") ax[0].plot(csim.T, color="k", alpha=.25) ax[0].fill_between(xvals, c_perc_95m, c_perc_95p, alpha=.25, color="b") ax[0].fill_between(xvals, c_perc_90m, c_perc_90p, alpha=.25, color="r") ax[0].set(title="Consumption/Debt over time", ylim=(cmean-15, cmean+15), ylabel="consumption") # Debt fan ax[1].plot(xvals, debt_mean, color="k") ax[1].plot(bsim.T, color="k", alpha=.25) ax[1].fill_between(xvals, d_perc_95m, d_perc_95p, alpha=.25, color="b") ax[1].fill_between(xvals, d_perc_90m, d_perc_90p, alpha=.25, color="r") ax[1].set(xlabel="t", ylabel="debt") fig.tight_layout() return fig
Now let’s create figures with initial conditions of zero for \(y_0\) and \(b_0\)
out = income_consumption_debt_series(A_LSS, C_LSS, G_LSS, μ_0, Σ_0) bsim0, csim0, ysim0 = out[:3] cons_mean0, cons_var0, debt_mean0, debt_var0 = out[3:] consumption_income_debt_figure(bsim0, csim0, ysim0) plt.show()
consumption_debt_fanchart(csim0, cons_mean0, cons_var0, bsim0, debt_mean0, debt_var0) plt.show()
Here is what is going on in the above graphs.
For our simulation, we have set initial conditions \(b_0 = y_{-1} = y_{-2} = 0\).
Because \(y_{-1} = y_{-2} = 0\), nonfinancial income \(y_t\) starts far below its stationary mean \(\mu_{y, \infty}\) and rises early in each simulation.
Recall from the previous lecture that we can represent the optimal decision rule for consumption in terms of the co-integrating relationship
So at time \(0\) we have
This tells us that consumption starts at the income that would be paid by an annuity whose value equals the expected discounted value of nonfinancial income at time \(t=0\).
To support that level of consumption, the consumer borrows a lot early and consequently builds up substantial debt.
In fact, he or she incurs so much debt that eventually, in the stochastic steady state, he consumes less each period than his nonfinancial income.
He uses the gap between consumption and nonfinancial income mostly to service the interest payments due on his debt.
Thus, when we look at the panel of debt in the accompanying graph, we see that this is a group of ex-ante identical people each of whom starts with zero debt.
All of them accumulate debt in anticipation of rising nonfinancial income.
They expect their nonfinancial income to rise toward the invariant distribution of income, a consequence of our having started them at \(y_{-1} = y_{-2} = 0\).
50.5.2.1. Cointegration Residual¶
The following figure plots realizations of the left side of (50.6), which, as discussed in our last lecture, is called the cointegrating residual.
As mentioned above, the right side can be thought of as altering initial conditions, we shall remove this transient in our second example to be presented below
def cointegration_figure(bsim, csim): """ Plots the cointegration """ # Create figure fig, ax = plt.subplots(figsize=(10, 8)) ax.plot((1 - β) * bsim[0, :] + csim[0, :], color="k") ax.plot((1 - β) * bsim.T + csim.T, color="k", alpha=.1) ax.set(title="Cointegration of Assets and Consumption", xlabel="t") return fig
cointegration_figure(bsim0, csim0) plt.show()
50.5.3. A “Borrowers and Lenders” Closed Economy¶
When we set \(y_{-1} = y_{-2} = 0\) and \(b_0 =0\) in the preceding exercise, we make debt “head north” early in the sample.
Average debt in the cross-section rises and approaches the asymptote.
We can regard these as outcomes of a “small open economy” that borrows from abroad at the fixed gross interest rate \(R = r [Bew86] model” in the following way
as before, we start everyone at \(b_0 = 0\).
But instead of starting everyone at \(y_{-1} = y_{-2} = 0\), we draw \(\begin{bmatrix} y_{-1} \\ y_{-2} \end{bmatrix}\) from the invariant distribution of the \(\{y_t\}\) process.
This rigs a closed economy in which people are borrowing and lending with each other at a gross risk-free interest rate of \(R = \beta^{-1}\).
Across the group of people being analyzed, risk-free loans are in zero excess supply.
We have arranged primitives so that \(R = \beta^{-1}\) clears the market for risk-free loans at zero aggregate excess supply.
So the risk-free loans are being made from one person to another within our closed set of agents.
There is no need for foreigners to lend to our group.
Let’s have a look at the corresponding figures
out = income_consumption_debt_series(A_LSS, C_LSS, G_LSS, mxbewley, sxbewley) bsimb, csimb, ysimb = out[:3] cons_meanb, cons_varb, debt_meanb, debt_varb = out[3:] consumption_income_debt_figure(bsimb, csimb, ysimb) plt.show()
consumption_debt_fanchart(csimb, cons_meanb, cons_varb, bsimb, debt_meanb, debt_varb) plt.show()
The graphs confirm the following outcomes:
As before, the consumption distribution spreads out over time.
But now there is some initial dispersion because there is ex-ante heterogeneity in the initial draws of \(\begin{bmatrix} y_{-1} \\ y_{-2} \end{bmatrix}\).
As before, the cross-section distribution of debt spreads out over time.
Unlike before, the average level of debt stays at zero, confirming that this is a closed borrower-and-lender economy.
Now the cointegrating residual seems stationary, and not just asymptotically stationary.
Let’s have a look at the cointegration figure
cointegration_figure(bsimb, csimb) plt.show()
| https://python.quantecon.org/perm_income_cons.html | CC-MAIN-2021-49 | refinedweb | 3,203 | 55.03 |
See just the courses with free lessons.
You may also like to see the reverse-chronological list.
Learn these three tools -- map, filter, and reduce-- and you'll be well on your way to developing a functional mindset.
I get a lot of questions from people trying to learn Clojure. Sometimes, the best way to answer them is with a video. This course is for all of those questions that don't really fit anywhere else.
What mysteries do Clojure macros hold? This course jumps right into macros with gusto. It starts with the key to understanding macros, takes you through the implementation of 6 progressively more complex macros, and finishes with the three reasons you need macros.
How do I build reusable components? How do I choose component-local state vs application state?
Ever been completely baffled by Wikipedia articles on Monads and Functors? Are you curious about what everybody is raving about, but can't find any good ways to learn it? It turns out that many of the ideas of category theory come almost directly from the real world. Wouldn't you like to understand how those concepts relate to the real world?
Clojure is based on collections, but how are they used? What are some patterns for making the most of them? This course introduces you to the workhorses of the Clojure programming language, the immutable collections..
You've probably mastered the basic concurrency primitives in Clojure. You know just when you need an Atom, how to do transactional updates with Refs, and can do some interesting tricks with Agents. Are you ready to go to the next level? core.async is that..
Protocols are a very cool and very important feature in Clojure. They are a great way to build polymorphism into your software, including extending existing Java classes without modifying them.
What does it take to build an entire web app from scratch? This course is a longer one. It starts from a barebones project and gradually develops into a complete web app with REST API.
You.
Clojure core.async provides basic building blocks for communication and coordination. This course explores ten patterns you can easily implement using those building blocks.
With so many data formats out there, it's good to see some example code for reading and writing different formats. I'm talking JSON, CSV, EDN, and more. This course explores how to read and write data formats using Clojure.
People talk a lot about using data to model things in Clojure. But how do you do that? This 9-part series explores many different ways to model systems in Clojure, including with various literal data structures, closures, and records. This is a serious exploration with tradeoffs discussed. Your math teacher would be proud: all work is shown so you see how everything is related.
Ever.
Emacs is definitely the most popular Clojure editor. But it's kind of hard to know where to get started with it. This course aims to introduce you to Emacs as a general editor and for use with Clojure.
Chances are you will need to access an API on the web without a custom API client. You'll have to make the web requests yourself. You want something reliable, fast, and with all the features. In Clojure, that is clj-http..
If you already work at a large company, you may want to find ways to introduce Clojure to your work. This guide presents 5 steps for bringing Clojure into your job.
What..
Leiningen is the de facto standard project tool in Clojure. This course gives an overview of
lein commands, projects, templates, and dependencies.
Manipulating time is a difficult thing. Time was made for people. The rules are complicated and depend on where you are on Earth. Time units have varying lengths (how long is "one month"?; how long is a day when you change daylight savings?), daylight savings depends on the country you're in, and formatting dates depends on the language. It's complicated. Luckily, Joda Time does an excellent job. Joda Time is a date-time library that represents everything immutably. It's what people use when they want robust date-time calculations. clj-time wraps up the types from Joda Time and makes it easy to use from Clojure.
What's with all the namespace directives? How do I refer to Java classes? Can you not include stuff from clojure.core? Clojure namespaces are powerful but complex. This course is all about how to use them effectively.
How do we optimize our Clojure code?
What is recursion? How do you write recursive functions? Does it work with laziness? How is it different from a
for loop? All of these questions are answered, and more, using simple, clear examples. You'll never have fear of recursion again.
Why is everyone always talking about reduce? Reduce is actually really cool. It's the bee's knees, you might say. And it's also a universal recursion. With it you can implement lots of other recursive functions. This mini-course also goes over some of the more practical stuff you can do with reduce.
In this course, we develop the frontend of an app to help a scientist record her experiment notes. It's a lab notebook. The app is completely client-side. It uses ClojureScript and Om.
Web development in Clojure is just like everything else: you build up complex behavior from simple parts. This course builds a TODO list app from scratch, explaining the important concepts, and deploying it to a cloud service. | https://purelyfunctional.tv/courses/ | CC-MAIN-2017-39 | refinedweb | 931 | 68.77 |
Red Hat Bugzilla – Bug 509932
cost excludes are much slower in yum 3.2.23 than 3.2.21
Last modified: 2014-01-21 18:10:16 EST
+++ This bug was initially created as a clone of Bug #508445 +++
yum 3.2.23 on F10 is a lot slower than 3.2.21.
A simple "yum -C list updates" takes 90 seconds instead of 3 seconds,
if two repositories with the same rpms and different cost are enabled
(typical scenario for local mirroring of updates).
The problem appears to be that the code managing the exclusion of
rpm packages from the expensive repo, which loops on the rpms
and deletes them very inefficiently.
"excluding for cost:" lines are printed quite slowly (option -d 5).
Suspects on this code: (is this O(N^2) ?)
for pkg in pkgs[1:]:
if pkg.repo.cost > lowcost:
msg = _('excluding for cost: %s from %s') % (pkg, pkg.repo.id)
self.verbose_logger.log(logginglevels.DEBUG_3, msg)
pkg.repo.sack.delPackage(pkg)
Also see
(reproduced by another user with similar conf).
--- Additional comment from james.antill@redhat.com on 2009-07-03 10:57:45 EDT ---
Can you see what happens if you undo this patch (ie. just delete the function starting at line 284):
diff --git a/yum/yumRepo.py b/yum/yumRepo.py
index afd0877..964f19d 100644
--- a/yum/yumRepo.py
+++ b/yum/yumRepo.py
@@ -281,6 +281,19 @@ class YumRepository(Repository, config.RepoConf):
self._grabfunc = None
self._grab = None
+ def __cmp__(self, other):
+ """ Sort yum repos. by cost, and then by alphanumeric on their id. """
+ if other is None:
+ return 1
+ if hasattr(other, 'cost'):
+ ocost = other.cost
+ else:
+ ocost = 1000
+ ret = cmp(self.cost, ocost)
+ if ret:
+ return 1
+ return cmp(self.id, other.id)
+
def _getSack(self):
# FIXME: Note that having the repo hold the sack, which holds "repos"
--- Additional comment from bugzillaredhat-56f0@robertoragusa.it on 2009-07-05 05:17:58 EDT ---
It didn't help.
Successive run were as slow as before the change (90 seconds).
Much better results if I remove this line
self.costExcludePackages()
from __init__.py; it now runs in 7 seconds.
If I undestand correctly, it is now discarding duplicates
in the list of to-be-updated packages, instead of the list
of all packages; so it is faster. A better fix is certainly
possible, I suppose.
--- Additional comment from james.antill@redhat.com on 2009-07-06 14:16:56 EDT ---
Ok, I've confirmed it and I have a patch that "fixes" it:
Author: James Antill <james@and.org>
Date: Mon Jul 6 14:11:58 2009 -0400
Fix speed regression in costExcludes
diff --git a/yum/__init__.py b/yum/__init__.py
index 2f9723b..268baaf 100644
--- a/yum/__init__.py
+++ b/yum/__init__.py
@@ -1120,6 +1120,7 @@ class YumBase(depsolve.Depsolve):
pkgdict[po.pkgtup] = []
pkgdict[po.pkgtup].append(po)
+ verb = self.verbose_logger.isEnabledFor(logginglevels.DEBUG_3)
for pkgs in pkgdict.values():
if len(pkgs) == 1:
continue
@@ -1129,8 +1130,10 @@ class YumBase(depsolve.Depsolve):
#print '%s : %s : %s' % (pkgs[0], pkgs[0].repo, pkgs[0].repo.cost)
for pkg in pkgs[1:]:
if pkg.repo.cost > lowcost:
- msg = _('excluding for cost: %s from %s') % (pkg, pkg.repo.
- self.verbose_logger.log(logginglevels.DEBUG_3, msg)
+ if verb:
+ msg = _('excluding for cost: %s from %s') %(pkg,
+ pkg.repo.id
+ self.verbose_logger.log(logginglevels.DEBUG_3, msg)
pkg.repo.sack.delPackage(pkg)
...the big question is how/why this fixes it ... and what changed between 3.2.21 and 3.2.22 that makes the above much slower.
--- Additional comment from james.antill@redhat.com on 2009-07-06 14:20:41 EDT ---
My data for this was to use a RHEL-5 box and have multiple EPEL repos. named et1, et2, et3, et4 with different costs. The above patch (for 13,132 delPackage() calls) takes costExcludes() time from 243.10 seconds to 7.25 seconds (which is the same as 3.2.19-18).
--- Additional comment from bugzillaredhat-56f0@robertoragusa.it on 2009-07-06 15:49:12 EDT ---
Interesting.
I confirm that your fix works here.
I tried other variations of the two logging lines (without your patch).
This one is fast (7s):
msg = _('excluding for cost: %s from %s') % (pkg.repo.id,pkg.repo.id)
self.verbose_logger.log(logginglevels.DEBUG_3, msg)
This one is slow (101s):
msg = _('excluding for cost: %s from %s') % (pkg,pkg.repo.id)
self.verbose_logger.log(logginglevels.DEBUG_3, msg)
This one is slower (189s):
msg = _('excluding for cost: %s from %s') % (pkg,pkg)
self.verbose_logger.log(logginglevels.DEBUG_3, msg)
The slow down happens when the %s is expanded to pkg.
Ok, we've found root cause:;a=commitdiff;h=1f45838e29ba26dac22215dd9c918fb920569fef
Release note added. If any revisions are required, please set the
"requires_release_notes" flag to "?" and edit the "Release Notes" field accordingly.
All revisions will be proofread by the Engineering Content Services team.
New Contents:
A recent version of yum was substantially slower than previous versions when calculating cost excludes. The slowdown was caused by variable that expanded to unicode encoding rather than str. The calculation no longer uses unicode, which returns yum to its previous higher. | https://bugzilla.redhat.com/show_bug.cgi?id=509932 | CC-MAIN-2016-30 | refinedweb | 862 | 62.04 |
Localizing a Silverlight application is a pretty trivial task if you use resources. Once you create a resource file you are working with, you can use the code-behind class in XAML and bind to properties from that class that contain localized strings. First, import the namespace that is used for resx file, typically ApplicationResources
xmlns:Localized="clr-namespace:MyApplication.Resources"
Then add an instance of a specific resx code-behind class to resources in your user control
<UserControl.Resources>
<Localized:SpecificFile x:
In this case SpecificFile corresponds to SpecificFile.resx. Now that this is done, you can bind labels to it
<TextBlock Text="{Binding Path=MyPropertyFromResourceFile}/>
There is one issue though, if you edit resource file again in resources editor, and save it, the constructor scope in code behind is set to internal. This in turn will cause an exception (AG_E_PARSER_UNKNOWN_TYPE ) when you try to load this user control. All you have to do to fix it is edit code behind file for you resource file and change its constructor to public. Unfortunately, you have to do it every time you edit the file in resources editor. | http://www.dotnetspeak.com/silverlight/working-with-resources-in-silverlight/ | CC-MAIN-2022-40 | refinedweb | 188 | 51.58 |
This site uses strictly necessary cookies. More Information
I am trying to send a video file from the server to the client in unity with the help of message (1440 bytes at max I can send). Depending on the message from the unity client I am rendering the texture and after encoding I am sending video bytes to the unity client. Then from unity client, I am storing those bytes that in a file but I have seen I can't open that video file from the client. Can you please tell me what may be the reasons behind this?
This is my message from server.
public class RegisterHostMessages : MessageBase //outgoing message from server
{
public byte[] video;
public int size;
}
Sending the message by the channel using,
NetworkServer.SendByChannelToAll(123, msg, channel.
Continuosly Sending high amount of data over LAN problem
0
Answers
Handheld.PlayFullScreenMovie memory leak?
1
Answer
Switching Videoclips for VideoPlayer in Unity degrades FPS drastically
0
Answers
How do I sync a videoplayer on multiplayer?
0
Answers
videos stopped working in RAW image
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/1463536/reconstructing-video-bytes-from-the-unity-client-s.html | CC-MAIN-2021-39 | refinedweb | 181 | 65.01 |
TSHttpConnectWithPluginId¶
Allows the plugin to initiate an http connection. This will tag the HTTP state machine with extra data that can be accessed by the logging interface. The connection is treated as an HTTP transaction as if it came from a client.
Synopsis¶
#include <ts/ts.h>
Description¶
This call attempts to create an HTTP state machine and a virtual
connection to that state machine. This is more efficient than using
TSNetConnect() because it avoids using the operating system
stack via the loopback interface.
- addr
This is the network address of the target of the connection. This includes the port which should be stored in the
sockaddrstructure pointed at by addr.
- tag
This is a tag that is passed through to the HTTP state machine. It must be a persistent string that has a lifetime longer than the connection. It is accessible via the log field pitag. This is intended as a class or type identifier that is consistent across all connections for this plugin. In effect, the name of the plugin. This can be
NULL.
- id
This is a numeric identifier that is passed through to the HTTP state machine. It is accessible via the log field piid. This is intended as a connection identifier and should be distinct for every call to
TSHttpConnectWithPluginId(). The easiest mechanism is to define a plugin global value and increment it for each connection. The value
0is reserved to mean “not set” and can be used as a default if this functionality is not needed.
The virtual connection returned as the
TSVConn is API
equivalent to a network virtual connection both to the plugin and
to internal mechanisms. Data is read and written to the connection
(and thence to the target system) by reading and writing on this
virtual connection.
Note
This function only opens the connection. To drive the transaction an actual HTTP request must be sent and the HTTP response handled. The transaction is handled as a standard HTTP transaction and all of the standard configuration options and plugins will operate on it.
The combination of tag and id is intended to enable correlation in log post processing. The tag identifies the connection as related to the plugin and the id can be used in conjunction with plugin generated logs to correlate the log records.
Notes¶
The H2 implementation uses this to correlate client sessions
with H2 streams. Each client connection is assigned a distinct
numeric identifier. This is passed as the id to
TSHttpConnectWithPluginId(). The tag is selected
to be the NPN string for the client session protocol, e.g.
“h2”. Log post processing can then count the number of connections for the
various supported protocols and the number of H2 virtual streams for each
real client connection to Traffic Server. | https://docs.trafficserver.apache.org/en/latest/developer-guide/api/functions/TSHttpConnectWithPluginId.en.html | CC-MAIN-2020-40 | refinedweb | 461 | 56.45 |
STP/EID Component/ExtensionPoints
Contents
Extension points
These are the extension points defined by the org.eclipse.stp.eid plugin.
Runtime Extension Point
For each runtime that supports EIPs, there is an extension:
<eipRuntime name="nnnn" version="x.y.z" id="reference"> <ns prefix="xxxx" uri="uri:asdf" /> * multiples </eipRuntime>
If someone defines two extensions with the same name and version, then the namespaces are *added* to the ones that are already registered. If the namespaces are duplicated, they are ignored. If the prefixes are duplicated, but the uris are different, the most recent prefix gets a number appended to it to prevent explosions.
Other extensions will use the id of the runtime to refer to it.
Coordinator Extension Point
A runtime can be associated with multiple coordinators - these guys are responsible for constructing the folder structure and the various resources needed before configuration starts. They kick off and coordinate the configuration too, and then they finalize the project, do cleanups etc.
The reason why this is a separate extension point is to allow variety in how you structure your projects for a runtime. So if you use maven for example you could have a CamelMavenCoordinator that sets up the project appropriately, or you could have a CamelAntCoordinator that sets it up for an ant build.
<eipCoordinator id="..." class="...ICoordinator..."> <runtime id="..." /> <runtime name="..." version="..."/> </eipCoordinator>
The action that comes down from the UI should have the runtime and the coordinator details in it. The runtime gets picked (somehow) and then the coordinator is set by the menu choice or thru preferences or something like that. Preferences might be a good place for defaults.
Component Extension Point
There's a whole slew of EIPs, and these are called components for now. People should be able to add their own, and extend the capabilities of the system. So we need an extension for EIPs too.
<eipComponent model="...resource..." -> the model file -> category for the palette <description> All about this component </description> </eipComponent>
There's nothing here that says a particular component needs to be tied to a particular runtime, it's really just a model definition with some graphical bits and a name for human consumption. This takes the graphic stuff out of the existing model, which is a good idea.
Generator Extension Point
The piece that's missing is the bit which says "here's how you generate the configuration for this component when you are using this runtime with this particular version". This is the generator extension. Right now we are going to use JET2 and that's all there is to it.
<eipGenerator class="...IGenerator..."> <runtime name="..." version="..."> <component name="..." /> <component name="..." /> * </runtime> <runtime id="..."> <component name="..." /> <component id="..." /> * </runtime> </eipGenerator>
Proposed Extension Points
These ones are proposed. It's not decided yet whether or not it is a good idea to include them! Let us know via a bugzilla entry if you would like them to be put in place.
Repository Extension Point
There a fifth extension, and this is a bit speculative at the moment. There's this idea of a directory-based cache for the components, where everything is copied to and then they are parsed and loaded up. This serves a repository for new stuff that a user can put in too, so you can extend the component capabilities without having to create a plugin. I think that this capability is not fully baked in the current code, and while it's a nice idea, there's some work to put together a real strong implementation.
In any case, this is a candidate for this fifth extension - a way to share components between integration designer people.
<eipRepository provider="...IComponentRepository..." name="..." id="..."> <description>xxxx</description> </eipRepository> | http://wiki.eclipse.org/STP/EID_Component/ExtensionPoints | CC-MAIN-2014-52 | refinedweb | 621 | 51.48 |
in reply to Re: Our documentation sucksin thread Our documentation sucks
No amount or quality of documentation will fix the line of thinking that, for example, "It's a good idea to print HTTP or CGI headers directly, even if they're likely malformed and incorrect, because CGI.pm must be big and bloated and slow."
I disagree. Here, how do I print out an HTML header? Easy!
print "Content-type:text/html\n\n";
[download]
"It doesn't work,", you say? "Baloney," I reply. It works just fine for me. Why should I go learn some module and download and import it just to duplicate what I did in one line? Especially when I need to root through the docs. It doesn't affect you, it's not your code, and it works just fine. Why do I need a module?
Now, I'm playing devil's advocate. I use CGI.pm, don't get me wrong, but I don't remember how to print out a header without looking it up. I use it buried deep inside a black box so I never actually see the call to the header routine.
A quick glance at the docs yields a pretty decent section -
print header;
-or-
print header('image/gif');
-or-
print header('text/html','204 No response');
-or-
print header(-type=>'image/gif',
-nph=>1,
-status=>'402 Payment required',
-expires=>'+3d',
-cookie=>$cookie,
-charset=>'utf-7',
-attachment=>'foo.gif',
-Cost=>'$2.00');
[download]
Good docs, props to Lincoln. But, to the new user, it doesn't work. If I go back to my code and type in:
use CGI;
print header;
[download]
Nothing happens. Yes, yes, strict tells me about the bareword, and maybe I know enough to try guess to import the header function into my namespace (use CGI qw(header)) to make it work, but maybe I don't. A quick grep in CGI's docs found that "CREATING A STANDARD HTTP HEADER:", but it didn't explicitly tell me to import the function.
The case can be made that it's just being lazy ("Go read all the documentation!"), but it's still a barrier to entry. One line to print it out by myself or round trips to the docs to find out how to do it, then to find out that I need to import another function. Maybe I should've just looked at the synopsis and tried importing :standard, but maybe I didn't know that. If the example block started off with "use CGI qw/:standard/", I would've been going immediately, and arguably be happier to use the module.
When I finally get it working, I see that my output is:
Content-Type: text/html; charset=ISO-8859-1
[download]
I could've just printed that out myself, right? Why wasn't I told to just add on the charset=ISO-8859-1 bit to my manual print line? Instead I was sent to a new module to read documentation in multiple places to get something that I see no benefit in?
Yes, this example's quite contrived since it's so simple.
But I stand by my premise - if the docs have quick, easy to find, complete, and correct examples, people are going to be more likely to use 'em. Point them in the right direction for the module, and they can get up and running immediately instead of trying to learn something additional.
And before people start claiming I'm against learning modules, I'm not. I just want people to get up and running with a module in the minimal case as fast as they can. Then they can learn additional features once they've solved the immediate problem at hand.
That's odd. When I wrote my first CGI script using CGI I copy and pasted the synopsis sample, edited it a little and it worked straight off. It may be because the first couple of "interesting" lines in the sample are:
use CGI qw/:standard/;
print header,
[download]
which, without reading the comprehensive documentation, DWIM. Hey, maybe some of this CPAN documentation isn't so bad after all. ;). | http://www.perlmonks.org/?node_id=609786 | CC-MAIN-2017-47 | refinedweb | 693 | 71.14 |
Created on 2020-02-16 13:41 by blueyed, last changed 2020-02-24 04:53 by gvanrossum. This issue is now closed.
It does:
```
if '__args__' in frame.f_locals:
args = frame.f_locals['__args__']
else:
args = None
if args:
s += reprlib.repr(args)
else:
s += '()'
```
However that appears to be wrong/unnecessary since the following likely, but
maybe also others:
commit 75bb54c3d8
Author: Guido van Rossum <guido@python.org>
Date: Mon Sep 28 15:33:38 1998 +0000
Don't set a local variable named __args__; this feature no longer
works and Greg Ward just reported a problem it caused...
diff --git a/Lib/bdb.py b/Lib/bdb.py
index 3ca25adbbf..f2cf4caa36 100644
--- a/Lib/bdb.py
+++ b/Lib/bdb.py
@@ -46,7 +46,7 @@ def dispatch_line(self, frame):
return self.trace_dispatch
def dispatch_call(self, frame, arg):
- frame.f_locals['__args__'] = arg
+ # XXX 'arg' is no longer used
if self.botframe is None:
# First call of dispatch since reset()
self.botframe = frame
Code ref:.
So it should either get removed, or likely be replaced with actually displaying
the args.
For this the part could be factored out of `do_args` maybe, adjusting it for
handling non-current frames.
Of course somebody might inject/set `__args__` still (I've thought about doing that initially for pdb++, but will rather re-implement/override `format_stack_entry` instead), so support for this could be kept additionally.
That seems to be a correct observation. @blueyed, do you want to submit a PR to gt rid of the redundant check?
Sure:
New changeset 4015d1cda3cdba869103779eb6ff32ad798ff885 by Daniel Hahler in branch 'master':
bpo-39649: Remove obsolete check for `__args__` in bdb.Bdb.format_stack_entry (GH-18531)
New changeset 097612a3f711f5a6a3aec207cad78a35eb3a756d by Miss Islington (bot) in branch '3.7':
bpo-39649: Remove obsolete check for `__args__` in bdb.Bdb.format_stack_entry (GH-18531)
New changeset c97fc564a6c76ba5287f1b16bc841a1765820b0c by Miss Islington (bot) in branch '3.8':
bpo-39649: Remove obsolete check for `__args__` in bdb.Bdb.format_stack_entry (GH-18531) | https://bugs.python.org/issue39649 | CC-MAIN-2021-04 | refinedweb | 323 | 69.18 |
_thread vs uasyncio
Hello there,
My project needs multithreading, and some kind of locks.
As far as I know _thread is not support any kind of locks.
So do you know a workaround of that?
uasyncio could be one, but it is not supported on pycom boards. Is there a way to use it?
Which path should I choose?
- Brian Wyld last edited by
@peterp Note that the 'event.py' which defines a semaphore for asyncio does not load on the latest version, as it depends (for ThreadSafeFlag) on being able to extend uio.IOBase. This base class is not used in the pycom micropython uio port apparently...
This is an issue to use asyncio on pycom ports as ThreadSafeFlag is the only way to do a semaphore from an ISR or other _thread task...
any ideas?
FWIW, I just made a really short test, took the folder from and ran their simple 'hello world' example. that worked ok. Haven't tested deeper.
import uasyncio async def blink(led, period_ms): while True: print(led, 'on') await uasyncio.sleep_ms(5) print(led, 'off') await uasyncio.sleep_ms(period_ms) async def main(led1, led2): uasyncio.create_task(blink(led1, 700)) uasyncio.create_task(blink(led2, 400)) await uasyncio.sleep_ms(10_000) uasyncio.run(main(4,5))
I tested on 1.20.3.b3
@robert-hh I have downloaded, and updated firmware and confirm it works!
Thanks for you awesome support!
@JSmith I have a working subset which is good for 1.20.2.r4. Part of that is from micropython-lib/uasyncio in a maybe older version..
I did not use that a lot, but what I appended works. So it may be a starting point. I could not add an archive here, so you'll find it here:
@robert-hh thank you very much for the insight.
Is V2 the version that was supposed to be supported in: ?
I suppose what I am trying to understand is if there is anyway I can get a version of uasyncio working on my Wipy3.0?
@JSmith Uasyncio V3 is not supported. The Pycom firmware still sticks to an old version of the MicroPython core, and even for uasyncio V2 there is a pitfall, which is the order of arguments of ticks_diff.
Hi guys, this topic is similar to my current issue.
I see uasyncio was supposed to be supported as per:
This would be brilliant for my scheduling requirements, and since I am running firmware: 1.20.2.r2 I attempted to use this using upip install, as per:
However I cannot seem to use the library as I get error: "AttributeError: 'module' object has no attribute 'run'" if I try and run any of the tutorial code.
I assume the pip install has installed V3 uasyncio. Is this supported? Or could anyone help point me at direction for installing uasyncio?
Kind regards, Jake
@tttadam said in _thread vs uasyncio:
As far as I know _thread is not support any kind of locks.
What about this? | https://forum.pycom.io/topic/6922/_thread-vs-uasyncio | CC-MAIN-2022-33 | refinedweb | 499 | 76.11 |
Fibonacci Hash
June 19, 2018
Hash tables are ubiquitous in computing, and we’ve both used and implemented hash tables on several occasions; there is even a hash table implementation in the Standard Prelude. Most hash tables nowadays use the elements of an array as the heads of linked lists that store key/value pairs, so to access (store or fetch) a particular element the procedure is to calculate the hash value based on the key, convert the hash value to an index into the array, and scan down the appropriate linked list until you find the desired item.
The usual way to convert the hash value to an array index is to choose the array size prime, then take the hash value modulo the prime. That can be slow, because the modulo operation requires a division, which is always slow compared to other primitive arithmetic operations. Fibonacci hash replaces the division with multiplication and a shift, which often takes less than half the time.
Fibonacci hash works like this: Choose b the number of bits in an integer, usually either 32 or 64. Then compute 2b ÷ φ, where φ = (1 + √5) ÷ 2 ≈ 1.618; for b = 32 this quantity is 2654435769 and for b = 64 this quantity is 11400714819323198485. Then to compute the array index, multiply the hash value by the quantity shown above, allowing it to wrap around if the product exceeds the integer bounds, and shift right, leaving as many bits as desired. The array size should be a power of 2. Here is an implementation in C:
unsigned long long fibhash(unsigned long long h) { return (h * 11400714819323198485ull) >> 54 }
This returns a ten-bit value (since the 64 bit product is shifted right 54 bits) from 0 inclusive to 1024 exclusive, which is used as the index to the array. If you need more bits, just change the size of the shift.
Malte Skarupke describes the theory behind Fibonacci hash, which you should look at, because it includes some neat math; be sure not to miss the linked video from Vi Hart.
Your task is to implement Fibonacci hash in the language of your choice. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in Haskell.
import Data.Bits
fibhash :: Word -> Word
fibhash h = (h * 11400714819323198485) `shiftR` 54
Example (excluding out-of-range literal warning):
Formatted:
Another implementation in D
449 | https://programmingpraxis.com/2018/06/19/fibonacci-hash/ | CC-MAIN-2018-39 | refinedweb | 418 | 55.47 |
Drawing lines with Lines3D
Before VectorVision was integrated, Papervision3D already had a Lines3D class for drawing 3D lines. Two differences between drawing lines with VectorShape3D and Lines3D are:
- Whereas VectorShape3D enables you to easily draw rectangles, circles, and ellipses, Lines3D does not have built-in methods to do such things.
- Lines3D creates lines with a Vertex3D as the start and end point, resulting in 3D projection of the vertices that make the line. On the other hand, VectorShape3D lets you draw a 2D shape, which you then can rotate in order to achieve a 3D perspective.
Let's take a look at how to create straight as well as curved lines with Lines3D, and how to add interactivity. The following class will serve as a template for the Lines3D examples to come:
package
{
import flash.events.Event;.materials.special.LineMaterial;
import org.papervision3d.view.BasicView;
public class Lines3DTemplate extends BasicView
{
private var lines:Lines3D;
private var easeOut:Number = 0.6;
private var reachX:Number = 0.5
private var reachY:Number = 0.5
private var reachZ:Number = 0.5;
public function Lines3DTemplate ()
{
super(stage.stageWidth,stage.stageHeight);
stage.frameRate = 40;
init();
startRendering();
}
private function init():void
{
//code to be added
}
override protected function onRenderTick(e();
}
}
}
Let's first examine what happens when we draw a line using the Lines3D class.
How drawing with Lines3D works
Each line is defined by a start and an end point, both being 3D vertices. The vertices are converted into 2D space coordinates. The lineTo() method of the Flash drawing API is then used to render the line.
To create a line with the Lines3D class, we need to take these steps in the following order:
- Create line material with the LineMaterial class. The material defines the look of the line.
- Create a Lines3D instance, which is a do3D that will be used to store and render the lines.
- Use the Line3D class to instantiate a line.
- Add the line to the Lines3D instance with the addLine() method.
Equivalent to how Particle instances need to be added in Particles using theaddParticle() method, we add Line3D instances to a Lines3D instance in order to render them.
Lines3D has the following three methods to add Line3D instances:
- addLine()
- ad dNewLine()
- ad dNewSegmentedLine()
Let's have a look at what they do and create some lines.
Straight lines
All t he following code should be added inside the init() method. First we create line material.
var blueMaterial:LineMaterial = new LineMaterial(0x0000FF);
You can pass two optional parameters as shown in the next table:
We passed blue as the color and added no transparency.
Next, we instantiate a Lines3D object that will contain and render the lines to be created. The Lines3D class inherits from DisplayObject3D, so we can add the instance to the scene:
lines = new Lines3D();
scene.addChild(lines);
Each line is defined by two 3D vertices, which refer to the start point and the end point.
var v0:Vertex3D = new Vertex3D(-300,0,0);
var v1:Vertex3D = new Vertex3D(-300,300,0);
Now we create a line by instantiating Line3D.
var blueLine:Line3D = new Line3D(lines,blueMaterial,3,v0,v1);
We passed five parameters to the Line3D constructor, all of them required.
Finally, we add the blue line to the Lines3D instance so that it will be rendered:
lines.addLine(blueLine);
Actually this is quite a lot of code to draw just one line. Let's draw another line, this time using a much shorter, inline notation.
var redLine:Line3D = new
Line3D(lines,new LineMaterial(0xFF0000,1),3,new Vertex3D(0,0,0),
new Vertex3D(-300,0,0))
lines.addLine(redLine);
We have just seen how to draw a straight line. Let's make it curved.
Curved lines
To make a line curved, you add a control vertex using the addControlVertex() method. You can only add one control vertex because the curve is defined by a quadratic Bezier. Let's curve the red line we just created.
redLine.addControlVertex(-150,-300,0);
Just like the 3D vertices that define the start and end point of the line, the control vertex is converted into 2D space and rendered using the Flash drawing API, this time using the curveTo() method. The following screenshot shows both—the straight and the curved line:
Adding lines with addNewLine()
When you call the addNewLine() method, you don't have to create a Line3D instance before you add a new line:
lines.addNewLine(5,0,0,0,300,0,300);
The material that has been passed to the Lines3D constructor defines the color and the transparency of the line. If no material has been passed, the line will use the default material color 0xFF0000 and the default alpha value of 1. The seven parameters required are:
The addNewLine() method returns the created Line3D instance, enabling you to create a line first and then modify it.
var line:Line3D = lines.addNewLine(5,0,0,0,300,0,300);
line.size = 2;
Or we can create and modify a line within one line of code, in the following example a curved line:
lines.addNewLine(5,0,0,0,300,0,300).addControlVertex(150,150,150);
Creating segmented lines
Dividing a line in multiple segments can help you when z-fighting takes place between the line and another object. The addNewSegmentedLine() method adds a line that is made of two or more segments:
lines.addNewSegmentedLine(3,8,300,0,300,600,0,0);
The parameters of addNewSegmentedLine() are identical to those in addNewLine(), except that you also need to pass the number of segments.
The next screenshot shows a line made of 8 segments. Setting the transparency to 1 will show a fluent line, but here the transparency of the material is set to 0.6, resulting in a clear view of the segments:
The addNewSegmentedLine() method returns an array, which contains the Line3D instances that make up the segmented line and can be manipulated. The following code creates a segmented line and curves the third line in the array:
var segLine:Array = lines.addNewSegmentedLine(3,10,300,0,300,0,0,500);
segLine[3].addControlVertex(-10,-30,0);
Note that when you trace the length of the array, the number it returns is one higher than the number of lines you specify. The array element with index 0 does not refer to a visual line. In this example segLine[3] corresponds with the third line.
As said, working with segmented lines can be helpful in avoiding z-sorting problems. When a non-segmented line cuts through a triangle of another object, the whole line will be sorted in front of or behind the triangle. When using a segmented line, the z-sorting process will take into account only the segment that cuts through the triangle. Take a look at the following screenshots. On the left, a non-segmented line runs through a sphere, on the right, a segmented line was used. Both lines are positioned in such a way that they cut right through the center of the sphere. The black line is not segmented and is sorted behind the sphere. The dotted, white line indicates where it should have run. The segmented line does a much better job, giving the desired illusion of cutting through the sphere. Again, the transparency of the segmented line is set to 0.6 to help demonstrate what's happening here.
Lines3DExample
Adding interactivity to Lines3D lines
Interactivity can be added through the material instance. Taking Lines3DTemplate as a starting point, we will see an example of lines that are interactive.
All of the following code should be added inside the init() method. First we create a material and make it interactive:
var material:LineMaterial = new LineMaterial(0x000000,0.6);
material.interactive = true;
Don't forget to change the super() call in the constructor to make the viewport interactive as well.
We then define the number of lines and add some variables that we will use to create a circular shape of lines:
var numberOfLines:uint = 80;
var radius:Number = 100;
var angle:Number = (Math.PI*2) / numberOfLines;
Next we add a for loop:
for(var i:uint = 0; i < numberOfLines; i++)
{
var v0:Vertex3D = new Vertex3D(-300,0,0);
var v1:Vertex3D = new Vertex3D(300,0,0);
var lines:Lines3D = new Lines3D();
var line:Line3D = new Line3D(lines,material,3,v0,v1);
lines.addLine(line);
scene.addChild(lines);
lines.x = (Math.cos(i*angle) * radius);
lines.y = -300;
lines.z = Math.sin(i*angle) * radius;
lines.rotationY = (-i*angle) * (180/Math.PI) + 270;
lines.addEventListener(InteractiveScene3DEvent.OBJECT_OVER,
linesOverListener);
}
Inside the for loop we create two 3D vertices at each iteration, v0 and v1, that refer to the start and end point of each line. Then we create a Lines3D instance that will contain and render the line. We instantiate Line3D while passing the Lines3D instance, the material, a line weight of 3 and the start and end points. Next, we add the line to the Lines3D instance, which in turn is added to the scene. The position and rotation of each line are defined by some math, which results in a circular arrangement. Finally, we add an event listener to the Lines3D instance, which will trigger the associated handler method when the mouse hovers a line.
The handler method looks as follows:
private function linesOverListener(e:InteractiveScene3DEvent):void
{
Tweener.addTween(e.displayObject3D,{y:200,time:1,transition:
"easeInOutExpo"});
}
Using Tweener, the line that has been hovered tweens upwards from its currenty position of -300 to a new y position of 200. The following image shows three different states of the example:
InteractiveLines3DExample
Growing lines example
Although the previous example tweened the position of the lines when they were hovered, the lines themselves were pretty static. Their length and shape stayed the same. The next example shows how to grow a line dynamically. We will create a small sphere and move it around. Out of the sphere a line will grow, which curves depending on how the mouse moves.
We first need to prepare the Lines3DTemplate. Remove all the code in the onRenderTick() method that makes the camera interact with the mouse, but leave the super.onRenderTick(); call. Also remove all the private class properties and put these in their place:
private var lines:Lines3D;
private var sphere:Sphere;
private var lineMaterial:LineMaterial;
private var previousVertex:Vertex3D;
Now the class is ready for our example. Most of the work will be done in the render method, but first add this in the init() method:
sphere = new Sphere(new PhongMaterial(new PointLight3D(),0xFFFFFF,
0x484848,10),100,20,20);
scene.addChild(sphere);
lineMaterial = new LineMaterial(0xFFFFFF);
lines = new Lines3D(lineMaterial);
scene.addChild(lines);
lines.addNewLine(2,0,0,0,0,0,0);
previousVertex = lines.geometry.vertices[1];
camera.target = sphere;
Let's run through the above code. We first instantiate a sphere with Phong material and add it to the scene. The sphere will serve as a guide for the dynamic line. We create a line material and a Lines3D instance, of which the latter is added to the scene. Next, we add a line with a weight of 3 and a start and end 3D vertex. Notice that we give the line a length of 0, because when we publish the application we don't want to see a line from the start. The previousVertex variable will be used in the render method but we initially set it to the coordinates of the second 3D vertex inLines3D instance, which is the end point of the line we just added. Finally, we set the sphere as the target of the camera. Now let's move to the render method.
Inside the render method, we let the sphere rotate depending on the mouse position and we move it forward by 100 units per frame:
sphere.localRotationX = -(mouseX/stage.stageWidth) * 360;
sphere.localRotationY = -(mouseY/stage.stageWidth) * 360;
sphere.moveForward(100);
The next piece of code, still in the render method, takes care of growing the line dynamically:
var new Vertex:Vertex3D = new Vertex3D(sphere.x,sphere.y,sphere.z);
var line:Line3D = new Line3D(lines,lineMaterial,2,previousVertex,
newVertex);
lines.addLine(line);
previousVertex = newVertex;
At each frame, we create a new 3D vertex with the coordinates of the sphere at that moment. Also, we create a new line and add it. Finally we set previousVertex to the new 3D vertex.
So what happens here? In each frame, the start position of the new line is defined by previousVertex, which is set to the new 3D vertex after the new line has been added. The end position of every new line is defined by the position of the sphere, which is constantly moving (and rotating if the user moves the mouse). All this results in creating a dynamically growing line that follows the sphere, as shown in the following images:
If you don't want to lose sight of the sphere because of its growing distance to the camera, adding the following code to the onRenderTick() method copies the position of the sphere to the camera and moves it backward:
camera.copyPosition(sphere);
camera.moveBackward(4000);
To prevent the line from growing too long, we add the following:
if(lines.lines.length > 500)
{
lines.removeLine(lines.lines[0]);
}
Lines3D has a lines property, which is an array that contains the lines added. If this number exceeds 500, we remove the first line from the array by using the removeLine() method.
GrowingLines3DExample
Summary
We discussed the Lines3D class that also allows you to draw 3D lines. Each line is defined by two 3D vertices, which refer to a start point and an end point. As this class works with 3D vertices, it is possible to set z coordinates, resulting in the illusion of lines with depth. You can also add a control point in order to curve a line. The Lines3D and Line3D classes were already part of Papervision3D before VectorVision was incorporated. In several examples, we have seen how to create lines with these classes, add interactivity to them, and make them grow dynamically. | https://www.packtpub.com/books/content/3d-vector-drawing-and-text-papervision3d-part-2 | CC-MAIN-2016-44 | refinedweb | 2,349 | 63.59 |
Turn URL variables into models.
Project description
Dart turns URL variables into database models with a decorator.
That means you can do something like this:
@app.route('/user/<user_id>/tracks', methods=['GET']) @dart.inject(User, 'user', from_var='user_id') def user_tracks(user=None): return jsonify(user.tracks)
If you’re smart, you might have a decorator that checks user authorization, something like @login_required. You can compose Dart with other decorators to simplify logic, while still keeping your code readable and concise:
def login_required(view): @functools.wraps(view) @dart.inject(User, 'user', from_var='user_id') @dart.inject(User, 'current_user', from_val=lambda: session['user_id']) def decorated_view(user=None, current_user=None, *args, **kwargs): if current_user != user: abort(403) else: return view(user=user, *args, **kwargs) return decorated_view @login_required def view(user=None): return '{} did it!'.format(user.name)
Of course, Dart isn’t just a Flask. It’s literally just a decorator that takes a keyword arg or lambda expression and queries the model class using it as the primary key. That means you can use the Dart decorator with any function.
For more info, check out the source code – it’s 27 lines.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/dart/ | CC-MAIN-2019-35 | refinedweb | 216 | 51.75 |
I built a new VM from zero. Ubuntu 20.04apt install build-essentialapt install gitapt install cmakeapt install python3-pippip3 install pygccxmlbuild, install pybind11 from 2.4.3 tarballsetup gnuradio repository to releasesapt install gnuradioThis gives gnuradio 3.9.1.0git-cloning both Ron's gr-iqlevels and my gr-hpsdr, going through cmake, make, sudo make install, sudo ldconfigyields exactly the same results as before: the gr:sync_block (gr-iqlevels) or the gr::block (gr-hpsdr) are not imported.-- Tom, N5EGOn Sun, May 9, 2021 at 11:44 AM Tom McDermott <tom.n5eg@gmail.com> wrote:Hi Ron - thank you for sending me the link to your 3.9 gr-iqlevels module !It builds and installs OK, but when trying to run it gives me the same type of error as my own module:Note: cmake .. -DCMAKE_INSTALL_PREFIX=/usr was used for for gr-iqlevels
$ python3
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gnuradio
>>> import iqlevels
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/iqlevels/__init__.py", line 18, in <module>
from .iqlevels_python import *
ImportError: generic_type: type "iqlevels" referenced unknown base type "gr::sync_block"
>>>And when run from GRC:Traceback (most recent call last):
File "/home/tom/Desktop/iqlevels.py", line 142, in <module>
main()
File "/home/tom/Desktop/iqlevels.py", line 120, in main
tb = top_block_cls()
File "/home/tom/Desktop/iqlevels.py", line 81, in __init__
self.iqlevels_iqlevels_0 = iqlevels.iqlevels(samp_rate, 1)
AttributeError: type object 'iqlevels' has no attribute 'iqlevels'So it appears there is something wrong or misconfigured in my system.I am baffled as to what that might be.Ubuntu 20.04Gnuradio 3.9.0.0Python 3.8.5Cmake 3.16.3GCC 9.3.0pygccxml 2.1.0 installed using pip3pybind11-2.4.3 installed from tarball according to the OOT 3.9 instructionspybind11 build, cmake, make, make install by the above directions.it put the various pybind headers into /usr/local/include/pybind11/Is there some other configuration, path, or other thing that needs to be setup?-- Tom, N5EG | https://lists.gnu.org/archive/html/discuss-gnuradio/2021-05/msg00056.html | CC-MAIN-2021-49 | refinedweb | 362 | 58.99 |
I have a list of complex numbers for which I want to find the closest value in another list of complex numbers.
My current approach with numpy:
import numpy as np
refArray = np.random.random(16);
myArray = np.random.random(1000);
def find_nearest(array, value):
idx = (np.abs(array-value)).argmin()
return idx;
for value in np.nditer(myArray):
index = find_nearest(refArray, value);
print(index);
Here's one vectorized approach with
np.searchsorted based on
this post -
def closest_argmin(A, B): L = B.size sidx_B = B.argsort() sorted_B = B[sidx_B] sorted_idx = np.searchsorted(sorted_B, A) sorted_idx[sorted_idx==L] = L-1 mask = (sorted_idx > 0) & \ ((np.abs(A - sorted_B[sorted_idx-1]) < np.abs(A - sorted_B[sorted_idx])) ) return sidx_B[sorted_idx-mask]
Brief explanation :
Get the sorted indices for the left positions. We do this with -
np.searchsorted(arr1, arr2, side='left') or just
np.searchsorted(arr1, arr2). Now,
searchsorted expects sorted array as the first input, so we need some preparatory work there.
Compare the values at those left positions with the values at their immediate right positions
(left + 1) and see which one is closest. We do this at the step that computes
mask.
Based on whether the left ones or their immediate right ones are closest, choose the respective ones. This is done with the subtraction of indices with the
mask values acting as the offsets being converted to
ints.
Benchmarking
Original approach -
def org_app(myArray, refArray): out1 = np.empty(myArray.size, dtype=int) for i, value in enumerate(myArray): # find_nearest from posted question index = find_nearest(refArray, value) out1[i] = index return out1
Timings and verification -
In [188]: refArray = np.random.random(16) ...: myArray = np.random.random(1000) ...: In [189]: %timeit org_app(myArray, refArray) 100 loops, best of 3: 1.95 ms per loop In [190]: %timeit closest_argmin(myArray, refArray) 10000 loops, best of 3: 36.6 µs per loop In [191]: np.allclose(closest_argmin(myArray, refArray), org_app(myArray, refArray)) Out[191]: True
50x+ speedup for the posted sample and hopefully more for larger datasets! | https://codedump.io/share/733sPpwaK8g0/1/find-nearest-indices-for-one-array-against-all-values-in-another-array---python--numpy | CC-MAIN-2019-26 | refinedweb | 334 | 52.05 |
This post is to discuss few important points about parse() method. If you are looking for String to Date and Date to String conversion then refer the following posts:
Converting strings to desired date format is a time consuming and tedious process in many languages including Java. However Java provides several APIs to accomplish this.
java.text.DateFormat
java.text.SimpleDateFormat
java.util.Date
java.util.Calendar
java.util.TimeZone
The first two APIs are concerned with representing dates as strings. They both have methods:
String format (java.util.Date)
java.util.Date parse (String)
The difference between java.text.DateFormat and java.text.SimpleDateFormat is that the java.text.SimpleDateFormat uses a custom format defined by special formatting characters where as the java.text.DateFormat uses the standard date formatting of the current locale
For Example
import java.text.*; SimpleDateFormat sdfmt1 = new SimpleDateFormat("dd/MM/yy"); SimpleDateFormat sdfmt2= new SimpleDateFormat("dd-MMM-yyyy"); java.util.Date dDate = sdfmt1.parse( strInput ); String strOutput = sdfmt2.format( dDate );
This will turn e.g. “21/4/99” into “21-Apr-1999”.
Points to note:
1. The parse() method does not (by default) throw an Exception if the date is correctly formatted but invalid on the calendar (e.g. 29/2/2001), instead it alters the date to be a valid one (in the previous example, to 1/3/2001). If this isn’t what you want, call date.setLenient( false ).
2. The format represented as a 4-digit year (yyyy) then “12/6/01” is parsed as “12/06/0001”.
If it is 2-digit (yy) then the year is set to be between 80 years before and 20 years after the date the SimpleDateFormat instance is created (e.g. today!). Thus if today is 1/10/01, then “30/9/21” is interpreted as “30/09/2021” and “1/10/22” is “01/10/1922”. This boundary date can be altered by the set2DigitYearStart() method.
3. Both java.util.* and java.sql.* packages contain objects called Date. Hence user need to explicitly mention the Date as java.util.Date (in case if the user is working with SQL also)
More sophisticated date arithmetic and processing can be done using TimeZone, Calendar and its child Gregorian Calendar, but these do not deal directly with dates formatted as strings. | https://beginnersbook.com/2013/05/java-parse-date/ | CC-MAIN-2017-51 | refinedweb | 385 | 50.53 |
One of the most common questions that comes up in #django is about static files.
Why are my images not loading? How do I make Django serve my CSS files? The
answer depends on the environment. You might want to hook up
django.views.static.serve
in development and
Alias in production. I want to help clarify all static
file questions.
How do I make Django serve static files?
It is possible to setup Django to serve your static files. This functionality is off by default. Django is a web application framework. It is not intended to serve any static files. It might serve static content which is cached in memcached, the database or on the filesystem. The method to setup static file serving in Django is disclaimed in the documentation:
Using this method is inefficient and insecure. Do not use this in a production setting. Use this only for development.
Check out the static documentation for Django to get more information about
how to set it up with your
urls.py. Lets cover what settings that Django has
that I will use through out the rest of this article:
MEDIA_ROOT
- The default value is
""(an empty string). Django uses
MEDIA_ROOTas the root path for the
upload_toparameter for
FileFieldand
ImageField. It is typically the place where you will want to make publically available through your web server.
MEDIA_URL
- The default value is
""(an empty string). There is nothing magically about
MEDIA_URL. It is more of an aide to you to properly map static files to the correct location in your templates. You can get
MEDIA_URLdefined in all of your templates by using
django.core.context_processors.mediain your
TEMPLATE_CONTEXT_PROCESSORS. This is turned on by default if you are using SVN revision 5379 or newer. However, you need to ensure you are using the
RequestContextas your context in reach view that renders a template.
A quick tip serving static files in development
I can't say that I invented this idea, because I originally found it in
Satchmo. Create a new settings variable called
LOCAL_DEVELOPMENT. Set the
value to either
True or
False depending on whether the project is local
or on a production server. Then make your
urls.py look similar to this:
from django.conf import settings from django.conf.urls.defaults import * urlpatterns = patterns("", # normal url patterns here. ) if settings.LOCAL_DEVELOPMENT: urlpatterns += patterns("django.views", url(r"%s(?P<path>.*)/$" % settings.MEDIA_URL[1:], "static.serve", { "document_root": settings.MEDIA_ROOT, }) )
Keep in mind that if you have a url pattern that consumes your
MEDIA_URL
before getting to the new one I show you above then you will need to restructure
things. Also keep in mind that if your
MEDIA_URL is an absolute URL then
this will clearly not work. If you have separated your
settings.py file to
allow for different settings in different locations then just override your main
MEDIA_URL to be something that can be used in the
urlpatterns.
UPDATE: It has come to my attension that the above code was wrong and has
now been corrected. It used to allow
settings.MEDIA_URL pass through to
the regex, but that was incorrect when
settings.MEDIA_URL has a leading
slash as it should to be properly referenced in the templates. I am now using
settings.MEDIA_URL[1:] to eat the leading slash.
Serving static files in production
I will describe how to accomplish static file serving using Apache. This is the easiest method to configure considering you are probably deploying to Apache. Here is a quick example of how you might setup Django within Apache and mod_python:
<Location "/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonDebug On </Location>
This works well, but as you can see if a request is made to
/site_media/css/layout.css then it is passed to Django. Then Django would
need to resolve it and return something back to client. If you accidently left
LOCAL_DEVELOPMENT turned on then this will magically work and you may ignore
that and assume everything is okay. However, this is very bad because now Django
is being forced to serve static files when the web server should be responsible
for that. Apache can serve the static files much more efficiently than Django
can. So, let's add on to our Apache configuration:
<Location "/site_media"> SetHandler None </Location>
Okay, now we have told Apache that when a request is made with
/site_media
as the beginning portion of the path to do nothing. We are not done yet, because
we need to tell Apache to map requests from
/site_media to the files located
on the file system. This can be done using Apache's
Alias directive:
Alias /site_media/ /path/to/media <Location "/site_media"> SetHandler None </Location>
Replace
/path/to/media to your
MEDIA_ROOT path. Setting up the admin
media files is done the same way. Just map
ADMIN_MEDIA_PREFIX to the location
of the admin media files. The location will vary from system to system, but the
path inside the Django source tree is
django/contrib/admin/media. Be sure
to find out where your Django source tree resides and map it accordingly. Also,
keep in mind you may need to look at the permissions to ensure the webserver user
that Apache runs as has the permission to read those files. This applies to all
static files being served by Apache.
This wraps up how to serve static files in a Django environment. I am looking forward to expand on this article and cover Cherokee and the environment that is required for that setup.
Excellent post and thank you for detailing this. It comes up so often and now this is a great resource to point people to.
I do have a question, why is it that you use LOCAL_DEVELOPMENT as opposed to just using DEBUG like the docs show? You mentioned this on the show and I didn't get to clarify it then.
Thanks again.
Posted by Empty on Jan 24, 2008 at 6:54 PM | http://oebfare.com/blog/2007/dec/31/django-and-static-files/ | crawl-001 | refinedweb | 1,000 | 66.54 |
CGI::FormBuilder - Easily generate and process stateful forms
use CGI::FormBuilder; # Let's assume we did a DBI query to get existing values my $dbval = $sth->fetchrow_hashref; my $form = CGI::FormBuilder->new( method => 'POST', fields => [qw/name email phone gender/], values => $dbval, validate => { email => 'EMAIL', phone => 'PHONE' }, required => 'ALL', font => 'arial,helvetica', ); # Change gender field to have options $form->field(name => 'gender', options => [qw/Male Female/]); if ($form->submitted && $form->validate) { my $fields = $form->field; # get form fields as hashref # Do something to update your data (you would write this) do_data_update($fields->{name}, $fields->{email}, $fields->{phone}, $fields->{gender}); # Show confirmation screen print $form->confirm(header => 1); # Email the person a brief confirmation $form->mailconfirm(to => $fields->{email}); } else { # Print out the form print $form->render(header => 1); }
This documentation is very extensive, and likely all you will need. However, there is even more online, as well as examples and tutorials, at:
You should also consider joining the mailing list by sending an email to:
fbusers-subscribe@formbuilder.org
You are encouraged to visit the website, even if you are a longtime user, as there are a number of hints and tricks that you may find useful.
I hate generating and processing forms. Hate it, hate it, hate it, hate it. My forms almost always end up looking the same, and almost always end up doing the same thing. Unfortunately, there really haven't the venerable
CGI.pm are great for processing parameters, but they don't save you much time when trying to generate and process forms.
The goal of
CGI::FormBuilder (FormBuilder) is to provide an easy way for you to generate and process CGI form-based applications. This module is designed to be smart in that it figures a lot of stuff out for you. As a result, FormBuilder gives you about a 4:1 ratio of the code it generates versus what you have to write.
For example, if you have multiple values for a field, it sticks them in a radio, checkbox, or select group, depending on some factors. It will also automatically name fields for you in human-readable labels depending on the field names, and lay everything out in a nicely formatted table. It will even title the form based on the name of the script itself (
order_form.cgi becomes "Order Form").
Plus, FormBuilder provides you full-blown validation for your fields, including some useful builtin patterns. It will even generate JavaScript validation routines on the fly! And, of course, it maintains state ("stickiness") across submissions, with hooks provided for you to plugin your own sessionid module such as
Apache::Session.
And though it's smart, it allows you to customize it as well. For example, if you really want something to be a checkbox, you can make it a checkbox. And, if you really want something to be output a specific way, you can even specify the name of an
HTML::Template or Template Toolkit (
Template) compatible template which will be automatically filled in, statefully.
Let's walk through a whole example to see how FormBuilder works. The basic usage is straightforward, and has these steps:
CGI::FormBuilderobject with the proper options
FormBuilder is designed to do the tedious grunt work for you. In fact, a whole form-based application can be output with nothing more than this:
use CGI::FormBuilder; my @fields = qw(name email password confirm_password zipcode); my $form = CGI::FormBuilder->new(fields => \@fields); print $form->render(header => 1);
Not only does this generate about 4 times as much HTML-compliant code as the above Perl code, but it also keeps values statefully across submissions, even when multiple values are selected. And if you do nothing more than add the
validate option to
new():
my $form = CGI::FormBuilder->new( fields => \@fields, validate => {email => 'EMAIL'} );
You now get a whole set of JavaScript validation code, as well as Perl hooks for validation. In total you get about 6 times the amount of code generated versus written. Plus, statefulness and validation are handled for you, automatically.
Let's keep building on this example. Say we decide that we really like our form fields and their stickiness, but we need to change a couple things. For one, we want the page to be laid out very precisely. No problem! We simply create an
HTML::Template compatible template and tell our module to use that. The
HTML::Template module uses special HTML tags to print out variables. All you have to do in your template is create one for each field that you're printing, as well as one for the form header itself:
you need to do in your Perl is add the
template option:
my $form = CGI::FormBuilder->new(fields => \@fields, validate => {email => 'EMAIL'}, template => 'userinfo.tmpl');
And the rest of the code stays the same.
You can also do a similar thing using the Template Toolkit () to generate the form. This time, specify the
template option as a hashref which includes the
type option set to
TT2 and the
template option to denote the name of the template you want processed. You can also add
variable as an option (among others) to denote the variable name that you want the form data to be referenced by.
my $form = CGI::FormBuilder->new( fields => \@fields, template => { type => 'TT2', template => 'userinfo.tmpl', variable => 'form', } );
The template might look something like this:
<html> <head> <title>[% form.title %]</title> [% form.jshead %] </head> <body> [% form.start %] <table> [% FOREACH field = form.fields %] <tr valign="top"> <td> [% field.required ? "<b>$field.label</b>" : field.label %] </td> <td> [% IF field.invalid %] Missing or invalid entry, please try again. <br/> [% END %] [% field.field %] </td> </tr> [% END %] <tr> <td colspan="2" align="center"> [% form.submit %] </td> </tr> </table> [% form.end %] </body> </html>
So, as you can see, there is plugin capability for FormBuilder to basically "run" the two major templating engines, HTML::Template and Template Toolkit.
Now, back to FormBuilder. Let's assume that we want to validate our form on the server side, which is common since the user may not be running JavaScript. All we have to add is the statement:
$form->validate;
Which will go through the form, checking each value can only fiddle our database or whatever if everything looks good. We can then use our
confirm() method to print out a generic results page:
if ($form->validate) { # form was good, let's update database ... print $form->confirm; } else { print $form->render; }
The
validate() method will use whatever criteria were passed into
new() via the
validate parameter to check the form submission to make sure it's correct.
However, we really only want to do this after our form has been submitted, since this could otherwise result in our form showing errors even though the user hasn't gotten a chance to fill it out yet. As such, we can check for whether the form has been submitted yet by wrapping the above with:
if ($form->submitted && $form->validate) { # form was good, let's update database ... print $form->confirm; } else { print $form->render; }
Of course, this module wouldn't be really smart if it didn't provide some more stuff for you. A lot of times, we want to send a simple confirmation email to the user (and maybe ourselves) saying that the form has been submitted. Just use
mailconfirm():
$form->mailconfirm(to => $form->field('email'), from => 'auto-reply');
With FormBuilder, any default values you specify are automatically overridden by whatever the user enters into the form and submits. These can then be gotten to by using the
field() method:
my $email = $form->field(name => 'email');
Of course, like
CGI.pm's param() you can just specify the name of the field when getting a value back:
my $email = $form->field('email');
FormBuilder is good at giving you the data that you should be getting. That is, let's say that you initially setup your
$form object to use a hash of existing values from a database select or something. Then, you
render() the form, the user fills it out, and submits it. When you call
field(), you'll get whatever the correct value is, either the default or what the user entered across the CGI.
So, our complete code thus far looks like this:
use CGI::FormBuilder; my @fields = qw(name email password confirm_password zipcode); my $form = CGI::FormBuilder->new( fields => \@fields, validate => { email => 'EMAIL' }, template => 'userinfo.tmpl', header => 1 ); if ($form->submitted && $form->validate) { # form was ok, let's update database (you write this part) my $fields = $form->field; # get all fields as hashref do_data_update($fields); # show a confirmation message print $form->confirm; # and send them email about their submission $form->mailconfirm(to => $form->field('email'), from => 'auto-reply'); }.
Now back to our regularly-scheduled program...
Of course, in the spirit of flexibility this module takes a bizillion different options. None of these are mandatory - you can call the
new() constructor without any fields, but your form will be really really short. :-)
This documentation is very extensive, but can be a bit dizzying due to the enormous number of options that let you tweak just about anything. As such, I recommend that if this is your first time using this module, you stop and visit:
And click on "Tutorials" and "Examples". Then, use the following section as a reference later on.
This is the constructor, and must be called very first. It returns a
$form object, which you can then modify and print out to create the form. This function accepts all of the options listed under
render() below. In addition, it takes 6 options that can only be specified to
new(): option can only be specified to
new() but not to
render().
This names the form. It is optional, but if you specify it you must do so in
new() since the name is then used to alter how variables are created and looked up.
This option has an important side effect. When used, it renames several key variables and functions according to the name of the form. This allows you to (a) use multiple forms in a sequential application and (b) display multiple forms inline in one document. If you're trying to build a complex multi-form app and are having problems, try naming your forms. $mode = $q->param('mode'); # do stuff based on mode ... my $form = CGI::FormBuilder->new(... params => $q);
The above example would allow you to access CGI parameters directly via
$q->param (however, note that you could get the same functionality by using
$form->cgi_param).
This option takes a hashref of key/value pairs. Each key is the name of a field from the
fields option, or the string
ALL in which case it applies to all fields. Each value is one of the following:
- a regular expression to match the field sets up each field so that it is required. However, if you specify the
required option, then only those fields explicitly listed would be required, and the rest would only be validated if filled in. See the
required option; }
This would create both JavaScript and Perl conditionals or.
This option allows you to customize basically all the messages this module outputs. This is useful if you are writing a multilingual application, or are just anal and want the messages exactly right.
The messaging system is simple, as it borrows somewhat from
getttext(). Each message displayed;
Then, your language file would contain, are there are many many messages that can be customized. Here is a list of the fields that can be customized, along with their default values.
js_invalid_start %s error(s) were encountered with your submission: js_invalid_end Please correct these fields and try again. js_invalid_input - You must enter a valid value for the "%s" field js_invalid_select - You must choose an option for the "%s" field js_invalid_checkbox - You must choose an option for the "%s" field js_invalid_radio - You must choose an option for the "%s" field js_invalid_password - You must enter a valid value for the "%s" field js_invalid_textarea - You must fill in the "%s" field js_invalid_file - You must specify a valid file for the "%s" field form_required_text <p>Fields shown in <b>bold</b> are required. form_invalid_text <p>%s error(s) were encountered with your submission. Please correct the fields <font color="%s"> <b>highlighted</b></font> below. form_invalid_color red form_confirm_text Success! Your submission has been received %s. form_invalid_input You must enter a valid value form_invalid_select You must choose an option from this list form_invalid_checkbox You must choose an option from this group form_invalid_radio You must choose an option from this group form_invalid_password You must enter a valid value form_invalid_textarea You must fill in this field form_invalid_file You must specify a valid filename form_select_default -select- form_submit_default Submit form_reset_default Reset, you this is optional, so if you leave it out then you won't get the number of errors.
The best way to get an idea of how these work is to experiment a little. It should become obvious really quickly.
If set to 1, the module spits copious debugging info to STDERR. If set to 2, it spits out even more gunk. Defaults to 0.
This function renders the form into HTML, and returns a string containing the form. The most common use is simply:
print $form->render;
However,
render() accepts the exact same options as
new() Why? Because this allows you to set certain options at different points in your code, which is often useful. For example, you could change the formatting based on whether
layout appeared in the query string:
my $form = CGI::FormBuilder->new(method => 'POST', fields => [qw/name email/]); # Get our layout from an extra CGI param my $layout = $form->cgi_param('layout'); # If we're using a layout, then make sure to request a template if ($layout) { print $form->render(template => $layout); } else { print $form->render(header => 1); }
The following are all the options accepted by both
new() and
render():
What script to point the form to. Defaults to itself, which is the recommended setting.
This takes a hashref of attributes that will be stuck in the
<body> tag verbatim (for example, bgcolor, alink, etc). If you're thinking about using this, also check out the
template option above (and below).
This can be used to set the default type for all fields. For example, if you're writing a survey application, you may want all of your fields to be of type
textarea by default. Easy:
my $form = CGI::FormBuilder->new(... fieldtype => 'textarea');
Even more flexible than
fieldtype, this option allows you to specify any type of HTML attribute and have it be the default for all fields. For example:
my $form = CGI::FormBuilder->new(... fieldattr => { class => 'myClass' });
Would set the
class HTML attribute on all fields by default, so that when they are printed out they will have a
class="myClass" part of their HTML tag. Maybe you want a template?
The font face to use for the form. This is output as a series of
<font> tags for best browser compatibility, and will even take care of the tedious table elements. I use this option all the time. If you specify a hashref instead of just a font name, then each key/value pair will be taken as part of the
<font> tag. For example:
font => {face => 'verdana', size => '-1', color => 'gray'}
Would generate the following tag:
<font face="verdana" size="-1" color="gray">
And properly nest them in all of the table elements.
If set to 1, a valid
Content-type header will be printed out, along with a whole bunch of HTML
<body> code, a
<title> tag, and so on. This defaults to 0, since usually people end up using templates or embedding forms in other HTML. Setting it to 1 is a great way to throw together a quick and dirty form, though.
If set to 1, JavaScript is generated in addition to HTML, the default setting.
If using JavaScript, you can also specify some JavaScript code that will be included verbatim in the <head> section of the document. I'm not very fond of this one, what you probably want is the next option.
Just like
jshead, only this is stuff that will go into the
validate JavaScript function. As such, you can use it to add extra JavaScript validate code verbatim. If something fails, you should do two things:
- append to the JS variable "alertstr" - increment the JS variable "invalid"
For example:
my $jsfunc = <<EOJS;; if (form._submit.value == 'Delete') { if (confirm("Really DELETE this entry?")) return true; return false; } else if (form._submit.value == 'Cancel') { // skip validation since we're cancelling return true; } EOJS
Important: When you're quoting, remember that Perl will expand "\n" itself. So, if you want a literal newline, you must double-escape it, as shown above.
If set to 1, then extra parameters not set in your fields declaration will be kept as hidden fields in the form. However, you will need to use
cgi_param(), not
field(), to get to the values. This is useful if you want to keep some extra parameters like referer or company available but not have them be valid form fields. See below under
/"param" for more details.
You can also specify an arrayref, in which case only params found on that list will be preserved. For example, saying:
->new(keepextras => 1, ...);
Will preserve all non-field parameters, whereas saying:
->new(keepextras => [qw/mode company/], ...);
Will only preserve the params
mode and
company..
This is how to align the field labels in the table layout. I really don't like this option being here, but it does turn out to be pretty damn useful. You should probably be using a template.
If set to 1, line breaks will be inserted after each input field. By default this is figured out for you, so usually not needed.
Either
POST or
GET, the type of CGI method to use. Defaults to
GET if nothing is specified.
By using this argument, you can avoid having to specify the options for different fields individually:
my $form = CGI::FormBuilder->new( fields => [qw/part_number department in_stock/], options => { department => [qw/hardware software/], in_stock => [qw/yes no/], } );
This will then create the appropriate multi-option HTML inputs (in this case, radio groups) automatically.
This is a list of those values that are required to be filled in. Those fields named must be included by the user. If the
required option is not specified, by default any fields named in
validate will be required.
As of v1.97, the
required option now takes two other settings, the string
ALL and the string
NONE. If you specify
ALL, then all fields are required. If you specify
NONE, then none of them are in spite of what may be set via the "validate" option.
This is useful if you have fields that you need to be validated if filled in, but which are optional. For example:".
These affect the "intelligence" of the module. If a given field has any); # This is the one special case - single items are checkboxes $form->field(name => 'answer', options => ['Yes']);
There is no threshold for checkboxes since these are basically a type of multiple radio select group. As such, a radio group becomes a checkbox group if there are multiple values (not options, but actual values) for a given field, or if you specify
multiple => 1 to the
field() method.
render() or
new(), this has the same effect as the same-named option to
field(), only it applies to all fields.
If set to 1, then the form will be output with static hidden fields. Defaults to 0.
Determines whether or not form values should be sticky across submissions. This does not affect the value you get back from a call to
field(). It also does not affect default values. It only affects values the user may have entered via the CGI.}
This points to a filename that contains an
HTML::Template compatible template to use to layout the HTML. You can also specify the
template option as a reference to a hash, allowing you to further customize the template processing options.
For example, you could turn on caching in
HTML::Template with something like the following:
my $form = CGI::FormBuilder->new( fields => \@fields, template => { filename => 'form.tmpl', shared_cache => 1 } );
In addition, processor. Use
TT2 to invoke the Template Toolkit or
HTML (the default) to invoke
HTML::Template as shown above. All other options besides
type are passed to the constructor for that templating system verbatim, so you'll need to consult those docs to see what different options do.
For lots more information on templates, see the "TEMPLATES" section below..
Another one I don't like, this alters how form fields are laid out in the natively-generated table. Default is "middle".. While
new() is used as an example, this can of course be used in
render() as well.
Note that any other options specified are passed to the
<form> tag verbatim. For example, you could specify
onSubmit or
enctype to add the respective attributes.
This method is called on the
$form object you get from the
new() method above, and is used to manipulate individual fields. You can use this if you want to specify something is a certain type of input, or has a certain set of options.
For example, let's say that you create a new form:
my $form = CGI::FormBuilder->new(fields => [qw/name state zip/]);
And that you want to make the "state" field a select list of all the states. You would just say:
$form->field(name => 'state', type => 'select', options => \@states);
Then, when you used
render() to create the form output, the "state" field would appear as a select list with the values in
@states as options.
If just given the name of the field, then the value of that field will be returned, just like
CGI.pm:
my $email = $form->field('email');
Why is this not named
param()? Simple: Because it's not compatible. Namely, while the return context behavior is the same, this function is not responsible for retrieving all CGI parameters - only those defined as valid form fields. This is important, as it allows your script to accept only those field names you've defined for security.
To get the list of valid field names just call it without and args:
my @fields = $form->field;
And to get a hashref of field/value pairs, call it as:
my $fields = $form->field; my $name = $fields->{name};
Note that if you call it as a hashref, you will only get one single value per field. This is just fine as long as you don't have multiple values per field (the normal case). However, if you have a query string like this:
favorite_colors.cgi?color=red&color=white&color=blue
Then you will only get one value for
color in the hashref. In this case you'll need to access it via
field() to get them all:
my @colors = $form->field('color');
The
field() function takes several parameters, the first of which is mandatory. The rest are listed in alphabetical order:
Finally, you can also take advantage of a new feature and address fields directly by name. This means instead of:
my $address = $form->field('address');
You can say:
my $address = $form->address;
This works for setting properties as well:
$form->field(name => 'user_id', size => '8', maxlength => '12'); $form->user_id(size => '8', maxlength => '12');
Both of those would do the exact same thing. You will get a fatal error if you try to address an invalid field.
The name of the field to manipulate. The "name =>" part is optional if there's only one argument. For example:
my $email = $form->field(name => 'email'); my $email = $form->field('email'); # same thing
However, if you're specifying more than one argument then you must include the
name part:
$form->field(name => 'email', size => '40');
This prints out the given comment after the field to fill in, vebatim. For example, if you wanted a field to look like this:
Joke [____________] (keep it clean, please!)
You would use the following:
$form->field(name => 'joke', comment => '(keep it clean, please!)');
The
comment can actually be anything you want (even another form field). But don't tell anyone I said that.
This is used in conjunction with the
value option to forcibly override a field's value. See below under the
value option for more details. For compatibility with
CGI.pm, you can also call this option
override instead, but don't tell anyone.
This is a simple abstraction over directly specifying the JavaScript action type. This turns out to be extremely useful, since if an option list changes from
select to
radio or
checkbox (depending on the number of options), then the action changes from
onChange to
onClick. Why?!?!
So if you said:
$form->field(name => 'credit_card', jsclick => 'recalc_total();', options => \@cards)
This would generate the following code, depending on the number of
@cards:
<select name="credit_card" onChange="recalc_total();"> ... <radio name="credit_card" onClick="recalc_total();"> ...
You get the idea.
This will be the label printed out next to the field. By default it will be generated automatically from the field name.
This takes a hashref of key/value pairs where each key is one of the options, and each value is what its printed label should be. For example:
.
You can also get the same effect by passing complex data structures directly to the
options argument (see below). If you have predictable data, check out the
nameopts option.
Similar to the top-level "linebreaks" option, this one will put breaks in between options, to space things out more. This is useful with radio and checkboxes especially. just like the fields. So, if you specified a list like:
.
This takes an arrayref of options. It also automatically results in the field becoming a radio (if <= 4) or select list (if > 4), unless you explicitly set the type with the
type parameter.
Each item will become both the value and the text label by default. That is, if you specified these options:
$form->field(name => 'opinion', options => [qw/yes no maybe so/]);
You will get something like this:
<select name="opinion"> <option value="yes">yes</option> <option value="no">no</option> <option value="maybe">maybe</option> <option value="so">so</option> </select>
However, if a given item is either an arrayref or hashref, then the first element will be taken as the value and the second as the label. So something like);
You get the idea. The goal is to give you as much flexibility as possible when constructing your data structures, and this module figures it out correctly. The only disadvantage to the very last method is that since the top-level structure is a hash, you cannot control the order of the options.
If you're just looking for simple naming, see the
nameopts option above.
Finally, currently a single builtin options set is included:
STATE, which contains all 50 states + DC as 2-letter codes.
A synonym for the
force option described above.
If set to 1, the field must be filled in:
$form->field(name => 'email', required => 1);
This is rarely useful - what you probably want is the
validate option to
new().
If set, and there are options, then the options will be sorted in the specified order. For example:
$form->field(name => 'category', options => \@cats, sortopts => 'alpha');
Would sort the
@cats options in alpha order.
The terms "NAME" and "NUM" have been introduced to keep consistency with the
validate options. They are synonymous with "alpha" and "numeric", respectively. If you specify "1", then an alpha sort is done, again for simplicity.
Type of input box to make it. Default is "text", and valid values include anything allowed by the HTML specs, including "password", "select", "radio", "checkbox", "textarea", "hidden", and so on.
If set to "static", then the field will be printed out, but will not be editable. Like when you print out a complete static form, the field's value will be placed in a hidden field as well.
The
value option can take either a single value or an arrayref of multiple values. In the case of multiple values, this will result in the field automatically becoming a multiple select list or checkbox group, depending on the number of options specified above.
Just like the 'values' to
new(), this can be overridden by CGI values. To forcibly change a value, you need to specify the
force option described above, for example:
$form->field(name => 'credit_card', value => 'not shown', force => 1);
This would make the
credit_card field into "not shown", useful for hiding stuff if you're going to use
mailresults(). is that this needs to be easily usable can be passed to either
new() or
render() and which provides global defaults for all fields.
Wait a second, if we have
field() from above, why the heck would we ever need
cgi_param()?
Simple. The above
field() function does a bunch of special stuff. For one thing, it will only return fields which you have explicitly defined in your form. Excess parameters will be silently ignored. Also, it will incorporate defaults you give it, meaning you may get a value back even though the user didn't enter one explicitly in the form (see above).
But, you may have some times when you want extra stuff so that you can maintain state, but you don't want it to appear in your form. B2B and branding are easy examples:
This could change stuff in your form so that it showed the logo and company name for the appropriate vendor, without polluting your form parameters.
This call simply redispatches to
CGI::Minimal (if installed) or
CGI.pm's
param() methods, so consult those docs for more information.
This allows you to interface with your
HTML::Template template, if you are using one. As with
cgi_param() above, this is only useful if you're manually setting non-field values. FormBuilder will automatically setup your field parameters for you; see the "template" option for more details.:
print $form->confirm(template => 'success.tmpl');
So that you don't get the same screen twice..
This gets and sets the sessionid, which is stored in the special form field
_sessionid. By default no session ids are generated or used. Rather, this is intended to provide a hook for you to easily integrate this with a session id module like
Apache:);
This will cause it to be automatically carried through subsequent forms..
FormBuilder has the ability to "drive" several template engines:
HTML::Template Text::Template Template Toolkit
You enable a template by specifying the
template option and passing it the appropriate information. Then, you must place special tags in your template which will be expanded for you. Let's look at each template solution in turn.
HTML::Template is the default template option and is activated one of two ways. Either:
my $form = CGI::FormBuilder->new( fields => \@fields, template => $filename );
Or, you can specify any options which
HTML::Template->new accepts by using a hashref:
my $form = CGI::FormBuilder->new( fields => \@fields, template => { filename => $filename, die_on_bad_params => 0, shared_cache => 1, loop_context_vars => 1 } );, and this would be expanded to the complete HTML
<input> tag.
In addition, there are a couple special fields:
<tmpl_var js-head> - JavaScript to stick in <head> <tmpl_var form-title> - The <title> of the HTML form <tmpl_var form-start> - Opening <form> tag w/ options <tmpl_var form-submit> - The submit button(s) <tmpl_var form-reset> - The reset button <tmpl_var form-end> - Just the closing </form> tag
So, let's revisit our
userinfo.tmpl template from above:
=> [qw/1 0/], labels => {_var label></td> <td><tmpl_var field></td> </tr> </tmpl_loop> </table>
Each loop will have a
label,
field,
value, etc, just like above.
For more information on templates, see HTML::Template.
Thanks to a huge patch from Andy Wardley, FormBuilder also supports
Template Toolkit. This is enabled by specifying the following options as a hashref to the
template argument:
my $form = CGI::FormBuilder->new( fields => \@fields, template => { type => 'TT2', # use Template Toolkit template => 'form.tmpl' } );
By default, the Template Toolkit makes all the form and field information accessible through simple variables.
[% jshead %] - JavaScript to stick in <head> [% title %] - The <title> of the HTML form [% start %] - Opening <form> tag w/ options [% submit %] - The submit button(s) [% reset %] - The reset button [% end %] - Closing </form> tag [% fields %] - List of fields [% field %] - Hash of fields (for lookup by name)
You can specify the
variable option to have all these variables accessible under a certain namespace. For example:
my $form = CGI::FormBuilder->new( fields => \@fields, template => { type => 'TT2', template => 'form.tmpl', variable => 'form' }, );
With
variable set to
form the variables are accessible as:
[% form.jshead %] [% form.start %] etc.
You can access individual fields via the
field variable.
For a field named... The field data is in... -------------------- ----------------------- job [% form.field.job %] size [% form.field.size %] email [% form.field.email %]
Each field contains various elements. For example:
[% myfield = form.field.email %] [% myfield.label %] # text label [% myfield.field %] # field input tag [% myfield.value %] # first value [% myfield.values %] # list of all values [% myfield.option %] # first value [% myfield.options %] # list of all values [% myfield.required %] # required flag [% myfield.invalid %] # invalid flag
The
fields variable contains a list of all the fields in the form. To iterate through all the fields in order, you could do something like this:
[% FOREACH field = form.fields %] <tr> <td>[% field.label %]</td> <td>[% field.field %]</td> </tr> [% END %]
If you want to customise any of the Template Toolkit options, you can set the
engine option to contain a reference to an existing
Template object or hash reference of options which are passed to the
Template constructor. You can also set the
data item to define any additional variables you want accesible when the template is processed.
my $form = CGI::FormBuilder->new( fields => \@fields, template => { type => 'TT2', template => 'form.tmpl', variable => 'form' engine => { INCLUDE_PATH => '/usr/local/tt2/templates', }, data => { version => 1.23, author => 'Fred Smith', }, }, );
For further details on using the Template Toolkit, see
Template or
Also thanks to a user contribution, this time by Jonathan Buhacoff,
Text::Template is also supported.).
<% $jshead %> - JavaScript to stick in <head> <% $title %> - The <title> of the HTML form <% $start %> - Opening <form> tag w/ options <% ->{option}; # first option $myfield->{options}; # list of all options $myfield->{required}; # required flag $myfield->{invalid}; # invalid flag %> <% for my $field (@{$form{fields}}) { $OUT .= "<tr>\n<td>" . $field->{label} . "</td> <td>" . $field->{field} . "</td>\n<tr>"; } %>
In addition, when using the engine option, as in Template Toolkit, you.
I find this module incredibly useful, so here are even more examples, pasted from sample code that I've written:
This example provides an order form complete with validation of the important fields.
#!/usr/bin/perl -w use strict; use CGI::FormBuilder; my @states = qw(AL AK AZ AR CA CO CT DE DC FL GE); my $form = CGI::FormBuilder->new( header => 1, method => 'POST', title => 'Order Info', fields => [qw/first_name last_name email address state zipcode credit_card/], validate => {email => 'EMAIL', zipcode => 'ZIPCODE', credit_card => 'CARD'} ); $form->field(name => 'state', options => \@states, sort => 'alpha'); # This adds on the 'details' field to our form dynamically $form->field(name => 'details', cols => '50', rows => '10'); # try to validate it first if ($form->submitted && $form->validate) { # ... more code goes here to do stuff ... print $form->confirm; } else { print $form->render; }
This will create a form called "Order Info" that will provide a pulldown menu for the "state", a textarea for the "details", and normal text boxes for the rest. It will then validate the fields specified to the
validate option appropriately.
This is very similar to the above, only it uses the
smartness option to fill in the "state" options automatically, as well as guess at the validation types we want. I recommend you use the
debug option to see what's going on until you're sure it's doing what you want.
#!/usr/bin/perl -w use strict; use CGI::FormBuilder; my $form = CGI::FormBuilder->new( header => 1, method => 'POST', smartness => 2, debug => 2, fields => [qw/first_name last_name email address state zipcode credit_card/], ); # This adds on the 'details' field to our form dynamically $form->field(name => 'details', cols => '50', rows => '10'); # try to validate it first if ($form->submitted && $form->validate) { # ... more code goes here to do stuff ... print $form->confirm; } else { print $form->render; }
Since we didn't specify the
title option, it will be automatically determined from the name of the executable. In this case it will be "Order Form".
This is a simple search script that uses a template to layout the search parameters very precisely. Note that we set our options for our different fields and types.
#!/usr/bin/perl -w use strict; use CGI::FormBuilder; my $form = CGI::FormBuilder->new( header => 1, template => 'ticket_search.tmpl', fields => [qw/type string status category/] ); # Need to setup some specific field options $form->field(name => 'type', options => [qw/ticket requestor hostname sysadmin/]); $form->field(name => 'status', type => 'radio', value => 'incomplete', options => [qw/incomplete recently_completed all/]); $form->field(name => 'category', type => 'checkbox', options => [qw/server network desktop printer/]); # Render the form and print it out so our submit button says "Search" print $form->render(submit => ' Search ');
Then, in our
ticket_search.tmpl HTML file, we would have something like this:
<html> <head> <title>Search Engine</title> <tmpl_var js-head> </head> <body bgcolor="white"> <center> <p> Please enter a term to search the ticket database. Make sure to "quote phrases". => '/^\d{3}-\d{4}-\d{4}$/', pn => '/^\d{3}-.
There are a couple questions and subtle traps that seem to poke people on a regular basis. Here are some hints.
If you're used to
CGI.pm, you have to do a little bit of a brain shift when working with this module.
First, this module is designed to address fields as abstract entities. That is, you don't create a "checkbox" or "radio group" per se. Instead, you create a field named for the data you want to collect. FormBuilder takes care of figuring out what the most optimal HTML representation is for you. => [qw/Yes No/], value => 'Yes');
Now you'll get a radio group, and "Yes" will be selected for you! By viewing fields as data entities (instead of HTML tags) you get much more flexibility and less code maintenance. If you want to be able to accept multiple values, simply add the
multiple arg:
$form->field(name => 'favorite_colors', multiple => 1, options => [qw/red green blue]);
Depending on the number of
options you have, you'll get either a set of checkboxes or a multiple select list (unless you manually override this with the
type arg). Regardless, though, to get the data back all you have to say is: modify your code so you use FormBuilder exclusively.
Easy.
my $form = CGI::FormBuilder->new(sticky => 0, ...);
By turning off the
sticky option, you will still be able to access the values, but they won't show up in the form.
You must specify the
force option:
$form->field(name => 'name_of_field', value => $value, force => 1);
If you don't specify
force, then any CGI value will always win.
Remember that
render() can take any option that
new() can. This means that you can set some features on your form sooner and others later:
my $form = CGI::FormBuilder->new(method => 'POST'); my $mode = $form->cgi_param('mode'); if ($mode eq 'add') { print $form->render(fields => [qw/name email phone/], title => 'Add a new entry'); } elsif ($mode eq 'edit') { # do something to select existing values my %values = select_values(); print $form->render(fields => [qw/name email phone/], title => 'Edit existing entry', values => \%values); }
In fact, since any of the options can be used in either
new() or
render(), you could have specified
fields to
new() above since they are the same for both conditions. has been used pretty thoroughly in a production environment for a while now, so it's definitely stable, but I would be shocked if it's bug-free. Bug reports and especially patches to fix such bugs are welcomed.
I'm always open to entertaining "new feature" requests, but before sending me one, first try to work within this module's interface. You can very likely do exactly what you want by using a template.
Parameters beginning with a leading underscore are reserved for future use by this module. Use at your own peril.
This module does a lot of guesswork for you. This means that sometimes (although hopefully rarely), you may be scratching your head wondering "Why did it do that?". Just use the
field method to set things up the way you want and move on.
Due to too many incompatibilities with CGI.pm, unfortunately
CGI::Minimal is no longer used. Sorry. you
$ENV{PATH} at the top of your script. This is actually a good habit regardless.
For support, please start by visiting the FormBuilder website at:
This site has numerous tutorials and other documentation to help you use FormBuilder to its full potential. If you can't find the answer there, then join the mailing list by emailing:
fbusers-subscribe@formbuilder.org
To submit patches, please first join the mailing list and post your question or issue. That way we can have a discussion about the best way to address it.
This module has really taken off, thanks to very useful input, bug reports, and encouraging feedback from a number of people, including:
Andy Wardley Jakob Curdes Mark Belanger Peter Billam Brad Bowman Jonathan Buhacoff Godfrey Carnegie Florian Helmberger Mark Houliston Dimitry Kharitonov Randy Kobes William Large Kevin Lubic Robert Mathews Mehryar Koos Pol Shawn Poulson Dan Collis Puro John Theus Remi Turboult
Thanks!
HTML::Template, Text::Template, Template Toolkit, CGI::Minimal, CGI, CGI::Application
$Id: FormBuilder.pod,v 2.11 2003/07/11 18:08:12 nwiger Exp $
Copyright (c) 2001-2003 Nathan Wiger, Sun Microsystems <nate@sun.com>. All Rights Reserved.
This module is free software; you may copy this under the terms of the GNU General Public License, or the Artistic License, copies of which should have accompanied your Perl kit. | http://search.cpan.org/~nwiger/CGI-FormBuilder-2.11/FormBuilder.pod | crawl-002 | refinedweb | 7,002 | 61.77 |
Current Map implementation moves map to Rome by default (albeit Rome, Italy is a cool city), but many times you want to move it to a different and specific position.
Which means the control will be updated twice instead of just once, wasting draw cycles.
Making the control not go to the default location requires some work and investigation which is completely unnecessary.
I don't understand the decision to have a default location.
MoveToRegion(MapSpan mapSpan)
On all platforms the native map control has a way to animate when moving the map position. All current renderers in Xamarin Forms already use an animation value when moving the position on the native map.
The
Xamarin.Forms.Map control should have the
bool animate parameter in the
MoveToRegion(MapSpan mapSpan):
void MoveToRegion(MapSpan mapSpan, bool animate = true)
+1 to this, I have implemented maps into a recent application and I find the loading time is a little slow and I'm looking into ways to speed it up.
If a user is displaying the map, chances are they are wanting to show a specific region so would it not make sense to make a mandatory parameter to pass in the location you want the map to display? Just a suggestion
@seanyda Both can be a reason for a slower loading time. If someone from Xamarin team approves this, I could make a PR.
There's also a bug I found with Map,
MoveToRegionis buggy.
It doesn't make sense to start working on a PR without having OK from the XF team first, otherwise I risk working in vain.
I hope Xamarin team really looks at this forum...
I wish this forum had a way to vote so people could give their votes ...
I am facing the same problem... Any fix for this ? i do not want to center my map in Rome !
You don't have to. There is a method to move it:
Just replace the above latitude and longitude in the position parameter.
This thread is discussing how to improve the maps.
note: you can also set the start-up map location in XAML if you need that
@ChaseFlorell Correct, but that is very very ugly. Why would I need to do that in any place, any project where I need a Map control?
because the Map Constructor is the only place to set a different "initial location". This makes it so that you don't have to use
MoveToRegionafter the map is constructed. If you don't do it in the constructor, then you have to move the map away from Rome.
@ChaseFlorell So you do not agree with not having the Map take a default location?
99.999% of the Xamarin Forms apps which use the Map control will not want to have Rome, Italy as default location.
Do you think it's nice to ask every developer to write that ugly XAML to initialize the map to something else?
Another issue is you can't even bind the start position.
To get round it (as the geopos data is resfful and can be slow to come from our provider), I only create the map when the data arrives.
Been able to set a default and bindable would be very nice.
I personally like the constructor, and even with the "ugly XAML", I feel it's a perfectly acceptable approach. Basically, if you need a start position on your map, that's what you use. If nothing else, I wish the
VisibleRegionproperty were set to TwoWay binding instead of OneWayFromSource.
As for having it Bindable, I've written my own Map Renderer, and have made the
VisibleRegionwork exactly like that. Under the covers, I use
MoveToRegion(VisibleRegion);when the binding updates. This now allows the developer to update the VisibleRegion from the ViewModel, but also get the VisibleRegion back from the map if the user moves the map.
We're pondering investing the time in doing something similar as we don't want to add more nugets but it should be bindable out of the box quite honestly. The map has had very little features added since Forms 1.3.
It was pretty straight forward actually. I just made the
VisibleRegion propertynew
and changed it's binding toTwoWay`
Then I detect which way the binding is coming from, blocking the infinite loop when you bind from the property.
The native Map controls do not have a default position.
And beside that, can you give me an example in the whole XAML platform where a control has such a "personal" default value? This isn't something like text color with the default to Black or background color.
I wish there shouldn't be a need to write custom renders for such basic things.
In our scenario, our business services a specific region. So constructing the map with a specific location works well for us. We show the boundaries of our service area by default and move the map if necessary after the fact. (using the User's GPS location).
If your service area is larger, then I suggest using that.. IE: if you service the entire USA, then use the entire USA as your starting point, and
MoveToRegion(loc);from there. Similarly, if you service the entire planet, you can start with a top view of the entire planet and
MoveToRegion(loc);from there.
At any rate, I think the conversation is off topic now. Let's leave it for the X.F team to decide.
-1 from me.
@ChaseFlorell My understanding of this proposal is there is a very slim chance that you want the location of your map to be on Rome, so the chances are you will be passing in the location you want it to display... So the map has to do multiple draw cycles instead of a single one. What's the disadvantage of creating a mandatory parameter to make the user provide the location they want the map to display which will improve performance because it won't have to go to Rome then elsewhere every time?
Or am I misunderstanding the proposal?
The misunderstanding is that the map already has this. It's part of the constructor and you can set the initial load location to anywhere you want. The OP says that it's "ugly XAML", so if the proposal is to make it prettier, then maybe I misunderstood, but as it stands, #1 in the list already exists.
There are two constructors for a map
If you don't want to center on Rome, you don't have to... you can center on anything you like.
@seanyda said:
You got it right Sean. But Chase keeps arguing it's perfectly fine to have Rome, Italy (why Rome and not Tokyo or New York?) , so I surrender.
Should I hold my breath?
Xamarin/MS should just invest in GoogleMaps
X.F Maps is woefully inadequate for even basic things like working with pins. For example, pins need an ID, otherwise I have no idea which pin is being used when tapped. Sure, the pins Clicked() event can be wired up, but now which pin was clicked, exactly? Even if I get the whole object from the sender, I have no idea which is which if I have a collection that came from a programmtic list with IDs. And where are other events on the map, such as pins being selected, camera moving, etc.?
Digging in the forums, people have been asking for a simple pin ID property since at least 2013!
Speaking of programmatic, I need to be able to select pins programmatically too. All this is already in amay077 GoogleMaps. HOWEVER, even that project suffers because UWP support is not par (and desperately needs to be).
Mapbox for Xamarin is superior to all of this in terms of features, but with no UWP or macOS support at all, that is a dead, unusable map too IMO.
Maps should also support macOS apps now that Mac can be targeted with X.F. X.F is all about all supported platforms, not a subset.
All things considering, mapping of any kind on Xamarin Forms is leaving us all wanting more. Much more!
@dapug Instead of each of us doing islands of implementations, there should be pull-requests. But unfortunately Xamarin doesn't encourage participating, they look very late at PRs, so someone working on a PR could end up doing work in vain.
only this for the map:
Then in my view Model I have the following which allows me to use pure binding and no custom renderer.
public class LocationHistoryViewModel: BaseViewModel
{
public LocationHistoryViewModel()
{
// Set the bindable Map
LocationHistoryMap = CreateMap();
}
One thing I would like to ask @NMackay is why doesn't the map api provide the current location? It is seems like you would know what it is since I can set IsShowingUser = true and it shows My Location.
this:
Then in my view Model I have the following which allows me to use pure binding and no custom renderer.
One thing I would like to ask @NMackay is why doesn't the map api provide the current location? It is obvious that you know what it is since I can set IsShowingUser = true and it shows My Location.
I get an error:
Position 15:18. Type Position not found in xmlns C:\Users\User\source\repos\Test\Views\PSFinder.xaml
And I also don't know how to do it on the code-behind because I use:
protected override async void OnAppearing() { base.OnAppearing();
I want to center the map to somewhere else and not Rome for both iOS and Android devices. I use MoveToRegion but it still centers on Rome before moving to the region I prefer after a couple of seconds.
My map in XAML:
<maps:Map x:
I'm having issues with this map. Like why can't the default location be the current location of the device?
Or why can't i locate myself?
isShowingUsercrashes my app
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
//Best practice to always check that the key exists
if (results.ContainsKey(Permission.Location))
status = results[Permission.Location];
} | https://forums.xamarin.com/discussion/comment/303610/ | CC-MAIN-2020-10 | refinedweb | 1,711 | 64 |
>>.
Microsoft vs. Sun (Score:5, Informative)
Uh... what? (Score:3, Informative)
Re:Microsoft vs. Sun (Score:2)
Oh, Microsoft IS shipping with HD-DVD... (Score:3, Informative)
Don't believe Microsoft would be so stupid? Read this [cooltechzone.com]!
As the saying goes - Game Over, Man! And not for Sony.
And for cross-reference, Balmer said as much (about the eventual inclusion of HD-DVD) when interviewed by Engadget way back in May. Actually what he really said then was they could go other way, but the link I provided seems to indicate which way they are swinging - and is anyone surprised it's whatever Sony is NOT doing?
thank god (Score:5, Interesting)
Re:thank god (Score:2, Insightful)
Re:thank god (Score:2)
Okay, this is much more likely to happen on the PSP, since everyone is running (roughly) the same code. But if there are obvious enough cracks [seattlewireless.net], even more obscure appliances will be cracked.
Re:thank god (Score:2, Insightful)
-Peter
That'll learn 'em! (Score:2)
I suggest breaking copyright law and aquiring a better copy.
Or a bloody coup... ya know... whichever.
Re:thank god (Score:4, Funny)
Re:thank god (Score:3, Funny)
Gives a whole new meaning to "Every man should know where his towel is".
Re:thank god (Score:2)
Re:thank god (Score:3, Interesting)
Re:thank god (Score:3, Informative) [dvd-replica.com] [dvd-replica.com] [wikicities.com]
(brief descriptions of the current DVD VM commands).
Great! (Not) (Score:2, Insightful)
Re:Great! (Not) (Score:5, Insightful)
Re:Great! (Not) (Score:2)
Re:Great! (Not) (Score:5, Informative)
b) Java isn't interpreted anymore... its just-in-time compiled and then executed as native code. A bit of a start-up pause while the classes compile, that's all.
Re:Great! (Not) (Score:2)
Show me a cell phone whose apps are 95% written in Java, and it's reasonably speedy and the battery life doesn't suck.
I'll give you a hint. I work at a company where far too much money has been spent trying to do develop this several different times. CPU's are getting closer to making this worthwhile, but so far I've just seen spectacular failures.
(I might behind the times... there might have been some decent java phones released recently
Re:Great! (Not) (Score:4, Informative)
Java actually wasn't designed for generic 'embedded systems', it was designed for set-top boxes, but it was apparently too expensive for the prospective customers.
So this was Gosling's original intent. I don't know whether it's good or bad that it's now fulfilling that intent. I'd rather see Ruby in the standard, it'd be a lot easier to work with (and cheaper to license)..
Nope. (Score:2)
Re:Great! (Not) (Score:3, Informative)
In Tivo's case, it actually is Java. The interface used to be very quick and snappy. Then they decided to push the Home Media Option out to all users, and the same quick, responsive UI has now slowed down to a horrible crawl. The hardware didn't change at all, only the software.
As for the poster making the crack about putting Windows Mobile on a b
Re:Great! (Not) (Score:5, Informative)
The problem with your reasoning is that the quick and snappy UI was also in Java.
The future is now. (Score:3, Interesting)
I believe they're already essentially here, in the form of previews - some of which are unskippable - before you can even get to the menu. (Not Flash, but obviously still something very, very wrong.)
Look on the bright side... (Score:5, Insightful)
Well, at least they'll take up less space than the current annoying MPEG2 intros...
games on dvd player (Score:2, Funny)
Re:games on dvd player (Score:2, Funny)
Re:games on dvd player (Score:2)
Misconceptions, as usual (Score:5, Insightful):Java IS sux (Score:4, Informative)
Yes, because, like, no-one uses E-Bay, banks, stock-markets, airline on-line booking systems.
I'm sure the majority of people couldn't give a hang about these.
Re:Java IS sux (Score:2)
Re:Java IS sux (Score:2)
I am simply pointing out what Java can do.
Other than people who work in that industry no end-user cares a damn about what goes into running enterprise (god I HATE that word) solutions. Stop trying to pretend otherwise. You act like every little pleb out there owes a big thank you to people who write this crap in Java, ASP,
But they do. These systems are designed because they c
Re:Java IS sux (Score:2)
Re:Java IS sux (Score:2) fin
Re:Java IS sux (Score:3, Funny)
Bob
Re:Misconceptions, as usual (Score:5, Informative)
As shown by Linpack benchmarks run last year, Java can run at up to 95% of the speed of optimised C++.
and eats memory like there's no tomorrow.
Embedded Java systems can run in as little as a few hundred KB of memory.
This is going to seriously hinder blu-ray adaption.
Just as the use of Java on mobile phones has (not) hindered the production of Java games and applications for those phones?
A Java implementation means at least 30% more processor power and memory than otherwise needed.
Why not look at the real situation and not present a years-old outdated view of Java?
Re:Misconceptions, as usual (Score:2)
More to the point: many many cell phones these days include PJava/KJava, with a huge number of APIs [nokia.com]. And if you stick a decent graphics library onto a language, even perl can be used to generate very responsive graphics [frozen-bubble.org].
Re:Misconceptions, as usual (Score:3, Informative)
Ok. Let's take an obscure rare example like... E-Bay!
The entire site is written in Java. It is one of the most high-performance, reliable and successful websites ever written. Your bank uses Java. All major stock exchanges (with tens of thousands of transactions per second) use Java.
It takes forever to fire up due to the V
Re:Misconceptions, as usual (Score:3)
That is the remnant of their legacy system. E-Bay discarded their original C++ ISAPI system and moved to Java/J2EE running on WebSphere years ago. l
Re:Misconceptions, as usual (Score:2)
My view (and I could be wrong) is that most developers don't care. The zero financial price is the real reason for it's success.
Then there's the fact that it is slow when compared to most other languages which are used for designing large scale systems (C, C++, etc.).
This hasn't been true for years. I don't understand why this myth persists when almost all benchmarks have shown equivalent Java code to be within 80-100% of C,C++ speed for some time.
Re:Misconceptions, as usual (Score:2)
Re:Misconceptions, as usual (Score:3)
import java.applet.Applet;
import java.awt.Graphics;
public class ItsBoth extends Applet {
String message = "";
public void paint(Graphics g) {
g.drawString(message, 50, 25);
}
public init() {
message="It's a floor wax!";
}
public static void main(String[] args) {
System.out.println("It's a Dessert Topping!");
}
}
Re:Scope widening too far? (Score:2)
Re:Scope widening too far? (Score:3, Informative)
Why?
and the ability to run java bytecode when the discs boot could allow a whole new range of lockdown facilities on the disks.
How is this different from running any other software when the discs boot? The use of Java bytecode has no relevance to lockdown.
Not to mention the amount of complexity having network & JVM functionality must be introducing to the end units. Surely even mass production wil struggle to bring such complex devices down to sane pric
Re:Scope widening too far? (Score:2)
You're kidding, right? Building a unit that can use Java for network connectivity and menus won't be very expensive. Your average TiVo box or PDA has more horsepower than they need for that, and I don't see a lot of problems with mass production of those.
I'd expect next-gen DVD players to enter the market at around a $200 price point anyways.
Seems very unlikley (Score:5, Insightful)
There may be some specialized discs that do something like this but I don't not think it will be mandatory.
Interesting things - how to kill a console (Score:2)
Since the HD-DVD drives probably won't be ready by the time Xbox 360 is available in retail channels, Microsoft said it would ship the console initially with regular DVD drives and then revise the console with HD-DVD drives once they are ready.
Yes, Microsoft is prepared to Osbourne its console!!! Who will buy the launch units when HD-DVD units (which you know some interesting games will make use of later on) will be out later?
I was amazed that Microsoft.
Re:One of my absolute top peeves (Score:5, Interesting)
Publicists should be shot.
Re:One of my absolute top peeves (Score:2)
Re:One of my absolute top peeves (Score:2)
I live in region 4 aswell, but we usually see a lot of DVDs for other regions (the wonders of region-free players!)
A way around... (Score:2)
Re:A way around... (Score:2)
Your player may just not honor the UOP (User Operation Prohibited) part of the DVD spec. But that is a totally cool violation with me.
And the worst bits (Score:2)
Some of the Thomas the Tank Engine videos my three-year old is in love with have 3 seperate, unskippable "We made this!" snippets, along with the FBI warning and two trailers. (At least the latter are skippable.)
Now add in menus that have to go through the entire minute plus animation before responding, it can easily take three minutes from disc insert to viewing the video. Ever waited with a three year old desperate for his fix for that long?
HULK WANT TO SMASH!
Re:One of my absolute top peeves (Score:3, Informative)
Video Help [videohelp.com] is your friend - look up your dvd player and crack it. Chances are good your player is easily hackable to disable the unskippable crap. If yours isn't on the list, at least you now have a list of what DVD players to consider buying when you want to upgrade.
Re:One of my absolute top peeves (Score:2)
Hell, since I moved away from my parents' house they no longer rent DVDs. Yep, back to VHS, because they find DVD menus too confusing and frustrating. They don't care about special features or better image/sound quality, so for them DVDs were only a step backwards. And I'm sure they're not the only ones who feel that w
I Completely Agree (Score:2)
DVD menus should be completely declarative, and the exact layout should be decided and implemented by the player. This would allow for players which can attempt to read the menu captions out for blind viewers, among other benefits. It would also mean that they would by necessity be less flashy and annoying, and they'd work the same for every DVD. It wouldn't work the same on every DVD player, but then people might start shopping for DVD players based on who has the best UI, which would be fine by me.
Re:I Completely Agree (Score:2)
Seriously, I didn't think blind people would listen to movies... seems like a terribly boring thing to do.
Re:I Completely Agree (Score:2)
Re:One of my absolute top peeves (Score:2)
Re:One of my absolute top peeves (Score:2)
Now with Java coming I'm sure we can look forward to a whole new universe of sluggish, buggy interfaces. I forsee a day when it doesn't just take 5 seconds to go from screen to screen, but it there is a maddening delay between moving the selection from one item to another on the SAME screen. That will be SWEET.
(M
Re:One of my absolute top peeves (Score:2)
Re:One of my absolute top peeves (Score:2)
First off I agree that many menus are obnoxious, and not straight forward to the user. There is also a lot of overuse of video clips going into and out of menus.
However, when you purchase a movie/TV show/etc. you are buying a creative piece. You may not consider it art, but the people who create it do. They (and in many cases 'they' refers to the studios more than the producers/directors/actors/etc but the studios do also own creative rights to the work), they have the right to create a who
Re:One of my absolute top peeves (Score:2) int
Re:Not Java but JVM. (Score:2)
You sure you're not thinking of
Re:Not Java but JVM. (Score:3, Interesting)
Re:Not Java but JVM. (Score:3, Informative)
While there are a number of ways to generate Java bytecode from code that is not Java, these ar
Re:Not Java but JVM. (Score:3, Insightful)
Untrue. The Java-GCC backend can be used now, for significant program. For instance, Fedora 4 ships the Eclipse IDE compiled using GCC.
Untrue. JDK 6.0 will include an API to use scripting languages directly, and will include a Javascript-on-Java implementation. There is also Project Coyote (scripting languages on Sun's Netbeans IDE),
My DVD player already has Flash. (Score:4, Informative)
The playstation 2 already has a flash player in it, used by various games for their menu systems among other things.
I guess game companies try not to annoy their customers, so Flash gets used reasonably there.
Re:My DVD player already has Flash. (Score:2)
I should have phrased that as "There is a flash player available for the playstation 2", but it isn't built-in.
Apparently, it was used in "Star Wars Starfighter" (
Java DVD Player + network connection + Azureus (Score:3, Interesting)
Could be much nicer for DVD content creation apps (Score:5, Informative)
At the very least those games they always throw on kids DVD's might not be so awful to play if they do not have to be shoe-horned into a system never really designed for games.
More integration... (Score:2)
This convergence thing is really starting to go too far. Does anyone else agree, or do people actually want all your products to do a gazillion things?
They already have games today (Score:2)
I use the term loosely because the games are hampered by the fairly horrific need to use the DVD menu system to play them. This makes for really annoying games, even if you like the basic concept.
In the DVD release of National Treasure, they had actually kind of a cool little movie/game, that was trying to interactively demonstrate different forms of encryption. It had some kind of interesting activities
DVD's With Really Cool Win95 UI (Score:2)
It sounds like they want some kind of time shifting device that's network enabled. Let's see, time shifting? Yup done. Now networked media device? Yup done.
So that means my mega-corporation will make a device that will be higher priced that no one will buy because the price is too high and the feature set too vague! "Let's
Glad to hear it (Score:2)
So... are there details anywhere? (Score:2)
Finally... (Score:2, Funny)
I can see it now (Score:3, Funny)
"NullPointerException? WTF?"
now will someone port MAME to java? (Score:2)
In 2020.. (Score.
This is ancient news and lousy planning (Score:4, Informative)
Every DVD player comes equiped with its own CPU, and even its own assembly code that is a part of the DVD-Video specification. This is already a part of the DVD-Video spec from even the very beginning. The problem is that Hollywood (together with the other members of the DVD Consortium... now DVD Forum) deliberately crippled the CPU so that it could in reality do very little. I've described this CPU has having 26 registers, no RAM at all, and 1 TB ROM address space, with incredible video capabilities but lousy rendering capabilities (sub-pictures).
Frankly, I think the DVD Forum blew their chance at having a cheap consumer entertainment computer back when the original design was put together back in the mid 1980s. If the CPU would have even had just a little bit more computing power, including a small (even 64 K) amount of RAM and text rendering capabilities (nothing new or even expensive to implement back when the design was being put together) they would have had not only a movie playing machine, but a computing platform that would have been more widely distruted than the X-Box or Playstation.
Even before the DVD-Video 1.0 spec came out (it was at a beta 0.98 when I mentioned this) I was suggesting to the design committee for DVD-Video to incorporate Java into the specification. Even then (about 10 years ago) I felt that some sort of programming environment would have been both easy to implement and offer to make DVD-Video something well beyond a simple movie playback box. Obviously my idea fell on deaf ears. Too bad I didn't patent the idea (perhaps I should have).
The DVD Forum will probabaly screw this one up as well, but at least they are going down the right general direction. IMHO there is no reason to make it specific to the Blu-ray format except as a splash to make the new generation of players seem to have more capabilities. Existing DVD discs certainly could be using this same capability, and there is plenty of space on a DVD for some binary (even raw source code) programming instructions, with a full two hour movie..
Re:Ethernet port (Score:2)
Re:Ethernet port (Score:2)
Re:Ethernet port (Score:2)
You know, not every household has a ethernet hub directly connected to the internet. What makes you think it would require that? Now, if they come standard with phone jacks, perhaps you may have something to worry about.
Also, the java VM may be part of the standard. That means, to play HD dvd content, you will need to use a player that adopts the standard. Is your $100 DVD player going to play the 40GB+ HD content dvd's? I don't think so.
Re:The only appliances that are fit for Java: (Score:2, Funny)
Re:Java and Linux... (Score:2)
Show me a version of Linux that can run within a few hundred kilobytes of memory, like embedded Java, and I might agree you have a point.
Re:Java and Linux... (Score:2)
The Java that runs E-Bay - the most profitable website ever. I think you may have to concede the point.
Re:slashdot finally through (Score:2)
Better not buy any new mobile phone then. Virtually all of them come with Java.
Re:ARG (Score:3, Informative)
It may already be there: | https://developers.slashdot.org/story/05/06/28/2319213/java-to-appear-in-next-gen-dvd-players | CC-MAIN-2017-09 | refinedweb | 3,218 | 72.56 |
AutoIt is a scripting language that came about from the requirement to automate Windows GUI actions. It is commonly used to solve installation issues but that is not of much interest to us. What is a little more interesting is some of the functionality of AutoIt is available to external programs through AutoItX.
This comes as a DLL (well two, a 32- and 64-bit version) which you can call a function from or register the DLL to get a COM server. In this article I will use the COM interface which is documented nicely in the accompanying help file.
If you installed the whole AutoIt package it should register the DLL for you. If not change into the directory with the DLL and type in regsvr32.exe AutoItX3.dll (or AutoItX3_x64.dll for a 64-bit OS).
To check whether everything is set up correctly try the following example code. It just moves the currently active window to the top left hand corner of the screen. Gimmicky but fairly short.
import win32com.client aitcom = win32com.client.Dispatch("AutoItX3.Control") # get currently active window title and its x & y position wintitle = aitcom.WinGetTitle("") startx = aitcom.WinGetPosX(wintitle) starty = aitcom.WinGetPosY(wintitle) # tool tip - stays on the screen until cleared aitcom.ToolTip("Currently active window: "+wintitle,startx+25,starty+25) # move window to top left hand corner in steps steps = 10 x = range(startx,0,-startx//steps) y = range(starty,0,-starty//steps) for i in range(1,steps): aitcom.WinMove(wintitle,"",x[i],y[i]) aitcom.WinMove(wintitle,"",0,0) aitcom.ToolTip("") # clear tool tip
Look through the documentation for more functionality and experiment. | https://quackajack.wordpress.com/2013/04/ | CC-MAIN-2018-47 | refinedweb | 274 | 59.09 |
Introduction
The menu is an essential component for most CMS, with Wagtail, we can build powerful menu component as we like. But right now there is no good tutorial talking about this feature with Wagtail, so I decided to write this article to help people.
In this Wagtail tutorial, we would learn how menu in Wagtail works, and how to create a powerful menu using
wagtailmenus package.
Note: source code of this tutorial is available at wagtail-bootstarap-blog
Prerequisites
If you have an existing Wagtail project, that would be good to go, if you are new to Wagtail. I recommend you to check wagtail-bootstarap-blog , this project is developed exclusively for my Wagtail tutorial series, it is a standard blog which is based on Bootstrap theme and Wagtail.
We would use python shell to help us inspect some object, so
IPyhon is recommended to install in your env. You can do this by using command
pip install ipython
Step 1 — Inspect Page object in Wagtail
Next lets' first start to inspect page objects of our wagtail project, we can do this by entering Django shell.
Django shell is just like the Python prompt, but with some additional Django magic. :) You can use all the Python commands here too
# cd to root directory of your Wagtail project $ python manage.py shell Python 3.5.0 (default, Aug 17 2017, 10:54:23) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]:
Now we entered the Django shell, and we can write code and check the output at the same time.
We try to check the detail of
Page model in Wagtail, and find out there is something interesting, you can use the same method to check other fields of Wagtail Page.
In [1]: from wagtail.core.models import Page In [2]: Page? Init signature: Page(*args, **kwargs) Docstring: Page(id, path, depth, numchild, title, draft_title, slug, content_type, live, has_unpublished_changes, url_path, owner, seo_title, show_in_menus, search_description, go_live_at, expire_at, expired, locked, first_published_at, last_published_at, latest_revision_created_at, live_revision) File: ~/.pyenv/versions/wagtail_projet/lib/python3.5/site-packages/wagtail/core/models.py Type: PageBase
The
? behind Page model is an built-in operation from IPython, it can help us quickly get the detail of any object of Python.
As we can see from the output above, there is a field
show_in_menus in Wagtail
Page definition, if you check the Wagtail admin, you can find out that it is in
Promote tab.
So if we want to make some pages to display in menu component, we need set the
show_in_menus value to
True, then write code to filter them and render the pages in template.
Step 2 — Basic Menu Implementation
Now we try to implement a very basic top menu in our blog. It would display some specific pages such as
about,
welcome pages.
First, we try to add code
get_context of our
BlogPage model,
def get_context(self, request, *args, **kwargs): context = super(BlogPage, self).get_context(request, *args, **kwargs) context['posts'] = self.posts context['blog_page'] = self context['menuitems'] = self.get_children().filter( live=True, show_in_menus=True) return context
What you should notice is the
menuitems here, we use Django query to help us find the all live, menuable pages in the blog.
Next, we try to print the menu out in our template. So the template should look like this.
<ul class="nav navbar-nav"> {% for menu in menuitems %} <li> <a href="{{menu.url}}">{{menu.title}}</a> </li> {% endfor %} </ul>
If you do it in
wagtail-bootstrap-blog, so the effects should look like this. If you do not see any links in the menu, please make sure you have set the
show_in_menus of page to True.
Step 3 — Change page order in Wagtail menu
Wagtail has built-in support for page order, so if you want to change the link order in the menu, just change the page order in Wagtail admin.
After you are done with the page order, then refresh the blog page, link order should also be modified as well.
Step 4 — Install wagtailmenus
Now you have a good understanding of how menu in Wagtail works, so I'd like to give you a better solution for you to build menu in your Wagtail project.
It is wagtailmenus
Here I'd like to show you how to import it into our Wagtail project to generate the top menu for us.
pip install wagtailmenus
Then add settings below to the
INSTALLED_APPS of your project settings.
INSTALLED_APPS = [ ... 'wagtail.contrib.modeladmin', # Don't repeat if it's there already 'wagtailmenus', ]
Then add
wagtailmenus.context_processors.wagtailmenus to the
context_processors in your
TEMPLATES. So your template settings would look like this.
'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtailmenus.context_processors.wagtailmenus', ],
After all config done, run
python manage.py migrate wagtailmenus to config the database.
If you meet problem in this step, please check the wagtailmenus official doc for more detail
Step 5 — Render menu using wagtailmenus
Now we start to use
wagtailmenus to help us build a top menu. It would contain links of the blog post, and some external link (surprise? ^_^).
We enter to our Wagtail admin, then goto
/settigns/main menu/
In this page we can choose page from our Wagtail application, or insert external link, and change the link text of our menu.
After we config the menu, now we start to modify our template to render the data of the menu.
Edit template
blog/templates/blog/base.html
{% load menu_tags %} <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!--="{{ blog_page.url }}">{{ blog_page.title }}</a> </div> {% main_menu template="menus/bootstrap3/main_menu_dropdown.html" %} <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav>
There are some things you can notice here.
{% load menu_tags %}to make Django tag in wagtailmenus can be found.
main_menuis used to render menu we just created, the
templateparameter is to how menu is generated.
wagtailmenushas built-in templates for bootstrap3, you can modify it as you like.
wagtailmenushas many powerful Django tag for us to render menu in a quick way. Main menu is supposed to generate the most important menu for you and the menu data is saved in db. If you want to generate menu from Wagtail pages dynamically, you can check
section_menuor
children_menu
The final result of our blog would look like this
Conclusion
In this Wagtail tutorial, we've learne how menu in Wagtail work and how to build powerful menu using wagtailmenus package
Now, where should you go next? Here are some suggestions.
- You can start importing
wagtailmenusto your Wagtail project for better menu management.
- You can checkout wagtail-bootstrap-blog to get the source code of this Wagtail tutorial
- If you want to know more about Wagtail, you can check my Wagtail Tutorial Series | https://www.accordbox.com/blog/wagtail-tutorial-12-how-create-and-manage-menus-wagtail-application/ | CC-MAIN-2019-43 | refinedweb | 1,142 | 61.97 |
Basic class to show how to implement own algorithms. More...
#include <pitchraise.h>
Basic class to show how to implement own algorithms.
This class will calculate an equidistant tuning curve.
Definition at line 39 of file pitchraise.h.
Constructor of the pitch-raise algorithm.
Definition at line 53 of file pitchraise.cpp.
PitchRaise::algorithmWorkerFunction.
This is the main worker function of the Pitch-Raise algorithm which is executed in an independent thread. All computations are carried out here. The main parts are the following. First the recorded keys are identified. their measured inharmonicity is loaded and the logarithm is taken. The assumption is that this logarithm varies linearly with the key index in both diagonal sections of the strings. Therefore, an ordinary linear regression is carried out. This allows one to define an approximated inharmonicity for all keys (implemented as a lambda function). With this data a tuning curve is computed by a mixed 4:2 6:3 ... tuning, similar to the initial condition in the entropy minimizer. The whole process is artificially slowed down (msleep) in order to show how the tuning curve grows.
Definition at line 116 of file pitchraise.cpp.
Update the tuning curve for a given key number.
This function translates the actual mPitch value into the corresponding frequency, stores the value in the local piano copy mPiano and sends a message that the tuning curve has to be redrawn.
Definition at line 73 of file pitchraise.cpp.
Update the entire tuning curve.
This function translates the all mPitch values into the corresponding frequencies, stores the values in the local piano copy mPiano and sends a sequence of messages that the tuning curve has to be redrawn.
Definition at line 89 of file pitchraise.cpp.
Definition at line 52 of file pitchraise.h. | http://doxygen.piano-tuner.org/classpitchraise_1_1_pitch_raise.html | CC-MAIN-2022-05 | refinedweb | 297 | 59.9 |
I am often confronted with unwanted dialogues popping up when I am trying to drive some application programmatically. In Revit, many dialogues raise an event when they are displayed and allow us to implement an add-in application to handle them automatically. Unfortunately, as noted in the discussion on using the DialogBoxShowing event, some of the Revit dialogues do not raise such an event when displayed, so we cannot use the standard Revit API to handle or dismiss them.
Also, there are many other applications besides Revit that I am trying to drive programmatically, and they often do not provide any API at all, let alone a possibility to disable or automatically handle any of their user interface message boxes.
Furthermore, there may be situations within Revit where the DialogBoxShowing event is raised and the dialogue can be handled, but this causes problems within Revit. For instance, one developer reports that the DialogBoxShowing event handler crashes when trying to hide the dialog using an override result after the dialogue has been triggered due to closing a transaction using EndTransaction. In that case, Revit says that the document was modified outside the transaction and generates an exception.
Question: What can I do to automatically handle or dismiss dialogues in these situations?
Answer: As said, most Revit messages can be caught and responded to programmatically by a plug-in application by handling the Revit dialogue box DialogBoxShowing event, and source code and a description for exploring this kind of situation is provided in the discussion mentioned above.
The easiest way to find out whether you can use this event to handle your specific dialogue is to:
- Implement and install the dialogue box handler.
- Set a breakpoint in the event handler.
- Reproduce the situation in which the dialogue is displayed by Revit.
- Check whether the event was fired or not.
Inside the event handler, the debugger will show you what data is being passed in and thus how you can identify this dialogue in your code for automatic processing.
On the other hand, if the specific dialogue you are confronted with is not accessible in the Revit call-back, or you are dealing with some completely different application lacking the DialogBoxShowing event, I will explain below how you can use the .NET framework in C# and VB or the native Windows API to handle it automatically instead. In short:
- In the .NET framework, you can use methods from the WinApi.User32 namespace like FindWindow, EnumWindows, and GetWindowText from inside a System.Timers.Timer instance to determine that a certain window is being displayed by the Windows OS and close it using WinApi.User32.SendMessage.
- In the native Windows API, similar functionality can be achieved by creating a hook in the main Revit window with SetWindowsHookEx and sending a WM_CLOSE or some other message to a dialogue when it is displayed.
.NET Dialogue Clicker in C#
Here is the C# source code and entire Visual Studio solution for a little utility named JtClicker that I have used many times in the past and is very near and dear to me. It was especially useful during my time in Autodesk Consulting, when we were always automating a large number of different applications which unfortunately were equipped with user interfaces as well as APIs. The user interfaces would often insist on popping up various irritating dialogue boxes which could not be suppressed programmatically.
The solution that I developed for this is a Windows API based stand-alone command-line utility that simply sits and waits for a dialogue with certain characteristics to appear. If and when such a dialogue is displayed, the utility immediately dismisses it in a certain predefined way.
This solution I implemented is thus a generic dialogue clicker in C# using the .NET framework to access the underlying Windows API. In fact, it has nothing at all to do with the Revit API.
Since every dialogue is different, we need a lot of flexibility in the details of identifying and handling various specific dialogues. The two main requirements for a high degree of flexibility are:
- How to identify that the dialogue we are interested in has been displayed.
- How the dialogue should be dismissed, once it has been identified.
Therefore, this utility will always require some tweaking before use and is only useful in source code format for that reason. Check out the source code and the following discussion I had on that topic with my colleague Greg Wesner of Autodesk Consulting for details:
.NET Dialogue Clicker in VB
I was prompted to dive into this subject again recently by Greg Wesner of Autodesk Consulting. Here is an example of my interaction with him when he made use of JtClicker, in which Greg also provides a VB version of the original C# implementation:
[Q] I heard you might have a sample of code for how to 'spoof' a click of the OK button in a windows dialog. Specifically, I need to launch the options dialog in AutoCAD and then close it immediately with an OK click, i.e. I cannot cancel it. Closing the dialog with OK results in AutoCAD refreshing all the paths. Launching is obviously no problem but the OK click is tougher. I'm working in VB.NET, so a .NET sample is really what I'm after.
[A] Yes, I am appending my little dialogue clicker to this mail. There are comments inside form1 explaining its function and usage. It searches for a dialogue using certain characteristics. Once the dialogue appears, it sends windows messages to it in EnumChildProc. You will need to tweak those messages to hit the button you need.
[Q] Thanks Jeremy. That was exactly what I needed. Hooked it all up and it is working great.
[A] Very glad to hear that it works for you! Have you changed or improved anything in it? If so, could you show me what you fixed or improved?
[Q] Well, I wish I could say that I improved on it, but you pretty much had all the parts I needed. I was actually able to 'dumb' it down some because I could hard code the dialog name "Options" and the button "OK". I also tested that "Options" and "OK" would dismiss the Options dialog in AutoCAD as expected with the original project files you sent.
I was hoping that I wouldn't need to use the timer and would be able to just make the call straight to EnumWindows. But that didn't work because the Options dialog doesn't actually come up until my function returns. So I had to use the timer as well to delay the call to EnumWindows. I found dropping the interval to 300ms was better though, because you barely see the dialog come up. I call Timer.Stop() as soon as I find the button I'm looking for, because I will only need it to happen once every time the dialog comes up. I am thinking about adding some defensive code that counts how many times we call EnumWindows in the Timer, and if we go above a certain number of times (maybe 500), we stop trying. That way if anything happens and the Options dialog never comes up, we don't chew up CPU cycles forever.
One thing I did do was translate WinApi.vb and the EnumWindowsProc() and EnumChildProc() methods to VB. So I could pass that on to you in case you get requests for this in VB. First, here is the module WinApi.vb providing access to the Windows API calls:
Imports System Imports System.Runtime.InteropServices Imports System.Text Module User32 Delegate Function EnumWindowsProc(ByVal hWnd As Integer, ByVal lParam As Integer) As Boolean <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function FindWindow(ByVal className As String, ByVal windowName As String) As Integer End Function <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function EnumWindows(ByVal callbackFunc As EnumWindowsProc, ByVal lParam As Integer) As Integer End Function <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function EnumChildWindows(ByVal hwnd As Integer, ByVal callbackFunc As EnumWindowsProc, ByVal lParam As Integer) As Integer End Function <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function GetWindowText(ByVal hwnd As Integer, ByVal buff As StringBuilder, ByVal maxCount As Integer) As Integer End Function <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function GetLastActivePopup(ByVal hwnd As Integer) As Integer End Function <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _ Function SendMessage(ByVal hwnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer End Function Public BM_SETSTATE As Integer = 243 Public WM_LBUTTONDOWN As Integer = 513 Public WM_LBUTTONUP As Integer = 514 End Module
Here is the main application:
Private timer1 As Timer Private timer_interval As Integer = 300 ' in milliseconds so 1000 = 1 second Private timer_attempts As Integer Public Function EnumWindowsProc(ByVal hwnd As Integer, ByVal lParam As Integer) As Boolean Dim sbTitle As New StringBuilder(256) Dim test As Integer = User32.GetWindowText(hwnd, sbTitle, sbTitle.Capacity) Dim title As String = sbTitle.ToString() If title.Length = 0 Then Return True End If If title = "Options" Then Else Return True End If User32.EnumChildWindows(hwnd, New User32.EnumWindowsProc(AddressOf EnumChildProc), 0) Return False End Function Public Function EnumChildProc(ByVal hwnd As Integer, ByVal lParam As Integer) As Boolean Dim sbTitle As New StringBuilder(256) User32.GetWindowText(hwnd, sbTitle, sbTitle.Capacity) Dim title As String = sbTitle.ToString() If title.Length = 0 Then Return True End If If title = "OK" Then Else Return True End If User32.SendMessage(hwnd, User32.BM_SETSTATE, 1, 0) User32.SendMessage(hwnd, User32.WM_LBUTTONDOWN, 0, 0) User32.SendMessage(hwnd, User32.WM_LBUTTONUP, 0, 0) User32.SendMessage(hwnd, User32.BM_SETSTATE, 1, 0) timer1.Stop() timer1 = Nothing Return False End Function Public Sub timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) 'timer_attempts is a failsafe to make sure that if for some reason the Options dialog ' never comes up, we don't keep looking for it forever. We usually find the dialog on the ' first few tries, so if it doesn't come up in about the first minute, we give up If timer_attempts < 300 Then User32.EnumWindows(New User32.EnumWindowsProc(AddressOf EnumWindowsProc), 0) Else timer1.Stop() End If timer_attempts += 1 Debug.Print(timer_attempts.ToString()) End Sub ' The options dialog will not come up until our function returns, so we setup a timer ' that will check every 300 milliseconds to see if it can find the dialog. Once it finds ' the dialog and clicks OK, it stops. Public Sub closeOptionsDialog() timer_attempts = 0 If timer1 Is Nothing Then timer1 = New Timer() End If timer1.Interval = timer_interval AddHandler timer1.Tick, New EventHandler(AddressOf timer1_Tick) timer1.Start() End Sub
If the source code lines are truncated by your browser, you can copy and paste the text to a text editor.
Using a native Windows API Hook
The JtClicker dialogue clicker application described above is using the .NET framework to identify the dialogue and send messages to dismiss it. Since the Win32 portion of the .NET framework is just a wrapper around native Windows API calls, the same functionality can also be implemented more directly using the native API.
Here is a report on using a Windows hook to dismiss a dialogue triggered by closing a Revit transaction.
I investigated using a hook, and this is the solution :-) I created a hook in the main Revit window with SetWindowsHookEx and send messages to the dialogue when it is detected. Initially I sent a WM_CLOSE message to close it, later I changed it to click the OK button instead. This works really well, even if the dialog is shown when ending a transaction, in which case the DialogBoxShowing event generates an exception if I try to hide the dialog with OverrideResult.
My hook function is:
private static void ProcessWindow( IntPtr hwnd ) { if (App.OcultarMensajesRevit) { // Buscamos el botón de aceptar y lo pulsamos. int ID_OK = 1; IntPtr hwndOk = Win32.Functions.GetDlgItem( hwnd, ID_OK ); if (hwndOk != IntPtr.Zero) { Win32.Functions.SendMessage( hwndOk, (uint)Win32.Messages.WM_LBUTTONDOWN, (int)Win32.KeyStates.MK_LBUTTON, 0 ); Win32.Functions.SendMessage( hwndOk, (uint)Win32.Messages.WM_LBUTTONUP, (int)Win32.KeyStates.MK_LBUTTON, 0 ); } //Win32.Functions.SendMessage( // hwnd, (uint)Win32.Messages.WM_CLOSE, 0, 0 ); } }
App.OcultarMensajesRevit is a variable I created to enable dialogue auto closing. Instead of sending a WM_CLOSE message to the window to cancel it, I observed I needed to push the OK button for all things to work, so I search for that button and send it a button down and a button up message to simulate a mouse click.
To connect the hook function, I used the WindowInterceptor class I found at CodeProject.
Then I add the following in the Startup event of my application:
Process process = Process.GetCurrentProcess(); IntPtr hwnd = process.MainWindowHandle; App._windowsInterceptor = new WindowInterceptor( hwnd, ProcessWindow );
To clean up at the end, I add the following on shutdown:
App._windowsInterceptor.Stop(); | http://thebuildingcoder.typepad.com/blog/2009/10/dismiss-dialogue-using-windows-api.html | CC-MAIN-2014-52 | refinedweb | 2,140 | 55.34 |
Multithreading in java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
}
}
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.
There are various stages in life cycle of thread as shown in above diagram:
- are multiple threads running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread get executed. Therefore, this state is referred as waiting state.
- Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".
Threads can be created by using two mechanisms :
- Extending the Thread class
- Implementing the Runnable Interface
Extending Thread Class in Java Example
One.
class ExtendingThread extends Thread
{
String s[]={"Welcome","to","Java","Programming","Language"};
public static void main(String args[])
{
ExtendingThread t=new ExtendingThread("Extending Thread Class");
}
public ExtendingThread (String n)
{
super(n);
start();
}
public void run()
{
String name=getName();
for(int i=0;i<s.length;i++)
{
try
{
sleep(500);
}
catch(Exception e)
{
}
System.out.println(name+":"+s[i]);
}
}
}
Implementing the Runnable Interface
The
Clock applet displays the current time and updates its display every second. You can scroll the page and perform other tasks while the clock updates. The reason is that the code that updates the clock's display runs within its own thread.
The
Clock applet uses a technique different from
SimpleThread’s for providing the
run method for its thread. Instead of subclassing
Thread,
Clock implements the
Runnable interface and therefore implements the
run method defined in it.
Clock then creates a thread with itself as the
Thread’s target. When created in this way, the
Thread gets its run method from its target. The code that accomplishes this is highlighted:
import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.applet.Applet;
public class Clock extends Applet implements Runnable {
private Thread clockThread = null;
public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}
public void run() {
Thread myThread = Thread.currentThread();
while (clockThread == myThread) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//the VM doesn’t want us to sleep anymore,
//so get back to work
}
}
}
public void paint(Graphics g) {
//get the time and convert it to a date
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
//format it and display it
DateFormat dateFormatter =
DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(date), 5, 10);
}
//overrides Applet’s stop method, not Thread’s
public void stop() {
clockThread = null;
}
}
Java Supports Multithreading
- Java's multithreading support is centered around the java.lang.Thread class. The Thread class provides the capability to create objects of class Thread, each with its own separate flow of control. The Thread class encapsulates the data and methods associated with separate threads of execution and allows multithreading to be integrated within the object-oriented framework.
- Java provides two approaches to creating threads. In the first approach, you create a subclass of class Thread and override the run() method to provide an entry point into the thread's execution. When you create an instance of your Thread subclass, you invoke its start() method to cause the thread to execute as an independent sequence of instructions. The start() method is inherited from the Thread class. It initializes the Thread object using your operating system's multithreading capabilities and invokes the run() method. You learn how to create threads using this approach in the next section.
- The approach to creating threads identified in the previous paragraph is very simple and straightforward. However, it has the drawback of requiring your Thread objects to be under the Thread class in the class hierarchy. In some cases, as you'll see when you study applets in Part VI, "Programming the Web with Applets and Scripts," this requirement can be somewhat limiting.
- Java's other approach to creating threads does not limit the location of your Thread objects within the class hierarchy. In this approach, your class implements the java.lang.Runnable interface. The Runnable interface consists of a single method, the run() method, which must be overridden by your class. The run() method provides an entry point into your thread's execution. In order to run an object of your class as an independent thread, you pass it as an argument to a constructor of class Thread. You learn how to create threads using this approach later in this chapter in the section titled "Implementing Runnable."
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
- Process-based Multitasking(Multiprocessing)
- Thread-based Multitasking(Multithreading).
Thread-based Multitasking (Multithreading)
- Threads share the same address space.
- Thread is lightweight.
- Cost of communication between the thread is low..
For indepth understanding of Java click on
Exception Handling in Java | https://tekslate.com/java-multithreading-in-java | CC-MAIN-2021-43 | refinedweb | 864 | 56.76 |
.
Then I decided to find a workaround to the problem, firstly I installed Guake.
Everything works fine, but I find it a bit too wide for my liking. I certainly do not need it to be that wide. It would be nice if I can somehow dock it to the right screen-edge (as left edge is being used by unity’s launcher). However, after digging through the preference options, there seem to be no way of doing that.
So to make it work the way I want, I would have to find workarounds for two problems. Firstly how to shrink the width of the terminal, secondly make it somehow ‘docked’ to the right hand side of the screen edge.
A quick search at google returns this guide, and after much playing with the python script, I modified a couple of things to somehow adjust the terminal to my liking. In short, I modified the main python script to the following state:
def get_final_window_rect(self): """Gets the final size of the main window of guake. The height is the window_height property, width is window_width and the horizontal alignment is given by window_alignment. """ screen = self.window.get_screen() height = self.client.get_int(KEY('/general/window_height')) width = 33 halignment = ALIGN_RIGHT # get the rectangle just from the first/default monitor in the # future we might create a field to select which monitor you # wanna use window_rect = screen.get_monitor_geometry(0) total_width = window_rect.width window_rect.height = window_rect.height * height / 100 window_rect.width = window_rect.width * width / 100 if width < total_width: if halignment == ALIGN_CENTER: window_rect.x = (total_width - window_rect.width) / 2 elif halignment == ALIGN_LEFT: window_rect.x = 0 elif halignment == ALIGN_RIGHT: window_rect.x = total_width window_rect.y = 0 return window_rect
In short, I changed the value of width, halignment, and window_rect.x.
So the terminal seems to show up at the place I want it to be. To make it respond to right screen edge, I launched ccsm, and turned off Desktop wall plugin (as I don’t need it and it somehow conflict with the following step). Then in the Commands plugin, I map command 0 to launch guake. The last step is then to bind the right screen edge to command 0.
And there it is, whenever my mouse pointer points to the right screen edge, guake terminal pops up. There are a lot of things I would love to fix though. Firstly being making it to slide out instead of just popping out. Secondly, while I have already set it to disappear after losing focus, I would prefer it to actually disappears whenever my mouse leaves the window (think onmouseout event in like we do in javascript). I am sure there’s a way to actually fix it, but I am happy with what it is for now.
Quick screenshot with modded Guake in action.
Should I file a feature request to Guake?
I use conky for that (: | https://cslai.coolsilon.com/2013/11/15/quick-hack-terminal-appearing-from-right/?color_scheme=default | CC-MAIN-2022-21 | refinedweb | 480 | 73.98 |
How will the future operating systems look like? How the user interface, the inner workings, the security policies and the networking will interact? In any case, innovation is the key. 🙂.
2.2 Dialog windows
Of course, configuration and property windows don’t need the entire screen. Therefore, they can appear in smaller, document-modal (see below) windows. If you open one, the full-screen view behind it should be grayed out, so that the window containing the things you can do appears lightened up, so that it really gets your attention.
The appearance of MacOS 8/9 also has this effect, but it is lots more confusing because it makes no difference between windows that can’t be activated because of a dialog (as in my proposal) and windows that are plain inactive and can be switched to with a single mouseclick.
2.3 The widgets an sich
Nowadays everybody points out that Gnome should be used instead of KDE because it looks more polished, that you should use MacOS X because Aqua looks so cool and that Longhorn is even better because it provides hardware accelerated control drawing. Sounds great? It actually isn’t. Those fancy user interfaces waste precious CPU and GPU cycles, making your computer slower than it needs to be, thus making you work slower. In return, you are distracted from your work so that your productivity is even lower. ” the new OS has a GUI in which each control is drawn with hardware acceleration”.
3 The document model
After having done away the windows, we should also get rid of applications, because they are also confusing. On Windows, you can open documents in two ways: from an empty application window and from the Explorer. The same applies to creating new documents, but strangely enough not to saving them. On the MacOS, that is also the case and it is even more confusing: an application can be active and running without displaying any windows. That means you see the desktop and the finder, but that the menu bar is different because you are effectively running another application. Those are enough reasons to leave the application model.
Instead, the only thing the user should see are documents. Nothing more and nothing less. When the user clicks a document, it is opened, and when he closes it, the document is closed. What software is used to accomplish this should not be visible in any way. The way this can be implemented is by making applications effectively applets (like KParts or OLE objects). When a document is opened, a new full-screen view is created and the document is embedded into it, along with the application.
3.1 OLE!
The advantage of the applet model above applications is that no seperate logic is needed to provide embedding documents – the parent document’s applet just needs to embed another applet into it, and for that applet it is not visible whether it runs full-screen or embedded.
For normal documents, data will come from a file, either on disk or embedded in another document. That’s the way it also works on Windows, MacOS and KDE. However, sometimes that is not practical. Imagine that you want to make a chart application. You will probably want to link the data to the spreadsheet it is embedded in. It should be obvious that would not work. Therefore, we need to create the GUI equivalent of pipes, so that you can use (a selection of) your spreadsheet data as the input of the chart applet. That can create powerful systems: functions like bibliographies and tables of contents can be placed in separate applets that can be embedded in the document they are used in.
3.2 DDF
The documents can be stored in any format – the applet can determine it. To make embedding more flexible, a standard output format should be made, however. For this new OS, it should be designed from the ground up – this to support a few important things for the embedding to work properly. The reason for this is that besides the well-known object embedding, it should also provide text embedding, to make things like Table of Contents-applets possible.
Embedding objects is easy. The host applet defines, within the DDF, a region containing a sub-ddf and pastes the output of the embedded applet within it.
Embedding text is more difficult, and that has a reason. With embedded objects, the host decides how large the frame is in which the object is embedded. With embedded text however, the applet needs to decide the size as you can’t just rescale a text. Additionally, it would not look nice if embedded texts would not have advanced features like, say, automatic hyphenation. A solution would be to let the host application decode the DDF the embedded object outputs. That is not a clean solution, however, as the host applet needs to sport a complete DDF interpreter.
I believe the solution can come from breaking a monolithic program into several applets. The usual word processor can be split up into two pieces. The first one will be for composing formatted text. Let it support feautures like word wrap and embedding of other texts. The other applet will do the layout: it will put the text (and images) into frames, possibly on multiple pages, supporting text flow, page numbers and so on. In that way, you can still edit complex documents, but you have more flexibility, and can use the same advanced text formatting in both the word processor and the spreadsheet program.
4 The Network is the Computer
In these days, networking has become an essential part of every computer system, be it a standalone PC, a file server or a mobile phone. Well, you are right, the dishwasher has no network connection… yet. So the new OS certainly needs to be network enabled. That does not mean that there is no room for improvement, however. We have the Static, DHCP and Zeroconf methods of getting IP adresses, NFS and SMB to share files, Cups, LPR and SMB to share printers, NIS, NIS+ and LDAP to have the same user accounts everywhere, and Remote Desktop, VNC and X for remote logins.
These existing systems work. Sometimes. After editing a lot of settings and configuration files. And that is not how it should be. When networking should be practical, it should be really practical, for everyone. After all, a home user wanting to take advantage of the network they have made for internet sharing, does not want to dive into the world of TCP/IP, DHCP servers, gateways, DNS and so on. They want a network that just works. And what would be rather practical, is if you were able to edit the same document no matter whether you are working on the desk computer, the laptop or the refrigator.
Such a thing cannot be accomplished easily. Rendezvous is a step in the right direction, but it is still bound to one single computer: you don’t instantly have access to your documents – you need to search through other computers for the resource you need and login to that computer before you have access.
4.1 The basic idea
This is a rather interesting question. Imagine you have a home network with two computers. On the one hand, you want to be able to login to both of them, even when the other one is down. On the other hand, you don’t want that a hacker can enter the network with his laptop and have access to everything. And in a larger network, you don’t want each PC to store all user data, as such a network probably does have a server running 24/7.
That does already imply that there would be two “modes” of operation: one for the home user, where each PC knows all accounts, and another one for centralized networks where a server knows them. In a perfect world, these two could be matched, so let’s look how that can be done.
4.2 Peer-to-peer and server-client implementation
In principle, each PC operates in decentralized mode. Without a network, that means that it has one user (with associated ID) that owns everything. If two such computers meet eachother, both will learn the user data from eachother. Now, you can login to both computers with exactly the same result.
In a larger network, a server can be added. In a similar p2p-method as with decentralized mode, the server information is shared (but only its address, not the accounts themselves). When someone wants to login now, first the local user database is checked and when there is no match, the computer will also look at the server. The latter will send the account information to the local PC, and if everything is right you will get logged in and have access to the network, most likely the printers and drive space attached to the server. Additionally, the account now exists on your local PC too, so that you can use it even when you aren’t connected to the network.
4.3 Account modification
The only problem left is changing your password, as the new password needs to be propagated through the network without allowing hackers to change your password. Luckily, for this there is a solution, too, and it is rather easy. The new password will have the old one “within itself”, so that the new password can identify itself. In this way, no hacker can change your password without knowing the current one, while you can do it. To solve the problem for when two password changes meet, the date of each password can be stored in the account. This also makes it possible to remove obsolete passwords after a certain amount of time.
5. The end result
Finally, it might be useful to look at the results of the proposal: is it innovative, and almost more important, is it useful and user-friendly?
I believe the proposed GUI does indeed break with the current tradition and does this in a useful way. Doing away the windowed interface seems going back, but removes something which is rather confusing for new computer users (and has no advantage over split-screen like windowing other than wasting space because windows don’t fit to eachother). Not having a too fancy interface is also a good thing, as it doesn’t distract you from your work and does not scare away people (yes, people fear Windows XP as it is different from 98/Me).
The document format, on the other hand, does not offer much more than Display PDF or something like that. Combined with the linking model, however, it becomes more powerful than what we have today, allowing to use pipes, famous within the Unix world, within a graphical environment, which serverely extends possibilities and reduces complexity.
The network model, finally, unifies the traditional, server-based systems like UNIX and Netware, and the peer-to-peer networks like AppleShare and SMB in one package, allowing for one consistent, interface for both types of networks, still powerful but also comprehensible for the average home user.
Though this proposal might never see a working implementation, I still believe it shows there is a lot of room for innovation in the current operating systems. So I hope that they will not only innovate behind the scenes (SMP support, NTPL, WinFS, …) but that one of them will take the step to break with the past to allow new concepts in, so that the end user will finally get improvements as well.
I think this is a seriously flawed article, for example the following suggestions are obviously backward steps in UI design.
.“
what do you do if you have applications that do not process any documents?
e.g. a calculator and i bet you’ll find many more examples…
greets philipp
… with the first post. I think this article is seriously flawed. Maybe it is too radical a change, maybe I lack mental flexibility, but I really think some of the author’s ideas as bad. The first one coming to my mind is this:
“Instead, the only thing the user should see are documents. Nothing more and nothing less. When the user clicks a document, it is opened, and when he closes it, the document is closed. What software is used to accomplish this should not be visible in any way.”
Hidding which software you are using will be source of confusion… unless you agree to be fed whatever the
OS provider want…
There’s other things I don’t agree with, or I find outright ridiculous. Example:
“KDE even has the window buttons in exactly the same place as Windows.” Conclusion: KDE is mimicking Windows… Well, I am not sying that KDE cannot be made to look like Windows, but still I cannot swallow that easily the comparison: Gnome, KDE == Windows imitation.
I’m not an expert, so I should be modest. This is just my opinion.
Finally, a last word. The GUI presented here look a little bit like a “shell GUI” for X. I’m sorry I don’t remember the name, but the idea is that windows do not overlap and that you can split your screen as you feel to accomodate new applications… Do someone remember the name of this GUI?
I agree with m, this is a bit of a joke.
How many people work with every window on their machine maximised? I know I don’t, as sometimes it is just impractical, such as WinAmp. Can’t imagine using that in full screen mode, even if it supported it.
I think the author of the article is pushing more towards Task Based desktops. And with bigger screens, and something like the Screen Tiles in Longhorn, and KDE/Gnome, would work better. Winamp, downloads and other non-important service based programs on a tile where they can be quickly accessed, while the main program being used is in maximised.
It is Ion:
If I understood it right, in terms of the GUI the author is basically suggesting we take the Mac OS approach to window management, then make every application a seamless part of the OS. Then the user will be able to
(a) work with their desktop more effectively (I’ve seen lots of examples of the Outlook Express email problem, so that’s a good analogy), and
(b) be able to think entirely in terms of tasks, not the current OS + apps = solution model.
Why not a Longhorn style sidebar to hold all the mini-applets that don’t rate a full screen window?
@Barlin – Winamp with its media library thingy takes up most of the screen at 1024×768, so I can see it filling the entire screen
Funny that the author thinks up a “new radical approach” to UI and uses techniques that are from the past (full-screen non-windows) and the present (dialog non-windows).
Especially when he then notes that to achieve dnd, there should be two full-screen (ummm…) windows visible at the same time.
The GUI pipes are a good idea, but that’s already available by dnd or c&p. All you have to do is make the applications work like that (and that’s not operating systems problem anymore).
The general idea in the network section seems to be “replace old protocols with new ones”. I don’t know what good would come from increasing the number of protocols (yeah yeah, the new one will be better than those old ones, right? and everyone and his brother will use the new one) when there are already too many of them.
The only truly valid point in this article is the document-model.
If I would be impolite, I’d say that this article is crappy, but I’m not.
I agree that every application should be a seamless part of the experience (maybe not the O/S: an important distinction) for example, we will see blurred lines between local and remote windows, as much as local and remote applications, documents, storage, etc: I tend to agree that application per se should be downplayed: future environments are more about tasks, whether those tasks are documents (in a traditional sense) or interactive windows (chat, e.g.) or so on. I think the author of the article has a few valid points, but the points aren’t well explained, and too mixed up with other incorrectness. Quite simply, if the audience for this article is the “informed technical person” (I put myself into this category), then there are too many mistakes for it to be a worthy article to read, and if the audience is the “lay technical person” (joe six-pack, e.g.) then the article is deeply misleading.
If someone _really_ wants to write an article about the future of O/S etc: then realistically the only way to do it in the current world is to set up a collaborative system (a wiki, e.g.) that many people can contribute to and refine to have a consensus: in today’s world, no single person has the perspective.
Daan,
Thanks for your article. It takes courage to challange the status quo in a public forum.
Kramii.
you’ve gotta be kidding, there is almost no change suggested by the article. It is still WIMP (windows, icons, menus, and pointers)
Future? Operating system of tomorrow?
My view of the future operating system is a marriage between what can be seen at:
and what can be red at:
text rules baby, as long as is used the right way
This is literaly just tomorrow. Thats all what we have, just nicer, with more eyecandy?
Did the author ever heard of ubiquitous computing? It think when your jacket sleeve sports a personal assistant you stuck with those things? The questions are interfaces and they do not necessarily mean GUI. Heard of Sony Qrio? And you are talking about GUI? Those things need some more ideas for OSes than just some filesystem and widgets.
Mitchell wrote 15 years ago that we stuck with WIMP. And somebody asking for more? Seriously, a very very flawed article, lacking any foundation.
You don’t solve the overlapping problem by making everything overlap all the time. You solve it by making it impossible for things to overlap. The problem that overlap solves is depicting an arbitrary amount of window area on a screen of finite dimensions. And unless we use z-axis (overlap), we need to use either a curved plane with adaptive area (non-linear zoom + no overlap), or virtual desktops (replacing overlap by viewport cropping), a combination of those, or something else.
Suppose you go all the way with the document-centric UI. If we take the view that a document == file, we need to cram 200k+ (300k+ on OS X) files on the screen. Which looks like this in a zoomable fs visualizer:
Point 1 – virtual Machine.
This is definitely the way to go. You loose performance but gain safety, portability, easier development and much more.
Point 2 – away with overlapping windows
This is a good point too. A taskbar to show which windows exist and an emacs-like splitting (plus d&d) gives 99% of what you need. Anyone working with emacs knows that this is more comfortable than overlapping windows.
Point 3 – simple look
Again true that too many fancy widgets distract you from your work. Platinum uses greys for widgets and one color for text highlight.
Point 4 – only documents
Documents are not enough, sometimes I need to perform “tasks”: Duplicate A CD; Synch Files with My Laptop etc.
Point 5 – software is invisible
Software is important. I want to be aware of using Photoshop and not GIMP, Word and not OO etc. especially if I paid for it. And sometimes I want both installed and to be able to choose.
Points 6 – embedding text
This is in my opinion a technical issue. I didn’t understand fully what he means but I think there are better solutions.
Point 7 – network model
There is little innovation here, although much is needed in this area.
Well, the always-maximised thing may indeed be easier for non-techies; in my experience, most ordinary unsophisticated users simply don’t understand the concept of windows on a screen. Everyone I watch always maximises everything (eg mail composition windows) even though it’s pointless and less productive. They simply cannot understand the concept of sizing windows and leaving other things visible on the side etc. So though it’s less powerful, the always-maximised model is the one that most Joe-Blows already use!
Your networking sounds a lot like something I’m implementing.
I’m not quite there (public key crypto is slowing my progress).
It is very complex matter, and I’m not sure I’ll ever complete it….
OS designers have been using the vm idea for years esp. with WinNT. Here the OS is separated for the H/W through the use of a Hardware Abstraction Layer (HAL) and hence porting WinNT to another platform (e.g. the DEC Alpha) was simply a case of porting the HAL.
My conclusion on this article is that it is seriously flawed. The majority of the points raised are old ideas, and some are considered bad practice (e.g. the points raised on UI design)..
I agree that a truly document based interface would be a good idea, preferably one where the “applets” used for editing data can easily be extended and have functionality replaced with plugins and new applets.
The GUI you are looking for is probably ‘screen’, commonly found in /bin/screen
It’s a terminal multiplexer.
On the other side, we have the innovative Mac OS X. It is the user-friendliest computer system on earth, built on UNIX and has OpenGL acceleration of the screen.
If that was so, every living being in the world would be using OS X. However, the reality is that OS X is in fact harder to use for 90% of computer users, (Windows users).
In fact, it is so esoteric to use that 99% of the time, the Mac laboratories over at the University I work at are 99% empty. I run Jaguar on an iMac, and there have been several occassions where I just break down and boot into Windows XP, or switch over to my Linux workstation. And I’m a self proclaimed computer geek.
Usability and familiarity go hand in hand. If you are familiar with a concept, its process becomes usable. Apple’s window manager simply sucks! It is absolutely, completely horrendous and just plain retarded. And it is perhaps the fundamental reason why the Mac labs at the University are 99% empty.
When your user doesn’t know how to quit, maximize, minimize or shuffle between applications, there is a problem. How about not knowing where to look for applications? Suppose a user wants to see all applications available to the system, what does he or she do?
In windows, they start at the start menu and then logically, proceed to the programs menu. In GNOME, the “applications” menu is glaringly conspicuous. In KDE, the K menu is an instinctive place to check. In Jaguar OS X?
Uhmmm…you search for it in Finder. Or while messing around with the finder menu, they user inspirationally clicks on “Go” then “Applications”. How innovative. I don’t know if that has changed in Panther, because I haven’t bothered to upgrade and probably will not. Admittedly, Aqua looks sexy, pretty, and polished, even more so than any other GUI environment I’ve laid my eyes upon. But looks don’t automatically translate in usability.
It took me months to learn how to use OS X and unlearn many computer habbits. That hardly bodes well for usability, ease of use, and flat learning curves. Even as we speak, I feel a little crippled when I use Jaguar, compared to other OSes. On linux, I can effectively and efficiently use GNOME via keyboard input, no mouse.
On OS X Jaguar, I can’t remember how to select links on Safari, using the keyboard, nor do I remember how to minizime, maximize, resize, or move windows via the keyboard. I don’t even think you can shade windows in OS X. I think you could in OS 9, but I digress. I don’t remember how to expand the apple menu via keyboard, nor do I know a quick way to launch programs that are absent on the task bar. Anyone who uses Linux will acknowledge why I feel crippled in Jaguar.
To the best of my knowledge, I have to use a mouse to do majority of the window management activity in Jaguar. Even cycling through applications is a pain Jaguar. I understand that has been fixed in Panther. But that means shelling out $129 for a silly feature that even ‘free’ ICEWM provides.
I can go on and on about how Windows and Linux are an other of magnitude more usable than OS X, but it is not necessary. To be usable, Apple need to through away several of their window management philosophies, and present users with ones they are already familiar with. For Christ sake, I can’t even maximize windows in OS X. Neither can I set applications to fullscreen mode. I mean, these are necesities.
Enough of my rant, I disagree with you that OS X is the most usable Operating System on earth. I think that title should rightly go to GNOME. It is the most usable environment I’ve been in. And I’m willing to bet my sister, that Average Joe will have an easier time migrating from Windows to GNOME, than he would from Windows to OS X, or Mac.
Yes, I don’t agree with the stereotype, now shoot me..
Where did you get the idea that POSIX compatability means you can’t have a GUI? We’re ( ) doing fine with POSIX and GNU tools. If you don’t supply basic tools, your OS can not function. What will you do without GNU tools such as a compiler and linker? Creating your own tools as well as an OS is going to take a lot of effort; porting non-GNU tools isn’t going to reduce your reliance on POSIX or Unix-like standards.
Existing POSIX based code offers most everything you list as “needs”. If you want fonts, you want Freetype2. If you want webpages you want Gecko or Khtml. If you want pictures and movies you want FFMpeg and friends. All of those are much easier to port if you have POSIX compatability!
Anyone who says that has not discovered the KDE Configurabillity that it is so famed for!
KDE is the universal operating system! You can make it look like nearly ANY operating system, or invent your own. KDE can look like Windows, MAC, BeOS, CDE, Amiga, QNX, RiscOS and more. Check out the Keramik and Plastik themes, completely revised for KDE 3.2! As for placing Window buttons, right click any window title bar and select Configure Window behavior. You can configure it until your hearts content!
Saying KDE is a Windows clone is just ignorance, and I will come down HARD anyone who says so.
Does Windows have the versitle KDE control center? Panel applets, built in Wallpaper Slideshows (and this was before Mac OS X had it, it was there in version 1 of KDE, in 1999!). SO repeat after me KDE IS NOT A WINDOWS CLONE! In fact, the longhorn beta is copying KDE!).
Menus in Windows are relative to the application to which they pertain. As much as people in the Mac OS world once adored the idea of the fixed menu placement at the top of the screen, it was confusing in a completely different way, because you had to be aware of which window it pertained to, and lead to more mouse movement if you used a larger monitor with resized windows (instead of maximized windows).
I find that the reason most users tend towards maximized windows is because they’re running at 800×600 or 640×480 (depending mostly on which OS they’re using), and those resolutions often are barely capable of displaying all of the relevant information on the screen at one time. Most of them use these resolutions either because they’re the default resolutions or because they find higher resolutions harder to read (because setting font sizes and so forth is not only too complicated for many of them, but is also inconsistent), and the higher resolutions require better accuracy with the mouse in most cases, which can be an issue for many users (that problem could be solved by resolution-independant icon size, but Windows doesn’t currently have that built-in).
I, personally, only use maximized windows for applications that convey a great deal of information and, in most cases, can have multiple documents available in the same window area. Most of the time I prefer my documents to be viewed in a window that’s taller than it is wide, as this is a more familiar orientation for documents often viewed in print, and, for me, is often easier to read (as the lines don’t become jumbled 1000 pixels into the 1600-pixel screen). Additionally, any application I keep maximized tends to become background when I start using other applications, so everything I use is constantly displayed with that one application in the viewing area, which is helpful because often what I’m working on in the foreground is related to what sits in the background..
Unlike MacOS, though, when you have a floating window in Windows with an attached menu you are usually closer to the menu than to any of those 4 other points (though they’re easy to get to if you like to toss your mouse across the room or use a trackball like a 5-year-old playing centipede). The idea of attaching menus to the windows is based on the idea that users will commonly be using the mouse in the window in which they are working, and will focus attention on that window. Personally, I’m more keyboard-oriented anyway, so the only reason it matters to me is because I don’t need another slice of my screen being used up by something that makes the interface harder for me to use, if not everyone else.
I agree that a truly document based interface would be a good idea, preferably one where the “applets” used for editing data can easily be extended and have functionality replaced with plugins and new applets.
This would be great for people that do nothing on their computers but edit and read documents, but computers are general-purpose things, and moving them towards a document-centric model simply alienates the rest of the user base. On the other hand, making document-centric work easier, and making the operating system behave well in a document-centric user’s day-to-day tasks is a good thing. It just needs to be balanced against the general purpose needs of the remainder of the system’s users.
you will be going back to the single static partition of memory if the only application that gets used at any one time must have the attention of the user.
there is a reason we left that model back in the dust…. it was inflexible and inefficient.
…if we all stood up and decided to “invent” our own OS. Wooopeee! I don’t know about you guys but I seriously think more energy should be focused on improving what we have (good or bad or ugly). Everyone has an opinion and disagrees with others. We don’t need 5000 different OSs. I bet future OSs will simplify and become more transperant. They will fundementally work the best way (OS Core) and will only differ cosmetically (Think OSX – UNIX core with any GUI you please). Less people will care about what the underpinnings of the OS are – it will just work. If anything, forget about reinventing the OS and work on designing X server + window managers/environments. The rest should be transperant and irrelevent. VM? Current Linux/BSD porting efforts should be given more credit.
yikes! The problem isn’t overlapping windows. The problem is the default click-to-front behavior of the windows. windows should stay put until the user moves them (except for some “emergency” type warning messages.) woot?
If OS X is harder to use for 90% of the computer users (Windows users)? Most of them never used OS X. In fact I believe most of them have never seen a Mac for real.
or not?
For the simple reason that it has stimulated much debate over OS design. I for one agree with most of the Authors points.
Most windows should be always maximized as this stops the user spending time fiddling trying to get screen layout right. As for drag and drop between apps, it is useless, Just use cut and paste. In a filesystem environment your filemanager should start with split screen just as smart ones like MC (midnight commander) does, drag and drop should only affect the main app and maybe to items in the taskbar or elsewhere.
Posix has more to do with the programmers than the end users.
Windows should never be lost to the user. This is the #1 UI design mistake today. We need ways to see where the data we are working on is.
And yes not everything is document centric but very few people have trouble with non-document centric apps.
The claim that eye candy just wastes cycles, while true in some cases is not a universal. Drop shadows under menus and windows is a usabity plus as it allows you to determine the window that presently has focus quicker.
The GUI option that allows only one application to be visible at a time is a very poor idea. Very often I find myself (and I expect that other do too) wanting to have multiple things visble. API docs while coding, an email I am responding too, a article being reference in something else I am writing. The list is endless. The current system has enough flexiblity that everyone can find a system that works for them. If all maximized windows works for you, that great it wouldn’t work for me.
Replace documents with files and you have a good step.
I want an extremely intergrated enviroment. I want to click (or double click) on an icon and launch the nessacary app(already done)think the embedded viewers in KDE. I click on a text document, and in the same window the text editor opens. I click on a image icon a small menu opens and asks whether I want to view it, or edit the image. Photoshop is already a part of the system. If I select multiple images I can either drag them to another directory or open the entire selection in an slide show. I want tighter intergration of software, while using open standards. That way KDE can open stuff and i can send it to my friend who uses Gnome who changes it and they can send it to a windows user who can change it and send it back.
Microsoft’s tight intergration even tighter, with open standards for file formats. That will be a near term OS of the future(20 years).
Ask 10 people what makes a good UI design and no doubt you’ll get 10 different answers.
Some people like all windows to be maximised, other don’t. Some people like windows to come to the front when clicked while others find that annoying.
I think what makes a good UI is how flexible and configurable it is. The moment the UI forces the user to do things a certain way it loses potential users.
since when is GUI and apps the same as OS design? when i think of OS design, i think of microkernels and exokernels, page replacement algorithms and tcp/ip stacks. shouldn’t this article be called “Designing the GUI and Apps of Tomorrow”. everything discussed here can already be implemented on existing kernels that are out there.. Japanise company has tried introduced a more reliable operating system to desktop and portable computer market. What did the GIANT of the USA do? They blocked such development. This clearly p***ed the Japanise corporation of badly. They are now switching over to Linux. The GIANT of the USA are pretty stupid in my opnion.
Put every document in XML, and then the namespace defines the presentation behaviour/software to use eg. svg, html, word(?); then piping documents would be easy, using XPointers or something, remote and local docs could be referenced.
I guess you register different software against each namespace/doctype. So no ms software if you want.
A VM running multiple browser windows displaying lots of different doc formats -> Mozilla !?!
– – – – – + + + + + – – – – –
Begin Analytical Comment
I think the Main Question here is how to make advanced machines like computers look as simple as a box of cookies (first thing that sprang into my head, just ate one).
The question is not IF it can be done. We’ve seen before that advanced things can become simple to the user. By putting an automatic gearbox into a car, for instance. But you won’t get the same feeling.
It’s just what’s more important to you, and how fast you’re willing to adapt to a new (and simpler) environment. But as said, be very careful when implementing.
Personally, I think that restriction and simplicity lead to creativity, as is proven many times. Give a child a piece of paper and a pencil, and it will start to draw. Give it a full painter’s kit, and it will run away. But that’s just my opinion.
Anyway, it’s good to have a real discussion about this.
End, thank you.
– – – – – + + + + + – – – – –
…reading when the author said, “C++ was a bad fix to C, and Java cleaned everything up”. This statement and most that came after were sheer garbage. Is it too much to ask that an author know something about their subject before writing about it? If I’m going to take the time to read three pages of material I’d like some confidence that the people asking for my time do some do some actual, honest research and become educated before establishing a dialog with the rest of us.
“Such approach are better suited to pen computer. Apple did it with OpenDoc and Newton, but chicken out when Job took over.”
“The GIANT of the USA are pretty stupid in my opnion.”
Perhaps you should get a sufficient handle on the GIANT’s rudimentary grammar and spelling conventions before you offer criticism. You undercut your own argument by demonstrating that development continues regardless of America’s presumed anti-competitive practices.
.”
?!?!?!?!?!?
Compared to what?
For the simple reason that it has stimulated much debate over OS design. I for one agree with most of the Authors points.
It’s much easier to get a lot of discussion out of a bad article than a good one, but at the same time this particular topic on a forum dedicated to operating systems tends to be an attraction for discussion anyway. The article itself is highly flawed, but a point-by-point discussion on a 3-page article is nearly impossible on this forum without submitting a counter-article (due in part to the length limit on posts, and in part to the way posts are displayed).
Most windows should be always maximized as this stops the user spending time fiddling trying to get screen layout right. As for drag and drop between apps, it is useless, Just use cut and paste.
Users that might spend a lot of time fiddling with non-maximized windows would probably be the same users that rely on drag-and-drop. People confused by overlapping windows would probably be equally confused by cut and paste. Most windows have no need to be maximized, and often doing so just causes excess wasted space. Imagine Notepad with a short pre-formatted (with line breaks in the file itself) file open, at 1600×1200, or even 800×600. Even more complex document editors, like Word (or equivalents), tend to waste a lot of space in full-screen mode, because most of the documents they deal with are meant for printing on paper that’s longer than it is wide. Web sites often fall into the same trap because they’re forced to design around the small resolutions most viewers will have, leading to pages wider than they are long even though the information could be conveyed more clearly and with fewer pages in the other direction (then again, if you can span multiple pages you can get more ad hits).
In a filesystem environment your filemanager should start with split screen just as smart ones like MC (midnight commander) does, drag and drop should only affect the main app and maybe to items in the taskbar or elsewhere.
Why should your file manager be split-screen if you’re not going to use drag & drop? The whole idea of split-screen views in file managers is to make drag & drop easier. This is exactly why I don’t use split-screen file managers, and only occasionally use directory-view options in file managers (primarily if I’m moving things between directories with similar names in different parts of the hierarchy). If I need a second directory open in the file manager to make movement between directories faster, I should be able to open another file manager window and move between them easily, without worrying about the file manager having too much overhead to open quickly and run side-by-side. The options required in a file manager’s menu and toolbars are fairly limited, so the extra screen real estate from a second window should be minimal.
Posix has more to do with the programmers than the end users.
This is true, and people should be reminded that WindowsNT could just as easily be POSIX certified as many UNIX derivatives. With SFU there’s a POSIX subsystem in WindowsXP that’s perfectly fine for many POSIX-aware apps. It can all be made to look like Windows, or it could be made to look like OS X, and though POSIX does include standards for the UI services, the actual look and feel doesn’t matter.
Windows should never be lost to the user. This is the #1 UI design mistake today. We need ways to see where the data we are working on is.
This is the type of problem easily solved at the application level, though. Additionally, much of this behavior is user-dependant. Many people would not like it if they couldn’t switch between multiple documents of different types without hassle, or between a document and application windows, simply because some UI designer thought the user shouldn’t be allowed to shift focus away from the document they’re currently working on.
And yes not everything is document centric but very few people have trouble with non-document centric apps.
People have trouble with all types of apps, the document-centric ones simply tend to have the worst interfaces because the designers are trying to cram features into them while still allowing the user as much space as possible to view the document these features will modify. People using *nix like emacs and vi not because they’re simpler than applications like Word, but because they have most of the same features (and more or less in many areas), yet keep most of the interface out of the way (in favour of obscure keyboard commands that scare many users away, in many versions of each editor). Document work is fundamentally not drag & drop, point & click, but instead is done with hands on the keyboard, so of course those that know the keyboard commands for their editors can handle the documents much faster and with less hassle. Still, how many people would be willing to use (or mandate in their company) Word if the interface were simply the document window and every new user had a list of keyboard commands taped to their desk to figure out how to do anything more than simply type?
If people more commonly have problems with document-centric applications (as is implied by saying that people don’t have trouble with non-document-centric apps), what benefit is it to make the OS itself document-centric? In many ways, it already is, as it suffers from many of the same problems that are inherent in document-centric applications: they try to pack as many features in as possible while still trying to stay out of the way of whatever application you’re trying to focus on. No one has a perfect solution, I don’t have an OS no one’s ever seen before in my back-pocket that will solve these problems. However, the points need to be made and people need to start thinking about these things in different ways. The arguments are really not very different than they were 10 years ago, and at that time Linux didn’t have a GUI worth mentioning, MacOS was unrecognizable to someone first exposed to it with OS X, and Windows was still a DOS application that no one used.
A future computing paradigm like the one described at really looks nice.
“People that don’t learn from the past are bound to repeat it”. There was almost nothing that was different to what people have tried (and suggested) in the past, yes you can do 90% of applications this way but it is the other 10% that break your model and they are very difficult to implement. Once you have to ‘hack’ you design to add these in you will find that it would have been simpler not to have constrained the model in the first place but now you are stuck with lots of source that you will have to change.
Most windows should be always maximized as this stops the user spending time fiddling trying to get screen layout right.
That won’t work very well with multiple monitors – I hate it when apps maximize across monitors. My dual headed matrox card makes 2 of my monitors (I use 3) act like a single monitor so whenever I maximize an app on either of those two monitors it expands across them – and I hate it when that happens.
Convince Apple to release Aqua/Quartz window manager under the GPL license.
Don’t get me wrong. I HATE Mac OSX. The “one menu bar” system drives me bonkers. The entire system is based on the fundamental principal of ONE FEEKING MOUSE BUTTON and the basic interface just isn’t intuitive.
But it has serious advantages over all competition in that it’s incredibly responsive, has smooth, flawless eye candy, perfect fonts, etc etc. It’s already based on FreeBSD and XFree86, so compatibility is not an issue.
It would take a matter of hours for someone to port a working version to Linux. You can even download and boot the Mac kernel and Darwin on i386-based machines, straight from the Apple site. Imagine KDE or Gnome running on the Quartz/Aqua platform. I prefer KDE in terms of customisation and usability, but I can appreciate the concepts behind the Gnome prject, and always keep an eye on development. With the Quartz back-end in place, Gnome especially would be a perfect desktop, and the support in development would simply explode.
An important issue is convincing Apple that this is in their interest. This is the difficult part. My personal opinion is this:- If Linux with Gnome or KDE was as flawlessly responsive as Aqua, then it would make Linux undoubtably the best PC desktop OS. This would not only push the popularity of Linux, but also push innovation in Mac OSX. This in turn would push the G4/G5 processors as a viable alternative to Intel/AMD.
Don’t get me wrong, I’m certainly no expert, and this concept is probably fundamentally flawed in a dozen way. But at the moment, in my head, it’s a great idea. I just wish I could sit down and have a one-to-one with Mr Jobs.
This would work well for the new computer user as an introduction to computing.
However, this system seems to me, mean that you are going to loose efficiency in production of comple models, and not even be able to achieve them.
Personally, I like having ovelapping windows, I find I can do it in a neat and efficient way.
VM machine would be too slow, esp. on top of modern systems.
folder navgiation will become difficult, if even possible according to the article. Folder navigation in my view is best done as in OS X with colomn view.
about diff protocols, doesn’t worry me, the computer sorts it all out for me.
apps, you need to be able to see your different apps properly, how would something like photoshop work?? tiles on another seperate part of the screen. No thanks. I like modern systems, despite lack of new inovation, becasue it’s not necessary. People have got used to that way of working, and to change it all now is a little late, and would slow productivity down for sometime while people got used to the new system.
If the Author likes it so much he should create a copy for himself and present it to the public.
Personally, I think that restriction and simplicity lead to creativity, as is proven many times. Give a child a piece of paper and a pencil, and it will start to draw. Give it a full painter’s kit, and it will run away. But that’s just my opinion.
I think if you give a child a full painter’s kit, then the kid’s more likely to make one very large mess instead of running away.
Also, how you restrain the child while still allowing the painter to paint if there’s only one set of tools available? ie – makeing the OS simple enough for the novice, while not makeing it difficult for someone with a clue to use the full power available to them.
<rant>One point worth mentioning is that many of the authors points have nothing to do with OS design, but rather with UI/application design. This point always bothers me: much of the debate I have seen between which OS is better are truly user interface and user experience arguments, which in reality have almost nothing to do with the OS at all! What is really being argued are the virtues of an operating environment which is really just a large program running on a host OS. As is seen with KDE and Gnome, the operating environment can run on different host operating systems. The only people who really ‘use’ an OS are programmers who are interacting with that OS’s system call interface, and dealing with the foibles of that OS’s design and implementation. The rest is UI and application design.</rant>
On to the article:
I think an example of the ‘everything is a document’ idea is the Gobe Productive office suite. It has a single unified document format for the word processor, spreadsheet, drawing, and presentation software such that essentially one user interface and document format is used to handle them all, and parts of each type of document can easily be dragged and dropped onto each other. It is a good idea, though as others have pointed out, not do-able across all application domains.
VM’s and fully distributed designs are where true OS design is headed in my opinion. I think MacOS X is a good example of how the VM idea may work. Currently OS X can run native OS X apps, and OS 9 apps through a module-like OS 9 support environment. This concept could be expanded to include support environments to run applications natively compiled for a larger number of other platforms. Perhaps we will end up seeing a single small kernel (perhaps stored in a ROM) with a group of software VMs. The kernel will be responsible for loading the proper VM based on what type of application is being launched.
A distributed framework would allow different networked devices to be used (hopefully transparently) to access your data, as long as the appropriate VM is available for that device.
These are very general ideas, but I think this is the way things will go.
Brennan
It’s already based on FreeBSD and XFree86, so compatibility is not an issue.
Quartz isn’t based on XFree86, it’s based on DisplayPDF which is a descendant of DisplayPostscript from NeXT. While Apple do ship an X Server (which, I believe, is based on XFree86) , it sits on top of DisplayPDF.
Imagine KDE or Gnome running on the Quartz/Aqua platform.
Why imagine when you can already do it: for gnome and evolution and for KDE. Note that the GNOME stuff requires Fink and X, while the KDE stuff is native (though I think a Fink/X Window based KDE is also available). A native GTK on OS/X project can be found here:
.”
KDE and GNOME are the most popular (!) DE’s and WM’s. If you want an innovative DE/WM you’d better not take the popular or the popular’s default settings which is exactly what you chose to conclude from.
Instead, try to change the default settings. The default settings are meant for people who are new. And most new people are comming from MS Windows 9x/NT. You don’t want to scare them, do you? KDE is more like Windows than GNOME is, imo — which is why i believe KDE is more popular.
Want an innovative DE/WM? Try for example Enlightenment and see how innovative the various versions, themes, and features are.
Enlightenment doesn’t exist to “take over the world” either which is what you can note when you know it is BSD licensed or when you read from the authors (ie. Raster, Pixelmonkey, etc)
If you want to se ean innovation, you’ll have to look futher than you nose long is and prepare to move away from the status quo/popular. Mostly, the chances that the innovation will become popular are slim… which correlates with why it isn’t popular, why you perhaps didn’t knew about it.
Quartz isn’t based on XFree86, it’s based on DisplayPDF which is a descendant of DisplayPostscript from NeXT. While Apple do ship an X Server (which, I believe, is based on XFree86) , it sits on top of DisplayPDF.
I knew Quartz has something to do with PDF, which I found quite confusing, but interesting. But I didn’t know XFree was secondary. Is that what gives OSX its smoothness? I always wondered why there was such a huge gap in feel between Linux & Mac OSX GUI’s. Like I say, I’m no expert.
Why imagine when you can already do it:
I’ve never seen these projects before, and although they are interesting, my point here was to port the existing graphical backend & GUI to the i386 platform, through GPL. That’s where 90% of the market share is, after all, and I think, in the long run, it would be beneficial to Apple. Plus I don’t have a Mac, and crave a major update to XFree (or whatever makes Macs so responsive).
For all its faults, Windows is definately more intuitive and responsive than KDE or Gnome, and it’s the main reason the majority of i386-based users are stuck with M$. I feel until this is resolved, Linux will remain a hobbyists toy when it comes to home users desktops.
In saying that, I also have strong feeling over package management (which sucks on all platforms that I have experience with). But it looks like there is a lot more creativity going into that now (compared to recent years).
… translates to
The widgets themself
;o)
Cheers!
STIBS
First I would like to congratulate the author on a good effort to come up with an alternative solution to some aspects of computing that have troubled him, and which might lead to some better systems for some people.
However, I can’t help but agree with many other comments here.. this is not really very innovative. It is taking some old ideas and throwing them around in different ways. I really don’t see very much that is new or different. It’s more like a rearranging of furniture than a completely new building.
I think the author grasps some of the basic issues in computing today – for example the unification of individual computers over a network, making the user interface easier, etc… but I don’t really see a central core or reasoning or philosophy behind these decisions. It’s kind of just a bunch of pieces thrown together without a whole lot of coherent reason. I don’t see an underlying thread of consistency. I think the ideas here will have to be developed further and in more detail because at the moment this radical new model isn’t so radical.
Since this author focusses a lot on what is practical I am thinking they are a practical kind of a person, perhaps a Taurus, Virgo or Capricorn, astrologically speaking. Such people are now always able to come up with something new and original, it’s part of their style.. but I DO very much appreciate the focus on practicality and down-to-earth simplicity in this article, so thumbs up for that!
A good future os is going to need rather a lot more refinement and VISION, but this is a good step.
Brennan, I agree with your point… a lot of discussion is about user interfaces and applications rather than operating systems. But here is the point… every user is subjective and not everyone has a DEEP understanding of what an operating system is. They figure it’s the way they use the computer…. what image or face the computer shows to them as part of the way they interface with it. Yes, we know that there are lower levels and things going on behind the scenes but for a lot of users, an operating system is considered the same thing as the user’s understanding of how the computer works, and if all they’ve ever done is use applications with a limited knowledge of how they really work, as might be the case here, it’s no surprise that they’d be thinking on a level of applications and user interfaces rather than behind the scenes technology. I guess it raises an interesting question of what, the user, an operating system really is. Furthermore, I think an operating system should be transparent to the user, so maybe this author actually has a good point about focussing on what the user experiences rather than on what goes on in the background. Wouldn’t a good operating system be one that does not require that the user know about how it does what it does? Isn’t that what makes a good interface? Isn’t the interface the operating system, to the average user? A lot of us know that an OS is a lot more detailed than that, and in that sense this article does fall short, or at least appear to, but maybe in the author’s naievety he actually has the right focus?
Just another two cents… must be ranking up the coins now.
Since this author focusses a lot on what is practical I am thinking they are a practical kind of a person, perhaps a Taurus, Virgo or Capricorn, astrologically speaking.
:oP
I knew Quartz has something to do with PDF, which I found quite confusing, but interesting. But I didn’t know XFree was secondary. Is that what gives OSX its smoothness?
Yep, X is in there only to provide backward compatability with graphical UNIX apps (and, I suppose, to tempt *NIX users over to the Mac). The Server sits on top and uses Quartz (ie DisplayPDF) to draw the X apps on screen. DisplayPDF is what gives OS/X it’s smoothness.
my point here was to port the existing graphical backend & GUI to the i386 platform, through GPL
Probably the easiest way to achieve this “GPL’d OS/X” nirvana would be to use GNUstep (a clone of the NextStep/Cocoa API) on top of Linux and to revive GNU DisplayGhostcript (a long dead clone of DisplayPostscript). While GNUstep has had some life breathed back into it (probably helped by people wanting to port OS/X software to other *nixes – it had languished for quite awhile) I don’t think there are enough people with the itch (at least for now) to revive DisplayGhostscript.
As someone else pointed out, the title of the article should have been Future Desktop Concepts – not Designing the Operating System of Tomorrow. I thought this article was going to be about microkernels vs monolithic, and other technical operating system concepts. Not a gui design advocacy.
As far as maximized windows, I like my windows maximized and then I just alt-tab through them, but I wouldn’t want to force this on anybody. I run at 1600×1200 too. I tend to organize my windows into different workspace too, so I don’t have to alt-tab through too many windows.
I don’t think there are enough people with the itch (at least for now) to revive DisplayGhostscript.
I forgot to add – DisplayGhostscript sits on top of X instead of drawing directly (like Quartz does), so you wouldn’t get much benefit from reviving it unless it’s rewriten to draw to the screen directly.
It’s certainley a cool idea, even if it’s not realistic. By sheer coincidence, there’s a big post on Slashdot just came up about the X.org development team, the breakaway from XFree86, and promises of a “new level” of Xserver technology.
IMO they need to move very quickly, or this won’t be the “Year Of The Desktop” for Linux. If Linus genuinely has home desktop aspirations for Linux, then he has to seriously urge devolpers into intense and fast work on Xserver or its alternatives.
I still believe that in Quartz/Aqua, Apple has the power in its hands to steal a large chunk of the Windows market. It’s even rumoured (and I stress rumoured) that Apple have a working i386 version of OSX.
Think of it this way:- It’s much easier to seduce the Linux user to Apple products if they are the driving force behind open-source GUI development. And it’s much easier to seduce Windows users to Linux if Linux has a world-beating GUI. The way I see it, Apple has the home computing world in its lap, and doesn’t even seem know it.
Also, I failed to mention the XFCE4 window manager. Although in a basic stage of development compared to the likes of Gnome & KDE, I found playing with this little front-end to be an absolute joy, in terms of it’s lightning speed, smooth look and total simplicity. It needs a whole lot of development, but it’s an excellent step in the right direction for Linux. Not something I would use full time, but something to watch, all the same.
A window manager that fits the bill is called ratpoison.
I think this article is totally ridiculous. It basically says: New users expect [situation A] so let’s cater to new users across the board and call it innovation. Back to reality, those of us who use computers everyday are not only used to and comfortable with the current interface similarities, but we also are more productive with these interfaces.
On the comparison of KDE/GNOME to Windows. It doesn’t take a rocket scientist to see that all three are quite different. Each project makes their own UI decisions based on input from its userbase (except maybe Windows). The most notable thing about KDE specifically is that it can morph to practically any behavior that you might want. GNOME shares much of its UI design with that of MacOS. They may not look the same (those are called widgets), but they act the same in many ways and have thought out virtually every UI design decision down to should OK be on the right or on the left of cancel.
I think some real innovation is happening on the desktop in a few areas. Sun’s Java desktop is showing a new way of thinking, though it is severly limited in practicality thus far. Sphere3d for WindowsXP shows promise but needs some serious UI work before the benefits outweigh the badUI tax that it has. Finally MS is taking a different tach. They are scarcely changing the shell at all, but boosting and integrating applications in a way that will provide endless complexities for IT staff around the world. The end result of the MS’s work looks good when it works, but I shutter to think what it will be like when it doesn’t. Let me paraphrase and reapply Bjarne Stroustrup: With [WinXP] it was easy to shoot yourself in the foot, with [Longhorn] it will be more difficult to shoot yourself, but when you do, it will take your whole leg with it.
I am a total newbie, but even I recognise that the document model is outdated when talking about future OS designs.
I would have thought that Task-based OS’s would be the way forward, so you are neither thinking about applications (‘what program do I use?’) or documents (‘what file do I open?’) and instead you simply think “what do I want to achieve?” and then employ whatever task-based tools are required to make that happen.
C++ was a bad fix to C, and Java cleaned everything up.
I’m sorry, I can hardly contain my laughter.
… just about user UI, mostly GUI – windows, etc.
IMHO though GUI could (and probably should) be a part of an OS, it is not GUI that defines an OS.
If anyone interested about some innovations in OS – look at Plan9 – and it _is_ pretty old!
Also IMHO appearance of Linux effectively killed all OS innovations – last 10 years everyone seems busy with just coping/porting into linux the whole win/unix mess as it was by mid-to-end-90s.
Sir.
“what do you do if you have applications that do not process any documents?”
You have them process data. ( and shove the results in the temp save area )
For those that do not process any data ( like screen savers and games ), you dont need to care about these anyway.
Sounds like the author unknowningly fell in love with OpenDoc(tm).
Most people on this forum are throwing the baby out with the bath-water.
GOOD POINTS:
1) data pipes for GUI: abstract production/consumption of data
2) KDE, GNOME, and co. aren’t inovative (gasp!)
3) eliminate over-lapping windows: this extra power is not worth the confusion for most users IMHO
4) VM
5) interfaces should be more data-centric: users care more about their data than their apps
DUBIOUS POINTS:
1) I’m not sold on an entirely doc-centric interface
JUST PLAIN WRONG (or VERY funny):
1) C++ was a bad fix to C, and Java cleaned everything up: this is wrong on so many levels of a abstraction (hehe)
To be fair, Daan did not claim that is ideas were orig. This is only his vision for his ideal future OS.
Still, he presents a nice synthesis of ideas, some of which are still not perfected in any OS today.
oh pls linux for desktop is more A X server.
its not enough for apple reduces their hardware price, os x on x86? dream on. by the time apple releases osx for x86. its no match for windows or linux.
In every great revolution, to have the conservative right and the radical left. What will result from these ideologies and the way things work now will not be this particular GUI model, but a reevaluation from the ground up of our current GUI systems. The next generation GUI will be VERY different from the Windows/KDE/GNOME models we have now, but not that different.
The next answer will come from the person who decides to build this GUI, point out the character flaws and the general uncomfortabilities and decides to build on it with the ideas already in use.
It’s already know that ergonomically, the Windows GUI sucks. As he said in the article, it’s almost as if they INTENDED to break all the rules. The close, min, max buttons are on the exact opposite corner of the screen as the menu/quick launch. As my mouse is normally at the top right corner anyways, from the layout of the windows, I’ve moved my menu to the top of a right aligned docklet, but most people don’t know how to do that in KDE, let alone Windows. All of my utilities are on a bottom aligned docklet since I read top to bottom, it’s just in good flow for my eyes. There is no doubt that desktop icons need to be done away with, for boot speed purposes. But something tells me the masses WILL NOT be comfortable with that.
I think the document-model is decent. Have file associations so that the icon for the document shows what application is going to be used by default, but still allow double clicking to open it in another application.
Let me say that I would not use such a GUI, simply because I know how to manipulate blackbox/kde. But most users don’t.
I think that his concept on the config applets is very valid.
I’ve read a lot of bad reviews on 3d desktop (which technically z-indexing is 3d emulation), but perhaps a window rolodex of some kind. A portion of the window is visible behind the other windows, click on a title bar and the window is moved to the front and all the others shift back one to fill the hole.
Just a thought.
Hasta
oh pls linux for desktop is more A X server.
its not enough for apple reduces their hardware price, os x on x86? dream on. by the time apple releases osx for x86. its no match for windows or linux.
I said it was just an idea, which was most likely fundamentaly flawed, and I realise this is true. But you don’t present any reasons behind your little rant. Did you even read my post? ;o)
I really believe that all Linux lacks to become a genuine MS-Windows-beater is a classy GUI and a standard package management system. And those things getting close. I think that with the chaos in the XServer community, Apple are missing a golden opportunity to finish the job they started with the original Macintosh.
It’s just my opinion, and I know it’s flawed, but Windows is the single worst operating system on the planet. It is broken down to the very core and philosophy. I have it installed only for 2 games that I play online, which cannot be emulated with Winex3.
If I woke up tomorrow, and Windows was gone, I wouldn’t shed a tear, because I can do 90% of anything I personally need a computer for with Linux. The other 10% will follow soon. Microsoft had better start believing that.
Also, I said nothing of porting Mac OSX to x86. I said I hate Mac OSX. I just want the graphical back-end (apparently Quartz/DisplayPDF) to be ported. If Apple slapped their name onto that most fundamental part of the Linux Desktop, attatched to a GPL licence, then it would be in a position to steal back (at least) a big chunk of the market share.
Lets not forget that without Quartz, OSX is essentially beefed-up FreeBSD. Is it really such a controversial thing to suggest that they might have an x86 port in mind? Especially with the Darwin source-code and x86 install openly available on their site.
Okay so it’s a crazy dream, but a nice one.
You’ve definately got some interesting ideas in this article, The Future OS needs people who aren’t afraid to explore modern innovative ideas in these fields of user interfaces and decentralized computing. Keep up the good work; don’t be shy to stand on the shoulders of giants either. Perhaps look into things like Capability Security Systems, Microkernels (L4 etc), peer to peer virtual hard disks, mind mapping associative file systems, etc.
I think all dem buttons should be pushed and all da stuff work tagedder reel well. And den dah stuff all workz and uzers happi.
(future request to OSnews : please make sure writers have GED or equivalent)
The last page sounds very much like Plan9. People should
take a look at it, the OS itself has some very nice features.
(though it needs applications and a usable U.
Oops, someone just fell into a big gaping hole in logic. Every OS I’ve seen that works on devices with similar functionality and form factor to the Newton does something similar, and doesn’t have overlapping windows, even when they’re multi-tasking. You don’t need to store clippings on-screen to do this, as you can store them the same way you do in other operating systems (though storing them on-screen can be nice). This method of functioning is primarily determined by the form factor, low resolution, and normal method of use, though, and not some massive UI revolution that’s going to take over outside of the handheld space.
“what do you do if you have applications that do not process any documents?”
You have them process data. ( and shove the results in the temp save area )
Why? Not all applications have results, and not all applications need to export any results they may have.
For those that do not process any data ( like screen savers and games ), you dont need to care about these anyway.
This is very true, and it’s just a matter of not engineering the OS in such a way that it becomes cumbersome to design software in this way.
Sounds like the author unknowningly fell in love with OpenDoc(tm).
That’s quite possible, but again much of what he’s looking for can be done on existing systems without OpenDoc. The big difference is that it’s generally not forced on people by the operating system, and when it is, it’s generally not a current desktop OS.
> C++ was a bad fix to C, and Java cleaned everything up.
yes. all my JAVA friends always tell me how they “deploy” everything, just …. I ask how to define a “class variable”, and they need their eclipse work shell working to answer that. In this sense, JAVA is a big big playground for … ok I don’t write it :>
I agree with the comment that windows was INTENDED to work badly.. with icons in wierd places and unergonomic layout etc. Why? Because they figure most users aren’t smart enough to care or question it. They don’t bother to set an ideal or a high standard, they just give the user the minimal that they will tolerate and they focus on making a system which reflects what the market seems to be, rather than taking a leadership role. They realise that the ideal system, in business terms, will be one that looks at the current nature of society and maps itself to it. Win/MS is not interested in inspiring us or truly making our lives better or leading the way with honest practices and a truly pure system. They just want to implement whatever earns the doh. That’s why they never cared that the OS looked ugly. They figured most people are ugly so they dont care about looks. .. I know I know… sounds kinda goofy, but hey! My point is, MS makes a product that the most populance can relate to, in the position they are in, rather than how people COULD relate following a spiritual transformation.
Several of the ideas in this article are very similar to Jef Raskins “The Humane Environment”, but not quite as developed.
That is what I see w/ your “new” model of GUI. I like the flexibility I have to move windows around depending on how I work. No two people work the same and you plan to force a one-sized-fits-all approach on the user. The one thing I truely miss on a Windows desktop, that I have on Gnome and KDE, is the pushpin (always on top). I like the ability to make some app always viewable and yet still work in another app that is underneath. I can monitor a download or IRC while typing a document or surfing. I flike being able to watch a movie in a small window or window-shade xmms (either to desktop or taskbar) and still work or read other stuff.
Please don’t take away what we users have gained. The time for the model you propose was back in the day of the original Mac or Windows 1.0. Heck, when I had DOS I used Norton Commander to manipulate files and launch programs. I then had two panes open so I could copy files from one file tree location to another, but once a program was launched, the program took over the screen. Those days were OK, slow CPU and small screen real estate, but those days are gone and that 286 is gathering dust.
I know, I know, their UI has sucked since CDE but Looking Glass looks mighty yummy..
Take a look at;
Congratulations you just invented emacs. Fire it up! Fire it up!
Enjoy your Lisp VM, non-overlapping windows, simple look, only documents, invisible software sub-components, embedded text, and network aware file system.
I read the authors points about 3D interfaces in Mac OS X and the upcoming Longhorn and just laughed.
The points the author made read like he/she had absolutely no idea what he/she was talking about.
I quote;
“Sounds great? It actually isn’t. Those fancy user interfaces waste precious CPU and GPU cycles, making your computer slower than it needs to be, thus making you work slower. In return, you are distracted from your work so that your productivity is even lower.”
As someone that has been a new user of OS X for the past 2 years, I’ve found that there has never been any hinderance to my productivity due to the use of a 3D enhanced, OpenGL powered interface. In fact, I would say that my experience and productivity within and of the OS has been empowered by it.
I also laugh at the idea that the computer is slowed down by these “fancy user interfaces”. Considering that Mac OS X is typically bundled on machines which could run an entire space mission, and still render a decent version of Final Fantasy (the movie), I found this comment redundant.
There is a reason why video cards such as Radeons, and GeForce’s are being shipped with the G3/G4/G5, they are OpenGL aware, and can handle most of the rendering in the GPU of the video card. His point about a slower computer is only true on machines that don’t have 3d video cards, and are slower than today’s 400MHz XScale CPU’s from Intel.
Other parts of the article are also amusing, however, other replies have covered why.
Yes, it takes guts to write and publish an article like this, but it takes brains to make the article a good one.
why the hell did this make me think of haystack from mit?
other then that i want to comment that while kde have the default gui look and act very mutch like windows it enables you to place the “start” button anywhere on a bar or have it appear as part of the desktops rightclick menu. hell you can have the taskswitch and “systray” on a totaly diffrent bar from the “start” button. this can allso be done in gnome.
from what i recall windows dont allow for this level of custom work on the basic gui (this can be a good or a bad thing, i know).
other then that i kinda like the ideas in the article, most of all the idea of software as applets and a document senteric gui. while i like the idea of windows never overlaping, i still want to comment on the fact that some stuff work best in maximized view, therefor there is still the need for a maximize button…
The one thing a lot of people seemed to like was the document model idea, but I disagree. I personnally don’t want a simple note to myself ( say: Chrissy’s number, 555-1234 ) to take up 50 kilobytes of space, just to accomodate all the header info and markup tags in order to make it a generic document format. This is what everyone seems to want to do with XML anyway. Not a new idea.
The idea of a VM in the operating system is an interesting one, but not too feasible. This implies that all software on the os, including the kernel itself, should pass through the VM. Obviously, this cannot happen. How can you write device drivers that way? You can’t. Ok, so maybe he’s saying application software should run on the VM, but the kernel and dd’s should be native code. Ok, that means the kernel has to be designed to communicate with application software through the VM. Bottleneck. The author did say that people today want video, music, etc, did he not? Well how exactly do you propose to get smooth audio and video playback, let alone editing, IF YOU REMOVE THE HARDWARE ACCELERATION FEATURES AND MAKE THE SOFTWARE RUN IN A VM?????? Ever heard of MMX? SSE? Ever heard of the fact that mp3 audio and mpeg video is compressed with wavelet math. Have any idea how complex they are to decompress because of the wavelet math and how much data is constantly flowing through the bus? And you really think you can actually accomplish this effectively utilizing a VM???
Anyway, the author threw around quite a bit of terminology, but did anyone else notice how he didn’t really seem to understand what he was talking about? Or the fact that he invented the abbreviation GI because he didn’t know about the acronym GUI? Please don’t tell me he actually got paid to write this load of bs.
I consider myself one of those users who uses the taskbar for almost everything. When I use Windows or Gnome (i don’t use kde) i look @ the taskbar constantly to know what i have running. I don’t see overlapping windows as a problem, because all i have to do when i can’t find something is click the taskbar button. If my windows were always maximized, i think i’d freak. I’d go for more of an “always minimized” approach. I minimize everything, and like to see like one or two apps up at a time. And virtual desktops make things even easier, so i don’t see why windows are a problem. If anyone’s used Enlightenment, i think someone should expand on that idea, of looking at only half a desktop at a time, so that you can switch between two maximized apps.
I also forgot to point out one thing..
Whats the matter with having your CPU and video card used by the OS? We all know just how much a waste it is to see your brand spanking new $500 video card sitting there for 98% of the time displaying a pretty chick in a swimsuit as your wallpaper. The power is there, so why not use it?
The same can be said of the CPU. Considering that there is development of having multiple CPU’s in the one package, why not take advantage of this? Intel’s Hyperthreading Pentium 4’s and Xeons have this ability (in a limited way, however).
The author then doubles back on his prior statements about fancy user interfaces, in this quote (critical error is in bold):
‘the new OS has a GUI in which each control is drawn with hardware acceleration’.”
Just what do you think Apple OSX does? Use fairies? As I said in my earlier reply, there is a reason why 3D graphics cards are shipped with Apple PC’s.
The same is true with Longhorn. Those “fancy effects” are not going to be applied by the CPU, but they are going to be specifically made to utilise the video card’s power. Not only that, but if the author had bothered to read the hundreds (if not thousands) of articles on Aero, he/she would have noticed that there are going to be different levels of the “interface experience” (the user will only see certain effects depending on how powerful their computer is).
Now that Longhorn and Apple OSX are utilising the video cards, it is entirely feasible to have a resolution independant interface, with applications and fonts scaling to the resolution natively.
The author makes further comments about removing applications, but instead using invisible applets. Whilst this idea is radical, it is flawed. The user must be able to control the applications, and see them, as well as interact with them. How the software is used, and integrated should become invisible, but retain its usefulness and useability.
I do agree with the idea of DDF. Having the document store the format itself is a brilliant idea, and one seen in Unix, Linux, BSD, and Mac OS.
The idea of splitting a program such as a word processor into two is flawed as well. It is crucial to be able to manipulate the document at all levels, and having the functionality split will only hinder the end user. If one was to split the functionality, it would be to make one half a “reader/viewer only”, and the other the editor. Both these applications would require a seamless link and method of switching between the two modes.
Err, when I say Unix, Linux, BSD, and Mac OS store the document format itself, thats not what I mean, I mean that they don’t require document extensions, because those are internally stored. That is what I meant, and sadly, DDF is not used by afformentioned OS’s.
I do still think its a great idea.
> Put every document in XML, and then the namespace defines
> the presentation behaviour/software to use eg. svg, html,
> word(?); then piping documents would be easy, using
> XPointers or something, remote and local docs could be
> referenced.
I like this comment better than the article.
I believe the author has the right idea when he talks about not needing Windows or a visible Application program. I would compare this with the game of dungeon and dragons. Yet it would be in line with the user’s daily living experience.
Take this interaction as an example:
Where am i?
Outside your front door.
Enter house
Done.
Describe
You are in the foyer
Northwest: long narrow hallway.
South: Door to Den.
Southwest: stairway going up.
Go south.
You are in the Den.
Get Address book.
Obtained.
Lookup B.Peren
Brad Peren
123 Anystreet
Anycity, Anystate, 00000
Send email.
Is the document already typed?
No
<Bring up box to type email>
*************
This is all command line yet it can be graphic with a picture of a home, place of work, place of worship, desk, addressbook and the like and all would be touch screen/ or with a mouse. Or a CAD drawing/Map. So in general the design should be in line with the user’s daily living experience.
Sounds like Microsoft Bob.
My thoughts on this article is that it is well written and makes a good point. For a computer to be worth having, it must not take up more time than it gives, i.e. it must make my life easier without making it harder. For total newbies, the system that he described would be absolutely awesome. It would allow users to focus more on creativity and doing something with the machine rather than babysitting it (as with windows most the time, and some Linux and Mac machines sometimes).
However, this is for “normal” computer users. Administration, however, by network and server administrators, will almost always be done in the shell, and this is where unix/linux shines by allowing us to use redirection and piping to make their job easier.
These things are not opposed to each other. The computer interface is only different because the jobs we do with them are different. I’m not going to compare Windows XP to Autozone software running on Redhat 7.3, because their functions are much different. Autozone uses a two-color curses-like interface for their parts ordering system, but it is rock-stable, and does the job it was designed to do.
So, in summary, I like the article. A computer’s purpose is to do a job, and the interface should be designed around that purpose, or around being good at all functions (for multi-use desktops, like the one the author described, would be good at).
If Apple slapped their name onto that most fundamental part of the Linux Desktop, attatched to a GPL licence, then it would be in a position to steal back (at least) a big chunk of the market share.
And without any ability to charge for that, how do you think they’ll make money and stay in business ?
Lets not forget that without Quartz, OSX is essentially beefed-up FreeBSD.
No, it’s not. OS X without the GUI is Darwin, which is basically a Mach microkernel what a BSD personality combined running a bunch of userspace tools ported from the various BSDs (not just FreeBSD). Under the hood, there’s little resemblence between FreeBSD and OS X.
This is really just semantics, however, the point you’re trying to make is that without the GUI, OS X offers nothing new and is, for all intents and purposes, valueless.
Which is precisely why Apple giving away their crown jewels would be a monumentally stupid thing to do.
Incidentally, I don’t know how you can call OS X’s GUI “smooth”. The main reason I still haven’t bought a Mac is because – even with the latest revision of OS X – the GUI remains chunky and unresponsive. Windows is much snappier and even KDE or GNOME on X are no worse.
Is it really such a controversial thing to suggest that they might have an x86 port in mind?
Controversial ? Only to hardcore Mac zealots. Naive and silly ? Yes.
There were a few years there where Macs based around an x86 CPU were a distinct possibility, due to the brick wall Motorola ran into with their PPCs. Indeed, somewhere inside Apple, there were almost certainly x86-based prototypes running OS X. Similarly, Apple almost certainly keeps an up-to-date port of OS X to x86 (and possibly other platforms) simply to make sure OS X remains a portable OS and platform dependencies don’t creep in (Microsoft do the same with Windows).
However, IBM’s PPC 970 removed any need for – or benefit from – an x86 Mac.
Also, this “x86 port” of OS X would *not* have run on regular PCs. It would only have run on Apple’s x86 Macs, which would not just be regular PCs with a fancy case and a 20% markup. They would have had fundamental architectural differences (eg: Open Firmware instead of a traditional PC BIOS, no ISA bus, no legacy ports, etc). It would probably have been possible to hack x86 Darwin to run x86 OS X on a regular PC – but the EULA would have made it illegal (much like the current OS X EULA says you can’t run OS X on non-Apple systems).
This is also ignoring the fact none of the important software packages would work on x86 OS X.
This is all because Apple doesn’t sell OSes, they sell systems. Their main selling point *is* OS X, true, but OS X’s real advantages stem from the way Apple control both the software *and* the hardware. Standalone OSes (like Windows and Linux) simply can’t match this (and it appears a significant number of people don’t consider that a big problem). Apple knows this, which is why they killed the Mac cloners and why they never ventured into the market of OSes for mass produced, commodity hardware.
Especially with the Darwin source-code and x86 install openly available on their site.
The technical issues around an x86 port – even to regular PCs – of OS X are trivial. Apple could probably have most of it done in a week. The political, practical and business issues are *huge*. It’s not going to happen. Even if it did, OS X wouldn’t run on regular PCs and Macs wouldn’t be any cheaper.
Great! Let’s start all over again with the Open Source movement. Longhorn won’t be there for two years or more. Everybody is afraid of what Micro$oft will produce. Well, I’ll tell you this: it will be a critical cleanup, not to say: a rebuild. They got a serious problem and will have to rebuild the entire kernel. When it comes, it will most certainly be bugridden and flawed. In spite of all the marketing hype, it will need at least another two years before it is ready to rock ‘n roll.
We got proven technology, rock-solid, and still plenty of room for improvement. Note that Unix is most of all an ARCHITECTURE and one of the most successful that the world has ever seen. You can expand it, plug new stuff into it and it will continue to run.
Instead of starting at square one, we should use those four years to expand the functionality, add new concepts WITHOUT losing the advantage we already got. Sure, we do need original ideas and new concepts and we should apply them, but we should not get lured into starting all over.
For all reasons, there is no need to! We GOT a good kernel, we GOT a good architecture. And now we got the opportunity not to imitate Windows, but surpass it. And once they got catching up to do, we win.
I’m glad that I can use my Linux without being bothered by alpha concepts like “objects”, “methods”, etc. I never understood OO until I found out that it was just a bunch of structures and pointers to functions. I’m glad I don’t have an operating system that forces this “geitenharenwollensokken” jargon on to me, thank you!
I’m sorry, but the article is interesting in scope but badly implemented. When discussing things we can’t always pretend to know nothing, we have to use established concepts to communicate. None of your ideas are new. (The object desktop example is good, exactly ALL the major players were heading that way some nine years ago) Now the interesting thing is, why don’t we have them today? Is it your development model that will be different this time? Or the unique combination of concepts? Pray tell us, because THAT is what would be interesting to read!
While reading your article I had to think of Oberon.
So before you start with your own implementation have a look at:
Have a look at
It is able to run on an own os and the idea of the gui is quit simlar to your ideas.
… that we should continue to work on useability. It is an issue.
What he says about making the installation of a network, an OS, or whatever easier, is quite flawed. Any enduser who is not able or willing to address installation problems, as they invariably may occur, really, regardless of efforts to make it easier, should not perform the installation by himself, but find someone who has that ability and/or willingness to face such problems when they occur. Case closed.
Eugenia, why the hell do you put this kind of crap on your site?
I’m so mixed in opinion about osnews.com. Generally its good, and then there’s stories like this that make it appear as if anyone simple willing to write an article for you will get it published.
Ugh.
I can’t believe I just spent all this time reading such a useless article!
I did get a little teary-eyed when OLE was mentioned – I remembered the beauty of OpenDoc. I wish that technology would have survived.
There are few innovative ideas here. There is not much that I haven’t already heard of.
And for one thing, I don’t like the proposed return of Xero non-overlapping windows. Screen real-estate is small as it is. Beside, I like to see the cool windows semi-transparency with overlapping windows on Mac OS X and Linux. 🙂
Well, I tried to read most of the comments posted, so I’ll reply to some of them.
I stopped reading at Java > C++ > C. Maybe you are right, in that case I hope you enjoyed the joke. The only thing I “know” about them is that:
1. Java looks like C# (as explained in C’T)
2. Gnome people use C and say C# is lots better than C++
3. C++ is an extension to C.
So how have I concluded the wrong thing? Please explain!
What you write is crap / You know nothing about GUI design. Maybe. I do not claim to be a usability expert. But that does not mean I have read nothing about usability. A quick investigation: I read about Fitt’s Law, Hicks Law
Now that I think about it: scrollbars at the right are useful, as (in maximized windows) they conform Fitts Law. Problem here is the mouse pointer, however, as you can’t see it when you move the mouse to the right -> bad usability.
Also, the OS X menu is a good idea. The *STEP one too, but it were even better if it popped up at the mouse pointer, like in RiscOS.
POSIX doesn’t mean no GUI But having POSIX encourages utilities like ls, cp, rm, tar, gzip and gcc to be ported, and those have bad usability.
Emacs! Is confusing. For example, there is no clear way of creating a new document. And it has no capabilities for spreadsheets and so on (just like Screen).
KDE != Windows. True. But I looked at the default setup and found that KDE copied the Windows fault of putting Maximize next to Close.
Overlapping windows are useful. For drag and drop, indeed. IMHO drag-and-drop is a clear way of doing certain things, as it is clear to the user what is moved from where to where. For the rest, they are confusing. My mother, for example, had that Outlook Express problem (and related ones) more than once.
By the way, both applications I am running now (Mozilla and Delphi) are maximized.
And now that I think about it: why is Tabbed Browsing so popular, when windows are such useful things? For normal webbrowsing, they are very practical, but not for File Management – at least not in Konqueror as there you can’t drang-and-drop files between tabs.
Aqua is the best GUI Now imagine the KDE Control Center were an Aqua application.
Drop shadows behind menus and windows can be useful, I agree.
It’s not innovative. It isn’t revolutionary, indeed, so there is (relatively) even less innovation. It’s still WIMP, indeed, but most computers are. Additionally, layouting and editing a text document is still most easy on something with a screen and input devices, I think.
Note that I have nothing against doing away the mouse+keyboard, make a tablet PC with a screen on which you write with a pen using handwriting recognition. Then, the PC becomes some kind of A4 paper, but with lots more of possibilities.
Innovation is difficult. I once wrote an essay about spelling reform, about all kind of aspects of reform I had never previously heard about. Years later, I read a book about spelling reform and it turned out that I had compiled a list of about all arguments other reformers had made, nothing more and nothing less.
IMO, the most “innovative” things are the GUI pipes. They allow things like placing graphs in a document without having a hidden spreadsheet behind it, like in Office. And they make document-based software more modular.
The network thing was mostly practical. I think about the network as a tool, that should be as flexible as possible. Work Anywhere, at Work and at Home. Automagically 🙂
Your ideas are old and they simply never caught on. That does not mean they are bad. Video2000 was better than VHS, I have been told. VHS has become the standard, however, as it was cheaper. And MS-DOS didn’t win form Caldera’s DOS because it was better, but because Windows 3.1 was made not to work on the latter.
How about CD players/burners, …? The fixed-size windows containing no documents. Good question.
But then – my proposal was some kind of task-based UI. Editing a document can be seen as a task. Playing a CD too. So the CD player should get its own “screen”, just like the calculator. The application will then run as a dialog with just no document behind it.
Multiple monitors. If you have two monitors, then you should be able to either have one application appear on both, or have each monitor display one application.
You focus only on UI. Indeed. Technology works behind the scene, and in the end the User is where it is all about. They want a system that Just Works, no matter whether EtherTalk or mDNS+TCP+IPv6 are at work. Actually, I already wrote that, at the end of the article.
Behind the scenes, I have no doubt there are innovations happening. WinFS. ReiserFS4. mDNS. RendezVous. CUPS. IPv6. All great technologies (if I’m not mistaken). But they don’t really ease the life of the end user if they can’t be used easily.
Final note: nice to see it at least raises a discussion.
I think not, not in the way the author describes it. Yes, UIs will continue to be graphical, but not to the exclusion of CLIs.
The CLI is the best user interface for most activities. The mouse is a curse; as most UI experts will tell you, you want to minimize the user having to move her hands between the keyboard and the mouse. A predominantly GUI based UI maximizes the amount a user has to move their hands between the mouse and the keyboard.
The problem has always been that the CLI is limited in its ability to interpret what the user wants. A smart CLI would allow the user to tell the computer what she wants, and is the step in between what we have now and the future where the computer can communicate with the user with normal speech. Even then, the keyboard will probably lurk around for tasks that would be tedious to dictate, such as editing documents. | https://www.osnews.com/story/6633/designing-the-operating-system-of-tomorrow/ | CC-MAIN-2019-51 | refinedweb | 17,473 | 70.43 |
access TX/RX on fipy + pytrack :
Hello,
Could you please explain me how to access the TX/RX of the fipy/pytrack. I would like to retrieve the data from the GPS and the Accelerometer data using UART but I'm not quite sure to understand how to proceed on the board.
I just use Sigfox and the GPS/Accelerometer , and by default I deactivated the wifi/bt
pycom.wifi_on_boot(False).
Thanks.
@testos Yes, you need to connect to the external IO header below the fipy. And you have to specify these Pins, when you open the UART, most likely UART1. On a Fipy, two of the three UARTs are already used by the firmware UART0 and maybe UART2. You have to try.
Hello @robert-hh,
it's a bit related to my question last day in a different thread, I thought it could be better to create a dedicated one.
You are right I could get the data from the USB but would like to send the data to pi zero. I do understand the "coding" part, what I don't understand is how should I do the wiring on the pytrack, I need to connect to the external IO header ?
Thanks for your patience
@testos I do not understand you intention. If you use pytrack, the the UART/USB bridge will forward the communication over UART0 to the USB serial.
If you want to use another UART for that, you have to open that, like:
from machine import UART uart = UART(1, baudrate=19200, pins=('P9','P10'))
Note that I reassigned the UART1 pins from their default assignment to P9 and P10 to avoid a conflict with the SD card.
And then you can use uart.write() to send, uart.read() to receive, uart.any() to tell, whether there is data in the input buffer, etc.... | https://forum.pycom.io/topic/4180/access-tx-rx-on-fipy-pytrack/4 | CC-MAIN-2019-30 | refinedweb | 308 | 79.6 |
These any main stream Linux machine but with open source efforts of Microsoft, it is also available for windows.
So I decided to install, configure and run Redis server on Ubuntu Server 13.10 and fiddle with it using C# redis client libraries available.
I am using Microsoft Azure Cloud Service (recommended for your cloud needs) for creating Redis server, you can do the same on your local Ubuntu machine, VM or any other cloud service you prefer.
Step: Create and setup Ubuntu Server 13.10 in the cloud
Step: Connect to your newly created Ubuntu Server 13.10 using SSH.
Now let me take a few lines to introduce CMDER, console / terminal emulator for Windows. I came to know about this awesome tool from Scott Hanselman’s Newsletter of Wonderful Things (thanks), December 17th, 2013 edition. Gawd now I cannot stand a windows command prompt on my screen.
So fire command window (cmder in my case) and connect to the Ubuntu Server using SSH.
$ ssh {your-ubuntu-machine-name-or-ip-address} –l {username}
Step: Make sure your Ubuntu machine is update-to-date (not mandatory, but no harm).
$ sudo apt-get update
Step: To install redis using source files, you will require the packages to build source (so called "build essentials")
$ sudo apt-get install build-essential
Note: If you want to check if the above or below packages are installed or not use the following command on Ubuntu or Debian
$ dpkg –s {package-name}
you will receive message “package ‘{package-name}’ is not installed and no information is available” if it was not installed.
Step: Next we need to install TCL package before you can start installing Redis server (Imp: I got errors on building source when I didn't installed TCL).
$ sudo apt-get install tcl8.5
Step: Download Redis release stable source code
$ wget
Step: Untar / extract the downloaded .tar.gz and navigate to the extracted folder
$ tar xzf redis-stable.tar.gz $ cd redis-stable.tar.gz
Note: You can find the version of this Redis source in “[redis-folder]/src/version.h”. Mine is 2.8.3 at the time of writing.
Step: Now we compile the source with make command
$ make
Step: Test your compilation (not mandatory, but no harm)
$ make test
Step: Now that redis source code is compiled we install it
$ sudo make install
Step: Redis source comes with some helpful scripts, can be found in “[redis-folder]/utils”. One of the scripts we are interested is the one that configures Redis to run as a background process.
$ cd utils $ sudo ./install_server.sh
- Default port number: 6379
- Default redis config file name: /etc/redis/6379.conf
- Default redis log file name: /var/log/redis_6379.log
- Default data directory for this instance: /var/log/redis/6379
- Default redis executable path: /usr/local/bin/redis-server
Step: Commands to start / stop redis server (the number is the one you set while running the previous command, 6379 in my case)
To start Redis server:
$ sudo service redis_6379 start
To stop Redis server:
$ sudo service redis_6379 stop
Step: You can check if the redis server is running and listening on your configured port number using following command. The number is the one you set while running install_server.sh script, 6379 in my case)
$ netstat –nlpt | grep 6379
Step: To set redis to run automatically on each boot use the following command
sudo update-rc.d redis_6379 defaults
Step: To verify if redis server is listening on IP-Address / host where you are expecting it to, run the following command
$ redis-cli –h {ip-address-or-host} ping
you will receive “PONG” as response if everything is setup correctly.
Note: Azure users need to add “6379” in their endpoint settings page for target virtual machine, if not then redis will only PONG for internal IP Address and not for Public Virtual IP (VIP) Address.
To customize your redis instance you can modify
/etc/redis/6379.config file.
So you have a fine Redis up and running at this point.
Fire your Davenvy (devenv :D) and create a sample to connect with Redis server, add some data and retrieve the same.
For demo purpose I am going to use Boolsleeve but all the listed C# clients are great and fast especially ServiceStack.Redis, Booksleeve and Sider (no judging). Choose one depending on your needs.
C# client code using Booksleeve:
namespace Fiddling.RedisClient { #region Namespace using System; using System.Text; using System.Threading.Tasks; using BookSleeve; #endregion /// <summary> /// Default program class for console application. /// </summary> public class Program { /// <summary> /// Main method. /// </summary> /// <param name="args">Input arguments.</param> private static void Main(string[] args) { var doRedisTask = Task.Run(() => DoRedis()); doRedisTask.Wait(); Console.ReadLine(); } /// <summary> /// Do something with Redis server. /// </summary> /// <returns>Task of void.</returns> private static async Task DoRedis() { using (var connection = new RedisConnection("your-redis-server-ipaddress-port-number")) { await connection.Open(); await connection.Strings.Set(12, "key01", "value01"); var value = connection.Strings.Get(12, "key01"); var storeValue = await value; Console.WriteLine(Encoding.UTF8.GetString(storeValue)); } } } }
Enjoy your fiddling with Redis.
Happy Coding !! | https://blog.jsinh.in/install-configure-and-consume-redis-data-store-running-on-ubuntu-with-csharp/ | CC-MAIN-2018-13 | refinedweb | 848 | 56.76 |
MooseX::APIRole - automatically create API roles for your classes and roles
version 0.01
If you write a Moose class like this:
package Class; use Moose; use MooseX::APIRole; use true; use namespace::autoclean; sub foo {} make_api_role 'Class::API'; __PACKAGE__->meta->make_immutable;
MooseX::APIRole will automatically create an API role like this:
package Class::API; use Moose::Role; requires 'foo';
And apply it to your class.
If you forget what you called the API role, or don't want the API role to have a name, you can get at it via the metaclass:
my $role = Class->meta->get_api_role;
You can then treat
$role like you would any other role.
You can also create API roles for roles:
package Role; use Moose::Role; use MooseX::APIRole; use true; use namespace::autoclean; sub foo {} requires 'bar'; make_api_role 'Role::API';
This results in the following role:
package Role::API; use Moose::Role; requires 'foo'; requires 'bar';
If you do not call
make_api_role or
apply_api_role, you can still get the lazily-built anonymous API role via the metaclass. But the class won't
does_role the role, which could be confusing.
Inheritance is handled such that if
Subclass extends
Class with API role
APIRole,
Subclass will also do the
APIRole. The same applies to roles; if
Role does
RoleAPI and
AnotherRole consumes
Role, then
AnotherRole will also do
RoleAPI.
Wunderbar.
You can control the behavior of this module by calling these imported functions:
This is the namespace that you want the API role to be in. The results of using an existing class name are undefined. It's likely that demons will come out of your nose and all your plants will die. So come up with a unique name.
If you want the API role to be applied to your class or role, call this function.
You almost always want to do this, but it can't be done automatically for the same reason that
Class->meta->make_immutable can't be done automatically.
Works like
set_api_role_name followed by
apply_api_role.
See MooseX::APIRole::Meta for the metaclass attributes you get.
Jonathan Rockway <jrockway@cpan.org>
This software is copyright (c) 2010 by Jonathan Rockway.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. | http://search.cpan.org/~jrockway/MooseX-APIRole-0.01/lib/MooseX/APIRole.pm | CC-MAIN-2016-07 | refinedweb | 384 | 68.5 |
Important: Please read the Qt Code of Conduct -
[SOLVED] Cropping an image using QLabel and QPixmap
- qurban_ali36 last edited by
Hi,
I want to take a screenshot of my desktop screen and then crop that image by drawing a rectangle on it. So for I am able to capture the screenshot as QPixmap, set it on QLabel and displayed as a window (window.showMaximized()). I am also able to draw a rectangle on QLabel using mouse events and paintEvent of QLabel.
The problem is that, when the paintEvent is called to draw the rectangle, the actual image vanishes from the QLabel.
How can I draw a rectangle on QLabel without loosing the pixmap?
Here is the code:
@
class Label(QLabel):
def init(self, parent = None):
super(Label, self).init(parent)
self.mousePos = QPoint()
self.mouseDown = False
self.rect = QRect()
self.setPixmap(QPixmap.grabWindow(QApplication.desktop().winId()))
def mousePressEvent(self, event): self.mouseDown = True self.mousePos = event.pos() self.rect.setTopLeft(self.mousePos) def mouseReleaseEvent(self, event): self.rect.setBottomRight(event.pos()) self.repaint() def mouseMoveEvent(self, event): if self.mouseDown: self.rect.setBottomRight(event.pos()) self.repaint() def paintEvent(self, event): if self.rect.x() > 0: painter = QPainter(self) painter.setPen(QPen(Qt.black, 1, Qt.SolidLine)); painter.drawRect(self.rect);
@
- raven-worx Moderators last edited by
for such purposes check QRubberBand class on top (as a child widget) of the label
- qurban_ali36 last edited by
Thank you very much :) It worked like a charm.
btw, how to make this post as "solved"? I am new to qt-project.org
- raven-worx Moderators last edited by
just edit your first post and prepend [SOLVED] to the title. | https://forum.qt.io/topic/31388/solved-cropping-an-image-using-qlabel-and-qpixmap | CC-MAIN-2021-39 | refinedweb | 277 | 51.55 |
Today, we’ll be talking about something controversial: static methods. I have yet to read anything that says static methods are good and useful, other than Effective Java recommending them in the use of static factory methods. There are some really interesting (and somewhat defective) arguments out there against them that rarely, if ever, even get explained. Notably, I’m providing a rebuttal to the article, Utility Classes Have Nothing to do With Functional Programming.
Today, we’re going to look at the good and bad of static methods; what they’re good for and what they’re not.
Static Methods are What Pure Functional Languages Use
As you probably know, functional programming has returned to our world as the “in” thing to do, and most OO languages have been adopting first-class functions (or some way to represent them, anyway) in order to be more of a hybrid between OO and FP.
In pure FP, there aren’t any classes; there are data types and functions. Those functions are not attached to any types, just namespaces. The same goes for static methods. They aren’t attached to types, they just have a namespace. Some might think that they are attached to types, since you have to put them in classes. But when it comes to static methods, the classes that are using them aren’t acting as classes; they only serve as namespaces for the static methods, a way to import them and differentiate them from other functions that might have the same name and arguments in a different namespace.
As long as both are able to do the same thing (which they practically can, when higher-order methods are available), they are the same. Things like currying only make functional programming more convenient are aren’t strictly necessary, in my opinion. So this doesn’t disqualify static methods from being the same thing.
There is one difference – an important one – between functions in pure functional programming and static methods: static methods can have side effects. For the sake of argument, we’ll assume we’re good programmers, though, and that we make our static methods pure. Or, at least mostly pure. There shouldn’t be any external side effects, at least, and these are the side effects I’ll refer to from now on. At the end, we’ll come back to this and look at the kind of difference it makes.
The Arguments
Now that we know that FP functions and static methods are essentially the same thing, let’s look at the arguments, shall we?
Imperative vs Declarative: In the linked article above, the author argues that FP functions are declarative while static methods are imperative. In truth, either can be either.
People tout that FP is declarative while OO is imperative. I’ve looked at this for a while and have come to the conclusion each simply makes one or the other the obvious way to do it. All the declarative building blocks of FP can be done in OO, and FP has the many of the same pieces available that make up imperative code. This is why Java’s Stream API is declarative; even if you don’t use lambdas or method references, you can use it declaratively with well-named functions and classes.
Even the other guy mentioned that you can be declarative in OO.
Testability: The complaint isn’t so much that static methods are hard to test (the claim is that FP is easy to test, so this better not be the case), but that things that use them are harder to test, since the calls are hard-coded and cannot be swapped out for others during testing. I have several rebuttals to this:
- Some parts of your functionality shouldn’t or don’t need to be swapped out, even for testing. If there are no side effects caused by the static method, there is almost no reason that it needs to be swapped out. If FP can handle this and still be called testable, so can static methods.
- You can swap out static methods. The trick is to take in a function as a parameter, where the static method can be supplied as an argument. “But then the static method gets hard-coded at the call site,” one might say. I say back, “Something has to get hard-coded somewhere.” Even with DI systems, we either tell it explicitly which specific class to use to fulfill a dependency, or it’s able to deduce it somehow; in either case, a specific class is used and therefore “hard-coded”. At some point, the dependency implementations must be chosen.
- If we can accept types that cannot be subclassed (String, for example) and use their methods, then there’s no fundamental difference between those methods and static methods, other than encapsulation. Sure, the primary object is passed as an argument instead of being what the method is called from, but that’s a semantic difference, not functional.Polymorphism doesn’t apply in those cases, so you can’t swap anything out other than the class’instance, which can also be done with static methods. No one says not to use those, though; in fact, preventing subclassing is often lauded as a virtue.
So, yeah, static methods are not fundamentally less testable.
Readability: By this, the original author talks about how huge utility classes get, collecting dozens and dozens of static methods. To that, I say that these utility classes are usually for classes that areextremely generic, and there’s a lot you should be able to do with them, which is what makes the utility classes big. Most of those utility methods should have been on the original class, making themreally big instead.
Efficiency: Next, he seems to claim that static methods are inherently eager and cannot be lazy. While this isn’t true, making them lazy largely just turns the static methods into static factory methods, since they’d have to create an object of a type that makes the operation lazy. FP languages have less of a problem with this because it’s the language that provides the laziness, so we can still write as if it’s eager, and it won’t be. Though, some forms of laziness can be used without language conventions or specialized objects. Simply accepting a value-generating function instead of a straight value as an argument that will only be used if/when needed is laziness.
Laziness isn’t always the ideal, though. In those instances when we’re definitely going to need the calculation, and right away, the overhead of creating the lazy operation wrapper supersedes the benefit of being able to put off the operation.
Devil’s Advocate
Now that I’ve said all that, it’s time for us to pull back a bit. I’m not saying to switch to all static methods; I don’t think being a purist in either direction is the way to go. Personally, I actually lean away from static methods as anything other than factory methods, as “replacements” for constructors. Also, they can be good for fluent interfaces, such as in matcher and testing libraries.
If you’re going to try and go mostly FP in a hybrid language, you may end up using more static methods, but there’s certainly nothing wrong with doing a normal method call. Go full on static should make us change our approach though. Generally, FP languages provide very powerful generic data structures and use them for just about everything, making new types only when it becomes less tedious to do so. This allows for reuse of functions more easily, keeping to total count down.
There’s an interesting inverse dynamic between functions using a family of types in FP compared to families of types with a shared interface of methods in OO. In true FP, it’s easier to add new functionality to the family of types, because you only need to write a single function to handle the different possibilities, but adding a new type to the family requires a change to all the already created functions. In OO, polymorphism allows us to add a type to a family without it affecting practically any old code, but adding a method to the family requires a change to every type in the family. In this sense, neither is inherently better than the other.
We probably shouldn’t overload our code bases with a ton of utility classes, as the article says (though ones for classes as generic as Strings, Dates, and Files probably aren’t as bad as people make them out to be), but neither should we ignore the fact that, sometimes, a static method serves a purpose better than objects and normal methods. Pragmatism should be used; do what’s best for the situation.
Static Method Guidelines
Whatever you do, don’t directly use static methods that are impure, that have side effects; any side effect calls should be swappable for testing. It’s slightly okay to create impure static methods, though it’s a dangerous idea, since it’s less obvious how to factor those method dependencies out for swappability.
When making our own static methods, keep them short, like anything else; this helps to keep the testability of the methods high.
If we’re working in a language with static methods, we should probably lean toward instances and methods and polymorphism, as that is where the language likely shines.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/static-methods-are-fine-1 | CC-MAIN-2017-22 | refinedweb | 1,597 | 58.11 |
cobra alternatives and similar packages
Based on the "Standard CLI" category
urfave/cli9.8 9.3 cobra VS urfave/cliA small package for building command line apps in Go.
kingpin8.9 5.4 cobra VS kingpinA command line and flag parser supporting sub commands.
The Platinum Searcher8.8 0.0 cobra VS The Platinum SearcherA code search tool similar to ack and the_silver_searcher(ag). It supports multi platforms and multi encodings.
go-flags8.4 0.0 cobra VS go-flagsgo command line option parser
Dnote8.3 8.3 cobra VS DnoteA simple and end-to-end encrypted notebook for developers.
readline8.3 0.0 cobra VS readlineA pure golang implementation that provide most of features in GNU-Readline under MIT license.
pflag8.1 3.2 cobra VS pflagDrop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.
docopt.go7.9 0.0 cobra VS docopt.goA command-line arguments parser that will make you smile.
mitchellh/cli7.7 2.8 cobra VS mitchellh/cliA Go library for implementing command-line interfaces.
cli-init7.5 0.0 cobra VS cli-initThe easy way to start building Golang command line application.
liner7.3 0.9 cobra VS linerA Go readline-like library for command-line interfaces.
complete7.1 3.2 cobra VS completeWrite bash completions in Go + Go command bash completion.
mow.cli7.1 1.3 cobra VS mow.cliA Go library for building CLI applications with sophisticated flag and argument parsing and validation.
flaggy7.0 6.2 cobra VS flaggyA robust and idiomatic flags package with excellent subcommand support.
cli6.9 1.6 cobra VS cliA feature-rich and easy to use command-line package based on golang tag
ops6.5 7.6 cobra VS opsUnikernel Builder/Orchestrator.
argparse5.6 6.0 cobra VS argparseCommand line argument parser inspired by Python's argparse module.
climax5.4 0.0 cobra VS climaxAn alternative CLI with "human face", in spirit of Go command
sflags4.7 0.3 cobra VS sflagsStruct based flags generator for flag, urfave/cli, pflag, cobra, kingpin and other libraries.
commandeer4.6 3.9 cobra VS commandeerDev-friendly CLI apps: sets up flags, defaults, and usage based on struct fields and tags.
wmenu4.6 2.8 cobra VS wmenuAn easy to use menu structure for cli applications that prompts users to make choices.
flag4.4 4.4 cobra VS flagA simple but powerful command line option parsing library for Go support subcommand
1build4.4 7.5 cobra VS 1buildCommand line tool to frictionlessly manage project-specific commands.
ukautz/clif4.4 0.0 cobra VS ukautz/clifA small command line interface framework.
job3.7 4.4 cobra VS jobJOB, make your short-term command as a long-term job.
calories3.3 0.0 cobra VS caloriesCalories Tracker for the Commandline
gocmd3.1 0.0 cobra VS gocmdGo library for building command line applications.
wlog3.0 1.9 cobra VS wlogA simple logging interface that supports cross-platform color and concurrency.
clîr2.9 6.4 cobra VS clîrA Simple and Clear CLI library. Dependency free.
cmdr2.9 9.5 cobra VS cmdrA POSIX/GNU style, getopt-like command-line UI Go library.
strumt2.8 3.9 cobra VS strumtLibrary to create prompt chain.
flagvar2.6 2.5 cobra VS flagvarA collection of flag argument types for Go's standard flag package.
go-getoptions2.2 7.1 cobra VS go-getoptionsGo option parser inspired on the flexibility of Perl’s GetOpt::Long.
go-commander2.0 1.1 cobra VS go-commanderGo library to simplify CLI workflow.
go-cli1.8 4.1 cobra VS go-cliA full-featured and easy to use command-line package
argv1.5 2.7 cobra VS argvA Go library to split command line string as arguments array using the bash syntax.
sand1.3 0.0 cobra VS sandSimple API for creating interpreters and so much more.
ts1.0 1.6 cobra VS tsTimestamp convert & compare tool.
Go-Console0.4 7.5 cobra VS Go-ConsoleGoConsole allows you to create butifull command-line commands with arguments and options. (follow the docopt standard)
multi-tailf0.3 0.0 cobra VS multi-tailfwatch multiple logs on local or remote servers.
hiboot cli0.2 - cobra VS hiboot clicli application framework with auto configuration and dependency injection.
Do you think we are missing an alternative of cobra or a related project?
Popular Comparisons
README
Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
Cobra is used in many Go projects such as Kubernetes, Hugo, and Github CLI to name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
Table of Contents
- Overview
- Concepts
- Installing
- Getting Started
- Using the Cobra Generator
- Using the Cobra Library
- Working with Flags
- Positional and Custom Arguments
- Example
- Help Command
- Usage Message
- PreRun and PostRun Hooks
- Suggestions when "unknown command" happens
- Generating documentation for your command
- Generating bash completions
- Generating zsh completions
- Contributing
- License
Overview
Concepts
Cobra is built on a structure of commands, arguments & flags.
Commands represent actions, Args are things and Flags are modifiers for those actions.
The best applications will read like sentences when used. Users will know how to use the application because they will natively understand how to use it.
The pattern to follow is
APPNAME VERB NOUN --ADJECTIVE.
or
APPNAME COMMAND ARG --FLAG
A few good real world examples may better illustrate this point.
In the following example, 'server' is a command, and 'port' is a flag:
hugo server --port=1313
In this command we are telling Git to clone the url bare.
git clone URL --bare
Commands
Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action.
In the example above, 'server' is the command.
Flags
A flag is a way to modify the behavior of a command. Cobra supports fully POSIX-compliant flags as well as the Go flag package. A Cobra command can define flags that persist through to children commands and flags that are only available to that command.
In the example above, 'port' is the flag.
Flag functionality is provided by the pflag library, a fork of the flag standard library which maintains the same interface while adding POSIX compliance.
Installing
Using Cobra is easy. First, use
go get to install the latest version
of the library. This command will install the
cobra generator executable
along with the library and its dependencies:
go get -u github.com/spf13/cobra/cobra
Next, include Cobra in your application:
import "github.com/spf13/cobra"
Getting Started
While you are welcome to provide your own organization, typically a Cobra-based application will follow the following organizational structure:
▾ appName/ ▾ cmd/ add.go your.go commands.go here.go main.go
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
package main import ( "{pathToYourApp}/cmd" ) func main() { cmd.Execute() }
Using the Cobra Generator
Cobra provides its own program that will create your application and add any commands you want. It's the easiest way to incorporate Cobra into your application.
Here you can find more information about it.
Using the Cobra Library
To manually implement Cobra you need to create a bare main.go file and a rootCmd file. You will optionally provide additional commands as you see fit.
Create rootCmd
Cobra doesn't require any special constructors. Simply create your commands.
Ideally you place this in app/cmd/root.go:
var rootCmd = &cobra.Command{ Use: "hugo", Short: "Hugo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
You will additionally define flags and handle configuration in your init() function.
For example cmd/root.go:
package cmd import ( "fmt" "os" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( // Used for flags. cfgFile string userLicense string rootCmd = &cobra.Command{ Use: "cobra", Short: "A generator for Cobra based Applications", Long: `Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, } ) // Execute executes the root command. func Execute() error { return rootCmd.Execute() } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>") viper.SetDefault("license", "apache") rootCmd.AddCommand(addCmd) rootCmd.AddCommand(initCmd) } func er(msg interface{}) { fmt.Println("Error:", msg) os.Exit(1) } func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { er(err) } // Search config in home directory with name ".cobra" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".cobra") } viper.AutomaticEnv() if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
Create your main.go
With the root command you need to have your main function execute it. Execute should be run on the root for clarity, though it can be called on any command.
In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
package main import ( "{pathToYourApp}/cmd" ) func main() { cmd.Execute() }
Create additional commands
Additional commands can be defined and typically are each given their own file inside of the cmd/ directory.
If you wanted to create a version command you would create cmd/version.go and populate it with the following:
package cmd import ( "fmt" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(versionCmd) } var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of Hugo", Long: `All software has versions. This is Hugo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") }, }
Working with Flags
Flags provide modifiers to control how the action command operates.
Assign flags to a command
Since the flags are defined and used in different locations, we need to define a variable outside with the correct scope to assign the flag to work with.
var Verbose bool var Source string
There are two different approaches to assign a flag.
Persistent Flags
A flag can be 'persistent' meaning that this flag will be available to the command it's assigned to as well as every command under that command. For global flags, assign a flag as a persistent flag on the root.
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
Local Flags
A flag can also be assigned locally which will only apply to that specific command.
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Local Flag on Parent Commands
By default Cobra only parses local flags on the target command, any local flags on
parent commands are ignored. By enabling
Command.TraverseChildren Cobra will
parse local flags on each command before executing the target command.
command := cobra.Command{ Use: "print [OPTIONS] [COMMANDS]", TraverseChildren: true, }
Bind Flags with Config
You can also bind your flags with viper:
var author string func init() { rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) }
In this example the persistent flag
author is bound with
viper.
Note, that the variable
author will not be set to the value from config,
when the
--author flag is not provided by user.
More in viper documentation.
Required flags
Flags are optional by default. If instead you wish your command to report an error when a flag has not been set, mark it as required:
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") rootCmd.MarkFlagRequired("region")
Positional and Custom Arguments
Validation of positional arguments can be specified using the
Args field
of
Command.
The following validators are built in:
NoArgs- the command will report an error if there are any positional args.
ArbitraryArgs- the command will accept any args.
OnlyValidArgs- the command will report an error if there are any positional args that are not in the
ValidArgsfield of
Command.
MinimumNArgs(int)- the command will report an error if there are not at least N positional args.
MaximumNArgs(int)- the command will report an error if there are more than N positional args.
ExactArgs(int)- the command will report an error if there are not exactly N positional args.
ExactValidArgs(int)- the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the
ValidArgsfield of
Command
RangeArgs(min, max)- the command will report an error if the number of args is not between the minimum and maximum number of expected args.
An example of setting the custom validator:
var cmd = &cobra.Command{ Short: "hello", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("requires a color argument") } if myapp.IsValidColor(args[0]) { return nil } return fmt.Errorf("invalid color specified: %s", args[0]) }, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, World!") }, }
Example
In the example below, we have defined three commands. Two are at the top level and one (cmdTimes) is a child of one of the top commands. In this case the root is not executable meaning that a subcommand is required. This is accomplished by not providing a 'Run' for the 'rootCmd'.
We have only defined one flag for a single command.
More documentation about flags is available at
package main import ( "fmt" "strings" "github.com/spf13/cobra" ) func main() { var echoTimes int var cmdPrint = &cobra.Command{ Use: "print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, } var cmdEcho = &cobra.Command{ Use: "echo [string to echo]", Short: "Echo anything to the screen", Long: `echo is for echoing anything back. Echo works a lot like print, except it has a child command.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Echo: " + strings.Join(args, " ")) }, } var cmdTimes = &cobra.Command{ Use: "times [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user by providing a count and a string.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, } cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") var rootCmd = &cobra.Command{Use: "app"} rootCmd.AddCommand(cmdPrint, cmdEcho) cmdEcho.AddCommand(cmdTimes) rootCmd.Execute() }
For a more complete example of a larger application, please checkout Hugo.
Help Command
Cobra automatically adds a help command to your application when you have subcommands. This will be called when a user runs 'app help'. Additionally, help will also support all other commands as input. Say, for instance, you have a command called 'create' without any additional configuration; Cobra will work when 'app help create' is called. Every command will automatically have the '--help' flag added.
Example
The following output is automatically generated by Cobra. Nothing beyond the command and flag definitions are needed.
$ cobra help.
Help is just a command like any other. There is no special logic or behavior around it. In fact, you can provide your own if you want.
Defining your own help
You can provide your own Help command or your own template for the default command to use with following functions:
cmd.SetHelpCommand(cmd *Command) cmd.SetHelpFunc(f func(*Command, []string)) cmd.SetHelpTemplate(s string)
The latter two will also apply to any children commands.
Usage Message
When the user provides an invalid flag or invalid command, Cobra responds by showing the user the 'usage'.
Example
You may recognize this from the help above. That's because the default help embeds the usage as part of its output.
$ cobra --invalid Error: unknown flag: --invalid.
Defining your own usage
You can provide your own usage function or template for Cobra to use. Like help, the function and template are overridable through public methods:
cmd.SetUsageFunc(f func(*Command) error) cmd.SetUsageTemplate(s string)
Version Flag
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
Running an application with the '--version' flag will print the version to stdout using
the version template. The template can be customized using the
cmd.SetVersionTemplate(s string) function.
PreRun and PostRun Hooks
It is possible to run functions before or after the main
Run function of your command. The
PersistentPreRun and
PreRun functions will be executed before
Run.
PersistentPostRun and
PostRun will be executed after
Run. The
Persistent*Run functions will be inherited by children if they do not declare their own. These functions are run in the following order:
PersistentPreRun
PreRun
Run
PostRun
PersistentPostRun
An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's
PersistentPreRun but not the root command's
PersistentPostRun:
package main import ( "fmt" "github.com/spf13/cobra" ) func main() { var rootCmd = &cobra.Command{ Use: "root [sub]", Short: "My root command", PersistentPreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) }, PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) }, } var subCmd = &cobra.Command{ Use: "sub [no options!]", Short: "My subcommand", PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) }, } rootCmd.AddCommand(subCmd) rootCmd.SetArgs([]string{""}) rootCmd.Execute() fmt.Println() rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) rootCmd.Execute() }
Output:
Inside rootCmd PersistentPreRun with args: [] Inside rootCmd PreRun with args: [] Inside rootCmd Run with args: [] Inside rootCmd PostRun with args: [] Inside rootCmd PersistentPostRun with args: [] Inside rootCmd PersistentPreRun with args: [arg1 arg2] Inside subCmd PreRun with args: [arg1 arg2] Inside subCmd Run with args: [arg1 arg2] Inside subCmd PostRun with args: [arg1 arg2] Inside subCmd PersistentPostRun with args: [arg1 arg2]
Suggestions when "unknown command" happens
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the
git command when a typo happens. For example:
$ hugo srever Error: unknown command "srever" for "hugo" Did you mean this? server Run 'hugo --help' for usage.
Suggestions are automatic based on every subcommand registered and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
If you need to disable suggestions or tweak the string distance in your command, use:
command.DisableSuggestions = true
or
command.SuggestionsMinimumDistance = 1
You can also explicitly set names for which a given command will be suggested using the
SuggestFor attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
$ kubectl remove Error: unknown command "remove" for "kubectl" Did you mean this? delete Run 'kubectl help' for usage.
Generating documentation for your command
Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
Generating bash completions
Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
Generating zsh completions
Cobra can generate zsh-completion file. Read more about it in [Zsh Completions](zsh_completions.md).
Contributing
- Fork it
- Download your fork to your PC (
git clone && cd cobra)
- Create your feature branch (
git checkout -b my-new-feature)
- Make changes and add them (
git add .)
- Commit your changes (
git commit -m 'Add some feature')
- Push to the branch (
git push origin my-new-feature)
- Create new pull request
License
Cobra is released under the Apache 2.0 license. See LICENSE.txt
*Note that all licence references and agreements mentioned in the cobra README section above are relevant to that project's source code only. | https://go.libhunt.com/cobra-alternatives | CC-MAIN-2020-24 | refinedweb | 3,530 | 51.14 |
The question is answered, right answer was accepted
So i created this test scene to show you my problem
i wanted to detect how far my cube( for this example ) can move in a certain direction. I use Physics.Boxcast instead of raycast because raycast is way to thin.
I used Physics.Spherecast in past and it worked perfectly fine but i wanted to use Boxcast because my Object isn't a sphere
so my problem is that i get completly wrong hit.distance values and also my gizmos always show a distance betweet ground and itself for reasons i dont understand.
I want my Boxcast to go all the way down to the ground or the wall and give me the right hit.distance value
If you can fix my problem you can send me a email with your paypal data after and i give you a small donation, because you really don't find much about this on the web.
and a screenshot of my scene
using System.Collections; using System.Collections.Generic; using UnityEngine; public class testscript : MonoBehaviour { public float maxDistance; public LayerMask layerMask; private Vector3 origin; private Vector3 direction; private float currentHitdistance; void Update () { origin = transform.position; direction = Vector3.down; RaycastHit hit; if (Physics.BoxCast(origin,new Vector3(1,1,1),direction,out hit, Quaternion.LookRotation(direction),maxDistance,layerMask,QueryTriggerInteraction.UseGlobal)) { currentHitdistance = hit.distance; Debug.Log(hit.distance); } } private void OnDrawGizmos() { Gizmos.color = Color.red; Gizmos.DrawWireCube(origin + direction * currentHitdistance, new Vector3(1,1,1)); } }
I don't care about the donation or whatever, but I am curious, what do you mean it is giving improper distance? You are aware that it gives the distance traveled, correct? Which means your box having halfextents of 1, makes the box size 2, and as such, the box will never calculate the distance to the center of the box, but the first edge of the box that touches the terrain. So automatically this will be a minimum of 1 meter away.
thank you i didnt knew this
also did it just delete my first reply, i am knew at this forum
fuck i didnt knew this thank you i feel like the biggest idiot right now guess i just have to add half the rest amount then, thank you
Answer by taylank
·
Mar 26, 2018 at 05:12 PM
When you use Vector3(1,1,1) with BoxCast, that's the half extents of your box, so your real box size is assumed to be 2,2,2. Whereas with DrawWireCube the argument you pass is size, which is the whole length of an edge. So you are visualizing two mismatched lengths.
thank you i didnt knew this,
do you want you reward?
Don't worry about it. :)
oke then i will close this.
Slant Physics Raycast Implementation
0
Answers
iam using raycast.hit function.am trying to move vehicle over the terrain ups and down??
0
Answers
Closest point that has been between two objects
2
Answers
Restrict two objects from getting too close.
1
Answer
Is there a limit on the distance of raycast?
2
Answers | https://answers.unity.com/questions/1485566/problems-with-physicsboxcast-reward-for-fixing-10.html | CC-MAIN-2019-51 | refinedweb | 519 | 64 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 0.6, 0.7
- Fix Version/s: None
- Component/s: C++ - Compiler
-
- Patch Info:Patch Available
Description
steps:
./bootstrap.sh
./configure
make
sudo make install
cd contrib/fb303
./bootstrap.sh
./configure
make
Fails with error:
gen-cpp/fb303_types.cpp:11: error: 'fb_status' is not a class or namespace
gen-cpp/fb303_types.cpp:12: error: 'fb_status' is not a class or namespace
gen-cpp/fb303_types.cpp:13: error: 'fb_status' is not a class or namespace
gen-cpp/fb303_types.cpp:14: error: 'fb_status' is not a class or namespace
gen-cpp/fb303_types.cpp:15: error: 'fb_status' is not a class or namespace
gen-cpp/fb303_types.cpp:16: error: 'fb_status' is not a class or namespace
make[3]: *** [fb303_types.o] Error 1
make[3]: Leaving directory `/home/sudhir/workspace/scribe/thrift-apache/contrib/fb303/cpp'
make[2]: *** [all] Error 2
make[2]: Leaving directory `/home/sudhir/workspace/scribe/thrift-apache/contrib/fb303/cpp'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/sudhir/workspace/scribe/thrift-apache/contrib/fb303'
make: *** [all] Error 2
Activity
hi! how does this solve the issue above? i also encountered it while compiling fb303. does it need to be placed in some directory and run it? please help. thanks.
I could not reproduce your error on trunk:
URL:
Revision: 1076790
What version are you using?
This defect hit me today on Ubuntu 10.04. I first tried building the latest release, 0.6.0. Then built from trunk (r1086298). Got the err described above both times. I patched compiler/cpp/src/generate/t_cpp_generator.cc as shown in the patch. After rebuilding thrift I found that I could now successfully build fb303. I can't really say if the patch is right, but applying it did allow my build of fb303 to succeed, both in the 0.6.0 release and HEAD of trunk (as of this morning).
Upgraded to Ubuntu 10.10, reverted the patch to Trunk HEAD, rebuilt. Build failed again as described in this bug.
Built thrift 0.5.0 and fb303. Problem does NOT occur in that version.
Patch seems to work.
committed! Thanks all for verification.
THRIFT-1060. Fixes fb303 compile issue and other pure enum related compile errors. | https://issues.apache.org/jira/browse/THRIFT-1060?attachmentSortBy=fileName | CC-MAIN-2015-11 | refinedweb | 379 | 53.78 |
How to: Use a Report Model as a Data Source
You can create reports in Report Designer that use a published report model as the data source type. This capability allows you to create predefined custom reports for clickthrough data exploration. For more information about how predefined reports are used in clickthrough data exploration, see Managing Report Models.
Before you can choose Report Server Model as a data source type, you must have a published model to work with.
You can specify a report model data source type for reports that you add to a report server project, or for reports that you create using the Report Wizard. The instructions in this topic assume you are adding a report to the current project. For more information about using the wizard, see Tutorial: Creating Model-Based Reports in Report Designer.
To create a report model data source type
In Report Designer, add a report to the current report server project.
In the Report Data pane, on the toolbar, click New, then click Data Source.
In the Data Source Properties dialog box, type a name in the Name text box or accept the default name.
Verify that Embedded connection is selected.
From the Type list, select Report Server Model.
In the Connection string text box, type a connection string that specifies a URL to a report server and a path to the model. The connection string you use depends on whether the report model is on a report server configured in native mode or in SharePoint integrated mode. Example connection strings for each mode are shown in the following list:
Native mode server=; datasource=/Models/AdventureWorks Model
SharePoint integrated mode server=; datasource= Works.smdl
If you want to use localhost for the Web server, verify that TCP/IP is enabled. Otherwise, a connection error might occur. For more information, see Troubleshooting Server and Database Connection Problems.
The model name is specified through the data source connection string argument. The argument must resolve to a fully qualified model name in the report server folder namespace. In the example, the folder is named /Data Sources, and it is a child folder of the root node in the report server folder namespace. The path must start with a forward slash. If you are not sure about the path, use SQL Server Management Studio or Report Manager to navigate the folder hierarchy.
On the Credentials tab, specify credentials to access the data source.
Choose Windows Authentication (integrated security) or stored credentials. If you choose prompted credentials, you will need to type credentials every time the report server establishes a connection to the data source. Do not choose No credentials unless you have configured the unattended execution account. For more information, see Specifying Credential and Connection Information for Report Data Sources.
Click OK.
This data source appears in the Report Data pane. To open the Report Model Query Designer so that you can create a dataset, right-click the data source, and then click Add Dataset, and then Query Designer. If the Report Model Query Designer does not appear, connection to the report model failed. Check the connection string and credentials to resolve the error and open the query designer. | https://msdn.microsoft.com/en-us/library/ms345238.aspx | CC-MAIN-2015-32 | refinedweb | 533 | 54.73 |
On Mon, Aug 5, 2013 at 2:14 PM, Steven D'Aprano <report@bugs.python.org>wrote:
> > As you say, there's no state to be stored. So why not simply have
> separate functions `median`, `median_low`, `median_high`, `median_grouped`,
> etc.?
>
> Why have a pseudo-namespace median_* when we could have a real namespace
> median.* ?
I am with Steven on this one. Note that these functions are expected to be
used interactively and with standard US keyboards "." is much easier to
type than "_".
My only objection is to having a class xyz such that isinstance(xyz(..),
xyz) is false. While this works with CPython, it may present problems for
other implementations. | https://bugs.python.org/msg194502 | CC-MAIN-2021-43 | refinedweb | 110 | 69.68 |
A ASGI Server based on Hyper libraries and inspired by Gunicorn.
Project description
Hypercorn is an ASGI web server based on the sans-io hyper, h11, h2, and wsproto libraries and inspired by Gunicorn. Hypercorn supports HTTP/1, HTTP/2, WebSockets (over HTTP/1 and HTTP/2), ASGI/2, and ASGI/3 specifications. Hypercorn can utilise asyncio, uvloop, or trio worker types.
Hypercorn can optionally serve the current draft of the HTTP/3 specification using the aioquic library. To enable this install the h3 optional extra, pip install hypercorn[h3] and then choose a quic binding e.g. hypercorn --quic-bind localhost:4433 ....
Hypercorn was initially part of Quart before being separated out into a standalone ASGI server. Hypercorn forked from version 0.5.0 of Quart.
Quickstart
Hypercorn can be installed via pip,
$ pip install hypercorn
and requires Python 3.7.0 or higher.
With hypercorn installed ASGI frameworks (or apps) can be served via Hypercorn via the command line,
$ hypercorn module:app
Alternatively Hypercorn can be used programatically,
import asyncio from hypercorn.config import Config from hypercorn.asyncio import serve from module import app asyncio.run(serve(app, Config()))
learn more (including a Trio example of the above) in the API usage docs.
Contributing
Hypercorn is developed on GitLab. If you come across an issue, or have a feature request please open an issue. If you want to contribute a fix or the feature-implementation please do (typo fixes welcome), by proposing a merge request.
The Hypercorn documentation is the best place to start, after that try searching stack overflow, if you still can’t find an answer please open an issue.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/Hypercorn/ | CC-MAIN-2020-40 | refinedweb | 303 | 58.69 |
I got this code from MSDN for a FAQ for Visual C++ 4.2
I saw this code, ran my eyes over it and I am wondering if the code is legal, according to the standard.
you know, even in the recent VC++ tutorial, they still used void main()...you know, even in the recent VC++ tutorial, they still used void main()...Code://piglatin.cpp #include <string> #include <iostream> //convert a string to piglatin string piglatin(const string& s) { string s1 ; string s2(" .,;:?") ; //word separators //word boundary markers size_t start, end, next, p0 ; int done = 0 ; start = end = next = 0 ; while (!done) { // Find start of word. start = s.find_first_not_of(s2, next) ; // Find end of word. // Check for end of string. p0 = s.find_first_of(s2, start) ; end = (p0 >= s.length()) ? s.length() : p0 - 1 ; // Copy all the word separators. s1 = s1 + s.substr(next, start - next) ; // Convert word to piglatin. s1 = s1 + s.substr(start + 1, end - start) + s[start] + "ay" ; next = end + 1; // Check for end of string. if( next >= s.length()) done = 1 ; } return s1 ; } void main() { string s("she sells sea shells by the sea shore") ; cout << "s = " << s << endl ; cout << "\npiglatin(s) = " << piglatin(s) << "\n"<< endl; }
no wonder windows has so many problems.
note: haven't tried compiling yet but I know it will compile...
Shouldn't it say
under the includes...under the includes...Code:using namespace std;
also, i really think void should be changed to int (on main) and a return 0; added to the bottom. OR AT LEAST
__asm mov eax, 0x0
right?
-LC | https://cboard.cprogramming.com/cplusplus-programming/42950-should-work.html | CC-MAIN-2017-09 | refinedweb | 261 | 85.99 |
Today with the Visual Studio 2015 Preview, one of the big things we’ve done is improved the C++ experience, adding support for targeting Android, boosting runtime and build-time performance, improving standards compliance, and improving the editor experience. The Preview is available here for download and as a VM that you can run in Azure (if you’re an MSDN subscriber, you get 150 hours of Azure for free).
Let’s go deeper on what’s in the release!
- C++ Cross-Platform Mobile Development. C++ is attractive because it offers portability and a chance to reuse the same code on different platforms. With Visual Studio 2015 Preview, modern application developers can use the Visual C++ tool chain (c1xx, c2) to target Microsoft Windows Platforms and Clang / LLVM for targeting Android (with plans to support iOS in the near future). This makes it even easier to re-use existing C++ libraries to target multiple platforms (Android/Windows/iOS), share cross-platform code, and create high-quality Xamarin Native Android and Native-Activity applications using all of the power of Visual Studio. For a closer look, see Cross-Platform Mobile Development with Visual C++.
- C++11, C++14, C++17 (proposed) compatibility. Standards support across compilers improves portability. With Visual Studio 2015 Preview, Visual C++ is even more compliant with user-defined literals (C++11), generic lambdas (C++14), and await (C++17 proposed). For a view of VS conformance in table form, see this post by Stephan Lavavej (STL). Also check out Details About Some of the New C++ Language Features, Improvements to Warnings in the C++ Compiler, and Resumable Functions in C++.
- Enhanced productivity & build-time improvements. “Productivity” and “C++” are not often used in the same sentence except to criticize some aspect of the IDE, build process or diagnostics. Friction in any of these areas slows down the development process. With Visual Studio 2015 Preview, you get improvements in each including refactoring for C++ and improved IntelliSense database buildup and simplified QuickInfo for template deduction (IDE); incremental linking for static libs, new fast PDB generation techniques, multithreading in the linker (build); and dedicated space for analyzing graphics space using the Visual Studio Graphics Analyzer (VSGA) and you can view the impact of shader code changes without re-running the app (diagnostics). For more details about incremental build, see Speeding up the Incremental Build Scenario. For more details about C++ Refactoring support, see All about C++ Refactoring in Visual Studio 2015 Preview.
- Improved performance. Most of the C++ developers we spoke with needed code to run fast, often as part of intensive data transformation or analysis or real-time control. Visual Studio 2015 Preview builds on the AVX2 support in Visual Studio 2013 to bring more general optimizations like loop-if unswitching, Vectorization of control flow, and increased support for Vectorization (including when optimizing in favor of smaller code). In addition we have a number of ARM32 compiler code generation improvements.
In Visual Studio 2015 Preview, you will be able to target Windows 8.1 Phone and Store along with Windows 8.0 Phone development. See C++ Tools Acquisition for Windows Phone and Store Development for more details.
The team is eager to get your feedback. Members of the team will be available for a live discussion through the following sessions:
- Multi-Device Development using Visual Studio (iOS, Android & Windows) (Thu, 13:40 EST)
- C++ in Visual Studio “14” (Thu, 17:00 EST)
You can also watch over 55 on-demand sessions from Microsoft engineers including Herb Sutter’s Visual C++ Conformance and Cross-Platform Development in Visual Studio 2015 video.
Take some time now to download the Visual Studio 2015 Preview and, after kicking the tires a bit, giving us some feedback. Share feature suggestions on UserVoice, log bugs you find on our Connect site and send us a smile or frown from inside the IDE. In addition, keep an eye here for posts on our cross-platform support for Android, language conformance, diagnostics, and more over the next few days.
Thanks!
Join the conversationAdd Comment
Any plans to make it easier to consume (build and link) third-party C++ libs? It's so annoying…
@Olaf, what would make the process easier for you? What if the third-party C++ library was already compiled for VS2015 Preview?
@Eric:
1. Download and extract libX.7z
2. Run a few commands in command prompt
3. Have all required output files ready for consumption by my projects
Pre-compiling libs doesn't scale and wouldn't add that much.
Hi, great news about cross platform and standard conformance! Recently started building a LOB app, nice to see that I'll be able to port it to other platforms.
However, still wondering about support for Windows desktop, specifically: is there any news on the MFC front? Will we get a truly modern C++ UI framework, or at least get MFC updated (say, a CXamlView would be epic!)?
Thanks in advance!
@Fernando
Glad you like our direction with the cross-platform mobile development.
As for the Windows Desktop UI & MFC, nothing major yet on that horizon. We are investigating some of the MFC major dissatisfactions specially the ones mentioned at visualstudio.uservoice.com/…/2782934-improve-mfc
Thanks,
Hi, will there be any AVX-512 support in VS 2015 preview ?
@Olaf, @Fernando, we would like to learn more about your scenarios. Want to chat? Email me ebattali@microsoft.com.
@Richard
No support for AVX-512 in the preview. (Just 256-bit AVX, under the /arch:AVX2 switch)
I already checked the VS012 (…/0163 ) and VS2013 (…/0288 ). Later I will check VS2015. But every time it is "defective check". Perhaps we became friends and you send me makefile/solution for build VS libraries? My check vs2015 can get more productive :).
Looks like an exciting update!
Is this able to use the VS2010 SP1 and VS2013 compiler backends?
Also, any hints regarding RTM dates? (or does that come later during Connect())?
Thank you @Ayman Shoukry yes I voted for that item. That particular "Microsoft does still own MFC :)" message brought a new hope! 🙂
@Erik than you, already sent an email to get in touch. Best regards!!!
Just tried 2015, the optimizer is still crap.
Is there any intention on improving it or is the Clang/LLVM path suggested by Herb the long term solution?
@Arash, we would like to learn more about your scenario. Can you email me ebattali@microsoft.com? Thanks!
@Eric: Been doing so for that for past 4+ years…
connect.microsoft.com/…/806491
connect.microsoft.com/…/813174
Note: Moved away from using the msvc compiler for production release – currently using a mix of intel/gcc.
Amazed to see on-going improvement and standardization of native C++. Hope VC++ meets all standards optimally. Surprised to see Android support, but what about Windows UI using native C++? What about improving MFC, or supplying a world class native C++ UI library?
I think it's time to think about ARM-64..
Would you consider making the git SCM plugin open-source just so people can contribute via pull requests? That's one plugin that could really use some community momentum. There'd still be regular, blessed downloads, but people could add the things they need.
@Ajay, re:C++ for desktop UI, we have no definite plans but we have heard plenty from the C++ developer community about the importance of desktop applications and UI. If you want to share more details about your apps, ping me ebattali@microsoft.com
Can we only download VS2015 Preview once? I tried to download it on two different machines, but in the second machine, the download link only redirects me to a profile page.
Please give us update on status of C99 support? Can we claim MSVCR now supports full C99 language specs and features? How about <tgmath.h> and the rest of those missing from VS-2013?
@Marcel, you should be able to download it as many times as desired. Can you try again?
@(CC), check out Herb Sutter's video, channel9.msdn.com/…/311
@Eric, I think Marcel means a single download that can be sneaker-netted to multiple computers. I pay for my used bandwidth, so I'd prefer an option like that too (an ISO or something). I'd be happy to register each computer, but I only want the bulk transfer once.
Thanks, it works now! The link that didn't work was from the Visual Studio blog and led to visualstudio.com (still doesn't work). The link in this post to the download center works.
I actually only wanted to download either the ISO or the web installer twice. I successfully downloaded the ISO on one machine and couldn't on a second machine because I was redirected to a profile page. Then I tried downloading the web installer, but the download got stuck at 45%. When I retried the download, I was redirected to that profile page again. I just tried again and now nothing at all happens when I click on "Your Selection: Ultimate 2015 Preview".
I found a potential issue with the standard C++ libraries (libcpmt, libcpmtd, msvcprt, msvcprtd) that break any code that tries to use codecvt<char16_t> or codecvt<char32_t>. I can't submit the bug report to the Connect site because it doesn't appear to be working right now ("You are not authorized to submit the feedback for this connection."), so I'm reporting it here.
Repro steps:
1. Save this code in main.cpp:
#include <codecvt>
void main() { std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> test; }
2. Try compiling it:
> cl /EHsc main.cpp
main.obj : error LNK2019: unresolved external symbol "public: static class std::locale::id std::codecvt<char16_t,char,struct _Mbstatet>::id" (?id@?$codecvt@_SDU_Mbstatet@@@std@@2V0locale@2@A) referenced in function "public: __thiscall std::locale::locale<class std::codecvt_utf8<char16_t,1114111,0> >(class std::locale const &,class std::codecvt_utf8<char16_t,1114111,0> const *)" (??$?0V?$codecvt_utf8@_S$0BAPPPP@$0A@@std@@@locale@std@@QAE@ABV01@PBV?$codecvt_utf8@_S$0BAPPPP@$0A@@1@@Z)
main.exe : fatal error LNK1120: 1 unresolved externals
It appears the C++ libs haven't been compiled with native char16_t/char32_t support. If you look at msvcprtd.lib for example, it only exports these three definitions of codecvt::id
7FA9A __imp_?id@?$codecvt@_WDU_Mbstatet@@@std@@2V0locale@2@A
7FB2A __imp_?id@?$codecvt@GDU_Mbstatet@@@std@@2V0locale@2@A
7FBB8 __imp_?id@?$codecvt@DDU_Mbstatet@@@std@@2V0locale@2@A
Those definitions are for codecvt<wchar_t>::id, codecvt<unsigned short>::id and codecvt<char>::id respectively. However, the codecvt<char16_t>::id and codecvt<char32_t>::id definitions aren't there, and indeed, if you look at locale0.cpp in the CRT source code you'll see they're not defined at all.
Any workarounds?
Javier Blazquez: That's a known issue, tracked by an active bug (DevDiv#1060849). We were able to update the STL's headers in response to char16_t/char32_t, but we still need to update the separately compiled sources.
Found the ISO. Can I install this on a production system next to VS2010? Or will the eventual uninstall cause problems?
How about this bug? – connect.microsoft.com/…/visual-c-14-ctp3-c-11-inheriting-constructor-bug
I think it's impressive and just right to support Android development in Visual Studio. Kudos to you! Even if I haven't had time to look at that yet.
However, here focusing on a single very strong improvement potential for use by students: that everything about the Win32 console project template is still wrong. That is, there's not a single right thing about it.
• Defaults to non-standard C++ by having precompiled headers as default. Every September students run into that, like, hey y my standard-compliant code, directly out of the (some) textbook, not work?!?
• In the generated code, the only comment, at the top, is just misleading verbiage: "Defines the entry point for the console application.". The documentation of a program's entry point has been incorrect since 1992 or thereabouts. A good start towards cleaning up that mess could be to change the wording here and elsewhere: "main" is by no means the machine code level entry point (and neither is "WinMain", as the documentation for a long time erroneously claimed, but as I recall that's replaced by other just as bad errors). It can reasonably be called a "startup" function, or just "main function". I mention this because evidently even Microsoft's own tech writers have been misled by Microsoft's adopted terminology here, conflating the machine code level entry point (which can be specified by linker option "/entry") with the C and C++ main function.
• The archaic macro "_tmain" instead of standard "main" is really ungood, especially since it's impossible to target the platform that that monstrosity once was in support of, namely Windows 9x. The idea of the T macros was obsolete already in the year 2000, with the introduction of Layer for Unicode. Today, no Windows 9x.
• Ditto for "_TCHAR".
• The "return 0;" statement isn't necessary for a standard "main": it's the default. If the idea of providing an explicit such statement is the save the user from typing, then in this template include the <stdlib.h> header and use "return EXIT_SUCCESS;"; that would save the user from doing that, and point newbies in the right direction. But "return 0;" isn't meaningful as part of the template.
What does the word "Visual" in Visual C++ mean?
Please, Please, Please consider fixing the UI.
Thanks.
Any chance that the counter part for POSIX getopt.h and getopt.cpp (and its variant getoptlong) get their way to standard C++? It is really inconvenient to use the guard for those files on Windows.
If isocpp is not interested, would it be possible for VC team to provide those guards OOTB?
When will VC++ support OpenMP 3 / 4?
Visual Studio 2015 still OpenMP 2.0 only…
Windows Phone is not free ?
Very bad for Windows Ecosystem.
@Olumide, we would love to learn more about UI issues you are having, can you email me at ebattali@microsoft.com? Thanks!
@Gary: C/C++ became "Visual" when we shipped the compiler as part of an integrated development environment and with the Microsoft Foundation Class libraries. Development became a little more visual (GUI assisted) versus the strict text file and command line experience.
We still have MFC available and we are still in an IDE though you can (still) compile using the command-line compilers.
(Thanks to Jonathan Caves for the backstory; he has been on the team for a while.)
@Heresy, we have no definite plans. If you want to discuss your scenario, email me ebattali@microsoft.com.
@Eric, can this be installed side-by-side on a computer that has older versions of VS ?
@Mark, you can install Visual Studio 2015 Preview along side VS2013 and VS2012, see…/visual-studio-2015-compatibility-vs.
> Any chance that the counter part for POSIX getopt.h and getopt.cpp (and its variant getoptlong) get their way to standard C++?
As far as I know, nobody has proposed that to the C++ Standardization Committee.
> would it be possible for VC team to provide those guards OOTB?
Highly unlikely. Use Boost.Program_Options for a portable solution.
@Eric, footnote 3 of the link you provided: "requires side-by-side installation of VS2010" answers my question. I don't need 2015 to target 2010, just not mess up my current install. Thanks for the pointer, I'll try it out this weekend.
@Mark, glad the link helped even if I mis-read your question!
Great news. I think Microsoft is moving in the right direction.
I'd like to see the improvements done by the team, because I build for mobile and tablets more than ever.
It feels so good to use Visual Studio again as my primary development tool. I'm a VS user since its very beginnings. Good work!
The quality of the IDE has massively decreased as we've moved from 2010 to 2012 to 2013, with 2013 being really bad. Can we look forward to yet more degradation in IDE performance and behavior? And please tell us that the start up times will take even longer! I will be devastated if Visual Studio actually approaches the quality and speed seen in Visual Studio 2008. If it exceeds it, I'd probably wet myself.
(Sarcasm on steroids–maybe if you spent more time on making the IDE not suck instead of tossing in C++17 features, you might make your users a little less pissed off and boy, are they pissed off.)
I am running VS 2013 on two machines. The launch is quite fast. I have no clue how are you coming up with those points. Are you making them up just because you are YAT: yet-another-troll? Or is it what you do for living?
Startup time dramatically improved for me between VS11 and VS12. Also the colored icons are back and SuppressUppercaseConversion became an official option in Update 3. Even though I prefer how the VS9 look respects my system settings, I find the VS12.3+ IDE no worse than the VS10 IDE.
@WesJorn, Visual Studio is one of the best IDEs on the market, and I think the vast majority of developers realize this. Also, startup times for VS 2013 are much better than previous releases. But maybe you're just trolling, which is fine (hey, it's a free country).
@Eric, We (unfortunately) still need to support Windows XP – what is the the story on this with regards to VS 2015?
Will the CRT source be reintroduced with VC2015?
@Mark R.
You will still be able to target XP as a runtime platform.
Thanks,
I stand by my comment that VS 2013 is slow. I'm one of the few developers I know using it, the rest opting to stick with 2012 or 2010. I don't have an SSD and when VS 2013 starts, the disk thrash is tremendous. Opening a project is also slower, accompanied with screen flashes. Navigating menus causes disk thrash and noticeable delays in menus popping up.
Yeah, Visual Studio is still the best IDE on the market, but that isn't testament to Visual Studio, but an indictment of how crappy all the rest are.
Dear Eric & team,
Two feature requests:
– allow Clang to build for Mac OS X. Officially or unofficially.. if you can build for iOS, Mac OS X should be a small step. Remote debugging over IP would be a nice-to-have (gdb over ssh) but not essential. Would be a massive time saver if I never have to open Xcode ever again (aside from the occasional debugging session and building nibs).
– support #pragma unroll for forced unrolling of tight loops. At the moment I have to rely on some really gross macro-hackery to get this to happen on MSVC++. 95% of the time the compiler knows best, but the other 5% isn't going to magically disappear.
When is the Visual C Compiler going to support ANSI C99?
Good post. I learn something totally new and challenging on blogs I stumbleupon every day.
It’s always useful to read articles from other writers and practice
a little something from other web sites. | https://blogs.msdn.microsoft.com/vcblog/2014/11/12/visual-studio-2015-preview-is-now-available/ | CC-MAIN-2016-40 | refinedweb | 3,225 | 65.83 |
I am using Selenium 2 and Robot Framework to automate our application. I have used the below JavaScript code to scroll down the page but am not able to scroll.
I want to enter text inside the text box after scrolling down, but I am receiving the exception:
Element not visible
The text box is partially visible on the screen by default, if we manually scroll down than its completely visible, But selenium robot framework unable to scroll down.
I have tried:
Execute JavaScript window.scrollTo(0,200) Execute JavaScript window.scrollBy(0,200) Execute JavaScript window.scrollTo(0, document.body.scrollHeight)
How can I fix this?
Your scrolling code looks ok. However, I don't think scrolling is your problem. Element visibility is ok even if it is scrolled away from screen. Try this code for example. At least on Chrome page scrolls back up at Input Text keyword
*** Settings *** Library Selenium2Library *** Test Cases *** Scroll Open Browser Chrome Execute JavaScript window.scrollTo(0, document.body.scrollHeight) Input Text //*[@id="search"]/input robot framework Sleep 3 Close All Browsers
I think you may have an incorrect locator for your edit box.
I fixed the issue with
Execute JavaScript ${element}.scrollby(0,200). It will not work in every case. If the element is not in a viewport it will not scroll.
There's an efficient way to scroll the page to get the element to a view port.
If we are using
Execute JavaScript Window.scroll(x,y), we need to specify a horizontal and vertical position, x,y, which is difficult to find and may not be accurate.
Instead we can use the following line of code,
Execute JavaScript window.document.evaluate("//xpathlocation", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView(true);
The above code will scroll the window and get the element specified in /xpathlocation to the view port.
You can use this as a keyword:
Execute Javascript $(document).scrollTop(${x})
Where,
x is the number in milliseconds to scroll down.
Have you tried in Selenium webdriver in the IPython console directly?
I have tried as in the following, and it is able to scroll down.
from selenium import webdriver firefox = webdriver.Firefox() firefox.get('') firefox.execute_script('window.scrollTo(0,200)')
If there is another element inside your page with scroll bar which you want to scroll into, you can use this Execute javascript command:
Execute Javascript document.querySelector('<div.css>').scrollTop = 200;
You can just change the '200' and increase it as you want to scroll down more. | https://javascriptinfo.com/view/157526/unable-to-scroll-down-the-web-page-using-the-robot-framework | CC-MAIN-2021-17 | refinedweb | 420 | 58.38 |
A custom operation to use in a reduce command. More...
#include <vtkCommunicator.h>
A custom operation to use in a reduce command.
Subclass this object to provide your own operations.
Definition at line 107 of file vtkCommunicator.h.
Definition at line 129 of file vtkCommunicator.h.
Subclasses must overload this method, which performs the actual operations.
The methods should first do a reinterpret cast of the arrays to the type suggested by
datatype (which will be one of the VTK type identifiers like VTK_INT, etc.). Both arrays are considered top be length entries. The method should perform the operation A*B (where * is a placeholder for whatever operation is actually performed) and store the result in B. The operation is assumed to be associative. Commutativity is specified by the Commutative method.
Subclasses override this method to specify whether their operation is commutative.
It should return 1 if commutative or 0 if not. | https://vtk.org/doc/nightly/html/classvtkCommunicator_1_1Operation.html | CC-MAIN-2019-30 | refinedweb | 152 | 51.44 |
Learning Curves for Machine Learning
But how do we diagnose bias and variance in the first place? And what actions should we take once we've detected something? In this post, we'll learn how to answer both these questions using learning curves.
The learning_curve() function from scikit-learn
We'll use the
learning_curve() function from the scikit-learn library to generate a learning curve for a regression model. There's no need on our part to put aside a validation set because
learning_curve() will take care of that.
In the code cell below, we:
- Do the required imports from
sklearn.
- Declare the features and the target.
- Use
learning_curve()to generate the data needed to plot a learning curve. The function returns a tuple containing three elements: the training set sizes, and the error scores on both the validation sets and the training sets. Inside the function, we use the following parameters:
estimator— indicates the learning algorithm we use to estimate the true model;
X— the data containing the features;
y— the data containing the target;
train_sizes— specifies the training set sizes to be used;
cv— determines the cross-validation splitting strategy (we'll discuss this immediately);
scoring— indicates the error metric to use; the intention is to use the mean squared error (MSE) metric, but that's not a possible parameter for
scoring; we'll use the nearest proxy, negative MSE, and we'll just have to flip signs later on.
from sklearn.linear_model import LinearRegression from sklearn.model_selection import learning_curve features = ['AT', 'V', 'AP', 'RH'] target = 'PE' train_sizes, train_scores, validation_scores = learning_curve( estimator = LinearRegression(), X = electricity[features], y = electricity[target], train_sizes = train_sizes, cv = 5, scoring = 'neg_mean_squared_error')
We already know what's in
train_sizes. Let's inspect the other two variables to see what
learning_curve() returned:
print('Training scores:\n\n', train_scores) print('\n', '-' * 70) # separator to make the output easy to read print('\nValidation scores:\n\n', validation_scores)
Training scores: [[ -0. -0. -0. -0. -0. ] [-19.71230701 -18.31492642 -18.31492642 -18.31492642 -18.31492642] [-18.14420459 -19.63885072 -19.63885072 -19.63885072 -19.63885072] [-21.53603444 -20.18568787 -19.98317419 -19.98317419 -19.98317419] [-20.47708899 -19.93364211 -20.56091569 -20.4150839 -20.4150839 ] [-20.98565335 -20.63006094 -21.04384703 -20.63526811 -20.52955609]] ---------------------------------------------------------------------- Validation scores: [[-619.30514723 -379.81090366 -374.4107861 -370.03037109 -373.30597982] [ -21.80224219 -23.01103419 -20.81350389 -22.88459236 -23.44955492] [ -19.96005238 -21.2771561 -19.75136596 -21.4325615 -21.89067652] [ -19.92863783 -21.35440062 -19.62974239 -21.38631648 -21.811031 ] [ -19.88806264 -21.3183303 -19.68228562 -21.35019525 -21.75949097] [ -19.9046791 -21.33448781 -19.67831137 -21.31935146 -21.73778949]]
Since we specified six training set sizes, you might have expected six values for each kind of score. Instead, we got six rows for each, and every row has five error scores.
This happens because
learning_curve() runs a
k-fold cross-validation under the hood, where the value of
k is given by what we specify for the
cv parameter.
In our case,
cv = 5, so there will be five splits. For each split, an estimator is trained for every training set size specified. Each column in the two arrays above designates a split, and each row corresponds to a test size.).
train_scores_mean = -train_scores.mean(axis = 1) validation_scores_mean = -validation_scores.mean(axis = 1) print('Mean training scores\n\n', pd.Series(train_scores_mean, index = train_sizes)) print('\n', '-' * 20) # separator print('\nMean validation scores\n\n',pd.Series(validation_scores_mean, index = train_sizes))
Mean training scores 1 -0.000000 100 18.594403 500 19.339921 2000 20.334249 5000 20.360363 7654 20.764877 dtype: float64 -------------------- Mean validation scores 1 423.372638 100 22.392186 500 20.862362 2000 20.822026 5000 20.799673 7654 20.794924 dtype: float64
Now we have all the data we need to plot the learning curves.
Before doing the plotting, however, we need to stop and make an important observation. You might have noticed that some error scores on the training sets are the same. For the row corresponding to training set size of 1, this is expected, but what about other rows? With the exception of the last row, we have a lot of identical values. For instance, take the second row where we have identical values from the second split onward. Why is that so?
This is caused by not randomizing the training data for each split. Let's walk through a single example with the aid of the diagram below. When the training size is 500 the first 500 instances in the training set are selected. For the first split, these 500 instances will be taken from the second chunk. From the second split onward, these 500 instances will be taken from the first chunk. Because we don't randomize the training set, the 500 instances used for training are the same for the second split onward. This explains the identical values from the second split onward for the 500 training instances case.
An identical reasoning applies to the 100 instances case, and a similar reasoning applies to the other cases.
To stop this behavior, we need to set the
shuffle parameter to
True in the
learning_curve() function. This will randomize the indices for the training data for each split. We haven't randomized above for two reasons:
- The data comes pre-shuffled five times (as mentioned in the documentation) so there's no need to randomize anymore.
- I wanted to make you aware about this quirk in case you stumble upon it in practice.
Finally, let's do the plotting.
Learning curves - high bias and low variance
We plot the learning curves using a regular matplotlib workflow:
import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn') plt.plot(train_sizes, train_scores_mean, label = 'Training error') plt.plot(train_sizes, validation_scores_mean, label = 'Validation error') plt.ylabel('MSE', fontsize = 14) plt.xlabel('Training set size', fontsize = 14) plt.title('Learning curves for a linear regression model', fontsize = 18, y = 1.03) plt.legend() plt.ylim(0,40)
(0, 40)
There's a lot of information we can extract from this plot. Let's proceed granularly.
When the training set size is 1, we can see that the MSE for the training set is 0. This is normal behavior, since the model has no problem fitting perfectly a single data point. So when tested upon the same data point, the prediction is perfect.
But when tested on the validation set (which has 1914 instances), the MSE rockets up to roughly 423.4. This relatively high value is the reason we restrict the y-axis range between 0 and 40. This enables us to read most MSE values with precision.. However, the model performs much better now on the validation set because it's estimated with more data.
From 500 training data points onward, the validation MSE stays roughly the same.. Adding more features, however, is a different thing and is very likely to help because it will increase the complexity of our current model.
Let's now move to diagnosing bias and variance. The main indicator of a bias problem is a high validation error. In our case, the validation MSE stagnates at a value of approximately 20. But how good is that? We'd benefit from some domain knowledge (perhaps physics or engineering in this case) to answer this, but let's give it a try.
Technically, that value of 20 has MW22 (megawatts squared) as units (the units get squared as well when we compute the MSE). But the values in our target column are in MW (according to the documentation). Taking the square root of 20 MW22 results in approximately 4.5 MW. Each target value represents net hourly electrical energy output. So for each hour our model is off by 4.5 MW on average. According to this Quora answer, 4.5 MW is equivalent to the heat power produced by 4500 handheld hair dryers. And this would add up if we tried to predict the total energy output for one day or a longer period.
We can conclude that the an MSE of 20 MW22 is quite large. So our model has a bias problem. But is it a low bias problem or a high bias problem?
To find the answer, we need to look at the training error. If the training error is very low, it means that the training data is fitted very well by the estimated model. If the model fits the training data very well, it means it has low bias with respect to that set of data.
If the training error is high, it means that the training data is not fitted well enough by the estimated model. If the model fails to fit the training data well, it means it has high bias with respect to that set of data.
In our particular case, the training MSE plateaus at a value of roughly 20 MW22. As we've already established, this is a high error score. Because the validation MSE is high, and the training MSE is high as well, our model has a high bias problem.
Now let's move with diagnosing eventual variance problems. Estimating variance can be done in at least two ways:
- By examining the gap between the validation learning curve and training learning curve.
- By examining the training error: its value and its evolution as the training set sizes increase.
A narrow gap indicates low variance. Generally, the more narrow the gap, the lower the variance. The opposite is also true: the wider the gap, the greater the variance. Let's now explain why this is the case.
As we've discussed earlier, if the variance is high, then the model fits training data too well. When training data is fitted too well, the model will have trouble generalizing on data that hasn't seen in training..
The relationship between the training and validation error, and the gap can be summarized this way:
gap=validation error−training errorgap=validation error−training error
So the bigger the difference between the two errors, the bigger the gap. The bigger the gap, the bigger the variance.
In our case, the gap is very narrow, so we can safely conclude that the variance is low.
High training MSE scores are also a quick way to detect low variance. If the variance of a learning algorithm is low, then the algorithm will come up with simplistic and similar models as we change the training sets. Because the models are overly simplified, they cannot even fit the training data well (they underfit the data). So we should expect high training MSEs. Hence, high training MSEs can be used as indicators of low variance.
In our case, the training MSE plateaus at around 20, and we've already concluded that's a high value. So besides the narrow gap, we now have another confirmation that we have a low variance problem.
So far, we can conclude that:
- Our learning algorithm suffers from high bias and low variance, underfitting the training data.
- Adding more instances (rows) to the training data is hugely unlikely to lead to better models under the current learning algorithm.
One solution at this point is to change to a more complex learning algorithm. This should decrease the bias and increase the variance. A mistake would be to try to increase the number of training instances.
Generally, these other two fixes also work when dealing with a high bias and low variance problem:
- Training the current learning algorithm on more features (to avoid collecting new data, you can generate easily polynomial features). This should lower the bias by increasing the model's complexity.
- Decreasing the regularization of the current learning algorithm, if that's the case. In a nutshell, regularization prevents the algorithm from fitting the training data too well. If we decrease regularization, the model will fit training data better, and, as a consequence, the variance will increase and the bias will decrease.
Learning curves - low bias and high variance
Let's see how an unregularized Random Forest regressor fares here. We'll generate the learning curves using the same workflow as above. This time we'll bundle everything into a function so we can use it for later. For comparison, we'll also display the learning curves for the linear regression model above.
### Bundling our previous work into a function ### def learning_curves(estimator, data, features, target, train_sizes, cv): train_sizes, train_scores, validation_scores = learning_curve( estimator, data[features], data[target], train_sizes = train_sizes, cv = cv, scoring = 'neg_mean_squared_error') train_scores_mean = -train_scores.mean(axis = 1) validation_scores_mean = -validation_scores.mean(axis = 1) plt.plot(train_sizes, train_scores_mean, label = 'Training error') plt.plot(train_sizes, validation_scores_mean, label = 'Validation error') plt.ylabel('MSE', fontsize = 14) plt.xlabel('Training set size', fontsize = 14) title = 'Learning curves for a ' + str(estimator).split('(')[0] + ' model' plt.title(title, fontsize = 18, y = 1.03) plt.legend() plt.ylim(0,40) ### Plotting the two learning curves ### from sklearn.ensemble import RandomForestRegressor plt.figure(figsize = (16,5)) for model, i in [(RandomForestRegressor(), 1), (LinearRegression(),2)]: plt.subplot(1,2,i) learning_curves(model, electricity, features, target, train_sizes, 5)
Now let's try to apply what we've just learned. It'd be a good idea to pause reading at this point and try to interpret the new learning curves yourself.
Looking at the validation curve, we can see that we've managed to decrease bias. There still is some significant bias, but not that much as before. Looking at the training curve, we can deduce that this time there's a low bias problem.
The new gap between the two learning curves suggests a substantial increase in variance. The low training MSEs corroborate this diagnosis of high variance.
The large gap and the low training error also indicates an overfitting problem. Overfitting happens when the model performs well on the training set, but far poorer on the test (or validation) set.
One more important observation we can make here is that adding new training instances is very likely to lead to better models. The validation curve doesn't plateau at the maximum training set size used. It still has potential to decrease and converge toward the training curve, similar to the convergence we see in the linear regression case.
So far, we can conclude that:
- Our learning algorithm (random forests) suffers from high variance and quite a low bias, overfitting the training data.
- Adding more training instances is very likely to lead to better models under the current learning algorithm.
At this point, here are a couple of things we could do to improve our model:
- Adding more training instances.
- Increase the regularization for our current learning algorithm. This should decrease the variance and increase the bias.
- Reducing the numbers of features in the training data we currently use. The algorithm will still fit the training data very well, but due to the decreased number of features, it will build less complex models. This should increase the bias and decrease the variance.
In our case, we don't have any other readily available data. We could go into the power plant and take some measurements, but we'll save this for another post (just kidding).
Let's rather try to regularize our random forests algorithm. One way to do that is to adjust the maximum number of leaf nodes in each decision tree. This can be done by using the
max_leaf_nodes parameter of
RandomForestRegressor(). It's not necessarily for you to understand this regularization technique. For our purpose here, what you need to focus on is the effect of this regularization on the learning curves.
learning_curves(RandomForestRegressor(max_leaf_nodes = 350), electricity, features, target, train_sizes, 5)
Not bad! The gap is now more narrow, so there's less variance. The bias seems to have increased just a bit, which is what we wanted.
But our work is far from over! The validation MSE still shows a lot of potential to decrease. Some steps you can take toward this goal include:
- Adding more training instances.
- Adding more features.
- Feature selection.
- Hyperparameter optimization.
The ideal learning curves and the irreducible error
Learning curves constitute a great tool to do a quick check on our models at every point in our machine learning workflow. But how do we know when to stop? How do we recognize the perfect learning curves?
For our regression case before, you might think that the perfect scenario is when both curves converge toward an MSE of 0. That's a perfect scenario, indeed, but, unfortunately, it's not possible. Neither in practice, neither in theory. And this is because of something called irreducible error.
When we build a model to map the relationship between the features X and the target Y, we assume that there is such a relationship in the first place. Provided the assumption is true, there is a true model
that describes perfectly the relationship between X and Y, like so:
But why is there an error?! Haven't we just said that
describes the relationship between X and Y perfectly?!
There's an error there because Y is not only a function of our limited number of features X. There could be many other features that influence the value of Y. Features we don't have. It might also be the case that X contains measurement errors. So, besides X, Y is also a function of irreducible error.
Now let's explain why this error is irreducible. When we estimate f(X) with a model
, we introduce another kind of error, called reducible error:
Replacing f(X) in (1) we get:
Error that is reducible can be reduced by building better models. Looking at equation (2) we can see that if the reducible errorreducible error is 0, our estimated model
is equal to the true model f(X). However, from (3) we can see that irreducible error remains in the equation even if reducible error is 0. From here we deduce that no matter how good our model estimate is, generally there still is some error we cannot reduce. And that's why this error is considered irreducible.
This tells us that that in practice the best possible learning curves we can see are those which converge to the value of some irreducible error, not toward some ideal error value (for MSE, the ideal error score is 0; we'll see immediately that other error metrics have different ideal error values).
In practice, the exact value of the irreducible error is almost always unknown. We also assume that the irreducible error is independent of X. This means that we cannot use X to find the true irreducible error. Expressing the same thing in the more precise language of mathematics, there's no function g to map X to the true value of the irreducible error:
irreducible error ≠.
What about classification?
So far, we've learned about learning curves in a regression setting. For classification tasks, the workflow is almost identical. The main difference is that we'll have to choose another error metric - one that is suitable for evaluating the performance of a classifier. Let's see an example:
Source: scikit-learn documentation
Unlike what we've seen so far, notice that the learning curve for the training error is above the one for the validation error. This is because the score used, accuracy, describes how good the model is. The higher the accuracy, the better. The MSE, on the other side, describes how bad a model is. The lower the MSE, the better.
This has implications for the irreducible error as well. For error metrics that describe how bad a model is, the irreducible error gives a lower bound: you cannot get lower than that. For error metrics that describe how good a model is, the irreducible error gives an upper bound: you cannot get higher than that.
As a side note here, in more technical writings the term Bayes error rate is what's usually used to refer to the best possible error score of a classifier. The concept is analogous to the irreducible error.
Next steps
Learning curves constitute a great tool to diagnose bias and variance in any supervised learning algorithm. We've learned how to generate them using scikit-learn and matplotlib, and how to use them to diagnose bias and variance in our models.
To reinforce what you've learned, these are some next steps to consider:
- Generate learning curves for a regression task using a different data set.
- Generate learning curves for a classification task.
- Generate learning curves for a supervised learning task by coding everything from scratch (don't use
learning_curve()from scikit-learn). Using cross-validation is optional.
- Compare learning curves obtained without cross-validating with curves obtained using cross-validation. The two kinds of curves should be for the same learning algorithm.
Bio: Alex Olteanu is a Student Success Specialist at Dataquest.io. He enjoys learning and sharing knowledge, and is getting ready for the new AI revolution.
Original. Reposted with permission.
Related:
- Regularization in Machine Learning
- How to Generate FiveThirtyEight Graphs in Python
- Training Sets, Test Sets, and 10-fold Cross-validation | https://www.kdnuggets.com/2018/01/learning-curves-machine-learning.html/2 | CC-MAIN-2019-18 | refinedweb | 3,519 | 65.42 |
ReportingService2010.CreateLinkedItem Method
Adds a new linked item to the report server database.
Assembly: ReportService2010 (in ReportService2010.dll)
Parameters
- ItemPath
- Type: System.String
The file name of the new linked item including the file name.
- Parent
- Type: System.String
The fully qualified URL of the parent folder to which to add the new item.
- Link
- Type: System.String
The fully qualified URL of the item that will be used for the item definition.
- Properties
- Type: ReportService2010.Property[]
An array of Property objects that defines the property names and values to set for the linked item.
The table below shows header and permissions information on this operation.
The length of the Parent and Link parameters cannot exceed 260 characters; otherwise, a SOAP exception is thrown with the error code rsItemLengthExceeded.
The Parent and Link parameters cannot be null or empty or contain the following reserved characters: : ? ; @ & = + $ , \ * > < | . ". You can use the forward slash character (/) to separate items in the full path name of the folder, but you cannot use it at the end of the folder name
A linked item has the same properties as a standard catalog item, but it does not contain its own item definition. A linked item cannot reference another linked item.
The creator of a linked item must have permission to read the definition of the item that the linked item references; however, this level of permission is not required to run a linked item.
Using the CreateLinkedItem method changes the ModifiedBy and ModifiedDate properties of the parent folder.
To compile this code example, you must reference the Reporting Services WSDL and import certain namespaces. For more information, see Compiling and Running Code Examples. The following code example creates a linked report: | https://technet.microsoft.com/en-us/library/reportservice2010.reportingservice2010.createlinkeditem(v=sql.105).aspx?cs-save-lang=1&cs-lang=jscript | CC-MAIN-2018-13 | refinedweb | 285 | 57.27 |
This is the base class from which all block classes are derived. More...
#include <nxsblock.h>
This is the base class from which all block classes are derived.
A NxsBlock-derived class encapsulates a Nexus block (e.g. DATA block, TREES block, etc.). The abstract virtual function Read must be overridden for each derived class to provide the ability to read everything following the block name (which is read by the NxsReader object) to the end or endblock statement. Derived classes must provide their own data storage and access functions. The abstract virtual function Report must be overridden to provide some feedback to user on contents of block. The abstract virtual function Reset must be overridden to empty the block of all its contents, restoring it to its just-constructed state.
Definition at line 97 of file nxsblock.h. | http://phylo.bio.ku.edu/ncldocs/v2.1/funcdocs/classNxsBlock.html | CC-MAIN-2018-05 | refinedweb | 139 | 64.81 |
[DISCLAIMER:Please Note: Any Image/data in this presentation/video is from SAP internal systems, sample data, or demo systems. Any resemblance to real data is purely coincidental]
Dear All,
In this blog, I would like to explain the steps to create extension field in supplier invoice excel template in SAP Business ByDesign System.
Agenda:
- Pre-Requisite
- Steps to add extension field in supplier invoice excel
Pre-Requisite:
Add the extension field via Adaption Mode and add the field in Inbound Services as per below screenshot:
Steps to add extension field in Excel:
In the below case, we have taken the header extension field ‘Test_SIV_PDI’ as example.
- Go to Supplier Invoicing work center -> select view: Invoices and Credit memos.
- Download the excel template from ‘Import from Microsoft excel’ option as per below screenshot.
3. Once the file is downloaded, open the file location and rename .xlsx to .zip. This will automatically convert the excel file to zip and open it with your preferred zip tool.
XML file location: NewSupplierInvoices_US_EN.zip\xl
4. Extract the XML file to specified folder and edit the same using Notepad ++ .
a) We need to add the field as part of the structure as mentioned below:
<xs:element minOccurs=”0″ maxOccurs=”1″ name=”Test_SIV_PDI” type=”xs:string”/>
b)There is one more change necessary in the xmlMaps.xml , in the transformations section.
<xsl:template match=”Test_SIV_PDI”> <xsl:element namespace=”” name=”Test_SIV_PDI”> <xsl:value-of select=”.”/>
</xsl:element>
</xsl:template>
5. Replace the XML in that zip and rename it from .zip to xlsx
6. Open the excel file and go to Developer->Source. You would be able to see extension field in XML maps ‘SAP_BYD_MAIN’.
Note: If you are unable to see, select it from the drop-down list.
As of now, the extensibility function is not provided in standard invoice upload excel file , hence , please contact your bydesign partner to implement the above steps as per your business requirement.
You can also check following blogs related to excel scenarios: | https://blogs.sap.com/2020/03/05/how-to-add-extension-field-in-supplier-invoice-upload-excel-template/ | CC-MAIN-2020-50 | refinedweb | 334 | 55.74 |
This package helps you reduce boilerplate when composing TEA-based (The Elm Architecture) applications using
Cmd.map,
Sub.map and
Html.map.
Glue is just a thin abstraction over these functions so it's easy to plug it in and out.
This package is highly experimental and might change a lot over time.
Feedback and contributions to both code and documentation are very welcome.
This package is not necessarily designed for either code splitting or reuse but rather for state separation.
State separation might or might not be important for reusing certain parts of application.
Not everything is necessarily stateful. For instance many UI parts can be expressed just by using
view function
to which you pass
msg constructors (
view : msg -> Model -> Html msg for instance) and let consumer manage its state.
On the other hand some things like larger parts of applications or parts containing a lot of self-maintainable stateful logic
can benefit from state isolation since it reduces state handling imposed on consumer of that module.
Generally it's a good rule of thumb single page application in Elm where some modules live in isolation from others. The goals and features of this package are:
updateand
initfunctions.
init,
update,
subscribeand
view.
As you would expect...
$ elm install turboMaCk/glue
The best place to start is probably to have a look at examples.
In particular, you can find examples of:
TEA is an awesome way to write UI apps in Elm. However, not every application
should be defined just in terms of single
Model and
Msg.
Basic separation of
Browser.element is really nice
but in some cases these functions as well as
Model and
Msg types tend to
grow pretty quickly in an unmanageable way so you need to start breaking things
down.
There are many ways
you can go about it. In particular the rest of this document will focus just on
separation of concerns.
This technique is useful for isolating parts that really don't need to know too
much about each other.
It reduces scope of things a particular module can operate with so the number of
things the programmer has to reason about while adding or changing behaviour is
lower. In TEA this is especially touching the
Msg and
Model types and
update
functions for managing the state.
It's important to understand that
init,
update,
view and
subscriptions
are all isolated functions connected via
Browser.element.
In pure functional programming we're "never" really managing state ourselves but
are rather composing functions that takes state as data and produce new version
of it (
update function in TEA).
Now let's have a look at how we can use
Cmd.map,
Sub.map and
Html.map for
concern separation in Elm application. We will nest
init,
update,
subscriptions and
view one into another and
map them from child's to
parent's types. Parent parent module only holds the
Model of a child module
(
SubModule) as a single value, and wraps its
Msg inside one of its own
Msg
constructors (
SubModuleMsg). Of course,
init,
update and
subscriptions
also have to know how to work with this part of
Model, and there you need
Cmd.map,
Sub.map and
Html to deconstruct the pair and construct new one. One can as well utilize
Tuple.mapFirst and
Tuple.mapSecond function (bifunctor interface):
update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of ... SubModuleMsg subMsg -> SubModule.update subMsg model.subModuleModel |> Tuple.mapFirst (\subModel -> { model | subModel = subModel }) |> Tuple.mapSecond (Cmd.map SubModuleMsg) ...
Let's take a look at
view and
Html.map now:
view : Model -> Html Msg view model = Html.div [] [ ... , Html.map SubModuleMsg <| SubModule.view model.subModuleModel , ... ]
You can use
Cmd.map inside
init as well?
The most important type that TEA is built around is
( Model, Cmd Msg ).
All we're missing is just a tiny abstraction that will make working with this
pair easier. This is really the core idea of the whole
Glue package.
To simplify gluing of things together, this package introduces the
Glue type.
This is simply just a name-space for pure functions that defines interface
between modules to which you can then refer by single name. Other functions
within the
Glue package use the
Glue.Glue type as proxy to access these functions.
Note that Glue has essentially 2 parts. The first one is simple Lens for model updates. The second is writer of effects (Cmds, Subscriptions).
This is how we can construct the
Glue type for counter example:
import Glue exposing (Glue) import Counter counter : Glue Model Counter.Model Msg Counter.Msg counter = Glue.glue { msg = CounterMsg , get = .counterModel , set = \subModel model -> { model | counterModel = subModel } }
All mappings from one type to another (
Model and
Msg of parent/child) will
happen as defined in this type. Definition of this interface depends on API of
child module (
Counter in this case).
With
Glue defined, we can go and integrate it to rest of the logic.
Based on the
Glue type definition, we know we're expecting
Model and
Msg
to be (at least) as following:
type alias Model = { counterModel : Counter.Model } type Msg = CounterMsg Counter.Msg
Now we can define init, update and view functions:
init : ( Model, Cmd Msg ) init = ( Model, Cmd.none ) |> Glue.init counter Counter.init update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of CounterMsg counterMsg -> ( model, Cmd.none ) |> Glue.update counter Counter.update counterMsg view : Model -> Html Msg view = Glue.view counter Counter.view
As you can see we're using just
Glue.init,
Glue.update and
Glue.view
in these functions to wire child module. Also compared to the original TEA example
we can easily update parent Model an generate additional parent Cmd as well.
This version of counter is using
Browser.elementtype of interface as opposed to
Browser.sandbox. It is possible to use
Gluewith
sandboxtype of interface. See the counter example and the
Glue.simpleconstructor.
We're going to be using term "polymorphic" just because of the lack of better
name. What we really mean is a module which already translates its inner
Msg
to some
a by function provided from parent module.
Such module can also be generating parent messages using function passed into its functions making it possible to (asynchronously) notify parent module about certain events.
To make the
Counter example "polymorphic" we start by adding one extra argument
to its
view function and use
Html.map internally. Then we need to change type
annotation of
init and
update to
Cmd msg. Since both function are using
just
Cmd.none we don't need to change anything else but that.
init : ( Model, Cmd msg ) update : msg -> Model -> ( Model, Cmd msg ) view : (Msg -> msg) -> Model -> Html msg view toMsg model = Html.map toMsg <| Html.div [] [ Html.button [ Html.Events.onClick Decrement ] [ Html.text "-" ] , Html.text <| toString model , Html.button [ Html.Events.onClick Increment ] [ Html.text "+" ] ]
As you can see
viewis now taking an extra argument - function from
Msgto parent's
msg. In practice it's usually good to use record with functions called
Config msgwhich will be much more extensible.
Now we need to change
Glue type definition in parent module to reflect the new API of
Counter:
counter : Glue Model Counter.Model Msg Msg counter = Glue.poly { get = .counterModel , set = \subModel model -> { model | counterModel = subModel } }
As you can see, we've switched from
Glue.glue function to
Glue.poly.
Also the type signature now contains
Msg twice as the type produced by the
child module is the
Msg of parent module. In fact
Glue.poly is just
a constructor that defines
msg as
identity.
We also need to change parent's view since its API has changed and we need to pass an extra argument now: pattern-match on it in parent.
If you need to do such a thing you might have made a design mistake (improper
separation of state). Do these states really need to be separated? In most cases
communicating with parent in async fashion makes it easier to reason about data
flow in the app but there is no silver bullet. You know the best what best
applies for your case.
Using
Cmd for communication with parent:
-- this uses `GlobalWebIndex/cmd-extra` import Cmd.Extra notify : (Int -> msg) -> Int -> Cmd msg notify toMsg count = Cmd.Extra.perform <| toMsg toMsg = let model = 0 in ( 0, notify toMsg model ) update : (Int -> msg) -> Msg -> Model -> ( Model, Cmd msg ) update toParentMsg msg model = let newModel = case msg of Increment -> model + 1 Decrement -> model - 1 in ( newModel, notify toParentMsg newModel )
Now both
init and
update should send
Cmd after
Model is updated.
This is a breaking change to
Counter's API (an extra argument) so we need to change its integration as well.
But since we want to actually use this message and do something with it let's first update
the parent's
Model and
Msg:
type alias Model = { max : Int , counter : Counter.Model } type Msg = CounterMsg Counter.Msg | CountChanged Int
Because we've changed
Model (added
max : Int) we should change
init
and probably render max value in
view of parent as well:
init : ( Model, Cmd Msg ) init = ( Model 0, Cmd.none ) |> Glue.init counter Counter.init.update CountChanged) counterMsg CountChanged num -> if num > model.max then ( { model | max = num }, Cmd.none ) else ( model, Cmd.none )
As you can see we're setting
max to received int if it's greater than the current value.
See this complete example to learn more.
BSD-3-Clause | https://package.frelm.org/repo/926/6.0.0 | CC-MAIN-2019-30 | refinedweb | 1,580 | 67.04 |
After you create a service retry rule for a multi-language application, if the application is temporarily inaccessible or encounters an occasional error, a request is retired to ensure that the expected results can be returned. This improves the robustness of the system. This topic describes how to create a service retry rule for a multi-language application.
Precautions
If you create both a service timeout rule and a service retry rule for an application, the timeout period that you specify for the former rule may affect the number of retries allowed.
For example, you set the timeout period to 1,000 ms and the maximum number of retries to five for errors with a code of 5xx for an application. If the application takes 300 ms to process a request, a timeout error occurs after the application attempts to process the third retry although a maximum of five retries are allowed. The following figure shows the detailed information:
Create a service retry rule
- Log on to the EDAS console.
- In the left-side navigation pane, choose .
- In the left-side navigation tree of the Service Mesh page, click Service Retry Setting.
- Select a region in the top navigation bar. Select a microservice namespace from the drop-down list next to Retry and click Create rule.
- In the Create a service retry rule panel, set the parameters and click OK.
The following table describes the parameters.After the service retry rule is created and enabled, check whether the rule takes effect.
Related operations
After you create a service retry rule, you can click Edit, Close, or Open in the Operation column to manage the rule. If the service retry rule is no longer required, you can click Delete to delete the rule. | https://www.alibabacloud.com/help/en/enterprise-distributed-application-service/latest/create-a-service-retry-rule-for-a-multi-language-application | CC-MAIN-2022-27 | refinedweb | 292 | 53.41 |
Technical Support
On-Line Manuals
Cx51 User's Guide
#include <80c517.h>
int printf517 (
const char *fmtstr /* format string */
<[>, arguments ...<]>); /* additional arguments */
The printf517 ('%') and require that additional
arguments are included in the printf517, the extra argumentsare ignored. Results are unpredictable if there
are not enough arguments for the format
specifications.
Format specifications have the following.
Note
Characters following a percent sign that are not recognized as a
format specification are treated as ordinary characters. For example,
"%%" writes a single percent sign to the output stream.
The flag field is a single character used to justify the
output and to print +/- signs and blanks, decimal points, and octal
and hexadecimal prefixes, as shown in the following table. '.
The precision field may be an asterisk ('*'), in which case
an int argument from the argument list provides
the value for the precision. Specifying a 'b' in front of the
asterisk specifies that the argument is an unsigned char.
The printf517 function returns the number of characters
actually written to the output stream.
gets, printf, puts, scanf, scanf517, sprintf517, sscanf, sscanf517, vprintf, vsprintf
#include <80c517.h>
void tst_printf517 517 ("char %bd int %d long %ld\n",a,b,c);
printf517 ("Uchar %bu Uint %u Ulong %lu\n",x,y,z);
printf517 ("xchar %bx xint %x xlong %lx\n",x,y,z);
printf517 ("String %s is at address %p\n",buf,p);
printf517 ("%f != %g\n", f, g);
printf517 ("%*f != %*g\n", (int)8, f, (int)8,. | https://www.keil.com/support/man/docs/c51/c51_printf517.htm | CC-MAIN-2020-40 | refinedweb | 243 | 56.55 |
pylapyla
pyla is a redis based storage system which can filter entries based on item's attributes.
In it's current version it stores the information of the entry in a sorted set with all information present in the key.
Why pyla?Why pyla?
Say you have certain jobs that you want to schedule and every job has certain attributes associated to it.
from pyla import entries from pyla import fields class Job(entries.Entry): id = fields.BaseField(primary=True) type = fields.BaseField(index=True) assigned_to = fields.BaseField(index=True) info = fields.BaseField(index=False) j = Job(id=1, type='create', assigned_to='dush', info='testing') j.save()
on calling save on that particular entry you will have following sorted sets available in redis
job job:type:create job:assigned_to:dush
Then you have the following awesome filtering abilities:
# Get all the jobs Job.objects.all() # Get jobs with type create Job.objects.filter(type='create') # Get jobs with either create or delete type Job.objects.filter(type=['create', 'delete']) # Get jobs which are assigened to dush Job.objects.filter(assigned_to='dush') # Get jobs which are assigened to dush or spam Job.objects.filter(assigned_to=['dush', 'spam']) # Get jobs which are assigened to dush and are of type create Job.objects.filter(assigned_to='dush', type='create') # Get jobs which are assigened to dush and are of type create or delete Job.objects.filter(assigned_to='dush', type=['create','delete']) # Get jobs which are assigened to dush or spam and are of type create or delete Job.objects.filter(assigned_to=['dush', 'spam'], type=['create','delete'])
You can have any number of filters over the fields which were set to index. Obviously, the more indexes you have the slower your writes become. | https://libraries.io/pypi/pyla | CC-MAIN-2018-26 | refinedweb | 288 | 50.94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.