| I l@ve RuBoard |
1.2 The _ _builtin_ _ ModuleThis module contains built-in functions that are automatically available in all Python modules. You usually don't have to import this module; Python does that for you when necessary. 1.2.1 Calling a Function with Arguments from a Tuple or DictionaryPython allows you to build function argument lists on the fly. Just put all the arguments in a tuple, and call the built-in apply function, as illustrated in Example 1-1. Example 1-1. Using the apply FunctionFile: builtin-apply-example-1.py def function(a, b): print a, b apply(function, ("whither", "canada?")) apply(function, (1, 2 + 3)) whither canada? 1 5 To pass keyword arguments to a function, you can use a dictionary as the third argument to apply, as shown in Example 1-2. Example 1-2. Using the apply Function to Pass Keyword ArgumentsFile: builtin-apply-example-2.py def function(a, b): print a, b apply(function, ("crunchy", "frog")) apply(function, ("crunchy",), {"b": "frog"}) apply(function, (), {"a": "crunchy", "b": "frog"}) crunchy frog crunchy frog crunchy frog One common use for apply is to pass constructor arguments from a subclass on to the base class, especially if the constructor takes a lot of arguments. See Example 1-3. Example 1-3. Using the apply Function to Call Base Class ConstructorsFile: builtin-apply-example-3.py class Rectangle: def _ _init_ _(self, color="white", width=10, height=10): print "create a", color, self, "sized", width, "x", height class RoundedRectangle(Rectangle): def _ _init_ _(self, **kw): apply(Rectangle._ _init_ _, (self,), kw) rect = Rectangle(color="green", height=100, width=100) rect = RoundedRectangle(color="blue", height=20) create a green <Rectangle instance at 8c8260> sized 100 x 100 create a blue <RoundedRectangle instance at 8c84c0> sized 10 x 20 Python 2.0 provides an alternate syntax. Instead of apply, you can use an ordinary function call, and use * to mark the tuple, and ** to mark the dictionary. The following two statements are equivalent: result = function(*args, **kwargs) result = apply(function, args, kwargs) 1.2.2 Loading and Reloading ModulesIf you've written a Python program larger than just a few lines, you know that the import statement is used to import external modules (you can also use the from-import version). What you might not know already is that import delegates the actual work to a built-in function called _ _import_ _. The trick is that you can call this function directly. This can be handy if you have the module name in a string variable, as in Example 1-4, which imports all modules whose names end with "-plugin": Example 1-4. Using the _ _import_ _ Function to Load Named ModulesFile: builtin-import-example-1.py import glob, os modules = [] for module_file in glob.glob("*-plugin.py"): try: module_name, ext = os.path.splitext(os.path.basename(module_file)) module = _ _import_ _(module_name) modules.append(module) except ImportError: pass # ignore broken modules # say hello to all modules for module in modules: module.hello() example-plugin says hello Note that the plug-in modules have hyphens. This means that you cannot import such a module using the ordinary import command, since you cannot have hyphens in Python identifiers. Example 1-5 shows the plug-in used in Example 1-4. Example 1-5. A Sample Plug-inFile: example-plugin.py def hello(): print "example-plugin says hello" Example 1-6 shows how to get a function object, given that the module and function name are strings. Example 1-6. Using the _ _import_ _ Function to Get a Named FunctionFile: builtin-import-example-2.py def getfunctionbyname(module_name, function_name): module = _ _import_ _(module_name) return getattr(module, function_name) print repr(getfunctionbyname("dumbdbm", "open")) <function open at 794fa0> You can also use this function to implement lazy module loading. In Example 1-7, the string module is imported when it is first used. Example 1-7. Using the _ _import_ _ Function to Implement Lazy ImportFile: builtin-import-example-3.py class LazyImport: def _ _init_ _(self, module_name): self.module_name = module_name self.module = None def _ _getattr_ _(self, name): if self.module is None: self.module = _ _import_ _(self.module_name) return getattr(self.module, name) string = LazyImport("string") print string.lowercase abcdefghijklmnopqrstuvwxyz Python provides some basic support for reloading modules that you've already imported. Example 1-8 loads the hello.py file three times. Example 1-8. Using the reload FunctionFile: builtin-reload-example-1.py import hello reload(hello) reload(hello) hello again, and welcome to the show hello again, and welcome to the show hello again, and welcome to the show reload uses the module name associated with the module object, not the variable name. Even if you've renamed the original module, reload can still find it. Note that when you reload a module, it is recompiled, and the new module replaces the old one in the module dictionary. However, if you have created instances of classes defined in that module, those instances will still use the old implementation. Likewise, if you've used from-import to create references to module members in other modules, those references will not be updated. 1.2.3 Looking in NamespacesThe dir function returns a list of all members of a given module, class, instance, or other type. It's probably most useful when you're working with an interactive Python interpreter, but can also come in handy in other situations. Example 1-9 shows the dir function in use. Example 1-9. Using the dir FunctionFile: builtin-dir-example-1.py def dump(value): print value, "=>", dir(value) import sys dump(0) dump(1.0) dump(0.0j) # complex number dump([]) # list dump({}) # dictionary dump("string") dump(len) # function dump(sys) # module 0 => [] 1.0 => [] 0j => ['conjugate', 'imag', 'real'] [] => ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] {} => ['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'update', 'values'] string => [] <built-in function len> => ['_ _doc_ _', '_ _name_ _', '_ _self_ _'] <module 'sys' (built-in)> => ['_ _doc_ _', '_ _name_ _', '_ _stderr_ _', '_ _stdin_ _', '_ _stdout_ _', 'argv', 'builtin_module_names', 'copyright', 'dllhandle', 'exc_info', 'exc_type', 'exec_prefix', 'executable', ... In Example 1-10, the getmember function returns all class-level attributes and methods defined by a given class. Example 1-10. Using the dir Function to Find All Members of a ClassFile: builtin-dir-example-2.py class A: def a(self): pass def b(self): pass class B(A): def c(self): pass def d(self): pass def getmembers(klass, members=None): # get a list of all class members, ordered by class if members is None: members = [] for k in klass._ _bases_ _: getmembers(k, members) for m in dir(klass): if m not in members: members.append(m) return members print getmembers(A) print getmembers(B) print getmembers(IOError) ['_ _doc_ _', '_ _module_ _', 'a', 'b'] ['_ _doc_ _', '_ _module_ _', 'a', 'b', 'c', 'd'] ['_ _doc_ _', '_ _getitem_ _', '_ _init_ _', '_ _module_ _', '_ _str_ _'] Note that the getmembers function returns an ordered list. The earlier a name appears in the list, the higher up in the class hierarchy it's defined. If order doesn't matter, you can use a dictionary to collect the names instead of a list. The vars function is similar, but it returns a dictionary containing the current value for each member. If you use vars without an argument, it returns a dictionary containing what's visible in the current local namespace, as shown in Example 1-11. Example 1-11. Using the vars FunctionFile: builtin-vars-example-1.py book = "library2" pages = 250 scripts = 350 print "the %(book)s book contains more than %(scripts)s scripts" % vars() the library book contains more than 350 scripts 1.2.4 Checking an Object's TypePython is a dynamically typed language, which means that a given variable can be bound to values of different types on different occasions. In the following example, the same function is called with an integer, a floating point value, and a string: def function(value): print value function(1) function(1.0) function("one") The type function (shown in Example 1-12) allows you to check what type a variable has. This function returns a type descriptor, which is a unique object for each type provided by the Python interpreter. Example 1-12. Using the type FunctionFile: builtin-type-example-1.py def dump(value): print type(value), value dump(1) dump(1.0) dump("one") <type 'int'> 1 <type 'float'> 1.0 <type 'string'> one Each type has a single corresponding type object, which means that you can use the is operator (object identity) to do type testing (as shown in Example 1-13). Example 1-13. Using the type Function with Filenames and File ObjectsFile: builtin-type-example-2.py def load(file): if isinstance(file, type("")): file = open(file, "rb") return file.read() print len(load("samples/sample.jpg")), "bytes" print len(load(open("samples/sample.jpg", "rb"))), "bytes" 4672 bytes 4672 bytes The callable function, shown in Example 1-14, checks if an object can be called (either directly or via apply). It returns true for functions, methods, lambda expressions, classes, and class instances that define the _ _call_ _ method. Example 1-14. Using the callable FunctionFile: builtin-callable-example-1.py def dump(function): if callable(function): print function, "is callable" else: print function, "is *not* callable" class A: def method(self, value): return value class B(A): def _ _call_ _(self, value): return value a = A() b = B() dump(0) # simple objects dump("string") dump(callable) dump(dump) # function dump(A) # classes dump(B) dump(B.method) dump(a) # instances dump(b) dump(b.method) 0 is *not* callable string is *not* callable <built-in function callable> is callable <function dump at 8ca320> is callable A is callable B is callable <unbound method A.method> is callable <A instance at 8caa10> is *not* callable <B instance at 8cab00> is callable <method A.method of B instance at 8cab00> is callable Note that the class objects (A and B) are both callable; if you call them, they create new objects. However, instances of class A are not callable, since that class doesn't have a _ _call_ _ method. You'll find functions to check if an object is of any of the built-in number, sequence, or dictionary types in the operator module. However, since it's easy to create a class that implements (for example, the basic sequence methods), it's usually a bad idea to use explicit type testing on such objects. Things get even more complicated when it comes to classes and instances. Python doesn't treat classes as types per se; instead, all classes belong to a special class type, and all class instances belong to a special instance type. This means that you cannot use type to test if an instance belongs to a given class; all instances have the same type! To solve this, you can use the isinstance function, which checks if an object is an instance of a given class (or of a subclass to it). Example 1-15 illustrates the isinstance function. Example 1-15. Using the isinstance FunctionFile: builtin-isinstance-example-1.py class A: pass class B: pass class C(A): pass class D(A, B): pass def dump(object): print object, "=>", if isinstance(object, A): print "A", if isinstance(object, B): print "B", if isinstance(object, C): print "C", if isinstance(object, D): print "D", print a = A() b = B() c = C() d = D() dump(a) dump(b) dump(c) dump(d) dump(0) dump("string") <A instance at 8ca6d0> => A <B instance at 8ca750> => B <C instance at 8ca780> => A C <D instance at 8ca7b0> => A B D 0 => string => The issubclass function is similar, but it instead checks whether a class object is the same as a given class, or is a subclass of it. The issubclass function is shown in Example 1-16. Note that while isinstance accepts any kind of object, the issubclass function raises a TypeError exception if you use it on something that is not a class object. Example 1-16. Using the issubclass FunctionFile: builtin-issubclass-example-1.py class A: pass class B: pass class C(A): pass class D(A, B): pass def dump(object): print object, "=>", if issubclass(object, A): print "A", if issubclass(object, B): print "B", if issubclass(object, C): print "C", if issubclass(object, D): print "D", print dump(A) dump(B) dump(C) dump(D) dump(0) dump("string") A => A B => B C => A C D => A B D 0 => Traceback (innermost last): File "builtin-issubclass-example-1.py", line 29, in ? File "builtin-issubclass-example-1.py", line 15, in dump TypeError: arguments must be classes 1.2.5 Evaluating Python ExpressionsPython provides several ways to interact with the interpreter from within a program. For example, the eval function evaluates a string as if it were a Python expression. You can pass it a literal, simple expression, or use built-in functions, as shown in Example 1-17. Example 1-17. Using the eval FunctionFile: builtin-eval-example-1.py def dump(expression): result = eval(expression) print expression, "=>", result, type(result) dump("1") dump("1.0") dump("'string'") dump("1.0 + 2.0") dump("'*' * 10") dump("len('world')") 1 => 1 <type 'int'> 1.0 => 1.0 <type 'float'> 'string' => string <type 'string'> 1.0 + 2.0 => 3.0 <type 'float'> '*' * 10 => ********** <type 'string'> len('world') => 5 <type 'int'> If you cannot trust the source from which you got the string, you may get into trouble using eval. For example, someone might use the built-in _ _import_ _ function to load the os module, and then remove files on your disk (as shown in Example 1-18). Example 1-18. Using the eval Function to Execute Arbitrary CommandsFile: builtin-eval-example-2.py print eval("_ _import_ _('os').getcwd()") print eval("_ _import_ _('os').remove('file')") /home/fredrik/librarybook Traceback (innermost last): File "builtin-eval-example-2", line 2, in ? File "<string>", line 0, in ? os.error: (2, 'No such file or directory') Note that you get an os.error exception, which means that Python actually tried to remove the file! Luckily, there's a way around this problem. You can pass a second argument to eval, which should contain a dictionary defining the namespace in which the expression is evaluated. Let's pass in an empty namespace: >>> print eval("_ _import_ _('os').remove('file')", {}) Traceback (innermost last): File "<stdin>", line 1, in ? File "<string>", line 0, in ? os.error: (2, 'No such file or directory') Hmm. We still end up with an os.error exception. The reason for this is that Python looks in the dictionary before it evaluates the code, and if it doesn't find a variable named _ _builtins_ _ in there (note the plural form), it adds one: >>> namespace = {} >>> print eval("_ _import_ _('os').remove('file')", namespace) Traceback (innermost last): File "<stdin>", line 1, in ? File "<string>", line 0, in ? os.error: (2, 'No such file or directory') >>> namespace.keys() ['_ _builtins_ _'] If you print the contents of the namespace variable, you'll find that they contain the full set of built-in functions. The solution to this little dilemma isn't far away: since Python doesn't add this item if it is already there, simply add a dummy item called _ _builtins_ _ to the namespace before calling eval, as shown in Example 1-19. Example 1-19. Using the eval Function to Evaluate Arbitrary Strings SafelyFile: builtin-eval-example-3.py print eval("_ _import_ _('os').getcwd()", {}) print eval("_ _import_ _('os').remove('file')", {"_ _builtins_ _": {}}) /home/fredrik/librarybook Traceback (innermost last): File "builtin-eval-example-3.py", line 2, in ? File "<string>", line 0, in ? NameError: _ _import_ _ Note that this doesn't protect you from CPU or memory-resource attacks (for example, something like eval("'*'*1000000*2*2*2*2*2*2*2*2*2") will most likely cause your program to run out of memory after a while). 1.2.6 Compiling and Executing CodeThe eval function only works for simple expressions. To handle larger blocks of code, use the compile and exec functions (as demonstrated in Example 1-20). Example 1-20. Using the compile Function to Check SyntaxFile: builtin-compile-example-1.py NAME = "script.py" BODY = """ prnt 'owl-stretching time' """ try: compile(BODY, NAME, "exec") except SyntaxError, v: print "syntax error:", v, "in", NAME # syntax error: invalid syntax in script.py When successful, the compile function returns a code object, which you can execute with the exec statement, as in Example 1-21. Example 1-21. Compiling and Executing Compiled CodeFile: builtin-compile-example-2.py BODY = """ print 'the ant, an introduction' """ code = compile(BODY, "<script>", "exec") print code exec code <code object ? at 8c6be0, file "<script>", line 0> the ant, an introduction To generate code on the fly, use the class shown in the Example 1-22. Use the write method to add statements, and the methods indent and dedent to add structure. The class will take care of the rest. Example 1-22. A Simple Code Generator ToolFile: builtin-compile-example-3.py import sys, string class CodeGeneratorBackend: "Simple code generator for Python" def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): self.code.append("") # make sure there's a newline at the end return compile(string.join(self.code, "\n"), "<code>", "exec") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 # in 2.0 and later, this can be written as: self.level += 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 # or: self.level -= 1 # # try it out! c = CodeGeneratorBackend() c.begin() c.write("for i in range(5):") c.indent() c.write("print 'code generation made easy!'") c.dedent() exec c.end() code generation made easy! code generation made easy! code generation made easy! code generation made easy! code generation made easy! Python also provides a function called execfile, a shortcut for loading code from a file, compiling it, and executing it. Example 1-23 shows how to use and emulate this function. Example 1-23. Using the execfile FunctionFile: builtin-execfile-example-1.py execfile("hello.py") def EXECFILE(filename, locals=None, globals=None): exec compile(open(filename).read(), filename, "exec") in locals, globals EXECFILE("hello.py") hello again, and welcome to the show hello again, and welcome to the show The contents of the hello.py file used Example 1-23 are shown in Example 1-24. Example 1-24. The hello.py ScriptFile: hello.py print "hello again, and welcome to the show" 1.2.7 Overloading Functions from the _ _builtin_ _ ModuleSince Python does not look among the built-in functions until after it has checked the local and module namespace, there may be situations in which you need to explicitly refer to the _ _builtin_ _ module. For instance, the script in Example 1-25 overloads the open function with a version that opens an ordinary file and checks that it starts with a "magic" string. To be able to use the original open function, the script explicitly refers to the function using the module name. Example 1-25. Explicitly Accessing Functions in the _ _builtin_ _ ModuleFile: builtin-open-example-1.py def open(filename, mode="rb"): import _ _builtin_ _ file = _ _builtin_ _.open(filename, mode) if file.read(5) not in("GIF87", "GIF89"): raise IOError, "not a GIF file" file.seek(0) return file fp = open("samples/sample.gif") print len(fp.read()), "bytes" fp = open("samples/sample.jpg") print len(fp.read()), "bytes" 3565 bytes Traceback (innermost last): File "builtin-open-example-1.py", line 12, in ? File "builtin-open-example-1.py", line 5, in open IOError: not a GIF file |
| I l@ve RuBoard |


§651-15 Officer's return; how made. The police officer shall make out a full inventory of the property attached and return the same with the writ of attachment. The police officer shall return the writ with the summons if issued at the same time; otherwise, within such time after its receipt as is allowed for a return of summons, with certificate of the police officer's proceedings endorsed thereon or attached thereto. [L 1905, c 84, §15; RL 1925, §2819; RL 1935, §4204; RL 1945, §10155; RL 1955, §233-15; HRS §651-15; gen ch 1985]
Revision Note
"Indorsed" changed to "endorsed" pursuant to §23G-15.
Rules of Court
See HRCP rule 4(g).


Is anyone available to do some animating?
Posted: Tue Jan 06, 2009 12:16 pm
If so, let me know. I have been spending a not-insignificant amount of time tinkering with character animations (cast spell, attack, get hit, etc...), and I think it might be time to outsource so I can get back to the code
You only need basic 3d modeling experience and you don't have to buy anything--all you need is time to play around with a file I send you.
Karl
You only need basic 3d modeling experience and you don't have to buy anything--all you need is time to play around with a file I send you.
Karl


You have 1 new tasks
You have 2 new notifications
Set Avatar
<EMAIL_ADDRESS>You08:44
Hi, we have some ideas for this template
Jake Rochleau08:45
Great! Let tell us now...


Maniana To Do List ${version_name}
What's new?
- Add and order task colors (in Settings | Tasks).
- French translation (thanks Cecile).
- German translation (thanks Bernd).
- Backup/Restore using Dropbox and Google Drive.
- Hiding Icon Widget count when zero.
- Various fixes and tweaks.
Press the Back button to continue...


Master de II. ULL. 1er cuatrimestre. 2020/2021
SameSite=None
supportsameSite: true
to work with draft-7 clients
true
now sends SameSite=Strict
instead of SameSite
sameSite
option
firstPartyOnly
option, never implemented by browsersencode
is not a functionexpires
is not a Date
Max-Age
to never be a floating point numberserialize
firstPartyOnly
optionserialize
maxAge
of 0
decode
optionencode
option=
maxAge
option to not throw error


|
| | CSimpleIniTempl (bool a_bIsUtf8=false, bool a_bMultiKey=false, bool a_bMultiLine=false) |
| |
| | ~CSimpleIniTempl () |
| |
| void | Reset () |
| |
| bool | IsEmpty () const |
| |
| SI_Error | LoadFile (const char *a_pszFile) |
| |
| SI_Error | LoadFile (FILE *a_fpFile) |
| |
| SI_Error | LoadData (const std::string &a_strData) |
| |
| SI_Error | LoadData (const char *a_pData, size_t a_uDataLen) |
| |
| SI_Error | SaveFile (const char *a_pszFile, bool a_bAddSignature=true) const |
| |
| SI_Error | SaveFile (FILE *a_pFile, bool a_bAddSignature=false) const |
| |
| SI_Error | Save (OutputWriter &a_oOutput, bool a_bAddSignature=false) const |
| |
| SI_Error | Save (std::string &a_sBuffer, bool a_bAddSignature=false) const |
| |
| void | GetAllSections (TNamesDepend &a_names) const |
| |
| bool | GetAllKeys (const SI_CHAR *a_pSection, TNamesDepend &a_names) const |
| |
| bool | GetAllValues (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, TNamesDepend &a_values) const |
| |
| int | GetSectionSize (const SI_CHAR *a_pSection) const |
| |
| const TKeyVal * | GetSection (const SI_CHAR *a_pSection) const |
| |
| const SI_CHAR * | GetValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pDefault=NULL, bool *a_pHasMultiple=NULL) const |
| |
| long | GetLongValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nDefault=0, bool *a_pHasMultiple=NULL) const |
| |
| double | GetDoubleValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nDefault=0, bool *a_pHasMultiple=NULL) const |
| |
| bool | GetBoolValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bDefault=false, bool *a_pHasMultiple=NULL) const |
| |
| SI_Error | SetValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pValue, const SI_CHAR *a_pComment=NULL, bool a_bForceReplace=false) |
| |
| SI_Error | SetLongValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, long a_nValue, const SI_CHAR *a_pComment=NULL, bool a_bUseHex=false, bool a_bForceReplace=false) |
| |
| SI_Error | SetDoubleValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, double a_nValue, const SI_CHAR *a_pComment=NULL, bool a_bForceReplace=false) |
| |
| SI_Error | SetBoolValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bValue, const SI_CHAR *a_pComment=NULL, bool a_bForceReplace=false) |
| |
| bool | Delete (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, bool a_bRemoveEmpty=false) |
| |
| bool | DeleteValue (const SI_CHAR *a_pSection, const SI_CHAR *a_pKey, const SI_CHAR *a_pValue, bool a_bRemoveEmpty=false) |
| |
| Converter | GetConverter () const |
| |
|
| void | SetUnicode (bool a_bIsUtf8=true) |
| |
| bool | IsUnicode () const |
| |
| void | SetMultiKey (bool a_bAllowMultiKey=true) |
| |
| bool | IsMultiKey () const |
| |
| void | SetMultiLine (bool a_bAllowMultiLine=true) |
| |
| bool | IsMultiLine () const |
| |
| void | SetSpaces (bool a_bSpaces=true) |
| |
| bool | UsingSpaces () const |
| |
template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
class CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >
Simple INI file reader.
This can be instantiated with the choice of unicode or native characterset, and case sensitive or insensitive comparisons of section and key names. The supported combinations are pre-defined with the following typedefs:
| Interface | Case-sensitive | Typedef |
| char | No | CSimpleIniA |
| char | Yes | CSimpleIniCaseA |
| wchar_t | No | CSimpleIniW |
| wchar_t | Yes | CSimpleIniCaseW |
Note that using other types for the SI_CHAR is supported. For instance, unsigned char, unsigned short, etc. Note that where the alternative type is a different size to char/wchar_t you may need to supply new helper classes for SI_STRLESS and SI_CONVERTER.
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
| bool CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::Delete |
( |
const SI_CHAR * |
a_pSection, |
|
|
const SI_CHAR * |
a_pKey, |
|
|
bool |
a_bRemoveEmpty = false |
|
) |
| |
Delete an entire section, or a key from a section. Note that the data returned by GetSection is invalid and must not be used after anything has been deleted from that section using this method. Note when multiple keys is enabled, this will delete all keys with that name; to selectively delete individual key/values, use DeleteValue.
- Parameters
-
| a_pSection | Section to delete key from, or if a_pKey is NULL, the section to remove. |
| a_pKey | Key to remove from the section. Set to NULL to remove the entire section. |
| a_bRemoveEmpty | If the section is empty after this key has been deleted, should the empty section be removed? |
- Returns
- true Key or section was deleted.
-
false Key or section was not found.
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
| bool CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::DeleteValue |
( |
const SI_CHAR * |
a_pSection, |
|
|
const SI_CHAR * |
a_pKey, |
|
|
const SI_CHAR * |
a_pValue, |
|
|
bool |
a_bRemoveEmpty = false |
|
) |
| |
Delete an entire section, or a key from a section. If value is provided, only remove keys with the value. Note that the data returned by GetSection is invalid and must not be used after anything has been deleted from that section using this method. Note when multiple keys is enabled, all keys with the value will be deleted.
- Parameters
-
| a_pSection | Section to delete key from, or if a_pKey is NULL, the section to remove. |
| a_pKey | Key to remove from the section. Set to NULL to remove the entire section. |
| a_pValue | Value of key to remove from the section. Set to NULL to remove all keys. |
| a_bRemoveEmpty | If the section is empty after this key has been deleted, should the empty section be removed? |
- Returns
- true Key/value or section was deleted.
-
false Key/value or section was not found.
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
Retrieve all unique key names in a section. The sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example. Only unique key names are returned.
NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use!
- Parameters
-
| a_pSection | Section to request data for |
| a_names | List that will receive all of the key names. See note above! |
- Returns
- true Section was found.
-
false Matching section was not found.
template<class SI_CHAR , class SI_STRLESS , class SI_CONVERTER >
Retrieve all section names. The list is returned as an STL vector of names and can be iterated or searched as necessary. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example.
NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these pointers are in use!
- Parameters
-
| a_names | Vector that will receive all of the section names. See note above! |
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
| bool CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::GetAllValues |
( |
const SI_CHAR * |
a_pSection, |
|
|
const SI_CHAR * |
a_pKey, |
|
|
TNamesDepend & |
a_values |
|
) |
| const |
Retrieve all values for a specific key. This method can be used when multiple keys are both enabled and disabled. Note that the sort order of the returned strings is NOT DEFINED. You can sort the names into the load order if desired. Search this file for ".sort" for an example.
NOTE! The returned values are pointers to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer!
- Parameters
-
| a_pSection | Section to search |
| a_pKey | Key to search for |
| a_values | List to return if the key is not found |
- Returns
- true Key was found.
-
false Matching section/key was not found.
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
| bool CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::GetBoolValue |
( |
const SI_CHAR * |
a_pSection, |
|
|
const SI_CHAR * |
a_pKey, |
|
|
bool |
a_bDefault = false , |
|
|
bool * |
a_pHasMultiple = NULL |
|
) |
| const |
Retrieve a boolean value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey.
Strings starting with "t", "y", "on" or "1" are returned as logically true. Strings starting with "f", "n", "of" or "0" are returned as logically false. For all other values the default is returned. Character comparisons are case-insensitive.
- Parameters
-
| a_pSection | Section to search |
| a_pKey | Key to search for |
| a_bDefault | Value to return if the key is not found |
| a_pHasMultiple | Optionally receive notification of if there are multiple entries for this key. |
- Returns
- a_nDefault Key was not found in the section
-
other Value of the key
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
Retrieve all key and value pairs for a section. The data is returned as a pointer to an STL map and can be iterated or searched as desired. Note that multiple entries for the same key may exist when multiple keys have been enabled.
NOTE! This structure contains only pointers to strings. The actual string data is stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset() while these strings are in use!
- Parameters
-
| a_pSection | Name of the section to return |
- Returns
- boolean Was a section matching the supplied name found.
template<class SI_CHAR, class SI_STRLESS , class SI_CONVERTER >
| const SI_CHAR * CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::GetValue |
( |
const SI_CHAR * |
a_pSection, |
|
|
const SI_CHAR * |
a_pKey, |
|
|
const SI_CHAR * |
a_pDefault = NULL , |
|
|
bool * |
a_pHasMultiple = NULL |
|
) |
| const |
Retrieve the value for a specific key. If multiple keys are enabled (see SetMultiKey) then only the first value associated with that key will be returned, see GetAllValues for getting all values with multikey.
NOTE! The returned value is a pointer to string data stored in memory owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed or Reset while you are using this pointer!
- Parameters
-
| a_pSection | Section to search |
| a_pKey | Key to search for |
| a_pDefault | Value to return if the key is not found |
| a_pHasMultiple | Optionally receive notification of if there are multiple entries for this key. |
- Returns
- a_pDefault Key was not found in the section
-
other Value of the key
template<class SI_CHAR , class SI_STRLESS , class SI_CONVERTER >
Save the INI data. The data will be written to the output device in a format appropriate to the current data, selected by:
| SI_CHAR | FORMAT |
| char | same format as when loaded (MBCS or UTF-8) |
| wchar_t | UTF-8 |
| other | UTF-8 |
Note that comments from the original data is preserved as per the documentation on comments. The order of the sections and values from the original file will be preserved.
Any data prepended or appended to the output device must use the the same format (MBCS or UTF-8). You may use the GetConverter() method to convert text to the correct format regardless of the output format being used by SimpleIni.
To add a BOM to UTF-8 data, write it out manually at the very beginning like is done in SaveFile when a_bUseBOM is true.
- Parameters
-
| a_oOutput | Output writer to write the data to. |
| a_bAddSignature | Prepend the UTF-8 BOM if the output data is in UTF-8 format. If it is not UTF-8 then this value is ignored. Do not set this to true if anything has already been written to the OutputWriter. |
- Returns
- SI_Error See error definitions
template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
| void CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::SetMultiKey |
( |
bool |
a_bAllowMultiKey = true | ) |
|
|
inline |
Should multiple identical keys be permitted in the file. If set to false then the last value encountered will be used as the value of the key. If set to true, then all values will be available to be queried. For example, with the following input:
[section]
test=value1
test=value2
Then with SetMultiKey(true), both of the values "value1" and "value2" will be returned for the key test. If SetMultiKey(false) is used, then the value for "test" will only be "value2". This value may be changed at any time.
- Parameters
-
| a_bAllowMultiKey | Allow multi-keys in the source? |
template<class SI_CHAR, class SI_STRLESS, class SI_CONVERTER>
| void CSimpleIniTempl< SI_CHAR, SI_STRLESS, SI_CONVERTER >::SetUnicode |
( |
bool |
a_bIsUtf8 = true | ) |
|
|
inline |
Set the storage format of the INI data. This affects both the loading and saving of the INI data using all of the Load/Save API functions. This value cannot be changed after any INI data has been loaded.
If the file is not set to Unicode (UTF-8), then the data encoding is assumed to be the OS native encoding. This encoding is the system locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP. If the storage format is set to Unicode then the file will be loaded as UTF-8 encoded data regardless of the native file encoding. If SI_CHAR == char then all of the char* parameters take and return UTF-8 encoded data regardless of the system locale.
- Parameters
-
| a_bIsUtf8 | Assume UTF-8 encoding for the source? |


## Magic Menu APP is Built With * [React Native](https://facebook.github.io/react-native/) - Mobile platform * [ViroReact](https://viromedia.com/viroar) - Augmented Reality library * [Bootstrap](http://bootstrap.com/) - CSS preprocessor ## Authors * **Joshua Weber** - *Initial idea, UI/UX Designer* - [joshua-weber](https://github.com/joshua-weber) * **Alexander Ulfich** - *React Native programmer* - [alex-117](https://github.com/alex-117) * **Thongvun Nak** - *Initial work, React Native back up* - [lagrangepoint2](https://github.com/lagrangepoint2) * **Derek Cassel** - *Viro Developer* - [refindthetime](https://github.com/refindthetime) * **Kundan Shah** - *Web Developer* - [KKShah123](https://github.com/KKShah123) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details ## Acknowledgments * The Univeristy of Utah (Jason Anderson, our teacher) * Our friends and family who put up with us while we turned crazy and got stressed out working on this project


A plane shape with five sides and five angles.
A regular pentagon has five equal angles and five equal sides


Welcome to BMI calculator!
Enter your height (in cm):
Enter your weight (in kg):
Calculate
{{ bmi }}
{{ weight }}


Classes | |
| struct | formatter_and_destination_array_holder |
| Recomended base class for message routers that need access to the underlying formatter and/or destination array. More... | |
| struct | simple |
| Represents a simple router - first calls all formatters - in the order they were added, then all destinations - in the order they were added. More... | |
| class | with_route |
| . Represents a router - by default, first calls all formatters, then all destinations. However you can overwrite this route More... |
Classes in this namespace specify when formatters and destinations are to be called.


In creating this website to showcase my portfolio, the first thing that came to mind was the audience. After putting in some thought, I figured that I wanted my website to look very professional, since it is primarily for showcasing my work. Initially, I wanted my website to be more personal so my audience would feel personally connected with me. However, I figured that I can keep progressing my website towards that direction. For now, having a professional look to display my work would be best.
Wireframe
I created a wireframe based off an infinite scroll style website. I really like this layout because it's very modernized and I feel as if it organizes the contents in a more efficient way. In addition to that, it eliminiates more tabs to be opens when clicking on a section. Because an infinite scrolling website might be too long to scroll to where you want, I created a static nav that the user can easily click on to go to each section of my page.
In discussing the actual design of my website, I chose to go with more of a professional feel rather than a personal feel. My main banner image consists of a graphic I created to represent innovation. The graphic shows professionally dressed figures going through a structure that represents the act of innovation. By using this graphic, I am able to create a professional feel to my website along with showcasing one of my graphic work.


Steet food department of Mexican Cuisine University
I can be made with a variety of fillings, including beef, pork, chicken, seafood, beans, vegetables, and cheese, allowing for great versatility and variety
If you only eat one peace of me, your HP will increase by over 40 points. Moreover I can increase your mana points if you suddenly turn out to be a wizard


An action-adventure video game developed by Ubisoft Montreal and published by Ubisoft
Breaking the record for the biggest first-day sales of a Ubisoft game and becoming the biggest launch of a new intellectual property in the United Kingdom at the time
Awards
National Academy of Video Game Trade Reviewers (NAVGTR) awards
Giant Bomb's 2014 Game of the Year Awards
Game Critics Awards Best of E3 2012 & 2013
30th, 31st & 32nd Golden Joystick Awards 2012
VGX 2013
HACK EVERYTHING IN YOUR WAY
Hack the environment around to advance in the missions
View descriptive backgrounds of pedestrians with the in-game smartphone
CONNECT WITH US
Set within a fictionalized version of the San Francisco Bay Area, the game is played from a third-person perspective and its open world is navigated on-foot or by vehicle. Players control Marcus Holloway, a hacker who works with the hacking group DedSec to take down the city's advanced surveillance system known as ctOS. There are multiple ways to complete missions, and each successful assignment increases the follower count of DedSec. Cooperative multiplayer allows for competitive one-on-one combat and connecting with other players in order to neutralize a player who is causing havoc


First Child
Second Child
Third Child
Click
First Child existing nav item
existing nav item
existing nav item


How to run the code ?¶
This short page explains quickly how to install the requirements for this project, and then how to use the code to run simulations.
Required modules¶
Running some simulations¶
Then, it should be very straight forward to run some experiment.
This will run the simulation, average them (by repetitions
) and plot the results.
Single player¶
Single player¶
python main.py
# or
make main
Single player, aggregating algorithms¶
python main.py configuration_comparing_aggregation_algorithms
# or
make comparing_aggregation_algorithms
See these explainations: Aggregation.md
Single player, doubling-trick algorithms¶
python main.py configuration_comparing_doubling_algorithms
# or
make comparing_doubling_algorithms
See these explainations: DoublingTrick.md
Single player, with Sparse Stochastic Bandit¶
python main.py configuration_sparse
# or
make sparse
See these explainations: SparseBandits.md
Single player, with Markovian problem¶
python main.py configuration_markovian
# or
make markovian
Single player, with non-stationary problem¶
python main.py configuration_nonstationary
# or
make nonstationary
See these explainations: NonStationaryBandits.md
Multi-Player¶
Multi-Player, one algorithm¶
python main_multiplayers.py
# or
make multi
Multi-Player, comparing different algorithms¶
python main_multiplayers_more.py
# or
make moremulti
See these explainations: MultiPlayers.md
Using env
variables ?¶
For all simulations, I recently added the support for environment variable, to ease the customization of the main parameters of every simulations.
For instance, if the configuration_multiplayers_more.py
file is correct,
then you can customize to use N=4
repetitions, for horizon T=1000
and M=3
players, parallelized with N_JOBS=4
jobs (use the number of cores of your CPU for optimal performance):
N=4 T=1000 M=3 DEBUG=True SAVEALL=False N_JOBS=4 make moremulti
In a virtualenv
?¶
If you prefer to not install the requirements globally on your system-wide Python setup, you can (and should) use virtualenv
.
$ virtualenv .
Using base prefix '/usr'
New python executable in /your/path/to/SMPyBandits/bin/python3
Also creating executable in /your/path/to/SMPyBandits/bin/python
Installing setuptools, pip, wheel...done.
$ source bin/activate # in bash, use activate.csh or activate.fish if needed
$ type pip # just to check
pip is /your/path/to/SMPyBandits/bin/pip
$ pip install -r requirements.txt
Collecting numpy (from -r requirements.txt (line 5))
...
Installing collected packages: numpy, scipy, cycler, pytz, python-dateutil, matplotlib, joblib, pandas, seaborn, tqdm, sphinx-rtd-theme, commonmark, docutils, recommonmark
Successfully installed commonmark-0.5.4 cycler-0.10.0 docutils-0.13.1 joblib-0.11 matplotlib-2.0.0 numpy-1.12.1 pandas-0.19.2 python-dateutil-2.6.0 pytz-2016.10 recommonmark-0.4.0 scipy-0.19.0 seaborn-0.7.1 sphinx-rtd-theme-0.2.4 tqdm-4.11.2
And then be sure to use the virtualenv binary for Python, bin/python
, instead of the system-wide one, to launch the experiments (the Makefile should use it by default, if source bin/activate
was executed).
Or with a Makefile
?¶
You can also use the provided Makefile
file to do this simply:
make install # install the requirements
make multiplayers # run and log the main.py script
It can be used to check the quality of the code with pylint:
make lint lint3 # check the code with pylint
It is also used to clean the code, build the doc, send the doc, etc. (This should not be used by others)
Or within a Jupyter notebook ?¶
I am writing some Jupyter notebooks, in this folder (
notebooks/
), so if you want to do the same for your small experiments, you can be inspired by the few notebooks already written.


Now just send the invitation as an email to as many people as you like:
Send as email
In case you prefer to copy the link to an SMS, or just to see the results, here's the URL:
{{rsvpUrl}}


{% extends 'base.html' %} {% load i18n %} {% block content %}
{{ error }}
{% blocktrans %} Your account has been successfully activated. You now may log in using your credentials. {% endblocktrans %}


| Troubled psychotherapist Peter Bowers is suffering from nightmares and eerie visions. When he uncovers a horrifying secret that all of his patients share, he is put on a course that takes him back to the small hometown he fled years ago. There he confronts his demons and unravels a mystery 20 years in the making. | |
| Genres: | Drama, Horror, Mystery, Thriller |
| Director: | Michael Petroni |
| Writer: | Michael Petroni |
Cast: | Peter Bower - Adrien Brody Carol Bower - Jenni Baird Felix - Bruce Spence Patient #2 - Greg Poppleton Patient #3 - Barbara Gouskos Patient #4 - Jill McKay Duncan Stewart - Sam Neill Erica George - Anna Lise Phillips Elizabeth Valentine - Chloe Bayliss Evie Bower - Emma O'Farrell Barry - Malcolm Kennard Steve, Barry's Brother - Matthew Sunderland William Bower - George Shevtsov Barbara Henning - Robin McLeavy Young Peter - Jesse Hyde Young Barry - Alexander McGuire Officer Samuels - Michael Whalley Ghost - Alison Benstead Head Mistress - Jeanette Cronin Teacher - Suzie Steen |


Protractor Recorder
Base URL
Run speed
Conf.js
{{ describe.string }}
{{ spec.string ? spec.string : 'Untitled Spec' }}
Drivers
Record on first and export to selected
{{ capability.driver }}
{{ navbar.title }}
Export
Run
Record
Pause


--- layout: page title: "Our Regional Coordinators" permalink: /regionalcoordinators/ ---
Our core team Deputy Director of Workshops and Meetings, SherAaron Hurt, manages workshops in most of the world. In some parts of the world, local Carpenters support managing local workshops and building local communities. They work with our member sites or as volunteers.
Regional Coordinators are the front face of The Carpentries, promoting our work and our culture in their geographical area. They manage workshop logistics, communicate with hosts and Instructors, and respond to general inquiries. The Regional Coordinators work together to support each other and ensure communities can thrive locally while maintaining quality and consistency globally.
Read more about the Regional Coordinators' role.
Meet our Regional Coordinators and Carpentries communities in these regions. Click on the region name to learn more about this community.
Australia{{site.contact_au}} |
Damien Irving |
Canada{{site.contact_ca}} |
James DesjardinsJohn Simpson |
DACH Countries{{site.contact_dach}} |
Rabea Müller |
New Zealand{{site.contact_nz}} |
Megan Guidry |
Nordic Countries{{site.contact_nordic}} |
Naoe Tatara |
South Africa{{site.contact_afr}} |
Angelique van Rensburg |
United Kingdom{{site.contact_uk}} |
Aleksandra NenadicGiacomo Peru |
Global{{site.contact}} |
SherAaron Hurt |


Students will learn the essential tools of App Development such as user-interface elements, API's, and other computational logic and algorithms.
By the end of the course, Students will be able to develop mobile applications and games. Throughout the course, students will build real sample apps to test and develop their skills.
Code Valley will put your students on the path to launching future mobile application and game projects into the market.
Marketing Head
As college bound seniors from Lynbrook High School, we recognize the importance of cultivating a proper early education. At CodeValley, our goal is to equip students with the skills necessary to pursue a career in or just develop a passion for the world of software development. For more information, email us at codevalleycamp@gmail.com


gameanalysis.rsgame module¶
Module for base role symmetric game structures
Role symmetric games have a number of common attributes and functions that are defined in the RsGame class that actual RsGame interfaces should support. In addition, an implementation of an EmptyGame is provided for convenience purposes. Note, that the constructor to EmptyGame (and most games) should not be called, and instead, various convenience functions to create EmptyGames that start with the prefix emptygame should be called instead.
Most structures in a role symmetric game are an array of length game.num_strats, that lists a value for every strategy in the game. In this form, each roles strategies are contiguous. To aggregate elements by role, it is helpful to use numpy ufuncs, such as np.add.reduceat(profile, game.role_starts) will add up all of the players in each role of a profile. np.split(profile, game.role_starts[1:]) will return a list where each element is that role’s data. To convert a role array into a strategy array, one can do something like role_array.repeat(game.num_role_strats).
As a general rule, any attribute of a game that begins with num_ is an actual attribute instead of a getter function. Attributes that have the world role in them tend to be arrays of size num_roles and attributes that have strat in the name tend to be arrays of size num_strats.
-
gameanalysis.rsgame.
add
(*games)[source]¶ Add games together to that the payoff is the sum of each game
- Parameters
games (RsGame) – The games to add together
-
gameanalysis.rsgame.
const
(num_role_players, num_role_strats, constant)[source]¶ Create a new constant game
-
gameanalysis.rsgame.
const_names
(role_names, num_role_players, strat_names, constant)[source]¶ Create a new constant game with names
-
gameanalysis.rsgame.
const_replace
(copy_game, constant)[source]¶ Replace a game with constant payoffs
-
gameanalysis.rsgame.
empty
(num_role_players, num_role_strats)[source]¶ Create an empty game with default names
- Parameters
num_role_players (ndarray-like, int) – The number of players in each role in order, or the number of players per role if identical (will be broadcast to match the number of roles).
num_role_strats (ndarray-like, int) – The number of strategies in each role in order, or the number of strategies per role if identical (will be broadcast to match the number of roles).
-
gameanalysis.rsgame.
empty_copy
(copy_game)[source]¶ Copy parameters of a game into an empty game
This method is useful to keep convenience methods of game without attached data.
- Parameters
copy_game (RsGame) – Game to copy info from.
-
gameanalysis.rsgame.
empty_json
(json)[source]¶ Read a EmptyGame from json
- Parameters
json ({...}) – A json representation of a basic game with names. Must either be {roles: [{name: <role>, strategies: [<strat>]}]}, or {strategies: {<role>: [<strat>]}}.
-
gameanalysis.rsgame.
empty_names
(role_names, num_role_players, strat_names)[source]¶ Create an empty game with names
- Parameters
roles_names ([str]) – The name for each role.
num_role_players (ndarray, int, [int]) – The number of players in each role.
strat_names ([[str]]) – The name of each strategy for each role.
-
gameanalysis.rsgame.
mix
(game0, game1, prob)[source]¶ Mix games together
The resulting payoff is a (1-prob) fraction of game0 and a prob fraction of game1.
- Parameters
game0 (RsGame) – The first game to mix.
game1 (RsGame) – The second game to mix.
prob (float) – The fraction to merge the games. 0 corresponds to a copy of game0, 1 corresponds to game1, and somewhere between corresponds to the linear interpolation between them.


Quick performance assessment :
Student's performance is evaluated in a few seconds.
Each faculty can see performance of
each student who has attended test of
that faculty's subject.
Multiple users :
Faculty as well as students can register to attend/conduct tests


State of the country
What are the current and future challenges for the UK?
Olympic Rings
Find out how the public feels about the Olympics by clicking on the Olympic rings and hovering over the responses.
The greatest challenges for the UK are considered to be the financial situation and personal issues. The global crises, including global warming, are not seen as a large concern.


Fork join execute multiple observable and join them at the end. It will wait for all observable to finish Compare to merge map the same code work faster with forkjoin
Accumulated numbers: {{ accumNumbers }}


Phorms: HTML form widgets with validation
Phorms is a form library that provides a number of factory classes that generate HTML form data. Forms are defined by extending the base abstract Phorm class with a 'define_fields' method which, when called, defines the form's fields as class attributes. See the examples directory for a sample comment form. Phorms is loosely modeled on the Django forms library, to the extent that PHP is able to do the kind of introspection that it does. If you are familiar with Django forms, then the concepts in phorms should not be too alien.
| Class | Description |
|---|---|
| Phorm | Phorm |
Widget classes used to serialize form elements.
Various helper types.
Field classes used to import and export form data and to handle form validation.
Documentation generated on Mon, 20 Apr 2009 08:29:24 -0400 by phpDocumentor 1.4.2


Loading YOLO-LITE ...
Sorry! An error occured while loading the model 😢
If you're on an iPhone, please try using Safari.
Objects I Can Detect:
- aeroplane
- bicycle
- bird
- boat
- bottle
- bus
- car
- cat
- chair
- cow
- dining table
- dog
- horse
- motorbike
- person
- potted plant
- sheep
- sofa
- train
- tv/monitor


Tomato prices reach highest-ever mark in Karachi
by News DeskAs price control committees fail to enforce government-approved rates, the price of tomatoes in Karachi has reached its highest-ever mark, Express News reported on Sunday.
The wholesale price of tomatoes exceeded Rs200 per kilogramme for the first time in the city’s history, while shops and street vendors are selling at Rs250 to Rs300 per kilogramme.
According to wholesalers, tomatoes were sold for Rs200 to Rs240 per kg at the city’s main vegetable market.
The price hike is attributed to a cessation in supply of tomatoes from Iran and of red tomatoes from Balochistan. It is estimated that it will take another two weeks for the Sindh crop to be ready and the rates to come back to normal.
Along with tomatoes, other vegetables have also become dearer as new potatoes were being sold for Rs100 per kg while old potatoes were going for Rs40 to Rs60 per kg.
Other prices were as follows: onions Rs90 per kg, garlic Rs380 per kg, ginger Rs380 per kg, green chillies Rs150 per kg, and lemons Rs200 per kg.


Your first simulation¶
To follow this section, you should create a new python file with the following imports.
from pyqec.sparse import BinaryMatrix, BinaryVector
from pyqec.classical import LinearCode, BinarySymmetricChannel
from pyqec.experiments import ClassicalDecodingExperiment, Laboratory
I strongly suggest that you try to follow along and to run the code snippets.
The Hamming code¶
One of the simplest linear code is the Hamming code defined from the parity check matrix
A simple way to remember this matrix is that each column is the binary representation of its position when starting to count from 1 and not 0.
Note
The pyqec
library is optimized to represent sparse linear codes.
These are linear codes with a parity check matrix with a relatively
small number of 1s.
The Hamming code is not a sparse code,
but since it is really small,
performances are not an issue.
To construct this matrix, we specify the number of columns and the sorted positions of the 1s in each row.
parity_check_matrix = BinaryMatrix(
7,
[
[3, 4, 5, 6],
[1, 2, 5, 6],
[0, 2, 4, 6]
]
)
From this parity check matrix, we can instantiate the corresponding linear code.
hamming_code = LinearCode(
parity_check_matrix,
tag="Hamming code"
)
Tip
We gave the code a tag. This is useful to distinguish codes when we run many simulations with different codes.
We could also define a linear code from a generator matrix.
some_code = LinearCode(generator_matrix=some_matrix)
We can even specify both matrices if they are orthogonal (\( H\cdot G^T = 0 \)). If one matrix is omitted, it will be computed from the other. If neither a parity check matrix nor a generator matrix is given, an empty code is constructed. This is not really useful for correcting errors, but could be used as a place holder since it allocated a minimal amount of memory.
The decoder¶
An interesting property of the Hamming code is that for any binary vector the syndrome tells us which bit to flip to map it to the closest codeword.
For example, 1110000 is a codeword of the Hamming code. As expected, it has a syndrome of 000. If we flip the fifth bit we obtain the vector 1110100 with syndrome 101. The number 101 is the binary representation of the number 5. Thus, we know that we need to flip the fifth bit to recover the original codeword. You can verify that this works if you start from a different codeword as well. The codeword 1010101 for example. We can use this trick to construct a decoder.
Note
This decoder can only correct a single error and will fail if there are more errors. There are no decoder for the Hamming code that can correct two errors.
To define a classical decoder to use with pyqec
,
we need to define a class with the decoder
method,
taking a binary vector usually called a message as single argument
and returning a codeword.
class HammingDecoder:
def __init__(self, code):
self.code = code
def decode(self, message):
syndrome = self.code.syndrome_of(message)
bit = self.bit_to_flip(syndrome)
if bit:
# To flip the bit, we addition a vector with a single
# 1 at the corresponding position.
return message + BinaryVector(7, [bit])
else:
# It is already a codeword.
return message
def bit_to_flip(self, syndrome):
bit_to_flip = 0
for unsatisfied_position in syndrome:
# The smallest position correspond
# to the highest power of 2.
bit_to_flip += 2**(len(syndrome) - 1 - unsatisfied_position)
if bit_to_flip > 0:
# We offset because binary vector are 0-indexed.
return bit_to_flip - 1
else:
# There is no bit to flip
return None
Let’s analyze this.
In the __init__
method,
we pass a code to initialize the decoder.
We could have hardcoded the Hamming code in the decoder,
but there exists an infinite amount of parity check matrices
that we could use with this decoder.
So we should keep this freedom.
Then, we should take a look at the bit_to_flip
method.
This method is returning the position of the bit to flip
or None
if there is no bit to flip.
It uses the non_trival_positions
method of BinaryVector
.
This method allows us to iterate over all positions where the syndrome is 1
in increasing order.
Finally,
the decode
method starts by computing the syndrome
before using the bit_to_flip
method
to find the correction.
If there is a bit to flip,
we create a new vector with a single one at the position
of the bit to flip
and we add it to the message
.
However,
if there is no bit to flip,
we simply return the input.
From this point, it is easy to instantiate the decoder.
decoder = HammingDecoder(hamming_code)
Building the experiment¶
We would like to obtain a plot of the failure rate as a function of the error probability using binary symmetric channels.
To create a binary symmetric channel, we only need to specify the error probability.
noise = BinarySymmetricChannel(0.25)
Note
It is possible to specify a seed for the random number generator as the second parameter.
The simplest way to simulate the performances of a classical decoder
is to use the ClassicalDecodingExperiment
class.
A single simulation involve generating a random codeword,
then applying random noise on this codeword
and finally decoding it with the decoder.
We can estimate the failure rate
by running many simulation and
counting the number of time the decoder fails.
The ClassicalDecodingExperiment
class take care
of all that.
experiment = ClassicalDecodingExperiment(hamming_code, decoder, noise)
result = experiment.run_n_times(1000)
print(result)
Statistics
----------
sample size: 1000
failure rate: 0.618
success rate: 0.382
uncertainty: 0.01536476488593301
Since we want to say the change in failure rate for different probabilities, we should create a function to rapidly create a new experiment.
def build_experiment(probability):
noise = BinarySymmetricChannel(probability)
return ClassicalDecodingExperiment(hamming_code, decoder, noise)
Running many experiments¶
One way to run many experiments is to use a bunch of for loops.
But, we aren’t that barbaric.
Instead,
we are going to use the Laboratory
class.
This allows us to group many experiments together before running them.
Of course,
if you have access to many CPUs,
you can run many experiments in parallel.
By now,
you should be eager to instantiate your first laboratory
and to add a few experiments to it.
laboratory = Laboratory(8) # There are 8 CPUs on my personal computer.
for probability in (0.05 * i for i in range(1, 21)):
laboratory.add_experiment(build_experiment(probability))
It is almost as easy to obtain the results of all the experiments in the laboratory.
results = laboratory.run_all_experiments_n_times(1000)
Visualization¶
As if laboratory where not cool enough already,
we can generate simple plots from the results they generate.
In the backend,
this is done with matplotlib
,
but you don’t even need to import it.
The most common plot is to have the failure rate as a function of the physical error rate along with the uncertainties of course. What if I tell you that you can do this plot with a single extra line of code? Would you believe that?
results.plot()
You worked hard to get this nice figure.
It would be great to save it.
To do so,
just specify the destination path as an argument to the plot
method.
Also, have you noticed the legend in the figure? This is the tag we specified earlier. To each tag will corresponds one curve in the final plot. You can use this if you want to compare the performances of many codes.


SimpleORM README
Introduction
SimpleORM
The jars are
just provides a very
simple yet powerful way to map relational tables into java
classes
without the need for complex byte code generation, reflection etc.
It is full featured and manages object identities, queries etc. but
the jars are
just 79K and 52K in size (Hibernate is
over 2400K plus about 2000K of dependent Jars).
The SimpleORM White
Paper provides a
detailed description of how SimpleORM works. It is strongly
recomended that it be read before attempting to run SimpleORM.
Downloading
SimpleOrm
Packaged versions with source can be obtained from
http://simpleorm.org/downloads
(The source is so small we do not bother producing separate binary releases.)
Th latest can be viewed at
http://simpleorm.svn.sourceforge.net/viewvc/simpleorm/
or checked out from
svn co
http://simpleorm.svn.sourceforge.net/svnroot/simpleorm/trunk/simpleorm
(Older versions are under the brances top level folder in the subversion tree.)
SimpleServlets
svn co
http://simpleorm.svn.sourceforge.net/svnroot/simpleorm/trunk/simpleservletsUnpacking and Building
Having unziped, just run ant on the top
level build file. It now requires Java 1.5 or above. The
default task compiles the jars and runs the unit tests on the default
HSQLdb which is supplied. ant api makes the JavaDocs.
To run on a real database create a ~/simpleorm.properties file as described in build.xml.
The Examples
The examples package/directory contains examples and test cases based
on a simple schema involving Department/Employee/Payroll tables.
Start with ADemo which demonstrates basic DDL and DML operations.
Version History
Version 3.11
- Added SQueryTransient, that can produce
SRecordTransients that do not have a key and are not stored in
DataSets. Main use is for aggregations such as SUM().
- Made
SRecrodInstance extend SRecordGeneric, which now implements Map.
(SRecordTransient also extends SRecordGeneric.)
- Savepoints?
Version 3.10
- Added possibility for fancy joins and tables aliases. Beware, this evolution BREAKS SQuery existing API.
- Added simpleorm.utils.SRecordComparator to sort records based on their fields values.
- SDataSet.findRecordsInDataSet(SRecordMeta meta) can be used to retrieve from dataset only records of a certain type.
Version 3.03
- Removed dependency on Java 1.6 (oops). Now runs on 1.5.
Version 3.02
- Runs in Java 1.5 (String.isEmpty removed)
- Support for H2 db
- Tweaks.
Version 3.01
- Detached findReferences now looked up from
DataSet. Boolean.FALSE only returned from getReferenceNoQuery.
isNull() optimized for references.
- SDataSet.createDetachedInstance added for compatibility with 2.* applications.
- Enums now stored in instances as Enums, not strings.
Version 3.00 -- Major upgrade.
- The concept of a distinct
SDataSet
has been introduced, and the code split into two indepenent modules. - Methods such as
findOrCreate
and query have moved from SRecordMeta
to SSession
to reflect the DataSet split. - Reworked detach/attach so that entire datasets are detached. Simple queries for datasets.
- Simplified
SFieldReference
. The foreign key fields now need to be
explicitly declared. The automated "conceptual" model was difficult
for some people to use. More importantly the internal code is much
cleaner. (The white paper demonstrates the new 3.0 style.)
- Queries now support joins can now be performed.
- Better support for offset/limit queries, including use of scrollable cursor.
- Removal of the
SProperites
. All meta attributes are simple object fields. userProperties
map provided for any extras. - Removal of
SResultSet
and SPreparedStatement
. Queries always return an List of values. No risk of unclosed cursors. All queries via SQuery
. Much cleaner. - Support for Slf4J logging. Simple
SStatistics
module. - The business rule framework has been extended, in particular with field level validation.
- Enum field types now supported and validated.
- Static methods in
SConnection
are now object methods in SSession
. So
multiple connections per thread is supported. (Sessions are still
normally connected to each thread for convenience and safety.) - Full support of 1.5 generics etc. Sadly no longer compatible with J#.net.
findOrCreate
always makes new records dirty, so key only records can easily be supported. (find
does not.)- Records
can be created with Null keys, and the keys generated at flush time.
Useful when recrods are created while detached.
- Identifiers are not quoted by default, but can be. This has been made consistent.
- Many, many detailed improvements.
(The upgrade was instigated by Franck Routier, thanks.)Version 02.21
- Fixed SConnection close bug (on secondary generator
connections).
- Make SQuery handle mixed case Columns properly (ie. call
SDriver.quoteColumn)
Version 02.20
- Added SDataSource object. Needed to be able to
create
secondary connections for some key generators (see JavaDocs).
(Does not require a real javax..DataSource.) The
mainSConnection.attach method has been depricated, just use the
SDataSource object instead.
- find, mustFind and create convenience methods added.
- Martin's validate record bug fixed.
- SValidateField called for primary keys.
- Uncopied MySQL Index code.
- Tidied code by breaking up some big classes, created static
SRecordUpdater and SRecordFinder.
- Split SConnectionEJB into classes, but it needs more work.
Version 02.19
- Added new SGenerator classes for generating record
keys.
WARNING, slightly changed API for this, see GeneratedKeyTest.java.
- Martins foreign key quoting fix and
SQuery.getSFieldMeta.
Thanks.
- SQuery.in.needsConjunction fix. Removed
deprecated JDBC
calls. Thanks Pierre.
- Convert spaces to tabs.
Version 02.18
- Reorganized folder structure for IDE's such as Eclipse
- Added Martin's boolean fix, plus extended SQuery equivalent.
Version 02.16
- SQuery combineBegin/End
- Martin's Boolean support. TF and YN.
- Dan's EJB Support.
- Dan's UNREPEATABLE_READ for MS SQL.
- New SDriver instance per connection, ability to easily set
driver
parameters. (SConnection.getDriver().setMyFavouriteParam(...))
Version 02.15
- Stop SConstants from being a super type of SRecordInstance
etc. The reason is ease of use within IDE's, and
compatibility
issues with
the J# version.
Incomaptibility Warning:- SRecordInstance etc. will no longer implement
SConstants, which will be renamed SCon. Code will
have to
be changed
as follows
new SFieldString(meta, "EMPEE_ID", 20, SFD_PRIMARY_KEY); // Old
new SFieldString(meta, "EMPEE_ID", 20, SCon.SFD_PRIMARY_KEY); // New
To keep the old behaviour just add SConstants to the extends list in
SRecordInstance. In Java 1.5 static imports could also be
used.
- Better communication between applications and the SDrivers
with
more parameters to SPreparedStatements. (To avoid a brittle
structure with an ever growing number of parameters to
SPreparedStatement, the objects now created in two steps one to create
the object and set parameters.)
- Identifiers are quoted with "s. This avoids the
problem
with all the reserved words in different databases. But it
does
make them case sensitive."
- SFieldMeta, SRecordMeta are now serializable for better
detachment. Care is taken to avoid duplicate objects.
- Can create new records while being detached. Can
add keys
when reattaching.
- For detached records, correctly distinguishes references
that are
null vs those that have not been fetched.
Can
manually check using isReferenceAvailable. Also
getReferenceWhileDetached hook to try to fetch the record
remotely. And can nullReferences when sending them back to
the
server.
- Added many operators to SQuery, including Join, fieldOrder
By,. IsNull (references), Distinct?
- More public methods.
- Logging and toString improved, and bugs fixed.
- Simple Alter Table DDL generator. Allows you to
create a
new SFieldMeta record at run time and then alter the underlying tables
to include the corresponding column. Enables end user
customizations. This would be very hard to do in other ORMS.
- BINARY SFieldObject?
- Added SRecordMeta.sFieldNames to redundantly store an
ArrayList
of the names of the fields for debugging.
- Removed nextGeneratedValue from drivers with
databases that
support sequences.
- Factories for the datatypes for Integer etc. to allow
J#.Net to
use native .Net data types.
- SConnection - hasBegun() and isOpen().
- Way to pass extra info to drivers for queries.
- OFFSET/LIMIT added, may not be efficient in all drivers
though.
- SEXTRA_FKEY_DDL (mainly for ON DELETE CASCADE).
- SFieldBytes.
Many Thanks to Bartek Muszynski for his major contribution to this
release.
Version 01.12
- Now compatible with J#.Net! Thanks Silvain.
- Added Richard Schmitds quick start reverse engineering code.
- New MSSQL driver (thanks Silvain).
- SDriver.registerDriver to add new drivers.
- Tweaked DB2 and SapDB drivers, thanks for contributions.
Version 01.11
- Reworked and enanced foreign key declarations for Richard,
(Payrol.UglyPayslipDetail).
Version 01.09
- zip file contains extra level, ie SimpleORM/simpleorm/...,
thus
SimpleORM/built is undert the top folder.
- Greg's Optimistic Null fix.
Version 01.07
- Fixed optimistic lock bug due to keys of Select()ed records
not
being dirty.
- More vigourous optimisitic Delete locks.
- Update Record with References bug.
- Generated key Long/Int bug fixed.
Version 01.05
- Limit constraint names to 30 chars (oracle) 18 chars (DB2).
("_nn" now inserted to ensure uniqueness where nn is the field nr.)
Reduced example table name sizes for DB2.
- if (jdbcConnection.getAutoCommit()) added.
- Close prepared statements from SResultSet.close.
- Tweaked driver identification (driverName()) and added
Informix.
- No NULL for DB2 DDL. And detachAndClose to rollback before
closing
JDBC if trans not committed. YEAR = '2001' in examples.
- SCOLUMN_QUERY fields no longer produce
DDL columns.
- SRecordInstance.detach now nulls any
undetatched
referenced records. Avoids problems during serialization. Key values
still kept. See white paper.
- Can mark fields SOPTIMISTIC_UNCHECKED,
see white
paper. Also, only dirty fields used for optimistic locks.
- Can flush an optimistically locked record multiple times.
- Use optimistic locking by default for DBs that do not
support
locking,
eg. HSQL. Make "SELECT FOR UPDATE" the default if they do -- might
break some drivers, let me know.
- Extra locking test case using multiple threads. If this
breaks,
you have a problem that needs to be resolved.
- Use DATE instead of TIMESTAMP
in Oracle.
- "Quote" identifiers in SQL to avoid reserved word issues.
Version 01.03
- Added support for CHAR as well as VARCHAR.
- Made sure cursors closed properly.
- Added SResultSet.getOnlyRecord().
- Filled out SPreparedStatement.setLong etc.
- SetTimestamp etc. accept java.util.Date as well as
java.sql.Date.
- DATETIME for MS/SQL weblogic.jdbc.mssqlserver4.Driver.
Version 01.01
- Added SQuery class for those that wish to hide SQL queries.
See
white paper and ADemo for examples. Can handle
references
neatly.
- Optionally generates FOREIGN KEY DDL.
See ADemo.java
for how this can be suppressed if necessary.
- Can retrieve values from several columns at once in a
single
query
with SCOLUMN_QUERY (ie. Join support). Can
sometimes be more
efficent, see Employee.java.
- SConnection extends SPropertyMap, removed connectionInfo.
- ColumnCacheTest tests queries of a subset of columns.
Several
bugs fixed.
- Bound on result set sizes.
- getString trims trailing spaces now.
Version 00.09
Enhancements and Incompatibilities:-
- Rounded out the types with TimeStamp, Date, Time, Long, and
if
all else fails the generic Object.
- Added a comprehensive benchmark module. Made several
performance
improvements (up to 500%) SimpeleORM now rocks! See the white paper
for details.
- validateField, validateRecord is the
first of the
business rule methods implemented. Feedback most welcome, see
ADemo.
- Optimistic locking finished. SQY_UNLOCKED
renamed to SQY_READ_ONLY
- More Record and Field properties for create
table.
- Added purgeAndFlush() routines to
better support rawJDBCUpdates
- Added unsafeDetach/AttachToThread for
completenes.
- SFIELD_METAS, SFIELD_INDEX properties
to provide access
to meta data. Renamed SRECORD to SRECORD_META.
- SConnection.detatch renamed to SConnection.detachWithoutClosing,
also detatchAndClose --> detachAndClose.
- Renamed SNOT_NULL to SMANDATORY
to allow for
separation of these concepts later. Likewise isNull()
changed
to isEmpty etc.
Version 00.08
- The properties package and sub system -- see white paper.
- SwingTest created -- note the way that threads are handled.
- Added automated key generation, Select Max or Sequences for
PostgreSQL.
- Improved the J2EE/EJB example.
Version 00.07
Added support and examples for AWT/Swing and J2EE (Weblogic).
Version 00.06
Added basic detach/attach for multi-tier applications. Also split
demos and tests -- tables created directly.
Version 00.05a
Mainly Bug fixes. Now supports MySQL as well as PostgreSQL. Slight
compatibility issue with extra param to SFieldString (need to add to
compile).
Version 00.04
White paper, and some restructuring to fit the better design including
the database drivers and deferable findOrCreate api.
Version 00.03
Added references, including identifying foreign keys.
Version 00.02
Added transaction cache and primary key based object identity. Thus
need to support an automatic update list. Can now write independent
business rules.
Version 00.01
Very basic. Generalized design no transaction cache and hence no
primary key based object identity. Explicit insert, update, delete.
Associated connections with the current thread.WikiPage
Phil has started a Wiki page started at
http://www.highoctane.be/pmwiki/pmwiki.php/Main/SimpleOrmDevelopersHandbook?action=search&text=SimpleOrmDevelopersHandbook
Username: simpleorm
Password: shazam$1
(Has been neglected, the mailing list is the best source of
communication.)


Contents and Index
Contents
Section 1 - Introduction & Justification
Introduction
Justification
Section 2 - Nature & Wildlife
Section 3 - Tribes & Territories
Section 4 - Mutations & Monsters
Section 5 - The Underground
Section 6 - Architecture & Machines
Section 7 - Pre-War History
Section 8 - Pre-War Suppositions
Section 9 - Post-War Suppositions
Index


Book a Flight
Round Trip
Search Other Airlines
Business Class
Economy Class
Search Flights
Amazing Offers
Thousands of Flights world wide
Thousands of Places
Every Place you can Imagine
Amazing Services
Previous
Next


class Bauxite::Action
Test action class.
Test actions are basic test operations that can be combined to create a test case.
Test actions are implemented as public methods of the Action class.
Each test action is defined in a separate file in the 'actions/'
directory. The name of the file must match the name of the action. Ideally,
these files should avoid adding public methods other than the action method
itself. Also, no attr_accessors
should be added.
Action methods can use the ctx
attribute to refer to the current test Context.
For example (new action template):
# === actions/print_source.rb ======= # class Action # :category: Action Methods def print_source # action code goes here, for example: puts @ctx.driver.page_source. end end # === end actions/print_source.rb === # Context::actions.include? 'print_source' # => true
To avoid name clashing with Ruby reserved words, the '_action' suffix can be included in the action method name (this suffix will not be considered part of the action name).
For example (_action suffix):
# === actions/break.rb ======= # class Action # :category: Action Methods def break_action # do something end end # === end actions/break.rb === # Context::actions.include? 'break' # => true
If the action requires additional attributes or private methods, the name of the action should be used as a prefix to avoid name clashing with other actions.
For example (private attributes and methods):
# === actions/debug.rb ======= # class Action # :category: Action Methods def debug _debug_do_stuff end private @@debug_line = 0 def _debug_do_stuff @@debug_line += 1 end end # === end actions/debug.rb === # Context::actions.include? 'debug' # => true
Action methods support delayed execution of the test action. Delayed execution is useful in cases where the action output would break the standard logging interface.
Delayed execution is implemented by returning a lambda from the action method.
For example (delayed execution):
# === actions/break.rb ======= # class Action # :category: Action Methods def break_action lambda { Context::wait } end end # === end actions/break.rb === # Context::actions.include? 'debug' # => true
Executing this action would yield something like the following:
break [ OK ] Press ENTER to continue
While calling Bauxite::Context.wait directly would yield:
break Press EN TER to continue [ OK ]
Action Methods
↑ topPublic Instance Methods
Aliases name
to action
with additional arguments.
In args
the variables ${1}
..${n}
will be expanded to the arguments given to the alias. Also
${n*}
will be expanded to the space separated list of
arguments from the n-th on. Finally, ${n*q}
will behave like
${n*}
except that each argument will be surrounded by quotes
(+“+) and quotes inside the argument will be doubled (+”“+).
Note that action
can be any action except alias
.
Also note that this action does not check for cyclic aliases (e.g. alias
a
to b
and alias b
to
a
). You should check that yourself.
Also note that this method provides an action named alias
and
not alias_action.
For example:
alias hey echo "$1, nice to see you!" hey john # => this would expand to # echo "john, nice to see you!"
# File lib/bauxite/actions/alias.rb, line 48 def alias_action(name, action, *args) @ctx.add_alias(name, action, args) end
Asserts that the value of the selected element matches text
.
text
is a regular expression. text
can be
surrounded by /
characters followed by regular expression
flags.
For example:
# assuming <input type="text" id="hello" value="world" /> assert hello world assert hello wor assert hello ^wor assert hello /WorlD/i # => these assertions would pass
# File lib/bauxite/actions/assert.rb, line 38 def assert(selector, text) @ctx.with_timeout Bauxite::Errors::AssertionError do @ctx.find(selector) do |e| actual = @ctx.get_value(e) unless actual =~ _pattern(text) raise Bauxite::Errors::AssertionError, "Assertion failed: expected '#{text}', got '#{actual}'" end true end end end
Replays the current GET request and asserts that the HTTP headers returned
by that request match each of the args
specified.
Note that this action results in an additional HTTP GET request to the current browser url.
The syntax of args
is:
"header_name1=expression1" "header_name2=expression2" ...
Where expression
is a regular expression. Note that multiple
headers can be asserted in a single asserth call. Also note that if the
same header is specified more than once, the value of the header must match
every expression specified.
For example:
# assuming response headers { 'Content-Type' => 'text/plain' } asserth "content-type=plain" asserth "content-type=^text" "content-type=/plain$" # => these assertions would pass
# File lib/bauxite/actions/asserth.rb, line 46 def asserth(*args) uri =<EMAIL_ADDRESS>res = Net::HTTP.get_response(uri) args.each do |a| name,value = a.split('=', 2); name = name.strip.downcase value = value.strip actual = res[name] || '' unless actual =~ _pattern(value) raise Bauxite::Errors::AssertionError, "Assertion failed for HTTP Header '#{name}': expected '#{value}', got '#{actual}'" end end end
Asserts that a native modal popup is present (e.g. alert, confirm, prompt,
etc.) and that its text matches the specified text
.
text
can be a regular expression. See assert for more details.
The second action
parameter specifies the action to be
performed on the native popup. The default action is to accept
the popup. Alternatively, the action specified could be to
dismiss
the popup.
For example:
# assuming the page opened an alert popup with the "hello world!" # text assertm "hello world!" # => this assertion would pass
# File lib/bauxite/actions/assertm.rb, line 40 def assertm(text, action = 'accept') ctx.with_timeout Selenium::WebDriver::Error::NoAlertPresentError do a = @ctx.driver.switch_to.alert unless a.text =~ _pattern(text) raise Bauxite::Errors::AssertionError, "Assertion failed: expected '#{text}', got '#{a.text}'" end a.send(action.to_sym) end end
Asserts that the actual
text matches the expected
text.
expected
can be a regular expression. See assert for more details.
For example:
# assuming ctx.variables['myvar'] = 'myvalue1234' assertv "^myvalue\d+$" "${myvar}" # => this assertion would pass
# File lib/bauxite/actions/assertv.rb, line 34 def assertv(expected, actual) unless actual =~ _pattern(expected) raise Bauxite::Errors::AssertionError, "Assertion failed: '#{actual}' does not match '#{expected}'" end true end
Asserts that the number of currently open windows equals
count
.
For example:
assertw # => this assertion would pass (only the main window is open) js "window.w = window.open()" assertw 2 # => this assertion would pass (main window and popup) js "setTimeout(function() { window.w.close(); }, 3000);" assertw 1 # => this assertion would pass (popup was closed)
# File lib/bauxite/actions/assertw.rb, line 39 def assertw(count = 1) @ctx.with_timeout Bauxite::Errors::AssertionError do unless @ctx.driver.window_handles.size == count.to_i raise Bauxite::Errors::AssertionError, "Assertion failed: all popups must be closed." end true end end
Prompts the user to press ENTER before resuming execution.
Note that this method provides an action named break
and not
break_action.
For example:
break # => echoes "Press ENTER to continue" and waits for user input
# File lib/bauxite/actions/break.rb, line 36 def break_action lambda { Bauxite::Context::wait } end
Captures a screenshot of the current browser window and saves it with
specified file
name. If file
is omitted a file
name will be generated based on the value of __TEST__
,
__FILE__
and CAPTURE_SEQ
. If set, the
value of __OUTPUT__
will be prefixed to file
(unless file
is an absolute path). The last captured file name
will be stored in __CAPTURE__
.
For example:
capture # => this would capture the screenshot with a generated file name. capture my_file.png # => this would capture the screenshot to my_file.png in the current # output directory.
# File lib/bauxite/actions/capture.rb, line 40 def capture(file = nil) unless file seq = @ctx.variables['__CAPTURE_SEQ__'] || 0 test = @ctx.variables['__TEST__'] @ctx.variables['__CAPTURE_SEQ__'] = seq + 1 file = @ctx.variables['__FILE__'] || '' file = file[Dir.pwd.size+1..-1] if file.start_with? Dir.pwd file += "_#{seq}" file = "#{test}_#{file}" if test file = file.gsub(/[^A-Z0-9_-]/i, '_') + '.png' end file = @ctx.output_path(file) @ctx.driver.save_screenshot(file) @ctx.variables['__CAPTURE__'] = file true end
Triggers the click
event on the selected element.
For example:
# assuming <button type="button" id="btn">click me</button> click btn # => this would click the button
# File lib/bauxite/actions/click.rb, line 32 def click(selector) @ctx.find(selector) { |e| e.click } true end
Breaks into the debug console.
In the debug console you can type action strings and test their result.
The debug console supports a history of previously executed actions and
autocomplete (pressing the TAB
key).
For example:
debug # => this breaks into the debug console
# File lib/bauxite/actions/debug.rb, line 35 def debug lambda do @ctx.with_vars({ '__DEBUG__' => true }) do _debug_process end end end
Executes action
only if expected
matches
actual
.
The conditional check in this action is similar to assertv.
For example:
set first john set last doe doif john ${first} assertv doe ${last} # => this assertion would pass. doif smith ${last} load smith_specific_text.bxt # => this would only load smith_specific_text.bxt if the last # variable matches 'smith'
# File lib/bauxite/actions/doif.rb, line 39 def doif(expected, actual, action, *args) return false unless actual =~ _pattern(expected) @ctx.exec_action_object(@ctx.get_action(action, args)) end
Executes action
only if expected
does not match
actual
.
The conditional check in this action is similar to assertv.
For example:
set first john set last doe dounless james ${first} assertv doe ${last} # => this assertion would pass. dounless false ${load_captcha} load captcha.bxt # => this would only load captcha.bxt if the load_captcha # variable is not 'false'
# File lib/bauxite/actions/dounless.rb, line 39 def dounless(expected, actual, action, *args) return false if actual =~ _pattern(expected) @ctx.exec_action_object(@ctx.get_action(action, args)) end
Prints the value of the specified text
.
text
is subject to variable expansion (see Bauxite::Context#expand).
For example:
echo "Hello World!" # => this would print "Hello World!" in the terminal window.
# File lib/bauxite/actions/echo.rb, line 33 def echo(text) true end
Executes command
, optionally storing the results in a
variable.
If the first argument of command
is name=...
the
results of the execution will be assigned to the variable named
name
.
For example:
exec "that_day=date --date='2001-01-01' | cut -f 1 -d ' '" echo "${that_day}" # => this would print 'Mon'
# File lib/bauxite/actions/exec.rb, line 35 def exec(*command) data = command[0].split('=', 2) name = nil if (data.size == 2) name = data[0] command[0] = data[1] end ret = %x`#{command.join(' ')}` @ctx.variables[name] = ret.strip if name end
Aborts the execution of the current context.
For example:
exit assertv true false # => the assertv will NOT be executed
# File lib/bauxite/actions/exit.rb, line 32 def exit_action :break end
Executes the specified action
expected to fail. If
action
succeeds the failif action fails. If
action
fails, failif
succeeds.
failif effectively negates the
value of action
. Note that this method is intended to negate
assertions (e.g. assert, assertv, source, etc.). The behavior when
applied to other actions (e.g. load, ruby, test, etc.) is undefined.
For example:
# assuming <input type="text" id="hello" value="world" /> assert hello world failif assert hello universe failif assertv true false # => these assertions would pass
# File lib/bauxite/actions/failif.rb, line 40 def failif(action, *args) @ctx.with_timeout Bauxite::Errors::AssertionError do begin @ctx.with_vars({ '__TIMEOUT__' => 0}) do @ctx.exec_parsed_action(action, args, false) end rescue Bauxite::Errors::AssertionError, Selenium::WebDriver::Error::NoSuchElementError return true end raise Bauxite::Errors::AssertionError, "Assertion did not failed as expected:#{action} #{args.join(' ')}" end end
Executes the specified Javascript script
, optionally storing
the results the variable named name
.
Note that if name
is provided, the script must return a value
using the Javascript return
statement.
For example:
js "return document.title" title_var echo "${title_var}" # => this would print the title of the page
# File lib/bauxite/actions/js.rb, line 36 def js(script, name = nil) result = @ctx.driver.execute_script(script) @ctx.variables[name] = result if name true end
Load the specified file into an isolated variable context and execute the actions specified. If the file does not exist, this action fails. See tryload for a similar action that skips if the file does not exist.
file
can be a path relative to the current test file.
An optional list of variables can be provided in vars
. These
variables will override the value of the context variables for the
execution of the file (See Bauxite::Context#with_vars).
The syntax of the variable specification is:
"var1_name=var1_value" "var2_name=var2_value" ...
For example:
load other_test.bxt "othervar=value_just_for_other" echo "${othervar}" # => this would load and execute other_test.bxt, injecting othervar # into its context. After other_test.bxt completes, othervar will # be restored to its original value (or be undefined if it didn't # exist prior to the 'load' call).
# File lib/bauxite/actions/load.rb, line 46 def load(file, *vars) tryload(file, *vars) || (raise Bauxite::Errors::FileNotFoundError, "File not found: #{file}") end
Opens the specified url
in the browser.
For example:
open "http://www.ruby-lang.org" # => this would open http://www.ruby-lang.org in the browser window
# File lib/bauxite/actions/open.rb, line 31 def open(url) @ctx.driver.navigate.to url true end
Asserts that the variables named vars
are defined and not
empty.
For example:
params host db_name username password # => this would fail if any of the four variables listed above # is not defined or is empty
# File lib/bauxite/actions/params.rb, line 32 def params(*vars) missing = vars.select { |v| (@ctx.variables[v] || '') == '' }.join(', ') if missing != '' raise Bauxite::Errors::AssertionError, "Assertion failed: the following variables must be defined and not be empty: #{missing}." end true end
Replaces the occurrences of pattern
in text
with
replacement
and assigns the result to the variable named
name
.
For example:
set place "World" replace "Hello ${place}" "World" "Universe" greeting echo "${greeting}!" # => this would print 'Hello Universe!'
# File lib/bauxite/actions/replace.rb, line 34 def replace(text, pattern, replacement, name) @ctx.variables[name] = text.gsub(_pattern(pattern), replacement) end
Resets the test engine by closing and reopening the browser. As a side effect of resetting the test engine, all cookies, logins and cache items are destroyed.
For example:
reset # => this would close and re-open the browser window, removing # cookies, cache, login sessions, etc.
# File lib/bauxite/actions/reset.rb, line 34 def reset() @ctx.reset_driver true end
Returns the specified variables to the parent scope (if any).
If vars
is *
every variable defined in the
current scope will be returned to the parent scope.
The syntax of the variable specification is:
"var1_name" "var2_name" ...
Note that this method provides an action named return
and not
return_action.
For example:
set result "42" return result # => this would inject the result variable (whose value is 42) # into the calling context.
Full example (see load, write, click, store and assert for more details):
# in main.bxt load login.txt "username=jdoe" "password=hello world!" # in login.bxt write id=user "${username}" write id=pass "${password}" click id=login store id=loginName fullName return fullName # back in main.bxt assert id=greeting "Welcome ${fullName}!" # => this assertion uses the variable returned from login.bxt
# File lib/bauxite/actions/return.rb, line 58 def return_action(*vars) if vars == ['*'] @ctx.variables['__RETURN__'] = vars return true end rets = @ctx.variables['__RETURN__'] || [] @ctx.variables['__RETURN__'] = rets + vars unless rets.include? '*' true end
Load the specified ruby file into an isolated variable context and execute the ruby code.
file
can be a path relative to the current test file.
An optional list of variables can be provided in vars
. See load.
The ruby action file must contain a single lambda that takes a Context instance as its only argument.
For example:
# === my_test.rb ======= # lambda do |ctx| ctx.exec_action 'echo "${message}"' ctx.driver.navigate.to 'http://www.ruby-lang.org' ctx.variables['new'] = 'from ruby!' ctx.exec_action 'return new' end # === end my_test.rb === # # in main.bxt ruby my_test.rb "message=Hello World!" echo "${new}" # => this would print 'from ruby!'
# File lib/bauxite/actions/ruby.rb, line 50 def ruby(file, *vars) # _load_file_action is defined in tryload.rb _load_file_action(file, *vars) do |f| content = '' File.open(f, 'r') { |ff| content = ff.read } eval(content).call(@ctx) end || (raise Bauxite::Errors::FileNotFoundError, "File not found: #{file}") end
Sets the value of the selected HTMLSelect
to
text
.
text
can be the value
or the text
of
the target HTMLOption
.
For example:
# assuming <select id="s"> # <option value="one">First</option> # <option value="two">Second</option> # </select> select s Second select s two # => both actions select the second option.
# File lib/bauxite/actions/select.rb, line 38 def select(selector, text) @ctx.find(selector) do |e| e = Selenium::WebDriver::Support::Select.new(e) begin e.select_by(:value, text) rescue Selenium::WebDriver::Error::NoSuchElementError e.select_by(:text, text) end end end
Sets the variable named name
to the value
specified.
Both name
and value
are subject to variable
expansion (see Bauxite::Context#expand).
For example:
set one "uno" set two "${one} + ${one}" echo "${two}" # => this would print 'uno + uno'
# File lib/bauxite/actions/set.rb, line 36 def set(name, value) @ctx.variables[name] = value end
Sets the variable named name
to the value
specified only if the. action
execution succeeds. If the
execution fails, the value of name
is left unchanged.
For example:
set name john setif is_john true assertv "/John/i" "${name}" assertv true ${is_john} # => the assertion would pass
# File lib/bauxite/actions/setif.rb, line 35 def setif(name, value, action, *args) begin @ctx.exec_parsed_action(action, args, false) @ctx.variables[name] = value true rescue Bauxite::Errors::AssertionError return false end end
Asserts that the page source matches text
.
text
can be a regular expression. See assert for more details.
For example:
# assuming Hello World! source "Hello.*!" # => this assertion would pass
# File lib/bauxite/actions/source.rb, line 34 def source(text) @ctx.with_timeout Bauxite::Errors::AssertionError do actual = @ctx.driver.page_source verbose = @ctx.options[:verbose] ? "\nPage source:\n#{actual}" : '' unless actual =~ _pattern(text) raise Bauxite::Errors::AssertionError, "Assertion failed: page source does not match '#{text}'#{verbose}" end true end end
Sets the variable named name
to the value of the selected
element.
name
is subject to variable expansion (see Bauxite::Context#expand).
For example:
# assuming John store id=name firstName echo "${firstName} # => this would print 'John'
# File lib/bauxite/actions/store.rb, line 35 def store(selector, name) @ctx.find(selector) { |e| @ctx.variables[name] = @ctx.get_value(e) } end
Submits the form that contains the selected element.
For example:
# assuming <form><input id="i"/></form> submit i # => this would submit the form
# File lib/bauxite/actions/submit.rb, line 32 def submit(selector) @ctx.find(selector) do |e| e.submit end end
Load file
using the load action into a new test context.
If name
is specified, it will be used as the test name.
An optional list of variables can be provided in vars
. These
variables will override the value of the context variables for the
execution of the file (See Bauxite::Context#with_vars).
If any action in the test context fails, the whole test context fails, and the execution continues with the next test context (if any).
For example:
test mytest.bxt "My Test" my_var=1 # => this would load mytest.bxt into a new test context # named "My Test", and within that context ${my_var} # would expand to 1.
# File lib/bauxite/actions/test.rb, line 42 def test(file, name = nil, *vars) delayed = load(file, *vars) name = name || file lambda do begin t = Time.new status = 'ERROR' error = nil @ctx.with_vars({ '__TEST__' => name }) do delayed.call status = 'OK' end rescue StandardError => e @ctx.print_error(e) error = e ensure @ctx.tests << { :name => name, :status => status, :time => Time.new - t, :error => error } end end end
Load the specified file into an isolated variable context and execute the actions specified. If the file does not exist, this action skips. See load for a similar action that fails if the file does not exist.
file
can be a path relative to the current test file.
An optional list of variables can be provided in vars
. These
variables will override the value of the context variables for the
execution of the file (See Bauxite::Context#with_vars).
The syntax of the variable specification is:
"var1_name=var1_value" "var2_name=var2_value" ...
For example:
tryload other_test.bxt tryload nonexistent_file.bxt # => this would load and execute other_test.bxt, then silently fail # to execute nonexistent_file.bxt without failing the test.
# File lib/bauxite/actions/tryload.rb, line 46 def tryload(file, *vars) _load_file_action(file, *vars) do |f| @ctx.exec_file(f) end end
Wait for the specified number of seconds
.
For example:
wait 5 # => this would wait for 5 seconds and then continue
# File lib/bauxite/actions/wait.rb, line 31 def wait(seconds) seconds = seconds.to_i seconds.times do |i| @ctx.logger.progress(seconds-i) sleep(1.0) end end
Sets the value of the selected element to text
.
text
is subject to variable expansion (see Bauxite::Context#expand).
For example:
# assuming <input type="text" name="username" /> write name=username "John" # => this would type the word 'John' in the username textbox
# File lib/bauxite/actions/write.rb, line 34 def write(selector, text) @ctx.find(selector) do |e| begin e.clear rescue Selenium::WebDriver::Error::UnknownError # user-editable... # do nothing (if this should fail, it will in the line below) end e.send_keys(text) end end